@johpaz/hive-agents 1.1.3 → 1.1.5

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 (53) hide show
  1. package/README.md +3 -3
  2. package/dist/hive.js +52087 -4376
  3. package/dist/tool-worker.js +49660 -1160
  4. package/dist/ui/assets/{A2UIPage-EDS7lN-K.js → A2UIPage-Dr3p75oE.js} +1 -1
  5. package/dist/ui/assets/{AgentCreateForm-KvhVhAFP.js → AgentCreateForm-DqYhH_gm.js} +1 -1
  6. package/dist/ui/assets/{AgentDetailPage-B2dCpO92.js → AgentDetailPage-BVtE88U5.js} +1 -1
  7. package/dist/ui/assets/{AgentNewPage-CF2B4dbu.js → AgentNewPage-BRpFxJIT.js} +1 -1
  8. package/dist/ui/assets/{AgentsPage-CMvz-CtA.js → AgentsPage-BOIJ55cj.js} +1 -1
  9. package/dist/ui/assets/{ApiClientPage-tzzL3rZC.js → ApiClientPage-R9UDWfR2.js} +1 -1
  10. package/dist/ui/assets/{ChannelsPage-fE2vRwup.js → ChannelsPage-C5V2BmjL.js} +1 -1
  11. package/dist/ui/assets/{DashboardPage-57SaHnBL.js → DashboardPage-B18gMzNj.js} +1 -1
  12. package/dist/ui/assets/{LoginPage-Fag9Bp5h.js → LoginPage-nrsYF9AY.js} +1 -1
  13. package/dist/ui/assets/{LogsPage-GVJd_a65.js → LogsPage-DICMU_7m.js} +1 -1
  14. package/dist/ui/assets/{MeetingPage-TKQu8Nr-.js → MeetingPage-xslJGfIz.js} +1 -1
  15. package/dist/ui/assets/{ModelSelector-DciHLo7R.js → ModelSelector-BX4IvuYY.js} +1 -1
  16. package/dist/ui/assets/Office3DPage-a6cuzt5X.js +727 -0
  17. package/dist/ui/assets/{ProvidersPage-BsWFvzqz.js → ProvidersPage-C8-xGoeh.js} +1 -1
  18. package/dist/ui/assets/{RecoverPage-BkdOyljs.js → RecoverPage-Blms3NBa.js} +1 -1
  19. package/dist/ui/assets/{SettingsPage-D_43Rc2I.js → SettingsPage-BBeeq_QS.js} +1 -1
  20. package/dist/ui/assets/{SetupPage-D6Z3SYZu.js → SetupPage-CAjLseE_.js} +1 -1
  21. package/dist/ui/assets/{Vignette-bSrGVyRd.js → Vignette-DrI2yK2m.js} +1 -1
  22. package/dist/ui/assets/VoicePage-BeSSYstD.js +307 -0
  23. package/dist/ui/assets/{WebChatPage-Dzk3FhiR.js → WebChatPage-Bat7uUfd.js} +1 -1
  24. package/dist/ui/assets/{bia-csMImkVQ.glb → bia-qdLMQRFi.glb} +0 -0
  25. package/dist/ui/assets/{conversationsStore-5hf5grlP.js → conversationsStore-DhM07qYi.js} +1 -1
  26. package/dist/ui/assets/{dialog-DKnsGLwr.js → dialog-BP3GTCPn.js} +1 -1
  27. package/dist/ui/assets/{index-mBw9Tl7u.js → index-BG3nUPKq.js} +2 -2
  28. package/dist/ui/assets/{useAudioDevices-BYFaA0X-.js → useAudioDevices-zj0fuGwZ.js} +1 -1
  29. package/dist/ui/assets/{useHiveAgentsModelLoad-RRQ6-ANC.js → useHiveAgentsModelLoad-Cd9p-bjs.js} +1 -1
  30. package/dist/ui/assets/{useProviders-DXr4pJ57.js → useProviders-Dj1k5PCk.js} +1 -1
  31. package/dist/ui/index.html +1 -1
  32. package/package.json +1 -1
  33. package/packages/cli/src/commands/onboard.ts +8 -7
  34. package/packages/core/src/agent/agent-catalog.ts +2 -2
  35. package/packages/core/src/gateway/routes/providers.ts +26 -79
  36. package/packages/core/src/gateway/server.ts +20 -0
  37. package/packages/core/src/scheduler/integration.ts +26 -20
  38. package/packages/core/src/storage/collections.ts +7 -0
  39. package/packages/core/src/storage/model-sync.ts +404 -0
  40. package/packages/core/src/storage/seed.ts +33 -3
  41. package/packages/core/src/tools/a2ui/index.ts +76 -0
  42. package/packages/core/src/tools/cron/index.ts +25 -3
  43. package/packages/core/src/tools/office/office-escribir-docx.ts +275 -97
  44. package/packages/core/src/tools/office/office-escribir-pdf.ts +489 -99
  45. package/packages/core/src/tools/office/office-escribir-pptx.ts +86 -84
  46. package/packages/core/src/tools/office/office-escribir-xlsx.ts +196 -40
  47. package/packages/core/src/tools/office/office-style.ts +452 -0
  48. package/packages/core/src/tools/web/obscura-install.ts +119 -0
  49. package/packages/core/src/tools/web/obscura.ts +26 -4
  50. package/packages/core/src/utils/date.ts +29 -0
  51. package/packages/skills/src/bundled-data.generated.ts +780 -780
  52. package/dist/ui/assets/Office3DPage-CQnO522l.js +0 -727
  53. package/dist/ui/assets/VoicePage-CCE2EOE9.js +0 -307
