@johpaz/hive-agents 1.0.4 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (248) hide show
  1. package/README.md +5 -5
  2. package/dist/hive.js +88127 -103024
  3. package/dist/tool-worker.js +13243 -17002
  4. package/dist/ui/assets/A2UIPage-CS0VPY6a.js +8 -0
  5. package/dist/ui/assets/AgentCreateForm-DXkjtXaS.js +1 -0
  6. package/dist/ui/assets/AgentDetailPage-DUIX_cuQ.js +1 -0
  7. package/dist/ui/assets/AgentNewPage-SNXz2wik.js +1 -0
  8. package/dist/ui/assets/AgentsPage-CGsdgx5F.js +10 -0
  9. package/dist/ui/assets/{ApiClientPage-6a6KFwsQ.js → ApiClientPage-MNMjfSDs.js} +2 -2
  10. package/dist/ui/assets/ChannelsPage-BEwxWUcE.js +8 -0
  11. package/dist/ui/assets/DashboardPage-D6cRFKWW.js +6 -0
  12. package/dist/ui/assets/LoginPage-ByYmIa2p.js +1 -0
  13. package/dist/ui/assets/LogsPage-Bmk9rohg.js +1 -0
  14. package/dist/ui/assets/MeetingPage-Dm97Mbiw.js +1 -0
  15. package/dist/ui/assets/ModelSelector-gubC8j_Q.js +1 -0
  16. package/dist/ui/assets/NotFound-PUg3gEO0.js +1 -0
  17. package/dist/ui/assets/{Office3DPage-C3SIzd2H.css → Office3DPage-31AMJ-LN.css} +1 -1
  18. package/dist/ui/assets/Office3DPage-Bfi-S2kG.js +727 -0
  19. package/dist/ui/assets/ProvidersPage-CSo0MYxd.js +1 -0
  20. package/dist/ui/assets/RecoverPage-YY2QU-qh.js +1 -0
  21. package/dist/ui/assets/SettingsPage-DrafhhKw.js +9 -0
  22. package/dist/ui/assets/SetupPage-LXnd2XbV.js +1 -0
  23. package/dist/ui/assets/Vignette-BcPWkNhm.js +4302 -0
  24. package/dist/ui/assets/VoicePage-p-hTMAq7.js +307 -0
  25. package/dist/ui/assets/VoicePage-uLWdtoD4.css +1 -0
  26. package/dist/ui/assets/WebChatPage-B61ZDjQ8.js +29 -0
  27. package/dist/ui/assets/agentCapabilities-PfTEVxG1.js +1 -0
  28. package/dist/ui/assets/alert-CjiX20jI.js +1 -0
  29. package/dist/ui/assets/badge-B5AKge1b.js +1 -0
  30. package/dist/ui/assets/bia-4LFKOyxR.webp +0 -0
  31. package/dist/ui/assets/bia-BFcUpOu3.glb +0 -0
  32. package/dist/ui/assets/card-mTJ4oZbL.js +1 -0
  33. package/dist/ui/assets/conversationsStore-BlwA3yd2.js +1 -0
  34. package/dist/ui/assets/dialog-B04KpdNt.js +1 -0
  35. package/dist/ui/assets/dist-js-Dh18rcg9.js +1 -0
  36. package/dist/ui/assets/{dist-js-CLxM1g2B.js → dist-js-q7C_AB0j.js} +1 -1
  37. package/dist/ui/assets/index-ByTufXPh.css +2 -0
  38. package/dist/ui/assets/index-DKJFLL3a.js +116 -0
  39. package/dist/ui/assets/label-D_fvqJyD.js +1 -0
  40. package/dist/ui/assets/lock-3IApZyVy.js +1 -0
  41. package/dist/ui/assets/{square-psq7k_CB.js → mic-CpDU_2as.js} +1 -1
  42. package/dist/ui/assets/pencil-L3Li7_pz.js +1 -0
  43. package/dist/ui/assets/rotate-ccw-LoM1AuqK.js +1 -0
  44. package/dist/ui/assets/scroll-area-CbH8FOo8.js +1 -0
  45. package/dist/ui/assets/select-v_3QBYrD.js +1 -0
  46. package/dist/ui/assets/slider-DXS4h1LB.js +1 -0
  47. package/dist/ui/assets/square-D5zdNkAY.js +1 -0
  48. package/dist/ui/assets/switch-ndx8VCpm.js +1 -0
  49. package/dist/ui/assets/tabs-epu-3Tl4.js +1 -0
  50. package/dist/ui/assets/textarea-BgZJFZTX.js +1 -0
  51. package/dist/ui/assets/useAudioDevices-B2stUHvr.js +41 -0
  52. package/dist/ui/assets/useHiveAgentsModelLoad-B4EjHvj4.js +1 -0
  53. package/dist/ui/assets/useOfficeModel-BaDn7U-X.js +1 -0
  54. package/dist/ui/assets/{useProviders-CiLSc05q.js → useProviders-B1NS24md.js} +1 -1
  55. package/dist/ui/assets/vendor-react-kUOwxn0g.js +1 -0
  56. package/dist/ui/assets/volume-2-EaA0JRvD.js +1 -0
  57. package/dist/ui/assets/volume-x-CROXNMGT.js +1 -0
  58. package/dist/ui/index.html +6 -6
  59. package/package.json +10 -6
  60. package/packages/cli/src/adapters/config.ts +11 -3
  61. package/packages/cli/src/commands/causal.ts +1 -1
  62. package/packages/cli/src/commands/doctor.ts +101 -46
  63. package/packages/cli/src/commands/onboard.ts +4 -2
  64. package/packages/core/src/agent/agent-catalog.ts +47 -47
  65. package/packages/core/src/agent/agent-loop.ts +67 -14
  66. package/packages/core/src/agent/capability-search.ts +2 -1
  67. package/packages/core/src/agent/compaction.ts +19 -7
  68. package/packages/core/src/agent/context-compiler.ts +166 -28
  69. package/packages/core/src/agent/conversation-store.ts +26 -2
  70. package/packages/core/src/agent/goal-runner.ts +2 -2
  71. package/packages/core/src/agent/jev-decisions.ts +148 -0
  72. package/packages/core/src/agent/jev-planner.ts +293 -0
  73. package/packages/core/src/agent/llm-client.ts +29 -7
  74. package/packages/core/src/agent/llm-providers/ollama.ts +17 -4
  75. package/packages/core/src/agent/llm-providers/openai-compat-base.ts +27 -12
  76. package/packages/core/src/agent/llm-providers/opencode-go.ts +37 -0
  77. package/packages/core/src/agent/prompt-builder.ts +1 -1
  78. package/packages/core/src/agent/realtime-providers/gemini-live.ts +233 -0
  79. package/packages/core/src/agent/realtime-providers/index.ts +29 -0
  80. package/packages/core/src/agent/realtime-providers/interface.ts +108 -0
  81. package/packages/core/src/agent/skill-selector.ts +5 -3
  82. package/packages/core/src/agent/thread-id.ts +71 -0
  83. package/packages/core/src/agent/thread-store.ts +230 -0
  84. package/packages/core/src/agent/tool-selector.ts +2 -0
  85. package/packages/core/src/agent/tracer.ts +2 -0
  86. package/packages/core/src/canvas/canvas-manager.ts +145 -27
  87. package/packages/core/src/canvas/emitter.ts +24 -0
  88. package/packages/core/src/channels/telegram.ts +19 -1
  89. package/packages/core/src/channels/webchat.ts +47 -45
  90. package/packages/core/src/config/loader.ts +9 -6
  91. package/packages/core/src/events/tool-narration.ts +1 -0
  92. package/packages/core/src/gateway/channel-notify.ts +24 -5
  93. package/packages/core/src/gateway/delegation-groups.ts +5 -5
  94. package/packages/core/src/gateway/delegation-notify.ts +34 -5
  95. package/packages/core/src/gateway/durable-queue.ts +22 -0
  96. package/packages/core/src/gateway/failure-notify.ts +8 -2
  97. package/packages/core/src/gateway/initializer.ts +17 -10
  98. package/packages/core/src/gateway/job-executors.ts +3 -3
  99. package/packages/core/src/gateway/realtime/bridge-tools.ts +470 -0
  100. package/packages/core/src/gateway/realtime/index.ts +305 -0
  101. package/packages/core/src/gateway/realtime/prompt.ts +182 -0
  102. package/packages/core/src/gateway/realtime/protocol.ts +60 -0
  103. package/packages/core/src/gateway/realtime/voice-session.ts +442 -0
  104. package/packages/core/src/gateway/resolver.ts +31 -4
  105. package/packages/core/src/gateway/routes/artifacts.ts +13 -0
  106. package/packages/core/src/gateway/routes/chat.ts +20 -4
  107. package/packages/core/src/gateway/routes/conversations.ts +121 -0
  108. package/packages/core/src/gateway/routes/providers.ts +16 -1
  109. package/packages/core/src/gateway/routes/setup.ts +25 -14
  110. package/packages/core/src/gateway/routes/system.ts +4 -2
  111. package/packages/core/src/gateway/routes/tts-local.ts +2 -1
  112. package/packages/core/src/gateway/server.ts +171 -13
  113. package/packages/core/src/gateway/slash-commands.ts +48 -10
  114. package/packages/core/src/gateway/tts/src/server.ts +2 -1
  115. package/packages/core/src/gateway/webchat-turn.ts +68 -10
  116. package/packages/core/src/index.ts +2 -0
  117. package/packages/core/src/scheduler/CronScheduler.ts +20 -8
  118. package/packages/core/src/scheduler/cron/cron-engine.test.ts +295 -0
  119. package/packages/core/src/scheduler/cron/expression.ts +165 -0
  120. package/packages/core/src/scheduler/cron/index.ts +10 -0
  121. package/packages/core/src/scheduler/cron/job.ts +340 -0
  122. package/packages/core/src/scheduler/cron/next-run.ts +121 -0
  123. package/packages/core/src/scheduler/cron/zoned-time.ts +139 -0
  124. package/packages/core/src/scheduler/integration.ts +16 -5
  125. package/packages/core/src/scheduler/types.ts +3 -18
  126. package/packages/core/src/storage/bootstrap.ts +23 -0
  127. package/packages/core/src/storage/collections.ts +38 -1
  128. package/packages/core/src/storage/crypto.ts +23 -12
  129. package/packages/core/src/storage/onboarding.ts +39 -39
  130. package/packages/core/src/storage/reconcile.ts +6 -1
  131. package/packages/core/src/storage/seed.ts +82 -8
  132. package/packages/core/src/storage/usage.ts +53 -1
  133. package/packages/core/src/tool-runtime/index.ts +19 -1
  134. package/packages/core/src/tools/a2ui/index.ts +65 -1
  135. package/packages/core/src/tools/agents/get-available-models.ts +3 -1
  136. package/packages/core/src/tools/core/index.ts +39 -4
  137. package/packages/core/src/tools/cron/index.ts +4 -4
  138. package/packages/core/src/tools/index.ts +2 -1
  139. package/packages/core/src/tools/office/office-escribir-xlsx.ts +2 -1
  140. package/packages/core/src/tools/office/office-leer-xlsx.ts +2 -1
  141. package/packages/core/src/tools/office/xlsx-loader.ts +19 -0
  142. package/packages/core/src/tools/web/browser-backend.ts +141 -44
  143. package/packages/core/src/tools/web/browser-click.ts +2 -2
  144. package/packages/core/src/tools/web/browser-extract.ts +2 -2
  145. package/packages/core/src/tools/web/browser-navigate.ts +2 -2
  146. package/packages/core/src/tools/web/browser-screenshot.ts +12 -5
  147. package/packages/core/src/tools/web/browser-script.ts +2 -2
  148. package/packages/core/src/tools/web/browser-service.ts +63 -384
  149. package/packages/core/src/tools/web/browser-session.ts +125 -0
  150. package/packages/core/src/tools/web/browser-type.ts +2 -2
  151. package/packages/core/src/tools/web/browser-wait.ts +2 -2
  152. package/packages/core/src/tools/web/computer-use.ts +553 -0
  153. package/packages/core/src/tools/web/index.ts +5 -1
  154. package/packages/core/src/tools/web/webview-backend.ts +559 -21
  155. package/packages/core/src/utils/port.ts +33 -0
  156. package/packages/core/src/voice/index.ts +2 -1
  157. package/packages/mcp/src/config.ts +2 -1
  158. package/packages/mcp/src/manager.ts +9 -0
  159. package/packages/mcp/src/transports/index.ts +42 -1
  160. package/packages/mcp/src/transports/sse.ts +11 -5
  161. package/packages/skills/src/bundled/a2ui/a2ui_dashboard/SKILL.md +2 -2
  162. package/packages/skills/src/bundled/a2ui/a2ui_form/SKILL.md +2 -2
  163. package/packages/skills/src/bundled/a2ui/a2ui_interactive/SKILL.md +4 -4
  164. package/packages/skills/src/bundled/agents/agent_spawner/SKILL.md +7 -7
  165. package/packages/skills/src/bundled/agents/memory_manager/SKILL.md +9 -9
  166. package/packages/skills/src/bundled/agents/research_and_remember/SKILL.md +8 -8
  167. package/packages/skills/src/bundled/agents/task_orchestrator/SKILL.md +8 -8
  168. package/packages/skills/src/bundled/artifacts/artifact_reader/SKILL.md +104 -0
  169. package/packages/skills/src/bundled/cli/cli_pipeline/SKILL.md +6 -6
  170. package/packages/skills/src/bundled/cli/cli_safe_exec/SKILL.md +5 -5
  171. package/packages/skills/src/bundled/cron_manager/SKILL.md +29 -19
  172. package/packages/skills/src/bundled/cron_reminder/SKILL.md +5 -5
  173. package/packages/skills/src/bundled/filesystem/file_manager/SKILL.md +4 -4
  174. package/packages/skills/src/bundled/filesystem/file_read_and_summarize/SKILL.md +7 -7
  175. package/packages/skills/src/bundled/filesystem/file_writer/SKILL.md +10 -10
  176. package/packages/skills/src/bundled/search_knowledge/capability_discovery/SKILL.md +8 -8
  177. package/packages/skills/src/bundled/web/browser_automate/SKILL.md +21 -12
  178. package/packages/skills/src/bundled/web/browser_scrape/SKILL.md +28 -13
  179. package/packages/skills/src/bundled/web/web_monitor/SKILL.md +6 -6
  180. package/packages/skills/src/bundled/web/web_research/SKILL.md +5 -5
  181. package/packages/skills/src/bundled-data.generated.ts +837 -783
  182. package/dist/ui/assets/A2UIPage-7Ry5rHh9.js +0 -8
  183. package/dist/ui/assets/AgentCreateForm-Dh5W0q_t.js +0 -1
  184. package/dist/ui/assets/AgentDetailPage-CIoPjtsS.js +0 -1
  185. package/dist/ui/assets/AgentNewPage-BNsZcJQf.js +0 -1
  186. package/dist/ui/assets/AgentsPage-YZrDmgNI.js +0 -10
  187. package/dist/ui/assets/ChannelsPage-Dice4dkJ.js +0 -8
  188. package/dist/ui/assets/DashboardPage-B9r0sc0F.js +0 -6
  189. package/dist/ui/assets/LoginPage-BkAAX_tu.js +0 -1
  190. package/dist/ui/assets/LogsPage-8-H1OJs3.js +0 -1
  191. package/dist/ui/assets/MeetingPage-14JoQo71.js +0 -1
  192. package/dist/ui/assets/ModelSelector-CrgJQ7DG.js +0 -1
  193. package/dist/ui/assets/NotFound-B06kVW7N.js +0 -1
  194. package/dist/ui/assets/Office3DPage-BMUZWkFS.js +0 -4614
  195. package/dist/ui/assets/ProvidersPage-BiL3QxCs.js +0 -1
  196. package/dist/ui/assets/RecoverPage-D1o8yxNz.js +0 -1
  197. package/dist/ui/assets/SettingsPage-GP8UwQIL.js +0 -9
  198. package/dist/ui/assets/SetupPage-B_gU1YQU.js +0 -1
  199. package/dist/ui/assets/WebChatPage-Yahufnth.js +0 -29
  200. package/dist/ui/assets/agentCapabilities-Dg72UAFj.js +0 -1
  201. package/dist/ui/assets/alert-DChoEVJw.js +0 -1
  202. package/dist/ui/assets/badge-uRjRSt86.js +0 -1
  203. package/dist/ui/assets/card-DwQizslL.js +0 -1
  204. package/dist/ui/assets/dialog--mljnfAi.js +0 -1
  205. package/dist/ui/assets/dist-js-B0s_TDau.js +0 -1
  206. package/dist/ui/assets/index-BHHUQZJd.js +0 -116
  207. package/dist/ui/assets/index-CEFhf4dF.css +0 -2
  208. package/dist/ui/assets/label-BceoUB2w.js +0 -1
  209. package/dist/ui/assets/pencil-CUbpCfeG.js +0 -1
  210. package/dist/ui/assets/scroll-area-DMEaZZUp.js +0 -1
  211. package/dist/ui/assets/select-BBEBtcLm.js +0 -1
  212. package/dist/ui/assets/slider-DcmBdvYD.js +0 -1
  213. package/dist/ui/assets/switch-CgiDezVR.js +0 -1
  214. package/dist/ui/assets/tabs-gUXIjjZv.js +0 -1
  215. package/dist/ui/assets/textarea-DedxQYBx.js +0 -1
  216. package/dist/ui/assets/useHiveAgentsModelLoad-C7bhWPDG.js +0 -1
  217. package/dist/ui/assets/useOfficeModel-BAFasrg8.js +0 -1
  218. package/dist/ui/assets/vendor-react-DYyYpuMy.js +0 -1
  219. package/dist/ui/assets/volume-x-BDlMCDYT.js +0 -1
  220. /package/dist/ui/assets/{core-Sjunb8Z1.js → core-B_5cyOSV.js} +0 -0
  221. /package/dist/ui/assets/{download-D0aDV8Y_.js → download-BQXrpH0m.js} +0 -0
  222. /package/dist/ui/assets/{ellipsis-vertical-BOW_iEOO.js → ellipsis-vertical-D7uFJLGh.js} +0 -0
  223. /package/dist/ui/assets/{external-link-5cujQzfV.js → external-link-6oTH9pUM.js} +0 -0
  224. /package/dist/ui/assets/{eye-sRPY5qOa.js → eye-CxvxtQT5.js} +0 -0
  225. /package/dist/ui/assets/{file-text-DNSyNLUh.js → file-text-D5ZJEx3E.js} +0 -0
  226. /package/dist/ui/assets/{gateway-url-BZj_2-jf.js → gateway-url-BALS_wVh.js} +0 -0
  227. /package/dist/ui/assets/{gauge-C__zxC3_.js → gauge-CEu7PhTW.js} +0 -0
  228. /package/dist/ui/assets/{history-BHQWfE-7.js → history-DLK5rTlP.js} +0 -0
  229. /package/dist/ui/assets/{info-CG1VohyH.js → info-8ReWzubE.js} +0 -0
  230. /package/dist/ui/assets/{key-BC28VCjO.js → key-DPkOY-J0.js} +0 -0
  231. /package/dist/ui/assets/{lock-open-Bhp0UJlL.js → lock-open-v0EphssG.js} +0 -0
  232. /package/dist/ui/assets/{mail-Biwn8WrV.js → mail-vwCEHyhQ.js} +0 -0
  233. /package/dist/ui/assets/{pause-C2l5G2Py.js → pause-Cm9LzIZK.js} +0 -0
  234. /package/dist/ui/assets/{play-CMAscR3a.js → play-zqogwA2l.js} +0 -0
  235. /package/dist/ui/assets/{plus-DzvRxH4U.js → plus-Bm08ABhc.js} +0 -0
  236. /package/dist/ui/assets/{radio-DfGzov4y.js → radio-Cii1BjMt.js} +0 -0
  237. /package/dist/ui/assets/{refresh-cw-DZXu5FrG.js → refresh-cw-DXv3XgEt.js} +0 -0
  238. /package/dist/ui/assets/{search-ykSx-zZU.js → search-BMwCI-pX.js} +0 -0
  239. /package/dist/ui/assets/{send-DAhlz2i9.js → send-D6fgWV7m.js} +0 -0
  240. /package/dist/ui/assets/{settings-DL0REysC.js → settings-qV3kVkeG.js} +0 -0
  241. /package/dist/ui/assets/{shield-BPZZhjCT.js → shield-CIarwBvx.js} +0 -0
  242. /package/dist/ui/assets/{sparkles-BViXTAh7.js → sparkles-DVvY6jDT.js} +0 -0
  243. /package/dist/ui/assets/{terminal-CzxPKG-h.js → terminal-BEcTK780.js} +0 -0
  244. /package/dist/ui/assets/{trash-2-SgYCWiVk.js → trash-2-D6oziYAK.js} +0 -0
  245. /package/dist/ui/assets/{utils-SGUggNJc.js → utils-DEmd_M8c.js} +0 -0
  246. /package/dist/ui/assets/{vendor-router-Dsg8fxNQ.js → vendor-router-DP84b3LQ.js} +0 -0
  247. /package/dist/ui/assets/{wifi-CyPHteEm.js → wifi-BUJuOcgP.js} +0 -0
  248. /package/dist/ui/assets/{zap-OVVrfEHr.js → zap-DSoX9NDk.js} +0 -0
