@johpaz/hive-agents 1.0.5 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. package/README.md +5 -5
  2. package/dist/hive.js +85466 -101014
  3. package/dist/tool-worker.js +13241 -17001
  4. package/dist/ui/assets/A2UIPage-CS0VPY6a.js +8 -0
  5. package/dist/ui/assets/{AgentCreateForm-Bcp3HN8D.js → AgentCreateForm-DXkjtXaS.js} +1 -1
  6. package/dist/ui/assets/AgentDetailPage-DUIX_cuQ.js +1 -0
  7. package/dist/ui/assets/AgentNewPage-SNXz2wik.js +1 -0
  8. package/dist/ui/assets/AgentsPage-CGsdgx5F.js +10 -0
  9. package/dist/ui/assets/{ApiClientPage-DHfIlSAg.js → ApiClientPage-MNMjfSDs.js} +2 -2
  10. package/dist/ui/assets/ChannelsPage-BEwxWUcE.js +8 -0
  11. package/dist/ui/assets/DashboardPage-D6cRFKWW.js +6 -0
  12. package/dist/ui/assets/{LoginPage-BaX6cAPa.js → LoginPage-ByYmIa2p.js} +1 -1
  13. package/dist/ui/assets/LogsPage-Bmk9rohg.js +1 -0
  14. package/dist/ui/assets/MeetingPage-Dm97Mbiw.js +1 -0
  15. package/dist/ui/assets/ModelSelector-gubC8j_Q.js +1 -0
  16. package/dist/ui/assets/NotFound-PUg3gEO0.js +1 -0
  17. package/dist/ui/assets/{Office3DPage-C3SIzd2H.css → Office3DPage-31AMJ-LN.css} +1 -1
  18. package/dist/ui/assets/Office3DPage-Bfi-S2kG.js +727 -0
  19. package/dist/ui/assets/ProvidersPage-CSo0MYxd.js +1 -0
  20. package/dist/ui/assets/{RecoverPage-C_Id9WM-.js → RecoverPage-YY2QU-qh.js} +1 -1
  21. package/dist/ui/assets/SettingsPage-DrafhhKw.js +9 -0
  22. package/dist/ui/assets/SetupPage-LXnd2XbV.js +1 -0
  23. package/dist/ui/assets/{Vignette-Cyi27LQH.js → Vignette-BcPWkNhm.js} +17 -17
  24. package/dist/ui/assets/VoicePage-p-hTMAq7.js +307 -0
  25. package/dist/ui/assets/WebChatPage-B61ZDjQ8.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-BlwA3yd2.js +1 -0
  31. package/dist/ui/assets/dialog-B04KpdNt.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-ByTufXPh.css +2 -0
  35. package/dist/ui/assets/index-DKJFLL3a.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-B2stUHvr.js +41 -0
  46. package/dist/ui/assets/{useHiveAgentsModelLoad-CHmtvNp4.js → useHiveAgentsModelLoad-B4EjHvj4.js} +1 -1
  47. package/dist/ui/assets/useOfficeModel-BaDn7U-X.js +1 -0
  48. package/dist/ui/assets/{useProviders-C7FA6z4M.js → useProviders-B1NS24md.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/core/src/agent/agent-catalog.ts +31 -31
  56. package/packages/core/src/agent/agent-loop.ts +67 -14
  57. package/packages/core/src/agent/capability-search.ts +2 -1
  58. package/packages/core/src/agent/compaction.ts +19 -7
  59. package/packages/core/src/agent/context-compiler.ts +165 -27
  60. package/packages/core/src/agent/conversation-store.ts +12 -1
  61. package/packages/core/src/agent/goal-runner.ts +2 -2
  62. package/packages/core/src/agent/jev-decisions.ts +148 -0
  63. package/packages/core/src/agent/jev-planner.ts +293 -0
  64. package/packages/core/src/agent/llm-client.ts +27 -5
  65. package/packages/core/src/agent/llm-providers/ollama.ts +17 -4
  66. package/packages/core/src/agent/llm-providers/openai-compat-base.ts +27 -12
  67. package/packages/core/src/agent/llm-providers/opencode-go.ts +37 -0
  68. package/packages/core/src/agent/realtime-providers/gemini-live.ts +5 -2
  69. package/packages/core/src/agent/skill-selector.ts +4 -2
  70. package/packages/core/src/agent/thread-id.ts +71 -0
  71. package/packages/core/src/agent/thread-store.ts +230 -0
  72. package/packages/core/src/agent/tool-selector.ts +1 -0
  73. package/packages/core/src/agent/tracer.ts +2 -0
  74. package/packages/core/src/canvas/canvas-manager.ts +17 -1
  75. package/packages/core/src/canvas/emitter.ts +24 -0
  76. package/packages/core/src/channels/telegram.ts +19 -1
  77. package/packages/core/src/channels/webchat.ts +47 -45
  78. package/packages/core/src/config/loader.ts +3 -2
  79. package/packages/core/src/gateway/channel-notify.ts +24 -5
  80. package/packages/core/src/gateway/delegation-groups.ts +3 -3
  81. package/packages/core/src/gateway/delegation-notify.ts +34 -5
  82. package/packages/core/src/gateway/durable-queue.ts +22 -0
  83. package/packages/core/src/gateway/failure-notify.ts +8 -2
  84. package/packages/core/src/gateway/job-executors.ts +3 -3
  85. package/packages/core/src/gateway/realtime/bridge-tools.ts +106 -28
  86. package/packages/core/src/gateway/realtime/index.ts +63 -7
  87. package/packages/core/src/gateway/realtime/prompt.ts +45 -0
  88. package/packages/core/src/gateway/realtime/voice-session.ts +1 -0
  89. package/packages/core/src/gateway/resolver.ts +31 -4
  90. package/packages/core/src/gateway/routes/artifacts.ts +13 -0
  91. package/packages/core/src/gateway/routes/chat.ts +20 -4
  92. package/packages/core/src/gateway/routes/conversations.ts +121 -0
  93. package/packages/core/src/gateway/routes/providers.ts +15 -0
  94. package/packages/core/src/gateway/routes/setup.ts +22 -11
  95. package/packages/core/src/gateway/routes/system.ts +4 -2
  96. package/packages/core/src/gateway/routes/tts-local.ts +2 -1
  97. package/packages/core/src/gateway/server.ts +85 -12
  98. package/packages/core/src/gateway/slash-commands.ts +46 -10
  99. package/packages/core/src/gateway/tts/src/server.ts +2 -1
  100. package/packages/core/src/gateway/webchat-turn.ts +68 -10
  101. package/packages/core/src/index.ts +2 -0
  102. package/packages/core/src/scheduler/CronScheduler.ts +20 -8
  103. package/packages/core/src/scheduler/cron/cron-engine.test.ts +295 -0
  104. package/packages/core/src/scheduler/cron/expression.ts +165 -0
  105. package/packages/core/src/scheduler/cron/index.ts +10 -0
  106. package/packages/core/src/scheduler/cron/job.ts +340 -0
  107. package/packages/core/src/scheduler/cron/next-run.ts +121 -0
  108. package/packages/core/src/scheduler/cron/zoned-time.ts +139 -0
  109. package/packages/core/src/scheduler/integration.ts +16 -5
  110. package/packages/core/src/scheduler/types.ts +3 -18
  111. package/packages/core/src/storage/bootstrap.ts +23 -0
  112. package/packages/core/src/storage/collections.ts +29 -1
  113. package/packages/core/src/storage/crypto.ts +23 -12
  114. package/packages/core/src/storage/reconcile.ts +6 -1
  115. package/packages/core/src/storage/seed.ts +63 -7
  116. package/packages/core/src/storage/usage.ts +53 -1
  117. package/packages/core/src/tool-runtime/index.ts +19 -1
  118. package/packages/core/src/tools/a2ui/index.ts +65 -1
  119. package/packages/core/src/tools/agents/get-available-models.ts +3 -1
  120. package/packages/core/src/tools/core/index.ts +39 -4
  121. package/packages/core/src/tools/cron/index.ts +4 -4
  122. package/packages/core/src/tools/index.ts +1 -1
  123. package/packages/core/src/tools/office/office-escribir-xlsx.ts +2 -1
  124. package/packages/core/src/tools/office/office-leer-xlsx.ts +2 -1
  125. package/packages/core/src/tools/office/xlsx-loader.ts +19 -0
  126. package/packages/core/src/tools/web/webview-backend.ts +140 -20
  127. package/packages/core/src/utils/port.ts +33 -0
  128. package/packages/core/src/voice/index.ts +2 -1
  129. package/packages/mcp/src/config.ts +2 -1
  130. package/packages/mcp/src/manager.ts +9 -0
  131. package/packages/mcp/src/transports/index.ts +42 -1
  132. package/packages/mcp/src/transports/sse.ts +11 -5
  133. package/packages/skills/src/bundled/a2ui/a2ui_dashboard/SKILL.md +2 -2
  134. package/packages/skills/src/bundled/a2ui/a2ui_form/SKILL.md +2 -2
  135. package/packages/skills/src/bundled/a2ui/a2ui_interactive/SKILL.md +4 -4
  136. package/packages/skills/src/bundled/agents/agent_spawner/SKILL.md +7 -7
  137. package/packages/skills/src/bundled/agents/memory_manager/SKILL.md +9 -9
  138. package/packages/skills/src/bundled/agents/research_and_remember/SKILL.md +8 -8
  139. package/packages/skills/src/bundled/agents/task_orchestrator/SKILL.md +8 -8
  140. package/packages/skills/src/bundled/artifacts/artifact_reader/SKILL.md +104 -0
  141. package/packages/skills/src/bundled/cli/cli_pipeline/SKILL.md +6 -6
  142. package/packages/skills/src/bundled/cli/cli_safe_exec/SKILL.md +5 -5
  143. package/packages/skills/src/bundled/cron_manager/SKILL.md +29 -19
  144. package/packages/skills/src/bundled/cron_reminder/SKILL.md +5 -5
  145. package/packages/skills/src/bundled/filesystem/file_manager/SKILL.md +4 -4
  146. package/packages/skills/src/bundled/filesystem/file_read_and_summarize/SKILL.md +7 -7
  147. package/packages/skills/src/bundled/filesystem/file_writer/SKILL.md +10 -10
  148. package/packages/skills/src/bundled/search_knowledge/capability_discovery/SKILL.md +8 -8
  149. package/packages/skills/src/bundled/web/browser_automate/SKILL.md +21 -12
  150. package/packages/skills/src/bundled/web/browser_scrape/SKILL.md +28 -13
  151. package/packages/skills/src/bundled/web/web_monitor/SKILL.md +6 -6
  152. package/packages/skills/src/bundled/web/web_research/SKILL.md +5 -5
  153. package/packages/skills/src/bundled-data.generated.ts +837 -783
  154. package/dist/ui/assets/A2UIPage-DTW79pyL.js +0 -8
  155. package/dist/ui/assets/AgentDetailPage-10XptMde.js +0 -1
  156. package/dist/ui/assets/AgentNewPage-CUt49rVS.js +0 -1
  157. package/dist/ui/assets/AgentsPage-1_e1a9xa.js +0 -10
  158. package/dist/ui/assets/ChannelsPage-BnCQAGZL.js +0 -8
  159. package/dist/ui/assets/DashboardPage-BsCCKHgg.js +0 -6
  160. package/dist/ui/assets/LogsPage-DiFBQt7o.js +0 -1
  161. package/dist/ui/assets/MeetingPage-Bpv5zVXf.js +0 -1
  162. package/dist/ui/assets/ModelSelector-DfExlPzx.js +0 -1
  163. package/dist/ui/assets/NotFound-C8HBdF73.js +0 -1
  164. package/dist/ui/assets/Office3DPage-ChsGMapf.js +0 -319
  165. package/dist/ui/assets/ProvidersPage-B39pfWHf.js +0 -1
  166. package/dist/ui/assets/SettingsPage-BgFqasyg.js +0 -9
  167. package/dist/ui/assets/SetupPage-YeJFfgbt.js +0 -1
  168. package/dist/ui/assets/VoicePage-Cp63Abj4.js +0 -307
  169. package/dist/ui/assets/WebChatPage-DxFLWgtM.js +0 -29
  170. package/dist/ui/assets/agentCapabilities-DOeepCty.js +0 -1
  171. package/dist/ui/assets/alert-Cj4DpKv6.js +0 -1
  172. package/dist/ui/assets/badge-DKpeVCpY.js +0 -1
  173. package/dist/ui/assets/card-Cag15G4h.js +0 -1
  174. package/dist/ui/assets/dialog-7E3EoEt3.js +0 -1
  175. package/dist/ui/assets/dist-js-DwLn9F4C.js +0 -1
  176. package/dist/ui/assets/index-Bi8qEmrK.js +0 -116
  177. package/dist/ui/assets/index-D2UhaSb0.css +0 -2
  178. package/dist/ui/assets/label-C6atPuIh.js +0 -1
  179. package/dist/ui/assets/pencil-CUbpCfeG.js +0 -1
  180. package/dist/ui/assets/scroll-area-CSoG2z53.js +0 -1
  181. package/dist/ui/assets/select-DlCT21_r.js +0 -1
  182. package/dist/ui/assets/slider-Bb_PHFJT.js +0 -1
  183. package/dist/ui/assets/switch-CUsGuBNi.js +0 -1
  184. package/dist/ui/assets/tabs-Ckfc7DGG.js +0 -1
  185. package/dist/ui/assets/textarea-BH6pI9Ax.js +0 -1
  186. package/dist/ui/assets/useAudioDevices-Dpr_hn6i.js +0 -41
  187. package/dist/ui/assets/useOfficeModel-Cc5VkReZ.js +0 -1
  188. package/dist/ui/assets/vendor-react-DYyYpuMy.js +0 -1
  189. /package/dist/ui/assets/{core-Dz04EE_8.js → core-B_5cyOSV.js} +0 -0
  190. /package/dist/ui/assets/{download-D0aDV8Y_.js → download-BQXrpH0m.js} +0 -0
  191. /package/dist/ui/assets/{ellipsis-vertical-BOW_iEOO.js → ellipsis-vertical-D7uFJLGh.js} +0 -0
  192. /package/dist/ui/assets/{external-link-5cujQzfV.js → external-link-6oTH9pUM.js} +0 -0
  193. /package/dist/ui/assets/{eye-sRPY5qOa.js → eye-CxvxtQT5.js} +0 -0
  194. /package/dist/ui/assets/{file-text-DNSyNLUh.js → file-text-D5ZJEx3E.js} +0 -0
  195. /package/dist/ui/assets/{gateway-url-BzQV75Ig.js → gateway-url-BALS_wVh.js} +0 -0
  196. /package/dist/ui/assets/{gauge-C__zxC3_.js → gauge-CEu7PhTW.js} +0 -0
  197. /package/dist/ui/assets/{history-BHQWfE-7.js → history-DLK5rTlP.js} +0 -0
  198. /package/dist/ui/assets/{info-CG1VohyH.js → info-8ReWzubE.js} +0 -0
  199. /package/dist/ui/assets/{key-BC28VCjO.js → key-DPkOY-J0.js} +0 -0
  200. /package/dist/ui/assets/{lock-open-Bhp0UJlL.js → lock-open-v0EphssG.js} +0 -0
  201. /package/dist/ui/assets/{mail-Biwn8WrV.js → mail-vwCEHyhQ.js} +0 -0
  202. /package/dist/ui/assets/{mic-Rq4BxU1R.js → mic-CpDU_2as.js} +0 -0
  203. /package/dist/ui/assets/{pause-C2l5G2Py.js → pause-Cm9LzIZK.js} +0 -0
  204. /package/dist/ui/assets/{play-CMAscR3a.js → play-zqogwA2l.js} +0 -0
  205. /package/dist/ui/assets/{plus-DzvRxH4U.js → plus-Bm08ABhc.js} +0 -0
  206. /package/dist/ui/assets/{radio-DfGzov4y.js → radio-Cii1BjMt.js} +0 -0
  207. /package/dist/ui/assets/{refresh-cw-DZXu5FrG.js → refresh-cw-DXv3XgEt.js} +0 -0
  208. /package/dist/ui/assets/{rotate-ccw-Dx92orJM.js → rotate-ccw-LoM1AuqK.js} +0 -0
  209. /package/dist/ui/assets/{search-DB4w9YHW.js → search-BMwCI-pX.js} +0 -0
  210. /package/dist/ui/assets/{send-xi8HzUdc.js → send-D6fgWV7m.js} +0 -0
  211. /package/dist/ui/assets/{settings-pV0cF8Kf.js → settings-qV3kVkeG.js} +0 -0
  212. /package/dist/ui/assets/{shield-nLNsomh_.js → shield-CIarwBvx.js} +0 -0
  213. /package/dist/ui/assets/{sparkles-CerRDYxk.js → sparkles-DVvY6jDT.js} +0 -0
  214. /package/dist/ui/assets/{square-CcWzRWyG.js → square-D5zdNkAY.js} +0 -0
  215. /package/dist/ui/assets/{terminal-C2SUZUAD.js → terminal-BEcTK780.js} +0 -0
  216. /package/dist/ui/assets/{trash-2-BZsMCfso.js → trash-2-D6oziYAK.js} +0 -0
  217. /package/dist/ui/assets/{utils-lc8H6VGT.js → utils-DEmd_M8c.js} +0 -0
  218. /package/dist/ui/assets/{vendor-router-DCsSv_I7.js → vendor-router-DP84b3LQ.js} +0 -0
  219. /package/dist/ui/assets/{volume-2-CBMYsuF3.js → volume-2-EaA0JRvD.js} +0 -0
  220. /package/dist/ui/assets/{volume-x-vNFf2e4-.js → volume-x-CROXNMGT.js} +0 -0
  221. /package/dist/ui/assets/{wifi-DNv53AfN.js → wifi-BUJuOcgP.js} +0 -0
  222. /package/dist/ui/assets/{zap-Yed86Sh8.js → zap-DSoX9NDk.js} +0 -0
@@ -57,7 +57,7 @@ export async function calculateCost(
57
57
  const key = `${provider}/${model}`;
58
58
  if (!unpricedModels.has(key)) {
59
59
  unpricedModels.add(key);
60
- log.warn(`[usage] Sin tarifa para ${key} — su costo se contará como $0. Agregá inputPer1M/outputPer1M en SEED_DATA.models (storage/seed.ts).`);
60
+ log.warn(`[usage] Sin tarifa para ${key} — su costo se contará como $0. Agrega inputPer1M/outputPer1M en SEED_DATA.models (storage/seed.ts).`);
61
61
  }
62
62
  return 0;
63
63
  }
@@ -154,6 +154,15 @@ export interface UsageRecord {
154
154
  created_at: number;
155
155
  }
156
156
 
157
+ export interface JevUsageSummary {
158
+ decisions: number;
159
+ costUsd: number;
160
+ /** Estimated main-model input tokens avoided; negative when Jev added more than it removed. */
161
+ savedTokens: number;
162
+ savedCostUsd: number;
163
+ byAgent: Record<string, { decisions: number; costUsd: number; savedTokens: number; savedCostUsd: number }>;
164
+ }
165
+
157
166
  export interface UsageSummary {
158
167
  totalTokens: number;
159
168
  totalInputTokens: number;
@@ -168,6 +177,7 @@ export interface UsageSummary {
168
177
  toonSavingsPercent: number;
169
178
  byProvider: Record<string, { tokens: number; costUsd: number; inputTokens: number; outputTokens: number }>;
170
179
  byModel: Record<string, { tokens: number; costUsd: number; provider: string; inputTokens: number; outputTokens: number }>;
180
+ jev: JevUsageSummary;
171
181
  recentRecords: UsageRecord[];
172
182
  }
173
183
 
@@ -240,6 +250,7 @@ export async function getUsageStats(hours: number = 24): Promise<UsageSummary> {
240
250
  let totalInput = 0, totalOutput = 0, totalCost = 0;
241
251
  let toonSavedTokens = 0, toonSavedCost = 0, toonSavedBytes = 0;
242
252
  let toonJsonTokens = 0, toonToonTokens = 0, toonJsonBytes = 0;
253
+ const jev: JevUsageSummary = { decisions: 0, costUsd: 0, savedTokens: 0, savedCostUsd: 0, byAgent: {} };
243
254
 
244
255
  for (const r of rollups) {
245
256
  totalInput += r.inputTokens;
@@ -251,6 +262,18 @@ export async function getUsageStats(hours: number = 24): Promise<UsageSummary> {
251
262
  toonJsonTokens += r.toonJsonTokens;
252
263
  toonToonTokens += r.toonToonTokens;
253
264
  toonJsonBytes += r.toonJsonBytes;
265
+ jev.decisions += r.jevDecisions ?? 0;
266
+ jev.costUsd += r.jevCostUsd ?? 0;
267
+ jev.savedTokens += r.jevSavedTokens ?? 0;
268
+ jev.savedCostUsd += r.jevSavedCostUsd ?? 0;
269
+ for (const [agentId, a] of Object.entries(r.jevByAgent ?? {})) {
270
+ const cur = jev.byAgent[agentId] ?? { decisions: 0, costUsd: 0, savedTokens: 0, savedCostUsd: 0 };
271
+ cur.decisions += a.jevDecisions ?? 0;
272
+ cur.costUsd += a.jevCostUsd ?? 0;
273
+ cur.savedTokens += a.jevSavedTokens ?? 0;
274
+ cur.savedCostUsd += a.jevSavedCostUsd ?? 0;
275
+ jev.byAgent[agentId] = cur;
276
+ }
254
277
 
255
278
  for (const [provider, p] of Object.entries(r.byProvider ?? {})) {
256
279
  const cur = providerMap[provider] ?? { tokens: 0, costUsd: 0, inputTokens: 0, outputTokens: 0 };
@@ -301,10 +324,39 @@ export async function getUsageStats(hours: number = 24): Promise<UsageSummary> {
301
324
  toonSavingsPercent,
302
325
  byProvider: providerMap,
303
326
  byModel: modelMap,
327
+ jev,
304
328
  recentRecords
305
329
  };
306
330
  }
307
331
 
332
+ /**
333
+ * Persists one Jev decision into the hourly rollup. The avoided tokens are
334
+ * priced with the advised agent's own model (input rate), through the same
335
+ * catalog lookup as real usage, so "saved" and "spent" are comparable.
336
+ */
337
+ export function recordJevDecision(options: {
338
+ agentId: string;
339
+ provider: string;
340
+ model: string;
341
+ savedTokens: number;
342
+ costUsd: number;
343
+ }): void {
344
+ Promise.resolve().then(async () => {
345
+ try {
346
+ const unitCost = await calculateCost(options.provider, options.model, Math.abs(options.savedTokens), 0);
347
+ const savedCostUsd = Math.sign(options.savedTokens) * unitCost;
348
+ await bumpRollup("usageRollups", hourBucket(Date.now()), {
349
+ jevDecisions: 1,
350
+ jevCostUsd: options.costUsd,
351
+ jevSavedTokens: options.savedTokens,
352
+ jevSavedCostUsd: savedCostUsd,
353
+ }, { field: "jevByAgent", key: options.agentId });
354
+ } catch (error) {
355
+ log.warn(`[JEV] Failed to record decision:`, error);
356
+ }
357
+ });
358
+ }
359
+
308
360
  /**
309
361
  * Record TOON savings for metrics tracking
310
362
  * This updates the usage_records table with complete TOON compression metrics
@@ -46,6 +46,8 @@ export type ExecuteToolBatchOptions = {
46
46
  }
47
47
  hiveConfig?: Config
48
48
  workerPool?: ToolRuntimeConfig
49
+ /** Per-batch decision. Undefined preserves the configured legacy behavior. */
50
+ parallelToolCalls?: boolean
49
51
  mainThreadToolNames?: string[]
50
52
  signal?: AbortSignal
51
53
  }
@@ -198,6 +200,7 @@ const DEFAULT_MAIN_THREAD_TOOL_NAMES = new Set([
198
200
  // These tools depend on process-local singleton state (HiveDB handle, live
199
201
  // channel senders, schedulers, browser sessions, or in-memory services).
200
202
  "search_knowledge",
203
+ "conversation_read",
201
204
  "save_note",
202
205
  "memory_write",
203
206
  "memory_read",
@@ -597,6 +600,7 @@ function getPool(maxWorkers: number): ToolWorkerPool | null {
597
600
 
598
601
  export async function executeToolBatch(options: ExecuteToolBatchOptions): Promise<ToolBatchResult[]> {
599
602
  const runtimeConfig = resolveRuntimeConfig(options.workerPool)
603
+ const parallelToolCalls = options.parallelToolCalls ?? runtimeConfig.parallelToolCalls
600
604
  const hiveConfig = options.hiveConfig ?? loadConfig()
601
605
  const mainThreadToolNames = [
602
606
  ...DEFAULT_MAIN_THREAD_TOOL_NAMES,
@@ -617,11 +621,25 @@ export async function executeToolBatch(options: ExecuteToolBatchOptions): Promis
617
621
 
618
622
  // A null pool means workers are disabled, unnecessary (single call), or
619
623
  // unavailable in this build — all three degrade to the main thread.
620
- const pool = runtimeConfig.enabled && runtimeConfig.parallelToolCalls && options.toolCalls.length > 1
624
+ const pool = runtimeConfig.enabled && parallelToolCalls && options.toolCalls.length > 1
621
625
  ? getPool(runtimeConfig.maxWorkers)
622
626
  : null
623
627
 
624
628
  if (!pool) {
629
+ if (options.parallelToolCalls === true && options.toolCalls.length > 1) {
630
+ return Promise.all(options.toolCalls.map(async (toolCall) => {
631
+ const startedAt = performance.now()
632
+ const effectiveTimeout = resolveToolTimeout(toolCall.function.name, options.allTools, hiveConfig, runtimeConfig.toolTimeoutMs)
633
+ const result = await executeInMainThreadWithTimeout({
634
+ toolCall, allTools: options.allTools, toolConfig: options.toolConfig, signal: options.signal,
635
+ }, effectiveTimeout)
636
+ return {
637
+ toolCall, toolName: toolCall.function.name, result,
638
+ ok: !(result && typeof result === "object" && (result as any).error === true),
639
+ durationMs: Math.round(performance.now() - startedAt),
640
+ }
641
+ }))
642
+ }
625
643
  const results: ToolBatchResult[] = []
626
644
  for (const toolCall of options.toolCalls) {
627
645
  const startedAt = performance.now()
@@ -1,8 +1,62 @@
1
1
  import type { Tool } from "../types.ts";
2
2
  import type { Config } from "../../config/loader.ts";
3
- import { canvasManager } from "../../canvas/canvas-manager.ts";
3
+ import { canvasManager, mergeComponentsById } from "../../canvas/canvas-manager.ts";
4
4
  import { logger } from "../../utils/logger.ts";
5
5
 
6
+ /** Ids a component renders, in both the flat and the nested (`{ Card: {...} }`) forms. */
7
+ function childIds(component: Record<string, unknown>): string[] {
8
+ const nested = component.component && typeof component.component === "object" && !Array.isArray(component.component)
9
+ ? Object.values(component.component as Record<string, unknown>)[0]
10
+ : undefined
11
+ const c = nested && typeof nested === "object" ? { ...component, ...(nested as Record<string, unknown>) } : component
12
+ const ids: unknown[] = []
13
+ const children = c.children
14
+ if (typeof children === "string") ids.push(children)
15
+ else if (Array.isArray(children)) ids.push(...children)
16
+ else if (children && typeof children === "object") {
17
+ const ch = children as Record<string, unknown>
18
+ if (Array.isArray(ch.explicitList)) ids.push(...ch.explicitList)
19
+ if (Array.isArray(ch.array)) ids.push(...ch.array)
20
+ ids.push(ch.componentId, (ch.template as Record<string, unknown> | undefined)?.componentId)
21
+ }
22
+ ids.push(c.child, c.trigger, c.content, c.entryPointChild, c.contentChild)
23
+ for (const tab of [...(Array.isArray(c.tabItems) ? c.tabItems : []), ...(Array.isArray(c.tabs) ? c.tabs : [])]) {
24
+ ids.push((tab as Record<string, unknown> | null)?.child)
25
+ }
26
+ return ids.filter((id): id is string => typeof id === "string" && id.length > 0)
27
+ }
28
+
29
+ /**
30
+ * First cycle in the component tree ("card -> card"), or null. A component
31
+ * that contains itself or an ancestor made the panel recurse until the
32
+ * browser killed the tab.
33
+ */
34
+ export function findComponentCycle(components: unknown[]): string[] | null {
35
+ const graph = new Map<string, string[]>()
36
+ for (const c of components) {
37
+ if (c && typeof c === "object" && typeof (c as { id?: unknown }).id === "string") {
38
+ graph.set((c as { id: string }).id, childIds(c as Record<string, unknown>))
39
+ }
40
+ }
41
+ const done = new Set<string>()
42
+ const visit = (id: string, path: string[]): string[] | null => {
43
+ const loop = path.indexOf(id)
44
+ if (loop >= 0) return [...path.slice(loop), id]
45
+ if (done.has(id) || !graph.has(id)) return null
46
+ for (const child of graph.get(id)!) {
47
+ const cycle = visit(child, [...path, id])
48
+ if (cycle) return cycle
49
+ }
50
+ done.add(id)
51
+ return null
52
+ }
53
+ for (const id of graph.keys()) {
54
+ const cycle = visit(id, [])
55
+ if (cycle) return cycle
56
+ }
57
+ return null
58
+ }
59
+
6
60
  export function createA2UISurfaceTool(_config: Config): Tool {
7
61
  const log = logger.child("a2ui-surface");
8
62
 
@@ -148,6 +202,16 @@ Root component: usar id="root" explícito.`,
148
202
  ? (rawSessionId.startsWith("canvas:") ? rawSessionId : `canvas:${rawSessionId}`)
149
203
  : (userId ? `canvas:${userId}` : (() => { throw new Error("No session or user ID provided"); })());
150
204
 
205
+ if (!Array.isArray(params.components)) throw new Error("components must be an array")
206
+ // Checked on the merged tree the client will render, not only this batch.
207
+ const cycle = findComponentCycle(mergeComponentsById(
208
+ canvasManager.getCachedComponents(sessionId, params.surfaceId as string),
209
+ params.components,
210
+ ))
211
+ if (cycle) {
212
+ throw new Error(`Ciclo en los componentes: ${cycle.join(" -> ")}. Un componente no puede contenerse a sí mismo ni a un ancestro. Dale al hijo un id propio (por ejemplo "${cycle[0]}_contenido") y vuelve a enviar. No se publicó nada.`)
213
+ }
214
+
151
215
  await canvasManager.sendA2UIMessage(sessionId, "a2ui:updateComponents", {
152
216
  surfaceId: params.surfaceId as string,
153
217
  components: params.components,
@@ -60,7 +60,9 @@ export const getAvailableModelsTool: Tool = {
60
60
  .filter(m => m.enabled && providersById.has(m.provider_id));
61
61
 
62
62
  if (providerId) models = models.filter(m => m.provider_id === providerId);
63
- if (modelType) models = models.filter(m => m.model_type === modelType);
63
+ // Decision models (Jev) only answer the Decisions API, never chat: an
64
+ // agent assigned one would fail every turn.
65
+ models = modelType ? models.filter(m => m.model_type === modelType) : models.filter(m => m.model_type !== "decision");
64
66
  if (capabilities) models = models.filter(m => (m.capabilities ?? "").includes(capabilities));
65
67
 
66
68
  // Transformar a formato amigable
@@ -14,7 +14,7 @@ import {
14
14
  type CapabilityType,
15
15
  } from "../../agent/capability-search.ts";
16
16
  import { CORE_TOOL_CATALOG } from "../../agent/tool-selector.ts";
17
- import { saveScratchpadNote } from "../../agent/conversation-store.ts";
17
+ import { saveScratchpadNote, getRecentMessages, getScratchpad } from "../../agent/conversation-store.ts";
18
18
 
19
19
  const log = logger.child("core");
20
20
 
@@ -353,7 +353,9 @@ export const notifyTool: Tool = {
353
353
 
354
354
  log.info(`[notify] Sending to ${channel}/${userId}: ${message.substring(0, 80)}`);
355
355
 
356
- const result = await sendToUserChannel(channel, userId, message)
356
+ const threadId = config?.configurable?.thread_id as string | undefined;
357
+
358
+ const result = await sendToUserChannel(channel, userId, message, { threadId })
357
359
  if (!result.ok) throw new Error(`Channel send failed: ${result.error}`)
358
360
  return result
359
361
  },
@@ -448,13 +450,46 @@ export const reportProgressTool: Tool = {
448
450
 
449
451
  // Send real-time update to the user's channel
450
452
  const progressEmoji = progress >= 100 ? "✅" : progress >= 50 ? "⚙️" : "🔄";
451
- const result = await sendToUserChannel(channel, userId, `${progressEmoji} ${progress}% — ${message}`)
453
+ const result = await sendToUserChannel(channel, userId, `${progressEmoji} ${progress}% — ${message}`, {
454
+ threadId: config?.configurable?.thread_id as string | undefined,
455
+ })
452
456
  if (!result.ok) throw new Error(`Channel send failed: ${result.error}`)
453
457
 
454
458
  return { ok: true, progress, message, task_id: taskId };
455
459
  },
456
460
  };
457
461
 
462
+ /** Recover a small, scoped slice of conversation omitted by Jev's context plan. */
463
+ export const conversationReadTool: Tool = {
464
+ name: "conversation_read",
465
+ description: "Read earlier messages from the current conversation by message IDs or text query when selected context is insufficient.",
466
+ parameters: {
467
+ type: "object",
468
+ properties: {
469
+ message_ids: { type: "array", description: "Message IDs shown in the context plan", items: { type: "number" } },
470
+ note_keys: { type: "array", description: "Scratchpad note keys shown in the context plan", items: { type: "string" } },
471
+ query: { type: "string", description: "Optional case-insensitive text to search in earlier messages" },
472
+ },
473
+ },
474
+ execute: async (params, config) => {
475
+ const threadId = config?.configurable?.thread_id as string | undefined
476
+ if (!threadId) return { ok: false, error: "Conversation scope unavailable" }
477
+ const ids = new Set(Array.isArray(params.message_ids) ? params.message_ids.map(Number).filter(Number.isFinite) : [])
478
+ const noteKeys = new Set(Array.isArray(params.note_keys) ? params.note_keys.map(String) : [])
479
+ const query = String(params.query ?? "").trim().toLocaleLowerCase()
480
+ if (!ids.size && !noteKeys.size && !query) return { ok: false, error: "Provide message_ids, note_keys or query" }
481
+ const rows = await getRecentMessages(threadId, 200)
482
+ const notes = await getScratchpad(threadId)
483
+ return {
484
+ ok: true,
485
+ messages: rows.filter(row => (ids.size && ids.has(row.id)) || (query && row.content.toLocaleLowerCase().includes(query)))
486
+ .slice(-8).map(row => ({ id: row.id, role: row.role, source: row.source, content: row.content.slice(0, 2000) })),
487
+ notes: notes.filter(note => noteKeys.has(note.key) || (query && `${note.key} ${note.value}`.toLocaleLowerCase().includes(query)))
488
+ .slice(0, 8).map(note => ({ key: note.key, value: note.value.slice(0, 2000) })),
489
+ }
490
+ },
491
+ };
492
+
458
493
  export function createTools(): Tool[] {
459
- return [searchKnowledgeTool, notifyTool, saveNoteTool, reportProgressTool];
494
+ return [searchKnowledgeTool, notifyTool, saveNoteTool, reportProgressTool, conversationReadTool];
460
495
  }
@@ -12,7 +12,7 @@ import type { Tool } from "../types";
12
12
  import { col, toIndexable } from "../../storage/hive";
13
13
  import type { UserDoc, UserIdentityDoc, ChannelDoc, CronJobDoc, TaskRunDoc } from "../../storage/collections";
14
14
  import { logger } from "../../utils/logger";
15
- import { Cron } from "croner";
15
+ import { Cron } from "../../scheduler/cron";
16
16
 
17
17
  const log = logger.child("CronTools");
18
18
 
@@ -114,9 +114,9 @@ export const cronCreateTool: Tool = {
114
114
  tool_name: { type: "string", description: "Specific tool to execute (optional)" },
115
115
  max_runs: { type: "number", description: "Maximum executions (optional, null = unlimited)" },
116
116
  channel: { type: "string", description: "Notification channel (system, telegram, discord, whatsapp, cli)" },
117
- start_at: { type: "string", description: "ISO 8601 datetime: start of execution window (Croner startAt). Optional." },
118
- stop_at: { type: "string", description: "ISO 8601 datetime: end of execution window (Croner stopAt). Optional." },
119
- dom_and_dow: { type: "boolean", description: "If true, both day-of-month AND day-of-week must match (Croner domAndDow). Default: false (OR logic)" },
117
+ start_at: { type: "string", description: "ISO 8601 datetime: start of execution window. Optional." },
118
+ stop_at: { type: "string", description: "ISO 8601 datetime: end of execution window. Optional." },
119
+ dom_and_dow: { type: "boolean", description: "If true, both day-of-month AND day-of-week must match. Default: false (OR logic)" },
120
120
  },
121
121
  required: ["name", "task", "task_type"],
122
122
  },
@@ -14,7 +14,7 @@ import * as filesystem from "./filesystem/index.ts";
14
14
  // Web (11)
15
15
  import * as web from "./web/index.ts";
16
16
 
17
- // Cron (8) - Croner-based scheduler tools
17
+ // Cron (8) - scheduler tools
18
18
  import * as cron from "./cron/index.ts";
19
19
 
20
20
  // CLI (1)
@@ -10,6 +10,7 @@ import type { Tool } from "../types.ts";
10
10
  import { logger } from "../../utils/logger.ts";
11
11
  import * as path from "node:path";
12
12
  import * as fs from "node:fs";
13
+ import { cargarXlsx } from "./xlsx-loader";
13
14
 
14
15
  const log = logger.child("office-escribir-xlsx");
15
16
 
@@ -55,7 +56,7 @@ export const officeEscribirXlsxTool: Tool = {
55
56
  log.debug(`Generando XLSX: ${ruta}`);
56
57
 
57
58
  try {
58
- const XLSX = await import("xlsx");
59
+ const XLSX = await cargarXlsx();
59
60
 
60
61
  const workbook = XLSX.utils.book_new();
61
62
 
@@ -10,6 +10,7 @@ import type { Tool } from "../types.ts";
10
10
  import { logger } from "../../utils/logger.ts";
11
11
  import * as fs from "node:fs";
12
12
  import * as path from "node:path";
13
+ import { cargarXlsx } from "./xlsx-loader";
13
14
 
14
15
  const log = logger.child("office-leer-xlsx");
15
16
 
@@ -55,7 +56,7 @@ export const officeLeerXlsxTool: Tool = {
55
56
  return { ok: false, error: `Archivo no encontrado: ${rutaAbsoluta}` };
56
57
  }
57
58
 
58
- const XLSX = await import("xlsx");
59
+ const XLSX = await cargarXlsx();
59
60
  const buffer = fs.readFileSync(rutaAbsoluta);
60
61
  const workbook = XLSX.read(buffer, { type: "buffer" });
61
62
 
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Carga el lector de hojas de cálculo, o explica por qué no puede.
3
+ *
4
+ * `xlsx` se importa en caliente para no pagarlo en cada arranque, y eso deja el
5
+ * fallo a merced del momento: si la dependencia no llegó a instalarse —su
6
+ * tarball se cayó una vez en mitad de un release— el usuario recibía un
7
+ * "Cannot find module" crudo en medio de una respuesta.
8
+ */
9
+ export async function cargarXlsx(): Promise<typeof import("xlsx")> {
10
+ try {
11
+ return await import("xlsx");
12
+ } catch (error) {
13
+ throw new Error(
14
+ "El soporte de hojas de cálculo no está disponible en esta instalación: " +
15
+ `falta la dependencia «xlsx» (${(error as Error).message}). ` +
16
+ "Reinstala las dependencias con `bun install` para recuperarlo.",
17
+ );
18
+ }
19
+ }
@@ -22,7 +22,12 @@
22
22
 
23
23
  import { logger } from "../../utils/logger.ts";
24
24
  import { resolveWebViewEngine, type BrowserBackend, type ScreenshotOptions, type SnapshotOptions, type WebViewEngine } from "./browser-backend.ts";
25
- import { loadStoredCookies, sessionPersistenceEnabled, storeCookies } from "./browser-session.ts";
25
+ import {
26
+ loadStoredCookies,
27
+ sessionPersistenceEnabled,
28
+ storeCookies,
29
+ type StoredCookie,
30
+ } from "./browser-session.ts";
26
31
 
27
32
  const log = logger.child("webview-backend");
28
33
 
@@ -36,6 +41,85 @@ const SNAPSHOT_CHAR_LIMIT = 20_000;
36
41
  */
37
42
  const SESSION_SAVE_DEBOUNCE_MS = 3_000;
38
43
 
44
+ /** Intentos de restaurar la sesión dentro de una misma navegación, y la espera entre ellos. */
45
+ const RESTORE_INTENTOS = 3;
46
+ const RESTORE_ESPERA_MS = 150;
47
+
48
+ /** Navegaciones que pueden pagar un reintento antes de darse por vencido. */
49
+ const RESTORE_LLAMADAS = 2;
50
+
51
+ /** Identidad de una cookie: nombre + dominio + valor. */
52
+ const clave = (name: string, domain: string, value: string): string =>
53
+ JSON.stringify([name, domain, value]);
54
+
55
+ /**
56
+ * Cuántas de las cookies guardadas quedaron realmente en el navegador.
57
+ *
58
+ * `Network.setCookies` puede responder sin error y no dejar nada —el target
59
+ * todavía no está listo—, así que la única señal confiable es leer de vuelta.
60
+ * Se comparan nombre, dominio y valor: una cookie con el mismo nombre pero otro
61
+ * valor es una cookie vieja del perfil, no la sesión que se quería restaurar.
62
+ */
63
+ export function contarRestauradas(enElNavegador: unknown[] | undefined, esperadas: StoredCookie[]): number {
64
+ if (!Array.isArray(enElNavegador)) return 0;
65
+ const presentes = new Set(
66
+ enElNavegador
67
+ .filter((c): c is Record<string, unknown> => typeof c === "object" && c !== null)
68
+ .map((c) => clave(String(c.name), String(c.domain), String(c.value))),
69
+ );
70
+ return esperadas.filter((c) => presentes.has(clave(c.name, c.domain, c.value))).length;
71
+ }
72
+
73
+ /** Lo que la restauración necesita de una vista: navegar y hablar CDP. */
74
+ interface VistaRestaurable {
75
+ navigate(url: string): Promise<void>;
76
+ cdp(method: string, params?: Record<string, unknown>): Promise<unknown>;
77
+ }
78
+
79
+ /**
80
+ * Pone las cookies guardadas y comprueba que quedaran, reintentando.
81
+ *
82
+ * Vive fuera de la clase para poder probarla sin abrir un navegador: el motor
83
+ * real llega por `correr`, que es la cola de la vista.
84
+ */
85
+ export async function restaurarCookiesEnVista(
86
+ cookies: StoredCookie[],
87
+ correr: <T>(operacion: (vista: VistaRestaurable) => Promise<T>) => Promise<T>,
88
+ ): Promise<{ restaurada: boolean; puestas: number; intentos: number }> {
89
+ let intentos = 0;
90
+
91
+ for (let intento = 1; intento <= RESTORE_INTENTOS; intento++) {
92
+ intentos = intento;
93
+ try {
94
+ const puestas = await correr(async (vista) => {
95
+ // `about:blank` primero: `cdp()` no tiene sesión hasta que la vista
96
+ // navegó alguna vez, y las cookies tienen que estar antes del destino
97
+ // para que el primer request ya salga autenticado.
98
+ await vista.navigate("about:blank");
99
+ await vista.cdp("Network.setCookies", { cookies });
100
+ const leidas = (await vista.cdp("Network.getAllCookies")) as { cookies?: unknown[] };
101
+ return contarRestauradas(leidas?.cookies, cookies);
102
+ });
103
+ if (puestas > 0) {
104
+ log.info(`sesión del navegador restaurada (${puestas}/${cookies.length} cookies)`);
105
+ return { restaurada: true, puestas, intentos };
106
+ }
107
+ log.warn(
108
+ `el navegador no conservó ninguna de las ${cookies.length} cookies guardadas ` +
109
+ `(intento ${intento}/${RESTORE_INTENTOS})`,
110
+ );
111
+ } catch (err) {
112
+ log.warn(
113
+ `no se pudo restaurar la sesión (intento ${intento}/${RESTORE_INTENTOS}): ` +
114
+ `${(err as Error).message}`,
115
+ );
116
+ }
117
+ if (intento < RESTORE_INTENTOS) await Bun.sleep(RESTORE_ESPERA_MS);
118
+ }
119
+
120
+ return { restaurada: false, puestas: 0, intentos };
121
+ }
122
+
39
123
  /**
40
124
  * Tope para las operaciones que el motor puede dejar pendientes para siempre.
41
125
  *
@@ -382,6 +466,7 @@ export class WebViewBackend implements BrowserBackend {
382
466
  private axEnabled = false;
383
467
  /** La sesión guardada se restaura una sola vez, antes de la primera página. */
384
468
  private sessionRestored = false;
469
+ private restoreFallidos = 0;
385
470
  private saveTimer: ReturnType<typeof setTimeout> | null = null;
386
471
 
387
472
  constructor(
@@ -511,23 +596,37 @@ export class WebViewBackend implements BrowserBackend {
511
596
  */
512
597
  private async restoreSession(): Promise<void> {
513
598
  if (this.sessionRestored) return;
514
- this.sessionRestored = true;
515
- if (!sessionPersistenceEnabled(this.options.persistSession) || !this.hasCdp) return;
599
+ if (!sessionPersistenceEnabled(this.options.persistSession) || !this.hasCdp) {
600
+ this.sessionRestored = true;
601
+ return;
602
+ }
516
603
 
517
- try {
518
- const cookies = await loadStoredCookies();
519
- if (!cookies.length) return;
604
+ const cookies = await loadStoredCookies();
605
+ if (!cookies.length) {
606
+ this.sessionRestored = true;
607
+ return;
608
+ }
520
609
 
521
- await this.run(async (view) => {
522
- await view.navigate("about:blank");
523
- await view.cdp("Network.setCookies", { cookies });
524
- });
525
- log.info(`sesión del navegador restaurada (${cookies.length} cookies)`);
526
- } catch (err) {
527
- // Una sesión que no se pudo restaurar es un login perdido, no un fallo de
528
- // la navegación: el agente sigue, sólo que deslogueado.
529
- log.warn(`no se pudo restaurar la sesión: ${(err as Error).message}`);
610
+ // Chrome recién abierto no siempre tiene la sesión CDP lista: `setCookies`
611
+ // falla, o responde bien y la cookie no queda puesta. Antes se daba por
612
+ // restaurada igual y el agente navegaba deslogueado sin que nada fallara
613
+ // (así se caía este test en CI, de forma intermitente). Ahora se comprueba
614
+ // leyendo de vuelta y se reintenta.
615
+ const { restaurada } = await restaurarCookiesEnVista(cookies, (op) => this.run(op));
616
+ if (restaurada) {
617
+ this.sessionRestored = true;
618
+ return;
530
619
  }
620
+
621
+ // Sin marcar `sessionRestored`: el próximo navigate vuelve a intentarlo, que
622
+ // para entonces la vista ya está caliente. Después de `RESTORE_LLAMADAS` se
623
+ // deja de insistir para no pagar un about:blank en cada navegación.
624
+ this.restoreFallidos++;
625
+ if (this.restoreFallidos >= RESTORE_LLAMADAS) this.sessionRestored = true;
626
+ log.warn(
627
+ `sesión del navegador NO restaurada (${cookies.length} cookies guardadas): ` +
628
+ "el agente navega deslogueado",
629
+ );
531
630
  }
532
631
 
533
632
  /** Agenda un volcado de cookies; las llamadas seguidas se funden en una. */
@@ -547,24 +646,45 @@ export class WebViewBackend implements BrowserBackend {
547
646
  * Vuelca la sesión ya, sin esperar la ventana del debounce. Lo usan el
548
647
  * apagado ordenado y los tests; el camino normal es `scheduleSessionSave()`.
549
648
  */
649
+ /**
650
+ * Guarda la sesión ahora y falla si no puede.
651
+ *
652
+ * A diferencia del guardado periódico, aquí alguien pidió expresamente que la
653
+ * sesión quede en disco, así que callarse un fallo convierte el problema en
654
+ * "la cookie no aparece" mucho más tarde y en otro sitio — que es justo cómo
655
+ * se vivió desde una integración continua, sin forma de saber la causa.
656
+ */
550
657
  async flushSession(): Promise<void> {
551
658
  if (this.saveTimer) {
552
659
  clearTimeout(this.saveTimer);
553
660
  this.saveTimer = null;
554
661
  }
555
- await this.saveSession();
662
+ await this.saveSession(true);
556
663
  }
557
664
 
558
- private async saveSession(): Promise<void> {
559
- if (!this.view) return;
560
- if (!sessionPersistenceEnabled(this.options.persistSession) || !this.hasCdp) return;
665
+ private async saveSession(estricto = false): Promise<void> {
666
+ const rendirse = (motivo: string) => {
667
+ if (estricto) throw new Error(`no se pudo guardar la sesión: ${motivo}`);
668
+ };
669
+ if (!this.view) return rendirse("no hay ninguna vista abierta");
670
+ // Apagada por configuración: no hay nada que guardar y tampoco un problema
671
+ // que contar. Sólo se protesta cuando debía guardar y no pudo.
672
+ if (!sessionPersistenceEnabled(this.options.persistSession)) return;
673
+ if (!this.hasCdp) {
674
+ return rendirse(`el motor «${this.engine ?? this.options.engine ?? "?"}» no expone CDP`);
675
+ }
561
676
  try {
562
677
  const res = (await this.run((view) => view.cdp("Network.getAllCookies"))) as {
563
678
  cookies?: unknown[];
564
679
  };
565
- const guardadas = await storeCookies(res?.cookies ?? []);
680
+ const cookies = res?.cookies ?? [];
681
+ const guardadas = await storeCookies(cookies);
566
682
  if (guardadas) log.debug(`sesión del navegador guardada (${guardadas} cookies)`);
683
+ else if (estricto && cookies.length === 0) {
684
+ throw new Error("el navegador no reportó ninguna cookie");
685
+ }
567
686
  } catch (err) {
687
+ if (estricto) throw err;
568
688
  log.warn(`no se pudo guardar la sesión: ${(err as Error).message}`);
569
689
  }
570
690
  }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Resolución de puertos desde el entorno.
3
+ *
4
+ * Bun 1.4 endureció `Bun.serve`: un puerto fuera de `[0, 65535]` —o `NaN`, que
5
+ * es lo que devuelve `parseInt("no-es-un-numero")`— ahora lanza `RangeError` en
6
+ * vez de recortar el valor. Un `HIVE_PORT` mal escrito dejó de degradar y pasó a
7
+ * tumbar el arranque con una excepción sin capturar:
8
+ *
9
+ * RangeError: The value of "options.port" is out of range.
10
+ * It must be an integer. Received NaN
11
+ *
12
+ * Este helper vuelve a la degradación explícita: avisa y sigue con el puerto por
13
+ * defecto, que para una variable de entorno mal tipeada es el comportamiento
14
+ * útil. El `0` se deja pasar a propósito: `Bun.serve` lo interpreta como "asigna
15
+ * un puerto libre" y hay código que se apoya en eso.
16
+ *
17
+ * Avisa con `console.warn` y no con el logger del proyecto a propósito: esto lo
18
+ * usa `config/loader.ts`, y el logger importa `config/loader.ts` para saber
19
+ * dónde escribir. Importarlo acá cierra el ciclo y rompe con "Cannot access
20
+ * 'logger' before initialization". Además, cuando se resuelve un puerto el
21
+ * logger todavía no está configurado.
22
+ */
23
+
24
+ export function resolvePort(raw: unknown, fallback: number): number {
25
+ if (raw === undefined || raw === null || raw === "") return fallback
26
+
27
+ const n = typeof raw === "number" ? raw : Number(String(raw).trim())
28
+ if (!Number.isInteger(n) || n < 0 || n > 65535) {
29
+ console.warn(`[config] Puerto inválido ${JSON.stringify(raw)}; se usa ${fallback}`)
30
+ return fallback
31
+ }
32
+ return n
33
+ }
@@ -1,3 +1,4 @@
1
+ import { resolvePort } from "../utils/port";
1
2
  import { col } from "../storage/hive";
2
3
  import type { ChannelDoc, ModelDoc } from "../storage/collections";
3
4
  import { loadProviderApiKey } from "../storage/crypto";
@@ -311,7 +312,7 @@ class VoiceService {
311
312
 
312
313
  private async speakWithPiper(text: string, voiceId?: string): Promise<AudioOutput> {
313
314
  const cleanText = cleanTextForTTS(text);
314
- const port = Number(process.env.TTS_PORT ?? 5500);
315
+ const port = resolvePort(process.env.TTS_PORT, 5500);
315
316
  const res = await fetch(`http://localhost:${port}/tts`, {
316
317
  method: "POST",
317
318
  headers: { "Content-Type": "application/json" },