@@ -10,6 +10,7 @@ import {
10
10
  import { getJevStatus, resetJevStatus } from "../../agent/jev-decisions"
11
11
  import { loadHiveAgentsModel, getHiveAgentsModelStatus } from "../../agent/llm-providers/hiveagents"
12
12
  import { logger } from "../../utils/logger"
13
+ import { fetchProviderModels, syncProviderModels } from "../../storage/model-sync"
13
14
 
14
15
  const log = logger.child("gateway")
15
16
 
@@ -158,31 +159,25 @@ export async function fetchProviderModelNames(
158
159
  providerId: string,
159
160
  baseUrl: string | null
160
161
  ): Promise<DiscoveryResult> {
161
- if (providerId === "ollama") {
162
- const host = (baseUrl || "http://localhost:11434").replace(/\/+$/, "").replace(/\/(v1|api)$/, "")
163
- const res = await fetch(`${host}/api/tags`, { signal: AbortSignal.timeout(10000) })
164
- if (!res.ok) return { names: [], error: `Ollama responded ${res.status}`, status: 502 }
165
- const data = await res.json() as { models: Array<{ name: string }> }
166
- return { names: (data.models || []).map(m => m.name) }
167
- }
168
-
169
- if (!baseUrl) {
162
+ if (providerId !== "ollama" && !baseUrl && providerId !== "gemini" && providerId !== "anthropic") {
170
163
  return { names: [], error: `El provider "${providerId}" no tiene base_url configurada.`, status: 400 }
171
164
  }
172
-
173
165
  // Se manda la key si el provider tiene una: hay endpoints cuyo listado es
174
166
  // público (ModelScope, NVIDIA) y otros que devuelven 401 sin autenticar
175
167
  // (DashScope), donde sin esto el explorador de modelos no servía.
176
- const apiKey = await loadProviderApiKey(providerId).catch(() => null)
177
- const headers: Record<string, string> = apiKey ? { Authorization: `Bearer ${apiKey}` } : {}
178
-
179
- const res = await fetch(`${baseUrl.replace(/\/+$/, "")}/models`, {
180
- headers,
181
- signal: AbortSignal.timeout(10000),
182
- })
183
- if (!res.ok) return { names: [], error: `${providerId} responded ${res.status}`, status: 502 }
184
- const data = await res.json() as { data: Array<{ id: string }> }
185
- return { names: (data.data || []).map(m => m.id) }
168
+ const apiKey = await loadProviderApiKey(providerId).catch(() => "")
169
+ const headers = await loadProviderHeaders(providerId).catch(() => ({}))
170
+ try {
171
+ const found = await fetchProviderModels({
172
+ providerId, baseUrl, apiKey,
173
+ headers: Object.fromEntries(Object.entries(headers).filter(([, v]) => typeof v === "string")) as Record<string, string>,
174
+ fetch, timeoutMs: 10000,
175
+ })
176
+ return { names: found.map(m => m.wireId) }
177
+ } catch (err) {
178
+ const status = (err as { status?: number }).status
179
+ return { names: [], error: status ? `${providerId} responded ${status}` : `No se pudo consultar ${providerId}`, status: 502 }
180
+ }
186
181
  }
187
182
 
188
183
  /**
@@ -232,69 +227,21 @@ export async function handleSyncProviderModels(
232
227
  providerId: string
233
228
  ): Promise<Response> {
234
229
  const providersCol = await col<ProviderDoc>("providers")
235
- const modelsCol = await col<ModelDoc>("models")
236
- const providerEntry = await providersCol.get(providerId)
237
-
238
- if (!providerEntry) {
230
+ if (!(await providersCol.get(providerId))) {
239
231
  return addCorsHeaders(new Response("Provider not found", { status: 404 }), req)
240
232
  }
241
233
 
242
- try {
243
- const discovered = await fetchProviderModelNames(providerId, providerEntry.doc.base_url)
244
- if (discovered.error) {
245
- return addCorsHeaders(Response.json({ error: discovered.error }, { status: discovered.status }), req)
246
- }
247
- const modelNames = discovered.names
248
-
249
- if (modelNames.length === 0) {
250
- return addCorsHeaders(Response.json({ error: "No models found from provider" }, { status: 400 }), req)
251
- }
252
-
253
- // Los ids se guardan con la clave de catálogo (prefijada en los providers
254
- // revendedores) para que dos servicios que sirvan el mismo modelo no se
255
- // pisen la fila.
256
- const discoveredKeys = new Set(modelNames.map(n => catalogModelKey(providerId, n)))
257
- for (const name of modelNames) {
258
- const key = catalogModelKey(providerId, name)
259
- const existing = await modelsCol.get(key)
260
- await modelsCol.put(key, {
261
- id: key, provider_id: providerId, name,
262
- model_type: existing?.doc.model_type ?? "llm",
263
- context_window: existing?.doc.context_window ?? 32768,
264
- capabilities: existing?.doc.capabilities ?? null,
265
- enabled: true, active: true,
266
- source: existing?.doc.source ?? "discovered",
267
- input_per_1m: existing?.doc.input_per_1m ?? null,
268
- output_per_1m: existing?.doc.output_per_1m ?? null,
269
- }, existing ? { expectedVersion: existing.version } : undefined)
270
- }
271
-
272
- // Disable models that are no longer present
273
- const existingModels = await modelsCol.findBy("provider_id", providerId)
274
- for (const row of existingModels) {
275
- if (!discoveredKeys.has(row.id)) {
276
- await modelsCol.put(row.id, { ...row.doc, active: false, enabled: false }, { expectedVersion: row.version })
277
- }
278
- }
279
-
280
- // Se devuelve el doc completo: recortar los campos dejaba a la UI sin
281
- // context_window ni precio justo después de sincronizar.
282
- const models = (await modelsCol.findBy("provider_id", providerId)).map(m => m.doc)
283
-
284
- return addCorsHeaders(Response.json({
285
- success: true,
286
- synced: modelNames.length,
287
- models
288
- }), req)
289
- } catch (err: unknown) {
290
- const errorMsg = (err as Error).message
291
- const hint = providerId === "ollama"
292
- ? "Could not connect to Ollama"
293
- : `Could not connect to provider: ${errorMsg}`
294
- return addCorsHeaders(Response.json({
295
- error: `${hint}: ${errorMsg}`
296
- }, { status: 502 }), req)
234
+ // Lo que el proveedor declara de cada modelo se guarda sin tocar lo que es del usuario (nombre, activación, precio) y
235
+ // sin apagar ni borrar los que el proveedor ya no lista: ver storage/model-sync.ts.
236
+ const result = await syncProviderModels(providerId)
237
+ if (!result.ok) {
238
+ const status = result.skipped ? 400 : result.found === 0 ? 400 : 502
239
+ return addCorsHeaders(Response.json({ error: result.skipped ?? result.error, ...result }, { status }), req)
297
240
  }
241
+ // Se devuelve el doc completo: recortar los campos dejaba a la UI sin
242
+ // context_window ni precio justo después de sincronizar.
243
+ const models = (await (await col<ModelDoc>("models")).findBy("provider_id", providerId)).map(m => m.doc)
244
+ return addCorsHeaders(Response.json({ success: true, synced: result.found, ...result, models }), req)
298
245
  }
299
246
 
300
247
  export async function handleLoadHiveAgentsModel(
@@ -22,6 +22,7 @@ import rootPackage from "../../../../package.json";
22
22
  // standalone executables instead of depending on a package.json at runtime.
23
23
  const _pkgVersion = rootPackage.version;
24
24
  import { ensureHiveDb } from "../storage/bootstrap";
25
+ import { syncActiveProviderModels } from "../storage/model-sync";
25
26
  import { col, fromIndexable, nextId } from "../storage/hive";
26
27
  import { reconcileOnBoot } from "../storage/reconcile";
27
28
  import { getBootId } from "../storage/boot-id";
@@ -217,6 +218,19 @@ export async function startGateway(
217
218
  await ensureHiveDb();
218
219
  } catch { /* si falla, los endpoints manejarán el error */ }
219
220
 
221
+ // Pregunta a cada provider ACTIVO qué modelos tiene y actualiza la BD (ventana de contexto, capacidades, retirados).
222
+ // En segundo plano: nunca retrasa el arranque, y un fallo de red solo queda en el log. Se omite con
223
+ // HIVE_MODEL_SYNC=0 y en las pruebas (BD en memoria).
224
+ if (process.env.HIVE_MODEL_SYNC !== "0" && process.env.HIVE_DB_PATH !== ":memory:") {
225
+ void syncActiveProviderModels()
226
+ .then((results) => {
227
+ const ok = results.filter((r) => r.ok)
228
+ const summary = ok.map((r) => `${r.provider} (+${r.added} ~${r.updated} -${r.unlisted})`).join(", ")
229
+ log.info(`[model-sync] ${ok.length}/${results.length} providers actualizados${summary ? `: ${summary}` : ""}`)
230
+ })
231
+ .catch((err) => log.warn(`[model-sync] ${(err as Error).message}`))
232
+ }
233
+
220
234
  // Setup mode: DB existe pero tiene 0 usuarios (primera ejecución interrumpida)
221
235
  let gatewaySetupMode = false;
222
236
  try {
@@ -1457,6 +1471,12 @@ export async function startGateway(
1457
1471
  return await handleGetProviderAvailableModels(req, addCorsHeaders, availableModelsMatch[1])
1458
1472
  }
1459
1473
 
1474
+ // POST /api/models/refresh — actualiza los modelos de todos los providers activos preguntándoselos a cada uno
1475
+ if (url.pathname === "/api/models/refresh" && req.method === "POST") {
1476
+ const results = await syncActiveProviderModels()
1477
+ return addCorsHeaders(Response.json({ success: true, results }), req)
1478
+ }
1479
+
1460
1480
  // POST /api/models - Create a new model
1461
1481
  if (url.pathname === "/api/models" && req.method === "POST") {
1462
1482
  return await handleCreateModel(req, addCorsHeaders)
@@ -14,7 +14,8 @@ import { getNarration } from "../gateway/helpers";
14
14
  import { addMessage } from "../agent/conversation-store";
15
15
  import { makeThreadId, CRON_CHANNEL } from "../agent/thread-id";
16
16
  import { threadForChannel } from "../agent/thread-store";
17
- import { resolveBestChannel } from "../tools/cron/index";
17
+ import { resolveBestChannel, resolveActiveChannels } from "../tools/cron/index";
18
+ import { formatUserDateTime } from "../utils/date";
18
19
  import { col } from "../storage/hive";
19
20
  import type { UserDoc, CronJobDoc } from "../storage/collections";
20
21
 
@@ -234,30 +235,35 @@ export async function notifyTaskCompletion(
234
235
  const userEntry = (await usersCol.scan({ limit: 1 }))[0];
235
236
  const userId = userEntry?.id || "";
236
237
 
237
- const explicitChannel = task.channel && task.channel !== "system" ? task.channel : undefined;
238
- const notifyChannel = (await resolveBestChannel(userId, explicitChannel)) || "webchat";
239
- log.info(`[notifyTaskCompletion] task.channel=${task.channel} explicit=${explicitChannel} resolved=${notifyChannel}`);
238
+ const timezone = userEntry?.doc.timezone || "UTC";
239
+ const when = formatUserDateTime(new Date(), timezone);
240
+ const stamp = when ? `\n🕒 ${when} (${timezone})` : "";
240
241
 
241
242
  const status = success ? "✅" : "❌";
242
243
  const message = success
243
- ? `${status} Scheduled task "${taskName}" completed\n${response || ""}`
244
- : `${status} Scheduled task "${taskName}" failed\n${error || ""}`;
244
+ ? `${status} Scheduled task "${taskName}" completed${stamp}\n${response || ""}`
245
+ : `${status} Scheduled task "${taskName}" failed${stamp}\n${error || ""}`;
245
246
 
246
- log.info(`[notify] Sending notification to ${notifyChannel}: "${message.slice(0, 50)}..."`);
247
+ // El resultado va a TODOS los canales activos, sin distinción ni prioridad.
248
+ const channels = await resolveActiveChannels(userId);
249
+ log.info(`[notify] Sending "${taskName}" result to all active channels: [${channels.join(", ")}]`);
247
250
 
248
- // El aviso se guarda en el hilo donde el usuario lo va a leer —su conversación
249
- // activa en la web, o el chat del canal— y no en el hilo del usuario, que desde
250
- // la separación por canal ya no es donde mira nadie.
251
- const notifyThreadId = (await threadForChannel(userId, notifyChannel)) ?? userId;
252
-
253
- try {
254
- await addMessage(notifyThreadId, "assistant", message, { channel: notifyChannel });
255
- } catch (e) {
256
- log.warn(`[notify] Failed to persist notification to DB: ${(e as Error).message}`);
257
- }
258
-
259
- await sendToUserChannel(notifyChannel, userId, message, { threadId: notifyThreadId });
260
- log.info(`[notify] Notification sent to ${notifyChannel}`);
251
+ await Promise.all(channels.map(async (channel) => {
252
+ // El aviso se guarda en el hilo donde el usuario lo va a leer —su conversación
253
+ // activa en la web, o el chat del canal.
254
+ const threadId = (await threadForChannel(userId, channel)) ?? userId;
255
+ try {
256
+ await addMessage(threadId, "assistant", message, { channel });
257
+ } catch (e) {
258
+ log.warn(`[notify] Failed to persist notification for ${channel}: ${(e as Error).message}`);
259
+ }
260
+ try {
261
+ const res = await sendToUserChannel(channel, userId, message, { threadId });
262
+ if (!res.ok) log.warn(`[notify] ${channel} failed: ${res.error}`);
263
+ } catch (e) {
264
+ log.warn(`[notify] ${channel} threw: ${(e as Error).message}`);
265
+ }
266
+ }));
261
267
  }
262
268
 
263
269
  /**
@@ -62,6 +62,13 @@ export interface ModelDoc {
62
62
  */
63
63
  input_per_1m?: number | null
64
64
  output_per_1m?: number | null
65
+ /** Última vez que el propio proveedor confirmó este modelo (`storage/model-sync.ts`), en ms. */
66
+ synced_at?: number
67
+ /**
68
+ * El proveedor ya no lo lista (NVIDIA, por ejemplo, retira modelos sin avisar y responde 410). No se borra ni se
69
+ * apaga: puede haber agentes apuntándole. Se desmarca solo si vuelve a aparecer.
70
+ */
71
+ unlisted?: boolean
65
72
  }
66
73
 
67
74
  export interface AgentDoc {
@@ -0,0 +1,404 @@
1
+ /**
2
+ * Actualiza los modelos de la BD preguntándoselos al propio proveedor.
3
+ *
4
+ * El catálogo estático (`SEED_DATA.models`) envejece: los proveedores publican y retiran modelos sin avisar. Esto
5
+ * consulta el listado del proveedor y guarda lo que declara de cada modelo (tipo, ventana de contexto, capacidades y,
6
+ * cuando lo publica, el precio) como filas `source: "discovered"`, que el resembrado del arranque no borra.
7
+ *
8
+ * Reglas, para que sea seguro correrlo siempre:
9
+ * - Solo los providers ACTIVOS (`syncActiveProviderModels`); uno concreto solo si se pide (`syncProviderModels`).
10
+ * - Un modelo NUEVO entra apagado (`enabled: false`): un proveedor puede listar cientos y no se llena la interfaz.
11
+ * Los locales (Ollama) entran encendidos, como siempre.
12
+ * - Un modelo que YA existe conserva lo que es del usuario: nombre, `enabled`, `active` y el precio que ya tuviera.
13
+ * El proveedor es la autoridad de la ventana de contexto y de las capacidades que declara (se suman a las que ya
14
+ * había; nunca se quita ninguna).
15
+ * - Un modelo que el proveedor ya NO lista no se borra ni se apaga (podría haber agentes apuntándole): se marca
16
+ * `unlisted: true` para poder avisarlo, y se desmarca si vuelve a aparecer.
17
+ * - Un fallo (red, 401, formato raro) no toca nada y se informa por proveedor sin incluir nunca la clave.
18
+ * - Lo que el proveedor no dice no se inventa: ventana 0 = desconocida, precio `null` = desconocido.
19
+ */
20
+ import { col } from "./hive"
21
+ import type { ProviderDoc, ModelDoc } from "./collections"
22
+ import { catalogModelKey } from "./model-id"
23
+ import { loadProviderApiKey, loadProviderHeaders } from "./crypto"
24
+ import { logger } from "../utils/logger"
25
+
26
+ const log = logger.child("model-sync")
27
+
28
+ type ModelType = ModelDoc["model_type"]
29
+
30
+ /** Lo que un proveedor declara de un modelo, ya normalizado. */
31
+ export interface DiscoveredModel {
32
+ /** Nombre en el cable (sin el prefijo de revendedor). */
33
+ wireId: string
34
+ name?: string
35
+ type?: ModelType
36
+ contextWindow?: number
37
+ capabilities?: string[]
38
+ /** USD por millón de tokens, solo si el proveedor lo publica. */
39
+ inputPer1M?: number
40
+ outputPer1M?: number
41
+ }
42
+
43
+ export interface FetchContext {
44
+ providerId: string
45
+ baseUrl: string | null
46
+ apiKey: string
47
+ headers: Record<string, string>
48
+ fetch: typeof fetch
49
+ timeoutMs: number
50
+ }
51
+
52
+ export type ProviderFetcher = (ctx: FetchContext) => Promise<DiscoveredModel[]>
53
+
54
+ /** Providers cuyo listado responde sin clave (o que no la usan): se consultan aunque no haya una guardada. */
55
+ const KEYLESS = new Set(["ollama", "modelscope"])
56
+ /** Providers cuyo listado no es completo por diseño (modelos montados bajo demanda): nunca se marca nada como retirado. */
57
+ const PARTIAL_LISTING = new Set(["hiveagents", "piper"])
58
+ /** Providers locales: sus modelos son gratis y entran encendidos. */
59
+ const LOCAL = new Set(["ollama"])
60
+
61
+ const MAX_MODELS = 10_000
62
+ const MAX_PAGES = 10
63
+
64
+ class ProviderHttpError extends Error {
65
+ constructor(readonly status: number) {
66
+ super(`HTTP ${status}`)
67
+ }
68
+ }
69
+
70
+ async function getJson(ctx: FetchContext, url: string, headers: Record<string, string>): Promise<unknown> {
71
+ const response = await ctx.fetch(url, { headers, signal: AbortSignal.timeout(ctx.timeoutMs) })
72
+ if (!response.ok) throw new ProviderHttpError(response.status)
73
+ return response.json()
74
+ }
75
+
76
+ const trimSlash = (s: string) => s.replace(/\/+$/, "")
77
+ const positive = (n: unknown): number | undefined => (typeof n === "number" && Number.isFinite(n) && n > 0 ? Math.floor(n) : undefined)
78
+ const text = (v: unknown): string | undefined => (typeof v === "string" && v.trim() ? v.trim() : undefined)
79
+
80
+ /**
81
+ * Tipo de un modelo cuando el proveedor solo da su id. `null` = no es un tipo que la app maneje (imágenes, moderación…):
82
+ * no se guarda. Solo se usa si el proveedor no declaró nada mejor.
83
+ */
84
+ export function classifyModelId(wireId: string): ModelType | null {
85
+ const id = wireId.toLowerCase()
86
+ if (/(^|[-_/])(dall-e|imagen|sora|image|veo|moderation|omni-moderation|guard)([-_/.\d]|$)/.test(id)) return null
87
+ // Modelos auxiliares que no conversan: guardas de seguridad, CLIP, detectores, rerankers, parsers y similares.
88
+ if (/(guard|safety|nvclip|(^|[-_/])clip([-_/.\d]|$)|detector|reward|rerank|retriev|parse|[-_]ocr([-_/.\d]|$))/.test(id)) return null
89
+ if (/embed/.test(id)) return "embedding"
90
+ if (/(whisper|transcribe|scribe|\basr\b|[-_]asr[-_]|stt)/.test(id)) return "stt"
91
+ if (/(realtime|[-_]live([-_.\d]|$))/.test(id)) return "realtime"
92
+ if (/(tts|speech|voxtral)/.test(id)) return "tts"
93
+ return "llm"
94
+ }
95
+
96
+ // ─── Adaptadores ─────────────────────────────────────────────────────────────
97
+
98
+ /** `GET {base}/models` con `Authorization: Bearer`: OpenAI y casi todos los demás, con las señales extra que den. */
99
+ const openAiCompatible: ProviderFetcher = async (ctx) => {
100
+ if (!ctx.baseUrl) throw new Error("el provider no tiene base_url")
101
+ const headers: Record<string, string> = { ...ctx.headers }
102
+ if (ctx.apiKey) headers.Authorization = `Bearer ${ctx.apiKey}`
103
+ const body = (await getJson(ctx, `${trimSlash(ctx.baseUrl)}/models`, headers)) as Record<string, unknown>
104
+ const rows = (Array.isArray(body) ? body : (body.data as unknown[])) ?? []
105
+ const out: DiscoveredModel[] = []
106
+ for (const raw of rows.slice(0, MAX_MODELS)) {
107
+ const row = raw as Record<string, any>
108
+ const wireId = text(row.id) ?? text(row.model_id)
109
+ if (!wireId) continue
110
+ const found: DiscoveredModel = { wireId, name: text(row.display_name) ?? text(row.name) }
111
+ found.contextWindow =
112
+ positive(row.context_length) ?? positive(row.context_window) ?? positive(row.max_context_length) ??
113
+ positive(row.max_model_len) ?? positive(row.top_provider?.context_length)
114
+ // Modalidades declaradas (OpenRouter y compatibles).
115
+ const inputs: unknown[] | undefined = row.architecture?.input_modalities ?? row.input_modalities
116
+ const outputs: unknown[] | undefined = row.architecture?.output_modalities ?? row.output_modalities
117
+ const caps = new Set<string>()
118
+ if (inputs && outputs) {
119
+ if (outputs.includes("image")) continue // generación de imágenes: no se maneja
120
+ if (outputs.includes("audio")) { found.type = "tts"; caps.add("tts"); caps.add("speech") }
121
+ else if (inputs.includes("audio") && !inputs.includes("text")) { found.type = "stt"; caps.add("transcription") }
122
+ else if (outputs.includes("text")) { found.type = "llm"; caps.add("chat") }
123
+ if (inputs.includes("image")) caps.add("vision")
124
+ }
125
+ // Capacidades declaradas (Mistral) y parámetros soportados (OpenRouter).
126
+ const declared = row.capabilities
127
+ if (declared && typeof declared === "object" && !Array.isArray(declared)) {
128
+ if (declared.completion_chat) caps.add("chat")
129
+ if (declared.function_calling) caps.add("function_calling")
130
+ if (declared.vision) caps.add("vision")
131
+ }
132
+ const params: unknown[] | undefined = row.supported_parameters
133
+ if (Array.isArray(params)) {
134
+ if (params.includes("tools")) caps.add("function_calling")
135
+ if (params.includes("response_format") || params.includes("structured_outputs")) caps.add("json_mode")
136
+ if (params.includes("reasoning") || params.includes("include_reasoning")) caps.add("reasoning")
137
+ }
138
+ if (caps.size) found.capabilities = [...caps]
139
+ // Precio publicado (OpenRouter: USD por token, como texto; negativo = variable).
140
+ const prompt = Number(row.pricing?.prompt)
141
+ const completion = Number(row.pricing?.completion)
142
+ if (row.pricing && Number.isFinite(prompt) && prompt >= 0 && Number.isFinite(completion) && completion >= 0) {
143
+ found.inputPer1M = Math.round(prompt * 1e6 * 1e4) / 1e4
144
+ found.outputPer1M = Math.round(completion * 1e6 * 1e4) / 1e4
145
+ }
146
+ out.push(found)
147
+ }
148
+ return out
149
+ }
150
+
151
+ /** Anthropic: `GET /v1/models` con `x-api-key` y su versión de API. */
152
+ const anthropic: ProviderFetcher = async (ctx) => {
153
+ const base = trimSlash(ctx.baseUrl || "https://api.anthropic.com").replace(/\/v1$/, "")
154
+ const out: DiscoveredModel[] = []
155
+ let after: string | undefined
156
+ for (let page = 0; page < MAX_PAGES; page++) {
157
+ const url = `${base}/v1/models?limit=1000${after ? `&after_id=${encodeURIComponent(after)}` : ""}`
158
+ const body = (await getJson(ctx, url, { ...ctx.headers, "x-api-key": ctx.apiKey, "anthropic-version": "2023-06-01" })) as any
159
+ for (const row of (body.data as any[]) ?? []) {
160
+ const wireId = text(row.id)
161
+ if (!wireId) continue
162
+ const caps = new Set<string>(["chat"])
163
+ if (row.capabilities?.image_input?.supported) caps.add("vision")
164
+ if (row.capabilities?.structured_outputs?.supported) caps.add("json_mode")
165
+ if (row.capabilities?.thinking?.supported) caps.add("reasoning")
166
+ out.push({ wireId, name: text(row.display_name), type: "llm", contextWindow: positive(row.max_input_tokens), capabilities: [...caps] })
167
+ }
168
+ if (!body.has_more || !body.last_id) break
169
+ after = body.last_id
170
+ }
171
+ return out.slice(0, MAX_MODELS)
172
+ }
173
+
174
+ /** Gemini: `GET /v1beta/models` con `x-goog-api-key`; el tipo sale de los métodos de generación que declara. */
175
+ const gemini: ProviderFetcher = async (ctx) => {
176
+ const base = trimSlash(ctx.baseUrl || "https://generativelanguage.googleapis.com/v1beta")
177
+ const out: DiscoveredModel[] = []
178
+ let token: string | undefined
179
+ for (let page = 0; page < MAX_PAGES; page++) {
180
+ const url = `${base}/models?pageSize=1000${token ? `&pageToken=${encodeURIComponent(token)}` : ""}`
181
+ const body = (await getJson(ctx, url, { ...ctx.headers, "x-goog-api-key": ctx.apiKey })) as any
182
+ for (const row of (body.models as any[]) ?? []) {
183
+ const name = text(row.name)
184
+ if (!name) continue
185
+ const wireId = name.replace(/^models\//, "")
186
+ const methods: string[] = Array.isArray(row.supportedGenerationMethods) ? row.supportedGenerationMethods : []
187
+ let type: ModelType | undefined
188
+ const caps = new Set<string>()
189
+ if (methods.includes("bidiGenerateContent")) { type = "realtime"; caps.add("realtime") }
190
+ else if (/tts/.test(wireId)) { type = "tts"; caps.add("tts"); caps.add("speech") }
191
+ else if (methods.includes("generateContent") || methods.includes("streamGenerateContent")) {
192
+ if (/(image|imagen|veo)/.test(wireId)) continue // imágenes y vídeo: no se manejan
193
+ type = "llm"; caps.add("chat"); caps.add("streaming")
194
+ } else if (methods.includes("embedContent") || methods.includes("batchEmbedContents")) type = "embedding"
195
+ else if (methods.includes("predict") || methods.includes("predictLongRunning")) continue
196
+ if (row.thinking === true) caps.add("reasoning")
197
+ out.push({ wireId, name: text(row.displayName), type, contextWindow: positive(row.inputTokenLimit), capabilities: caps.size ? [...caps] : undefined })
198
+ }
199
+ token = text(body.nextPageToken)
200
+ if (!token) break
201
+ }
202
+ return out.slice(0, MAX_MODELS)
203
+ }
204
+
205
+ /** Ollama: `/api/tags` y, por cada modelo, `/api/show` (ventana de contexto y capacidades reales). Gratis por ser local. */
206
+ const ollama: ProviderFetcher = async (ctx) => {
207
+ const host = trimSlash(ctx.baseUrl || "http://localhost:11434").replace(/\/(v1|api)$/, "")
208
+ const tags = (await getJson(ctx, `${host}/api/tags`, ctx.headers)) as any
209
+ const names: string[] = ((tags.models as any[]) ?? []).map((m) => text(m.name) ?? text(m.model)).filter((n): n is string => !!n).slice(0, 500)
210
+ const out: DiscoveredModel[] = []
211
+ let next = 0
212
+ const worker = async () => {
213
+ while (next < names.length) {
214
+ const wireId = names[next++]
215
+ const found: DiscoveredModel = { wireId, type: "llm", inputPer1M: 0, outputPer1M: 0 }
216
+ try {
217
+ const response = await ctx.fetch(`${host}/api/show`, {
218
+ method: "POST", headers: { ...ctx.headers, "Content-Type": "application/json" },
219
+ body: JSON.stringify({ model: wireId }), signal: AbortSignal.timeout(ctx.timeoutMs),
220
+ })
221
+ if (response.ok) {
222
+ const info = (await response.json()) as any
223
+ for (const [key, value] of Object.entries(info.model_info ?? {})) {
224
+ if (key.endsWith(".context_length")) { found.contextWindow = positive(value); break }
225
+ }
226
+ const caps = new Set<string>()
227
+ for (const c of (info.capabilities as string[]) ?? []) {
228
+ if (c === "completion") caps.add("chat")
229
+ else if (c === "vision") caps.add("vision")
230
+ else if (c === "tools") caps.add("function_calling")
231
+ else if (c === "thinking") caps.add("reasoning")
232
+ else if (c === "embedding") found.type = "embedding"
233
+ }
234
+ if (caps.size) found.capabilities = [...caps]
235
+ }
236
+ } catch { /* sin detalle: el modelo se guarda igual con lo que dio /api/tags */ }
237
+ out.push(found)
238
+ }
239
+ }
240
+ await Promise.all([worker(), worker(), worker(), worker()])
241
+ return out
242
+ }
243
+
244
+ /** ElevenLabs: `GET /v1/models` con `xi-api-key`; solo los que sirven para síntesis de voz. */
245
+ const elevenlabs: ProviderFetcher = async (ctx) => {
246
+ const base = trimSlash(ctx.baseUrl || "https://api.elevenlabs.io/v1")
247
+ const body = (await getJson(ctx, `${base}/models`, { ...ctx.headers, "xi-api-key": ctx.apiKey })) as any[]
248
+ return (Array.isArray(body) ? body : [])
249
+ .filter((m) => m.can_do_text_to_speech === true && text(m.model_id))
250
+ .map((m) => ({ wireId: m.model_id as string, name: text(m.name), type: "tts" as const, capabilities: ["tts", "speech"] }))
251
+ }
252
+
253
+ const FETCHERS: Record<string, ProviderFetcher> = { anthropic, gemini, ollama, elevenlabs }
254
+
255
+ /** Consulta el listado del proveedor con el adaptador que le corresponde. */
256
+ export async function fetchProviderModels(ctx: FetchContext): Promise<DiscoveredModel[]> {
257
+ return (FETCHERS[ctx.providerId] ?? openAiCompatible)(ctx)
258
+ }
259
+
260
+ // ─── Fusión con la BD ────────────────────────────────────────────────────────
261
+
262
+ export interface ApplyResult {
263
+ added: number
264
+ updated: number
265
+ /** Marcados como que el proveedor ya no los lista. */
266
+ unlisted: number
267
+ }
268
+
269
+ const sameSet = (a: string[], b: string[]) => a.length === b.length && a.every((x) => b.includes(x))
270
+
271
+ function parseCapabilities(value: string | null | undefined): string[] {
272
+ if (!value) return []
273
+ try {
274
+ const parsed = JSON.parse(value)
275
+ return Array.isArray(parsed) ? parsed.filter((c): c is string => typeof c === "string") : []
276
+ } catch { return [] }
277
+ }
278
+
279
+ /** Guarda lo descubierto en `models` según las reglas del encabezado. */
280
+ export async function applyDiscoveredModels(provider: ProviderDoc, found: DiscoveredModel[], now = Date.now()): Promise<ApplyResult> {
281
+ const models = await col<ModelDoc>("models")
282
+ const result: ApplyResult = { added: 0, updated: 0, unlisted: 0 }
283
+ const seen = new Set<string>()
284
+ const local = LOCAL.has(provider.id)
285
+
286
+ for (const model of found) {
287
+ const key = catalogModelKey(provider.id, model.wireId)
288
+ if (seen.has(key)) continue
289
+ seen.add(key)
290
+ const type = model.type ?? classifyModelId(model.wireId)
291
+ const row = await models.get(key)
292
+ if (!row) {
293
+ if (type === null) continue // un tipo que la app no maneja
294
+ await models.put(key, {
295
+ id: key, provider_id: provider.id, name: model.name ?? model.wireId, model_type: type,
296
+ context_window: model.contextWindow ?? 0,
297
+ capabilities: model.capabilities?.length ? JSON.stringify(model.capabilities) : null,
298
+ enabled: local, active: false, source: "discovered",
299
+ input_per_1m: model.inputPer1M ?? (local ? 0 : null),
300
+ output_per_1m: model.outputPer1M ?? (local ? 0 : null),
301
+ synced_at: now,
302
+ }, { expectedVersion: 0 })
303
+ result.added++
304
+ continue
305
+ }
306
+ const doc = row.doc
307
+ const next: ModelDoc = { ...doc }
308
+ let changed = false
309
+ if (model.contextWindow && doc.context_window !== model.contextWindow) { next.context_window = model.contextWindow; changed = true }
310
+ if (model.capabilities?.length) {
311
+ const have = parseCapabilities(doc.capabilities)
312
+ const merged = [...new Set([...have, ...model.capabilities])]
313
+ if (!sameSet(have, merged)) { next.capabilities = JSON.stringify(merged); changed = true }
314
+ }
315
+ if ((doc.input_per_1m === null || doc.input_per_1m === undefined) && model.inputPer1M !== undefined) { next.input_per_1m = model.inputPer1M; changed = true }
316
+ if ((doc.output_per_1m === null || doc.output_per_1m === undefined) && model.outputPer1M !== undefined) { next.output_per_1m = model.outputPer1M; changed = true }
317
+ if (doc.unlisted) { delete next.unlisted; changed = true }
318
+ if (changed) {
319
+ next.synced_at = now
320
+ await models.put(key, next, { expectedVersion: row.version })
321
+ result.updated++
322
+ }
323
+ }
324
+
325
+ // Lo que el proveedor ya no lista se marca, no se borra. Una lista vacía o parcial por diseño no marca nada.
326
+ if (found.length > 0 && !PARTIAL_LISTING.has(provider.id)) {
327
+ for (const row of await models.findBy("provider_id", provider.id)) {
328
+ if (seen.has(row.id) || row.doc.unlisted) continue
329
+ await models.put(row.id, { ...row.doc, unlisted: true, synced_at: now }, { expectedVersion: row.version })
330
+ result.unlisted++
331
+ }
332
+ }
333
+ return result
334
+ }
335
+
336
+ // ─── Orquestación ────────────────────────────────────────────────────────────
337
+
338
+ export interface SyncDeps {
339
+ fetch?: typeof fetch
340
+ loadKey?: (providerId: string) => Promise<string>
341
+ loadHeaders?: (providerId: string) => Promise<Record<string, unknown>>
342
+ now?: () => number
343
+ timeoutMs?: number
344
+ }
345
+
346
+ export interface ProviderSyncResult {
347
+ provider: string
348
+ ok: boolean
349
+ /** Por qué no se consultó (sin clave, inactivo…). */
350
+ skipped?: string
351
+ found?: number
352
+ added?: number
353
+ updated?: number
354
+ unlisted?: number
355
+ /** Qué falló, sin la clave ni el cuerpo de la respuesta. */
356
+ error?: string
357
+ /** Código HTTP del proveedor si fue lo que falló. */
358
+ status?: number
359
+ }
360
+
361
+ function stringHeaders(raw: Record<string, unknown>): Record<string, string> {
362
+ return Object.fromEntries(Object.entries(raw).filter(([, v]) => typeof v === "string")) as Record<string, string>
363
+ }
364
+
365
+ /** Actualiza los modelos de UN provider (sin exigir que esté activo: es lo que pide una persona a mano). */
366
+ export async function syncProviderModels(providerId: string, deps: SyncDeps = {}): Promise<ProviderSyncResult> {
367
+ const providers = await col<ProviderDoc>("providers")
368
+ const entry = await providers.get(providerId)
369
+ if (!entry) return { provider: providerId, ok: false, error: "provider desconocido" }
370
+ const apiKey = await (deps.loadKey ?? loadProviderApiKey)(providerId).catch(() => "")
371
+ if (!apiKey && !KEYLESS.has(providerId)) return { provider: providerId, ok: false, skipped: "sin clave guardada" }
372
+ const headers = stringHeaders(await (deps.loadHeaders ?? loadProviderHeaders)(providerId).catch(() => ({})))
373
+ try {
374
+ const found = await fetchProviderModels({
375
+ providerId, baseUrl: entry.doc.base_url, apiKey, headers,
376
+ fetch: deps.fetch ?? fetch, timeoutMs: deps.timeoutMs ?? 10_000,
377
+ })
378
+ if (found.length === 0) return { provider: providerId, ok: false, found: 0, error: "el proveedor no devolvió ningún modelo" }
379
+ const applied = await applyDiscoveredModels(entry.doc, found, (deps.now ?? Date.now)())
380
+ return { provider: providerId, ok: true, found: found.length, ...applied }
381
+ } catch (err) {
382
+ if (err instanceof ProviderHttpError) return { provider: providerId, ok: false, error: `el proveedor respondió ${err.status}`, status: err.status }
383
+ const name = (err as Error).name
384
+ return { provider: providerId, ok: false, error: name === "TimeoutError" || name === "AbortError" ? "el proveedor no respondió a tiempo" : "no se pudo consultar el proveedor" }
385
+ }
386
+ }
387
+
388
+ /** Actualiza los modelos de todos los providers ACTIVOS, de a cuatro a la vez. */
389
+ export async function syncActiveProviderModels(deps: SyncDeps = {}): Promise<ProviderSyncResult[]> {
390
+ const providers = await col<ProviderDoc>("providers")
391
+ const active = (await providers.scan({})).filter((p) => p.doc.enabled && p.doc.active).map((p) => p.id)
392
+ const results: ProviderSyncResult[] = []
393
+ let next = 0
394
+ const worker = async () => {
395
+ while (next < active.length) {
396
+ const id = active[next++]
397
+ const result = await syncProviderModels(id, deps)
398
+ if (!result.ok && !result.skipped) log.warn(`[model-sync] ${id}: ${result.error}`)
399
+ results.push(result)
400
+ }
401
+ }
402
+ await Promise.all([worker(), worker(), worker(), worker()])
403
+ return results.sort((a, b) => a.provider.localeCompare(b.provider))
404
+ }