@johpaz/hive-agents 1.0.0 → 1.0.2

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 (165) hide show
  1. package/README.md +25 -11
  2. package/dist/hive.js +22498 -6889
  3. package/dist/tool-worker.js +6 -2
  4. package/dist/ui/assets/A2UIPage-BRpjnMss.js +8 -0
  5. package/dist/ui/assets/{AgentCreateForm-g1mQnIoJ.js → AgentCreateForm-ASjKD7Js.js} +1 -1
  6. package/dist/ui/assets/{AgentDetailPage-C3XkU4Ll.js → AgentDetailPage-bqJ-MS40.js} +1 -1
  7. package/dist/ui/assets/AgentNewPage-CPaf2C3u.js +1 -0
  8. package/dist/ui/assets/{AgentsPage-CNA778Eo.js → AgentsPage-BIpLG0V6.js} +1 -1
  9. package/dist/ui/assets/{ApiClientPage-t5DpKhmA.js → ApiClientPage-dRckcgrN.js} +1 -1
  10. package/dist/ui/assets/{ChannelsPage-yY6t0YTU.js → ChannelsPage-BX_hPtiN.js} +2 -2
  11. package/dist/ui/assets/{DashboardPage-BSeNSYg5.js → DashboardPage-KMaMaFf4.js} +2 -2
  12. package/dist/ui/assets/{LoginPage-eT5zDRDa.js → LoginPage-Zchu-f16.js} +1 -1
  13. package/dist/ui/assets/{LogsPage-Gczzzsdh.js → LogsPage-6Po7_T2u.js} +1 -1
  14. package/dist/ui/assets/{MeetingPage-Bu4aMMNR.js → MeetingPage-qrpYGVD-.js} +1 -1
  15. package/dist/ui/assets/{ModelSelector-nNOrW3te.js → ModelSelector-C8ny_pxu.js} +1 -1
  16. package/dist/ui/assets/{Office3DPage-B_iXEbyv.js → Office3DPage-BYwLMTCl.js} +2 -2
  17. package/dist/ui/assets/ProvidersPage-DP9v_1ko.js +1 -0
  18. package/dist/ui/assets/{RecoverPage-DMqSasKk.js → RecoverPage-BXwjLfap.js} +1 -1
  19. package/dist/ui/assets/SettingsPage-DD7GKtS6.js +9 -0
  20. package/dist/ui/assets/{SetupPage-DhcRbGgg.js → SetupPage-D7YX2io-.js} +1 -1
  21. package/dist/ui/assets/{WebChatPage-CWXjW4Hn.js → WebChatPage-C3cgimxd.js} +1 -1
  22. package/dist/ui/assets/{activity-CQuPevhB.js → activity-DZKL7dg4.js} +1 -1
  23. package/dist/ui/assets/{agentCapabilities-CDC6y91E.js → agentCapabilities-DuGs07XP.js} +1 -1
  24. package/dist/ui/assets/arrow-left-12JaXVoH.js +1 -0
  25. package/dist/ui/assets/arrow-right-Dbui5p0d.js +1 -0
  26. package/dist/ui/assets/arrow-up-right-CJBtXRrp.js +1 -0
  27. package/dist/ui/assets/{calendar-Be23hQGc.js → calendar-CkDsc4OJ.js} +1 -1
  28. package/dist/ui/assets/check-DxOMIDcl.js +1 -0
  29. package/dist/ui/assets/chevron-down-CObv-xyx.js +1 -0
  30. package/dist/ui/assets/chevron-left-C0mqwhLU.js +1 -0
  31. package/dist/ui/assets/chevron-right-jCt1h8Kw.js +1 -0
  32. package/dist/ui/assets/chevron-up-DX_5iw7O.js +1 -0
  33. package/dist/ui/assets/{circle-alert-BDVHxmAz.js → circle-alert-BkP6x0zQ.js} +1 -1
  34. package/dist/ui/assets/circle-check-CXC2AiMS.js +1 -0
  35. package/dist/ui/assets/{circle-x-Cb2Yer4s.js → circle-x-h4OJiHV3.js} +1 -1
  36. package/dist/ui/assets/{copy-33tZrzc9.js → copy-BtpYEEvV.js} +1 -1
  37. package/dist/ui/assets/{dialog-KOZKWbib.js → dialog-CO1WrPJc.js} +1 -1
  38. package/dist/ui/assets/{download-CiQqqXyz.js → download-aPuVaZik.js} +1 -1
  39. package/dist/ui/assets/{earth-DCvN7ynm.js → earth-sc8YJMc0.js} +1 -1
  40. package/dist/ui/assets/{ellipsis-vertical-BybFZDk2.js → ellipsis-vertical-DEBZJGzY.js} +1 -1
  41. package/dist/ui/assets/{external-link-0iNNBvZm.js → external-link-D_C_678M.js} +1 -1
  42. package/dist/ui/assets/{eye-C8sKSSkg.js → eye-BfN613fx.js} +1 -1
  43. package/dist/ui/assets/{file-text-DO8jqiJK.js → file-text-Bth5pPZX.js} +1 -1
  44. package/dist/ui/assets/gauge-DypSzSOE.js +1 -0
  45. package/dist/ui/assets/{history-BtTD1kDo.js → history-njH_sPSo.js} +1 -1
  46. package/dist/ui/assets/{index-Bejlp-R1.js → index-D-9yCvjP.js} +4 -4
  47. package/dist/ui/assets/index-wML8DaUo.css +2 -0
  48. package/dist/ui/assets/{info-mpk1tsNC.js → info-Def2ZFeP.js} +1 -1
  49. package/dist/ui/assets/{key-CoQ0qtXt.js → key-D8bkDl83.js} +1 -1
  50. package/dist/ui/assets/loader-circle-wLVzSdML.js +1 -0
  51. package/dist/ui/assets/{lock-open-Cd2aqwOd.js → lock-open-Cdopbw1b.js} +1 -1
  52. package/dist/ui/assets/{mail-BG0RYSkL.js → mail-BQ_YA9_b.js} +1 -1
  53. package/dist/ui/assets/{pause-Cme88_9s.js → pause-CvS_LzKx.js} +1 -1
  54. package/dist/ui/assets/{pencil-f1nJ1xhs.js → pencil-C3tPvnCk.js} +1 -1
  55. package/dist/ui/assets/play-C-oR-PMH.js +1 -0
  56. package/dist/ui/assets/plus-CF9No2td.js +1 -0
  57. package/dist/ui/assets/{radio-B5SpKJ-J.js → radio-dsaiFxuT.js} +1 -1
  58. package/dist/ui/assets/{refresh-cw-CroGQY62.js → refresh-cw-BmYQwOhh.js} +1 -1
  59. package/dist/ui/assets/search-CTONpTyl.js +1 -0
  60. package/dist/ui/assets/{select-BhbW0stK.js → select-BfRyBbi9.js} +1 -1
  61. package/dist/ui/assets/{send-D6whYpw-.js → send-C3o2wpLi.js} +1 -1
  62. package/dist/ui/assets/{settings-BX6q3MGB.js → settings-DEpdBuf2.js} +1 -1
  63. package/dist/ui/assets/{shield-BnGyu1xf.js → shield-gbUkSqfi.js} +1 -1
  64. package/dist/ui/assets/{sparkles-BcaOs_Jk.js → sparkles-Ccd1JZ3s.js} +1 -1
  65. package/dist/ui/assets/{square-ju5H8nrT.js → square-BrwQ6Mun.js} +1 -1
  66. package/dist/ui/assets/terminal-DP9j3HjM.js +1 -0
  67. package/dist/ui/assets/{trash-2-DjQXac_0.js → trash-2-CfCs7RhJ.js} +1 -1
  68. package/dist/ui/assets/{triangle-alert-B04mgMcg.js → triangle-alert-C3lWSnRr.js} +1 -1
  69. package/dist/ui/assets/{useHiveAgentsModelLoad-DT5-4CCj.js → useHiveAgentsModelLoad-D3s2U82M.js} +1 -1
  70. package/dist/ui/assets/{useProviders-DSX7eVsz.js → useProviders-B3rT_xU9.js} +1 -1
  71. package/dist/ui/assets/{volume-x-qnVxkRSM.js → volume-x-D2h9cyml.js} +1 -1
  72. package/dist/ui/assets/{wifi-BA1m2dGO.js → wifi-CGQECzu2.js} +1 -1
  73. package/dist/ui/assets/{zap-DT7cM7YS.js → zap-B1azpiE7.js} +1 -1
  74. package/dist/ui/index.html +8 -6
  75. package/dist/ui/logoblack.png +0 -0
  76. package/dist/ui/logocolor-dark.png +0 -0
  77. package/dist/ui/logocolorbg.png +0 -0
  78. package/dist/ui/logodoradobg.png +0 -0
  79. package/package.json +12 -8
  80. package/packages/cli/src/commands/doctor.ts +111 -0
  81. package/packages/cli/src/commands/onboard.ts +126 -59
  82. package/packages/cli/src/index.ts +23 -17
  83. package/packages/cli/src/ui-bundle.generated.ts +9 -92
  84. package/packages/core/src/agent/acceptance-checks.ts +172 -0
  85. package/packages/core/src/agent/agent-catalog.ts +1 -37
  86. package/packages/core/src/agent/agent-loop.ts +21 -2
  87. package/packages/core/src/agent/catalog-selector.ts +0 -1
  88. package/packages/core/src/agent/compaction.ts +16 -1
  89. package/packages/core/src/agent/context-compiler.ts +3 -1
  90. package/packages/core/src/agent/conversation-store.ts +1 -1
  91. package/packages/core/src/agent/delegation-runtime.ts +1 -8
  92. package/packages/core/src/agent/goal-runner.ts +111 -32
  93. package/packages/core/src/agent/index.ts +1 -1
  94. package/packages/core/src/agent/llm-client.ts +34 -2
  95. package/packages/core/src/agent/llm-providers/anthropic.ts +10 -7
  96. package/packages/core/src/agent/llm-providers/interface.ts +13 -2
  97. package/packages/core/src/agent/llm-providers/modelscope.ts +5 -0
  98. package/packages/core/src/agent/llm-providers/z-ai.ts +5 -0
  99. package/packages/core/src/agent/minimal-loadout.ts +1 -0
  100. package/packages/core/src/agent/proof-packet.ts +2 -11
  101. package/packages/core/src/agent/providers/index.ts +1 -1
  102. package/packages/core/src/agent/tool-selector.ts +25 -1
  103. package/packages/core/src/canvas/canvas-manager.ts +36 -7
  104. package/packages/core/src/canvas/emitter.ts +0 -44
  105. package/packages/core/src/channels/manager.ts +117 -25
  106. package/packages/core/src/channels/whatsapp.ts +6 -1
  107. package/packages/core/src/config/loader.ts +13 -1
  108. package/packages/core/src/events/channel-narration.ts +150 -0
  109. package/packages/core/src/events/tool-narration.ts +62 -0
  110. package/packages/core/src/gateway/channel-notify.ts +11 -7
  111. package/packages/core/src/gateway/delegation-groups.ts +24 -11
  112. package/packages/core/src/gateway/helpers/narration.ts +4 -62
  113. package/packages/core/src/gateway/helpers/ui-source.ts +67 -0
  114. package/packages/core/src/gateway/job-executors.ts +29 -67
  115. package/packages/core/src/gateway/resolver.ts +10 -2
  116. package/packages/core/src/gateway/routes/a2ui.ts +43 -0
  117. package/packages/core/src/gateway/routes/agents.ts +6 -6
  118. package/packages/core/src/gateway/routes/channels.ts +15 -1
  119. package/packages/core/src/gateway/routes/models.ts +69 -12
  120. package/packages/core/src/gateway/routes/providers.ts +110 -28
  121. package/packages/core/src/gateway/routes/runtime.ts +58 -0
  122. package/packages/core/src/gateway/routes/setup.ts +161 -90
  123. package/packages/core/src/gateway/routes/system.ts +8 -5
  124. package/packages/core/src/gateway/routes/voice.ts +3 -0
  125. package/packages/core/src/gateway/server.ts +74 -28
  126. package/packages/core/src/gateway/webchat-turn.ts +29 -5
  127. package/packages/core/src/index.ts +1 -1
  128. package/packages/core/src/storage/bootstrap.ts +13 -9
  129. package/packages/core/src/storage/collections.ts +12 -46
  130. package/packages/core/src/storage/crypto.ts +147 -58
  131. package/packages/core/src/storage/hivedb.ts +9 -0
  132. package/packages/core/src/storage/model-id.ts +53 -0
  133. package/packages/core/src/storage/onboarding.ts +36 -9
  134. package/packages/core/src/storage/seed.ts +283 -138
  135. package/packages/core/src/storage/usage.ts +61 -123
  136. package/packages/core/src/tools/agents/index.ts +199 -27
  137. package/packages/core/src/tools/index.ts +2 -1
  138. package/packages/core/src/tools/web/browser-backend.ts +129 -0
  139. package/packages/core/src/tools/web/browser-service.ts +75 -35
  140. package/packages/core/src/tools/web/webview-backend.ts +412 -0
  141. package/packages/core/src/voice/index.ts +108 -17
  142. package/packages/skills/src/bundled/agents/task_orchestrator/SKILL.md +2 -1
  143. package/packages/skills/src/bundled-data.generated.ts +2 -23
  144. package/dist/ui/assets/A2UIPage-D4nUFe5q.js +0 -8
  145. package/dist/ui/assets/AgentNewPage-CEkLeA79.js +0 -1
  146. package/dist/ui/assets/ProvidersPage-BupHs5yO.js +0 -1
  147. package/dist/ui/assets/SettingsPage-B6FTSkOn.js +0 -9
  148. package/dist/ui/assets/arrow-left-0EBE7nsF.js +0 -1
  149. package/dist/ui/assets/arrow-right-5QIaph-z.js +0 -1
  150. package/dist/ui/assets/arrow-up-right-DQQCY007.js +0 -1
  151. package/dist/ui/assets/check-Dp6tzwax.js +0 -1
  152. package/dist/ui/assets/chevron-down-33N886NY.js +0 -1
  153. package/dist/ui/assets/chevron-left-C6itJXh3.js +0 -1
  154. package/dist/ui/assets/chevron-right-CFodBS-b.js +0 -1
  155. package/dist/ui/assets/chevron-up-BvSmyBEs.js +0 -1
  156. package/dist/ui/assets/circle-check-BJWNbLuF.js +0 -1
  157. package/dist/ui/assets/gauge-BRGwuN8G.js +0 -1
  158. package/dist/ui/assets/index-XoTT41Hr.css +0 -2
  159. package/dist/ui/assets/loader-circle-BhqRN2nO.js +0 -1
  160. package/dist/ui/assets/play-CfYDHD6h.js +0 -1
  161. package/dist/ui/assets/plus-C5BxJeOX.js +0 -1
  162. package/dist/ui/assets/search-rfBcmohK.js +0 -1
  163. package/dist/ui/assets/terminal-Bjfu-TkS.js +0 -1
  164. package/packages/core/src/agent/acceptance-verifier.ts +0 -300
  165. package/packages/skills/src/bundled/agents/acceptance_verification/SKILL.md +0 -26