@@ -0,0 +1,293 @@
1
+ import type { LLMMessage, LLMToolDef } from "./llm-client"
2
+ import type { SkillDescriptor } from "./skill-selector"
3
+ import type { ContextTool } from "./context-compiler"
4
+ import type { PlaybookRule } from "./playbook-selector"
5
+ import { MINIMAL_TOOLS } from "./minimal-loadout"
6
+ import { searchCapabilities } from "./capability-search"
7
+ import { mcpToolFullName } from "./tool-selector"
8
+ import { askJev, getJevKey, type JevAnswer, type JevQuestion } from "./jev-decisions"
9
+ import { col } from "../storage/hive"
10
+ import type { AgentDoc, McpServerDoc, McpToolDoc } from "../storage/collections"
11
+
12
+ export interface JevDecisionMetrics {
13
+ latencyMs: number
14
+ costUsd: number
15
+ }
16
+
17
+ /** "activo": connected now; "disponible": enabled, connects on first use; "apagado": disabled. */
18
+ export type JevMcpState = "activo" | "disponible" | "apagado"
19
+
20
+ export interface JevMcpServer {
21
+ id: string
22
+ name: string
23
+ state: JevMcpState
24
+ tools: number
25
+ }
26
+
27
+ export interface JevSpecialist {
28
+ id: string
29
+ name: string
30
+ description: string
31
+ tools: string[]
32
+ mcp: Array<{ name: string; state: JevMcpState }>
33
+ }
34
+
35
+ /**
36
+ * What the swarm can do right now: every enabled worker (catalog and
37
+ * agent_create alike) with its tools, and every MCP server with its state.
38
+ * Jev routes and selects over this, so it never recommends a specialist whose
39
+ * MCP is off or proposes a tool that is not connected.
40
+ */
41
+ export async function describeSwarmCapabilities(
42
+ mcpManager: { getServerTools(key: string): unknown[] | undefined } | null,
43
+ opts: { includeSpecialists: boolean },
44
+ ): Promise<{ mcpServers: JevMcpServer[]; specialists: JevSpecialist[] }> {
45
+ const servers = (await (await col<McpServerDoc>("mcpServers")).scan({})).map(e => e.doc)
46
+ const mcpServers: JevMcpServer[] = servers.map(server => {
47
+ const tools = mcpManager?.getServerTools(server.id)?.length || mcpManager?.getServerTools(server.name)?.length || 0
48
+ return { id: server.id, name: server.name, tools, state: !server.enabled ? "apagado" : tools > 0 ? "activo" : "disponible" }
49
+ })
50
+ if (!opts.includeSpecialists) return { mcpServers, specialists: [] }
51
+
52
+ const byId = new Map(mcpServers.map(s => [s.id, s]))
53
+ const parse = (json: string | null | undefined): string[] => {
54
+ try { return json ? (JSON.parse(json) as unknown[]).map(String) : [] } catch { return [] }
55
+ }
56
+ const specialists = (await (await col<AgentDoc>("agents")).scan({}))
57
+ .map(e => e.doc)
58
+ .filter(a => a.role === "worker" && a.enabled && a.status !== "archived")
59
+ .map(a => ({
60
+ id: a.id,
61
+ name: a.name,
62
+ description: (a.description ?? a.name).slice(0, 200),
63
+ tools: parse(a.tool_allowlist_json).slice(0, 12),
64
+ mcp: parse(a.mcp_server_ids_json).map(id => byId.get(id)).filter((s): s is JevMcpServer => !!s)
65
+ .map(s => ({ name: s.name, state: s.state })),
66
+ }))
67
+ return { mcpServers, specialists }
68
+ }
69
+
70
+ /** One roster line: what the coordinator needs to pick a specialist without calling agent_find. */
71
+ export function renderSpecialistLine(s: JevSpecialist): string {
72
+ const mcp = s.mcp.length ? ` · MCP: ${s.mcp.map(m => `${m.name} (${m.state})`).join(", ")}` : ""
73
+ return `- ${s.id} (${s.name})${mcp}`
74
+ }
75
+
76
+ export interface JevContextPlan {
77
+ messages: LLMMessage[]
78
+ tools: LLMToolDef[]
79
+ skills: SkillDescriptor[]
80
+ agentId: string | null
81
+ /**
82
+ * MCP servers the recommended specialist depends on that are off. Non-empty
83
+ * means "this is the right specialist, but the user must turn these on
84
+ * first" — delegating now would hand it a task it cannot do.
85
+ */
86
+ agentMcpOff: string[]
87
+ selectedMessageIds: number[]
88
+ selectedToolNames: string[]
89
+ selectedSkillNames: string[]
90
+ selectedScratchpadKeys: string[]
91
+ selectedPlaybookIds: string[]
92
+ decision: JevDecisionMetrics
93
+ }
94
+
95
+ const excerpt = (value: unknown, max = 450): string =>
96
+ (typeof value === "string" ? value : JSON.stringify(value) ?? "").slice(0, max)
97
+ const probability = (answer: JevAnswer | undefined): number | null => answer?.type === "noul" ? answer.noul : null
98
+ const MANDATORY_TAIL = 4
99
+ /** Below this many characters of prunable tool output, a decision costs more latency than it saves. */
100
+ const MIN_PRUNABLE_CHARS = 4000
101
+
102
+ /** Decisions select only from already authorized, discoverable candidates. */
103
+ export async function planJevContext(input: {
104
+ objective: string
105
+ messages: LLMMessage[]
106
+ tools: LLMToolDef[]
107
+ allTools: ContextTool[]
108
+ skills: SkillDescriptor[]
109
+ scratchpadNotes?: Array<{ key: string; value: string }>
110
+ playbookRules?: PlaybookRule[]
111
+ isWorker: boolean
112
+ /** From describeSwarmCapabilities; absent means "unknown", not "none". */
113
+ swarm?: { mcpServers: JevMcpServer[]; specialists: JevSpecialist[] }
114
+ }): Promise<JevContextPlan | null> {
115
+ if (!await getJevKey().catch(() => null)) return null
116
+ const { objective, messages, tools, allTools, skills, isWorker } = input
117
+ const mandatoryMessages = new Set<number>()
118
+ // The last two exchanges carry the thread's immediate referents ("hazlo otra
119
+ // vez", "el anterior"); dropping them sent the model into conversation_read loops.
120
+ for (let i = Math.max(0, messages.length - MANDATORY_TAIL); i < messages.length; i++) mandatoryMessages.add(i)
121
+ messages.forEach((message, i) => {
122
+ if (Array.isArray(message.content) || (typeof message.content === "string" && message.content.startsWith("<hive:internal_event"))) mandatoryMessages.add(i)
123
+ })
124
+
125
+ const candidateMessageIds = messages.map((_, i) => i).filter(i => !mandatoryMessages.has(i))
126
+ let candidateTools: ContextTool[] = tools.filter(t => !MINIMAL_TOOLS.has(t.function.name))
127
+ .map(t => allTools.find(a => a.name === t.function.name))
128
+ .filter((t): t is ContextTool => !!t)
129
+ try {
130
+ const hits = await searchCapabilities(objective, { types: ["tool", "mcp"], k: 12 })
131
+ // allTools only holds MCP tools of servers that are enabled, connected and
132
+ // allowed for this agent — resolving through it is what keeps a dormant or
133
+ // foreign server's tools out of the plan.
134
+ const available = new Map(allTools.map(t => [t.name, t]))
135
+ const mcpTools = await col<McpToolDoc>("mcpTools")
136
+ const names = await Promise.all(hits.map(async h => {
137
+ if (h.type !== "mcp") return h.rawId
138
+ const tool = (await mcpTools.get(h.rawId))?.doc
139
+ return tool ? mcpToolFullName(tool.server_name, tool.tool_name) : null
140
+ }))
141
+ const discovered = names.map(n => n ? available.get(n) : undefined).filter((t): t is ContextTool => !!t && !MINIMAL_TOOLS.has(t.name))
142
+ candidateTools = [...new Map([...candidateTools, ...discovered].map(t => [t.name, t])).values()].slice(0, 24)
143
+ } catch { /* index unavailable: retain the current loadout */ }
144
+
145
+ const optionalSkills = skills.filter(s => s.active && s.body).slice(0, 8)
146
+ const scratchpadNotes = (input.scratchpadNotes ?? []).slice(-16)
147
+ const playbookRules = (input.playbookRules ?? []).slice(0, 8)
148
+ // Specialists with an MCP off stay eligible: Jev still names the right one,
149
+ // and the coordinator asks the user to turn the server on instead of
150
+ // delegating a task the specialist cannot do yet.
151
+ const agents = isWorker ? [] : (input.swarm?.specialists ?? []).slice(0, 16)
152
+ const questions: Record<string, JevQuestion> = {}
153
+ for (const i of candidateMessageIds) questions[`history_${i}`] = { type: "noul", instructions: `Is earlier conversation item ${i} necessary to complete the current objective?` }
154
+ for (const tool of candidateTools) questions[`tool_${tool.name}`] = { type: "noul", instructions: `Will tool ${tool.name} likely be needed for the current objective?` }
155
+ for (const skill of optionalSkills) questions[`skill_${skill.id}`] = { type: "noul", instructions: `Are instructions from skill ${skill.name} needed for the current objective?` }
156
+ for (const note of scratchpadNotes) questions[`note_${note.key}`] = { type: "noul", instructions: `Is scratchpad note ${note.key} needed for the current objective?` }
157
+ for (const rule of playbookRules) questions[`rule_${rule.id}`] = { type: "noul", instructions: `Does playbook rule ${rule.id} apply to the current objective?` }
158
+ if (agents.length) questions.agent = {
159
+ type: "choice", instructions: "Which existing specialist should handle a bounded part of this objective, or should the coordinator handle it?",
160
+ criteria: {
161
+ coordinator: "No bounded specialist task is needed",
162
+ ...Object.fromEntries(agents.map(a => [a.id, [
163
+ a.description,
164
+ a.tools.length ? `tools: ${a.tools.join(", ")}` : "",
165
+ a.mcp.length ? `MCP: ${a.mcp.map(m => `${m.name} (${m.state})`).join(", ")}` : "",
166
+ ].filter(Boolean).join(" · ").slice(0, 400)])),
167
+ },
168
+ }
169
+ const decision = await askJev({
170
+ objective: objective.slice(0, 3500),
171
+ history: candidateMessageIds.map(i => ({ id: i, role: messages[i].role, content: excerpt(messages[i].content) })),
172
+ tools: candidateTools.map(t => ({ name: t.name, description: t.description.slice(0, 240) })),
173
+ skills: optionalSkills.map(s => ({ id: s.id, name: s.name, description: s.description.slice(0, 240) })),
174
+ notes: scratchpadNotes.map(n => ({ key: n.key, value: n.value.slice(0, 350) })),
175
+ rules: playbookRules.map(r => ({ id: r.id, rule: r.rule.slice(0, 350) })),
176
+ mcp_servers: (input.swarm?.mcpServers ?? []).map(s => ({ name: s.name, state: s.state, tools: s.tools })),
177
+ }, questions)
178
+ if (!decision) return null
179
+
180
+ const selected = new Set(messages.map((_, i) => i).filter(i => mandatoryMessages.has(i) ||
181
+ !candidateMessageIds.includes(i) || (probability(decision.answers[`history_${i}`]) ?? 1) >= 0.35))
182
+ // A reply travels with the user turn it answered: Gemini silently drops a
183
+ // model turn that has no preceding user turn.
184
+ for (const i of [...selected]) {
185
+ if (messages[i].role !== "assistant") continue
186
+ for (let j = i - 1; j >= 0; j--) if (messages[j].role === "user") { selected.add(j); break }
187
+ }
188
+ const selectedMessageIds = [...selected].sort((a, b) => a - b)
189
+ const selectedToolNames = candidateTools.filter(t => (probability(decision.answers[`tool_${t.name}`]) ?? 1) >= 0.35).map(t => t.name)
190
+ const selectedSkills = optionalSkills.filter(s => (probability(decision.answers[`skill_${s.id}`]) ?? 1) >= 0.35)
191
+ const toolMap = new Map(allTools.map(t => [t.name, t]))
192
+ const selectedNames = new Set(selectedToolNames)
193
+ const candidateNames = new Set(candidateTools.map(t => t.name))
194
+ const combinedTools = tools.filter(t => !candidateNames.has(t.function.name) || selectedNames.has(t.function.name))
195
+ for (const name of selectedToolNames) {
196
+ const tool = toolMap.get(name)
197
+ if (tool && !combinedTools.some(t => t.function.name === name)) combinedTools.push({
198
+ type: "function", function: { name: tool.name, description: tool.description, parameters: tool.parameters },
199
+ })
200
+ }
201
+ const agentAnswer = decision.answers.agent
202
+ const agentId = agentAnswer?.type === "choice" && agentAnswer.confidence >= 0.7 && agentAnswer.choice !== "coordinator"
203
+ ? agentAnswer.choice : null
204
+ const agentMcpOff = agents.find(a => a.id === agentId)?.mcp.filter(m => m.state === "apagado").map(m => m.name) ?? []
205
+ return {
206
+ messages: selectedMessageIds.map(i => messages[i]), tools: combinedTools,
207
+ skills: selectedSkills, agentId, agentMcpOff, selectedMessageIds, selectedToolNames,
208
+ selectedSkillNames: selectedSkills.map(s => s.name),
209
+ selectedScratchpadKeys: scratchpadNotes.filter(n => (probability(decision.answers[`note_${n.key}`]) ?? 1) >= 0.35).map(n => n.key),
210
+ selectedPlaybookIds: playbookRules.filter(r => (probability(decision.answers[`rule_${r.id}`]) ?? 1) >= 0.35).map(r => r.id),
211
+ decision: { latencyMs: decision.latencyMs, costUsd: decision.costUsd },
212
+ }
213
+ }
214
+
215
+ /**
216
+ * Only independent reads, or separate delegated tasks, may execute concurrently.
217
+ * null leaves the batch to the runtime default; `decision` is present only when Jev was asked.
218
+ */
219
+ export async function jevWantsParallel(calls: Array<{ function: { name: string; arguments: unknown } }>): Promise<{ parallel: boolean; decision?: JevDecisionMetrics } | null> {
220
+ if (calls.length < 2) return null
221
+ if (!await getJevKey().catch(() => null)) return null
222
+ const names = calls.map(c => c.function.name)
223
+ const readOnly = names.every(n => /^(fs_read|fs_list|fs_glob|fs_exists|web_search|web_fetch|memory_read|memory_search|artifact_read|artifact_inspect|task_status|agent_find)$/.test(n))
224
+ const delegated = names.every(n => n === "task_delegate")
225
+ if (!readOnly && !delegated) return { parallel: false }
226
+ if (delegated) {
227
+ const ids = calls.map(call => {
228
+ try {
229
+ const args = typeof call.function.arguments === "string" ? JSON.parse(call.function.arguments) : call.function.arguments
230
+ return String(args?.worker_id ?? "")
231
+ } catch { return "" }
232
+ })
233
+ if (ids.some(id => !id) || new Set(ids).size !== ids.length) return { parallel: false }
234
+ const agentsCol = await col<AgentDoc>("agents")
235
+ const agents = await Promise.all(ids.map(id => agentsCol.get(id)))
236
+ const workspaces = agents.map(row => row?.doc.workspace)
237
+ if (workspaces.some(path => !path) || new Set(workspaces).size !== workspaces.length) return { parallel: false }
238
+ }
239
+ const result = await askJev({ calls: calls.map(c => ({ tool: c.function.name, arguments: excerpt(c.function.arguments, 700) })) }, {
240
+ independent: { type: "noul", instructions: "Can every listed operation run concurrently without needing the result of another listed operation?" },
241
+ })
242
+ const answer = result?.answers.independent
243
+ return result && answer?.type === "noul"
244
+ ? { parallel: answer.noul >= 0.8, decision: { latencyMs: result.latencyMs, costUsd: result.costUsd } }
245
+ : null
246
+ }
247
+
248
+ export async function planJevIteration(input: {
249
+ objective: string
250
+ messages: LLMMessage[]
251
+ tools: LLMToolDef[]
252
+ }): Promise<{ messages: LLMMessage[]; tools: LLMToolDef[]; action: string; omittedResults: number; decision: JevDecisionMetrics } | null> {
253
+ const toolIndices = input.messages.map((m, i) => m.role === "tool" ? i : -1).filter(i => i >= 0)
254
+ if (!toolIndices.length) return null
255
+ const older = toolIndices.slice(0, -1).slice(-8)
256
+ const prunableChars = older.reduce((sum, i) => sum + excerpt(input.messages[i].content, Infinity).length, 0)
257
+ if (prunableChars < MIN_PRUNABLE_CHARS) return null
258
+ const questions: Record<string, JevQuestion> = {
259
+ action: {
260
+ type: "choice",
261
+ instructions: "What capability should the text model use next to complete the current objective?",
262
+ criteria: {
263
+ continue: "Continue reasoning with currently available tools",
264
+ delegate: "Formulate a bounded task for an existing specialist",
265
+ discover: "Discover another tool or skill before continuing",
266
+ finish: "The evidence is sufficient to compose the final answer without more tools",
267
+ },
268
+ },
269
+ }
270
+ for (const i of older) questions[`result_${i}`] = {
271
+ type: "noul", instructions: `Is result ${i} still needed to complete the current objective?`,
272
+ }
273
+ const result = await askJev({
274
+ objective: input.objective.slice(0, 2800),
275
+ results: toolIndices.slice(-9).map(i => ({ id: i, tool: input.messages[i].name, content: excerpt(input.messages[i].content, 650) })),
276
+ }, questions)
277
+ if (!result) return null
278
+ const omitted = new Set(older.filter(i => (probability(result.answers[`result_${i}`]) ?? 1) < 0.35))
279
+ const projected = input.messages.map((m, i) => omitted.has(i)
280
+ ? { ...m, content: "[Previous tool result omitted from this call]" } : m)
281
+ const answer = result.answers.action
282
+ const latestResult = input.messages[toolIndices[toolIndices.length - 1]]
283
+ const resultFailed = typeof latestResult.content === "string" && (latestResult.content.startsWith("[Tool Error]") || latestResult.content.includes('"error":true'))
284
+ const proposedAction = answer?.type === "choice" && answer.confidence >= (answer.choice === "finish" ? 0.85 : 0.7) ? answer.choice : "continue"
285
+ const action = proposedAction === "finish" && resultFailed ? "continue" : proposedAction
286
+ let tools = input.tools
287
+ if (action === "finish") tools = []
288
+ else if (action === "delegate") tools = tools.filter(t => ["task_delegate", "agent_find", "search_knowledge"].includes(t.function.name))
289
+ else if (action === "discover") tools = tools.filter(t => t.function.name === "search_knowledge")
290
+ const decision = { latencyMs: result.latencyMs, costUsd: result.costUsd }
291
+ if (action !== "finish" && tools.length === 0) return { messages: projected, tools: input.tools, action: "continue", omittedResults: omitted.size, decision }
292
+ return { messages: projected, tools, action, omittedResults: omitted.size, decision }
293
+ }
@@ -16,7 +16,7 @@ import { loadConfig } from "../config/loader"
16
16
  import { withRetry, isRetryableError, type RetryPolicy } from "../resilience/retry"
