@johpaz/hive-agents 1.0.5 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (231) hide show
  1. package/README.md +17 -11
  2. package/dist/hive.js +87295 -101789
  3. package/dist/tool-worker.js +13241 -17001
  4. package/dist/ui/assets/A2UIPage-F1sUdZV7.js +8 -0
  5. package/dist/ui/assets/{AgentCreateForm-Bcp3HN8D.js → AgentCreateForm-CN5Gb9UN.js} +1 -1
  6. package/dist/ui/assets/AgentDetailPage-CzBnoKtH.js +1 -0
  7. package/dist/ui/assets/AgentNewPage-AGDjfAVf.js +1 -0
  8. package/dist/ui/assets/AgentsPage-BgKr7pAZ.js +10 -0
  9. package/dist/ui/assets/{ApiClientPage-DHfIlSAg.js → ApiClientPage-Dq4nPse4.js} +2 -2
  10. package/dist/ui/assets/ChannelsPage-BuWItmp-.js +8 -0
  11. package/dist/ui/assets/DashboardPage-CB1aM87o.js +6 -0
  12. package/dist/ui/assets/{LoginPage-BaX6cAPa.js → LoginPage-DBvwBCG6.js} +1 -1
  13. package/dist/ui/assets/LogsPage-Bc-oTBwY.js +1 -0
  14. package/dist/ui/assets/MeetingPage-C2H5SxaQ.js +1 -0
  15. package/dist/ui/assets/ModelSelector-D0aJvoD9.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-D5vwZkJa.js +727 -0
  19. package/dist/ui/assets/ProvidersPage-BBBt4Hcz.js +1 -0
  20. package/dist/ui/assets/{RecoverPage-C_Id9WM-.js → RecoverPage-nq901JiE.js} +1 -1
  21. package/dist/ui/assets/SettingsPage-DQ5KZPAd.js +9 -0
  22. package/dist/ui/assets/SetupPage-DeIGn-Uf.js +1 -0
  23. package/dist/ui/assets/{Vignette-Cyi27LQH.js → Vignette-BcPWkNhm.js} +17 -17
  24. package/dist/ui/assets/VoicePage-DJYsOsaU.js +307 -0
  25. package/dist/ui/assets/WebChatPage-CRDN4OlP.js +29 -0
  26. package/dist/ui/assets/agentCapabilities-PfTEVxG1.js +1 -0
  27. package/dist/ui/assets/alert-CjiX20jI.js +1 -0
  28. package/dist/ui/assets/badge-B5AKge1b.js +1 -0
  29. package/dist/ui/assets/card-mTJ4oZbL.js +1 -0
  30. package/dist/ui/assets/conversationsStore-BIs0iMhp.js +1 -0
  31. package/dist/ui/assets/dialog-DdbsUCv9.js +1 -0
  32. package/dist/ui/assets/dist-js-Dh18rcg9.js +1 -0
  33. package/dist/ui/assets/{dist-js-Bg0g3vPS.js → dist-js-q7C_AB0j.js} +1 -1
  34. package/dist/ui/assets/index-BD7hBA1d.css +2 -0
  35. package/dist/ui/assets/index-CpzwBwPg.js +116 -0
  36. package/dist/ui/assets/label-D_fvqJyD.js +1 -0
  37. package/dist/ui/assets/lock-3IApZyVy.js +1 -0
  38. package/dist/ui/assets/pencil-L3Li7_pz.js +1 -0
  39. package/dist/ui/assets/scroll-area-CbH8FOo8.js +1 -0
  40. package/dist/ui/assets/select-v_3QBYrD.js +1 -0
  41. package/dist/ui/assets/slider-DXS4h1LB.js +1 -0
  42. package/dist/ui/assets/switch-ndx8VCpm.js +1 -0
  43. package/dist/ui/assets/tabs-epu-3Tl4.js +1 -0
  44. package/dist/ui/assets/textarea-BgZJFZTX.js +1 -0
  45. package/dist/ui/assets/useAudioDevices-yU-wu-kt.js +41 -0
  46. package/dist/ui/assets/{useHiveAgentsModelLoad-CHmtvNp4.js → useHiveAgentsModelLoad-29pOYRd9.js} +1 -1
  47. package/dist/ui/assets/useOfficeModel-BaDn7U-X.js +1 -0
  48. package/dist/ui/assets/{useProviders-C7FA6z4M.js → useProviders-CiBi4Dt6.js} +1 -1
  49. package/dist/ui/assets/vendor-react-kUOwxn0g.js +1 -0
  50. package/dist/ui/index.html +6 -6
  51. package/package.json +10 -6
  52. package/packages/cli/src/adapters/config.ts +11 -3
  53. package/packages/cli/src/commands/causal.ts +1 -1
  54. package/packages/cli/src/commands/doctor.ts +2 -2
  55. package/packages/cli/src/commands/onboard.ts +1 -1
  56. package/packages/core/src/agent/acceptance-checks.ts +25 -0
  57. package/packages/core/src/agent/agent-catalog.ts +53 -33
  58. package/packages/core/src/agent/agent-loop.ts +67 -14
  59. package/packages/core/src/agent/capability-search.ts +2 -1
  60. package/packages/core/src/agent/compaction.ts +19 -7
  61. package/packages/core/src/agent/context-compiler.ts +165 -27
  62. package/packages/core/src/agent/conversation-store.ts +12 -1
  63. package/packages/core/src/agent/goal-runner.ts +2 -2
  64. package/packages/core/src/agent/jev-decisions.ts +242 -0
  65. package/packages/core/src/agent/jev-planner.ts +293 -0
  66. package/packages/core/src/agent/llm-client.ts +27 -5
  67. package/packages/core/src/agent/llm-providers/ollama.ts +17 -4
  68. package/packages/core/src/agent/llm-providers/openai-compat-base.ts +27 -12
  69. package/packages/core/src/agent/llm-providers/opencode-go.ts +37 -0
  70. package/packages/core/src/agent/realtime-providers/gemini-live.ts +5 -2
  71. package/packages/core/src/agent/skill-selector.ts +4 -2
  72. package/packages/core/src/agent/thread-id.ts +71 -0
  73. package/packages/core/src/agent/thread-store.ts +230 -0
  74. package/packages/core/src/agent/tool-selector.ts +42 -0
  75. package/packages/core/src/agent/tracer.ts +2 -0
  76. package/packages/core/src/canvas/canvas-manager.ts +17 -1
  77. package/packages/core/src/canvas/emitter.ts +24 -0
  78. package/packages/core/src/channels/telegram.ts +19 -1
  79. package/packages/core/src/channels/webchat.ts +47 -45
  80. package/packages/core/src/config/loader.ts +3 -2
  81. package/packages/core/src/gateway/channel-notify.ts +24 -5
  82. package/packages/core/src/gateway/delegation-groups.ts +3 -3
  83. package/packages/core/src/gateway/delegation-notify.ts +34 -5
  84. package/packages/core/src/gateway/durable-queue.ts +22 -0
  85. package/packages/core/src/gateway/failure-notify.ts +8 -2
  86. package/packages/core/src/gateway/job-executors.ts +3 -3
  87. package/packages/core/src/gateway/realtime/bridge-tools.ts +106 -28
  88. package/packages/core/src/gateway/realtime/index.ts +63 -7
  89. package/packages/core/src/gateway/realtime/prompt.ts +45 -0
  90. package/packages/core/src/gateway/realtime/voice-session.ts +1 -0
  91. package/packages/core/src/gateway/resolver.ts +31 -4
  92. package/packages/core/src/gateway/routes/artifacts.ts +13 -0
  93. package/packages/core/src/gateway/routes/chat.ts +20 -4
  94. package/packages/core/src/gateway/routes/conversations.ts +121 -0
  95. package/packages/core/src/gateway/routes/providers.ts +15 -0
  96. package/packages/core/src/gateway/routes/setup.ts +22 -11
  97. package/packages/core/src/gateway/routes/system.ts +4 -2
  98. package/packages/core/src/gateway/routes/tts-local.ts +2 -1
  99. package/packages/core/src/gateway/server.ts +85 -12
  100. package/packages/core/src/gateway/slash-commands.ts +46 -10
  101. package/packages/core/src/gateway/tts/src/server.ts +2 -1
  102. package/packages/core/src/gateway/webchat-turn.ts +68 -10
  103. package/packages/core/src/index.ts +2 -0
  104. package/packages/core/src/scheduler/CronScheduler.ts +20 -8
  105. package/packages/core/src/scheduler/cron/cron-engine.test.ts +295 -0
  106. package/packages/core/src/scheduler/cron/expression.ts +165 -0
  107. package/packages/core/src/scheduler/cron/index.ts +10 -0
  108. package/packages/core/src/scheduler/cron/job.ts +340 -0
  109. package/packages/core/src/scheduler/cron/next-run.ts +121 -0
  110. package/packages/core/src/scheduler/cron/zoned-time.ts +139 -0
  111. package/packages/core/src/scheduler/integration.ts +16 -5
  112. package/packages/core/src/scheduler/types.ts +3 -18
  113. package/packages/core/src/storage/bootstrap.ts +24 -1
  114. package/packages/core/src/storage/collections.ts +29 -1
  115. package/packages/core/src/storage/crypto.ts +133 -40
  116. package/packages/core/src/storage/reconcile.ts +6 -1
  117. package/packages/core/src/storage/seed.ts +101 -7
  118. package/packages/core/src/storage/usage.ts +53 -1
  119. package/packages/core/src/tool-runtime/index.ts +19 -1
  120. package/packages/core/src/tools/a2ui/index.ts +65 -1
  121. package/packages/core/src/tools/agents/get-available-models.ts +3 -1
  122. package/packages/core/src/tools/code-agent/adapters.ts +110 -0
  123. package/packages/core/src/tools/code-agent/index.ts +193 -0
  124. package/packages/core/src/tools/core/index.ts +39 -4
  125. package/packages/core/src/tools/cron/index.ts +4 -4
  126. package/packages/core/src/tools/index.ts +9 -1
  127. package/packages/core/src/tools/office/office-escribir-xlsx.ts +2 -1
  128. package/packages/core/src/tools/office/office-leer-xlsx.ts +2 -1
  129. package/packages/core/src/tools/office/xlsx-loader.ts +19 -0
  130. package/packages/core/src/tools/web/browser-backend.ts +22 -2
  131. package/packages/core/src/tools/web/index.ts +4 -0
  132. package/packages/core/src/tools/web/obscura.ts +860 -0
  133. package/packages/core/src/tools/web/webview-backend.ts +168 -26
  134. package/packages/core/src/utils/port.ts +33 -0
  135. package/packages/core/src/voice/index.ts +2 -1
  136. package/packages/mcp/src/config.ts +2 -1
  137. package/packages/mcp/src/manager.ts +9 -0
  138. package/packages/mcp/src/transports/index.ts +42 -1
  139. package/packages/mcp/src/transports/sse.ts +11 -5
  140. package/packages/skills/src/bundled/a2ui/a2ui_dashboard/SKILL.md +2 -2
  141. package/packages/skills/src/bundled/a2ui/a2ui_form/SKILL.md +2 -2
  142. package/packages/skills/src/bundled/a2ui/a2ui_interactive/SKILL.md +4 -4
  143. package/packages/skills/src/bundled/agents/agent_spawner/SKILL.md +7 -7
  144. package/packages/skills/src/bundled/agents/memory_manager/SKILL.md +9 -9
  145. package/packages/skills/src/bundled/agents/research_and_remember/SKILL.md +8 -8
  146. package/packages/skills/src/bundled/agents/task_orchestrator/SKILL.md +8 -8
  147. package/packages/skills/src/bundled/artifacts/artifact_reader/SKILL.md +104 -0
  148. package/packages/skills/src/bundled/cli/cli_pipeline/SKILL.md +6 -6
  149. package/packages/skills/src/bundled/cli/cli_safe_exec/SKILL.md +5 -5
  150. package/packages/skills/src/bundled/cli/external_code_agent/SKILL.md +69 -0
  151. package/packages/skills/src/bundled/cron_manager/SKILL.md +29 -19
  152. package/packages/skills/src/bundled/cron_reminder/SKILL.md +5 -5
  153. package/packages/skills/src/bundled/filesystem/file_manager/SKILL.md +4 -4
  154. package/packages/skills/src/bundled/filesystem/file_read_and_summarize/SKILL.md +7 -7
  155. package/packages/skills/src/bundled/filesystem/file_writer/SKILL.md +10 -10
  156. package/packages/skills/src/bundled/search_knowledge/capability_discovery/SKILL.md +8 -8
  157. package/packages/skills/src/bundled/web/browser_automate/SKILL.md +21 -12
  158. package/packages/skills/src/bundled/web/browser_scrape/SKILL.md +28 -13
  159. package/packages/skills/src/bundled/web/obscura_browser/SKILL.md +69 -0
  160. package/packages/skills/src/bundled/web/web_monitor/SKILL.md +6 -6
  161. package/packages/skills/src/bundled/web/web_research/SKILL.md +5 -5
  162. package/packages/skills/src/bundled-data.generated.ts +845 -773
  163. package/dist/ui/assets/A2UIPage-DTW79pyL.js +0 -8
  164. package/dist/ui/assets/AgentDetailPage-10XptMde.js +0 -1
  165. package/dist/ui/assets/AgentNewPage-CUt49rVS.js +0 -1
  166. package/dist/ui/assets/AgentsPage-1_e1a9xa.js +0 -10
  167. package/dist/ui/assets/ChannelsPage-BnCQAGZL.js +0 -8
  168. package/dist/ui/assets/DashboardPage-BsCCKHgg.js +0 -6
  169. package/dist/ui/assets/LogsPage-DiFBQt7o.js +0 -1
  170. package/dist/ui/assets/MeetingPage-Bpv5zVXf.js +0 -1
  171. package/dist/ui/assets/ModelSelector-DfExlPzx.js +0 -1
  172. package/dist/ui/assets/NotFound-C8HBdF73.js +0 -1
  173. package/dist/ui/assets/Office3DPage-ChsGMapf.js +0 -319
  174. package/dist/ui/assets/ProvidersPage-B39pfWHf.js +0 -1
  175. package/dist/ui/assets/SettingsPage-BgFqasyg.js +0 -9
  176. package/dist/ui/assets/SetupPage-YeJFfgbt.js +0 -1
  177. package/dist/ui/assets/VoicePage-Cp63Abj4.js +0 -307
  178. package/dist/ui/assets/WebChatPage-DxFLWgtM.js +0 -29
  179. package/dist/ui/assets/agentCapabilities-DOeepCty.js +0 -1
  180. package/dist/ui/assets/alert-Cj4DpKv6.js +0 -1
  181. package/dist/ui/assets/badge-DKpeVCpY.js +0 -1
  182. package/dist/ui/assets/card-Cag15G4h.js +0 -1
  183. package/dist/ui/assets/dialog-7E3EoEt3.js +0 -1
  184. package/dist/ui/assets/dist-js-DwLn9F4C.js +0 -1
  185. package/dist/ui/assets/index-Bi8qEmrK.js +0 -116
  186. package/dist/ui/assets/index-D2UhaSb0.css +0 -2
  187. package/dist/ui/assets/label-C6atPuIh.js +0 -1
  188. package/dist/ui/assets/pencil-CUbpCfeG.js +0 -1
  189. package/dist/ui/assets/scroll-area-CSoG2z53.js +0 -1
  190. package/dist/ui/assets/select-DlCT21_r.js +0 -1
  191. package/dist/ui/assets/slider-Bb_PHFJT.js +0 -1
  192. package/dist/ui/assets/switch-CUsGuBNi.js +0 -1
  193. package/dist/ui/assets/tabs-Ckfc7DGG.js +0 -1
  194. package/dist/ui/assets/textarea-BH6pI9Ax.js +0 -1
  195. package/dist/ui/assets/useAudioDevices-Dpr_hn6i.js +0 -41
  196. package/dist/ui/assets/useOfficeModel-Cc5VkReZ.js +0 -1
  197. package/dist/ui/assets/vendor-react-DYyYpuMy.js +0 -1
  198. /package/dist/ui/assets/{core-Dz04EE_8.js → core-B_5cyOSV.js} +0 -0
  199. /package/dist/ui/assets/{download-D0aDV8Y_.js → download-BQXrpH0m.js} +0 -0
  200. /package/dist/ui/assets/{ellipsis-vertical-BOW_iEOO.js → ellipsis-vertical-D7uFJLGh.js} +0 -0
  201. /package/dist/ui/assets/{external-link-5cujQzfV.js → external-link-6oTH9pUM.js} +0 -0
  202. /package/dist/ui/assets/{eye-sRPY5qOa.js → eye-CxvxtQT5.js} +0 -0
  203. /package/dist/ui/assets/{file-text-DNSyNLUh.js → file-text-D5ZJEx3E.js} +0 -0
  204. /package/dist/ui/assets/{gateway-url-BzQV75Ig.js → gateway-url-BALS_wVh.js} +0 -0
  205. /package/dist/ui/assets/{gauge-C__zxC3_.js → gauge-CEu7PhTW.js} +0 -0
  206. /package/dist/ui/assets/{history-BHQWfE-7.js → history-DLK5rTlP.js} +0 -0
  207. /package/dist/ui/assets/{info-CG1VohyH.js → info-8ReWzubE.js} +0 -0
  208. /package/dist/ui/assets/{key-BC28VCjO.js → key-DPkOY-J0.js} +0 -0
  209. /package/dist/ui/assets/{lock-open-Bhp0UJlL.js → lock-open-v0EphssG.js} +0 -0
  210. /package/dist/ui/assets/{mail-Biwn8WrV.js → mail-vwCEHyhQ.js} +0 -0
  211. /package/dist/ui/assets/{mic-Rq4BxU1R.js → mic-CpDU_2as.js} +0 -0
  212. /package/dist/ui/assets/{pause-C2l5G2Py.js → pause-Cm9LzIZK.js} +0 -0
  213. /package/dist/ui/assets/{play-CMAscR3a.js → play-zqogwA2l.js} +0 -0
  214. /package/dist/ui/assets/{plus-DzvRxH4U.js → plus-Bm08ABhc.js} +0 -0
  215. /package/dist/ui/assets/{radio-DfGzov4y.js → radio-Cii1BjMt.js} +0 -0
  216. /package/dist/ui/assets/{refresh-cw-DZXu5FrG.js → refresh-cw-DXv3XgEt.js} +0 -0
  217. /package/dist/ui/assets/{rotate-ccw-Dx92orJM.js → rotate-ccw-LoM1AuqK.js} +0 -0
  218. /package/dist/ui/assets/{search-DB4w9YHW.js → search-BMwCI-pX.js} +0 -0
  219. /package/dist/ui/assets/{send-xi8HzUdc.js → send-D6fgWV7m.js} +0 -0
  220. /package/dist/ui/assets/{settings-pV0cF8Kf.js → settings-qV3kVkeG.js} +0 -0
  221. /package/dist/ui/assets/{shield-nLNsomh_.js → shield-CIarwBvx.js} +0 -0
  222. /package/dist/ui/assets/{sparkles-CerRDYxk.js → sparkles-DVvY6jDT.js} +0 -0
  223. /package/dist/ui/assets/{square-CcWzRWyG.js → square-D5zdNkAY.js} +0 -0
  224. /package/dist/ui/assets/{terminal-C2SUZUAD.js → terminal-BEcTK780.js} +0 -0
  225. /package/dist/ui/assets/{trash-2-BZsMCfso.js → trash-2-D6oziYAK.js} +0 -0
  226. /package/dist/ui/assets/{utils-lc8H6VGT.js → utils-DEmd_M8c.js} +0 -0
  227. /package/dist/ui/assets/{vendor-router-DCsSv_I7.js → vendor-router-DP84b3LQ.js} +0 -0
  228. /package/dist/ui/assets/{volume-2-CBMYsuF3.js → volume-2-EaA0JRvD.js} +0 -0
  229. /package/dist/ui/assets/{volume-x-vNFf2e4-.js → volume-x-CROXNMGT.js} +0 -0
  230. /package/dist/ui/assets/{wifi-DNv53AfN.js → wifi-BUJuOcgP.js} +0 -0
  231. /package/dist/ui/assets/{zap-Yed86Sh8.js → zap-DSoX9NDk.js} +0 -0
