@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
@@ -25,12 +25,15 @@ import { maybeCompact, clearOldToolResults } from "./compaction"
25
25
  import { emitCanvas } from "../canvas/emitter"
26
26
  import type { MCPClientManager } from "@johpaz/hive-agents-mcp"
27
27
  import { compileContext } from "./context-compiler"
28
+ import { MINIMAL_TOOLS } from "./minimal-loadout"
28
29
  import { formatToolResult } from "../utils/toon"
29
30
  import { redactBinaryStrings } from "../utils/redact-binary"
30
31
  import { resolveUserId, resolveAgentId } from "../storage/onboarding"
31
32
  import type { ContentPart } from "../multimodal/types"
32
33
  import { loadConfig } from "../config/loader"
33
34
  import { executeToolBatch } from "../tool-runtime"
35
+ import { jevWantsParallel, planJevIteration } from "./jev-planner"
36
+ import { emitJevDecision } from "./jev-decisions"
34
37
  import { createStuckLoopDetector, getInterventionMessage, type StuckLoopState } from "./stuck-loop"
35
38
  import {
36
39
  createRun as createAgentRun,
@@ -51,6 +54,10 @@ import { getNarration } from "../events/tool-narration"
51
54
 
52
55
  const log = logger.child("agent-loop")
53
56
 
57
+ const JEV_ACTION_LABELS: Record<string, string> = {
58
+ continue: "Continuar", delegate: "Delegar", discover: "Descubrir", finish: "Cerrar",
59
+ }
60
+
54
61
  // Per-operation budget for a single LLM call — NOT an aggregate deadline for the
55
62
  // whole turn. Each call gets its own fresh window; a slow-but-healthy multi-step
56
63
  // turn (many quick operations) is never killed just for taking a while overall.
@@ -352,7 +359,9 @@ export async function* runAgent(
352
359
  opts.threadId,
353
360
  opts.channel && opts.userId
354
361
  ? { channel: opts.channel, userId: opts.userId }
355
- : undefined
362
+ : undefined,
363
+ providerCfg.contextWindow,
364
+ opts.signal,
356
365
  )
357
366
  }
358
367
 
@@ -367,7 +376,12 @@ export async function* runAgent(
367
376
  taskContext: opts.taskContext,
368
377
  userId: opts.userId,
369
378
  causalStreamId,
379
+ skipJev: !!opts.resume,
380
+ contextWindow: providerCfg.contextWindow,
370
381
  })
382
+ if (ctx.jevDecision) {
383
+ emitJevDecision({ ...ctx.jevDecision, agentId: opts.agentId, kind: "context", provider: providerCfg.provider, model: providerCfg.model })
384
+ }
371
385
 
372
386
  // Force extra tools into the loadout (tests/evals)