17
17
  import { GeminiProvider } from "./llm-providers/gemini"
18
18
  import { AnthropicProvider } from "./llm-providers/anthropic"
19
- import { OllamaProvider } from "./llm-providers/ollama"
19
+ import { OllamaProvider, ollamaDefaultNumCtx } from "./llm-providers/ollama"
20
20
  import { OpenAIProvider } from "./llm-providers/openai"
21
21
  import { GroqProvider } from "./llm-providers/groq"
22
22
  import { MistralProvider } from "./llm-providers/mistral"
@@ -97,6 +97,13 @@ export interface LLMCallOptions {
97
97
  signal?: AbortSignal
98
98
  /** Enable extended thinking for supported models (Anthropic Claude 3.7+). */
99
99
  thinking?: { enabled: boolean; budget_tokens?: number }
100
+ /**
101
+ * Stable id of the conversation this call belongs to (the agent loop's
102
+ * threadId). Providers that route or cache per session derive their own
103
+ * header from it — OpenCode Go's `x-opencode-session` — and never send it
104
+ * verbatim, since it carries user, channel and peer ids.
105
+ */
106
+ sessionId?: string
100
107
  }
101
108
 
102
109
  export interface LLMResponse {
@@ -214,19 +221,27 @@ export function describeProviderFailure(
214
221
  provider: string,
215
222
  cleanModel: string,
216
223
  ): string {
224
+ // NVIDIA usa 404 también para modelos que siguen en su catálogo público pero
225
+ // no están habilitados para esa key ("Function '…': Not found for account
226
+ // '…'"). Decir que "se retiró" mandaba a buscar un modelo que sí existe.
227
+ if (status === 404 && /not found for account/i.test((err as Error)?.message ?? "")) {
228
+ return `Tu cuenta de ${provider} no tiene habilitado el modelo "${cleanModel}" (HTTP 404): `
229
+ + `figura en su catálogo, pero no está disponible para esta API key. `
230
+ + `Elige otro modelo en Ajustes → Proveedores.`
231
+ }
217
232
  if (status === 404 || status === 410) {
218
233
  return `El modelo "${cleanModel}" ya no existe en ${provider} (HTTP ${status}). `
219
234
  + `El proveedor lo retiró de su catálogo; reintentar no sirve. `
220
- + `Elegí otro modelo en Ajustes → Proveedores.`
235
+ + `Elige otro modelo en Ajustes → Proveedores.`
221
236
  }
222
237
  if (status === 429) {
223
238
  return `${provider} está limitando las peticiones (HTTP 429) y los reintentos tampoco pasaron. `
224
- + `Es el límite de uso de tu cuenta, no un problema del modelo: esperá unos minutos, `
225
- + `revisá tu cuota con el proveedor, o cambiá de modelo en Ajustes → Proveedores.`
239
+ + `Es el límite de uso de tu cuenta, no un problema del modelo: espera unos minutos, `
240
+ + `revisa tu cuota con el proveedor, o cambia de modelo en Ajustes → Proveedores.`
226
241
  }
227
242
  if (status === 401 || status === 403) {
228
243
  return `${provider} rechazó la API key (HTTP ${status}). `
229
- + `Revisá que siga siendo válida y tenga acceso a "${cleanModel}" en Ajustes → Proveedores.`
244
+ + `Revisa que siga siendo válida y tenga acceso a "${cleanModel}" en Ajustes → Proveedores.`
230
245
  }
231
246
  return (err as Error).message
232
247
  }
@@ -289,13 +304,20 @@ export async function resolveProviderConfig(
289
304
  apiKey = process.env[`${providerId.toUpperCase()}_API_KEY`] || ""
290
305
  }
291
306
 
307
+ // The window the model will actually see. Ollama truncates at num_ctx
308
+ // without an error, so budgeting with the model's nominal window made the
309
+ // compiler build ~22k-token prompts that arrived cut to 4k.
310
+ const modelWindow = modelEntry?.doc.context_window || undefined
311
+ const numCtx = providerRow?.num_ctx ?? (providerId === "ollama" ? ollamaDefaultNumCtx(modelWindow) : undefined)
312
+ const contextWindow = modelWindow && numCtx ? Math.min(modelWindow, numCtx) : modelWindow ?? numCtx
313
+
292
314
  return {
293
315
  provider: providerId,
294
316
  model: modelId,
295
317
  apiKey,
296
318
  baseUrl: providerRow?.base_url || undefined,
297
- numCtx: providerRow?.num_ctx ?? undefined,
319
+ numCtx,
298
320
  numGpu: providerRow?.num_gpu ?? undefined,
299
- contextWindow: modelEntry?.doc.context_window ?? undefined,
321
+ contextWindow,
300
322
  }
301
323
  }
