@johpaz/hive-agents 1.1.4 → 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.
- package/README.md +3 -3
- package/dist/hive.js +52027 -4372
- package/dist/tool-worker.js +49660 -1160
- package/dist/ui/assets/{A2UIPage-EDS7lN-K.js → A2UIPage-Dr3p75oE.js} +1 -1
- package/dist/ui/assets/{AgentCreateForm-KvhVhAFP.js → AgentCreateForm-DqYhH_gm.js} +1 -1
- package/dist/ui/assets/{AgentDetailPage-B2dCpO92.js → AgentDetailPage-BVtE88U5.js} +1 -1
- package/dist/ui/assets/{AgentNewPage-CF2B4dbu.js → AgentNewPage-BRpFxJIT.js} +1 -1
- package/dist/ui/assets/{AgentsPage-CMvz-CtA.js → AgentsPage-BOIJ55cj.js} +1 -1
- package/dist/ui/assets/{ApiClientPage-tzzL3rZC.js → ApiClientPage-R9UDWfR2.js} +1 -1
- package/dist/ui/assets/{ChannelsPage-fE2vRwup.js → ChannelsPage-C5V2BmjL.js} +1 -1
- package/dist/ui/assets/{DashboardPage-57SaHnBL.js → DashboardPage-B18gMzNj.js} +1 -1
- package/dist/ui/assets/{LoginPage-Fag9Bp5h.js → LoginPage-nrsYF9AY.js} +1 -1
- package/dist/ui/assets/{LogsPage-GVJd_a65.js → LogsPage-DICMU_7m.js} +1 -1
- package/dist/ui/assets/{MeetingPage-TKQu8Nr-.js → MeetingPage-xslJGfIz.js} +1 -1
- package/dist/ui/assets/{ModelSelector-DciHLo7R.js → ModelSelector-BX4IvuYY.js} +1 -1
- package/dist/ui/assets/Office3DPage-a6cuzt5X.js +727 -0
- package/dist/ui/assets/{ProvidersPage-BsWFvzqz.js → ProvidersPage-C8-xGoeh.js} +1 -1
- package/dist/ui/assets/{RecoverPage-BkdOyljs.js → RecoverPage-Blms3NBa.js} +1 -1
- package/dist/ui/assets/{SettingsPage-D_43Rc2I.js → SettingsPage-BBeeq_QS.js} +1 -1
- package/dist/ui/assets/{SetupPage-D6Z3SYZu.js → SetupPage-CAjLseE_.js} +1 -1
- package/dist/ui/assets/{Vignette-bSrGVyRd.js → Vignette-DrI2yK2m.js} +1 -1
- package/dist/ui/assets/VoicePage-BeSSYstD.js +307 -0
- package/dist/ui/assets/{WebChatPage-Dzk3FhiR.js → WebChatPage-Bat7uUfd.js} +1 -1
- package/dist/ui/assets/{bia-csMImkVQ.glb → bia-qdLMQRFi.glb} +0 -0
- package/dist/ui/assets/{conversationsStore-5hf5grlP.js → conversationsStore-DhM07qYi.js} +1 -1
- package/dist/ui/assets/{dialog-DKnsGLwr.js → dialog-BP3GTCPn.js} +1 -1
- package/dist/ui/assets/{index-mBw9Tl7u.js → index-BG3nUPKq.js} +2 -2
- package/dist/ui/assets/{useAudioDevices-BYFaA0X-.js → useAudioDevices-zj0fuGwZ.js} +1 -1
- package/dist/ui/assets/{useHiveAgentsModelLoad-RRQ6-ANC.js → useHiveAgentsModelLoad-Cd9p-bjs.js} +1 -1
- package/dist/ui/assets/{useProviders-DXr4pJ57.js → useProviders-Dj1k5PCk.js} +1 -1
- package/dist/ui/index.html +1 -1
- package/package.json +1 -1
- package/packages/cli/src/commands/onboard.ts +8 -7
- package/packages/core/src/gateway/routes/providers.ts +26 -79
- package/packages/core/src/gateway/server.ts +20 -0
- package/packages/core/src/scheduler/integration.ts +26 -20
- package/packages/core/src/storage/collections.ts +7 -0
- package/packages/core/src/storage/model-sync.ts +404 -0
- package/packages/core/src/storage/seed.ts +33 -3
- package/packages/core/src/tools/cron/index.ts +25 -3
- package/packages/core/src/tools/office/office-escribir-docx.ts +275 -97
- package/packages/core/src/tools/office/office-escribir-pdf.ts +489 -99
- package/packages/core/src/tools/office/office-escribir-pptx.ts +86 -84
- package/packages/core/src/tools/office/office-escribir-xlsx.ts +196 -40
- package/packages/core/src/tools/office/office-style.ts +452 -0
- package/packages/core/src/tools/web/obscura-install.ts +119 -0
- package/packages/core/src/tools/web/obscura.ts +26 -4
- package/packages/core/src/utils/date.ts +29 -0
- package/packages/skills/src/bundled-data.generated.ts +780 -780
- package/dist/ui/assets/Office3DPage-CQnO522l.js +0 -727
- package/dist/ui/assets/VoicePage-CCE2EOE9.js +0 -307
|
@@ -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
|
|
238
|
-
const
|
|
239
|
-
|
|
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
|
-
|
|
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
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
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
|
+
}
|
|
@@ -362,11 +362,29 @@ export const SEED_DATA: SeedData = {
|
|
|
362
362
|
// julio/agosto con "Free Endpoint" en el catálogo de NGC, y responden con
|
|
363
363
|
// tool calling en una cuenta gratuita. Contexto según la referencia de la API
|
|
364
364
|
// de NVIDIA (Kimi K3) y OpenRouter (el resto). Verificado 2026-09-10.
|
|
365
|
-
{ id: "moonshotai/kimi-k3", providerId: "nvidia", name: "Kimi K3 (NVIDIA)", modelType: "llm", contextWindow: 1048576, capabilities: JSON.stringify(["chat", "code", "vision", "function_calling", "streaming", "reasoning"]), inputPer1M: 0, outputPer1M: 0 },
|
|
366
|
-
{ id: "deepseek-ai/deepseek-v4-flash-0731", providerId: "nvidia", name: "DeepSeek V4 Flash (NVIDIA)", modelType: "llm", contextWindow: 1048576, capabilities: JSON.stringify(["chat", "code", "function_calling", "streaming", "reasoning"]), inputPer1M: 0, outputPer1M: 0 },
|
|
367
365
|
{ id: "meta/muse-glimmer-30b", providerId: "nvidia", name: "Muse Glimmer 30B (NVIDIA)", modelType: "llm", contextWindow: 131072, capabilities: JSON.stringify(["chat", "vision", "function_calling", "streaming", "reasoning"]), inputPer1M: 0, outputPer1M: 0 },
|
|
368
366
|
{ id: "nvidia/nemotron-3-ultra-550b-a55b", providerId: "nvidia", name: "Nemotron 3 Ultra 550B", modelType: "llm", contextWindow: 1000000, capabilities: JSON.stringify(["chat", "code", "json_mode", "function_calling", "streaming", "reasoning"]), inputPer1M: 0, outputPer1M: 0 },
|
|
369
|
-
|
|
367
|
+
// Revisado el 2026-11-16 con llamadas reales a /v1/models y a cada modelo (nivel gratuito, "Free Endpoint"): de 23
|
|
368
|
+
// LLMs listados respondieron 11, y 10 de ellos también con herramientas. Que el proveedor liste un modelo NO
|
|
369
|
+
// garantiza que funcione: varios devuelven 404 "Function not found for account" o 500.
|
|
370
|
+
// Solo se declaran las capacidades comprobadas ese día, y SOLO quedan los que llamaron herramientas (tool_calls): sin
|
|
371
|
+
// eso un modelo no sirve para un agente. Retirados (410 Gone) y por eso quitados de esta lista:
|
|
372
|
+
// moonshotai/kimi-k3 (2026-10-15), deepseek-ai/deepseek-v4-flash-0731 (2026-09-21) y
|
|
373
|
+
// nvidia/nemotron-3-super-120b-a12b (2026-10-03). z-ai/glm-5.3 también se retiró (2026-10-28).
|
|
374
|
+
// Quedaron fuera por no responder hoy, aunque figuran en /v1/models: z-ai/glm-5.3-flash (agota 170 s, dos veces) y
|
|
375
|
+
// minimaxai/minimax-m3.1-flash (503 "content safety screening is temporarily unavailable", dos veces). Funcionaron
|
|
376
|
+
// en una prueba anterior: si vuelven, se pueden añadir de nuevo.
|
|
377
|
+
// deepseek-ai/deepseek-v4.1-flash respondió bien en las pruebas, pero /v1/models ya no lo lista: no entra (esta lista
|
|
378
|
+
// se valida contra el listado vivo; `storage/model-sync.ts` lo marcaría `unlisted`).
|
|
379
|
+
{ id: "nvidia/nemotron-3.5-super-vl-120b-a12b", providerId: "nvidia", name: "Nemotron 3.5 Super VL 120B", modelType: "llm", contextWindow: 1000000, capabilities: JSON.stringify(["chat", "vision", "reasoning", "function_calling"]), inputPer1M: 0, outputPer1M: 0 },
|
|
380
|
+
{ id: "nvidia/nemotron-3.5-bolt-e4b", providerId: "nvidia", name: "Nemotron 3.5 Bolt E4B", modelType: "llm", contextWindow: 65536, capabilities: JSON.stringify(["chat", "vision", "function_calling"]), inputPer1M: 0, outputPer1M: 0 },
|
|
381
|
+
{ id: "nvidia/nemotron-3-nano-omni-30b-a3b-reasoning", providerId: "nvidia", name: "Nemotron 3 Nano Omni 30B", modelType: "llm", contextWindow: 262144, capabilities: JSON.stringify(["chat", "vision", "reasoning", "function_calling"]), inputPer1M: 0, outputPer1M: 0 },
|
|
382
|
+
// Con ventana de contexto 0 (NVIDIA no la publica y no se inventa): el runtime ya la trata como desconocida.
|
|
383
|
+
{ id: "nvidia/nemotron-3.5-lightning-30b-a3b", providerId: "nvidia", name: "Nemotron 3.5 Lightning 30B", modelType: "llm", contextWindow: 0, capabilities: JSON.stringify(["chat", "reasoning", "function_calling"]), inputPer1M: 0, outputPer1M: 0 },
|
|
384
|
+
{ id: "mistralai/mistral-large-4-1t-a52b", providerId: "nvidia", name: "Mistral Large 4 (NVIDIA)", modelType: "llm", contextWindow: 0, capabilities: JSON.stringify(["chat", "reasoning", "function_calling"]), inputPer1M: 0, outputPer1M: 0 },
|
|
385
|
+
{ id: "google/gemma-4-31b-it", providerId: "nvidia", name: "Gemma 4 31B IT (NVIDIA)", modelType: "llm", contextWindow: 0, capabilities: JSON.stringify(["chat", "function_calling"]), inputPer1M: 0, outputPer1M: 0 },
|
|
386
|
+
{ id: "poolside/laguna-xs-2.1", providerId: "nvidia", name: "Laguna XS 2.1 (NVIDIA)", modelType: "llm", contextWindow: 0, capabilities: JSON.stringify(["chat", "function_calling"]), inputPer1M: 0, outputPer1M: 0 },
|
|
387
|
+
{ id: "stepfun-ai/step-5-preview", providerId: "nvidia", name: "Step 5 Preview (NVIDIA)", modelType: "llm", contextWindow: 0, capabilities: JSON.stringify(["chat", "reasoning", "function_calling"]), inputPer1M: 0, outputPer1M: 0 },
|
|
370
388
|
|
|
371
389
|
// ── ModelScope Qwen (fuente: GET https://api-inference.modelscope.ai/v1/models) ──
|
|
372
390
|
// Endpoint gratuito dentro de cuota (2000 llamadas/día, ≤500 por modelo), por
|
|
@@ -435,6 +453,18 @@ export const SEED_DATA: SeedData = {
|
|
|
435
453
|
// Se carga por el primer shard: llama.cpp descubre los otros dos solo.
|
|
436
454
|
// Sólo texto, y el más lento del inventario: ~91 s de carga y 12.8 t/s.
|
|
437
455
|
{ id: "DeepSeek-V4-Flash-UD-IQ2_XXS-00001-of-00003.gguf", providerId: "hiveagents", name: "DeepSeek V4 Flash 90 GB (lento)", modelType: "llm", contextWindow: 32768, capabilities: JSON.stringify(["chat", "streaming", "reasoning", "function_calling"]), inputPer1M: 0, outputPer1M: 0 },
|
|
456
|
+
|
|
457
|
+
// ── Voz y tiempo real del catálogo revisado el 2026-11-13 (mismo catálogo que usa el gateway Rust) ──
|
|
458
|
+
// Solo entran los que este proyecto sabe ejecutar: TTS con gemini, qwen y elevenlabs, y tiempo real con gemini.
|
|
459
|
+
// Quedan fuera, por no tener adaptador aquí: STT de gemini/qwen/elevenlabs/openai (solo hay groq y Whisper),
|
|
460
|
+
// TTS de mistral y minimax, tiempo real de openai y qwen, y el OCR de mistral.
|
|
461
|
+
{ id: "gemini-3.8-live-extended-thinking", providerId: "gemini", name: "Gemini 3.8 Live Extended Thinking", modelType: "realtime", contextWindow: 131072, capabilities: JSON.stringify(["realtime", "audio_in", "audio_out", "transcription", "function_calling"]) },
|
|
462
|
+
{ id: "gemini-3.8-flash-tts", providerId: "gemini", name: "Gemini 3.8 Flash TTS", modelType: "tts", contextWindow: 0, capabilities: JSON.stringify(["tts", "speech"]) },
|
|
463
|
+
{ id: "gemini-3.8-flash-lite-tts", providerId: "gemini", name: "Gemini 3.8 Flash Lite TTS", modelType: "tts", contextWindow: 0, capabilities: JSON.stringify(["tts", "speech"]) },
|
|
464
|
+
{ id: "qwen-audio-3.1-tts-flash", providerId: "qwen", name: "Qwen Audio 3.1 TTS Flash", modelType: "tts", contextWindow: 0, capabilities: JSON.stringify(["tts", "speech"]) },
|
|
465
|
+
{ id: "eleven_v4", providerId: "elevenlabs", name: "Eleven V4", modelType: "tts", contextWindow: 0, capabilities: JSON.stringify(["tts", "speech"]) },
|
|
466
|
+
{ id: "eleven_v4_turbo", providerId: "elevenlabs", name: "Eleven V4 Turbo", modelType: "tts", contextWindow: 0, capabilities: JSON.stringify(["tts", "speech"]) },
|
|
467
|
+
{ id: "eleven_v3_conversational", providerId: "elevenlabs", name: "Eleven V3 Conversational", modelType: "tts", contextWindow: 0, capabilities: JSON.stringify(["tts", "speech"]) },
|
|
438
468
|
],
|
|
439
469
|
|
|
440
470
|
|
|
@@ -13,6 +13,7 @@ import { col, toIndexable } from "../../storage/hive";
|
|
|
13
13
|
import type { UserDoc, UserIdentityDoc, ChannelDoc, CronJobDoc, TaskRunDoc } from "../../storage/collections";
|
|
14
14
|
import { logger } from "../../utils/logger";
|
|
15
15
|
import { Cron } from "../../scheduler/cron";
|
|
16
|
+
import { formatUserDateTime } from "../../utils/date";
|
|
16
17
|
|
|
17
18
|
const log = logger.child("CronTools");
|
|
18
19
|
|
|
@@ -32,6 +33,25 @@ async function getUserTimezone(): Promise<string> {
|
|
|
32
33
|
return userEntry?.doc.timezone || "UTC";
|
|
33
34
|
}
|
|
34
35
|
|
|
36
|
+
/**
|
|
37
|
+
* Todos los canales activos (conectados) del usuario, sin priorizar ninguno.
|
|
38
|
+
* Si no hay ninguno conectado cae a los que tengan identidad, y en último caso a webchat.
|
|
39
|
+
*/
|
|
40
|
+
export async function resolveActiveChannels(userId: string): Promise<string[]> {
|
|
41
|
+
const identitiesCol = await col<UserIdentityDoc>("userIdentities");
|
|
42
|
+
const identityEntries = await identitiesCol.scan({ prefix: `${userId}:` });
|
|
43
|
+
const all = [...new Set(identityEntries.map(e => e.doc.channel))];
|
|
44
|
+
|
|
45
|
+
const channelsCol = await col<ChannelDoc>("channels");
|
|
46
|
+
const active: string[] = [];
|
|
47
|
+
for (const channel of all) {
|
|
48
|
+
const entry = await channelsCol.get(channel);
|
|
49
|
+
if (entry?.doc.active && entry.doc.status === "connected") active.push(channel);
|
|
50
|
+
}
|
|
51
|
+
const result = active.length > 0 ? active : all;
|
|
52
|
+
return result.length > 0 ? result : ["webchat"];
|
|
53
|
+
}
|
|
54
|
+
|
|
35
55
|
export async function resolveBestChannel(userId: string, explicitChannel?: string): Promise<string> {
|
|
36
56
|
const usersCol = await col<UserDoc>("users");
|
|
37
57
|
const userEntry = await usersCol.get(userId);
|
|
@@ -201,7 +221,7 @@ export const cronCreateTool: Tool = {
|
|
|
201
221
|
ok: true,
|
|
202
222
|
task_id: result.id,
|
|
203
223
|
next_run: result.nextRun,
|
|
204
|
-
message: `Job "${name}" scheduled. Next run: ${result.nextRun
|
|
224
|
+
message: `Job "${name}" scheduled. Next run: ${formatUserDateTime(result.nextRun, timezone) ?? "unknown"} (${timezone})`,
|
|
205
225
|
};
|
|
206
226
|
} else {
|
|
207
227
|
const cronJobsCol = await col<CronJobDoc>("cronJobs");
|
|
@@ -272,6 +292,7 @@ export const cronListTool: Tool = {
|
|
|
272
292
|
if (task_type) tasks = tasks.filter(t => t.task_type === task_type);
|
|
273
293
|
|
|
274
294
|
tasks.sort((a, b) => (a.next_run_at ?? "").localeCompare(b.next_run_at ?? ""));
|
|
295
|
+
const tz = await getUserTimezone();
|
|
275
296
|
|
|
276
297
|
return {
|
|
277
298
|
ok: true,
|
|
@@ -285,8 +306,9 @@ export const cronListTool: Tool = {
|
|
|
285
306
|
fire_at: t.fire_at,
|
|
286
307
|
start_at: t.start_at,
|
|
287
308
|
stop_at: t.stop_at,
|
|
288
|
-
next_run: t.next_run_at,
|
|
289
|
-
last_run: t.last_run_at,
|
|
309
|
+
next_run: formatUserDateTime(t.next_run_at, tz),
|
|
310
|
+
last_run: formatUserDateTime(t.last_run_at, tz),
|
|
311
|
+
timezone: tz,
|
|
290
312
|
run_count: t.run_count,
|
|
291
313
|
channel: t.channel,
|
|
292
314
|
})),
|