@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
@@ -78,8 +78,8 @@ export abstract class OpenAICompatBase implements LLMProvider {
78
78
  /** Override to true for providers running on localhost. */
79
79
  protected isLocalProvider(): boolean { return false }
80
80
 
81
- /** Override to customize the OpenAI client (e.g. strip unwanted headers, add custom fetch). */
82
- protected async resolveOpenAIClient(apiKey: string, baseURL: string | undefined): Promise<any> {
81
+ /** Override to customize the OpenAI client (e.g. strip unwanted headers, add custom fetch, per-call headers). */
82
+ protected async resolveOpenAIClient(apiKey: string, baseURL: string | undefined, _options?: LLMCallOptions): Promise<any> {
83
83
  const { default: OpenAI } = await import("openai")
84
84
  return new OpenAI({ apiKey, baseURL })
85
85
  }
@@ -131,7 +131,7 @@ export abstract class OpenAICompatBase implements LLMProvider {
131
131
  throw new Error(`API key missing for provider: ${this.providerName}. Configure it in Settings → Providers.`)
132
132
  }
133
133
 
134
- const client = await this.resolveOpenAIClient(apiKey, baseURL)
134
+ const client = await this.resolveOpenAIClient(apiKey, baseURL, options)
135
135
 
136
136
  const sanitized = sanitizeMessages(options.messages)
137
137
  const rawMessages = this.needsReasoningRoundtrip()
@@ -268,9 +268,23 @@ export abstract class OpenAICompatBase implements LLMProvider {
268
268
  sendTools: boolean,
269
269
  profile: ReturnType<typeof getProviderProfile>,
270
270
  ): Promise<LLMResponse> {
271
+ // Without stream_options.include_usage an OpenAI-compatible stream reports
272
+ // no tokens at all: every NVIDIA call was recorded as 0 in / 0 out, so its
273
+ // cost and Jev's savings on it never reached the dashboard. A server that
274
+ // does not know the field gets the same request without it.
275
+ const createStream = async (request: any) => {
276
+ try {
277
+ return await client.chat.completions.create({ ...request, stream: true, stream_options: { include_usage: true } }, { signal: options.signal })
278
+ } catch (err: any) {
279
+ const message = String(err?.error?.message ?? err?.message ?? "").toLowerCase()
280
+ if (!message.includes("stream_options") && !message.includes("include_usage")) throw err
281
+ return await client.chat.completions.create({ ...request, stream: true }, { signal: options.signal })
282
+ }
283
+ }
284
+
271
285
  let stream
272
286
  try {
273
- stream = await client.chat.completions.create({ ...this.modifyRequestBody(body, options), stream: true }, { signal: options.signal })
287
+ stream = await createStream(this.modifyRequestBody(body, options))
274
288
  } catch (err: any) {
275
289
  const status = err?.status ?? err?.response?.status
276
290
  const errMsg = (err?.error?.message ?? err?.message ?? "").toLowerCase()
@@ -280,17 +294,17 @@ export abstract class OpenAICompatBase implements LLMProvider {
280
294
  const originalCount = body.messages.length
281
295
  compactBodyForContextOverflow(body, err)
282
296
  log.info(`[llm-client] ${this.providerName}: compacted ${originalCount} msgs → ${body.messages.length} msgs, max_tokens=${body.max_tokens}`)
283
- stream = await client.chat.completions.create({ ...this.modifyRequestBody(body, options), stream: true }, { signal: options.signal })
297
+ stream = await createStream(this.modifyRequestBody(body, options))
284
298
  } else if (sendTools && profile.retryWithoutToolsOnCodes.includes(status)) {
285
299
  log.warn(`[llm-client] ${this.providerName}: tools rejected (HTTP ${status}) — retrying stream without tools`)
286
300
  const bodyNoTools = { ...body }
287
301
  delete bodyNoTools.tools
288
302
  delete bodyNoTools.tool_choice
289
303
  delete bodyNoTools.parallel_tool_calls
290
- stream = await client.chat.completions.create({ ...stripProviderExtras(this.modifyRequestBody(bodyNoTools, options)), stream: true }, { signal: options.signal })
304
+ stream = await createStream(stripProviderExtras(this.modifyRequestBody(bodyNoTools, options)))
291
305
  } else if (EXTRAS_REJECTED_CODES.includes(status) && this.modifyRequestBody(body, options).chat_template_kwargs) {
292
306
  log.warn(`[llm-client] ${this.providerName}: request rejected (HTTP ${status}) — retrying stream without chat_template_kwargs`)
293
- stream = await client.chat.completions.create({ ...stripProviderExtras(this.modifyRequestBody(body, options)), stream: true }, { signal: options.signal })
307
+ stream = await createStream(stripProviderExtras(this.modifyRequestBody(body, options)))
294
308
  } else {
295
309
  throw err
296
310
  }
@@ -304,6 +318,12 @@ export abstract class OpenAICompatBase implements LLMProvider {
304
318
  let output_tokens = 0
305
319
 
306
320
  for await (const chunk of stream) {
321
+ // Usage arrives in its own final chunk with an empty `choices`: read it
322
+ // before skipping choice-less chunks, or it is dropped even when sent.
323
+ if (chunk.usage) {
324
+ input_tokens = chunk.usage.prompt_tokens ?? input_tokens
325
+ output_tokens = chunk.usage.completion_tokens ?? output_tokens
326
+ }
307
327
  const choice = chunk.choices?.[0]
308
328
  if (!choice) continue
309
329
 
@@ -329,11 +349,6 @@ export abstract class OpenAICompatBase implements LLMProvider {
329
349
  }
330
350
  }
331
351
  if (choice.finish_reason) finish_reason = choice.finish_reason
332
-
333
- if (chunk.usage) {
334
- input_tokens = chunk.usage.prompt_tokens ?? 0
335
- output_tokens = chunk.usage.completion_tokens ?? 0
336
- }
337
352
  }
338
353
 
339
354
  const tool_calls: LLMToolCall[] = [...toolCallMap.values()].map((tc) => ({
@@ -1,4 +1,29 @@
1
+ import { createHash, randomUUID } from "node:crypto"
2
+ import pkg from "../../../../../package.json"
1
3
  import { OpenAICompatBase } from "./openai-compat-base"
4
+ import type { LLMCallOptions } from "../llm-client"
5
+
6
+ /**
7
+ * OpenCode Go rechaza con 400 `MissingSessionID` toda petición sin
8
+ * `x-opencode-session` (verificado 2026-09-10 con una key real: sin el header
9
+ * 400, con él 200). Su documentación pide además que el cliente se identifique
10
+ * con su propio User-Agent en vez del genérico del SDK:
11
+ * https://opencode.ai/docs/go/#where-can-i-use-it
12
+ */
13
+ const USER_AGENT = `hive/${pkg.version}`
14
+
15
+ /** Sesión de respaldo para llamadas sin conversación (compactación, metas). */
16
+ const PROCESS_SESSION = randomUUID()
17
+
18
+ /**
19
+ * La sesión tiene que ser estable por conversación —OpenCode la usa para rutear
20
+ * y cachear el prompt—, pero el threadId lleva usuario, canal y contacto: a
21
+ * OpenCode sólo le llega un hash.
22
+ */
23
+ function sessionHeader(sessionId: string | undefined): string {
24
+ if (!sessionId) return PROCESS_SESSION
25
+ return createHash("sha256").update(`hive:${sessionId}`).digest("hex").slice(0, 32)
26
+ }
2
27
 
3
28
  export class OpenCodeGoProvider extends OpenAICompatBase {
4
29
  static readonly secretKey = "OPENCODE_GO_API_KEY"
@@ -6,4 +31,16 @@ export class OpenCodeGoProvider extends OpenAICompatBase {
6
31
  constructor() {
7
32
  super("opencode-go")
8
33
  }
34
+
35
+ protected async resolveOpenAIClient(apiKey: string, baseURL: string | undefined, options?: LLMCallOptions): Promise<any> {
36
+ const { default: OpenAI } = await import("openai")
37
+ return new OpenAI({
38
+ apiKey,
39
+ baseURL,
40
+ defaultHeaders: {
41
+ "x-opencode-session": sessionHeader(options?.sessionId),
42
+ "User-Agent": USER_AGENT,
43
+ },
44
+ })
45
+ }
9
46
  }
@@ -7,7 +7,10 @@
7
7
  *
8
8
  * Verificado contra gemini-3.1-flash-live-preview (2026-08): la inyección de
9
9
  * texto va por `sendRealtimeInput({text})`; `sendClientContent` quedó restringido
10
- * al contexto inicial en 3.x, así que no se usa acá.
10
+ * al contexto inicial en 3.x, así que no se usa acá. La guía actual de la Live
11
+ * API (2026-09) dice que en 3.8 Live `send_client_content` funciona durante toda
12
+ * la sesión y que con `turn_complete=false` agrega contexto sin que el modelo
13
+ * responda: pendiente de verificar con una llamada real antes de usarlo.
11
14
  */
12
15
 
13
16
  import { logger } from "../../utils/logger";
@@ -22,7 +25,7 @@ import type {
22
25
  const log = logger.child("realtime:gemini");
23
26
 
24
27
  /** Modelos con `bidiGenerateContent`. El id vive en la BD; esto es sólo el fallback. */
25
- export const DEFAULT_GEMINI_LIVE_MODEL = "gemini-3.1-flash-live-preview";
28
+ export const DEFAULT_GEMINI_LIVE_MODEL = "gemini-3.8-live";
26
29
 
27
30
  class GeminiLiveSession implements RealtimeSession {
28
31
  closed = false;
@@ -165,9 +165,11 @@ function matchTriggers(message: string, triggersJson: string | null): boolean {
165
165
  const triggers: string[] = triggersJson.split(",").map(t => t.trim()).filter(t => t.length > 0)
166
166
  if (triggers.length === 0) return false
167
167
 
168
- const lowerMessage = message.toLowerCase()
168
+ // Accent-insensitive: "recuérdame" must match "recuerdame" typed without tildes
169
+ const fold = (s: string) => s.normalize("NFD").replace(/\p{Diacritic}/gu, "").toLowerCase()
170
+ const foldedMessage = fold(message)
169
171
  return triggers.some(trigger =>
170
- lowerMessage.includes(trigger.toLowerCase())
172
+ foldedMessage.includes(fold(trigger))
171
173
  )
172
174
  } catch (err) {
173
175
  log.warn(`[skill-selector] Failed to parse triggers: ${(err as Error).message}`)
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Thread identity — `${userId}/${channel}/${peerId}`.
3
+ *
4
+ * Un hilo por canal Y por contacto: el chat privado de Telegram, cada grupo de
5
+ * WhatsApp y cada conversación de la web tienen historial propio. Antes había un
6
+ * único hilo por usuario (`threadId = userId`) compartido por todos los canales.
7
+ *
8
+ * Dos reglas de formato que no son cosméticas:
9
+ *
10
+ * 1. El separador es "/" y NO ":". Los mensajes viven en `conversations` con id
11
+ * `${threadId}:${seq}` y se leen por prefijo (`scan({ prefix: "${threadId}:" })`),
12
+ * sin índice secundario. El hilo legacy (id = userId pelado) se lee con prefijo
13
+ * `${userId}:`; si los hilos nuevos fueran `${userId}:webchat:...` ese scan se los
14
+ * tragaría enteros. Con "/" el historial viejo queda aislado sin migrar una fila.
15
+ *
16
+ * 2. Ningún segmento puede contener ":" — se sustituye por "_". Sin esto los peerIds
17
+ * compuestos rompen el aislamiento por prefijo: el DM de Telegram `12345` y el grupo
18
+ * `12345:678` (telegram.ts arma así el peerId de grupo) producirían los prefijos
19
+ * `.../12345:` y `.../12345:678:`, y el primero es prefijo del segundo — el DM leería
20
+ * los mensajes del grupo. Colapsar ":" hace que `${threadId}:` sea siempre un
21
+ * separador inequívoco, y mantiene válido el `lastIndexOf(":")` con que
22
+ * conversation-store extrae el número de secuencia.
23
+ */
24
+
25
+ export const THREAD_SEP = "/"
26
+
27
+ /** Canal sintético de las tareas programadas: un hilo estable por cron job. */
28
+ export const CRON_CHANNEL = "cron"
29
+
30
+ export interface ThreadParts {
31
+ userId: string
32
+ channel: string
33
+ peerId: string
34
+ }
35
+
36
+ /**
37
+ * Deja un segmento apto para formar parte de un threadId: sin "/" (rompería el
38
+ * parseo) y sin ":" (rompería el aislamiento por prefijo — ver cabecera).
39
+ */
40
+ export function sanitizeSegment(value: string): string {
41
+ return value.replace(/[/:]/g, "_").trim()
42
+ }
43
+
44
+ export function makeThreadId(userId: string, channel: string, peerId: string): string {
45
+ const parts = [userId, channel, peerId].map((p) => sanitizeSegment(p || "") || "default")
46
+ return parts.join(THREAD_SEP)
47
+ }
48
+
49
+ /**
50
+ * Descompone un threadId con formato. Devuelve null para todo lo que no lo tenga:
51
+ * el hilo legacy (`userId` pelado), los hilos aislados de los workers
52
+ * (`task-<id>-<agente>`) y cualquier id heredado. Quien llame debe conservar su
53
+ * comportamiento anterior ante un null, nunca inventar partes.
54
+ */
55
+ export function parseThreadId(threadId: string): ThreadParts | null {
56
+ if (!threadId) return null
57
+ const parts = threadId.split(THREAD_SEP)
58
+ if (parts.length !== 3) return null
59
+ const [userId, channel, peerId] = parts
60
+ if (!userId || !channel || !peerId) return null
61
+ return { userId, channel, peerId }
62
+ }
63
+
64
+ export function isStructuredThreadId(threadId: string): boolean {
65
+ return parseThreadId(threadId) !== null
66
+ }
67
+
68
+ /** Id de una conversación nueva de la web. No lo elige el cliente. */
69
+ export function newWebConversationId(): string {
70
+ return `conv-${crypto.randomUUID().replace(/-/g, "").slice(0, 12)}`
71
+ }
@@ -0,0 +1,230 @@
1
+ /**
2
+ * Thread store — el registro de conversaciones (`conversationThreads`).
3
+ *
4
+ * `conversations` no tiene índice secundario: los mensajes se leen por prefijo del
5
+ * threadId. Esta colección es el catálogo que permite listar las conversaciones de
6
+ * un usuario, ponerles título y borrarlas sin escanear todos los mensajes.
7
+ *
8
+ * El id de cada fila ES el threadId. La única fila cuyo id no tiene formato
9
+ * `${user}/${canal}/${peer}` es la del hilo legacy anterior a la separación por
10
+ * canal (ver ensureLegacyThread).
11
+ */
12
+
13
+ import { col, updateDoc } from "../storage/hive"
14
+ import { logger } from "../utils/logger"
15
+ import type { ConversationThreadDoc, ConversationDoc, SummaryDoc } from "../storage/collections"
16
+ import { makeThreadId, parseThreadId, newWebConversationId } from "./thread-id"
17
+
18
+ const log = logger.child("thread-store")
19
+
20
+ const TITLE_MAX_CHARS = 60
21
+
22
+ export interface EnsureThreadInput {
23
+ userId: string
24
+ channel: string
25
+ peerId: string
26
+ peerKind?: "direct" | "group"
27
+ }
28
+
29
+ async function threadsCol() {
30
+ return col<ConversationThreadDoc>("conversationThreads")
31
+ }
32
+
33
+ export async function getThread(threadId: string): Promise<ConversationThreadDoc | null> {
34
+ const c = await threadsCol()
35
+ const entry = await c.get(threadId)
36
+ return entry?.doc ?? null
37
+ }
38
+
39
+ /**
40
+ * Crea la fila de la conversación si aún no existe y devuelve su threadId.
41
+ * Idempotente: se llama en cada turno desde resolveContext.
42
+ */
43
+ export async function ensureThread(input: EnsureThreadInput): Promise<string> {
44
+ const threadId = makeThreadId(input.userId, input.channel, input.peerId)
45
+ const c = await threadsCol()
46
+ const existing = await c.get(threadId)
47
+ if (existing) return threadId
48
+
49
+ const now = Date.now()
50
+ try {
51
+ await c.put(threadId, {
52
+ id: threadId,
53
+ user_id: input.userId,
54
+ channel: input.channel,
55
+ peer_id: input.peerId,
56
+ peer_kind: input.peerKind ?? "direct",
57
+ title: null,
58
+ archived: false,
59
+ created_at: now,
60
+ last_message_at: now,
61
+ message_count: 0,
62
+ }, { expectedVersion: 0 })
63
+ } catch {
64
+ // Otro turno del mismo canal la creó primero — ambos quieren lo mismo.
65
+ }
66
+ return threadId
67
+ }
68
+
69
+ /** Conversación nueva de la web. El id lo elige el servidor, nunca el cliente. */
70
+ export async function createWebConversation(userId: string, title?: string): Promise<ConversationThreadDoc> {
71
+ const peerId = newWebConversationId()
72
+ const threadId = await ensureThread({ userId, channel: "webchat", peerId, peerKind: "direct" })
73
+ if (title?.trim()) await renameThread(threadId, title)
74
+ const doc = await getThread(threadId)
75
+ if (!doc) throw new Error(`No pude crear la conversación ${threadId}`)
76
+ return doc
77
+ }
78
+
79
+ /**
80
+ * Título derivado del primer mensaje del usuario. El contenido llega con el
81
+ * prefijo `[Timestamp: ...]` que le añaden el gateway y las rutas REST: esa línea
82
+ * no describe nada, así que se descarta antes de recortar.
83
+ */
84
+ export function deriveTitle(text: string): string | null {
85
+ const withoutTimestamp = text.replace(/^\[Timestamp:[^\]]*\]\s*/, "").trim()
86
+ const firstLine = withoutTimestamp.split("\n").find((l) => l.trim().length > 0)?.trim()
87
+ if (!firstLine) return null
88
+ return firstLine.length > TITLE_MAX_CHARS
89
+ ? `${firstLine.slice(0, TITLE_MAX_CHARS - 1)}…`
90
+ : firstLine
91
+ }
92
+
93
+ /**
94
+ * Registra actividad en el hilo: contador, fecha del último mensaje y —la primera
95
+ * vez que habla el usuario— el título.
96
+ *
97
+ * Si el hilo tiene formato y no existe la fila, la crea (es el caso de un hilo que
98
+ * nació fuera de resolveContext, como el de una tarea programada). Si no lo tiene
99
+ * —hilo legacy, hilos aislados `task-*`— solo actualiza una fila ya existente:
100
+ * nunca inventa conversaciones para los hilos internos de los workers.
101
+ */
102
+ export async function touchThread(
103
+ threadId: string,
104
+ opts: { role: "user" | "assistant" | "tool"; text?: string; internal?: boolean }
105
+ ): Promise<void> {
106
+ try {
107
+ const c = await threadsCol()
108
+ let existing = await c.get(threadId)
109
+
110
+ if (!existing) {
111
+ const parts = parseThreadId(threadId)
112
+ if (!parts) return
113
+ await ensureThread({ userId: parts.userId, channel: parts.channel, peerId: parts.peerId })
114
+ existing = await c.get(threadId)
115
+ if (!existing) return
116
+ }
117
+
118
+ const patch: Partial<ConversationThreadDoc> = {
119
+ last_message_at: Date.now(),
120
+ message_count: existing.doc.message_count + 1,
121
+ }
122
+ // El título sale del primer mensaje humano: ni de la respuesta del agente ni
123
+ // de un evento interno (fan-in de delegación), que no describen el tema.
124
+ if (!existing.doc.title && opts.role === "user" && !opts.internal && opts.text) {
125
+ const title = deriveTitle(opts.text)
126
+ if (title) patch.title = title
127
+ }
128
+ await updateDoc<ConversationThreadDoc>("conversationThreads", threadId, patch)
129
+ } catch (err) {
130
+ // El registro es un catálogo, no la fuente de verdad: nunca debe tumbar un turno.
131
+ log.warn(`no pude actualizar el hilo ${threadId}: ${(err as Error).message}`)
132
+ }
133
+ }
134
+
135
+ export async function listThreads(
136
+ userId: string,
137
+ opts?: { channel?: string; includeArchived?: boolean }
138
+ ): Promise<ConversationThreadDoc[]> {
139
+ const c = await threadsCol()
140
+ const rows = await c.findBy("user_id", userId)
141
+ return rows
142
+ .map((r) => r.doc)
143
+ .filter((d) => (opts?.channel ? d.channel === opts.channel : true))
144
+ .filter((d) => (opts?.includeArchived ? true : !d.archived))
145
+ .sort((a, b) => b.last_message_at - a.last_message_at)
146
+ }
147
+
148
+ /** La conversación de webchat en la que seguiría escribiendo el usuario. */
149
+ export async function mostRecentWebThread(userId: string): Promise<ConversationThreadDoc | null> {
150
+ const threads = await listThreads(userId, { channel: "webchat" })
151
+ return threads[0] ?? null
152
+ }
153
+
154
+ export async function renameThread(threadId: string, title: string): Promise<void> {
155
+ const clean = title.trim().slice(0, 200)
156
+ await updateDoc<ConversationThreadDoc>("conversationThreads", threadId, { title: clean || null })
157
+ }
158
+
159
+ /**
160
+ * Borra la conversación entera: mensajes, resumen, notas y la fila del registro.
161
+ * Los mensajes se localizan por prefijo, igual que los lee conversation-store.
162
+ */
163
+ export async function deleteThread(threadId: string): Promise<void> {
164
+ const conversations = await col<ConversationDoc>("conversations")
165
+ const messages = await conversations.scan({ prefix: `${threadId}:` })
166
+ for (const m of messages) await conversations.delete(m.id)
167
+
168
+ const summaries = await col<SummaryDoc>("summaries")
169
+ await summaries.delete(threadId).catch(() => {})
170
+
171
+ const scratchpad = await col<{ threadId: string }>("scratchpad")
172
+ const notes = await scratchpad.scan({ prefix: `${threadId}:` })
173
+ for (const n of notes) await scratchpad.delete(n.id)
174
+
175
+ const c = await threadsCol()
176
+ await c.delete(threadId).catch(() => {})
177
+
178
+ log.info(`conversación ${threadId} borrada (${messages.length} mensajes)`)
179
+ }
180
+
181
+ /**
182
+ * El hilo por el que hablarle a alguien en un canal cuando no venimos de un
183
+ * mensaje suyo (avisos de tareas programadas, por ejemplo).
184
+ *
185
+ * En la web es la conversación activa; en los demás canales, el contacto al que
186
+ * apunta `userIdentities`. Devuelve null si no hay ninguno, y quien llame decide
187
+ * el fallback.
188
+ */
189
+ export async function threadForChannel(userId: string, channel: string): Promise<string | null> {
190
+ if (channel === "webchat") return (await mostRecentWebThread(userId))?.id ?? null
191
+
192
+ const identities = await col<{ channel_user_id?: string }>("userIdentities")
193
+ const identity = await identities.get(`${userId}:${channel}`)
194
+ const peerId = identity?.doc.channel_user_id
195
+ return peerId ? makeThreadId(userId, channel, peerId) : null
196
+ }
197
+
198
+ /**
199
+ * Registra el hilo anterior a la separación por canal —`thread_id = userId`, un
200
+ * único hilo compartido por todos los canales— como una conversación más de la
201
+ * web, para que su historial siga siendo accesible. No mueve ni reescribe ningún
202
+ * mensaje: la fila apunta al mismo prefijo de siempre.
203
+ */
204
+ export async function ensureLegacyThread(userId: string): Promise<boolean> {
205
+ const c = await threadsCol()
206
+ if (await c.get(userId)) return false
207
+
208
+ const conversations = await col<ConversationDoc>("conversations")
209
+ const sample = await conversations.scan({ prefix: `${userId}:`, limit: 1 })
210
+ if (sample.length === 0) return false
211
+
212
+ const all = await conversations.scan({ prefix: `${userId}:` })
213
+ const lastAt = all.reduce((max, e) => Math.max(max, e.doc.created_at), 0)
214
+
215
+ await c.put(userId, {
216
+ id: userId,
217
+ user_id: userId,
218
+ channel: "webchat",
219
+ peer_id: "legacy",
220
+ peer_kind: "direct",
221
+ title: "Conversación anterior",
222
+ archived: false,
223
+ created_at: all[0]?.doc.created_at ?? Date.now(),
224
+ last_message_at: lastAt || Date.now(),
225
+ message_count: all.length,
226
+ }, { expectedVersion: 0 }).catch(() => {})
227
+
228
+ log.info(`hilo legacy ${userId} registrado como conversación (${all.length} mensajes)`)
229
+ return true
230
+ }
@@ -135,6 +135,8 @@ export const CORE_TOOL_CATALOG: ToolDescriptor[] = [
135
135
  // Code execution
136
136
  { name: "cli_exec", description: "Execute shell commands, run bash scripts and system commands. Spanish keywords: ejecutar comando, terminal, línea de comandos, bash, script, comando del sistema", category: "cli", abstractionLevel: "atomic" },
137
137
 
138
+ { name: "code_agent_run", description: "Delegate a coding task to an external coding-agent CLI (Claude Code, Codex, OpenCode, Kimi) in an isolated git worktree; returns summary, changed files and diff. Spanish keywords: agente de código, delegar programación, codex, claude code, opencode, kimi, implementar con otro agente", category: "cli", abstractionLevel: "atomic" },
139
+
138
140
  // Web tools
139
141
  { name: "web_search", description: "Search web for current information, find up-to-date news facts and research. Spanish keywords: buscar en internet, buscar web, información, noticias, investigación, buscar", category: "web", abstractionLevel: "atomic" },
140
142
  { name: "web_fetch", description: "Fetch content from URL, download and extract content from web pages. Spanish keywords: obtener página, descargar web, extraer contenido, obtener contenido, página web", category: "web", abstractionLevel: "atomic" },
@@ -168,6 +170,45 @@ export const CORE_TOOL_CATALOG: ToolDescriptor[] = [
168
170
  { name: "browser_script", description: "Execute arbitrary JavaScript in the browser page context and get the result. Spanish keywords: ejecutar javascript, script, código, función, evaluar, js en página", category: "browser", abstractionLevel: "atomic" },
169
171
  { name: "browser_wait", description: "Wait for an element to appear or condition to be met on the page. Spanish keywords: esperar, wait, condición, elemento, selector, aguardar carga", category: "browser", abstractionLevel: "atomic" },
170
172
 
173
+ // Obscura (headless browser, live session, element refs)
174
+ { name: "obscura_navigate", description: "Navigate to a URL and wait for the page to load, keeping a live browser session for subsequent obscura_* tools. Returns the final URL and title only: read the page next with obscura_snapshot or obscura_markdown. Spanish keywords: navegar, abrir página, ir a sitio web, cargar url, visitar", category: "browser", abstractionLevel: "atomic" },
175
+ { name: "obscura_back", description: "Navigate back in the page history (browser back button). Requires an active session from obscura_navigate. Spanish keywords: atrás, volver, página anterior, regresar", category: "browser", abstractionLevel: "atomic" },
176
+ { name: "obscura_forward", description: "Navigate forward in the page history. Requires an active session from obscura_navigate. Spanish keywords: adelante, página siguiente, avanzar", category: "browser", abstractionLevel: "atomic" },
177
+ { name: "obscura_reload", description: "Reload the current page. Requires an active session from obscura_navigate. Spanish keywords: recargar, refrescar página, actualizar página, f5", category: "browser", abstractionLevel: "atomic" },
178
+ { name: "obscura_close", description: "Close the current browser page and reset the session state. Spanish keywords: cerrar navegador, cerrar página, terminar sesión", category: "browser", abstractionLevel: "atomic" },
179
+ { name: "obscura_snapshot", description: "Get the current page as text: URL, title, readable body text and interactive element refs. Preferred first read after navigating. Spanish keywords: snapshot página, contenido página, ver página, texto página, captura textual", category: "browser", abstractionLevel: "atomic" },
180
+ { name: "obscura_markdown", description: "Extract the current page as Markdown (headings, paragraphs, lists, links, code blocks). Token-dense structured content instead of plain text. Spanish keywords: markdown, extraer markdown, contenido estructurado, página en markdown", category: "browser", abstractionLevel: "atomic" },
181
+ { name: "obscura_links", description: "List every anchor link on the current page as one JSON object per line {text, href}. Spanish keywords: listar enlaces, ver links, urls página, hipervínculos, enlaces", category: "browser", abstractionLevel: "atomic" },
182
+ { name: "obscura_interactive_elements", description: "List every clickable/typeable element with a stable ref ID and a brief description. Use BEFORE clicking or filling to act by ref instead of guessing CSS selectors. Spanish keywords: elementos interactivos, botones, campos, inputs, refs, elementos clicables", category: "browser", abstractionLevel: "atomic" },
183
+ { name: "obscura_detect_forms", description: "List every <form> on the page with its action URL, method and a description of each input/textarea/select. Understand a form before filling it. Spanish keywords: detectar formularios, ver formularios, campos formulario, estructura formulario", category: "browser", abstractionLevel: "atomic" },
184
+ { name: "obscura_extract", description: "Extract a structured object from the page given a map of {field_name: css_selector}. Use 'selector@attr' for attributes (e.g. 'a@href') and 'field[]' suffix for arrays. Spanish keywords: extraer datos, scraping, extraer estructura, datos página, seleccionar campos", category: "browser", abstractionLevel: "atomic" },
185
+ { name: "obscura_get_attribute", description: "Read an attribute of an element (href, src, value, class, data-*). Returns the raw value or empty string. Spanish keywords: leer atributo, obtener atributo, href, valor elemento, atributo html", category: "browser", abstractionLevel: "atomic" },
186
+ { name: "obscura_count", description: "Count how many elements on the page match a CSS selector. Cheap existence/pagination probe. Spanish keywords: contar elementos, cuántos, número de elementos, contar coincidencias", category: "browser", abstractionLevel: "atomic" },
187
+ { name: "obscura_search", description: "Find substring matches in the visible page text with surrounding context. Spanish keywords: buscar en página, encontrar texto, buscar contenido, texto en página", category: "browser", abstractionLevel: "atomic" },
188
+ { name: "obscura_click", description: "Click an element by ref (preferred, from obscura_snapshot/obscura_interactive_elements) or CSS selector. Spanish keywords: hacer clic, presionar botón, clickear, pulsar, click", category: "browser", abstractionLevel: "atomic" },
189
+ { name: "obscura_fill", description: "Set the value of an input element (replaces existing value). Pass ref (preferred) or selector. Spanish keywords: llenar campo, rellenar input, establecer valor, completar campo", category: "browser", abstractionLevel: "atomic" },
190
+ { name: "obscura_type", description: "Type text into an input element (appends to existing value). Pass ref (preferred) or selector. Spanish keywords: escribir en campo, teclear texto, introducir texto, escribir input", category: "browser", abstractionLevel: "atomic" },
191
+ { name: "obscura_fill_form", description: "Fill multiple inputs in one call: fields is an array of {ref?, selector?, value, type?} where type is text (default), check, uncheck or select. Optional submit_ref/submit_selector clicks after filling. Spanish keywords: llenar formulario, completar formulario, rellenar form, enviar formulario", category: "browser", abstractionLevel: "atomic" },
192
+ { name: "obscura_press_key", description: "Dispatch a keyboard event (Enter, Tab, Escape…) on an element or the document. Spanish keywords: presionar tecla, pulsar enter, teclado, keydown", category: "browser", abstractionLevel: "atomic" },
193
+ { name: "obscura_select_option", description: "Select an option from a <select> element by value or visible text. Spanish keywords: seleccionar opción, elegir opción, dropdown, lista desplegable, select", category: "browser", abstractionLevel: "atomic" },
194
+ { name: "obscura_scroll", description: "Scroll the page or an element: direction top/bottom/up/down/left/right, amount in pixels. Use 'bottom' to trigger infinite-scroll loaders. Spanish keywords: scroll, desplazar, bajar página, subir página, desplazamiento", category: "browser", abstractionLevel: "atomic" },
195
+ { name: "obscura_wait_for", description: "Wait for a CSS selector to appear in the DOM (default 30s). Spanish keywords: esperar elemento, aguardar selector, wait selector, esperar carga", category: "browser", abstractionLevel: "atomic" },
196
+ { name: "obscura_wait_for_text", description: "Wait until a substring appears anywhere in the rendered page text — for result messages and notifications. Spanish keywords: esperar texto, aguardar mensaje, esperar resultado, wait texto", category: "browser", abstractionLevel: "atomic" },
197
+ { name: "obscura_evaluate", description: "Evaluate a JavaScript expression in the page context and return the result as JSON. Spanish keywords: ejecutar javascript, evaluar expresión, js en página, script navegador, eval", category: "browser", abstractionLevel: "atomic" },
198
+ { name: "obscura_network_requests", description: "List the network requests made by the current page (URLs, statuses, timings). Spanish keywords: ver peticiones red, requests, tráfico red, llamadas http página, network", category: "browser", abstractionLevel: "atomic" },
199
+ { name: "obscura_console_messages", description: "List the console messages logged by the current page (logs, warnings, errors). Spanish keywords: ver consola, logs página, mensajes consola, errores javascript, console", category: "browser", abstractionLevel: "atomic" },
200
+ { name: "obscura_screenshot", description: "Capture the current rendered viewport as a PNG (saved to ~/.hivecode/screenshots/, returned with path + base64). Use for canvas/visual verification; prefer obscura_snapshot for text. Spanish keywords: captura de pantalla, screenshot, fotografiar página, imagen página, png", category: "browser", abstractionLevel: "atomic" },
201
+ { name: "obscura_pdf", description: "Export the current rendered document as a paginated PDF (saved to ~/.hivecode/screenshots/). Spanish keywords: exportar pdf, guardar pdf, página a pdf, documento pdf", category: "browser", abstractionLevel: "atomic" },
202
+ { name: "obscura_get_cookies", description: "Return all cookies in the browser's cookie jar as one JSON object per line. Spanish keywords: ver cookies, obtener cookies, cookies sesión, leer cookies", category: "browser", abstractionLevel: "atomic" },
203
+ { name: "obscura_set_cookie", description: "Add or replace a cookie in the jar — skip a login flow when you already have a session token. Spanish keywords: setear cookie, establecer cookie, inyectar cookie, cookie sesión", category: "browser", abstractionLevel: "atomic" },
204
+ { name: "obscura_clear_cookies", description: "Wipe every cookie from the jar. Spanish keywords: borrar cookies, limpiar cookies, eliminar cookies", category: "browser", abstractionLevel: "atomic" },
205
+ { name: "obscura_storage_state", description: "Export the full session state (cookies + localStorage + sessionStorage) as JSON — save it to skip a login on a later run. Spanish keywords: exportar sesión, estado sesión, guardar sesión, storage state", category: "browser", abstractionLevel: "atomic" },
206
+ { name: "obscura_set_storage_state", description: "Restore a session state previously returned by obscura_storage_state to bring an authenticated session back. Spanish keywords: restaurar sesión, importar sesión, cargar sesión guardada, login guardado", category: "browser", abstractionLevel: "atomic" },
207
+ { name: "obscura_tab_new", description: "Open a new tab (isolated browser page); subsequent tool calls operate on the most recent tab. Spanish keywords: nueva pestaña, abrir pestaña, nuevo tab", category: "browser", abstractionLevel: "atomic" },
208
+ { name: "obscura_tab_list", description: "List all open tabs with their ID, URL, title and which one is active. Spanish keywords: listar pestañas, ver pestañas, tabs abiertos", category: "browser", abstractionLevel: "atomic" },
209
+ { name: "obscura_tab_switch", description: "Switch the active tab — all subsequent tool calls target this tab. Spanish keywords: cambiar pestaña, cambiar tab, activar pestaña", category: "browser", abstractionLevel: "atomic" },
210
+ { name: "obscura_tab_close", description: "Close a tab by ID (default: the active tab). Spanish keywords: cerrar pestaña, cerrar tab", category: "browser", abstractionLevel: "atomic" },
211
+
171
212
  // A2UI v0.9 rich interactive surfaces
172
213
  { name: "a2ui_create_surface", description: "Create A2UI v0.9 surface for rich interactive UIs with forms, dashboards, and workflows. Spanish keywords: crear superficie A2UI, iniciar UI interactiva, crear formulario rico, interfaz A2UI, crear surface", category: "a2ui", abstractionLevel: "orchestration" },
173
214
  { name: "a2ui_update_components", description: "Send A2UI v0.9 components to an existing surface (Text, Button, TextField, Row, Column, Card, etc.). Spanish keywords: enviar componentes A2UI, actualizar UI, renderizar componentes, A2UI componentes, update components", category: "a2ui", abstractionLevel: "atomic" },
@@ -196,6 +237,7 @@ export const CORE_TOOL_CATALOG: ToolDescriptor[] = [
196
237
 
197
238
  // Capability discovery
198
239
  { name: "search_knowledge", description: "Search everything Hive knows: native tools, MCP tools, skills, catalog agents and playbook rules. Spanish keywords: buscar herramienta, descubrir capacidades, qué puedo hacer, buscar skill, buscar conocimiento", category: "core", abstractionLevel: "atomic" },
240
+ { name: "conversation_read", description: "Read earlier messages from this conversation by ID or search text when context is missing. Spanish keywords: recuperar contexto, leer historial, conversación anterior", category: "core", abstractionLevel: "atomic" },
199
241
 
200
242
  // HTTP / REST
201
243
  { name: "api_request", description: "Perform an authorized HTTP request against a REST endpoint and validate the response. Spanish keywords: llamar api, request rest, consumir endpoint, petición http, hacer get, hacer post", category: "api", abstractionLevel: "atomic" },
@@ -95,6 +95,7 @@ export function recordLLMUsage(opts: {
95
95
  model: string
96
96
  inputTokens: number
97
97
  outputTokens: number
98
+ latencyMs?: number
98
99
  }): void {
99
100
  Promise.resolve().then(async () => {
100
101
  try {
@@ -104,6 +105,7 @@ export function recordLLMUsage(opts: {
104
105
  model: opts.model,
105
106
  inputTokens: opts.inputTokens,
106
107
  outputTokens: opts.outputTokens,
108
+ latencyMs: opts.latencyMs,
107
109
  })
108
110
  } catch { /* ignore */ }
109
111
  })
@@ -42,6 +42,15 @@ interface A2UISurfaceCache {
42
42
  dataModel?: Record<string, unknown>;
43
43
  }
44
44
 
45
+ /** Overlays `incoming` on `current` by component id, keeping the order of first appearance. */
46
+ export function mergeComponentsById(current: unknown[], incoming: unknown[]): unknown[] {
47
+ const byId = new Map<string, unknown>()
48
+ const idOf = (c: unknown) => (c && typeof c === "object" ? String((c as { id?: unknown }).id ?? "") : "")
49
+ for (const c of current) byId.set(idOf(c), c)
50
+ for (const c of incoming) byId.set(idOf(c), c)
51
+ return [...byId.values()]
52
+ }
53
+
45
54
  export class CanvasManager {
46
55
  /**
47
56
  * Clientes por sesión, no *un* cliente por sesión.
@@ -197,6 +206,11 @@ export class CanvasManager {
197
206
  );
198
207
  }
199
208
 
209
+ /** What the client is rendering for a surface: every component sent so far, merged by id. */
210
+ getCachedComponents(sessionId: string, surfaceId: string): unknown[] {
211
+ return this.a2uiCache.get(sessionId)?.get(surfaceId)?.components ?? [];
212
+ }
213
+
200
214
  async sendA2UIMessage(sessionId: string, messageType: string, data: Record<string, unknown>): Promise<void> {
201
215
  // Update A2UI cache so late-connecting clients can receive current state
202
216
  const surfaceId = data.surfaceId as string | undefined;
@@ -207,7 +221,9 @@ export class CanvasManager {
207
221
  sessionSurfaces.set(surfaceId, { createData: data });
208
222
  } else if (messageType === "a2ui:updateComponents") {
209
223
  const cached = sessionSurfaces.get(surfaceId);
210
- if (cached) cached.components = data.components as unknown[];
224
+ // Merge by id, like the client: replacing the list made a reconnect
225
+ // replay a different surface from the one the user was looking at.
226
+ if (cached) cached.components = mergeComponentsById(cached.components ?? [], data.components as unknown[]);
211
227
  } else if (messageType === "a2ui:updateDataModel") {
212
228
  const cached = sessionSurfaces.get(surfaceId);
213
229
  if (cached) {
@@ -15,6 +15,8 @@ export type CanvasEventType =
15
15
  | "canvas:edge_add"
16
16
  | "canvas:edge_remove"
17
17
  | "canvas:work_event"
18
+ | "canvas:jev_decision"
19
+ | "canvas:jev_status"
18
20
  | "ag-ui:event"
19
21
 
20
22
  export type CanvasWorkPhase =
@@ -37,6 +39,23 @@ export interface CanvasWorkEvent {
37
39
  detail?: string | null
38
40
  }
39
41
 
42
+ /** One Jev decision, shown by the office's oracle as a beam to the agent it advised. */
43
+ export interface CanvasJevDecision {
44
+ eventId: string
45
+ agentId: string
46
+ kind: "context" | "iteration" | "parallel"
47
+ /** Short Spanish description of what was selected ("4/15 mensajes · 9/24 herramientas"). */
48
+ summary: string
49
+ /** Estimated main-model input tokens this decision avoided (chars/4); negative when it added context. */
50
+ savedTokens: number
51
+ latencyMs: number
52
+ costUsd: number
53
+ recommendedAgentId?: string | null
54
+ /** MCP servers the recommended specialist needs that are off; the coordinator asks the user to turn them on. */
55
+ mcpOff?: string[]
56
+ totals: { decisions: number; savedTokens: number; costUsd: number }
57
+ }
58
+
40
59
  const subscribers = new Set<{ send: (data: string) => void }>()
41
60
  let workEventSequence = 0
42
61
 
@@ -57,6 +76,11 @@ const LIVE_DEFAULTS: AgentLiveState = {
57
76
  delegatedBy: null,
58
77
  }
59
78
 
79
+ /** What each agent is doing right now (the same state the 3D office draws). */
80
+ export function getAgentLiveStates(): Array<{ agentId: string } & AgentLiveState> {
81
+ return [...agentLiveState.entries()].map(([agentId, state]) => ({ agentId, ...state }))
82
+ }
83
+
60
84
  export function subscribeCanvas(ws: { send: (data: string) => void }) {
61
85
  subscribers.add(ws)
62
86
  }