373
387
  if (opts.extraTools?.length) {
@@ -399,9 +413,11 @@ export async function* runAgent(
399
413
  if (opts.isolated) {
400
414
  messages.push({ role: "user", content: opts.userMessage })
401
415
  }
416
+ const jevObjective = typeof opts.userMessage === "string" ? opts.userMessage :
417
+ opts.userMessage.filter((part) => part.type === "text").map((part) => (part as { text: string }).text).join("\n")
402
418
 
403
419
  // ── Resume from checkpoint ─────────────────────────────────────────────────
404
- let injectedToolNames: string[] = []
420
+ let injectedToolNames: string[] = ctx.tools.map(t => t.function.name).filter(name => !MINIMAL_TOOLS.has(name))
405
421
  let systemPromptSkillSections: string[] = []
406
422
  let resumedFromPending = false
407
423
  let iterations = 0
@@ -422,6 +438,14 @@ export async function* runAgent(
422
438
  if (restored) {
423
439
  messages = restored.messages
424
440
  injectedToolNames = restored.injectedToolNames ?? []
441
+ const currentTools = new Set(ctx.tools.map(t => t.function.name))
442
+ for (const name of injectedToolNames) {
443
+ const tool = ctx.allTools.find(t => t.name === name)
444
+ if (tool && !currentTools.has(name)) {
445
+ ctx.tools.push({ type: "function", function: { name: tool.name, description: tool.description, parameters: tool.parameters } })
446
+ currentTools.add(name)
447
+ }
448
+ }
425
449
  systemPromptSkillSections = restored.systemPromptSkillSections ?? []
426
450
  iterations = restored.iterations ?? 0
427
451
  totalInputTokens = restored.totalInputTokens ?? 0
@@ -434,7 +458,7 @@ export async function* runAgent(
434
458
  const pending = JSON.parse(existing.pending_tool_calls_json)
435
459
  const interruptedMsgs = pending.map((tc: any) => ({
436
460
  role: "tool" as const,
437
- content: "[interrupted] El proceso se reinició mientras esta herramienta corría. El resultado no está disponible — decidí si reintentar o continuar sin él.",
461
+ content: "[interrupted] El proceso se reinició mientras esta herramienta corría. El resultado no está disponible — decide si reintentar o continuar sin él.",
438
462
  tool_call_id: tc.id,
439
463
  }))
440
464
  messages.push(...interruptedMsgs)
@@ -507,12 +531,30 @@ export async function* runAgent(
507
531
  : null
508
532
  let streamedThisCall = false
509
533
  let response: Awaited<ReturnType<typeof callLLM>>
534
+ const jevIteration = await planJevIteration({ objective: jevObjective, messages, tools: ctx.tools })
535
+ .catch((err) => { log.warn(`[agent-loop] Jev iteration fallback: ${(err as Error).message}`); return null })
536
+ const callMessages = jevIteration?.messages ?? messages
537
+ const callTools = jevIteration?.tools ?? ctx.tools
538
+ if (jevIteration) {
539
+ log.info(`[agent-loop] Jev action=${jevIteration.action} omitted_results=${jevIteration.omittedResults} tools=${callTools.map(t => t.function.name).join(",")}`)
540
+ // Measured on what the provider actually receives, after the usual truncation.
541
+ const payloadChars = (msgs: LLMMessage[], tools: typeof ctx.tools) =>
542
+ JSON.stringify(clearOldToolResults(msgs)).length + JSON.stringify(tools).length
543
+ emitJevDecision({
544
+ agentId: opts.agentId, kind: "iteration", provider: providerCfg.provider, model: providerCfg.model,
545
+ summary: `${JEV_ACTION_LABELS[jevIteration.action] ?? jevIteration.action} · ${jevIteration.omittedResults} resultado(s) omitido(s) · ${callTools.length}/${ctx.tools.length} herramientas`,
546
+ savedTokens: Math.round((payloadChars(messages, ctx.tools) - payloadChars(callMessages, callTools)) / 4),
547
+ latencyMs: jevIteration.decision.latencyMs, costUsd: jevIteration.decision.costUsd,
548
+ })
549
+ }
550
+ const llmCallStartedAt = performance.now()
510
551
  try {
511
552
  response = await withTimeout(() => callLLM({
512
553
  ...providerCfg,
513
- messages: clearOldToolResults(messages) as LLMMessage[],
514
- tools: ctx.tools.length > 0 ? ctx.tools : undefined,
554
+ messages: clearOldToolResults(callMessages) as LLMMessage[],
555
+ tools: callTools.length > 0 ? callTools : undefined,
515
556
  signal: opts.signal,
557
+ sessionId: opts.threadId,
516
558
  onToken: opts.onToken && !delegationGroupAtCall
517
559
  ? (token: string) => {
518
560
  streamedThisCall = true
@@ -527,7 +569,7 @@ export async function* runAgent(
527
569
  } catch (err) {
528
570
  if (err instanceof LLMCallTimeoutError) {
529
571
  log.warn(`[agent-loop] ${err.message} at iteration ${iterations}. Breaking.`)
530
- finalContent = "El modelo tardó demasiado en responder. Intentá de nuevo o simplificá la consulta."
572
+ finalContent = "El modelo tardó demasiado en responder. Intenta de nuevo o simplifica la consulta."
531
573
  break
532
574
  }
533
575
  throw err
@@ -544,6 +586,9 @@ export async function* runAgent(
544
586
  if (response.usage) {
545
587
  totalInputTokens += response.usage.input_tokens
546
588
  totalOutputTokens += response.usage.output_tokens
589
+ recordLLMUsage({ provider: providerCfg.provider, model: providerCfg.model,
590
+ inputTokens: response.usage.input_tokens, outputTokens: response.usage.output_tokens,
591
+ latencyMs: Math.round(performance.now() - llmCallStartedAt) })
547
592
  }
548
593
 
549
594
  // G9: record this LLM response as a causal "decision", chained off the
@@ -670,6 +715,16 @@ export async function* runAgent(
670
715
  }
671
716
  }
672
717
 
718
+ const jevParallel = await jevWantsParallel(response.tool_calls)
719
+ .catch((err) => { log.warn(`[agent-loop] Jev parallel fallback: ${(err as Error).message}`); return null })
720
+ if (jevParallel?.decision) {
721
+ log.info(`[agent-loop] Jev parallel=${jevParallel.parallel} calls=${response.tool_calls.length}`)
722
+ emitJevDecision({
723
+ agentId: opts.agentId, kind: "parallel", provider: providerCfg.provider, model: providerCfg.model,
724
+ summary: `${response.tool_calls.length} herramientas ${jevParallel.parallel ? "en paralelo" : "en secuencia"}`,
725
+ savedTokens: 0, latencyMs: jevParallel.decision.latencyMs, costUsd: jevParallel.decision.costUsd,
726
+ })
727
+ }
673
728
  const toolResults = await executeToolBatch({
674
729
  toolCalls: response.tool_calls,
675
730
  allTools: ctx.allTools,
@@ -690,6 +745,7 @@ export async function* runAgent(
690
745
  },
691
746
  hiveConfig,
692
747
  workerPool: hiveConfig.tools?.workerPool,
748
+ parallelToolCalls: jevParallel?.parallel,
693
749
  signal: opts.signal,
694
750
  })
695
751
 
@@ -1121,14 +1177,19 @@ export async function* runAgent(
1121
1177
  if (synthesisAttempt > 1) {
1122
1178
  log.warn("[agent-loop] Retrying terminal synthesis after an empty or failed response")
1123
1179
  }
1180
+ const synthesisStartedAt = performance.now()
1124
1181
  const synthesis = await callLLM({
1125
1182
  ...providerCfg,
1126
1183
  messages: clearOldToolResults(messages) as LLMMessage[],
1127
1184
  tools: undefined, // no tools — force text response
1185
+ sessionId: opts.threadId,
1128
1186
  })
1129
1187
  if (synthesis.usage) {
1130
1188
  totalInputTokens += synthesis.usage.input_tokens
1131
1189
  totalOutputTokens += synthesis.usage.output_tokens
1190
+ recordLLMUsage({ provider: providerCfg.provider, model: providerCfg.model,
1191
+ inputTokens: synthesis.usage.input_tokens, outputTokens: synthesis.usage.output_tokens,
1192
+ latencyMs: Math.round(performance.now() - synthesisStartedAt) })
1132
1193
  }
1133
1194
  // A provider failure comes back as non-empty `content`, which the
1134
1195
  // empty-content check above would happily accept as a valid synthesis and
@@ -1169,14 +1230,6 @@ export async function* runAgent(
1169
1230
  changes: { status: "idle", currentTool: null },
1170
1231
  })
1171
1232
 
1172
- // Record usage
1173
- recordLLMUsage({
1174
- provider: providerCfg.provider,
1175
- model: providerCfg.model,
1176
- inputTokens: totalInputTokens,
1177
- outputTokens: totalOutputTokens,
1178
- })
1179
-
1180
1233
  // Extract text for trace summary
1181
1234
  const textMessageFinal = opts.rawUserMessage || (typeof opts.userMessage === "string"
1182
1235
  ? opts.userMessage
@@ -80,7 +80,8 @@ export async function searchCapabilities(
80
80
  const k = opts.k ?? 10;
81
81
  const types = opts.types?.length ? opts.types : undefined;
82
82
  const trimmed = query.trim();
83
- if (!trimmed) return [];
83
+ // hive-db >= 0.4 rejects k <= 0 instead of returning no hits.
84
+ if (!trimmed || k <= 0) return [];
84
85
 
85
86
  const startTime = performance.now();
86
87
  const db = await getHiveDb();
@@ -39,6 +39,10 @@ const KEEP_LAST_N_MESSAGES = 5 // always keep most recent N messages
39
39
  const TOOL_RESULT_MAX_CHARS = 200 // max chars for old tool results after clearing
40
40
  const MAX_TRANSCRIPT_MSGS = 30 // cap messages sent to summarizer (avoids OOM on small models)
41
41
  const MAX_MSG_CHARS = 300 // chars per message in transcript
42
+ // Compaction runs before the turn and blocks it. A local model on CPU took
43
+ // minutes here; past this bound the turn goes on uncompacted — the context
44
+ // compiler already trims history to the window, so nothing overflows.
45
+ const COMPACTION_TIMEOUT_MS = 60_000
42
46
 
43
47
  /**
44
48
  * Check if compaction is needed and run it if so.
@@ -46,14 +50,18 @@ const MAX_MSG_CHARS = 300 // chars per message in transcript
46
50
  */
47
51
  export async function maybeCompact(
48
52
  threadId: string,
49
- notify?: { channel: string; userId: string }
53
+ notify?: { channel: string; userId: string },
54
+ /** The window the provider really reads (resolveProviderConfig); overrides the model row. */
55
+ contextWindow?: number,
56
+ /** The turn's abort signal: cancelling the turn also stops its compaction. */
57
+ signal?: AbortSignal,
50
58
  ): Promise<void> {
51
59
  try {
52
60
  const totalTokens = await getTotalTokens(threadId)
53
61
 
54
62
  // Use model's context window if available, otherwise use default
55
- let effectiveThreshold = COMPACT_TOKEN_THRESHOLD
56
- try {
63
+ let effectiveThreshold = contextWindow ? Math.floor(contextWindow * 0.25) : COMPACT_TOKEN_THRESHOLD
64
+ if (!contextWindow) try {
57
65
  const agentsCol = await col<AgentDoc>("agents")
58
66
  const coordinators = await agentsCol.findBy("role", "coordinator", { limit: 1 })
59
67
  const modelId = fromIndexable(coordinators[0]?.doc.model_id ?? null)
@@ -78,7 +86,8 @@ export async function maybeCompact(
78
86
  if (summary && summary.last_message_id > totalMessages - KEEP_LAST_N_MESSAGES) return
79
87
 
80
88
  log.info(`[compaction] Compacting thread=${threadId} tokens=${totalTokens}`)
81
- await compactThread(threadId, notify)
89
+ const timeout = AbortSignal.timeout(COMPACTION_TIMEOUT_MS)
90
+ await compactThread(threadId, notify, signal ? AbortSignal.any([signal, timeout]) : timeout)
82
91
  } catch (err) {
83
92
  log.warn("[compaction] Error during compaction check:", err)
84
93
  }
@@ -118,9 +127,10 @@ export function renderTranscript(rows: StoredMessage[], maxMsgChars = MAX_MSG_CH
118
127
  /**
119
128
  * Compress a thread's history into a summary.
120
129
  */
121
- async function compactThread(
130
+ export async function compactThread(
122
131
  threadId: string,
123
- notify?: { channel: string; userId: string }
132
+ notify?: { channel: string; userId: string },
133
+ signal?: AbortSignal,
124
134
  ): Promise<void> {
125
135
  const allMessages = await getHistory(threadId)
126
136
  if (allMessages.length <= KEEP_LAST_N_MESSAGES) return
@@ -150,6 +160,7 @@ async function compactThread(
150
160
 
151
161
  const summaryResponse = await callLLM({
152
162
  ...providerCfg,
163
+ signal,
153
164
  messages: [
154
165
  {
155
166
  role: "system",
@@ -191,7 +202,8 @@ async function compactThread(
191
202
  await sendToUserChannel(
192
203
  notify.channel,
193
204
  notify.userId,
194
- `🗜️ Resumí ${toSummarize.length} mensajes anteriores para mantener el contexto limpio.`
205
+ `🗜️ Resumí ${toSummarize.length} mensajes anteriores para mantener el contexto limpio.`,
206
+ { threadId }
195
207
  )
196
208
  } catch {
197
209
  // Non-critical — don't break the flow if notification fails
@@ -43,6 +43,7 @@ import { getHiveDb } from "../storage/hivedb"
43
43
  import { listCatalogAgents, renderAgentRoutingCatalog } from "./catalog-selector"
44
44
  import { expandToolAllowlist } from "./delegation-runtime"
45
45
  import { MINIMAL_TOOLS } from "./minimal-loadout"
46
+ import { describeSwarmCapabilities, planJevContext, renderSpecialistLine } from "./jev-planner"
46
47
 
47
48
  const log = logger.child("context-compiler")
48
49
 
@@ -89,6 +90,8 @@ export interface CompiledContext {
89
90
  tools: LLMToolDef[]
90
91
  allTools: ContextTool[]
91
92
  skills: SkillDescriptor[] // Skills loaded (minimal + discovered)
93
+ /** Jev's context plan, for the caller to publish once it knows the agent's resolved model. */
94
+ jevDecision?: { summary: string; savedTokens: number; latencyMs: number; costUsd: number; recommendedAgentId: string | null; mcpOff: string[] }
92
95
  }
93
96
 
94
97
  // ─── G9 causal context (buildAgentContext) ────────────────────────────────
@@ -146,6 +149,42 @@ function fromAgentDoc(doc: AgentDoc) {
146
149
  }
147
150
  }
148
151
 
152
+ // ─── History budget ─────────────────────────────────────────────────────────
153
+
154
+ const messageTokens = (m: LLMMessage) => estimateTokens(typeof m.content === "string" ? m.content : JSON.stringify(m.content))
155
+
156
+ /**
157
+ * Drops the oldest history until it fits `budget` tokens. The history used to
158
+ * go out whole whatever its size, and a provider that truncates (Ollama at
159
+ * num_ctx) cut it blindly instead. The last `minKeep` messages — the current
160
+ * turn and the exchange it refers to — always stay, even over budget: a window
161
+ * too small for them is better served by a truncated prompt than by an answer
162
+ * with no conversation at all. A single oversized newest message is trimmed
163
+ * from the middle, keeping its start and its end.
164
+ */
165
+ export function fitMessagesToBudget(messages: LLMMessage[], budget: number, minKeep = 4): LLMMessage[] {
166
+ let total = messages.reduce((sum, m) => sum + messageTokens(m), 0)
167
+ if (total <= budget || messages.length === 0) return messages
168
+ const kept = [...messages]
169
+ while (kept.length > Math.max(1, minKeep) && total > budget) total -= messageTokens(kept.shift()!)
170
+ // History must open on a user turn: providers reject or drop a leading model turn.
171
+ while (kept.length > 1 && kept[0].role !== "user") total -= messageTokens(kept.shift()!)
172
+ const last = kept[kept.length - 1]
173
+ if (total > budget && typeof last.content === "string") {
174
+ const maxChars = Math.max(400, Math.floor(Math.max(budget, 100) * 4))
175
+ if (last.content.length > maxChars) {
176
+ const half = Math.floor(maxChars / 2)
177
+ kept[kept.length - 1] = {
178
+ ...last,
179
+ content: `${last.content.slice(0, half)}\n[… recortado para caber en la ventana del modelo …]\n${last.content.slice(-half)}`,
180
+ }
181
+ }
182
+ }
183
+ if (kept.length === messages.length && kept[kept.length - 1] === last) return messages
184
+ log.info(`[context-compiler] History trimmed to fit the window: ${messages.length} → ${kept.length} messages (budget ${budget} tokens)`)
185
+ return kept
186
+ }
187
+
149
188
  // ─── Main compiler ─────────────────────────────────────────────────────────
150
189
 
151
190
  /**
@@ -166,6 +205,13 @@ export async function compileContext(opts: {
166
205
  mcpManager?: MCPClientManager | null
167
206
  /** G9 causal stream id for this invocation (agent-loop.ts's causalStreamId). */
168
207
  causalStreamId?: string
208
+ /** A resumed run restores the exact previously selected prompt and loadout. */
209
+ skipJev?: boolean
210
+ /**
211
+ * The window the provider will really read (resolveProviderConfig): the
212
+ * smaller of the model's and, for Ollama, num_ctx. Falls back to the model row.
213
+ */
214
+ contextWindow?: number
169
215
  }): Promise<CompiledContext> {
170
216
  const { agentId, threadId, mcpManager, userMessage, isolated, taskContext } = opts
171
217
 
@@ -211,8 +257,8 @@ export async function compileContext(opts: {
211
257
  log.info(`[context-compiler] [STEP-1] ✅ Compiling for ${isWorker ? 'worker' : 'coordinator'} agent=${agent.name}`)
212
258
 
213
259
  // Load model's context window for compaction decisions
214
- let modelContextWindow = DEFAULT_CONTEXT_WINDOW
215
- if (agent.model_id) {
260
+ let modelContextWindow = opts.contextWindow ?? DEFAULT_CONTEXT_WINDOW
261
+ if (!opts.contextWindow && agent.model_id) {
216
262
  try {
217
263
  const modelsCol = await col<ModelDoc>("models")
218
264
  // Id completo: el recorte del primer segmento fallaba para todo modelo
@@ -505,7 +551,45 @@ export async function compileContext(opts: {
505
551
  // or — on a context-overflow retry that keeps only the LAST system message
506
552
  // (openai-compat-base.ts) — silently replaces the real prompt. The summary
507
553
  // lives in `systemPrompt` instead (see conversationSummarySection below).
508
- const messages: LLMMessage[] = toAPIMessages(recentMessages)
554
+ let messages: LLMMessage[] = toAPIMessages(recentMessages)
555
+ let selectedSkills = allSkills
556
+ let jevAgentId: string | null = null
557
+ let jevAgentMcpOff: string[] = []
558
+ let omittedMessageIds: number[] = []
559
+ let omittedScratchpadKeys: string[] = []
560
+ const objectiveSource = taskContext ?? userMessage
561
+ const objective = typeof objectiveSource === "string" ? objectiveSource
562
+ : objectiveSource.filter((p: ContentPart) => p.type === "text").map((p: ContentPart) => (p as { text: string }).text).join("\n")
563
+ const playbookRules = (await selectPlaybookRules(objective)).filter((rule) => {
564
+ if (!rule.applicable_to || !rule.applicable_to.includes("agent:")) return true
565
+ return isCatalogAgent ? rule.applicable_to.includes(`agent:${agent.id}`) : false
566
+ })
567
+ const swarm = opts.skipJev ? undefined : await describeSwarmCapabilities(effectiveMcpManager, { includeSpecialists: !isWorker })
568
+ .catch((err) => { log.warn(`[context-compiler] Swarm capability map failed: ${(err as Error).message}`); return undefined })
569
+ const jevPlan = opts.skipJev ? null : await planJevContext({
570
+ objective, messages, tools: toolsForLLM, allTools, skills: allSkills, scratchpadNotes, playbookRules, isWorker, swarm,
571
+ }).catch((err) => { log.warn(`[context-compiler] Jev planning failed: ${(err as Error).message}`); return null })
572
+ // Characters the classic path would have sent minus what Jev's plan sends,
573
+ // accumulated section by section; the office shows it as estimated savings.
574
+ let jevSavedChars = 0
575
+ const classicToolCount = toolsForLLM.length
576
+ if (jevPlan) {
577
+ jevSavedChars += JSON.stringify(messages).length - JSON.stringify(jevPlan.messages).length
578
+ jevSavedChars += JSON.stringify(toolsForLLM).length
579
+ messages = jevPlan.messages
580
+ toolsForLLM = jevPlan.tools
581
+ selectedSkills = allSkills.filter(s => minimalSkills.some(m => m.id === s.id) || jevPlan.selectedSkillNames.includes(s.name))
582
+ jevAgentId = jevPlan.agentId
583
+ jevAgentMcpOff = jevPlan.agentMcpOff
584
+ omittedMessageIds = recentMessages.filter((_, i) => !jevPlan.selectedMessageIds.includes(i)).map(row => row.id)
585
+ omittedScratchpadKeys = scratchpadNotes.filter(note => !jevPlan.selectedScratchpadKeys.includes(note.key)).map(note => note.key)
586
+ if (!isWorker && (omittedMessageIds.length > 0 || omittedScratchpadKeys.length > 0) && !toolsForLLM.some(t => t.function.name === "conversation_read")) {
587
+ const reader = allTools.find(t => t.name === "conversation_read")
588
+ if (reader) toolsForLLM.push({ type: "function", function: { name: reader.name, description: reader.description, parameters: reader.parameters } })
589
+ }
590
+ jevSavedChars -= JSON.stringify(toolsForLLM).length
591
+ log.info(`[context-compiler] Jev selected messages=${jevPlan.selectedMessageIds.join(",")} tools=${toolsForLLM.map(t => t.function.name).join(",")} skills=${selectedSkills.map(s => s.name).join(",")} agent=${jevAgentId ?? "coordinator"}`)
592
+ }
509
593
 
510
594
  // [STEP-10] STRATEGY 4: ISOLATE — Build context based on agent role
511
595
  log.info(`[context-compiler] [STEP-10] Building system prompt...`)
@@ -534,33 +618,52 @@ export async function compileContext(opts: {
534
618
  // budget, so a summary appended last would be the first thing silently
535
619
  // dropped on an oversized prompt.
536
620
  systemPrompt += conversationSummarySection
621
+ if (omittedMessageIds.length > 0 || omittedScratchpadKeys.length > 0) {
622
+ const recoverable = `\n\n# CONTEXTO RECUPERABLE\nMensajes previos omitidos: ${omittedMessageIds.join(", ") || "ninguno"}. Notas omitidas: ${omittedScratchpadKeys.join(", ") || "ninguna"}. Si necesitas un dato de ellos, usa conversation_read con message_ids, note_keys o query antes de asumir que falta información.\n`
623
+ systemPrompt += recoverable
624
+ jevSavedChars -= recoverable.length
625
+ }
537
626
 
538
627
  // Only the live roster goes here — how to delegate, fan-out/fan-in and the
539
628
  // execution-truth rules are static doctrine and live in the coordinator's
540
629
  // stored prompt (storage/onboarding.ts), not duplicated per turn.
541
630
  if (!isWorker) {
542
- const routingCatalog = renderAgentRoutingCatalog(await listCatalogAgents())
543
- systemPrompt += `\n\n# COLMENA DE AGENTES\nWorkers disponibles ahora mismo (globales del sistema, ya existen):\n\n${routingCatalog}\n`
631
+ const catalogAgents = await listCatalogAgents()
632
+ const fullCatalog = `\n\n# COLMENA DE AGENTES\nWorkers disponibles ahora mismo (globales del sistema, ya existen):\n\n${renderAgentRoutingCatalog(catalogAgents)}\n`
633
+ if (jevPlan) {
634
+ // Ids, names and MCP state only: without them the coordinator spent
635
+ // iterations on agent_find just to learn who exists and what is
636
+ // connected. Descriptions stay behind agent_find.
637
+ const roster = swarm?.specialists.length
638
+ ? swarm.specialists.map(renderSpecialistLine).join("\n")
639
+ : catalogAgents.map(a => `- ${a.id} (${a.name})`).join("\n")
640
+ let rosterSection = roster ? `\n\n# COLMENA DE AGENTES\nWorkers disponibles (usa agent_find solo si necesitas su descripción). Un MCP "apagado" no está disponible; "disponible" se conecta al primer uso:\n${roster}\n` : ""
641
+ if (jevAgentId && jevAgentMcpOff.length > 0) {
642
+ // Turning a server on starts processes and uses credentials: that is
643
+ // the user's call, so the coordinator asks instead of delegating.
644
+ rosterSection += `\n\n# ESPECIALISTA RECOMENDADO — MCP APAGADO\nJev seleccionó ${jevAgentId} para esta tarea, pero depende de ${jevAgentMcpOff.length === 1 ? "el servidor MCP" : "los servidores MCP"} ${jevAgentMcpOff.join(", ")}, que está${jevAgentMcpOff.length === 1 ? "" : "n"} apagado${jevAgentMcpOff.length === 1 ? "" : "s"}. No lo delegues todavía: dile al usuario que para hacerlo hace falta encender ${jevAgentMcpOff.join(", ")} en Ajustes → Entorno → MCP Servers y que continúas en cuanto quede conectado. Si una parte se puede resolver sin ese MCP, ofrécela.\n`
645
+ } else if (jevAgentId) {
646
+ rosterSection += `\n\n# ESPECIALISTA RECOMENDADO\nJev seleccionó ${jevAgentId} para una subtarea acotada. Delega con task_delegate cuando puedas formular objetivo y criterios verificables.\n`
647
+ }
648
+ systemPrompt += rosterSection
649
+ jevSavedChars += fullCatalog.length - rosterSection.length
650
+ } else {
651
+ systemPrompt += fullCatalog
652
+ }
544
653
  }
545
654
 
546
- const playbookInput = taskContext || userMessage
547
- const playbookText = typeof playbookInput === "string"
548
- ? playbookInput
549
- : Array.isArray(playbookInput)
550
- ? playbookInput.filter((part) => part.type === "text").map((part) => (part as any).text).join("\n")
551
- : String(playbookInput)
552
- const playbookRules = (await selectPlaybookRules(playbookText)).filter((rule) => {
553
- if (!rule.applicable_to || !rule.applicable_to.includes("agent:")) return true
554
- return isCatalogAgent ? rule.applicable_to.includes(`agent:${agent.id}`) : false
555
- })
556
- if (playbookRules.length > 0) {
557
- systemPrompt += `\n\n# PLAYBOOK APRENDIDO\n${playbookRules.map((rule) => `- ${rule.rule}`).join("\n")}\n`
655
+ const selectedPlaybookRules = jevPlan ? playbookRules.filter(rule => jevPlan.selectedPlaybookIds.includes(rule.id)) : playbookRules
656
+ for (const rule of playbookRules) if (!selectedPlaybookRules.includes(rule)) jevSavedChars += rule.rule.length + 3
657
+ if (selectedPlaybookRules.length > 0) {
658
+ systemPrompt += `\n\n# PLAYBOOK APRENDIDO\n${selectedPlaybookRules.map((rule) => `- ${rule.rule}`).join("\n")}\n`
558
659
  }
559
660
 
560
661
  // Inject scratchpad (Strategy: WRITE) — usando TOON para ahorro de tokens
561
- if (scratchpadNotes.length > 0) {
662
+ const selectedScratchpadNotes = jevPlan ? scratchpadNotes.filter(note => jevPlan.selectedScratchpadKeys.includes(note.key)) : scratchpadNotes
663
+ for (const note of scratchpadNotes) if (!selectedScratchpadNotes.includes(note)) jevSavedChars += note.key.length + note.value.length + 4
664
+ if (selectedScratchpadNotes.length > 0) {
562
665
  const scratchpadData: Record<string, string> = {}
563
- for (const n of scratchpadNotes) {
666
+ for (const n of selectedScratchpadNotes) {
564
667
  scratchpadData[n.key] = n.value
565
668
  }
566
669
  // TOON comprime el formato clave-valor
@@ -616,10 +719,10 @@ export async function compileContext(opts: {
616
719
 
617
720
 
618
721
  // Inject available skills (minimal + discovered)
619
- if (allSkills.length > 0) {
722
+ if (selectedSkills.length > 0) {
620
723
  // Minimal skills: inject full body (always-loaded instructions)
621
724
  const minimalNames = new Set(minimalSkills.map(s => s.name))
622
- const minimalWithBody = allSkills.filter(s => minimalNames.has(s.name) && s.body)
725
+ const minimalWithBody = selectedSkills.filter(s => minimalNames.has(s.name) && s.body)
623
726
  if (minimalWithBody.length > 0) {
624
727
  let minimalSection = `\n\n# SKILLS SIEMPRE ACTIVAS\n`
625
728
  for (const skill of minimalWithBody) {
@@ -629,12 +732,23 @@ export async function compileContext(opts: {
629
732
  }
630
733
 
631
734
  // Discovered skills: list only (body arrives via agent-loop when tools are injected)
632
- const discoveredOnly = allSkills.filter(s => !minimalNames.has(s.name))
735
+ const discoveredOnly = selectedSkills.filter(s => !minimalNames.has(s.name))
736
+ if (jevPlan) {
737
+ // Classic lists every discovered skill in one line; Jev inlines the chosen bodies.
738
+ for (const skill of allSkills) {
739
+ if (minimalNames.has(skill.name)) continue
740
+ jevSavedChars += `- **${skill.name}**${skill.description ? ` — ${skill.description}` : ""}\n`.length
741
+ if (discoveredOnly.includes(skill)) jevSavedChars -= skill.body ? `\n## ${skill.name}\n${skill.body}\n`.length : 0
742
+ }
743
+ }
633
744
  if (discoveredOnly.length > 0) {
634
745
  let discoveredSection = `\n\n# SKILLS DESCUBIERTAS (relevantes para esta tarea)\n`
635
746
  for (const skill of discoveredOnly) {
636
- const desc = skill.description ? ` — ${skill.description}` : ""
637
- discoveredSection += `- **${skill.name}**${desc}\n`
747
+ if (jevPlan && skill.body) discoveredSection += `\n## ${skill.name}\n${skill.body}\n`
748
+ else {
749
+ const desc = skill.description ? ` — ${skill.description}` : ""
750
+ discoveredSection += `- **${skill.name}**${desc}\n`
751
+ }
638
752
  }
639
753
  systemPrompt += discoveredSection
640
754
  }
@@ -648,9 +762,9 @@ export async function compileContext(opts: {
648
762
  if (isWorker && opts.taskContext && !isCatalogAgent) {
649
763
  systemPrompt += `\n\n# HERRAMIENTAS DISPONIBLES\n` +
650
764
  `Arrancas con herramientas básicas. Si tu tarea requiere herramientas adicionales (web_search, fs_read, browser_navigate, etc.):\n` +
651
- `1. Usá \`search_knowledge(type="tools", query="<herramienta o tarea>")\` para encontrarlas.\n` +
765
+ `1. Usa \`search_knowledge(type="tools", query="<herramienta o tarea>")\` para encontrarlas.\n` +
652
766
  `2. Las herramientas que encuentres estarán disponibles para usar inmediatamente.\n` +
653
- `Si el coordinador te indicó herramientas específicas, buscalas primero con search_knowledge antes de ejecutar tu tarea.\n` +
767
+ `Si el coordinador te indicó herramientas específicas, búscalas primero con search_knowledge antes de ejecutar tu tarea.\n` +
654
768
  `\n# CURRENT TASK\n${opts.taskContext}\n\nFocus ONLY on this task. Do not deviate.`
655
769
  } else if (isWorker && opts.taskContext) {
656
770
  systemPrompt += `\n\n# CURRENT TASK\n${opts.taskContext}\n\nFocus ONLY on this task and return the required structured delivery.`
@@ -669,6 +783,16 @@ export async function compileContext(opts: {
669
783
  }
670
784
 
671
785
  const estimatedSystemTokens = estimateTokens(systemPrompt)
786
+ const estimatedToolTokensForBudget = toolsForLLM.reduce((sum, t) => sum + estimateTokens(JSON.stringify(t)), 0)
787
+ // History keeps at least a quarter of the window even when instructions and
788
+ // tools alone overflow it: otherwise a small model would lose the whole chat.
789
+ messages = fitMessagesToBudget(
790
+ messages,
791
+ Math.max(
792
+ Math.floor(modelContextWindow * 0.25),
793
+ Math.floor(modelContextWindow * COMPACT_RATIO) - estimatedSystemTokens - estimatedToolTokensForBudget,
794
+ ),
795
+ )
672
796
  const estimatedMsgTokens = messages.reduce((sum, m) => sum + estimateTokens(typeof m.content === 'string' ? m.content : JSON.stringify(m.content)), 0)
673
797
  const estimatedToolTokens = toolsForLLM.reduce((sum, t) => sum + estimateTokens(JSON.stringify(t)), 0)
674
798
  const estimatedTotal = estimatedSystemTokens + estimatedMsgTokens + estimatedToolTokens
@@ -682,13 +806,27 @@ export async function compileContext(opts: {
682
806
  `total=${estimatedTotal}/${modelContextWindow} (${budgetPct}%)`
683
807
  )
684
808
 
809
+ const jevDecision = jevPlan ? {
810
+ summary: [
811
+ `${jevPlan.selectedMessageIds.length}/${recentMessages.length} mensajes`,
812
+ `${toolsForLLM.length}/${classicToolCount} herramientas`,
813
+ `${selectedSkills.length}/${allSkills.length} skills`,
814
+ ].join(" · "),
815
+ savedTokens: Math.round(jevSavedChars / 4),
816
+ latencyMs: jevPlan.decision.latencyMs,
817
+ costUsd: jevPlan.decision.costUsd,
818
+ recommendedAgentId: jevAgentId,
819
+ mcpOff: jevAgentMcpOff,
820
+ } : undefined
821
+
685
822
  return {
686
823
  systemPrompt,
687
824
  conversationSummarySection,
688
825
  messages,
689
826
  tools: toolsForLLM,
690
827
  allTools,
691
- skills: allSkills,
828
+ skills: selectedSkills,
829
+ jevDecision,
692
830
  }
693
831
  }
694
832
 
@@ -11,6 +11,7 @@ import { logger } from "../utils/logger"
11
11
  import type { LLMMessage, ContentPart } from "./llm-client"
12
12
  import { estimateTokens } from "../utils/toon"
13
13
  import type { ConversationDoc, SummaryDoc, MessageSource } from "../storage/collections"
14
+ import { touchThread } from "./thread-store"
14
15
 
15
16
  const log = logger.child("conv-store")
16
17
 
@@ -66,7 +67,7 @@ export function formatInternalEvent(source: string, content: string): string {
66
67
  }
67
68
 
68
69
  return `<hive:internal_event source="${source}">\n` +
69
- `Evento interno del sistema — NO es un mensaje del usuario. No lo cites literalmente, no expongas IDs internos (task_id, worker_id) ni JSON crudo. Respondé al usuario de forma natural y breve.\n\n` +
70
+ `Evento interno del sistema — NO es un mensaje del usuario. No lo cites literalmente, no expongas IDs internos (task_id, worker_id) ni JSON crudo. Responde al usuario de forma natural y breve.\n\n` +
70
71
  `${content}\n` +
71
72
  `</hive:internal_event>`
72
73
  }
@@ -159,6 +160,16 @@ export async function addMessage(
159
160
  bumpRollup("activityRollups", hour, { messageCount: 1 }).catch(() => {})
160
161
  recentMessageTimestamps.push(now)
161
162
 
163
+ // Igual de opcional: el registro de conversaciones es el catálogo que alimenta la
164
+ // lista de la web (título, orden, contador). Se actualiza acá y no en cada llamador
165
+ // para que todo camino que escriba un mensaje —canales, webchat, API, voz— lo
166
+ // mantenga al día sin repetir la llamada.
167
+ touchThread(threadId, {
168
+ role,
169
+ text: textContent,
170
+ internal: isInternalSource(opts?.source),
171
+ }).catch(() => {})
172
+
162
173
  return seq
163
174
  }
164
175
 
@@ -166,7 +166,7 @@ async function judgeCriteriaWithLLM(
166
166
  ...clearOldToolResults(messages),
167
167
  {
168
168
  role: "user",
169
- content: `Evaluá si cada uno de los siguientes criterios de aceptación se cumplió, basándote en la conversación anterior.\n\nCriterios:\n${criteria.map((c) => `- ${c.id}: ${c.description}`).join("\n")}\n\nRespondé en JSON estricto, un resultado por criterio:\n{"results":[{"id":"...","met":true/false,"reason":"explicación breve"}]}`,
169
+ content: `Evalúa si cada uno de los siguientes criterios de aceptación se cumplió, basándote en la conversación anterior.\n\nCriterios:\n${criteria.map((c) => `- ${c.id}: ${c.description}`).join("\n")}\n\nResponde en JSON estricto, un resultado por criterio:\n{"results":[{"id":"...","met":true/false,"reason":"explicación breve"}]}`,
170
170
  },
171
171
  ];
172
172
 
@@ -253,7 +253,7 @@ export async function verifyGoal(
253
253
  ...clearOldToolResults(messages),
254
254
  {
255
255
  role: "user",
256
- content: `Evaluá si el siguiente objetivo ha sido cumplido basándote en la conversación anterior.\n\nObjetivo: "${goal}"\n\nRespondé en JSON:\n{"met": true/false, "reason": "explicación breve"}`,
256
+ content: `Evalúa si el siguiente objetivo ha sido cumplido basándote en la conversación anterior.\n\nObjetivo: "${goal}"\n\nResponde en JSON:\n{"met": true/false, "reason": "explicación breve"}`,
257
257
  },
258
258
  ];
259
259