@johpaz/hive-agents 1.0.1 → 1.0.3

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 (120) hide show
  1. package/README.md +3 -3
  2. package/dist/hive.js +1286 -764
  3. package/dist/ui/assets/A2UIPage-DExwevBV.js +8 -0
  4. package/dist/ui/assets/{AgentCreateForm-M2RhjeA1.js → AgentCreateForm-7PPShsUn.js} +1 -1
  5. package/dist/ui/assets/{AgentDetailPage-DkFRtj8g.js → AgentDetailPage-CiV4tz4P.js} +1 -1
  6. package/dist/ui/assets/AgentNewPage-D3TtVwQf.js +1 -0
  7. package/dist/ui/assets/{AgentsPage-Ctzq2LWx.js → AgentsPage-C2DThet7.js} +1 -1
  8. package/dist/ui/assets/{ApiClientPage-DKbGO1QW.js → ApiClientPage-Cowdq-0f.js} +1 -1
  9. package/dist/ui/assets/{ChannelsPage-H6rgr8DQ.js → ChannelsPage-D4IgglwJ.js} +1 -1
  10. package/dist/ui/assets/{DashboardPage-BIjYGf4m.js → DashboardPage-DAgVB7Iy.js} +1 -1
  11. package/dist/ui/assets/{LoginPage-DazoxtBJ.js → LoginPage-CpU61b3u.js} +1 -1
  12. package/dist/ui/assets/{LogsPage-DMZ6KtQ3.js → LogsPage-DyJOGQNy.js} +1 -1
  13. package/dist/ui/assets/{MeetingPage-CSLFvHL7.js → MeetingPage-DLmqHmm2.js} +1 -1
  14. package/dist/ui/assets/{ModelSelector-BCfvugHB.js → ModelSelector-D4OaICwN.js} +1 -1
  15. package/dist/ui/assets/{Office3DPage-BE6Epe0d.js → Office3DPage-BvO66B0h.js} +1 -1
  16. package/dist/ui/assets/{ProvidersPage-D0cApfM1.js → ProvidersPage-Bhb6Qr87.js} +1 -1
  17. package/dist/ui/assets/{RecoverPage-BVUPHG9z.js → RecoverPage-DaZrCpdB.js} +1 -1
  18. package/dist/ui/assets/SettingsPage-BRD2F7up.js +9 -0
  19. package/dist/ui/assets/{SetupPage-In19p30M.js → SetupPage-DKppgTja.js} +1 -1
  20. package/dist/ui/assets/WebChatPage-CPtETNL5.js +29 -0
  21. package/dist/ui/assets/{activity-BIIli7ET.js → activity-BSosMryb.js} +1 -1
  22. package/dist/ui/assets/{agentCapabilities-D1PD9yFH.js → agentCapabilities-VqxLmrF6.js} +1 -1
  23. package/dist/ui/assets/arrow-left-C9Y6p4Jt.js +1 -0
  24. package/dist/ui/assets/arrow-right-BYfOLnTB.js +1 -0
  25. package/dist/ui/assets/arrow-up-right-D2trA3Ob.js +1 -0
  26. package/dist/ui/assets/{calendar-S9-_Q6QR.js → calendar-rdd4nvY1.js} +1 -1
  27. package/dist/ui/assets/check-DUq9uoNQ.js +1 -0
  28. package/dist/ui/assets/chevron-down-rPF4Pr1n.js +1 -0
  29. package/dist/ui/assets/chevron-left-Crzzf2sY.js +1 -0
  30. package/dist/ui/assets/chevron-right-DtMIvG9A.js +1 -0
  31. package/dist/ui/assets/chevron-up-CG0_KGBy.js +1 -0
  32. package/dist/ui/assets/{circle-alert-DTVW4R94.js → circle-alert-CYt6gsDA.js} +1 -1
  33. package/dist/ui/assets/circle-check-Zl32-jCa.js +1 -0
  34. package/dist/ui/assets/{circle-x-CJXbXzRh.js → circle-x-BJXzKGmx.js} +1 -1
  35. package/dist/ui/assets/{copy-X_TPpA-A.js → copy-BmtJXmDe.js} +1 -1
  36. package/dist/ui/assets/{dialog-uUBz_NIB.js → dialog-Dn9hGPYl.js} +1 -1
  37. package/dist/ui/assets/{download-C-fXu08w.js → download-D3mYhuuL.js} +1 -1
  38. package/dist/ui/assets/{earth-CTsVjCmp.js → earth-BZzdDXFC.js} +1 -1
  39. package/dist/ui/assets/{ellipsis-vertical-5zBh5yzc.js → ellipsis-vertical-BF705XvB.js} +1 -1
  40. package/dist/ui/assets/{external-link-CvpRhwC_.js → external-link-gdpMTHUV.js} +1 -1
  41. package/dist/ui/assets/{eye-CM-HQEWU.js → eye-lSG04hI7.js} +1 -1
  42. package/dist/ui/assets/{file-text-lwkvYGtA.js → file-text-CjQxcJvN.js} +1 -1
  43. package/dist/ui/assets/gauge-DBryKhDK.js +1 -0
  44. package/dist/ui/assets/{history-eSHspWRr.js → history-BC6ir9qU.js} +1 -1
  45. package/dist/ui/assets/{index-ZjAc-KQS.js → index-DyxoAvTq.js} +2 -2
  46. package/dist/ui/assets/index-wML8DaUo.css +2 -0
  47. package/dist/ui/assets/{info-DTgFQ_jA.js → info-BGBaIyKc.js} +1 -1
  48. package/dist/ui/assets/{key-CeM9JJkq.js → key-D_CNJTY2.js} +1 -1
  49. package/dist/ui/assets/loader-circle-RXdrfPsH.js +1 -0
  50. package/dist/ui/assets/{lock-open-B089GUAJ.js → lock-open-UB61lorP.js} +1 -1
  51. package/dist/ui/assets/{mail--gNFIe4M.js → mail-C5bJ_dBt.js} +1 -1
  52. package/dist/ui/assets/{pause-DjT1nwQM.js → pause-BSTJvxDu.js} +1 -1
  53. package/dist/ui/assets/{pencil-6PRgdjiU.js → pencil-C2B1Q7y2.js} +1 -1
  54. package/dist/ui/assets/play-tcMbj-0p.js +1 -0
  55. package/dist/ui/assets/plus-BSZvyMND.js +1 -0
  56. package/dist/ui/assets/{radio-D-joO9J0.js → radio-D9CrjAar.js} +1 -1
  57. package/dist/ui/assets/{refresh-cw-BRrzoHQW.js → refresh-cw-D7EB_fVv.js} +1 -1
  58. package/dist/ui/assets/search-5S6LY69I.js +1 -0
  59. package/dist/ui/assets/{select-BOR8MsSL.js → select-ot0a6art.js} +1 -1
  60. package/dist/ui/assets/{send-DIlj81PT.js → send-Dax1tJ5b.js} +1 -1
  61. package/dist/ui/assets/{settings-CkBjgAEm.js → settings-97CL32lC.js} +1 -1
  62. package/dist/ui/assets/{shield-U0hIjGzm.js → shield-DwbCEZbF.js} +1 -1
  63. package/dist/ui/assets/{sparkles-VXHGDbNh.js → sparkles-CWMAzkpD.js} +1 -1
  64. package/dist/ui/assets/{square-OHeetvN3.js → square-B4dgTXI3.js} +1 -1
  65. package/dist/ui/assets/terminal-DoLedTPM.js +1 -0
  66. package/dist/ui/assets/{trash-2-DQxm7DUM.js → trash-2-DxnVYOz8.js} +1 -1
  67. package/dist/ui/assets/{triangle-alert-Dj8ZhmWj.js → triangle-alert-Cka-BeIE.js} +1 -1
  68. package/dist/ui/assets/{useHiveAgentsModelLoad-COLvs-Ho.js → useHiveAgentsModelLoad-BjnIsQKR.js} +1 -1
  69. package/dist/ui/assets/{useProviders-q6iROeWE.js → useProviders-CueMz_mL.js} +1 -1
  70. package/dist/ui/assets/{volume-x-Bm735CXN.js → volume-x-DLsli9cf.js} +1 -1
  71. package/dist/ui/assets/{wifi-DklBfOZ6.js → wifi-BQRJGfLZ.js} +1 -1
  72. package/dist/ui/assets/{zap-BEZNJ0i0.js → zap-DSR3CEce.js} +1 -1
  73. package/dist/ui/index.html +2 -2
  74. package/package.json +1 -1
  75. package/packages/cli/src/index.ts +23 -17
  76. package/packages/core/src/agent/agent-loop.ts +29 -3
  77. package/packages/core/src/agent/context-compiler.ts +13 -2
  78. package/packages/core/src/agent/mcp-result-normalizer.ts +150 -0
  79. package/packages/core/src/agent/providers/index.ts +8 -0
  80. package/packages/core/src/artifacts/store.ts +16 -0
  81. package/packages/core/src/canvas/canvas-manager.ts +36 -7
  82. package/packages/core/src/channels/base.ts +33 -0
  83. package/packages/core/src/channels/discord.ts +20 -1
  84. package/packages/core/src/channels/slack.ts +21 -2
  85. package/packages/core/src/channels/telegram.ts +16 -1
  86. package/packages/core/src/channels/whatsapp.ts +16 -3
  87. package/packages/core/src/gateway/durable-queue.ts +2 -1
  88. package/packages/core/src/gateway/failure-notify.ts +78 -0
  89. package/packages/core/src/gateway/job-executors.ts +1 -0
  90. package/packages/core/src/gateway/job-store.ts +6 -0
  91. package/packages/core/src/gateway/process-safety.ts +40 -0
  92. package/packages/core/src/gateway/routes/a2ui.ts +43 -0
  93. package/packages/core/src/gateway/routes/artifacts.ts +60 -0
  94. package/packages/core/src/gateway/routes/runtime.ts +58 -0
  95. package/packages/core/src/gateway/routes/setup.ts +127 -108
  96. package/packages/core/src/gateway/server.ts +52 -5
  97. package/packages/core/src/gateway/webchat-turn.ts +40 -1
  98. package/packages/core/src/storage/onboarding.ts +23 -7
  99. package/packages/core/src/storage/seed.ts +31 -2
  100. package/packages/core/src/utils/redact-binary.ts +17 -0
  101. package/dist/ui/assets/A2UIPage-D4nzp5NV.js +0 -8
  102. package/dist/ui/assets/AgentNewPage-CfBU7puz.js +0 -1
  103. package/dist/ui/assets/SettingsPage-DCZ4nql4.js +0 -9
  104. package/dist/ui/assets/WebChatPage-ByVBSzxL.js +0 -29
  105. package/dist/ui/assets/arrow-left-BfcnX8Er.js +0 -1
  106. package/dist/ui/assets/arrow-right-Q-dzAn8k.js +0 -1
  107. package/dist/ui/assets/arrow-up-right-Bf-8wrUQ.js +0 -1
  108. package/dist/ui/assets/check-CryV78SQ.js +0 -1
  109. package/dist/ui/assets/chevron-down-QCtMs-Af.js +0 -1
  110. package/dist/ui/assets/chevron-left-dTGbyl5G.js +0 -1
  111. package/dist/ui/assets/chevron-right-D0GjXbnO.js +0 -1
  112. package/dist/ui/assets/chevron-up-Cg0jO8uT.js +0 -1
  113. package/dist/ui/assets/circle-check-BAolxswA.js +0 -1
  114. package/dist/ui/assets/gauge-CB-cas-h.js +0 -1
  115. package/dist/ui/assets/index-D489S18g.css +0 -2
  116. package/dist/ui/assets/loader-circle-Dtfz4FWw.js +0 -1
  117. package/dist/ui/assets/play-tOrP0xUJ.js +0 -1
  118. package/dist/ui/assets/plus-Cnom3j47.js +0 -1
  119. package/dist/ui/assets/search-D277MUP0.js +0 -1
  120. package/dist/ui/assets/terminal-C6YPcJl_.js +0 -1