@@ -0,0 +1,242 @@
1
+ /** Optional decision plane. Jev is never used through the chat completions API. */
2
+ import { col } from "../storage/hive"
3
+ import type { ProviderDoc } from "../storage/collections"
4
+ import { loadProviderApiKey } from "../storage/crypto"
5
+ import { recordJevDecision, recordUsage } from "../storage/usage"
6
+ import { catalogModelKey } from "../storage/model-id"
7
+ import { logger } from "../utils/logger"
8
+ import { emitCanvas, type CanvasJevDecision } from "../canvas/emitter"
9
+
10
+ const log = logger.child("jev-decisions")
11
+ export const JEV_MODEL = "typesafe/jev-1.13"
12
+ const ENDPOINT = "https://openrouter.ai/api/alpha/decisions"
13
+ const TIMEOUT_MS = 3000
14
+ const COOLDOWN_MS = 60_000
15
+ /** Kev: same oracle served from the HiveAgents LLM host (llm.hiveagents.io), tried before Jev. */
16
+ export const KEV_MODEL = "Kev-9B-Q8_0.gguf"
17
+ const KEV_DEFAULT_BASE = "https://llm.hiveagents.io"
18
+ const KEV_READY_TTL_MS = 30_000
19
+ const KEV_STATUS_TIMEOUT_MS = 2000
20
+ export type DecisionBackend = "kev" | "jev"
21
+ let failures = 0
22
+ let cooldownUntil = 0
23
+ let lastError: string | null = null
24
+ let lastSuccessAt: number | null = null
25
+ let kevFailures = 0
26
+ let kevCooldownUntil = 0
27
+ let kevReadyCache: { at: number; ready: boolean } | null = null
28
+ let lastBackend: DecisionBackend | null = null
29
+ let decisionSequence = 0
30
+ /** Since gateway boot; the office shows them as the oracle's running contribution. */
31
+ const totals = { decisions: 0, savedTokens: 0, costUsd: 0 }
32
+
33
+ export type JevQuestion =
34
+ | { type: "choice"; instructions: string; criteria: Record<string, string> }
35
+ | { type: "noul"; instructions: string; criteria?: { true: string; false: string } }
36
+ | { type: "score"; instructions: string; criteria?: Record<string, string> }
37
+
38
+ export type JevAnswer =
39
+ | { type: "choice"; choice: string; confidence: number; probabilities: Record<string, number> }
40
+ | { type: "noul"; noul: number }
41
+ | { type: "score"; score: number }
42
+
43
+ export interface JevResult {
44
+ answers: Record<string, JevAnswer>
45
+ inputTokens: number
46
+ costUsd: number
47
+ latencyMs: number
48
+ backend: DecisionBackend
49
+ }
50
+
51
+ export async function getJevKey(): Promise<string | null> {
52
+ const provider = await (await col<ProviderDoc>("providers")).get("openrouter")
53
+ if (!provider?.doc.enabled || !provider.doc.active) return null
54
+ return (await loadProviderApiKey("openrouter")) || process.env.OPENROUTER_API_KEY || null
55
+ }
56
+
57
+ /** Kev is available when the HiveAgents LLM provider is on and has a key; readiness is checked separately. */
58
+ async function getKevConfig(): Promise<{ key: string; base: string } | null> {
59
+ const provider = await (await col<ProviderDoc>("providers")).get("hiveagents")
60
+ if (!provider?.doc.enabled || !provider.doc.active) return null
61
+ const key = (await loadProviderApiKey("hiveagents")) || process.env.HIVEAGENTS_API_KEY || null
62
+ if (!key) return null
63
+ return { key, base: provider.doc.base_url?.replace(/\/v1\/?$/, "").replace(/\/$/, "") || KEV_DEFAULT_BASE }
64
+ }
65
+
66
+ /** `kev-decision.service` is toggled with systemd on the lab PC, so ask the host; cached to spare every turn a request. */
67
+ async function isKevReady(cfg: { key: string; base: string }, fetcher: typeof fetch): Promise<boolean> {
68
+ if (Date.now() < kevCooldownUntil) return false
69
+ if (kevReadyCache && Date.now() - kevReadyCache.at < KEV_READY_TTL_MS) return kevReadyCache.ready
70
+ let ready = false
71
+ try {
72
+ const response = await fetcher(`${cfg.base}/api/decisions/status`, {
73
+ headers: { Authorization: `Bearer ${cfg.key}` },
74
+ signal: AbortSignal.timeout(KEV_STATUS_TIMEOUT_MS),
75
+ })
76
+ if (response.status === 401 || response.status === 403) kevCooldownUntil = Date.now() + COOLDOWN_MS
77
+ else if (response.ok) {
78
+ const data = await response.json().catch(() => null) as { ready?: unknown } | null
79
+ ready = data?.ready === true
80
+ }
81
+ } catch { /* host unreachable: Kev is simply off */ }
82
+ kevReadyCache = { at: Date.now(), ready }
83
+ return ready
84
+ }
85
+
86
+ /** True when any decision backend could answer; callers use it to skip building questions. */
87
+ export async function hasDecisionBackend(): Promise<boolean> {
88
+ if (await getJevKey().catch(() => null)) return true
89
+ const kev = await getKevConfig().catch(() => null)
90
+ return !!kev && Date.now() >= kevCooldownUntil
91
+ }
92
+
93
+ export interface JevStatus {
94
+ state: "off" | "ready" | "fallback"
95
+ backend: DecisionBackend | null
96
+ lastError: string | null
97
+ lastSuccessAt: number | null
98
+ totals: { decisions: number; savedTokens: number; costUsd: number }
99
+ }
100
+
101
+ export async function getJevStatus(): Promise<JevStatus> {
102
+ const key = await getJevKey().catch(() => null)
103
+ const kev = await getKevConfig().catch(() => null)
104
+ const jevOk = !!key && Date.now() >= cooldownUntil && !lastError
105
+ const kevOk = !!kev && Date.now() >= kevCooldownUntil && kevFailures === 0
106
+ // Before any decision has been served, report who would answer: Kev only when its host says ready.
107
+ const kevReady = kevOk && kev ? await isKevReady(kev, fetch).catch(() => false) : false
108
+ return {
109
+ state: !key && !kev ? "off" : jevOk || kevReady ? "ready" : "fallback",
110
+ backend: kevReady ? "kev" : lastBackend ?? (jevOk ? "jev" : null),
111
+ lastError: key || kev ? lastError : null,
112
+ lastSuccessAt: key || kev ? lastSuccessAt : null,
113
+ totals: { ...totals },
114
+ }
115
+ }
116
+
117
+ function broadcastStatus(): void {
118
+ getJevStatus().then(status => emitCanvas("canvas:jev_status", status)).catch(() => { /* best effort */ })
119
+ }
120
+
121
+ /**
122
+ * Publishes a served decision to the office and persists it for the dashboard.
123
+ * Callers estimate savings; Jev itself only answers questions. `provider`/`model`
124
+ * are the advised agent's main model, used to price the avoided tokens.
125
+ */
126
+ export function emitJevDecision({ provider, model, ...decision }: Omit<CanvasJevDecision, "eventId" | "totals"> & { provider: string; model: string }): void {
127
+ recordJevDecision({ agentId: decision.agentId, provider, model, savedTokens: decision.savedTokens, costUsd: decision.costUsd })
128
+ totals.decisions++
129
+ totals.savedTokens += decision.savedTokens
130
+ totals.costUsd += decision.costUsd
131
+ emitCanvas("canvas:jev_decision", {
132
+ ...decision,
133
+ eventId: `jev:${Date.now().toString(36)}:${++decisionSequence}`,
134
+ summary: decision.summary.slice(0, 160),
135
+ totals: { ...totals },
136
+ } satisfies CanvasJevDecision)
137
+ }
138
+
139
+ export function resetJevStatus(): void {
140
+ failures = 0
141
+ cooldownUntil = 0
142
+ lastError = null
143
+ lastSuccessAt = null
144
+ kevFailures = 0
145
+ kevCooldownUntil = 0
146
+ kevReadyCache = null
147
+ lastBackend = null
148
+ broadcastStatus()
149
+ }
150
+
151
+ function validateAnswers(questions: Record<string, JevQuestion>, data: { answers?: Record<string, JevAnswer> }): Record<string, JevAnswer> {
152
+ const answers: Record<string, JevAnswer> = {}
153
+ const unit = (n: unknown): n is number => typeof n === "number" && Number.isFinite(n) && n >= 0 && n <= 1
154
+ for (const [name, question] of Object.entries(questions)) {
155
+ const answer = data.answers?.[name]
156
+ if (question.type === "choice") {
157
+ if (answer?.type !== "choice" || !Object.hasOwn(question.criteria, answer.choice) || !unit(answer.confidence)) {
158
+ throw new Error(`Invalid choice answer: ${name}`)
159
+ }
160
+ } else if (question.type === "score") {
161
+ if (answer?.type !== "score" || !unit(answer.score)) throw new Error(`Invalid score answer: ${name}`)
162
+ } else if (answer?.type !== "noul" || !unit(answer.noul)) {
163
+ throw new Error(`Invalid noul answer: ${name}`)
164
+ }
165
+ answers[name] = answer
166
+ }
167
+ return answers
168
+ }
169
+
170
+ export async function askJev(
171
+ state: unknown,
172
+ questions: Record<string, JevQuestion>,
173
+ options: { fetcher?: typeof fetch; signal?: AbortSignal } = {},
174
+ ): Promise<JevResult | null> {
175
+ if (Object.keys(questions).length === 0) return null
176
+ const fetcher = options.fetcher ?? fetch
177
+ const kev = await getKevConfig().catch(() => null)
178
+ if (kev && await isKevReady(kev, fetcher)) {
179
+ const result = await requestDecision("kev", `${kev.base}/v1/systemone`, kev.key, KEV_MODEL, state, questions, options)
180
+ if (result || options.signal?.aborted) return result
181
+ }
182
+ const key = await getJevKey().catch(() => null)
183
+ if (!key || Date.now() < cooldownUntil) return null
184
+ return requestDecision("jev", ENDPOINT, key, JEV_MODEL, state, questions, options)
185
+ }
186
+
187
+ async function requestDecision(
188
+ backend: DecisionBackend,
189
+ endpoint: string,
190
+ key: string,
191
+ model: string,
192
+ state: unknown,
193
+ questions: Record<string, JevQuestion>,
194
+ options: { fetcher?: typeof fetch; signal?: AbortSignal },
195
+ ): Promise<JevResult | null> {
196
+ const started = performance.now()
197
+ const label = backend === "kev" ? "Kev" : "OpenRouter"
198
+ try {
199
+ const response = await (options.fetcher ?? fetch)(endpoint, {
200
+ method: "POST",
201
+ headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },
202
+ body: JSON.stringify({ model, state, questions }),
203
+ signal: options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(TIMEOUT_MS)]) : AbortSignal.timeout(TIMEOUT_MS),
204
+ })
205
+ if (!response.ok) {
206
+ if (response.status === 401 || response.status === 403) {
207
+ if (backend === "kev") kevCooldownUntil = Date.now() + COOLDOWN_MS
208
+ else cooldownUntil = Date.now() + COOLDOWN_MS
209
+ }
210
+ throw new Error(`${label} HTTP ${response.status}`)
211
+ }
212
+ const data = await response.json() as {
213
+ answers?: Record<string, JevAnswer>
214
+ usage?: { input_tokens?: number; output_tokens?: number; cost?: number }
215
+ }
216
+ const answers = validateAnswers(questions, data)
217
+ const recovered = lastError !== null
218
+ if (backend === "kev") kevFailures = 0
219
+ else failures = 0
220
+ lastError = null
221
+ lastSuccessAt = Date.now()
222
+ if (recovered || lastBackend !== backend) { lastBackend = backend; broadcastStatus() }
223
+ const inputTokens = data.usage?.input_tokens ?? 0
224
+ // Kev runs on our own hardware: no per-token cost.
225
+ const costUsd = backend === "kev" ? 0 : data.usage?.cost ?? inputTokens * 0.042 / 1_000_000
226
+ log.info(`Decision served: backend=${backend} questions=${Object.keys(questions).join(",")} latency_ms=${Math.round(performance.now() - started)} input_tokens=${inputTokens} cost_usd=${costUsd}`)
227
+ if (inputTokens > 0) {
228
+ const provider = backend === "kev" ? "hiveagents" : "openrouter"
229
+ recordUsage({ provider, model: catalogModelKey(provider, model), inputTokens, outputTokens: data.usage?.output_tokens ?? 0, latencyMs: Math.round(performance.now() - started) })
230
+ }
231
+ return { answers, inputTokens, costUsd, latencyMs: Math.round(performance.now() - started), backend }
232
+ } catch (error) {
233
+ if (options.signal?.aborted) return null
234
+ lastError = error instanceof Error ? error.message : `${label} unavailable`
235
+ if (backend === "kev") {
236
+ if (++kevFailures >= 3) { kevCooldownUntil = Date.now() + COOLDOWN_MS; kevReadyCache = null }
237
+ } else if (++failures >= 3) cooldownUntil = Date.now() + COOLDOWN_MS
238
+ log.warn(`Decision fallback (${backend}): ${lastError}`)
239
+ broadcastStatus()
240
+ return null
241
+ }
242
+ }
@@ -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, hasDecisionBackend, 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 hasDecisionBackend().catch(() => false)) 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 hasDecisionBackend().catch(() => false)) 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,6 +221,14 @@ 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. `
@@ -221,8 +236,8 @@ export function describeProviderFailure(
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
- + `revisa 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}). `
@@ -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