@@ -3,6 +3,20 @@ import { sanitizeMessages, resolveMaxTokens, ensureArrayItems } from "./interfac
3
3
  import type { LLMCallOptions, LLMProvider, LLMResponse, LLMToolCall } from "./interface"
4
4
  import type { ContentPart, LLMMessage } from "../llm-client"
5
5
 
6
+ /**
7
+ * Ollama reads only `num_ctx` tokens of a prompt and silently drops the rest,
8
+ * so this is the window Hive must budget for, not the model's nominal one.
9
+ * 4096 used to be the default and did not even fit the coordinator's base
10
+ * prompt (~6k tokens of instructions and tools); 16k fits a real turn while
11
+ * staying far below what exhausts RAM on 4B–8B models. providers.num_ctx
12
+ * overrides it.
13
+ */
14
+ export const OLLAMA_DEFAULT_NUM_CTX = 16384
15
+
16
+ export function ollamaDefaultNumCtx(modelContextWindow?: number): number {
17
+ return modelContextWindow ? Math.min(modelContextWindow, OLLAMA_DEFAULT_NUM_CTX) : OLLAMA_DEFAULT_NUM_CTX
18
+ }
19
+
6
20
  const log = logger.child("llm-client")
7
21
 
8
22
  // Local models known to support Ollama's `think` request flag (returns