@@ -14,6 +14,9 @@ import { normalizeUserEmail } from "../../storage/user-email"
14
14
  import { catalogModelKey, wireModelId } from "../../storage/model-id"
15
15
  import { getHiveDir } from "../../config/loader"
16
16
  import type { Config } from "../../config/loader"
17
+ import { logger } from "../../utils/logger"
18
+
19
+ const log = logger.child("setup")
17
20
 
18
21
  export async function handleSetupProviders(
19
22
  addCorsHeaders: (response: Response, request: Request) => Response,
@@ -139,7 +142,17 @@ export async function handleSetupStatus(): Promise<Response> {
139
142
  * Si el usuario apunta uno a un proxy propio, la verificación usa ese endpoint y
140
143
  * no uno fijo en el código.
141
144
  */
142
- const OPENAI_COMPAT_PING = new Set(["nvidia", "z-ai", "minimax", "qwen", "opencode-go", "modelscope"])
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"])
143
156
 
144
157
  /** base_url del provider tal como está en la BD. */
145
158
  async function providerBaseUrl(providerId: string): Promise<string | null> {
@@ -153,7 +166,12 @@ async function providerBaseUrl(providerId: string): Promise<string | null> {
153
166
 
154
167
  export async function handleVerifyProvider(req: Request): Promise<Response> {
155
168
  const body = await req.json().catch(() => ({}))
156
- 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
157
175
 
158
176
  if (!provider || !apiKey) {
159
177
  return Response.json({
@@ -163,25 +181,18 @@ export async function handleVerifyProvider(req: Request): Promise<Response> {
163
181
  }
164
182
 
165
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".
166
193
  let testUrl: string | null = null
167
- let testBody: unknown = null
168
194
  let headers: Record<string, string> = {}
169
195
 
170
- const testMessages = [{ role: "user" as const, content: "Say 'ok' if you can read this." }]
171
-
172
- // Modelo de prueba: el indicado en el request, o el primer modelo LLM del provider en la BD
173
- let pingModel: string | undefined = model
174
- if (!pingModel) {
175
- try {
176
- const modelsCol = await col<ModelDoc>("models")
177
- const candidates = (await modelsCol.findBy("provider_id", provider)).filter(e => e.doc.model_type === "llm")
178
- const best = [...candidates].sort((a, b) => Number(b.doc.active) - Number(a.doc.active))[0]
179
- // El id de la BD viene prefijado en los providers revendedores; acá se
180
- // arma el fetch a mano, así que hay que mandar el nombre del cable.
181
- pingModel = best ? wireModelId(provider, best.doc.id) : undefined
182
- } catch { /* DB may not be initialized yet during early setup — ignore */ }
183
- }
184
-
185
196
  if (provider === "ollama") {
186
197
  const ollamaUrl = process.env.OLLAMA_HOST || "http://localhost:11434"
187
198
  try {
@@ -201,95 +212,35 @@ export async function handleVerifyProvider(req: Request): Promise<Response> {
201
212
  }
202
213
 
203
214
  if (provider === "anthropic") {
204
- testUrl = "https://api.anthropic.com/v1/messages"
205
- testBody = {
206
- model: pingModel || "claude-sonnet-5",
207
- max_tokens: 10,
208
- messages: testMessages,
209
- }
215
+ testUrl = "https://api.anthropic.com/v1/models"
210
216
  headers = {
211
- "Content-Type": "application/json",
212
217
  "x-api-key": apiKey,
213
218
  "anthropic-version": "2023-06-01",
214
219
  "anthropic-dangerous-direct-browser-access": "true",
215
220
  }
216
221
  } else if (provider === "openai") {
217
- testUrl = "https://api.openai.com/v1/chat/completions"
218
- testBody = {
219
- model: pingModel || "gpt-5.6-luna",
220
- max_tokens: 10,
221
- messages: testMessages,
222
- }
223
- headers = {
224
- "Content-Type": "application/json",
225
- "Authorization": `Bearer ${apiKey}`,
226
- }
222
+ testUrl = "https://api.openai.com/v1/models"
223
+ headers = { "Authorization": `Bearer ${apiKey}` }
227
224
  } else if (provider === "gemini") {
228
- testUrl = `https://generativelanguage.googleapis.com/v1beta/models/${pingModel || "gemini-3.6-flash"}:generateContent?key=${apiKey}`
229
- testBody = {
230
- contents: [{ parts: [{ text: "Say ok" }] }],
231
- }
232
- headers = { "Content-Type": "application/json" }
225
+ testUrl = `https://generativelanguage.googleapis.com/v1beta/models?key=${apiKey}`
233
226
  } else if (provider === "groq") {
234
- testUrl = "https://api.groq.com/openai/v1/chat/completions"
235
- testBody = {
236
- model: pingModel || "llama-3.3-70b-versatile",
237
- max_tokens: 10,
238
- messages: testMessages,
239
- }
240
- headers = {
241
- "Content-Type": "application/json",
242
- "Authorization": `Bearer ${apiKey}`,
243
- }
227
+ testUrl = "https://api.groq.com/openai/v1/models"
228
+ headers = { "Authorization": `Bearer ${apiKey}` }
244
229
  } else if (provider === "openrouter") {
245
- testUrl = "https://openrouter.ai/api/v1/chat/completions"
246
- testBody = {
247
- model: pingModel || "anthropic/claude-sonnet-5",
248
- max_tokens: 10,
249
- messages: testMessages,
250
- }
251
- headers = {
252
- "Content-Type": "application/json",
253
- "Authorization": `Bearer ${apiKey}`,
254
- }
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}` }
255
234
  } else if (provider === "mistral") {
256
- testUrl = "https://api.mistral.ai/v1/chat/completions"
257
- testBody = {
258
- model: pingModel || "mistral-small-latest",
259
- max_tokens: 10,
260
- messages: testMessages,
261
- }
262
- headers = {
263
- "Content-Type": "application/json",
264
- "Authorization": `Bearer ${apiKey}`,
265
- }
235
+ testUrl = "https://api.mistral.ai/v1/models"
236
+ headers = { "Authorization": `Bearer ${apiKey}` }
266
237
  } else if (provider === "deepseek") {
267
- testUrl = "https://api.deepseek.com/v1/chat/completions"
268
- testBody = {
269
- model: pingModel || "deepseek-v4-flash",
270
- max_tokens: 10,
271
- messages: testMessages,
272
- }
273
- headers = {
274
- "Content-Type": "application/json",
275
- "Authorization": `Bearer ${apiKey}`,
276
- }
238
+ testUrl = "https://api.deepseek.com/v1/models"
239
+ headers = { "Authorization": `Bearer ${apiKey}` }
277
240
  } else if (provider === "kimi") {
278
- testUrl = "https://api.moonshot.ai/v1/chat/completions"
279
- testBody = {
280
- model: pingModel || "kimi-k3",
281
- max_tokens: 10,
282
- messages: testMessages,
283
- }
284
- headers = {
285
- "Content-Type": "application/json",
286
- "Authorization": `Bearer ${apiKey}`,
287
- }
288
- } else if (OPENAI_COMPAT_PING.has(provider)) {
289
- // Resto de providers OpenAI-compatibles: mismo shape de request, sólo
290
- // cambia el host. Sin esto, verificar su API key devolvía "Unsupported
291
- // provider" aunque el provider funcionara perfectamente.
292
- // Host y modelo salen de la BD; no hay catálogo fijo acá.
241
+ testUrl = "https://api.moonshot.ai/v1/models"
242
+ headers = { "Authorization": `Bearer ${apiKey}` }
243
+ } else if (PUBLIC_MODEL_LIST.has(provider)) {
293
244
  const baseUrl = (await providerBaseUrl(provider))?.replace(/\/+$/, "")
294
245
  if (!baseUrl) {
295
246
  return Response.json({
@@ -297,22 +248,79 @@ export async function handleVerifyProvider(req: Request): Promise<Response> {
297
248
  error: `El provider "${provider}" no tiene base_url configurada. Agregala en su configuración.`,
298
249
  })
299
250
  }
300
- if (!pingModel) {
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) {
301
276
  return Response.json({
302
277
  success: false,
303
- error: `El provider "${provider}" no tiene modelos en el catálogo para probar la key.`,
278
+ error: `No se pudo obtener el catálogo de modelos de "${provider}" para probar la key.`,
304
279
  })
305
280
  }
306
- testUrl = `${baseUrl}/chat/completions`
307
- testBody = {
308
- model: pingModel,
309
- max_tokens: 10,
310
- 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`)
311
304
  }
312
- headers = {
313
- "Content-Type": "application/json",
314
- "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
+ })
315
321
  }
322
+ testUrl = `${baseUrl}/models`
323
+ headers = { "Authorization": `Bearer ${apiKey}` }
316
324
  }
317
325
 
318
326
  if (provider === "hiveagents") {
@@ -347,20 +355,31 @@ export async function handleVerifyProvider(req: Request): Promise<Response> {
347
355
  }
348
356
 
349
357
  const response = await fetch(testUrl, {
350
- method: "POST",
358
+ method: "GET",
351
359
  headers,
352
- body: JSON.stringify(testBody),
353
360
  signal: AbortSignal.timeout(10000),
354
361
  })
355
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
+
356
367
  return Response.json({
357
368
  success: response.ok,
358
369
  error: response.ok ? null : `API error: ${response.status}`,
359
370
  })
360
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)
361
378
  return Response.json({
362
379
  success: false,
363
- 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}`,
364
383
  })
365
384
  }
366
385
  }
@@ -30,6 +30,8 @@ import { shutdownToolRuntime } from "../tool-runtime";
30
30
  import { initDurableQueue, getDurableQueue } from "./durable-queue";
31
31
  import { initJobExecutors, setJobExecutorMCPManager } from "./job-executors";
32
32
  import { initDelegationNotify } from "./delegation-notify";
33
+ import { initFailureNotify } from "./failure-notify";
34
+ import { installProcessSafetyNet } from "./process-safety";
33
35
  import { findAllPendingJobs, findExpiredLeases, loadJobRetryPolicy } from "./job-store";
34
36
  import type { UserDoc, AgentDoc } from "../storage/collections";
35
37
  import { canvasManager } from "../canvas/canvas-manager.ts";
@@ -48,6 +50,8 @@ import { handleGetAgents, handleCreateAgent, handleUpdateAgent, handleDeleteAgen
48
50
  import { handleGetProviders, handleCreateProvider, handleToggleProvider, handleUpdateProvider, handleSyncProviderModels, handleGetProviderAvailableModels, handleLoadHiveAgentsModel, handleGetHiveAgentsModelStatus } from "./routes/providers";
49
51
  import { handleGetUsers, handleCreateUser, handleUpdateUserSettings, handleGetUserChannels, handleLinkUserChannel } from "./routes/users";
50
52
  import { handleGetSkills, handleActivateSkill, handleUpdateSkill, handleDeleteSkill, handleCreateSkill } from "./routes/skills";
53
+ import { handleGetA2UISurfaces, handleDeleteA2UISurface } from "./routes/a2ui";
54
+ import { handleGetRuntimeStatus } from "./routes/runtime";
51
55
  import { handleGetEthics, handleActivateEthics, handleDeleteEthics } from "./routes/ethics";
52
56
  import { handleGetTools, handleActivateTool, handleUpdateTool } from "./routes/tools";
53
57
  import { handleGetTasks, handleUpdateTask } from "./routes/tasks";
@@ -90,6 +94,7 @@ import { handleGetVoiceProviders, handleGetConfiguredVoiceProviders, handleSaveV
90
94
  import { handleGetVisionProviders, handleGetChannelVision, handleUpdateChannelVision, handleOcrImage } from "./routes/multimodal";
91
95
  import { handleGetLocalTTSStatus, handleGetLocalTTSLogs, handleInstallLocalTTS, handleStartLocalTTS, handleStopLocalTTS, handleSpeakLocalTTS, handleGetAvailableModels, handleGetInstalledVoices, handleDownloadModel, handleGetDownloadLogs, initializeLocalTTS } from "./routes/tts-local";
92
96
  import { handleCreateMeeting, handleListMeetings, handleGetMeeting, handleAddMeetingSegment, handleStopMeeting, handleGenerateMeetingReport, handleDownloadMeetingReport } from "./routes/meeting";
97
+ import { handleDownloadArtifact } from "./routes/artifacts";
93
98
  import { handleGetActivityStats, handleGetSystemStats, handleGetUsageStats, handleSystemReload, handleApiReload, handleGetVersion, handleTriggerUpdate } from "./routes/system";
94
99
  import { handleGetChatHistory, handleGetNotes, handleUpdateNote } from "./routes/chat";
95
100
  import { handleChat as handlePostChat } from "./routes/chat";
@@ -133,6 +138,11 @@ export async function startGateway(
133
138
 
134
139
  const log = logger.child("gateway");
135
140
 
141
+ // Installed first, before anything else can throw: an exception no catch
142
+ // block reaches should crash loudly and exit cleanly, not hang silently
143
+ // (see process-safety.ts).
144
+ installProcessSafetyNet();
145
+
136
146
  log.info(`Starting gateway on ${host}:${port}`);
137
147
 
138
148
  // ── Auto-generate auth token if not provided ─────────────────────────────
@@ -289,6 +299,9 @@ export async function startGateway(
289
299
  // Closes the async task_delegate loop: relays worker_task outcomes
290
300
  // back into the delegating conversation (see delegation-notify.ts).
291
301
  initDelegationNotify();
302
+ // Never let a chat_turn/goal_run fail without telling the user (see
303
+ // failure-notify.ts) — previously only worker_task had a terminal hook.
304
+ initFailureNotify();
292
305
  log.info(`🔀 DurableQueue initialized (maxConcurrency=${durableQueue.getMaxGlobalConcurrency()})`);
293
306
 
294
307
  // Create and boot scheduler
@@ -612,6 +625,11 @@ export async function startGateway(
612
625
  }
613
626
  log.info(`📤 LLM response: ${responseContent.substring(0, 100)}${responseContent.length > 100 ? "..." : ""}`);
614
627
 
628
+ // Image artifacts (e.g. an MCP image-generation tool's result — see
629
+ // mcp-result-normalizer.ts) produced this turn, most recent first channel
630
+ // send only carries one at a time for now.
631
+ const imageArtifact = response.imageArtifacts?.[response.imageArtifacts.length - 1];
632
+
615
633
  // Narration is delivered off the critical path — let it drain first so the
616
634
  // final answer lands after the progress messages, not before them.
617
635
  await awaitChannelNarration(`${message.channel}:${routingSessionId}`);
@@ -620,13 +638,17 @@ export async function startGateway(
620
638
  let responseType: "text" | "audio" = "text";
621
639
  let ttsProviderUsed: string | null = null;
622
640
  let ttsMimeType: string | null = null;
641
+ const imageField = imageArtifact
642
+ ? { image: { artifactId: imageArtifact.artifactId, mimeType: imageArtifact.mimeType } }
643
+ : {};
623
644
 
624
645
  if (responseContent) {
625
646
  if (shouldSpeak) {
626
647
  if (!voiceConfig.ttsProvider) {
627
648
  log.warn(`⚠️ TTS provider not configured, user requested audio`);
628
649
  await channelManager.send(message.channel, routingSessionId, {
629
- content: `${responseContent}\n\n🔊 Para recibir respuestas en audio, configura el proveedor TTS en Configuración > Canales > [Tu canal] (ej: elevenlabs, openai-tts)`
650
+ content: `${responseContent}\n\n🔊 Para recibir respuestas en audio, configura el proveedor TTS en Configuración > Canales > [Tu canal] (ej: elevenlabs, openai-tts)`,
651
+ ...imageField,
630
652
  });
631
653
  } else {
632
654
  try {
@@ -641,22 +663,27 @@ export async function startGateway(
641
663
  if (channel?.sendAudio) {
642
664
  await channel.sendAudio(routingSessionId, audioOutput.data as Buffer, audioOutput.mimeType);
643
665
  log.info(`✅ Audio sent to ${routingSessionId}`);
666
+ // sendAudio() is a dedicated binary path, separate from
667
+ // send(OutboundMessage) — the image needs its own send() call.
668
+ if (imageArtifact) {
669
+ await channelManager.send(message.channel, routingSessionId, { content: "", ...imageField });
670
+ }
644
671
  } else {
645
672
  log.warn(`Channel ${message.channel} does not support audio, sending text`);
646
- await channelManager.send(message.channel, routingSessionId, { content: responseContent });
673
+ await channelManager.send(message.channel, routingSessionId, { content: responseContent, ...imageField });
647
674
  }
648
675
  } catch (audioError) {
649
676
  log.error(`❌ Audio send failed: ${(audioError as Error).message}, sending text instead`);
650
677
  // Fallback to text
651
- await channelManager.send(message.channel, routingSessionId, { content: responseContent });
678
+ await channelManager.send(message.channel, routingSessionId, { content: responseContent, ...imageField });
652
679
  }
653
680
  } catch (ttsError) {
654
681
  log.error(`❌ TTS failed: ${(ttsError as Error).message}, sending text instead`);
655
- await channelManager.send(message.channel, routingSessionId, { content: responseContent });
682
+ await channelManager.send(message.channel, routingSessionId, { content: responseContent, ...imageField });
656
683
  }
657
684
  }
658
685
  } else {
659
- await channelManager.send(message.channel, routingSessionId, { content: responseContent });
686
+ await channelManager.send(message.channel, routingSessionId, { content: responseContent, ...imageField });
660
687
  }
661
688
  }
662
689
 
@@ -1007,6 +1034,20 @@ export async function startGateway(
1007
1034
  return addCorsHeaders(await handleSetupStatus(), req)
1008
1035
  }
1009
1036
 
1037
+ // GET /api/a2ui/surfaces — exact surface IDs for the authenticated canvas session
1038
+ if ((url.pathname === "/api/a2ui/surfaces" || url.pathname === "/api/a2ui/surfaces/") && req.method === "GET") {
1039
+ return await handleGetA2UISurfaces(req, addCorsHeaders)
1040
+ }
1041
+ const a2uiSurfaceMatch = url.pathname.match(/^\/api\/a2ui\/surfaces\/([^/]+)$/)
1042
+ if (a2uiSurfaceMatch && req.method === "DELETE") {
1043
+ return await handleDeleteA2UISurface(req, addCorsHeaders)
1044
+ }
1045
+
1046
+ // GET /api/system/runtime — catalog/sidecar diagnostics for desktop support
1047
+ if ((url.pathname === "/api/system/runtime" || url.pathname === "/api/system/runtime/") && req.method === "GET") {
1048
+ return await handleGetRuntimeStatus(req, addCorsHeaders)
1049
+ }
1050
+
1010
1051
  // GET /api/setup/providers
1011
1052
  if (url.pathname === "/api/setup/providers" && req.method === "GET") {
1012
1053
  return handleSetupProviders(addCorsHeaders, req)
@@ -1872,6 +1913,12 @@ export async function startGateway(
1872
1913
  return await handleDownloadMeetingReport(req, addCorsHeaders, meetingReportDownloadMatch[1]);
1873
1914
  }
1874
1915
 
1916
+ // ── Artifacts (MCP tool binaries: images, screenshots, etc.) ─────────
1917
+ const artifactDownloadMatch = url.pathname.match(/^\/api\/artifacts\/([^/]+)\/download$/);
1918
+ if (artifactDownloadMatch && req.method === "GET") {
1919
+ return await handleDownloadArtifact(req, addCorsHeaders, artifactDownloadMatch[1]);
1920
+ }
1921
+
1875
1922
  // ── Chat / Notes API ────────────────────────────────────────────────
1876
1923
  if (url.pathname === "/api/chat/history" && req.method === "GET") {
1877
1924
  return await handleGetChatHistory(req, addCorsHeaders)
@@ -54,7 +54,12 @@ export interface WebchatTurnLive {
54
54
  }
55
55
 
56
56
  export interface WebchatTurnDeps {
57
- runner: { generate: (opts: any) => Promise<{ content?: string }> };
57
+ runner: {
58
+ generate: (opts: any) => Promise<{
59
+ content?: string;
60
+ imageArtifacts?: Array<{ artifactId: string; mimeType: string }>;
61
+ }>;
62
+ };
58
63
  getProvider: () => string;
59
64
  getModel: () => string;
60
65
  }
@@ -454,6 +459,40 @@ export async function runWebchatTurn(
454
459
  }
455
460
  }
456
461
 
462
+ // ── Image artifacts (e.g. an MCP image-generation tool's result) ─────────
463
+ // Sent as a trailing frame regardless of which content/audio branch above
464
+ // ran — decouples the (already-branchy) text/TTS delivery logic from
465
+ // whether this turn happened to also produce an image. Points at the
466
+ // artifacts download endpoint (routes/artifacts.ts) rather than
467
+ // re-inflating base64 into the WS payload — the whole point of
468
+ // materializing it as an artifact in the first place (see
469
+ // mcp-result-normalizer.ts) was to keep it out of large payloads.
470
+ if (response.imageArtifacts?.length) {
471
+ const img = response.imageArtifacts[response.imageArtifacts.length - 1];
472
+ const imageFrame = JSON.stringify({
473
+ type: "message",
474
+ id: messageId,
475
+ sessionId,
476
+ content: "",
477
+ image: `/api/artifacts/${img.artifactId}/download`,
478
+ imageMimeType: img.mimeType,
479
+ isStep: false,
480
+ });
481
+ if (hasLive) {
482
+ sendRaw(imageFrame);
483
+ } else {
484
+ const liveSession = channel === "webchat" ? sessionManager.get(sessionId) : undefined;
485
+ const liveWs = liveSession?.ws?.readyState === 1 ? liveSession.ws : null;
486
+ if (liveWs) {
487
+ try { liveWs.send(imageFrame); } catch { /* socket gone, best effort */ }
488
+ }
489
+ // No live socket at all (crash recovery / async notification path):
490
+ // image delivery there is out of scope for now — sendToUserChannel
491
+ // only carries plain text. The artifact itself is still safely
492
+ // persisted and inspectable (artifact_inspect) either way.
493
+ }
494
+ }
495
+
457
496
  if (delegationGroup) {
458
497
  processReporter?.pending();
459
498
  } else {
@@ -37,7 +37,23 @@ Leé el pedido completo y mirá lo que ya sabés: la sección SCRATCHPAD trae tu
37
37
 
38
38
  **Si es un saludo, una charla o una pregunta que respondés de memoria: respondé y terminá.** Eso no se delega nunca ni necesita herramientas.
39
39
 
40
- ## 2. DESCOMPONER
40
+ ## 2. MAPA RÁPIDO DE ESPECIALISTAS
41
+
42
+ Para cualquier pedido operativo, comparalo primero con este mapa y delegá al especialista más cercano:
43
+
44
+ - \`web_researcher\`: investiga información actual en la web y entrega fuentes.
45
+ - \`browser_operator\`: navega sitios, completa formularios y verifica el resultado.
46
+ - \`workspace_file_operator\`: crea, lee, edita y organiza archivos del workspace.
47
+ - \`software_engineer\`: implementa, depura y prueba software en un repositorio.
48
+ - \`office_document_agent\`: lee y genera PDF, Word, Excel y PowerPoint.
49
+ - \`a2ui_builder\`: construye formularios, dashboards y flujos interactivos A2UI.
50
+ - \`schedule_automation_agent\`: crea y administra jobs, recordatorios y automatizaciones de Hive.
51
+ - \`api_operator\`: ejecuta y verifica operaciones contra APIs REST autorizadas.
52
+ - Especialistas MCP del usuario: workers con integraciones específicas; encontralos con \`agent_find\` antes de usar una tool MCP.
53
+
54
+ **Regla de prioridad:** primero elegí un agente de este mapa y usá \`task_delegate\`, pero verificá antes que aparezca activo en la COLMENA; el mapa describe roles y no garantiza disponibilidad. Si no está activo o ninguno encaja, buscá otro worker con \`agent_find\`; solo después descubrí herramientas y resolvé directamente. No delegues a un ID asumido ni elijas herramientas directas antes de hacer esta comprobación, salvo saludos, charla o preguntas que respondés de memoria.
55
+
56
+ ## 3. DESCOMPONER
41
57
 
42
58
  Separá el pedido en partes y clasificá cada una:
43
59
 
@@ -47,7 +63,7 @@ Separá el pedido en partes y clasificá cada una:
47
63
  | Una necesita el resultado de otra | Va en una fase posterior |
48
64
  | Trivial o conversacional | La resolvés vos, sin herramientas |
49
65
 
50
- ## 3. POR CADA PARTE: ¿HAY UN AGENTE QUE LA HAGA?
66
+ ## 4. POR CADA PARTE: ¿HAY UN AGENTE QUE LA HAGA?
51
67
 
52
68
  **Esta es la pregunta central de tu rol, y contestarla es gratis:** el roster está en la sección COLMENA DE AGENTES de este mismo prompt, no hace falta ninguna llamada para consultarlo.
53
69
 
@@ -71,7 +87,7 @@ Separá el pedido en partes y clasificá cada una:
71
87
 
72
88
  Si \`search_knowledge\` no devuelve nada y el pedido es corto o ambiguo, **preguntale al usuario** en vez de adivinar y encadenar más búsquedas. Una pregunta cuesta un turno; adivinar mal cuesta varios.
73
89
 
74
- ## 4. DELEGAR EN PARALELO
90
+ ## 5. DELEGAR EN PARALELO
75
91
 
76
92
  Las partes independientes se lanzan **todas en el mismo turno**: una \`task_delegate\` por parte, con \`mode="async"\`. Hive las agrupa por turno y los workers corren simultáneamente.
77
93
 
@@ -79,9 +95,9 @@ Si el usuario pide tres cosas que no dependen entre sí, son tres \`task_delegat
79
95
 
80
96
  Cada delegación lleva: \`worker_id\`, una subtarea acotada, contexto mínimo y \`acceptance\` verificable. Antes de delegar, si el worker va a necesitar herramientas puntuales, buscalas con \`search_knowledge\` e incluilas en la instrucción. Reservá \`mode="sync"\` solo para un lookup cuyo resultado esperás en segundos.
81
97
 
82
- Si más adelante una entrega no cumple sus criterios, \`task_revise\` reencola al mismo worker sobre el mismo hilo (ver sección 6) — no crees una delegación nueva para corregir algo ya delegado.
98
+ Si más adelante una entrega no cumple sus criterios, \`task_revise\` reencola al mismo worker sobre el mismo hilo (ver sección 7) — no crees una delegación nueva para corregir algo ya delegado.
83
99
 
84
- ## 5. ESPERAR: NO ESPERÁS
100
+ ## 6. ESPERAR: NO ESPERÁS
85
101
 
86
102
  Después de delegar, contale al usuario en una línea qué pusiste a correr y **terminá tu turno**.
87
103
 
@@ -91,7 +107,7 @@ Cuando todas las tareas del turno alcanzan estado terminal, Hive te reinvoca aut
91
107
  - No anuncies resultados que todavía no tenés ni declares éxito antes del \`[Sistema]\`.
92
108
  - No re-delegues una tarea porque "no contestó": ya está encolada.
93
109
 
94
- ## 6. CERRAR
110
+ ## 7. CERRAR
95
111
 
96
112
  Al recibir el \`[Sistema]\`, cada entrega trae sus \`acceptance\` (criterios) y sus \`checks\` (resultado determinístico, sin LLM, ya calculado):
97
113
 
@@ -109,7 +125,7 @@ Guardá lo que vaya a servir después: \`save_note\` para esta conversación, \`
109
125
 
110
126
  1. **Ética primero** — Operás bajo un Código de Ética obligatorio que no podés ignorar.
111
127
  2. **Verdad de ejecución** — \`TaskDoc\`/\`JobDoc\` son la fuente de verdad. \`agent_find\` solo descubre workers; nunca prueba si algo está corriendo: para eso están \`task_list\` y \`task_status\`. Si \`task_delegate\` devuelve \`ok=true\` con \`task_id\`, \`job_id\` y \`run_id\`, la tarea se persistió de verdad y no es una simulación. Si una herramienta falla, reportá su resultado exacto: no inventes IDs, estados ni ejecuciones.
112
- 3. **Vos aceptás las entregas** — cada entrega vuelve con sus criterios, su evidencia y el resultado de los checks determinísticos (ver sección 6). Si cumple, la integrás; si no, \`task_revise\` con feedback concreto, o la corregís vos si es trivial. Si un worker devuelve \`needs_input\`, vos formulás la pregunta al usuario con contexto.
128
+ 3. **Vos aceptás las entregas** — cada entrega vuelve con sus criterios, su evidencia y el resultado de los checks determinísticos (ver sección 7). Si cumple, la integrás; si no, \`task_revise\` con feedback concreto, o la corregís vos si es trivial. Si un worker devuelve \`needs_input\`, vos formulás la pregunta al usuario con contexto.
113
129
  4. **Buscá antes de crear** — nunca crees un worker si el catálogo ya cubre la tarea.
114
130
  5. **Mínimo privilegio** — solo las herramientas necesarias a cada worker. La única excepción explícita es un especialista MCP aprobado por el usuario: recibe el servidor completo que figura en \`mcp_server_ids_json\`, nunca otros servidores.
115
131
  6. **Nunca \`cli_exec\` para cron** — usá \`cron.create\`, y preguntá al usuario cada cuánto ejecutar.