@johpaz/hive-agents 0.0.35 → 0.0.37

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 (441) hide show
  1. package/README.md +64 -39
  2. package/dist/hive.js +3231 -3189
  3. package/dist/tool-worker.js +218406 -0
  4. package/dist/ui/assets/{AgentCreateForm-B4eK7efF.js → AgentCreateForm-tJZv9FZC.js} +1 -1
  5. package/dist/ui/assets/{AgentDetailPage-BD2uoJWk.js → AgentDetailPage-Du-mRcAX.js} +1 -1
  6. package/dist/ui/assets/AgentNewPage-DIFYd_Ys.js +1 -0
  7. package/dist/ui/assets/{AgentsPage-4JUZXvkA.js → AgentsPage-YvSgWRiw.js} +6 -6
  8. package/dist/ui/assets/CanvasPage-DtMwGvxf.js +33 -0
  9. package/dist/ui/assets/{ChannelsPage-BUn7-nhV.js → ChannelsPage-BdBXWHjj.js} +1 -1
  10. package/dist/ui/assets/DashboardPage-ghl1ZguH.js +6 -0
  11. package/dist/ui/assets/{LoginPage-C8j_urUD.js → LoginPage-CAmSI9Vy.js} +1 -1
  12. package/dist/ui/assets/LogsPage-DAPBHkwK.js +1 -0
  13. package/dist/ui/assets/MeetingPage-WjjGOqqU.js +1 -0
  14. package/dist/ui/assets/{NotFound-Drh-sJPN.js → NotFound-BMeQSGcG.js} +1 -1
  15. package/dist/ui/assets/ProvidersPage-Ct6HsAi1.js +1 -0
  16. package/dist/ui/assets/{RecoverPage-DNb1Pr8h.js → RecoverPage-DpW3l-yv.js} +1 -1
  17. package/dist/ui/assets/SettingsPage-DBJ7_E6C.js +9 -0
  18. package/dist/ui/assets/SetupPage-DKmLVUaj.js +1 -0
  19. package/dist/ui/assets/{WebChatPage-R-YOwA4F.js → WebChatPage-CVRcKept.js} +2 -2
  20. package/dist/ui/assets/accordion-C5d5Rm5z.js +1 -0
  21. package/dist/ui/assets/{alert-U8FsgWi7.js → alert-C-NE-P3s.js} +1 -1
  22. package/dist/ui/assets/{alert-dialog-CRdMkkmk.js → alert-dialog-C5mzbHdP.js} +1 -1
  23. package/dist/ui/assets/{badge-Cli1jnH5.js → badge-ChpACfWO.js} +1 -1
  24. package/dist/ui/assets/chevron-up-BYhk0K2J.js +1 -0
  25. package/dist/ui/assets/{dialog-DQ3s-LuO.js → dialog-QnZ0ad8O.js} +1 -1
  26. package/dist/ui/assets/dropdown-menu-BK-CO3Od.js +1 -0
  27. package/dist/ui/assets/{es-DcMjrpbA.js → es-NQNoaWDx.js} +1 -1
  28. package/dist/ui/assets/index-B2fCYtTS.css +2 -0
  29. package/dist/ui/assets/index-DMCjjdqf.js +116 -0
  30. package/dist/ui/assets/{label-0BvGVXvZ.js → label-D2H1IR_J.js} +1 -1
  31. package/dist/ui/assets/progress-BherYzY6.js +1 -0
  32. package/dist/ui/assets/scroll-area-DkeyX32e.js +1 -0
  33. package/dist/ui/assets/{slider-D47dOrRa.js → slider-CsiUDxc3.js} +1 -1
  34. package/dist/ui/assets/switch-BDwN8RYV.js +1 -0
  35. package/dist/ui/assets/{table-DhowbNxQ.js → table-CSc8ubon.js} +1 -1
  36. package/dist/ui/assets/terminal-DN38Q456.js +1 -0
  37. package/dist/ui/assets/useProviders-C6_QHsEi.js +1 -0
  38. package/dist/ui/assets/{vendor-radix-JY4ncZrD.js → vendor-radix-cw1bQaVC.js} +4 -4
  39. package/dist/ui/assets/{vendor-react-CscwQerf.js → vendor-react-D4s9E-zj.js} +1 -1
  40. package/dist/ui/dist/assets/AgentCreateForm-tJZv9FZC.js +1 -0
  41. package/dist/ui/dist/assets/AgentDetailPage-Du-mRcAX.js +1 -0
  42. package/dist/ui/dist/assets/AgentNewPage-DIFYd_Ys.js +1 -0
  43. package/dist/ui/dist/assets/AgentsPage-YvSgWRiw.js +10 -0
  44. package/dist/ui/dist/assets/CanvasPage-DtMwGvxf.js +33 -0
  45. package/dist/ui/dist/assets/ChannelsPage-BdBXWHjj.js +8 -0
  46. package/dist/ui/dist/assets/DashboardPage-ghl1ZguH.js +6 -0
  47. package/dist/ui/dist/assets/LoginPage-CAmSI9Vy.js +1 -0
  48. package/dist/ui/dist/assets/LogsPage-DAPBHkwK.js +1 -0
  49. package/dist/ui/dist/assets/MeetingPage-WjjGOqqU.js +1 -0
  50. package/dist/ui/dist/assets/NotFound-BMeQSGcG.js +1 -0
  51. package/dist/ui/dist/assets/ProvidersPage-Ct6HsAi1.js +1 -0
  52. package/dist/ui/dist/assets/RecoverPage-DpW3l-yv.js +1 -0
  53. package/dist/ui/dist/assets/SettingsPage-DBJ7_E6C.js +9 -0
  54. package/dist/ui/dist/assets/SetupPage-DKmLVUaj.js +1 -0
  55. package/dist/ui/dist/assets/WebChatPage-CVRcKept.js +16 -0
  56. package/dist/ui/dist/assets/accordion-C5d5Rm5z.js +1 -0
  57. package/dist/ui/dist/assets/activity-c3pNngT_.js +1 -0
  58. package/dist/ui/dist/assets/alert-C-NE-P3s.js +1 -0
  59. package/dist/ui/dist/assets/alert-dialog-C5mzbHdP.js +1 -0
  60. package/dist/ui/dist/assets/arrow-left-CBcbX5EZ.js +1 -0
  61. package/dist/ui/dist/assets/badge-ChpACfWO.js +1 -0
  62. package/dist/ui/dist/assets/calendar-B-KZ9RQO.js +1 -0
  63. package/dist/ui/dist/assets/card-CNf6BS2e.js +1 -0
  64. package/dist/ui/dist/assets/chevron-left-D4U-5A27.js +1 -0
  65. package/dist/ui/dist/assets/chevron-right-CR4Skrf3.js +1 -0
  66. package/dist/ui/dist/assets/chevron-up-BYhk0K2J.js +1 -0
  67. package/dist/ui/dist/assets/circle-alert-CyHDwUj8.js +1 -0
  68. package/dist/ui/dist/assets/circle-check-Bb54Ebmu.js +1 -0
  69. package/dist/ui/dist/assets/cpu-Cdgc_B1K.js +1 -0
  70. package/dist/ui/dist/assets/dialog-QnZ0ad8O.js +1 -0
  71. package/dist/ui/dist/assets/download-C3ifGMjJ.js +1 -0
  72. package/dist/ui/dist/assets/dropdown-menu-BK-CO3Od.js +1 -0
  73. package/dist/ui/dist/assets/es-NQNoaWDx.js +1 -0
  74. package/dist/ui/dist/assets/external-link-BvxYeTP1.js +1 -0
  75. package/dist/ui/dist/assets/eye-DqNTU_GD.js +1 -0
  76. package/dist/ui/dist/assets/file-text-BT_9S9SM.js +1 -0
  77. package/dist/ui/dist/assets/folder-open-BhH8y9ac.js +1 -0
  78. package/dist/ui/dist/assets/format-GVHeOyWI.js +1 -0
  79. package/dist/ui/dist/assets/gateway-url-COCbW0IR.js +1 -0
  80. package/dist/ui/dist/assets/gauge-D_TMa4i9.js +1 -0
  81. package/dist/ui/dist/assets/globe-DeCQTCDJ.js +1 -0
  82. package/dist/ui/dist/assets/hexagon-DsGOUl-H.js +1 -0
  83. package/dist/ui/dist/assets/history-BSG-Ypqf.js +1 -0
  84. package/dist/ui/dist/assets/index-B2fCYtTS.css +2 -0
  85. package/dist/ui/dist/assets/index-DMCjjdqf.js +116 -0
  86. package/dist/ui/dist/assets/info-NwLoa2Mj.js +1 -0
  87. package/dist/ui/dist/assets/key-3EP0dhkT.js +1 -0
  88. package/dist/ui/dist/assets/label-D2H1IR_J.js +1 -0
  89. package/dist/ui/dist/assets/loader-circle-CZNax6kS.js +1 -0
  90. package/dist/ui/dist/assets/lock-Ei1_J-Nq.js +1 -0
  91. package/dist/ui/dist/assets/pause-BUqah9Bi.js +1 -0
  92. package/dist/ui/dist/assets/play-NcZ4swwL.js +1 -0
  93. package/dist/ui/dist/assets/plus-CX1xyhp5.js +1 -0
  94. package/dist/ui/dist/assets/progress-BherYzY6.js +1 -0
  95. package/dist/ui/dist/assets/refresh-cw-DaYdjQFk.js +1 -0
  96. package/dist/ui/dist/assets/rolldown-runtime-S-ySWqyJ.js +1 -0
  97. package/dist/ui/dist/assets/save-CUdYyHNy.js +1 -0
  98. package/dist/ui/dist/assets/scroll-area-DkeyX32e.js +1 -0
  99. package/dist/ui/dist/assets/send-B0H5SEIE.js +1 -0
  100. package/dist/ui/dist/assets/settings-Ds4SqD8s.js +1 -0
  101. package/dist/ui/dist/assets/slider-CsiUDxc3.js +14 -0
  102. package/dist/ui/dist/assets/sparkles-yUEb-7oH.js +1 -0
  103. package/dist/ui/dist/assets/square-BD81nFtN.js +1 -0
  104. package/dist/ui/dist/assets/switch-BDwN8RYV.js +1 -0
  105. package/dist/ui/dist/assets/table-CSc8ubon.js +1 -0
  106. package/dist/ui/dist/assets/terminal-DN38Q456.js +1 -0
  107. package/dist/ui/dist/assets/textarea-CXgXWKrT.js +1 -0
  108. package/dist/ui/dist/assets/trash-2-CNjMkoq6.js +1 -0
  109. package/dist/ui/dist/assets/triangle-alert-C9Y8Ub4X.js +1 -0
  110. package/dist/ui/dist/assets/useProviders-C6_QHsEi.js +1 -0
  111. package/dist/ui/dist/assets/utils-3pnRFmFe.js +1 -0
  112. package/dist/ui/dist/assets/vendor-charts-Bu2lyBKP.js +65 -0
  113. package/dist/ui/dist/assets/vendor-query-DsWPbQdG.js +1 -0
  114. package/dist/ui/dist/assets/vendor-radix-cw1bQaVC.js +63 -0
  115. package/dist/ui/dist/assets/vendor-react-D4s9E-zj.js +1 -0
  116. package/dist/ui/dist/assets/vendor-router-C9pIYwbJ.js +3 -0
  117. package/dist/ui/dist/assets/volume-2-CeSXNDv4.js +1 -0
  118. package/dist/ui/dist/assets/zap-hlXjpSeA.js +1 -0
  119. package/dist/ui/dist/favicon.ico +0 -0
  120. package/dist/ui/dist/index.html +40 -0
  121. package/dist/ui/dist/placeholder.svg +1 -0
  122. package/dist/ui/index.html +6 -6
  123. package/package.json +138 -13
  124. package/packages/cli/src/adapters/binary.ts +461 -0
  125. package/packages/cli/src/adapters/bun-global.ts +378 -0
  126. package/packages/cli/src/adapters/config.ts +314 -0
  127. package/packages/cli/src/adapters/docker.ts +308 -0
  128. package/packages/cli/src/adapters/factory.ts +168 -0
  129. package/packages/cli/src/adapters/index.ts +80 -0
  130. package/packages/cli/src/adapters/types.ts +218 -0
  131. package/packages/cli/src/commands/agent-run.ts +168 -0
  132. package/packages/cli/src/commands/agents.ts +398 -0
  133. package/packages/cli/src/commands/chat.ts +142 -0
  134. package/packages/cli/src/commands/config.ts +49 -0
  135. package/packages/cli/src/commands/cron.ts +487 -0
  136. package/packages/cli/src/commands/dev.ts +58 -0
  137. package/packages/cli/src/commands/doctor.ts +320 -0
  138. package/packages/cli/src/commands/gateway.ts +719 -0
  139. package/packages/cli/src/commands/logs.ts +57 -0
  140. package/packages/cli/src/commands/mcp.ts +175 -0
  141. package/packages/cli/src/commands/message.ts +77 -0
  142. package/packages/cli/src/commands/migrate.ts +90 -0
  143. package/packages/cli/src/commands/onboard.ts +1656 -0
  144. package/packages/cli/src/commands/security.ts +144 -0
  145. package/packages/cli/src/commands/service.ts +50 -0
  146. package/packages/cli/src/commands/sessions.ts +116 -0
  147. package/packages/cli/src/commands/skills.ts +215 -0
  148. package/packages/cli/src/commands/update.ts +203 -0
  149. package/packages/cli/src/index.ts +210 -0
  150. package/packages/cli/src/ui-bundle.generated.ts +3 -0
  151. package/packages/cli/src/utils/token.ts +6 -0
  152. package/packages/core/src/agent/agent-loop.ts +691 -0
  153. package/packages/core/src/agent/compaction.ts +240 -0
  154. package/packages/core/src/agent/context-compiler.ts +467 -0
  155. package/packages/core/src/agent/context-guard.ts +91 -0
  156. package/packages/core/src/agent/conversation-store.ts +244 -0
  157. package/packages/core/src/agent/curator.ts +158 -0
  158. package/packages/core/src/agent/hooks.ts +166 -0
  159. package/packages/core/src/agent/llm-client.ts +167 -0
  160. package/packages/core/src/agent/llm-providers/anthropic.ts +212 -0
  161. package/packages/core/src/agent/llm-providers/deepseek.ts +8 -0
  162. package/packages/core/src/agent/llm-providers/gemini.ts +215 -0
  163. package/packages/core/src/agent/llm-providers/groq.ts +5 -0
  164. package/packages/core/src/agent/llm-providers/interface.ts +195 -0
  165. package/packages/core/src/agent/llm-providers/kimi.ts +8 -0
  166. package/packages/core/src/agent/llm-providers/local-llama.ts +37 -0
  167. package/packages/core/src/agent/llm-providers/mistral.ts +5 -0
  168. package/packages/core/src/agent/llm-providers/nvidia.ts +5 -0
  169. package/packages/core/src/agent/llm-providers/ollama.ts +175 -0
  170. package/packages/core/src/agent/llm-providers/openai-compat-base.ts +379 -0
  171. package/packages/core/src/agent/llm-providers/openai.ts +5 -0
  172. package/packages/core/src/agent/llm-providers/openrouter.ts +5 -0
  173. package/packages/core/src/agent/llm-providers/qwen.ts +5 -0
  174. package/packages/core/src/agent/native-tools.ts +31 -0
  175. package/packages/core/src/agent/playbook-selector.ts +147 -0
  176. package/packages/core/src/agent/prompt-builder.ts +169 -0
  177. package/packages/core/src/agent/providers/index.ts +204 -0
  178. package/packages/core/src/agent/providers.ts +1 -0
  179. package/packages/core/src/agent/reflector.ts +200 -0
  180. package/packages/core/src/agent/service.ts +267 -0
  181. package/packages/core/src/agent/skill-selector.ts +479 -0
  182. package/packages/core/src/agent/stuck-loop.ts +133 -0
  183. package/packages/core/src/agent/tool-selector.ts +569 -0
  184. package/packages/core/src/agent/tracer.ts +100 -0
  185. package/packages/core/src/auth/auth.ts +108 -0
  186. package/packages/core/src/auth/index.ts +1 -0
  187. package/packages/core/src/canvas/a2ui-tools.ts +255 -0
  188. package/packages/core/src/canvas/canvas-manager.ts +390 -0
  189. package/packages/core/src/canvas/canvas-tools.ts +448 -0
  190. package/packages/core/src/canvas/emitter.ts +149 -0
  191. package/packages/core/src/canvas/index.ts +3 -0
  192. package/packages/core/src/channels/base.ts +154 -0
  193. package/packages/core/src/channels/discord.ts +273 -0
  194. package/packages/core/src/channels/index.ts +7 -0
  195. package/packages/core/src/channels/manager.ts +450 -0
  196. package/packages/core/src/channels/slack.ts +323 -0
  197. package/packages/core/src/channels/telegram.ts +612 -0
  198. package/packages/core/src/channels/webchat.ts +139 -0
  199. package/packages/core/src/channels/whatsapp.ts +548 -0
  200. package/packages/core/src/config/index.ts +12 -0
  201. package/packages/core/src/config/loader.ts +569 -0
  202. package/packages/core/src/events/agent-bus.ts +460 -0
  203. package/packages/core/src/events/event-bus.ts +169 -0
  204. package/packages/core/src/gateway/channel-notify.ts +64 -0
  205. package/packages/core/src/gateway/helpers/cors.ts +32 -0
  206. package/packages/core/src/gateway/helpers/index.ts +4 -0
  207. package/packages/core/src/gateway/helpers/narration.ts +57 -0
  208. package/packages/core/src/gateway/helpers/path.ts +13 -0
  209. package/packages/core/src/gateway/helpers/redact.ts +61 -0
  210. package/packages/core/src/gateway/index.ts +5 -0
  211. package/packages/core/src/gateway/initializer.ts +363 -0
  212. package/packages/core/src/gateway/lane-queue.ts +169 -0
  213. package/packages/core/src/gateway/llm-local/client.ts +94 -0
  214. package/packages/core/src/gateway/llm-local/detector.ts +321 -0
  215. package/packages/core/src/gateway/llm-local/downloader.ts +216 -0
  216. package/packages/core/src/gateway/llm-local/index.ts +34 -0
  217. package/packages/core/src/gateway/llm-local/manager.ts +186 -0
  218. package/packages/core/src/gateway/llm-local/models.ts +149 -0
  219. package/packages/core/src/gateway/llm-local/server.ts +179 -0
  220. package/packages/core/src/gateway/resolver.ts +108 -0
  221. package/packages/core/src/gateway/router.ts +124 -0
  222. package/packages/core/src/gateway/routes/agents.ts +210 -0
  223. package/packages/core/src/gateway/routes/auth.ts +244 -0
  224. package/packages/core/src/gateway/routes/channels.ts +484 -0
  225. package/packages/core/src/gateway/routes/chat.ts +241 -0
  226. package/packages/core/src/gateway/routes/config.ts +12 -0
  227. package/packages/core/src/gateway/routes/cron-api.ts +544 -0
  228. package/packages/core/src/gateway/routes/ethics.ts +46 -0
  229. package/packages/core/src/gateway/routes/llm-local.ts +271 -0
  230. package/packages/core/src/gateway/routes/mcp.ts +319 -0
  231. package/packages/core/src/gateway/routes/meeting.ts +232 -0
  232. package/packages/core/src/gateway/routes/models.ts +163 -0
  233. package/packages/core/src/gateway/routes/multimodal.ts +93 -0
  234. package/packages/core/src/gateway/routes/providers.ts +220 -0
  235. package/packages/core/src/gateway/routes/setup.ts +441 -0
  236. package/packages/core/src/gateway/routes/skills.ts +115 -0
  237. package/packages/core/src/gateway/routes/system.ts +469 -0
  238. package/packages/core/src/gateway/routes/tasks.ts +44 -0
  239. package/packages/core/src/gateway/routes/tools.ts +59 -0
  240. package/packages/core/src/gateway/routes/tts-local.ts +388 -0
  241. package/packages/core/src/gateway/routes/users.ts +122 -0
  242. package/packages/core/src/gateway/routes/voice.ts +189 -0
  243. package/packages/core/src/gateway/routes/workspace.ts +281 -0
  244. package/packages/core/src/gateway/server.ts +2744 -0
  245. package/packages/core/src/gateway/session.ts +95 -0
  246. package/packages/core/src/gateway/slash-commands.ts +207 -0
  247. package/packages/core/src/gateway/tts/README.md +94 -0
  248. package/packages/core/src/gateway/tts/package.json +25 -0
  249. package/packages/core/src/gateway/tts/src/client.ts +59 -0
  250. package/packages/core/src/gateway/tts/src/detect.ts +42 -0
  251. package/packages/core/src/gateway/tts/src/index.ts +15 -0
  252. package/packages/core/src/gateway/tts/src/install.ts +129 -0
  253. package/packages/core/src/gateway/tts/src/models.ts +50 -0
  254. package/packages/core/src/gateway/tts/src/server.ts +252 -0
  255. package/packages/core/src/gateway/tts/voices/.gitkeep +0 -0
  256. package/packages/core/src/heartbeat/index.ts +157 -0
  257. package/packages/core/src/index.ts +56 -0
  258. package/packages/core/src/mcp/hot-reload.ts +148 -0
  259. package/packages/core/src/mcp/singleton.ts +21 -0
  260. package/packages/core/src/mcp/tool-sync.ts +176 -0
  261. package/packages/core/src/multimodal/index.ts +2 -0
  262. package/packages/core/src/multimodal/types.ts +28 -0
  263. package/packages/core/src/multimodal/vision-service.ts +283 -0
  264. package/packages/core/src/plugins/api.ts +128 -0
  265. package/packages/core/src/plugins/index.ts +2 -0
  266. package/packages/core/src/plugins/loader.ts +365 -0
  267. package/packages/core/src/resilience/circuit-breaker.ts +225 -0
  268. package/packages/core/src/scheduler/CronScheduler.ts +699 -0
  269. package/packages/core/src/scheduler/dag/AgentExecutor.ts +53 -0
  270. package/packages/core/src/scheduler/dag/DAGScheduler.ts +250 -0
  271. package/packages/core/src/scheduler/dag/EventBridge.ts +122 -0
  272. package/packages/core/src/scheduler/dag/TaskGraph.ts +192 -0
  273. package/packages/core/src/scheduler/dag/TaskNode.ts +97 -0
  274. package/packages/core/src/scheduler/dag/TaskResult.ts +22 -0
  275. package/packages/core/src/scheduler/dag/errors.ts +37 -0
  276. package/packages/core/src/scheduler/dag/index.ts +26 -0
  277. package/packages/core/src/scheduler/dag/presets/ResearchPreset.ts +97 -0
  278. package/packages/core/src/scheduler/dag/strategies/ParallelStrategy.ts +21 -0
  279. package/packages/core/src/scheduler/dag/strategies/PriorityStrategy.ts +46 -0
  280. package/packages/core/src/scheduler/index.ts +22 -0
  281. package/packages/core/src/scheduler/integration.ts +237 -0
  282. package/packages/core/src/scheduler/types.ts +164 -0
  283. package/packages/core/src/security/google-chat.ts +269 -0
  284. package/packages/core/src/security/index.ts +192 -0
  285. package/packages/core/src/security/pairing.ts +250 -0
  286. package/packages/core/src/security/rate-limit.ts +270 -0
  287. package/packages/core/src/security/signal.ts +321 -0
  288. package/packages/core/src/state/store.ts +312 -0
  289. package/packages/core/src/storage/crypto.ts +197 -0
  290. package/packages/core/src/storage/migrate.ts +147 -0
  291. package/packages/core/src/storage/onboarding.ts +1506 -0
  292. package/packages/core/src/storage/schema.ts +666 -0
  293. package/packages/core/src/storage/seed.ts +628 -0
  294. package/packages/core/src/storage/sqlite.ts +407 -0
  295. package/packages/core/src/storage/usage.ts +374 -0
  296. package/packages/core/src/tool-runtime/index.ts +502 -0
  297. package/packages/core/src/tool-runtime/tool-worker.ts +125 -0
  298. package/packages/core/src/tools/agents/get-available-models.ts +118 -0
  299. package/packages/core/src/tools/agents/index.ts +610 -0
  300. package/packages/core/src/tools/canvas/index.ts +420 -0
  301. package/packages/core/src/tools/cli/index.ts +142 -0
  302. package/packages/core/src/tools/core/index.ts +478 -0
  303. package/packages/core/src/tools/cron/index.ts +635 -0
  304. package/packages/core/src/tools/filesystem/fs-delete.ts +78 -0
  305. package/packages/core/src/tools/filesystem/fs-edit.ts +106 -0
  306. package/packages/core/src/tools/filesystem/fs-exists.ts +63 -0
  307. package/packages/core/src/tools/filesystem/fs-glob.ts +108 -0
  308. package/packages/core/src/tools/filesystem/fs-list.ts +129 -0
  309. package/packages/core/src/tools/filesystem/fs-read.ts +72 -0
  310. package/packages/core/src/tools/filesystem/fs-write.ts +67 -0
  311. package/packages/core/src/tools/filesystem/index.ts +34 -0
  312. package/packages/core/src/tools/filesystem/workspace-guard.ts +62 -0
  313. package/packages/core/src/tools/index.ts +197 -0
  314. package/packages/core/src/tools/meeting/index.ts +363 -0
  315. package/packages/core/src/tools/office/index.ts +47 -0
  316. package/packages/core/src/tools/office/office-escribir-docx.ts +192 -0
  317. package/packages/core/src/tools/office/office-escribir-pdf.ts +172 -0
  318. package/packages/core/src/tools/office/office-escribir-pptx.ts +174 -0
  319. package/packages/core/src/tools/office/office-escribir-xlsx.ts +116 -0
  320. package/packages/core/src/tools/office/office-leer-docx.ts +93 -0
  321. package/packages/core/src/tools/office/office-leer-pdf.ts +114 -0
  322. package/packages/core/src/tools/office/office-leer-pptx.ts +136 -0
  323. package/packages/core/src/tools/office/office-leer-xlsx.ts +124 -0
  324. package/packages/core/src/tools/types.ts +39 -0
  325. package/packages/core/src/tools/voice/index.ts +104 -0
  326. package/packages/core/src/tools/web/browser-click.ts +78 -0
  327. package/packages/core/src/tools/web/browser-extract.ts +139 -0
  328. package/packages/core/src/tools/web/browser-navigate.ts +106 -0
  329. package/packages/core/src/tools/web/browser-screenshot.ts +87 -0
  330. package/packages/core/src/tools/web/browser-script.ts +88 -0
  331. package/packages/core/src/tools/web/browser-service.ts +554 -0
  332. package/packages/core/src/tools/web/browser-type.ts +101 -0
  333. package/packages/core/src/tools/web/browser-wait.ts +136 -0
  334. package/packages/core/src/tools/web/index.ts +41 -0
  335. package/packages/core/src/tools/web/web-fetch.ts +78 -0
  336. package/packages/core/src/tools/web/web-search.ts +123 -0
  337. package/packages/core/src/utils/benchmark.ts +80 -0
  338. package/packages/core/src/utils/crypto.ts +73 -0
  339. package/packages/core/src/utils/date.ts +42 -0
  340. package/packages/core/src/utils/index.ts +5 -0
  341. package/packages/core/src/utils/logger.ts +389 -0
  342. package/packages/core/src/utils/retry.ts +70 -0
  343. package/packages/core/src/utils/toon.ts +253 -0
  344. package/packages/core/src/voice/index.ts +643 -0
  345. package/packages/mcp/src/config.ts +13 -0
  346. package/packages/mcp/src/index.ts +1 -0
  347. package/packages/mcp/src/logger.ts +47 -0
  348. package/packages/mcp/src/manager.ts +439 -0
  349. package/packages/mcp/src/transports/index.ts +67 -0
  350. package/packages/mcp/src/transports/sse.ts +238 -0
  351. package/packages/mcp/src/transports/websocket.ts +159 -0
  352. package/packages/skills/src/bundled/agents/agent_spawner/SKILL.md +167 -0
  353. package/packages/skills/src/bundled/agents/code_delegator/SKILL.md +156 -0
  354. package/packages/skills/src/bundled/agents/memory_manager/SKILL.md +143 -0
  355. package/packages/skills/src/bundled/agents/research_and_remember/SKILL.md +139 -0
  356. package/packages/skills/src/bundled/agents/task_orchestrator/SKILL.md +198 -0
  357. package/packages/skills/src/bundled/canvas/a2ui_dashboard/SKILL.md +176 -0
  358. package/packages/skills/src/bundled/canvas/a2ui_form/SKILL.md +202 -0
  359. package/packages/skills/src/bundled/canvas/a2ui_interactive/SKILL.md +206 -0
  360. package/packages/skills/src/bundled/canvas/canvas_dashboard/SKILL.md +146 -0
  361. package/packages/skills/src/bundled/canvas/canvas_interact/SKILL.md +148 -0
  362. package/packages/skills/src/bundled/canvas/canvas_report/SKILL.md +146 -0
  363. package/packages/skills/src/bundled/cli/cli_pipeline/SKILL.md +136 -0
  364. package/packages/skills/src/bundled/cli/cli_safe_exec/SKILL.md +125 -0
  365. package/packages/skills/src/bundled/cron_manager/SKILL.md +188 -0
  366. package/packages/skills/src/bundled/cron_reminder/SKILL.md +112 -0
  367. package/packages/skills/src/bundled/filesystem/file_manager/SKILL.md +118 -0
  368. package/packages/skills/src/bundled/filesystem/file_read_and_summarize/SKILL.md +108 -0
  369. package/packages/skills/src/bundled/filesystem/file_writer/SKILL.md +135 -0
  370. package/packages/skills/src/bundled/meeting/meeting_transcription/SKILL.md +213 -0
  371. package/packages/skills/src/bundled/office/office_document_manager/SKILL.md +262 -0
  372. package/packages/skills/src/bundled/search_knowledge/busqueda_fts5/SKILL.md +74 -0
  373. package/packages/skills/src/bundled/voice/voice_assistant/SKILL.md +174 -0
  374. package/packages/skills/src/bundled/voice/voice_input/SKILL.md +146 -0
  375. package/packages/skills/src/bundled/voice/voice_output/SKILL.md +151 -0
  376. package/packages/skills/src/bundled/web/browser_automate/SKILL.md +120 -0
  377. package/packages/skills/src/bundled/web/browser_scrape/SKILL.md +109 -0
  378. package/packages/skills/src/bundled/web/web_monitor/SKILL.md +127 -0
  379. package/packages/skills/src/bundled/web/web_research/SKILL.md +119 -0
  380. package/packages/skills/src/bundled-data.generated.ts +1964 -0
  381. package/packages/skills/src/index.ts +1 -0
  382. package/packages/skills/src/loader.ts +388 -0
  383. package/dist/ui/assets/AgentNewPage-GB-tVN50.js +0 -1
  384. package/dist/ui/assets/BridgePage-DDcDILKu.js +0 -1
  385. package/dist/ui/assets/CanvasPage-oOk2sGOD.js +0 -33
  386. package/dist/ui/assets/DashboardPage-DV_2qWYJ.js +0 -6
  387. package/dist/ui/assets/LogsPage-DayYjh01.js +0 -1
  388. package/dist/ui/assets/MeetingPage-C01uPuqj.js +0 -1
  389. package/dist/ui/assets/ProjectsPage-B8_am_Ib.js +0 -1
  390. package/dist/ui/assets/ProvidersPage-DBzi66e4.js +0 -1
  391. package/dist/ui/assets/SettingsPage-CFA_Tknl.js +0 -9
  392. package/dist/ui/assets/SetupPage-BrUWbhvT.js +0 -1
  393. package/dist/ui/assets/accordion-DdAEfIXR.js +0 -1
  394. package/dist/ui/assets/chevron-down-DIosfU_U.js +0 -1
  395. package/dist/ui/assets/chevron-up-CI-W21Fy.js +0 -1
  396. package/dist/ui/assets/circle-S0-ouLz-.js +0 -1
  397. package/dist/ui/assets/circle-minus-CE0iJrl8.js +0 -1
  398. package/dist/ui/assets/circle-x-jUJ5zZvQ.js +0 -1
  399. package/dist/ui/assets/dropdown-menu-C2CXM1VE.js +0 -1
  400. package/dist/ui/assets/index-BN0875JH.css +0 -2
  401. package/dist/ui/assets/index-CH6sBa3Q.js +0 -116
  402. package/dist/ui/assets/pencil-5VdSj-h5.js +0 -1
  403. package/dist/ui/assets/progress-JN30I5fF.js +0 -1
  404. package/dist/ui/assets/scroll-area-BQQPitM8.js +0 -1
  405. package/dist/ui/assets/search-ChPgnVKj.js +0 -1
  406. package/dist/ui/assets/switch-C7W2-KEx.js +0 -1
  407. package/dist/ui/assets/terminal-C-R5Fckz.js +0 -1
  408. package/dist/ui/assets/useProviders-TBnWn-Hq.js +0 -1
  409. /package/dist/ui/assets/{card-DFKnZ6ky.js → card-CNf6BS2e.js} +0 -0
  410. /package/dist/ui/assets/{circle-alert-KuAm2FWh.js → circle-alert-CyHDwUj8.js} +0 -0
  411. /package/dist/ui/assets/{circle-check-6Ard1-2z.js → circle-check-Bb54Ebmu.js} +0 -0
  412. /package/dist/ui/assets/{cpu-KDy6-FAI.js → cpu-Cdgc_B1K.js} +0 -0
  413. /package/dist/ui/assets/{download-Cjbk4Rek.js → download-C3ifGMjJ.js} +0 -0
  414. /package/dist/ui/assets/{external-link-HtrFM63g.js → external-link-BvxYeTP1.js} +0 -0
  415. /package/dist/ui/assets/{eye-D1dB40_o.js → eye-DqNTU_GD.js} +0 -0
  416. /package/dist/ui/assets/{file-text-CE58EfH0.js → file-text-BT_9S9SM.js} +0 -0
  417. /package/dist/ui/assets/{folder-open-DIPKeiI_.js → folder-open-BhH8y9ac.js} +0 -0
  418. /package/dist/ui/assets/{format-BwdV8bB5.js → format-GVHeOyWI.js} +0 -0
  419. /package/dist/ui/assets/{gateway-url-D5uj6Nxg.js → gateway-url-COCbW0IR.js} +0 -0
  420. /package/dist/ui/assets/{gauge-DmQmJHEg.js → gauge-D_TMa4i9.js} +0 -0
  421. /package/dist/ui/assets/{globe-_hUGxQF4.js → globe-DeCQTCDJ.js} +0 -0
  422. /package/dist/ui/assets/{hexagon-BaNGQlQj.js → hexagon-DsGOUl-H.js} +0 -0
  423. /package/dist/ui/assets/{history-BfZVGlZa.js → history-BSG-Ypqf.js} +0 -0
  424. /package/dist/ui/assets/{info-CBZ5-AlC.js → info-NwLoa2Mj.js} +0 -0
  425. /package/dist/ui/assets/{key-Bv5DdTPh.js → key-3EP0dhkT.js} +0 -0
  426. /package/dist/ui/assets/{loader-circle-C4hhXLgp.js → loader-circle-CZNax6kS.js} +0 -0
  427. /package/dist/ui/assets/{lock-CkZYexqw.js → lock-Ei1_J-Nq.js} +0 -0
  428. /package/dist/ui/assets/{pause-Bpy1_s7y.js → pause-BUqah9Bi.js} +0 -0
  429. /package/dist/ui/assets/{play-Cj4osqJZ.js → play-NcZ4swwL.js} +0 -0
  430. /package/dist/ui/assets/{plus-BQhgZN3A.js → plus-CX1xyhp5.js} +0 -0
  431. /package/dist/ui/assets/{refresh-cw-BfREHVQM.js → refresh-cw-DaYdjQFk.js} +0 -0
  432. /package/dist/ui/assets/{save-FFTD4dMp.js → save-CUdYyHNy.js} +0 -0
  433. /package/dist/ui/assets/{settings-BdHKUL92.js → settings-Ds4SqD8s.js} +0 -0
  434. /package/dist/ui/assets/{sparkles-r4uJbJAl.js → sparkles-yUEb-7oH.js} +0 -0
  435. /package/dist/ui/assets/{square-G7Hyufqm.js → square-BD81nFtN.js} +0 -0
  436. /package/dist/ui/assets/{textarea-5kyuD04X.js → textarea-CXgXWKrT.js} +0 -0
  437. /package/dist/ui/assets/{trash-2-DXVBRWfh.js → trash-2-CNjMkoq6.js} +0 -0
  438. /package/dist/ui/assets/{triangle-alert-Bu5seg9O.js → triangle-alert-C9Y8Ub4X.js} +0 -0
  439. /package/dist/ui/assets/{vendor-router-CCECILJ0.js → vendor-router-C9pIYwbJ.js} +0 -0
  440. /package/dist/ui/assets/{volume-2-s9DuS696.js → volume-2-CeSXNDv4.js} +0 -0
  441. /package/dist/ui/assets/{zap-BPHZzXKV.js → zap-hlXjpSeA.js} +0 -0
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Prompt Builder — Construye el system prompt con la jerarquía constitucional.
3
+ *
4
+ * Orden de ensamblaje:
5
+ * 1. ÉTICA (capa constitucional, siempre completa, inmutable)
6
+ * 2. IDENTIDAD DEL AGENTE (de la tabla agents)
7
+ * 3. HIVE ECOSYSTEM (system prompt directo para el coordinador)
8
+ * 4. IDENTIDAD DEL USUARIO (de la tabla users)
9
+ *
10
+ * El Context Compiler agrega después:
11
+ * - Playbook rules (ACE)
12
+ * - Scratchpad notes
13
+ * - Skills activos
14
+ */
15
+
16
+ import { getDb } from "../storage/sqlite"
17
+ import { logger } from "../utils/logger"
18
+ import { formatContext } from "../utils/toon"
19
+ import { resolveUserId } from "../storage/onboarding"
20
+
21
+ const log = logger.child("prompt-builder")
22
+
23
+ export interface BuildSystemPromptOpts {
24
+ agentId: string
25
+ userId: string
26
+ }
27
+
28
+ /**
29
+ * Construye el system prompt completo para un agente.
30
+ *
31
+ * Jerarquía:
32
+ * 1. Ética (siempre completa, no se filtra, no se comprime)
33
+ * 2. Identidad del agente (role, description, system_prompt)
34
+ * 3. Hive Ecosystem (ya incluido en agents.system_prompt desde onboarding.ts)
35
+ * 4. Identidad del usuario (nombre, preferencias, contexto)
36
+ */
37
+ export async function buildSystemPrompt(opts: BuildSystemPromptOpts): Promise<string> {
38
+ const db = getDb()
39
+ const { agentId, userId } = opts
40
+
41
+ // ──────────────────────────────────────────────────────────────────────────
42
+ // 1. ÉTICA — Capa constitucional (siempre completa)
43
+ // ──────────────────────────────────────────────────────────────────────────
44
+ const ethicsRules = db.query<any, []>(`
45
+ SELECT name, content, description
46
+ FROM ethics
47
+ WHERE enabled = 1 AND active = 1
48
+ ORDER BY is_default DESC, id ASC
49
+ `).all()
50
+
51
+ let ethicsSection = ""
52
+ if (ethicsRules.length > 0) {
53
+ const ethicsContent = ethicsRules.map((rule: any) => {
54
+ return `## ${rule.name}\n${rule.content}`
55
+ }).join("\n\n")
56
+
57
+ ethicsSection = `# ÉTICA Y REGLAS CONSTITUCIONALES\n\n${ethicsContent}\n\n`
58
+ log.info(`[prompt-builder] Loaded ${ethicsRules.length} ethics rules`)
59
+ } else {
60
+ // Ética por defecto si no hay reglas configuradas
61
+ ethicsSection = `# ÉTICA Y REGLAS CONSTITUCIONALES\n\n` +
62
+ `- Sé útil, inofensivo y honesto\n` +
63
+ `- No generes contenido dañino, ilegal o peligroso\n` +
64
+ `- Respeta la privacidad y seguridad del usuario\n` +
65
+ `- Si no sabes algo, admítelo\n\n`
66
+ }
67
+
68
+ // ──────────────────────────────────────────────────────────────────────────
69
+ // 2. IDENTIDAD DEL AGENTE
70
+ // ──────────────────────────────────────────────────────────────────────────
71
+ const agent = db.query<any, [string]>(`
72
+ SELECT id, name, role, description, system_prompt, tone, max_iterations, workspace
73
+ FROM agents
74
+ WHERE id = ?
75
+ `).get(agentId)
76
+
77
+ if (!agent) {
78
+ throw new Error(`Agent not found: ${agentId}`)
79
+ }
80
+
81
+ let agentSection = `# IDENTIDAD DEL AGENTE\n\n`
82
+ agentSection += `**Nombre**: ${agent.name}\n`
83
+ agentSection += `**Rol**: ${agent.role}\n`
84
+
85
+ if (agent.description) {
86
+ agentSection += `**Descripción**: ${agent.description}\n`
87
+ }
88
+
89
+ if (agent.tone) {
90
+ agentSection += `**Tono**: ${agent.tone}\n`
91
+ }
92
+
93
+ agentSection += `**Iteraciones máximas**: ${agent.max_iterations}\n\n`
94
+
95
+ // Workspace configuration
96
+ const workspacePath = agent.workspace || null
97
+ if (workspacePath) {
98
+ agentSection += `# WORKSPACE — ESPACIO DE TRABAJO EXCLUSIVO\n\n`
99
+ agentSection += `**Tu directorio de trabajo es**: \`${workspacePath}\`\n\n`
100
+ agentSection += `## REGLAS OBLIGATORIAS (no negociables)\n\n`
101
+ agentSection += `1. **TODAS** tus operaciones de archivos y comandos ocurren DENTRO de \`${workspacePath}\`. Sin excepciones.\n`
102
+ agentSection += `2. Cuando el sistema te pida listar archivos, explorar, leer o escribir — hazlo SIEMPRE dentro de \`${workspacePath}\`.\n`
103
+ agentSection += `3. Nunca uses \`ls\`, \`find\`, \`cat\` u otras herramientas apuntando a directorios del sistema (\`/\`, \`~\`, \`/home\`, \`/etc\`, etc.).\n`
104
+ agentSection += `4. Cuando uses \`cli_exec\`, el directorio de trabajo ya es \`${workspacePath}\` por defecto — NO necesitas especificar \`cwd\`.\n`
105
+ agentSection += `5. Para rutas relativas, son relativas a \`${workspacePath}\` — no al directorio del proceso.\n`
106
+ agentSection += `6. Si el usuario pide explorar "el proyecto" o "los archivos", asume que se refiere a \`${workspacePath}\`.\n`
107
+ agentSection += `7. Las tools de filesystem (\`fs_read\`, \`fs_write\`, \`fs_list\`, etc.) ya tienen tu workspace configurado — úsalas directamente con rutas relativas.\n\n`
108
+ agentSection += `> IMPORTANTE: Cualquier intento de acceder fuera de \`${workspacePath}\` será bloqueado automáticamente por el sistema.\n\n`
109
+ agentSection += `## CONSULTAS EN MCP, para llamar datos puedes buscar las tools por get o list recors\n\n`
110
+
111
+ }
112
+
113
+ // System prompt específico del agente (su "personalidad" especializada)
114
+ if (agent.system_prompt) {
115
+ agentSection += `## System Prompt\n\n${agent.system_prompt}\n\n`
116
+ }
117
+
118
+
119
+ // ──────────────────────────────────────────────────────────────────────────
120
+ // 3. IDENTIDAD DEL USUARIO
121
+ // ──────────────────────────────────────────────────────────────────────────
122
+ const user = db.query<any, [string]>(`
123
+ SELECT id, name, language, timezone, occupation, notes
124
+ FROM users
125
+ WHERE id = ?
126
+ `).get(userId)
127
+
128
+ let userSection = `# IDENTIDAD DEL USUARIO\n\n`
129
+
130
+ if (user) {
131
+ const userData: Record<string, string | null> = {}
132
+
133
+ if (user.name) userData.Nombre = user.name
134
+ if (user.language) userData.Idioma = user.language
135
+ if (user.timezone) userData.ZonaHoraria = user.timezone
136
+ if (user.occupation) userData.Ocupación = user.occupation
137
+ if (user.notes) userData.Notes = user.notes
138
+
139
+ // Usar TOON para comprimir datos del usuario
140
+ if (Object.keys(userData).length > 0) {
141
+ userSection += formatContext(userData) + "\n\n"
142
+ } else {
143
+ userSection += `Usuario ID: ${userId}\n\n`
144
+ }
145
+ } else {
146
+ userSection += `Usuario ID: ${userId}\n\n`
147
+ }
148
+
149
+ // ──────────────────────────────────────────────────────────────────────────
150
+ // Ensamblar secciones en orden
151
+ // ──────────────────────────────────────────────────────────────────────────
152
+ const systemPrompt = `${ethicsSection}${agentSection}${userSection}`.trim()
153
+
154
+ log.info(`[prompt-builder] Built system prompt for agent=${agent.name} role=${agent.role}`)
155
+
156
+ return systemPrompt
157
+ }
158
+
159
+ /**
160
+ * Versión simplificada para cuando solo se necesita el agentId
161
+ * (usa userId por defecto de env o threadId)
162
+ */
163
+ export async function buildSystemPromptWithProjects(opts: {
164
+ agentId: string
165
+ userId?: string
166
+ }): Promise<string> {
167
+ const userId = opts.userId || resolveUserId({}) || "default"
168
+ return buildSystemPrompt({ agentId: opts.agentId, userId })
169
+ }
@@ -0,0 +1,204 @@
1
+ /**
2
+ * AgentRunner — thin wrapper over the native AgentLoop.
3
+ *
4
+ * Keeps the same public API (generate()) so server.ts doesn't need changes.
5
+ * Internally uses agent-loop.ts instead of LangGraph.
6
+ */
7
+
8
+ import type { Config } from "../../config/loader.ts"
9
+ import { logger } from "../../utils/logger.ts"
10
+ import { getDb } from "../../storage/sqlite.ts"
11
+ import { getAgentLoop } from "../agent-loop"
12
+ import { resolveUserId, resolveAgentId } from "../../storage/onboarding"
13
+ import type { ContentPart } from "../../multimodal/types"
14
+
15
+ export type Provider = "openai" | "anthropic" | "gemini" | "mistral" | "kimi" | "ollama" | "openrouter" | "deepseek" | "nvidia"
16
+
17
+ export interface StepEvent {
18
+ type: "text" | "plan" | "tool_call" | "tool_result"
19
+ message: string
20
+ toolName?: string
21
+ isError?: boolean
22
+ }
23
+
24
+ export interface ModelOptions {
25
+ provider?: Provider
26
+ model?: string
27
+ maxTokens?: number
28
+ temperature?: number
29
+ system?: string
30
+ messages: Array<{ role: string; content: string | ContentPart[] }>
31
+ tools?: Record<string, any>
32
+ maxSteps?: number
33
+ onToken?: (token: string) => void
34
+ onStep?: (step: StepEvent) => Promise<void>
35
+ threadId?: string
36
+ userId?: string
37
+ channel?: string
38
+ rawUserMessage?: string
39
+ signal?: AbortSignal
40
+ }
41
+
42
+ export interface ModelResponse {
43
+ content: string
44
+ toolCalls?: Array<{
45
+ id: string
46
+ name: string
47
+ args: Record<string, unknown>
48
+ }>
49
+ usage?: {
50
+ promptTokens: number
51
+ completionTokens: number
52
+ totalTokens: number
53
+ }
54
+ finishReason?: string
55
+ }
56
+
57
+ export class AgentRunner {
58
+ private config: Config
59
+
60
+ constructor(config: Config) {
61
+ this.config = config
62
+ }
63
+
64
+ async generate(options: ModelOptions): Promise<ModelResponse> {
65
+ const db = getDb()
66
+ // Resolve agentId from database (coordinator or first enabled)
67
+ const agentId = resolveAgentId(null) || "main"
68
+
69
+ // Resolve userId from database
70
+ const userId = options.userId || resolveUserId({})
71
+ if (!userId) {
72
+ throw new Error("No userId provided. Please complete onboarding first.")
73
+ }
74
+ const threadId = options.threadId || userId
75
+
76
+ const agentLoop = getAgentLoop()
77
+ if (!agentLoop) {
78
+ throw new Error("AgentLoop not initialized")
79
+ }
80
+
81
+ let lastAgentContent = ""
82
+ let accumulatedAgentContent = "" // Accumulate content from all agent chunks
83
+ let toolCalls: ModelResponse["toolCalls"] = []
84
+ let totalInputTokens = 0
85
+ let totalOutputTokens = 0
86
+
87
+ try {
88
+ const stream = agentLoop.stream(
89
+ { messages: options.messages },
90
+ {
91
+ configurable: {
92
+ thread_id: threadId,
93
+ agent_id: agentId,
94
+ user_id: userId,
95
+ // system_prompt intentionally omitted — context-compiler builds it
96
+ channel: options.channel,
97
+ raw_user_message: options.rawUserMessage,
98
+ },
99
+ signal: options.signal,
100
+ }
101
+ )
102
+
103
+ let chunkCount = 0
104
+ for await (const chunk of stream) {
105
+ chunkCount++
106
+
107
+ if (chunk.agent?.messages) {
108
+ const lastMsg = chunk.agent.messages[chunk.agent.messages.length - 1]
109
+ const hasToolCalls = (lastMsg as any)?.tool_calls?.length > 0
110
+ const contentLen = lastMsg?.content?.length ?? 0
111
+ const contentType = typeof lastMsg?.content
112
+ logger.info(
113
+ `[STREAM] chunk#${chunkCount} agent: contentLen=${contentLen} hasToolCalls=${hasToolCalls} contentType=${contentType}`
114
+ )
115
+
116
+ if (lastMsg?.content) {
117
+ const content = typeof lastMsg.content === "string"
118
+ ? lastMsg.content
119
+ : Array.isArray(lastMsg.content)
120
+ ? lastMsg.content.filter(p => p.type === "text").map(p => (p as any).text).join("\n")
121
+ : ""
122
+ lastAgentContent = content
123
+ // Accumulate non-empty content that's not just whitespace
124
+ if (content && content.trim().length > 0) {
125
+ accumulatedAgentContent += (accumulatedAgentContent ? "\n" : "") + content
126
+ logger.debug(`[STREAM] Accumulated content: total length=${accumulatedAgentContent.length}`)
127
+ } else {
128
+ logger.debug(`[STREAM] Content empty or whitespace only, skipping accumulation`)
129
+ }
130
+ if (options.onToken) options.onToken(content)
131
+ } else {
132
+ logger.debug(`[STREAM] No content in chunk, lastMsg.content is falsy`)
133
+ }
134
+
135
+ if (hasToolCalls) {
136
+ toolCalls = (lastMsg as any).tool_calls.map((tc: any) => ({
137
+ id: tc.id || tc.function?.name,
138
+ name: tc.function?.name || tc.name,
139
+ args: tc.function?.arguments
140
+ ? (typeof tc.function.arguments === "string"
141
+ ? JSON.parse(tc.function.arguments)
142
+ : tc.function.arguments)
143
+ : {},
144
+ }))
145
+
146
+ const narration = lastMsg?.content || ""
147
+ if (options.onStep && narration) {
148
+ await options.onStep({ type: "text", message: narration })
149
+ }
150
+ if (options.onStep) {
151
+ for (const tc of toolCalls) {
152
+ await options.onStep({
153
+ type: "tool_call",
154
+ toolName: tc.name,
155
+ message: `Calling tool: \`${tc.name}\``,
156
+ })
157
+ }
158
+ }
159
+ }
160
+ }
161
+
162
+ if (chunk.tools?.messages) {
163
+ const lastMsg = chunk.tools.messages[chunk.tools.messages.length - 1]
164
+ if (lastMsg?.content && options.onStep) {
165
+ await options.onStep({
166
+ type: "tool_result",
167
+ message: typeof lastMsg.content === "string" ? lastMsg.content : "",
168
+ })
169
+ }
170
+ }
171
+
172
+ if (chunk.usage) {
173
+ totalInputTokens += chunk.usage.input_tokens
174
+ totalOutputTokens += chunk.usage.output_tokens
175
+ }
176
+ }
177
+
178
+ logger.debug(`[STREAM] done. totalChunks=${chunkCount} lastAgentContent length=${lastAgentContent.length}, accumulated length=${accumulatedAgentContent.length}`)
179
+
180
+ // Use accumulated content if lastAgentContent is empty (handles case where final chunk has no text)
181
+ const finalContent = lastAgentContent || accumulatedAgentContent
182
+
183
+ logger.info(`[STREAM] Returning response: finalContent length=${finalContent.length}, lastAgentContent length=${lastAgentContent.length}, accumulated length=${accumulatedAgentContent.length}`)
184
+
185
+ return {
186
+ content: finalContent,
187
+ toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
188
+ usage: {
189
+ promptTokens: totalInputTokens,
190
+ completionTokens: totalOutputTokens,
191
+ totalTokens: totalInputTokens + totalOutputTokens,
192
+ },
193
+ finishReason: "stop",
194
+ }
195
+ } catch (error) {
196
+ logger.error("AgentRunner error:", error)
197
+ throw error
198
+ }
199
+ }
200
+ }
201
+
202
+ export function createAgentRunner(config: Config): AgentRunner {
203
+ return new AgentRunner(config)
204
+ }
@@ -0,0 +1 @@
1
+ export * from "./providers/index.ts";
@@ -0,0 +1,200 @@
1
+ /**
2
+ * ACE Reflector — analyzes recent traces and produces insights.
3
+ *
4
+ * Runs in the background (never blocks the main agent loop).
5
+ * Triggered by the tracer after N new traces.
6
+ *
7
+ * Output → `reflections` table → picked up by Curator.
8
+ */
9
+
10
+ import { logger } from "../utils/logger"
11
+
12
+ const log = logger.child("reflector")
13
+
14
+ const MAX_TRACES_TO_ANALYZE = 30
15
+ const MIN_TRACES_TO_RUN = 10
16
+
17
+ /** Main entry point — called from tracer.ts */
18
+ export async function runReflector(): Promise<void> {
19
+ try {
20
+ const { getDb } = await import("../storage/sqlite")
21
+ const db = getDb()
22
+
23
+ log.info(`[reflector] Starting reflection cycle...`)
24
+
25
+ // Fetch traces not yet covered by any reflection
26
+ log.debug(`[reflector] Querying last reflection ID...`)
27
+ const lastReflectionId = (db.query<any, []>(
28
+ "SELECT MAX(id) as mid FROM reflections"
29
+ ).get() as any)?.mid ?? 0
30
+ log.debug(`[reflector] Last reflection ID: ${lastReflectionId}`)
31
+
32
+ // Get last processed trace ID from reflections
33
+ log.debug(`[reflector] Querying last processed trace ID with json_each...`)
34
+ let lastProcessedTrace = 0
35
+ try {
36
+ const result = (db.query<any, []>(
37
+ `SELECT MAX(CAST(json_each.value AS INTEGER)) as max_id
38
+ FROM reflections, json_each(reflections.trace_ids)
39
+ WHERE reflections.id = (SELECT MAX(id) FROM reflections)`
40
+ ).get() as any)?.max_id ?? 0
41
+ lastProcessedTrace = result
42
+ log.debug(`[reflector] Last processed trace ID: ${lastProcessedTrace}`)
43
+ } catch (jsonErr) {
44
+ log.error(`[reflector] json_each query failed:`, jsonErr)
45
+ log.error(`[reflector] Full error details:`, {
46
+ message: (jsonErr as Error).message,
47
+ stack: (jsonErr as Error).stack,
48
+ errno: (jsonErr as any).errno,
49
+ byteOffset: (jsonErr as any).byteOffset,
50
+ })
51
+ throw jsonErr // Re-throw to see full stack trace in main catch
52
+ }
53
+
54
+ log.debug(`[reflector] Fetching traces from DB, lastProcessedTrace=${lastProcessedTrace}, limit=${MAX_TRACES_TO_ANALYZE}`)
55
+ const traces = db.query<any, [number, number]>(`
56
+ SELECT id, agent_id, agent_name, tool_used, input_summary,
57
+ output_summary, success, error_message, duration_ms, tokens_used, created_at
58
+ FROM traces
59
+ WHERE id > ?
60
+ ORDER BY id ASC
61
+ LIMIT ?
62
+ `).all(lastProcessedTrace, MAX_TRACES_TO_ANALYZE)
63
+
64
+ log.debug(`[reflector] Fetched ${traces.length} traces from DB`)
65
+
66
+ if (traces.length < MIN_TRACES_TO_RUN) {
67
+ log.debug(`[reflector] Not enough traces (${traces.length}/${MIN_TRACES_TO_RUN}), skipping`)
68
+ return
69
+ }
70
+
71
+ log.info(`[reflector] Analyzing ${traces.length} traces...`)
72
+
73
+ const insights = analyzeTracesLocally(traces)
74
+
75
+ if (insights.length === 0) {
76
+ log.debug("[reflector] No insights generated")
77
+ return
78
+ }
79
+
80
+ const traceIds = JSON.stringify(traces.map((t: any) => t.id))
81
+
82
+ for (const insight of insights) {
83
+ db.query(`
84
+ INSERT INTO reflections (trace_ids, insight_type, description, affected_tools, affected_agents, confidence)
85
+ VALUES (?, ?, ?, ?, ?, ?)
86
+ `).run(
87
+ traceIds,
88
+ insight.type,
89
+ insight.description,
90
+ insight.affectedTools ? JSON.stringify(insight.affectedTools) : null,
91
+ insight.affectedAgents ? JSON.stringify(insight.affectedAgents) : null,
92
+ insight.confidence,
93
+ )
94
+ }
95
+
96
+ log.info(`[reflector] Generated ${insights.length} insights`)
97
+
98
+ // Trigger curator
99
+ const { runCurator } = await import("./curator")
100
+ await runCurator()
101
+
102
+ log.info(`[reflector] Reflection cycle completed successfully`)
103
+ } catch (err) {
104
+ log.error(`[reflector] Error during reflection:`, {
105
+ message: (err as Error).message,
106
+ stack: (err as Error).stack,
107
+ errno: (err as any).errno,
108
+ byteOffset: (err as any).byteOffset,
109
+ code: (err as any).code,
110
+ })
111
+ }
112
+ }
113
+
114
+ // ─── Local analysis (heuristic, no LLM call needed for basic patterns) ────────
115
+
116
+ interface Insight {
117
+ type: "success_pattern" | "failure_pattern" | "optimization" | "ethics_violation"
118
+ description: string
119
+ affectedTools?: string[]
120
+ affectedAgents?: string[]
121
+ confidence: number
122
+ }
123
+
124
+ function analyzeTracesLocally(traces: any[]): Insight[] {
125
+ const insights: Insight[] = []
126
+
127
+ // ── Failure patterns ─────────────────────────────────────────────────────
128
+ const failures = traces.filter((t: any) => !t.success)
129
+ if (failures.length > 3) {
130
+ // Group by tool
131
+ const toolFailures: Record<string, number> = {}
132
+ for (const f of failures) {
133
+ if (f.tool_used) {
134
+ toolFailures[f.tool_used] = (toolFailures[f.tool_used] || 0) + 1
135
+ }
136
+ }
137
+ for (const [tool, count] of Object.entries(toolFailures)) {
138
+ if (count >= 3) {
139
+ insights.push({
140
+ type: "failure_pattern",
141
+ description: `Tool '${tool}' failed ${count} times recently. Consider verifying its configuration or avoiding it for this type of task.`,
142
+ affectedTools: [tool],
143
+ confidence: Math.min(0.9, count / 10),
144
+ })
145
+ }
146
+ }
147
+ }
148
+
149
+ // ── Slow tools ───────────────────────────────────────────────────────────
150
+ const slowThresholdMs = 5000
151
+ const slowTools: Record<string, number[]> = {}
152
+ for (const t of traces) {
153
+ if (t.tool_used && t.duration_ms > slowThresholdMs) {
154
+ if (!slowTools[t.tool_used]) slowTools[t.tool_used] = []
155
+ slowTools[t.tool_used].push(t.duration_ms)
156
+ }
157
+ }
158
+ for (const [tool, durations] of Object.entries(slowTools)) {
159
+ if (durations.length >= 3) {
160
+ const avg = Math.round(durations.reduce((a, b) => a + b, 0) / durations.length)
161
+ insights.push({
162
+ type: "optimization",
163
+ description: `Tool '${tool}' is consistently slow (avg ${avg}ms). Cache results when possible or use a faster alternative.`,
164
+ affectedTools: [tool],
165
+ confidence: 0.6,
166
+ })
167
+ }
168
+ }
169
+
170
+ // ── High success pattern ─────────────────────────────────────────────────
171
+ const successByTool: Record<string, { ok: number; total: number }> = {}
172
+ for (const t of traces) {
173
+ if (!t.tool_used) continue
174
+ if (!successByTool[t.tool_used]) successByTool[t.tool_used] = { ok: 0, total: 0 }
175
+ successByTool[t.tool_used].total++
176
+ if (t.success) successByTool[t.tool_used].ok++
177
+ }
178
+ for (const [tool, stats] of Object.entries(successByTool)) {
179
+ if (stats.total >= 5 && stats.ok / stats.total >= 0.9) {
180
+ insights.push({
181
+ type: "success_pattern",
182
+ description: `Tool '${tool}' has a high success rate (${stats.ok}/${stats.total}). Prefer it for related tasks.`,
183
+ affectedTools: [tool],
184
+ confidence: stats.ok / stats.total,
185
+ })
186
+ }
187
+ }
188
+
189
+ // ── High token usage ─────────────────────────────────────────────────────
190
+ const highTokenTraces = traces.filter((t: any) => t.tokens_used > 4000)
191
+ if (highTokenTraces.length > 3) {
192
+ insights.push({
193
+ type: "optimization",
194
+ description: `${highTokenTraces.length} recent calls used >4000 tokens. Be more concise and use tool results as summaries, not raw dumps.`,
195
+ confidence: 0.7,
196
+ })
197
+ }
198
+
199
+ return insights
200
+ }