@@ -90,11 +104,10 @@ export class OllamaProvider implements LLMProvider {
90
104
  },
91
105
  }))
92
106
 
93
- // Default num_ctx to 4096 for local models — prevents OOM on small models (2B-7B)
94
- // when Ollama's default (32k+) is too large for available RAM/VRAM.
95
- // Users can override via providers.num_ctx in DB.
107
+ // resolveProviderConfig already sends the window the context was budgeted
108
+ // for; the fallback only covers callers that build options by hand.
96
109
  const runtimeOptions: Record<string, unknown> = {
97
- num_ctx: options.numCtx ?? 4096,
110
+ num_ctx: options.numCtx ?? ollamaDefaultNumCtx(options.contextWindow),
98
111
  }
99
112
  if (options.numGpu !== undefined) runtimeOptions.num_gpu = options.numGpu
100
113
  if (options.temperature !== undefined) runtimeOptions.temperature = options.temperature
@@ -78,8 +78,8 @@ export abstract class OpenAICompatBase implements LLMProvider {
78
78
  /** Override to true for providers running on localhost. */
79
79
  protected isLocalProvider(): boolean { return false }
80
80
 
81
- /** Override to customize the OpenAI client (e.g. strip unwanted headers, add custom fetch). */
82
- protected async resolveOpenAIClient(apiKey: string, baseURL: string | undefined): Promise<any> {
81
+ /** Override to customize the OpenAI client (e.g. strip unwanted headers, add custom fetch, per-call headers). */
82
+ protected async resolveOpenAIClient(apiKey: string, baseURL: string | undefined, _options?: LLMCallOptions): Promise<any> {
83
83
  const { default: OpenAI } = await import("openai")
84
84
  return new OpenAI({ apiKey, baseURL })
85
85
  }
@@ -131,7 +131,7 @@ export abstract class OpenAICompatBase implements LLMProvider {
131
131
  throw new Error(`API key missing for provider: ${this.providerName}. Configure it in Settings → Providers.`)
132
132
  }
133
133
 
134
- const client = await this.resolveOpenAIClient(apiKey, baseURL)
134
+ const client = await this.resolveOpenAIClient(apiKey, baseURL, options)
135
135
 
136
136
  const sanitized = sanitizeMessages(options.messages)
137
137
  const rawMessages = this.needsReasoningRoundtrip()
@@ -268,9 +268,23 @@ export abstract class OpenAICompatBase implements LLMProvider {
268
268
  sendTools: boolean,
269
269
  profile: ReturnType<typeof getProviderProfile>,
270
270
  ): Promise<LLMResponse> {
271
+ // Without stream_options.include_usage an OpenAI-compatible stream reports
272
+ // no tokens at all: every NVIDIA call was recorded as 0 in / 0 out, so its
273
+ // cost and Jev's savings on it never reached the dashboard. A server that
274
+ // does not know the field gets the same request without it.
275
+ const createStream = async (request: any) => {
276
+ try {
277
+ return await client.chat.completions.create({ ...request, stream: true, stream_options: { include_usage: true } }, { signal: options.signal })
278
+ } catch (err: any) {
279
+ const message = String(err?.error?.message ?? err?.message ?? "").toLowerCase()
280
+ if (!message.includes("stream_options") && !message.includes("include_usage")) throw err
281
+ return await client.chat.completions.create({ ...request, stream: true }, { signal: options.signal })
282
+ }
283
+ }
284
+
271
285
  let stream
272
286
  try {
273
- stream = await client.chat.completions.create({ ...this.modifyRequestBody(body, options), stream: true }, { signal: options.signal })
287
+ stream = await createStream(this.modifyRequestBody(body, options))
274
288
  } catch (err: any) {
275
289
  const status = err?.status ?? err?.response?.status
276
290
  const errMsg = (err?.error?.message ?? err?.message ?? "").toLowerCase()
@@ -280,17 +294,17 @@ export abstract class OpenAICompatBase implements LLMProvider {
280
294
  const originalCount = body.messages.length
281
295
  compactBodyForContextOverflow(body, err)
282
296
  log.info(`[llm-client] ${this.providerName}: compacted ${originalCount} msgs → ${body.messages.length} msgs, max_tokens=${body.max_tokens}`)
283
- stream = await client.chat.completions.create({ ...this.modifyRequestBody(body, options), stream: true }, { signal: options.signal })
297
+ stream = await createStream(this.modifyRequestBody(body, options))
284
298
  } else if (sendTools && profile.retryWithoutToolsOnCodes.includes(status)) {
285
299
  log.warn(`[llm-client] ${this.providerName}: tools rejected (HTTP ${status}) — retrying stream without tools`)
286
300
  const bodyNoTools = { ...body }
287
301
  delete bodyNoTools.tools
288
302
  delete bodyNoTools.tool_choice
289
303
  delete bodyNoTools.parallel_tool_calls
290
- stream = await client.chat.completions.create({ ...stripProviderExtras(this.modifyRequestBody(bodyNoTools, options)), stream: true }, { signal: options.signal })
304
+ stream = await createStream(stripProviderExtras(this.modifyRequestBody(bodyNoTools, options)))
291
305
  } else if (EXTRAS_REJECTED_CODES.includes(status) && this.modifyRequestBody(body, options).chat_template_kwargs) {
292
306
  log.warn(`[llm-client] ${this.providerName}: request rejected (HTTP ${status}) — retrying stream without chat_template_kwargs`)
293
- stream = await client.chat.completions.create({ ...stripProviderExtras(this.modifyRequestBody(body, options)), stream: true }, { signal: options.signal })
307
+ stream = await createStream(stripProviderExtras(this.modifyRequestBody(body, options)))
294
308
  } else {
295
309
  throw err
296
310
  }
@@ -304,6 +318,12 @@ export abstract class OpenAICompatBase implements LLMProvider {
304
318
  let output_tokens = 0
305
319
 
306
320
  for await (const chunk of stream) {
321
+ // Usage arrives in its own final chunk with an empty `choices`: read it
322
+ // before skipping choice-less chunks, or it is dropped even when sent.
323
+ if (chunk.usage) {
324
+ input_tokens = chunk.usage.prompt_tokens ?? input_tokens
325
+ output_tokens = chunk.usage.completion_tokens ?? output_tokens
326
+ }
307
327
  const choice = chunk.choices?.[0]
308
328
  if (!choice) continue
309
329
 
@@ -329,11 +349,6 @@ export abstract class OpenAICompatBase implements LLMProvider {
329
349
  }
330
350
  }
331
351
  if (choice.finish_reason) finish_reason = choice.finish_reason
332
-
333
- if (chunk.usage) {
334
- input_tokens = chunk.usage.prompt_tokens ?? 0
335
- output_tokens = chunk.usage.completion_tokens ?? 0
336
- }
337
352
  }
338
353
 
339
354
  const tool_calls: LLMToolCall[] = [...toolCallMap.values()].map((tc) => ({
@@ -1,4 +1,29 @@
1
+ import { createHash, randomUUID } from "node:crypto"
2
+ import pkg from "../../../../../package.json"
1
3
  import { OpenAICompatBase } from "./openai-compat-base"
4
+ import type { LLMCallOptions } from "../llm-client"
5
+
6
+ /**
7
+ * OpenCode Go rechaza con 400 `MissingSessionID` toda petición sin
8
+ * `x-opencode-session` (verificado 2026-09-10 con una key real: sin el header
9
+ * 400, con él 200). Su documentación pide además que el cliente se identifique
10
+ * con su propio User-Agent en vez del genérico del SDK:
11
+ * https://opencode.ai/docs/go/#where-can-i-use-it
12
+ */
13
+ const USER_AGENT = `hive/${pkg.version}`
14
+
15
+ /** Sesión de respaldo para llamadas sin conversación (compactación, metas). */
16
+ const PROCESS_SESSION = randomUUID()
17
+
18
+ /**
19
+ * La sesión tiene que ser estable por conversación —OpenCode la usa para rutear
20
+ * y cachear el prompt—, pero el threadId lleva usuario, canal y contacto: a
21
+ * OpenCode sólo le llega un hash.
22
+ */
23
+ function sessionHeader(sessionId: string | undefined): string {
24
+ if (!sessionId) return PROCESS_SESSION
25
+ return createHash("sha256").update(`hive:${sessionId}`).digest("hex").slice(0, 32)
26
+ }
2
27
 
3
28
  export class OpenCodeGoProvider extends OpenAICompatBase {
4
29
  static readonly secretKey = "OPENCODE_GO_API_KEY"
@@ -6,4 +31,16 @@ export class OpenCodeGoProvider extends OpenAICompatBase {
6
31
  constructor() {
7
32
  super("opencode-go")
8
33
  }
34
+
35
+ protected async resolveOpenAIClient(apiKey: string, baseURL: string | undefined, options?: LLMCallOptions): Promise<any> {
36
+ const { default: OpenAI } = await import("openai")
37
+ return new OpenAI({
38
+ apiKey,
39
+ baseURL,
40
+ defaultHeaders: {
41
+ "x-opencode-session": sessionHeader(options?.sessionId),
42
+ "User-Agent": USER_AGENT,
43
+ },
44
+ })
45
+ }
9
46
  }
@@ -136,7 +136,7 @@ export async function buildSystemPrompt(opts: BuildSystemPromptOpts): Promise<st
136
136
  if (Object.keys(userData).length > 0) {
137
137
  userSection += formatContext(userData) + "\n\n"
138
138
  if (agent.role === "coordinator" && user.email) {
139
- userSection += `Cuando el usuario diga "envíame", "mándame" o "a mi correo" sin indicar otro destinatario, usá CorreoPropio. Para terceras personas, resolvé su dirección por separado.\n\n`
139
+ userSection += `Cuando el usuario diga "envíame", "mándame" o "a mi correo" sin indicar otro destinatario, usa CorreoPropio. Para terceras personas, resuelve su dirección por separado.\n\n`
140
140
  }
141
141
  } else {
142
142
  userSection += `Usuario ID: ${userId}\n\n`