@@ -11,8 +11,12 @@ import {
11
11
  activateEthics,
12
12
  } from "../../storage/onboarding"
13
13
  import { normalizeUserEmail } from "../../storage/user-email"
14
+ import { catalogModelKey, wireModelId } from "../../storage/model-id"
14
15
  import { getHiveDir } from "../../config/loader"
15
16
  import type { Config } from "../../config/loader"
17
+ import { logger } from "../../utils/logger"
18
+
19
+ const log = logger.child("setup")
16
20
 
17
21
  export async function handleSetupProviders(
18
22
  addCorsHeaders: (response: Response, request: Request) => Response,
@@ -90,11 +94,14 @@ export async function handleSetupOllamaModels(
90
94
  try {
91
95
  const modelsCol = await col<ModelDoc>("models")
92
96
  for (const m of detected) {
93
- if (!(await modelsCol.get(m.name))) {
94
- await modelsCol.put(m.name, {
95
- id: m.name, name: m.name, provider_id: "ollama", model_type: "llm",
97
+ const key = catalogModelKey("ollama", m.name)
98
+ if (!(await modelsCol.get(key))) {
99
+ await modelsCol.put(key, {
100
+ id: key, name: m.name, provider_id: "ollama", model_type: "llm",
96
101
  context_window: 0, capabilities: null, enabled: true, active: false,
97
102
  source: "discovered",
103
+ // Local: siempre gratis, no "precio desconocido".
104
+ input_per_1m: 0, output_per_1m: 0,
98
105
  }, { expectedVersion: 0 })
99
106
  }
100
107
  }
@@ -129,9 +136,42 @@ export async function handleSetupStatus(): Promise<Response> {
129
136
  })
130
137
  }
131
138
 
139
+ /**
140
+ * Providers OpenAI-compatibles que no necesitan un branch propio acá: el request
141
+ * es idéntico y sólo cambia el host, que sale de `providers.base_url` en la BD.
142
+ * Si el usuario apunta uno a un proxy propio, la verificación usa ese endpoint y
143
+ * no uno fijo en el código.
144
+ */
145
+ const OPENAI_COMPAT_PING = new Set(["z-ai", "minimax", "qwen", "opencode-go"])
146
+
147
+ /**
148
+ * Providers cuyo GET /models es público (no exige Authorization) — NVIDIA y
149
+ * ModelScope responden 200 con dummy key, así que ese endpoint sólo sirve para
150
+ * descubrir un modelo vivo, no para validar la key. Para eso se prueba una
151
+ * completion real con el primer modelo de ese mismo listado (nunca uno
152
+ * retirado, porque sale del catálogo vivo y no del seed) y se juzga la key por
153
+ * el status de esa respuesta.
154
+ */
155
+ const PUBLIC_MODEL_LIST = new Set(["nvidia", "modelscope"])
156
+
157
+ /** base_url del provider tal como está en la BD. */
158
+ async function providerBaseUrl(providerId: string): Promise<string | null> {
159
+ try {
160
+ const providersCol = await col<ProviderDoc>("providers")
161
+ return (await providersCol.get(providerId))?.doc.base_url ?? null
162
+ } catch {
163
+ return null
164
+ }
165
+ }
166
+
132
167
  export async function handleVerifyProvider(req: Request): Promise<Response> {
133
168
  const body = await req.json().catch(() => ({}))
134
- const { provider, apiKey, model } = body
169
+ const { provider } = body
170
+ // Trim: un \n o espacio colgado del copy-paste (típico al pegar desde un
171
+ // .txt o la terminal) es invisible en el input pero hace que `fetch()`
172
+ // explote al armar el header `Authorization: Bearer <key>` — antes de
173
+ // mandar nada, con un error críptico del runtime en vez de un 401 claro.
174
+ const apiKey = typeof body.apiKey === "string" ? body.apiKey.trim() : body.apiKey
135
175
 
136
176
  if (!provider || !apiKey) {
137
177
  return Response.json({
@@ -141,23 +181,18 @@ export async function handleVerifyProvider(req: Request): Promise<Response> {
141
181
  }
142
182
 
143
183
  try {
184
+ // Verificación por listado de modelos (GET, sin costo) en vez de armar una
185
+ // completion real con un modelo "de prueba" adivinado del catálogo. Ese
186
+ // enfoque anterior fallaba con key válida cuando el modelo elegido estaba
187
+ // retirado (NVIDIA da 410 Gone en modelos de baja) o el provider exigía un
188
+ // parámetro distinto para ese modelo puntual (p.ej. modelos de razonamiento
189
+ // de OpenAI que rechazan `max_tokens`). El dashboard (agregar/editar
190
+ // provider) nunca tuvo este problema porque sólo lista modelos — acá se
191
+ // alinea a lo mismo, y de paso deja de gastar tokens en cada click de
192
+ // "Verificar".
144
193
  let testUrl: string | null = null
145
- let testBody: unknown = null
146
194
  let headers: Record<string, string> = {}
147
195
 
148
- const testMessages = [{ role: "user" as const, content: "Say 'ok' if you can read this." }]
149
-
150
- // Modelo de prueba: el indicado en el request, o el primer modelo LLM del provider en la BD
151
- let pingModel: string | undefined = model
152
- if (!pingModel) {
153
- try {
154
- const modelsCol = await col<ModelDoc>("models")
155
- const candidates = (await modelsCol.findBy("provider_id", provider)).filter(e => e.doc.model_type === "llm")
156
- const best = [...candidates].sort((a, b) => Number(b.doc.active) - Number(a.doc.active))[0]
157
- pingModel = best?.doc.id
158
- } catch { /* DB may not be initialized yet during early setup — ignore */ }
159
- }
160
-
161
196
  if (provider === "ollama") {
162
197
  const ollamaUrl = process.env.OLLAMA_HOST || "http://localhost:11434"
163
198
  try {
@@ -177,90 +212,115 @@ export async function handleVerifyProvider(req: Request): Promise<Response> {
177
212
  }
178
213
 
179
214
  if (provider === "anthropic") {
180
- testUrl = "https://api.anthropic.com/v1/messages"
181
- testBody = {
182
- model: pingModel || "claude-sonnet-4-6",
183
- max_tokens: 10,
184
- messages: testMessages,
185
- }
215
+ testUrl = "https://api.anthropic.com/v1/models"
186
216
  headers = {
187
- "Content-Type": "application/json",
188
217
  "x-api-key": apiKey,
189
218
  "anthropic-version": "2023-06-01",
190
219
  "anthropic-dangerous-direct-browser-access": "true",
191
220
  }
192
221
  } else if (provider === "openai") {
193
- testUrl = "https://api.openai.com/v1/chat/completions"
194
- testBody = {
195
- model: pingModel || "gpt-4o-mini",
196
- max_tokens: 10,
197
- messages: testMessages,
198
- }
199
- headers = {
200
- "Content-Type": "application/json",
201
- "Authorization": `Bearer ${apiKey}`,
202
- }
222
+ testUrl = "https://api.openai.com/v1/models"
223
+ headers = { "Authorization": `Bearer ${apiKey}` }
203
224
  } else if (provider === "gemini") {
204
- testUrl = `https://generativelanguage.googleapis.com/v1beta/models/${pingModel || "gemini-2.5-flash"}:generateContent?key=${apiKey}`
205
- testBody = {
206
- contents: [{ parts: [{ text: "Say ok" }] }],
207
- }
208
- headers = { "Content-Type": "application/json" }
225
+ testUrl = `https://generativelanguage.googleapis.com/v1beta/models?key=${apiKey}`
209
226
  } else if (provider === "groq") {
210
- testUrl = "https://api.groq.com/openai/v1/chat/completions"
211
- testBody = {
212
- model: pingModel || "llama-3.3-70b-versatile",
213
- max_tokens: 10,
214
- messages: testMessages,
215
- }
216
- headers = {
217
- "Content-Type": "application/json",
218
- "Authorization": `Bearer ${apiKey}`,
219
- }
227
+ testUrl = "https://api.groq.com/openai/v1/models"
228
+ headers = { "Authorization": `Bearer ${apiKey}` }
220
229
  } else if (provider === "openrouter") {
221
- testUrl = "https://openrouter.ai/api/v1/chat/completions"
222
- testBody = {
223
- model: pingModel || "meta-llama/llama-3.3-70b-instruct",
224
- max_tokens: 10,
225
- messages: testMessages,
226
- }
227
- headers = {
228
- "Content-Type": "application/json",
229
- "Authorization": `Bearer ${apiKey}`,
230
- }
230
+ // /api/v1/models es público y responde 200 sin auth — no sirve para
231
+ // validar la key. /api/v1/key sí la exige.
232
+ testUrl = "https://openrouter.ai/api/v1/key"
233
+ headers = { "Authorization": `Bearer ${apiKey}` }
231
234
  } else if (provider === "mistral") {
232
- testUrl = "https://api.mistral.ai/v1/chat/completions"
233
- testBody = {
234
- model: pingModel || "mistral-small-latest",
235
- max_tokens: 10,
236
- messages: testMessages,
237
- }
238
- headers = {
239
- "Content-Type": "application/json",
240
- "Authorization": `Bearer ${apiKey}`,
241
- }
235
+ testUrl = "https://api.mistral.ai/v1/models"
236
+ headers = { "Authorization": `Bearer ${apiKey}` }
242
237
  } else if (provider === "deepseek") {
243
- testUrl = "https://api.deepseek.com/v1/chat/completions"
244
- testBody = {
245
- model: pingModel || "deepseek-chat",
246
- max_tokens: 10,
247
- messages: testMessages,
238
+ testUrl = "https://api.deepseek.com/v1/models"
239
+ headers = { "Authorization": `Bearer ${apiKey}` }
240
+ } else if (provider === "kimi") {
241
+ testUrl = "https://api.moonshot.ai/v1/models"
242
+ headers = { "Authorization": `Bearer ${apiKey}` }
243
+ } else if (PUBLIC_MODEL_LIST.has(provider)) {
244
+ const baseUrl = (await providerBaseUrl(provider))?.replace(/\/+$/, "")
245
+ if (!baseUrl) {
246
+ return Response.json({
247
+ success: false,
248
+ error: `El provider "${provider}" no tiene base_url configurada. Agregala en su configuración.`,
249
+ })
248
250
  }
249
- headers = {
250
- "Content-Type": "application/json",
251
- "Authorization": `Bearer ${apiKey}`,
251
+ // Modelos que ya verificamos manualmente como chat/tool-calling en el
252
+ // seed (storage/seed.ts) — van primero porque son los que más chance
253
+ // tienen de estar habilitados para la cuenta. El listado público de
254
+ // NVIDIA mezcla chat con embeddings/rerank (p.ej. `baai/bge-m3`), que
255
+ // jamás van a responder en /chat/completions sea cual sea la key.
256
+ let curatedModels: string[] = []
257
+ try {
258
+ const modelsCol = await col<ModelDoc>("models")
259
+ curatedModels = (await modelsCol.findBy("provider_id", provider))
260
+ .filter(e => e.doc.model_type === "llm")
261
+ .map(e => wireModelId(provider, e.doc.id))
262
+ } catch { /* DB puede no estar lista en early setup — se sigue con el catálogo vivo */ }
263
+
264
+ let liveModels: string[] = []
265
+ try {
266
+ const listRes = await fetch(`${baseUrl}/models`, { signal: AbortSignal.timeout(10000) })
267
+ const listData = await listRes.json() as { data?: Array<{ id: string }> }
268
+ const NON_CHAT = /embed|rerank|bge|colbert|clip|e5-|gte-|whisper|tts|guard/i
269
+ liveModels = (listData.data ?? [])
270
+ .map(m => m.id)
271
+ .filter(id => id && !NON_CHAT.test(id))
272
+ } catch { /* liveModels queda vacío, se sigue con lo curado si hay */ }
273
+
274
+ const candidates = [...new Set([...curatedModels, ...liveModels])].slice(0, 6)
275
+ if (candidates.length === 0) {
276
+ return Response.json({
277
+ success: false,
278
+ error: `No se pudo obtener el catálogo de modelos de "${provider}" para probar la key.`,
279
+ })
252
280
  }
253
- } else if (provider === "kimi") {
254
- testUrl = "https://api.moonshot.cn/v1/chat/completions"
255
- testBody = {
256
- model: pingModel || "moonshot-v1-8k",
257
- max_tokens: 10,
258
- messages: testMessages,
281
+ // El catálogo público de NVIDIA lista modelos que no siempre están
282
+ // habilitados para la cuenta puntual (404 "Function not found for
283
+ // account" aunque la key sea válida) — se prueban varios candidatos y
284
+ // sólo un 401/403 real se toma como key inválida. Cualquier otro error
285
+ // (404, 410, etc.) pasa al siguiente candidato.
286
+ let lastStatus = 0
287
+ let lastBody = ""
288
+ for (const candidate of candidates) {
289
+ const pingRes = await fetch(`${baseUrl}/chat/completions`, {
290
+ method: "POST",
291
+ headers: { "Content-Type": "application/json", "Authorization": `Bearer ${apiKey}` },
292
+ body: JSON.stringify({
293
+ model: candidate,
294
+ max_tokens: 10,
295
+ messages: [{ role: "user", content: "Say 'ok' if you can read this." }],
296
+ }),
297
+ signal: AbortSignal.timeout(10000),
298
+ })
299
+ if (pingRes.ok) return Response.json({ success: true, error: null })
300
+ lastStatus = pingRes.status
301
+ lastBody = (await pingRes.text()).slice(0, 300)
302
+ if (pingRes.status === 401 || pingRes.status === 403) break // key inválida, no tiene sentido seguir probando
303
+ log.warn(`verify-provider ${provider}: modelo=${candidate} status=${pingRes.status} body=${lastBody} — probando siguiente candidato`)
259
304
  }
260
- headers = {
261
- "Content-Type": "application/json",
262
- "Authorization": `Bearer ${apiKey}`,
305
+ log.warn(`verify-provider ${provider} falló tras ${candidates.length} candidato(s): último status=${lastStatus} body=${lastBody}`)
306
+ return Response.json({
307
+ success: false,
308
+ error: `API error: ${lastStatus}`,
309
+ })
310
+ } else if (OPENAI_COMPAT_PING.has(provider)) {
311
+ // Resto de providers OpenAI-compatibles: mismo shape de request, sólo
312
+ // cambia el host. Sin esto, verificar su API key devolvía "Unsupported
313
+ // provider" aunque el provider funcionara perfectamente.
314
+ // Host sale de la BD; no hay catálogo fijo acá.
315
+ const baseUrl = (await providerBaseUrl(provider))?.replace(/\/+$/, "")
316
+ if (!baseUrl) {
317
+ return Response.json({
318
+ success: false,
319
+ error: `El provider "${provider}" no tiene base_url configurada. Agregala en su configuración.`,
320
+ })
263
321
  }
322
+ testUrl = `${baseUrl}/models`
323
+ headers = { "Authorization": `Bearer ${apiKey}` }
264
324
  }
265
325
 
266
326
  if (provider === "hiveagents") {
@@ -295,20 +355,31 @@ export async function handleVerifyProvider(req: Request): Promise<Response> {
295
355
  }
296
356
 
297
357
  const response = await fetch(testUrl, {
298
- method: "POST",
358
+ method: "GET",
299
359
  headers,
300
- body: JSON.stringify(testBody),
301
360
  signal: AbortSignal.timeout(10000),
302
361
  })
303
362
 
363
+ if (!response.ok) {
364
+ log.warn(`verify-provider ${provider} falló: url=${testUrl} status=${response.status} body=${(await response.text()).slice(0, 300)}`)
365
+ }
366
+
304
367
  return Response.json({
305
368
  success: response.ok,
306
369
  error: response.ok ? null : `API error: ${response.status}`,
307
370
  })
308
371
  } catch (error) {
372
+ const message = (error as Error).message
373
+ log.warn(`verify-provider ${provider} excepción: ${message}`)
374
+ // fetch() rechaza el request antes de mandarlo si el header Authorization
375
+ // trae un carácter inválido (control chars, no-ASCII) — pasa con keys
376
+ // pegadas con basura invisible en el medio, no sólo al final.
377
+ const isHeaderError = /header/i.test(message) && /invalid/i.test(message)
309
378
  return Response.json({
310
379
  success: false,
311
- error: `Connection error: ${(error as Error).message}`,
380
+ error: isHeaderError
381
+ ? "La API key tiene caracteres inválidos (revisá que no tenga saltos de línea o espacios raros al copiarla)."
382
+ : `Connection error: ${message}`,
312
383
  })
313
384
  }
314
385
  }
@@ -207,14 +207,17 @@ export async function handleTriggerUpdate(
207
207
  break
208
208
 
209
209
  case "binary":
210
+ // Este gateway compilado corre embebido dentro de la app de
211
+ // escritorio (Tauri) — GitHub Releases ya no publica binarios
212
+ // standalone sueltos, así que no hay un "archivo" que reemplazar
213
+ // manualmente. La actualización real la maneja el updater de Tauri.
210
214
  return addCorsHeaders(Response.json({
211
215
  success: false,
212
- error: "Para actualizar el binario, descarga la última versión desde https://github.com/johpaz/hive/releases/latest",
216
+ error: "La app de escritorio se actualiza sola. Si no viste el aviso de actualización, reinícia la app o descarga el instalador más reciente.",
213
217
  instructions: [
214
- "1. Visita https://github.com/johpaz/hive/releases/latest",
215
- "2. Descarga el binario para tu sistema operativo",
216
- "3. Reemplaza el archivo existente",
217
- "4. Ejecuta: hive start"
218
+ "1. La app revisa actualizaciones al iniciar y las instala automáticamente",
219
+ "2. Si el aviso no aparece, cierra y volvé a abrir la app",
220
+ "3. Alternativa manual: descargá el instalador de tu sistema desde https://github.com/johpaz/hive/releases/latest y ejecutalo — reemplaza la instalación existente"
218
221
  ]
219
222
  }), req)
220
223
 
@@ -103,6 +103,9 @@ export async function handleGetVoiceProviderVoices(
103
103
  case "gemini":
104
104
  voices = voiceService.getGeminiVoices()
105
105
  break
106
+ case "groq":
107
+ voices = voiceService.getGroqVoices()
108
+ break
106
109
  case "qwen":
107
110
  voices = voiceService.getQwenVoices()
108
111
  break
@@ -1,6 +1,7 @@
1
1
  import type { Config } from "../config/loader";
2
2
  import { loadConfig, getHiveDir } from "../config/loader";
3
3
  import { logger, onLogEntry } from "../utils/logger";
4
+ import { resolveUISource } from "./helpers/ui-source";
4
5
  import { sessionManager, parseSessionId } from "./session";
5
6
  import { enqueueChatTurn, initWebchatTurnRunner } from "./webchat-turn";
6
7
  import {
@@ -44,9 +45,11 @@ import { handleSetupStatus, handleVerifyProvider, handleCompleteSetup, handleSet
44
45
  import { handleAuthStatus, handleLogin, handleSetupCredentials, handleChangePassword, handleRecover, handleDisableAuth, handleRecoveryKey } from "./routes/auth";
45
46
  import { resolveUserId } from "../storage/onboarding";
46
47
  import { handleGetAgents, handleCreateAgent, handleUpdateAgent, handleDeleteAgent, handleGetAgentProposals } from "./routes/agents";
47
- import { handleGetProviders, handleCreateProvider, handleToggleProvider, handleUpdateProvider, handleSyncProviderModels, handleLoadHiveAgentsModel, handleGetHiveAgentsModelStatus } from "./routes/providers";
48
+ import { handleGetProviders, handleCreateProvider, handleToggleProvider, handleUpdateProvider, handleSyncProviderModels, handleGetProviderAvailableModels, handleLoadHiveAgentsModel, handleGetHiveAgentsModelStatus } from "./routes/providers";
48
49
  import { handleGetUsers, handleCreateUser, handleUpdateUserSettings, handleGetUserChannels, handleLinkUserChannel } from "./routes/users";
49
50
  import { handleGetSkills, handleActivateSkill, handleUpdateSkill, handleDeleteSkill, handleCreateSkill } from "./routes/skills";
51
+ import { handleGetA2UISurfaces, handleDeleteA2UISurface } from "./routes/a2ui";
52
+ import { handleGetRuntimeStatus } from "./routes/runtime";
50
53
  import { handleGetEthics, handleActivateEthics, handleDeleteEthics } from "./routes/ethics";
51
54
  import { handleGetTools, handleActivateTool, handleUpdateTool } from "./routes/tools";
52
55
  import { handleGetTasks, handleUpdateTask } from "./routes/tasks";
@@ -57,6 +60,13 @@ import {
57
60
  markNotificationDelivered,
58
61
  } from "./notification-inbox";
59
62
  import { setNarrationDelivery } from "../events/narration";
63
+ import {
64
+ resolveNarrationMode,
65
+ shouldDeliverToChannel,
66
+ formatNarrationForChannel,
67
+ enqueueChannelNarration,
68
+ awaitChannelNarration,
69
+ } from "../events/channel-narration";
60
70
  import { CronScheduler } from "../scheduler/CronScheduler";
61
71
  import { createTaskHandler, setSchedulerForCleanup } from "../scheduler/integration";
62
72
 
@@ -214,7 +224,7 @@ export async function startGateway(
214
224
  type: metadata?.notificationId ? "notification" : "progress",
215
225
  sessionId,
216
226
  notificationId: metadata?.notificationId,
217
- });
227
+ }, metadata?.accountId);
218
228
  });
219
229
  setNarrationDelivery(async (event) => {
220
230
  if (event.channel === "webchat" && event.session_id) {
@@ -234,12 +244,20 @@ export async function startGateway(
234
244
  return;
235
245
  }
236
246
  }
237
- if (event.channel && event.session_id) {
247
+ if (!event.channel || !event.session_id) return;
248
+
249
+ // Messaging channels turn every event into a permanent chat message, so
250
+ // they get a filtered feed (see events/channel-narration.ts) delivered
251
+ // off the agent loop's critical path.
252
+ const mode = await resolveNarrationMode(event.channel);
253
+ if (!shouldDeliverToChannel(event, mode)) return;
254
+
255
+ enqueueChannelNarration(`${event.channel}:${event.session_id}`, async () => {
238
256
  await channelManager.send(event.channel, event.session_id, {
239
- content: event.detail ? `${event.label}: ${event.detail}` : event.label,
257
+ content: formatNarrationForChannel(event),
240
258
  type: "progress",
241
259
  });
242
- }
260
+ });
243
261
  });
244
262
 
245
263
  if (gatewaySetupMode) {
@@ -504,6 +522,7 @@ export async function startGateway(
504
522
  const { userId, threadId: conversationThreadId } = await resolveContext({
505
523
  channel: message.channel,
506
524
  channelUserId: message.sessionId,
525
+ accountId: message.accountId,
507
526
  });
508
527
 
509
528
  const telegramMeta = message.metadata?.telegram as { messageId?: number } | undefined;
@@ -595,6 +614,10 @@ export async function startGateway(
595
614
  }
596
615
  log.info(`📤 LLM response: ${responseContent.substring(0, 100)}${responseContent.length > 100 ? "..." : ""}`);
597
616
 
617
+ // Narration is delivered off the critical path — let it drain first so the
618
+ // final answer lands after the progress messages, not before them.
619
+ await awaitChannelNarration(`${message.channel}:${routingSessionId}`);
620
+
598
621
  const shouldSpeak = preferAudioResponse;
599
622
  let responseType: "text" | "audio" = "text";
600
623
  let ttsProviderUsed: string | null = null;
@@ -616,7 +639,7 @@ export async function startGateway(
616
639
  responseType = "audio";
617
640
 
618
641
  try {
619
- const channel = channelManager.getChannel(message.channel);
642
+ const channel = channelManager.getChannel(message.channel, message.accountId);
620
643
  if (channel?.sendAudio) {
621
644
  await channel.sendAudio(routingSessionId, audioOutput.data as Buffer, audioOutput.mimeType);
622
645
  log.info(`✅ Audio sent to ${routingSessionId}`);
@@ -887,16 +910,16 @@ export async function startGateway(
887
910
  return new Response("Not found", { status: 404 });
888
911
  }
889
912
 
890
- // In production: serve from dist folder
891
- // Priority: HIVE_UI_DIR (Docker) > ~/.hive/ui > HIVE_DIST_DIR/ui (global npm) > cwd/packages/hive-ui/dist (monorepo)
892
- const uiDirFromEnv = process.env.HIVE_UI_DIR;
893
- const uiDirFromHive = path.join(getHiveDir(), "ui");
894
- const uiDirFromDist = process.env.HIVE_DIST_DIR ? path.join(process.env.HIVE_DIST_DIR, "ui") : null;
895
- const uiDirFromCwd = path.join(process.cwd(), "packages/hive-ui/dist");
896
- const uiDir = uiDirFromEnv
897
- || (existsSync(path.join(uiDirFromHive, "index.html")) ? uiDirFromHive
898
- : uiDirFromDist && existsSync(path.join(uiDirFromDist, "index.html")) ? uiDirFromDist
899
- : uiDirFromCwd);
913
+ // In production: serve from dist folder, o del bundle embebido si no
914
+ // hay nada en disco. Ver helpers/ui-source.ts para el orden y por qué
915
+ // el disco le gana al embed.
916
+ const uiSource = resolveUISource({
917
+ uiDirEnv: process.env.HIVE_UI_DIR,
918
+ distDirEnv: process.env.HIVE_DIST_DIR,
919
+ hiveDir: getHiveDir(),
920
+ cwd: process.cwd(),
921
+ hasEmbedded: Boolean(embeddedUI?.size),
922
+ });
900
923
  let subPath = url.pathname;
901
924
 
902
925
  // En setup mode: / y /ui redirigen a /setup
@@ -927,7 +950,7 @@ export async function startGateway(
927
950
  // Standalone executables carry the UI inside the Bun binary. The CLI
928
951
  // passes that bundle into the child gateway process so both API and
929
952
  // UI continue to share a single port without extracting files.
930
- if (embeddedUI?.size) {
953
+ if (uiSource.kind === "embedded" && embeddedUI) {
931
954
  const entry = embeddedUI.get(subPath)
932
955
  ?? (!path.extname(subPath) ? embeddedUI.get("/index.html") : undefined);
933
956
  if (entry) {
@@ -942,17 +965,18 @@ export async function startGateway(
942
965
  }
943
966
  }
944
967
 
945
- const filePath = path.join(uiDir, subPath);
946
- const uiFile = Bun.file(filePath);
947
- if (await uiFile.exists()) {
948
- return new Response(uiFile);
949
- }
968
+ if (uiSource.kind === "disk") {
969
+ const uiFile = Bun.file(path.join(uiSource.dir, subPath));
970
+ if (await uiFile.exists()) {
971
+ return new Response(uiFile);
972
+ }
950
973
 
951
- // SPA fallback: paths without a file extension are React Router routes — serve index.html
952
- if (!path.extname(subPath)) {
953
- const indexFile = Bun.file(path.join(uiDir, "index.html"));
954
- if (await indexFile.exists()) {
955
- return new Response(indexFile);
974
+ // SPA fallback: paths without a file extension are React Router routes — serve index.html
975
+ if (!path.extname(subPath)) {
976
+ const indexFile = Bun.file(path.join(uiSource.dir, "index.html"));
977
+ if (await indexFile.exists()) {
978
+ return new Response(indexFile);
979
+ }
956
980
  }
957
981
  }
958
982
 
@@ -985,6 +1009,20 @@ export async function startGateway(
985
1009
  return addCorsHeaders(await handleSetupStatus(), req)
986
1010
  }
987
1011
 
1012
+ // GET /api/a2ui/surfaces — exact surface IDs for the authenticated canvas session
1013
+ if ((url.pathname === "/api/a2ui/surfaces" || url.pathname === "/api/a2ui/surfaces/") && req.method === "GET") {
1014
+ return await handleGetA2UISurfaces(req, addCorsHeaders)
1015
+ }
1016
+ const a2uiSurfaceMatch = url.pathname.match(/^\/api\/a2ui\/surfaces\/([^/]+)$/)
1017
+ if (a2uiSurfaceMatch && req.method === "DELETE") {
1018
+ return await handleDeleteA2UISurface(req, addCorsHeaders)
1019
+ }
1020
+
1021
+ // GET /api/system/runtime — catalog/sidecar diagnostics for desktop support
1022
+ if ((url.pathname === "/api/system/runtime" || url.pathname === "/api/system/runtime/") && req.method === "GET") {
1023
+ return await handleGetRuntimeStatus(req, addCorsHeaders)
1024
+ }
1025
+
988
1026
  // GET /api/setup/providers
989
1027
  if (url.pathname === "/api/setup/providers" && req.method === "GET") {
990
1028
  return handleSetupProviders(addCorsHeaders, req)
@@ -1045,7 +1083,9 @@ export async function startGateway(
1045
1083
  return addCorsHeaders(new Response(
1046
1084
  JSON.stringify({
1047
1085
  status: "ok",
1048
- version: "0.1.7",
1086
+ // Estaba hardcodeada en "0.1.7" mientras package.json iba por 1.0.1:
1087
+ // /status mentía sobre qué versión estaba corriendo.
1088
+ version: _pkgVersion,
1049
1089
  uptime: Math.floor((Date.now() - startTime) / 1000),
1050
1090
  gateway: { host, port },
1051
1091
  sessions: sessionManager.list().map((s) => ({
@@ -1323,6 +1363,12 @@ export async function startGateway(
1323
1363
  return await handleSyncProviderModels(req, addCorsHeaders, providerId)
1324
1364
  }
1325
1365
 
1366
+ // GET /api/providers/:id/available-models — lista lo que sirve el provider, sin persistir
1367
+ const availableModelsMatch = url.pathname.match(/^\/api\/providers\/([^/]+)\/available-models$/)
1368
+ if (availableModelsMatch && req.method === "GET") {
1369
+ return await handleGetProviderAvailableModels(req, addCorsHeaders, availableModelsMatch[1])
1370
+ }
1371
+
1326
1372
  // POST /api/models - Create a new model
1327
1373
  if (url.pathname === "/api/models" && req.method === "POST") {
1328
1374
  return await handleCreateModel(req, addCorsHeaders)
@@ -21,6 +21,7 @@ import { sendToUserChannel } from "./channel-notify";
21
21
  import { getNarration } from "./helpers";
22
22
  import { createRun, getRun } from "../agent/run-store";
23
23
  import { getDurableQueue } from "./durable-queue";
24
+ import { sessionManager } from "./session";
24
25
  import type { JobDoc, TurnSource } from "../storage/collections";
25
26
 
26
27
  const log = logger.child("webchat-turn");
@@ -423,11 +424,34 @@ export async function runWebchatTurn(
423
424
  }
424
425
  }
425
426
  } else if (content && payload.source !== "api") {
426
- // Rehydrated turn (crash recovery): nobody streamed this response, so
427
- // deliver the final content through the user's channel.
428
- await sendToUserChannel(channel, userId, content).catch((err) =>
429
- log.warn(`[runWebchatTurn] Failed to deliver crash-recovered response: ${(err as Error).message}`)
430
- );
427
+ // No live callback was attached to this job — either a genuine crash
428
+ // recovery, or (the common case for "delegation_summary"/"task_complete")
429
+ // a turn enqueued from a background job's terminal hook, which never has
430
+ // access to the original request's socket. Before falling back to the
431
+ // notification/toast path, check whether the user's browser still holds
432
+ // an open WS session under this exact sessionId — narration delivery
433
+ // (server.ts) already does this same lookup — and if so, push the
434
+ // response there as a normal chat message instead of a toast.
435
+ const liveSession = channel === "webchat" ? sessionManager.get(sessionId) : undefined;
436
+ const liveWs = liveSession?.ws?.readyState === 1 ? liveSession.ws : null;
437
+ if (liveWs) {
438
+ try {
439
+ liveWs.send(JSON.stringify({ type: "message", id: messageId, sessionId, content, isStep: false }));
440
+ liveWs.send(JSON.stringify({ type: "typing", isTyping: false, sessionId }));
441
+ } catch (err) {
442
+ log.warn(`[runWebchatTurn] Live push to open session failed, falling back to notification: ${(err as Error).message}`);
443
+ await sendToUserChannel(channel, userId, content).catch((err2) =>
444
+ log.warn(`[runWebchatTurn] Failed to deliver response: ${(err2 as Error).message}`)
445
+ );
446
+ }
447
+ } else {
448
+ // Rehydrated turn (crash recovery), or the user's browser isn't
449
+ // connected right now: deliver the final content through the user's
450
+ // channel (persisted notification for webchat; push API for the rest).
451
+ await sendToUserChannel(channel, userId, content).catch((err) =>
452
+ log.warn(`[runWebchatTurn] Failed to deliver crash-recovered response: ${(err as Error).message}`)
453
+ );
454
+ }
431
455
  }
432
456
 
433
457
  if (delegationGroup) {
@@ -13,7 +13,7 @@ export * from "./agent/skill-selector.ts";
13
13
  export * from "./agent/playbook-selector.ts";
14
14
  export * from "./agent/catalog-selector.ts";
15
15
  export * from "./agent/delegation-runtime.ts";
16
- export * from "./agent/acceptance-verifier.ts";
16
+ export * from "./agent/acceptance-checks.ts";
17
17
  export * from "./agent/llm-client.ts";
18
18
 
19
19
  // Channels