@johpaz/hive-agents 1.1.6 → 1.1.11

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 (182) hide show
  1. package/README.md +4 -10
  2. package/dist/hive.js +5258 -2985
  3. package/dist/tool-worker.js +197 -75
  4. package/dist/ui/assets/{A2UIPage-CxE3jH4_.js → A2UIPage-v-VggXW3.js} +4 -4
  5. package/dist/ui/assets/{AgentCreateForm-SGj5AqAX.js → AgentCreateForm-Dr1l4Cvg.js} +1 -1
  6. package/dist/ui/assets/AgentDetailPage-Dsh_grrr.js +1 -0
  7. package/dist/ui/assets/{AgentNewPage-xvAmX6kw.js → AgentNewPage-D7557C0J.js} +1 -1
  8. package/dist/ui/assets/AgentsPage-C_Z56LL1.js +10 -0
  9. package/dist/ui/assets/{ApiClientPage-NLw2wHjH.js → ApiClientPage-uuBnrh0y.js} +1 -1
  10. package/dist/ui/assets/ChannelsPage-BI4mAgRU.js +8 -0
  11. package/dist/ui/assets/DashboardPage-BjAxvzYP.js +6 -0
  12. package/dist/ui/assets/LoginPage-D7IZKON0.js +1 -0
  13. package/dist/ui/assets/{LogsPage-G9d2G1nL.js → LogsPage-mcqOYvGw.js} +1 -1
  14. package/dist/ui/assets/MeetingPage-qPJ1z5HA.js +1 -0
  15. package/dist/ui/assets/ModelSelector-njfNhkng.js +1 -0
  16. package/dist/ui/assets/{NotFound-D4ZlDVg9.js → NotFound-DY8e1RKh.js} +1 -1
  17. package/dist/ui/assets/{Office3DPage-31AMJ-LN.css → Office3DPage-C3SIzd2H.css} +1 -1
  18. package/dist/ui/assets/Office3DPage-Du42LRwi.js +319 -0
  19. package/dist/ui/assets/ProvidersPage-GDCJs8Zb.js +1 -0
  20. package/dist/ui/assets/{RecoverPage-Dr6qKgV5.js → RecoverPage-B6qvBBIl.js} +1 -1
  21. package/dist/ui/assets/SettingsPage-Br4PfWuc.js +9 -0
  22. package/dist/ui/assets/{SetupPage-BoVKIf4r.js → SetupPage-OaouFLGD.js} +1 -1
  23. package/dist/ui/assets/{Vignette-DrI2yK2m.js → Vignette-GSZ-owcN.js} +17 -17
  24. package/dist/ui/assets/VoicePage-DRQZBl3j.js +307 -0
  25. package/dist/ui/assets/WebChatPage-Cypq-SYi.js +29 -0
  26. package/dist/ui/assets/{agentCapabilities-CDSfJWhw.js → agentCapabilities-Bf71Gir4.js} +1 -1
  27. package/dist/ui/assets/{alert-CjiX20jI.js → alert-Dn604uVs.js} +1 -1
  28. package/dist/ui/assets/{badge-B5AKge1b.js → badge-C6H33ePv.js} +1 -1
  29. package/dist/ui/assets/{card-mTJ4oZbL.js → card-D0qneq1i.js} +1 -1
  30. package/dist/ui/assets/{conversationsStore-ns_ZfKgg.js → conversationsStore-D6XgjMr1.js} +1 -1
  31. package/dist/ui/assets/{dialog-C3n2xYF2.js → dialog-DO1fQCF7.js} +1 -1
  32. package/dist/ui/assets/dist-js-C2MfmbEW.js +1 -0
  33. package/dist/ui/assets/{dist-js-CkNhvsFc.js → dist-js-Djxbxbst.js} +1 -1
  34. package/dist/ui/assets/google-external-e9lvWjy4.js +1 -0
  35. package/dist/ui/assets/index-BKNFH2al.css +2 -0
  36. package/dist/ui/assets/index-U0e4e5mL.js +156 -0
  37. package/dist/ui/assets/{key-DPkOY-J0.js → key-round-Ca0Ns34v.js} +1 -1
  38. package/dist/ui/assets/{label-D_fvqJyD.js → label-CvAtVE-v.js} +1 -1
  39. package/dist/ui/assets/{scroll-area-CbH8FOo8.js → scroll-area-CYMu7sU0.js} +1 -1
  40. package/dist/ui/assets/select-BjBXxyxL.js +1 -0
  41. package/dist/ui/assets/{slider-DXS4h1LB.js → slider-DR31eN3r.js} +1 -1
  42. package/dist/ui/assets/{switch-ndx8VCpm.js → switch-B5dAwb54.js} +1 -1
  43. package/dist/ui/assets/{tabs-epu-3Tl4.js → tabs-Ct92cLXr.js} +1 -1
  44. package/dist/ui/assets/{earth-BJRGJbVn.js → terminal-CpBDERBE.js} +1 -1
  45. package/dist/ui/assets/{textarea-BgZJFZTX.js → textarea-xtFAVuPf.js} +1 -1
  46. package/dist/ui/assets/{useAudioDevices-CsPrtpWY.js → useAudioDevices-wZArmV3m.js} +1 -1
  47. package/dist/ui/assets/{useHiveAgentsModelLoad-nn4gON9g.js → useHiveAgentsModelLoad-CqJkzTOT.js} +1 -1
  48. package/dist/ui/assets/useOfficeModel-DZvwZRCw.js +1 -0
  49. package/dist/ui/assets/{useProviders-9tvEC3hX.js → useProviders-CeSzDnx-.js} +1 -1
  50. package/dist/ui/assets/vendor-router-DxU0Uf4R.js +3 -0
  51. package/dist/ui/index.html +5 -5
  52. package/package.json +1 -3
  53. package/packages/core/src/agent/agent-catalog.ts +98 -1
  54. package/packages/core/src/agent/agent-loop.ts +5 -44
  55. package/packages/core/src/agent/context-compiler.ts +6 -94
  56. package/packages/core/src/agent/conversation-store.ts +23 -1
  57. package/packages/core/src/agent/llm-providers/openai-compat-base.ts +1 -1
  58. package/packages/core/src/agent/prompt-builder.ts +17 -1
  59. package/packages/core/src/agent/tool-selector.ts +8 -0
  60. package/packages/core/src/artifacts/store.ts +66 -8
  61. package/packages/core/src/canvas/emitter.ts +0 -19
  62. package/packages/core/src/gateway/google-host.ts +228 -0
  63. package/packages/core/src/gateway/initializer.ts +8 -0
  64. package/packages/core/src/gateway/routes/agents.ts +14 -0
  65. package/packages/core/src/gateway/routes/auth.ts +25 -3
  66. package/packages/core/src/gateway/routes/chat.ts +14 -1
  67. package/packages/core/src/gateway/routes/google.ts +252 -0
  68. package/packages/core/src/gateway/routes/meeting.ts +11 -3
  69. package/packages/core/src/gateway/routes/models.ts +27 -11
  70. package/packages/core/src/gateway/routes/multimodal.ts +19 -0
  71. package/packages/core/src/gateway/routes/providers.ts +19 -18
  72. package/packages/core/src/gateway/routes/system.ts +1 -3
  73. package/packages/core/src/gateway/routes/tts-local.ts +20 -374
  74. package/packages/core/src/gateway/routes/voice.ts +29 -35
  75. package/packages/core/src/gateway/server.ts +58 -32
  76. package/packages/core/src/gateway/tts/README.md +7 -86
  77. package/packages/core/src/gateway/tts/build.py +105 -0
  78. package/packages/core/src/gateway/tts/kitten.ts +282 -0
  79. package/packages/core/src/gateway/tts/python.d.ts +4 -0
  80. package/packages/core/src/gateway/tts/src/detect.ts +33 -39
  81. package/packages/core/src/gateway/tts/worker.py +80 -0
  82. package/packages/core/src/google/client.ts +123 -0
  83. package/packages/core/src/google/config.ts +60 -0
  84. package/packages/core/src/google/google.test.ts +287 -0
  85. package/packages/core/src/google/index.ts +5 -0
  86. package/packages/core/src/google/oauth.ts +144 -0
  87. package/packages/core/src/google/scopes.ts +41 -0
  88. package/packages/core/src/google/token-store.ts +33 -0
  89. package/packages/core/src/multimodal/attachment-ingest.ts +19 -4
  90. package/packages/core/src/multimodal/image-generation.ts +244 -0
  91. package/packages/core/src/storage/collections.ts +8 -8
  92. package/packages/core/src/storage/google-capabilities.ts +91 -0
  93. package/packages/core/src/storage/model-activation.ts +18 -0
  94. package/packages/core/src/storage/model-sync.ts +66 -14
  95. package/packages/core/src/storage/onboarding.ts +10 -2
  96. package/packages/core/src/storage/seed.ts +81 -18
  97. package/packages/core/src/storage/usage.ts +0 -52
  98. package/packages/core/src/tools/agents/get-available-models.ts +1 -3
  99. package/packages/core/src/tools/core/index.ts +1 -1
  100. package/packages/core/src/tools/google/calendar.ts +204 -0
  101. package/packages/core/src/tools/google/drive.ts +160 -0
  102. package/packages/core/src/tools/google/gmail.ts +579 -0
  103. package/packages/core/src/tools/google/index.ts +18 -0
  104. package/packages/core/src/tools/google/shared.ts +80 -0
  105. package/packages/core/src/tools/image/image-generate.ts +90 -0
  106. package/packages/core/src/tools/image/index.ts +13 -0
  107. package/packages/core/src/tools/image/office-leer-imagenes.ts +198 -0
  108. package/packages/core/src/tools/index.ts +27 -0
  109. package/packages/core/src/tools/office/office-images.ts +137 -0
  110. package/packages/core/src/tools/office/office-leer-docx.ts +10 -1
  111. package/packages/core/src/tools/office/office-leer-pdf.ts +1 -1
  112. package/packages/core/src/tools/office/office-leer-pptx.ts +4 -1
  113. package/packages/core/src/tools/office/office-pdf-images.ts +225 -0
  114. package/packages/core/src/tools/office/pdf-text.ts +2 -2
  115. package/packages/core/src/tools/web/browser-screenshot.ts +7 -0
  116. package/packages/core/src/voice/index.ts +123 -155
  117. package/packages/core/src/voice/local-model.ts +8 -0
  118. package/packages/core/src/voice/stt-models.ts +39 -0
  119. package/packages/skills/src/bundled/google/google_calendar/SKILL.md +51 -0
  120. package/packages/skills/src/bundled/google/google_drive/SKILL.md +50 -0
  121. package/packages/skills/src/bundled/google/google_gmail/SKILL.md +61 -0
  122. package/packages/skills/src/bundled-data.generated.ts +45 -0
  123. package/dist/ui/assets/AgentDetailPage-CyYbqzHr.js +0 -1
  124. package/dist/ui/assets/AgentsPage-CEWNs4Lt.js +0 -10
  125. package/dist/ui/assets/ChannelsPage-CmeXP-hI.js +0 -8
  126. package/dist/ui/assets/DashboardPage-C3z4kZXD.js +0 -6
  127. package/dist/ui/assets/LoginPage-DDisP8hm.js +0 -1
  128. package/dist/ui/assets/MeetingPage-CKyjxtFr.js +0 -1
  129. package/dist/ui/assets/ModelSelector-VVwpDrYF.js +0 -1
  130. package/dist/ui/assets/Office3DPage-CYxB6z2p.js +0 -727
  131. package/dist/ui/assets/ProvidersPage-CM9-E-Pf.js +0 -1
  132. package/dist/ui/assets/SettingsPage-BvD-vs5g.js +0 -9
  133. package/dist/ui/assets/VoicePage-CmudxYny.js +0 -307
  134. package/dist/ui/assets/WebChatPage-CnoXpEOl.js +0 -29
  135. package/dist/ui/assets/dist-js-jWCEHSkB.js +0 -1
  136. package/dist/ui/assets/index-C0W6p0lk.js +0 -156
  137. package/dist/ui/assets/index-DmFPF9xQ.css +0 -2
  138. package/dist/ui/assets/lock-open-v0EphssG.js +0 -1
  139. package/dist/ui/assets/select-v_3QBYrD.js +0 -1
  140. package/dist/ui/assets/terminal-BEcTK780.js +0 -1
  141. package/dist/ui/assets/useOfficeModel-BaDn7U-X.js +0 -1
  142. package/dist/ui/assets/vendor-router-DSMCk-Ka.js +0 -3
  143. package/packages/core/src/agent/jev-decisions.ts +0 -242
  144. package/packages/core/src/agent/jev-planner.ts +0 -293
  145. package/packages/core/src/gateway/tts/package.json +0 -25
  146. package/packages/core/src/gateway/tts/src/client.ts +0 -59
  147. package/packages/core/src/gateway/tts/src/index.ts +0 -15
  148. package/packages/core/src/gateway/tts/src/install.ts +0 -137
  149. package/packages/core/src/gateway/tts/src/models.ts +0 -50
  150. package/packages/core/src/gateway/tts/src/server.ts +0 -253
  151. /package/dist/ui/assets/{core-p4c5dns5.js → core-npANj14X.js} +0 -0
  152. /package/dist/ui/assets/{download-BQXrpH0m.js → download-D0aDV8Y_.js} +0 -0
  153. /package/dist/ui/assets/{ellipsis-vertical-D7uFJLGh.js → ellipsis-vertical-BOW_iEOO.js} +0 -0
  154. /package/dist/ui/assets/{external-link-6oTH9pUM.js → external-link-DNJH7epD.js} +0 -0
  155. /package/dist/ui/assets/{eye-CxvxtQT5.js → eye-BVfTWOME.js} +0 -0
  156. /package/dist/ui/assets/{file-text-D5ZJEx3E.js → file-text-ByqNMpXm.js} +0 -0
  157. /package/dist/ui/assets/{gateway-url-BALS_wVh.js → gateway-url-BzQV75Ig.js} +0 -0
  158. /package/dist/ui/assets/{gauge-CEu7PhTW.js → gauge-CB4np0Vz.js} +0 -0
  159. /package/dist/ui/assets/{history-DLK5rTlP.js → history-CbhJX41s.js} +0 -0
  160. /package/dist/ui/assets/{info-8ReWzubE.js → info-BCD3-QX9.js} +0 -0
  161. /package/dist/ui/assets/{lock-3IApZyVy.js → lock-DpBean4K.js} +0 -0
  162. /package/dist/ui/assets/{mail-vwCEHyhQ.js → mail-Biwn8WrV.js} +0 -0
  163. /package/dist/ui/assets/{mic-CpDU_2as.js → mic-Rq4BxU1R.js} +0 -0
  164. /package/dist/ui/assets/{pause-BAMsNQkh.js → pause-87NGXbsz.js} +0 -0
  165. /package/dist/ui/assets/{pencil-CKritjT_.js → pencil-BG8EFaS3.js} +0 -0
  166. /package/dist/ui/assets/{play-Cwpe4tp6.js → play-D3De6YsQ.js} +0 -0
  167. /package/dist/ui/assets/{plus-RD44ce15.js → plus-Bp8-V68t.js} +0 -0
  168. /package/dist/ui/assets/{radio-lFPMHi6-.js → radio-m7rzuDKK.js} +0 -0
  169. /package/dist/ui/assets/{refresh-cw-DtJMHRHO.js → refresh-cw-D6F1zoC6.js} +0 -0
  170. /package/dist/ui/assets/{rotate-ccw-b3E_4PoX.js → rotate-ccw-DUlEC1_D.js} +0 -0
  171. /package/dist/ui/assets/{search-z2oZt00P.js → search-CfNwwpMW.js} +0 -0
  172. /package/dist/ui/assets/{send-CpoY_2F-.js → send-CI868CBV.js} +0 -0
  173. /package/dist/ui/assets/{settings-qV3kVkeG.js → settings-AEM2uWiD.js} +0 -0
  174. /package/dist/ui/assets/{shield-CIarwBvx.js → shield-DvVIcbzd.js} +0 -0
  175. /package/dist/ui/assets/{sparkles-DVvY6jDT.js → sparkles-DRe4GbSH.js} +0 -0
  176. /package/dist/ui/assets/{square-D5zdNkAY.js → square-DTWkjTT3.js} +0 -0
  177. /package/dist/ui/assets/{trash-2-D6oziYAK.js → trash-2-BZsMCfso.js} +0 -0
  178. /package/dist/ui/assets/{utils-DEmd_M8c.js → utils-lc8H6VGT.js} +0 -0
  179. /package/dist/ui/assets/{volume-2-EaA0JRvD.js → volume-2-CBMYsuF3.js} +0 -0
  180. /package/dist/ui/assets/{volume-x-CROXNMGT.js → volume-x-vNFf2e4-.js} +0 -0
  181. /package/dist/ui/assets/{wifi-BUJuOcgP.js → wifi-DNv53AfN.js} +0 -0
  182. /package/dist/ui/assets/{zap-DSoX9NDk.js → zap-Yed86Sh8.js} +0 -0
@@ -0,0 +1,244 @@
1
+ /**
2
+ * Generación de imágenes.
3
+ *
4
+ * Un solo modelo para todo el sistema (chat web, canales, agentes), elegido en
5
+ * Providers → Imagen. Es independiente del modelo de chat: la tool
6
+ * `image_generate` llama a ESTE modelo y entrega la imagen como artifact.
7
+ *
8
+ * Cada provider tiene su propio protocolo de imágenes, así que hay un adaptador
9
+ * por provider. Hoy: NVIDIA (endpoints `ai.api.nvidia.com/v1/genai/...`).
10
+ *
11
+ * Solo genera: los endpoints alojados de NVIDIA para editar (FLUX Kontext, FLUX.2
12
+ * klein con imagen) aceptan únicamente imágenes de ejemplo predefinidas
13
+ * (`data:image/png;example_id,N`), no fotos del usuario. Ver `docs/`.
14
+ */
15
+ import { col } from "../storage/hive"
16
+ import type { ModelDoc } from "../storage/collections"
17
+ import { loadProviderApiKey } from "../storage/crypto"
18
+ import { wireModelId } from "../storage/model-id"
19
+ import { logger } from "../utils/logger"
20
+
21
+ const log = logger.child("image-generation")
22
+
23
+ const SETTINGS_COLLECTION = "system_settings"
24
+ const SETTING_ID = "image_model"
25
+ const MAX_PROMPT_CHARS = 10_000
26
+ const REQUEST_TIMEOUT_MS = 120_000
27
+
28
+ export const ASPECT_RATIOS = ["square", "landscape", "portrait", "4:3", "3:4"] as const
29
+ export type AspectRatio = (typeof ASPECT_RATIOS)[number]
30
+
31
+ /** Tamaños que aceptan los modelos FLUX alojados (múltiplos de 64 entre 768 y 1344). */
32
+ const SIZES: Record<AspectRatio, { width: number; height: number }> = {
33
+ square: { width: 1024, height: 1024 },
34
+ landscape: { width: 1344, height: 768 },
35
+ portrait: { width: 768, height: 1344 },
36
+ "4:3": { width: 1152, height: 896 },
37
+ "3:4": { width: 896, height: 1152 },
38
+ }
39
+
40
+ export interface GenerateImageRequest {
41
+ prompt: string
42
+ aspectRatio?: AspectRatio
43
+ }
44
+
45
+ export interface GeneratedImage {
46
+ bytes: Uint8Array
47
+ mimeType: string
48
+ /** Fila de `models` que se usó. */
49
+ modelId: string
50
+ providerId: string
51
+ }
52
+
53
+ interface AdapterInput {
54
+ apiKey: string
55
+ /** El nombre que espera el provider en el cable, sin prefijo de revendedor. */
56
+ wireModelId: string
57
+ prompt: string
58
+ size: { width: number; height: number }
59
+ fetchImpl: typeof fetch
60
+ }
61
+
62
+ interface ImageAdapter {
63
+ generate(input: AdapterInput): Promise<{ bytes: Uint8Array; mimeType: string }>
64
+ }
65
+
66
+ export class ImageGenerationError extends Error {
67
+ constructor(message: string, readonly retryable = false) {
68
+ super(message)
69
+ this.name = "ImageGenerationError"
70
+ }
71
+ }
72
+
73
+ function sniffMime(bytes: Uint8Array): string {
74
+ if (bytes[0] === 0xff && bytes[1] === 0xd8) return "image/jpeg"
75
+ if (bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) return "image/png"
76
+ if (bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46) return "image/webp"
77
+ return "image/png"
78
+ }
79
+
80
+ const delay = (ms: number) => new Promise((r) => setTimeout(r, ms))
81
+
82
+ // ─── NVIDIA ──────────────────────────────────────────────────────────────────
83
+
84
+ const NVIDIA_GENAI = "https://ai.api.nvidia.com/v1/genai"
85
+
86
+ /**
87
+ * Cuerpo por modelo. Los endpoints validan con `additionalProperties: false`:
88
+ * un campo de más (p. ej. `seed`) devuelve 422, así que se envía lo mínimo.
89
+ * Los dos modelos del catálogo son de pocos pasos (destilados): `steps: 4`.
90
+ */
91
+ function nvidiaBody(wireId: string, input: AdapterInput): Record<string, unknown> {
92
+ void wireId
93
+ return { prompt: input.prompt, width: input.size.width, height: input.size.height, steps: 4 }
94
+ }
95
+
96
+ const nvidiaAdapter: ImageAdapter = {
97
+ async generate(input) {
98
+ const url = `${NVIDIA_GENAI}/${input.wireModelId}`
99
+ let lastError: ImageGenerationError | null = null
100
+ for (let attempt = 0; attempt < 2; attempt++) {
101
+ if (attempt > 0) await delay(1500)
102
+ let res: Response
103
+ try {
104
+ res = await input.fetchImpl(url, {
105
+ method: "POST",
106
+ headers: {
107
+ Authorization: `Bearer ${input.apiKey}`,
108
+ Accept: "application/json",
109
+ "Content-Type": "application/json",
110
+ },
111
+ body: JSON.stringify(nvidiaBody(input.wireModelId, input)),
112
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
113
+ })
114
+ } catch (err) {
115
+ const timeout = (err as Error).name === "TimeoutError"
116
+ lastError = new ImageGenerationError(
117
+ timeout ? "NVIDIA tardó demasiado en generar la imagen." : `No se pudo contactar a NVIDIA: ${(err as Error).message}`,
118
+ true,
119
+ )
120
+ continue
121
+ }
122
+
123
+ if (res.status === 401 || res.status === 403) {
124
+ throw new ImageGenerationError("NVIDIA rechazó la API key (revisa la clave del provider NVIDIA).")
125
+ }
126
+ if (res.status === 404) {
127
+ throw new ImageGenerationError(`NVIDIA ya no ofrece el modelo ${input.wireModelId}. Elige otro en Providers → Imagen.`)
128
+ }
129
+ if (res.status === 429) {
130
+ lastError = new ImageGenerationError("NVIDIA alcanzó el límite de solicitudes de la cuenta de prueba. Espera un momento.", true)
131
+ continue
132
+ }
133
+ if (res.status >= 500) {
134
+ lastError = new ImageGenerationError(`NVIDIA falló al generar la imagen (HTTP ${res.status}).`, true)
135
+ continue
136
+ }
137
+ const text = await res.text()
138
+ if (!res.ok) {
139
+ let detail = text.slice(0, 200)
140
+ try {
141
+ const j = JSON.parse(text) as { detail?: unknown }
142
+ detail = typeof j.detail === "string" ? j.detail : JSON.stringify(j.detail).slice(0, 200)
143
+ } catch { /* texto plano */ }
144
+ throw new ImageGenerationError(`NVIDIA rechazó la solicitud (HTTP ${res.status}): ${detail}`)
145
+ }
146
+
147
+ let json: { artifacts?: Array<{ base64?: string; finishReason?: string }> }
148
+ try { json = JSON.parse(text) } catch { throw new ImageGenerationError("NVIDIA devolvió una respuesta que no es JSON.") }
149
+ const artifact = json.artifacts?.[0]
150
+ if (artifact?.finishReason && artifact.finishReason !== "SUCCESS") {
151
+ throw new ImageGenerationError(
152
+ artifact.finishReason === "CONTENT_FILTERED"
153
+ ? "El filtro de contenido de NVIDIA bloqueó esta imagen. Prueba con otra descripción."
154
+ : `NVIDIA no completó la imagen (${artifact.finishReason}).`,
155
+ )
156
+ }
157
+ if (!artifact?.base64) throw new ImageGenerationError("NVIDIA no devolvió ninguna imagen.")
158
+ const bytes = new Uint8Array(Buffer.from(artifact.base64.replace(/^data:[^,]+,/, ""), "base64"))
159
+ if (bytes.byteLength < 100) throw new ImageGenerationError("NVIDIA devolvió una imagen vacía.")
160
+ return { bytes, mimeType: sniffMime(bytes) }
161
+ }
162
+ throw lastError ?? new ImageGenerationError("No se pudo generar la imagen.")
163
+ },
164
+ }
165
+
166
+ /** Providers con adaptador: solo ellos pueden ser el generador de imágenes. */
167
+ const ADAPTERS: Record<string, ImageAdapter> = {
168
+ nvidia: nvidiaAdapter,
169
+ }
170
+
171
+ export function supportsImageGeneration(providerId: string): boolean {
172
+ return providerId in ADAPTERS
173
+ }
174
+
175
+ // ─── Ajuste del sistema ──────────────────────────────────────────────────────
176
+
177
+ async function apiKeyFor(providerId: string): Promise<string> {
178
+ return (await loadProviderApiKey(providerId)) || process.env[`${providerId.toUpperCase()}_API_KEY`] || ""
179
+ }
180
+
181
+ export async function getImageModelId(): Promise<string | null> {
182
+ const entry = await (await col<{ model_id: string | null }>(SETTINGS_COLLECTION)).get(SETTING_ID)
183
+ return entry?.doc.model_id || null
184
+ }
185
+
186
+ /** Guarda el modelo generador (null lo quita). Valida tipo, adaptador y API key. */
187
+ export async function setImageModelId(modelId: string | null): Promise<void> {
188
+ if (modelId) {
189
+ const entry = await (await col<ModelDoc>("models")).get(modelId)
190
+ if (!entry) throw new Error(`El modelo ${modelId} no existe`)
191
+ if (entry.doc.model_type !== "image") throw new Error(`${entry.doc.name} no es un modelo de generación de imágenes`)
192
+ if (!supportsImageGeneration(entry.doc.provider_id)) {
193
+ throw new Error(`Hive todavía no sabe generar imágenes con el provider ${entry.doc.provider_id}`)
194
+ }
195
+ if (!(await apiKeyFor(entry.doc.provider_id))) {
196
+ throw new Error(`Primero configura la API key del provider ${entry.doc.provider_id}`)
197
+ }
198
+ }
199
+ const settings = await col<{ model_id: string | null }>(SETTINGS_COLLECTION)
200
+ const current = await settings.get(SETTING_ID)
201
+ await settings.put(SETTING_ID, { model_id: modelId }, { expectedVersion: current?.version ?? 0 })
202
+ }
203
+
204
+ // ─── Generación ──────────────────────────────────────────────────────────────
205
+
206
+ export class ImageModelNotConfiguredError extends Error {
207
+ constructor() {
208
+ super("No hay un modelo de generación de imágenes configurado.")
209
+ this.name = "ImageModelNotConfiguredError"
210
+ }
211
+ }
212
+
213
+ export async function generateImage(
214
+ req: GenerateImageRequest,
215
+ opts: { fetchImpl?: typeof fetch } = {},
216
+ ): Promise<GeneratedImage> {
217
+ const prompt = req.prompt?.trim()
218
+ if (!prompt) throw new ImageGenerationError("Falta la descripción de la imagen.")
219
+ if (prompt.length > MAX_PROMPT_CHARS) {
220
+ throw new ImageGenerationError(`La descripción es demasiado larga (${prompt.length} caracteres; máximo ${MAX_PROMPT_CHARS}).`)
221
+ }
222
+
223
+ const modelId = await getImageModelId()
224
+ if (!modelId) throw new ImageModelNotConfiguredError()
225
+ const entry = await (await col<ModelDoc>("models")).get(modelId)
226
+ if (!entry) throw new ImageGenerationError(`El modelo de imágenes ${modelId} ya no existe. Elige otro en Providers → Imagen.`)
227
+
228
+ const providerId = entry.doc.provider_id
229
+ const adapter = ADAPTERS[providerId]
230
+ if (!adapter) throw new ImageGenerationError(`Hive todavía no sabe generar imágenes con el provider ${providerId}.`)
231
+ const apiKey = await apiKeyFor(providerId)
232
+ if (!apiKey) throw new ImageGenerationError(`Falta la API key del provider ${providerId}.`)
233
+
234
+ const started = Date.now()
235
+ const out = await adapter.generate({
236
+ apiKey,
237
+ wireModelId: wireModelId(providerId, modelId),
238
+ prompt,
239
+ size: SIZES[req.aspectRatio ?? "square"] ?? SIZES.square,
240
+ fetchImpl: opts.fetchImpl ?? fetch,
241
+ })
242
+ log.info(`Imagen generada con ${providerId}/${modelId} (${out.bytes.byteLength} bytes, ${Date.now() - started} ms)`)
243
+ return { ...out, modelId, providerId }
244
+ }
@@ -20,6 +20,9 @@ export interface UserDoc {
20
20
  master_key_hash: string | null
21
21
  email: string | null
22
22
  password_hash: string | null
23
+ /** `sub` de la cuenta de Google vinculada: habilita «Continuar con Google». */
24
+ google_sub?: string | null
25
+ google_email?: string | null
23
26
  preferred_cron_channel: string
24
27
  created_at: number
25
28
  }
@@ -41,7 +44,7 @@ export interface ModelDoc {
41
44
  provider_id: string
42
45
  name: string
43
46
  /** "realtime": voz full-duplex (Live API), no confundir con stt+tts encadenados. */
44
- model_type: "llm" | "stt" | "tts" | "vision" | "embedding" | "realtime" | "decision"
47
+ model_type: "llm" | "stt" | "tts" | "vision" | "embedding" | "realtime" | "image"
45
48
  context_window: number
46
49
  capabilities: string | null
47
50
  enabled: boolean
@@ -302,6 +305,8 @@ export interface ConversationDoc {
302
305
  reasoning_content: string | null
303
306
  /** null on rows written before this field existed (legacy). */
304
307
  source: MessageSource | null
308
+ /** JSON `[{artifactId, mimeType}]` de las imágenes que las herramientas entregaron con esta respuesta. */
309
+ images_json?: string | null
305
310
  token_count: number
306
311
  created_at: number
307
312
  updated_at: number
@@ -531,7 +536,8 @@ export interface ArtifactDoc {
531
536
  height: number | null
532
537
  status: "active" | "expired"
533
538
  created_at: number
534
- expires_at: number
539
+ /** `null` = no caduca (contenido del usuario). */
540
+ expires_at: number | null
535
541
  expired_at: number | null
536
542
  }
537
543
 
@@ -714,12 +720,6 @@ export interface UsageRollupDoc {
714
720
  toonJsonBytes: number
715
721
  byProvider: Record<string, { inputTokens: number; outputTokens: number; costUsd: number }>
716
722
  byModel: Record<string, { inputTokens: number; outputTokens: number; costUsd: number }>
717
- /** Jev decision plane; absent on hours before it existed. Savings are estimates (chars/4) priced at the advised agent's model. */
718
- jevDecisions?: number
719
- jevCostUsd?: number
720
- jevSavedTokens?: number
721
- jevSavedCostUsd?: number
722
- jevByAgent?: Record<string, { jevDecisions: number; jevCostUsd: number; jevSavedTokens: number; jevSavedCostUsd: number }>
723
723
  }
724
724
 
725
725
  export interface ActivityRollupDoc {
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Qué capacidades de Google están activas. Los especialistas y las tools de
3
+ * Gmail/Calendar/Drive solo se activan mientras el usuario tenga esa parte
4
+ * conectada; al desconectar (o sin credenciales) quedan inactivos.
5
+ */
6
+ import { col } from "./hive.ts";
7
+ import type { AgentDoc, ToolDoc, UserDoc } from "./collections.ts";
8
+ import { getGoogleConfig, isGoogleConfigured } from "../google/config.ts";
9
+ import { servicesCovered, type GoogleService } from "../google/scopes.ts";
10
+ import { logger } from "../utils/logger.ts";
11
+
12
+ const log = logger.child("google-capabilities");
13
+
14
+ const SETTINGS_COLLECTION = "system_settings";
15
+ const SETTING_ID = "google_capabilities";
16
+
17
+ export const GOOGLE_AGENT_BY_SERVICE: Record<GoogleService, string> = {
18
+ gmail: "google_mail_agent",
19
+ calendar: "google_calendar_agent",
20
+ drive: "google_drive_agent",
21
+ };
22
+
23
+ const TOOL_PREFIX: Record<GoogleService, string> = { gmail: "gmail_", calendar: "gcal_", drive: "gdrive_" };
24
+
25
+ export const GOOGLE_AGENT_IDS = new Set(Object.values(GOOGLE_AGENT_BY_SERVICE));
26
+
27
+ export const isGoogleAgentId = (id: string) => GOOGLE_AGENT_IDS.has(id);
28
+
29
+ function serviceOfTool(name: string): GoogleService | null {
30
+ for (const [service, prefix] of Object.entries(TOOL_PREFIX) as Array<[GoogleService, string]>) {
31
+ if (name.startsWith(prefix)) return service;
32
+ }
33
+ return null;
34
+ }
35
+
36
+ /** Servicios que el usuario tiene conectados ahora mismo (vacío sin Google o sin conexión). */
37
+ export async function connectedGoogleServices(): Promise<GoogleService[]> {
38
+ if (!isGoogleConfigured()) return [];
39
+ const user = (await (await col<UserDoc>("users")).scan({ limit: 1 }))[0];
40
+ if (!user) return [];
41
+ const tokens = await getGoogleConfig().tokenStore.get(user.id);
42
+ if (!tokens) return [];
43
+ const allowed = getGoogleConfig().services;
44
+ return servicesCovered(tokens.scopes).filter((s) => allowed.includes(s));
45
+ }
46
+
47
+ /**
48
+ * Alinea filas de tools y agentes con la conexión real.
49
+ * · `reason: "connect"` — activa lo conectado y desactiva lo demás.
50
+ * · `reason: "boot"`/`"seed"` — solo desactiva lo no conectado: respeta que el
51
+ * usuario haya apagado a mano algo que sí está conectado. Excepción: la primera
52
+ * vez que encuentra una conexión ya existente (migración), activa sus agentes.
53
+ */
54
+ export async function syncGoogleCapabilities(reason: "connect" | "disconnect" | "boot" | "seed"): Promise<void> {
55
+ const connected = new Set(await connectedGoogleServices());
56
+ // Migración de una sola vez: quien conectó Google antes de que los agentes nacieran apagados
57
+ // tiene una conexión viva y agentes inactivos. La primera vez que se ve una conexión se
58
+ // activan; después, un arranque nunca reactiva lo que el usuario apagó a mano.
59
+ const settings = await col<{ initialized: boolean }>(SETTINGS_COLLECTION);
60
+ const initialized = (await settings.get(SETTING_ID))?.doc.initialized === true;
61
+ const adopt = !initialized && connected.size > 0 && (reason === "boot" || reason === "seed");
62
+ const enable = reason === "connect" || adopt;
63
+ let changed = 0;
64
+
65
+ const toolsCol = await col<ToolDoc>("tools");
66
+ for (const row of await toolsCol.scan({})) {
67
+ const service = serviceOfTool(row.doc.name);
68
+ if (!service || row.doc.category !== "google") continue;
69
+ const on = connected.has(service);
70
+ const wanted = on ? (enable ? true : row.doc.active) : false;
71
+ if (row.doc.active === wanted && row.doc.enabled === wanted) continue;
72
+ await toolsCol.put(row.id, { ...row.doc, active: wanted, enabled: wanted, updated_at: Date.now() }, { expectedVersion: row.version });
73
+ changed++;
74
+ }
75
+
76
+ const agentsCol = await col<AgentDoc>("agents");
77
+ for (const [service, agentId] of Object.entries(GOOGLE_AGENT_BY_SERVICE) as Array<[GoogleService, string]>) {
78
+ const row = await agentsCol.get(agentId);
79
+ if (!row) continue;
80
+ const on = connected.has(service);
81
+ const wanted = on ? (enable ? true : row.doc.enabled) : false;
82
+ if (row.doc.enabled === wanted) continue;
83
+ await agentsCol.put(agentId, { ...row.doc, enabled: wanted, updated_at: Date.now() }, { expectedVersion: row.version });
84
+ changed++;
85
+ }
86
+ if (enable && connected.size > 0 && !initialized) {
87
+ const current = await settings.get(SETTING_ID);
88
+ await settings.put(SETTING_ID, { initialized: true }, { expectedVersion: current?.version ?? 0 });
89
+ }
90
+ if (changed > 0) log.info(`[google] ${changed} capacidad(es) sincronizada(s) (${reason}; conectado: ${[...connected].join(", ") || "nada"})`);
91
+ }
@@ -0,0 +1,18 @@
1
+ import type { ModelDoc, ProviderDoc } from "./collections"
2
+ import { col } from "./hive"
3
+ import { supportsStt } from "../voice/stt-models"
4
+
5
+ export function voiceModelActivation(model: ModelDoc, provider?: ProviderDoc) {
6
+ if (model.unlisted || (model.model_type !== "tts" && !supportsStt(model, provider?.base_url))) return
7
+ const active = !!(provider?.active && provider.enabled)
8
+ return { active, enabled: active }
9
+ }
10
+
11
+ export async function reconcileProviderVoiceModels(provider: ProviderDoc): Promise<void> {
12
+ const models = await col<ModelDoc>("models")
13
+ for (const row of await models.findBy("provider_id", provider.id)) {
14
+ const activation = voiceModelActivation(row.doc, provider)
15
+ if (!activation || (row.doc.active === activation.active && row.doc.enabled === activation.enabled)) continue
16
+ await models.put(row.id, { ...row.doc, ...activation }, { expectedVersion: row.version })
17
+ }
18
+ }
@@ -7,10 +7,11 @@
7
7
  *
8
8
  * Reglas, para que sea seguro correrlo siempre:
9
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.
10
+ * - Los modelos de voz heredan la activación del proveedor. Los demás modelos nuevos entran apagados,
11
+ * salvo la disponibilidad local de Ollama.
12
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
13
+ * La activación de los modelos de voz se reconcilia con el proveedor. El proveedor es la autoridad
14
+ * de la ventana de contexto y de las capacidades que declara (se suman a las que ya
14
15
  * había; nunca se quita ninguna).
15
16
  * - Un modelo que el proveedor ya NO lista no se borra ni se apaga (podría haber agentes apuntándole): se marca
16
17
  * `unlisted: true` para poder avisarlo, y se desmarca si vuelve a aparecer.
@@ -20,8 +21,10 @@
20
21
  import { col } from "./hive"
21
22
  import type { ProviderDoc, ModelDoc } from "./collections"
22
23
  import { catalogModelKey } from "./model-id"
24
+ import { voiceModelActivation } from "./model-activation"
23
25
  import { loadProviderApiKey, loadProviderHeaders } from "./crypto"
24
26
  import { logger } from "../utils/logger"
27
+ import { GEMINI_AUDIO_INPUT, isGeminiAudioFamily, nvidiaSttBase } from "../voice/stt-models"
25
28
 
26
29
  const log = logger.child("model-sync")
27
30
 
@@ -54,7 +57,7 @@ export type ProviderFetcher = (ctx: FetchContext) => Promise<DiscoveredModel[]>
54
57
  /** Providers cuyo listado responde sin clave (o que no la usan): se consultan aunque no haya una guardada. */
55
58
  const KEYLESS = new Set(["ollama", "modelscope"])
56
59
  /** 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"])
60
+ const PARTIAL_LISTING = new Set(["hiveagents"])
58
61
  /** Providers locales: sus modelos son gratis y entran encendidos. */
59
62
  const LOCAL = new Set(["ollama"])
60
63
 
@@ -87,8 +90,8 @@ export function classifyModelId(wireId: string): ModelType | null {
87
90
  // Modelos auxiliares que no conversan: guardas de seguridad, CLIP, detectores, rerankers, parsers y similares.
88
91
  if (/(guard|safety|nvclip|(^|[-_/])clip([-_/.\d]|$)|detector|reward|rerank|retriev|parse|[-_]ocr([-_/.\d]|$))/.test(id)) return null
89
92
  if (/embed/.test(id)) return "embedding"
90
- if (/(whisper|transcribe|scribe|\basr\b|[-_]asr[-_]|stt)/.test(id)) return "stt"
91
93
  if (/(realtime|[-_]live([-_.\d]|$))/.test(id)) return "realtime"
94
+ if (/(whisper|transcribe|scribe|\basr\b|[-_]asr[-_]|stt)/.test(id)) return "stt"
92
95
  if (/(tts|speech|voxtral)/.test(id)) return "tts"
93
96
  return "llm"
94
97
  }
@@ -191,6 +194,7 @@ const gemini: ProviderFetcher = async (ctx) => {
191
194
  else if (methods.includes("generateContent") || methods.includes("streamGenerateContent")) {
192
195
  if (/(image|imagen|veo)/.test(wireId)) continue // imágenes y vídeo: no se manejan
193
196
  type = "llm"; caps.add("chat"); caps.add("streaming")
197
+ if (methods.includes("generateContent") && isGeminiAudioFamily(wireId)) caps.add(GEMINI_AUDIO_INPUT)
194
198
  } else if (methods.includes("embedContent") || methods.includes("batchEmbedContents")) type = "embedding"
195
199
  else if (methods.includes("predict") || methods.includes("predictLongRunning")) continue
196
200
  if (row.thinking === true) caps.add("reasoning")
@@ -241,16 +245,49 @@ const ollama: ProviderFetcher = async (ctx) => {
241
245
  return out
242
246
  }
243
247
 
244
- /** ElevenLabs: `GET /v1/models` con `xi-api-key`; solo los que sirven para síntesis de voz. */
248
+ /** OpenRouter lists file transcription models separately from the general catalog. */
249
+ const openrouter: ProviderFetcher = async (ctx) => {
250
+ if (!ctx.baseUrl) return openAiCompatible(ctx)
251
+ const headers = { ...ctx.headers, ...(ctx.apiKey ? { Authorization: `Bearer ${ctx.apiKey}` } : {}) }
252
+ const [general, transcription] = await Promise.all([
253
+ openAiCompatible(ctx),
254
+ getJson(ctx, `${trimSlash(ctx.baseUrl)}/models?output_modalities=transcription`, headers) as Promise<{ data?: Array<{ id: string; name?: string }> }>,
255
+ ])
256
+ if (!Array.isArray(transcription.data)) throw new Error("OpenRouter no devolvió su catálogo de transcripción")
257
+ const generalById = new Map(general.map(model => [model.wireId, model]))
258
+ const found = new Map(general
259
+ .filter(model => model.type !== "stt" && classifyModelId(model.wireId) !== "stt")
260
+ .map(model => [model.wireId, model]))
261
+ for (const row of transcription.data) {
262
+ if (!text(row.id)) continue
263
+ found.set(row.id, { ...generalById.get(row.id), wireId: row.id, name: text(row.name), type: "stt", capabilities: ["transcription"] })
264
+ }
265
+ return [...found.values()]
266
+ }
267
+
268
+ /** ElevenLabs: `GET /v1/models` con `xi-api-key`. */
245
269
  const elevenlabs: ProviderFetcher = async (ctx) => {
246
270
  const base = trimSlash(ctx.baseUrl || "https://api.elevenlabs.io/v1")
247
271
  const body = (await getJson(ctx, `${base}/models`, { ...ctx.headers, "xi-api-key": ctx.apiKey })) as any[]
248
272
  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"] }))
273
+ .flatMap((m): DiscoveredModel[] => {
274
+ const wireId = text(m.model_id)
275
+ if (!wireId) return []
276
+ if (/^scribe_v\d+(?:_medical)?$/.test(wireId)) return [{ wireId, name: text(m.name), type: "stt", capabilities: ["transcription"] }]
277
+ return m.can_do_text_to_speech ? [{ wireId, name: text(m.name), type: "tts", capabilities: ["tts", "speech"] }] : []
278
+ })
251
279
  }
252
280
 
253
- const FETCHERS: Record<string, ProviderFetcher> = { anthropic, gemini, ollama, elevenlabs }
281
+ const nvidia: ProviderFetcher = async (ctx) => {
282
+ const speechBase = nvidiaSttBase(ctx.baseUrl)
283
+ const models = await openAiCompatible({ ...ctx, baseUrl: speechBase ?? ctx.baseUrl })
284
+ return speechBase
285
+ ? models.map(model => /(?:^|\/)(?:canary|parakeet)[-_/]/.test(model.wireId)
286
+ ? { ...model, type: "stt", capabilities: ["transcription"] }
287
+ : model)
288
+ : models
289
+ }
290
+ const FETCHERS: Record<string, ProviderFetcher> = { anthropic, gemini, ollama, elevenlabs, openrouter, nvidia }
254
291
 
255
292
  /** Consulta el listado del proveedor con el adaptador que le corresponde. */
256
293
  export async function fetchProviderModels(ctx: FetchContext): Promise<DiscoveredModel[]> {
@@ -291,7 +328,7 @@ export async function applyDiscoveredModels(provider: ProviderDoc, found: Discov
291
328
  const row = await models.get(key)
292
329
  if (!row) {
293
330
  if (type === null) continue // un tipo que la app no maneja
294
- await models.put(key, {
331
+ const doc: ModelDoc = {
295
332
  id: key, provider_id: provider.id, name: model.name ?? model.wireId, model_type: type,
296
333
  context_window: model.contextWindow ?? 0,
297
334
  capabilities: model.capabilities?.length ? JSON.stringify(model.capabilities) : null,
@@ -299,13 +336,17 @@ export async function applyDiscoveredModels(provider: ProviderDoc, found: Discov
299
336
  input_per_1m: model.inputPer1M ?? (local ? 0 : null),
300
337
  output_per_1m: model.outputPer1M ?? (local ? 0 : null),
301
338
  synced_at: now,
302
- }, { expectedVersion: 0 })
339
+ }
340
+ await models.put(key, { ...doc, ...voiceModelActivation(doc, provider) }, { expectedVersion: 0 })
303
341
  result.added++
304
342
  continue
305
343
  }
306
344
  const doc = row.doc
307
345
  const next: ModelDoc = { ...doc }
308
346
  let changed = false
347
+ if (doc.source === "discovered" && model.type === "stt" && doc.model_type !== "stt") {
348
+ next.model_type = "stt"; changed = true
349
+ }
309
350
  if (model.contextWindow && doc.context_window !== model.contextWindow) { next.context_window = model.contextWindow; changed = true }
310
351
  if (model.capabilities?.length) {
311
352
  const have = parseCapabilities(doc.capabilities)
@@ -315,6 +356,11 @@ export async function applyDiscoveredModels(provider: ProviderDoc, found: Discov
315
356
  if ((doc.input_per_1m === null || doc.input_per_1m === undefined) && model.inputPer1M !== undefined) { next.input_per_1m = model.inputPer1M; changed = true }
316
357
  if ((doc.output_per_1m === null || doc.output_per_1m === undefined) && model.outputPer1M !== undefined) { next.output_per_1m = model.outputPer1M; changed = true }
317
358
  if (doc.unlisted) { delete next.unlisted; changed = true }
359
+ const activation = voiceModelActivation(next, provider)
360
+ if (activation && (next.active !== activation.active || next.enabled !== activation.enabled)) {
361
+ Object.assign(next, activation)
362
+ changed = true
363
+ }
318
364
  if (changed) {
319
365
  next.synced_at = now
320
366
  await models.put(key, next, { expectedVersion: row.version })
@@ -324,8 +370,9 @@ export async function applyDiscoveredModels(provider: ProviderDoc, found: Discov
324
370
 
325
371
  // 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
372
  if (found.length > 0 && !PARTIAL_LISTING.has(provider.id)) {
373
+ const listsStt = provider.id !== "elevenlabs" || found.some(model => model.type === "stt")
327
374
  for (const row of await models.findBy("provider_id", provider.id)) {
328
- if (seen.has(row.id) || row.doc.unlisted) continue
375
+ if (seen.has(row.id) || row.doc.unlisted || (!listsStt && row.doc.model_type === "stt")) continue
329
376
  await models.put(row.id, { ...row.doc, unlisted: true, synced_at: now }, { expectedVersion: row.version })
330
377
  result.unlisted++
331
378
  }
@@ -368,7 +415,8 @@ export async function syncProviderModels(providerId: string, deps: SyncDeps = {}
368
415
  const entry = await providers.get(providerId)
369
416
  if (!entry) return { provider: providerId, ok: false, error: "provider desconocido" }
370
417
  const apiKey = await (deps.loadKey ?? loadProviderApiKey)(providerId).catch(() => "")
371
- if (!apiKey && !KEYLESS.has(providerId)) return { provider: providerId, ok: false, skipped: "sin clave guardada" }
418
+ const nvidiaSpeech = providerId === "nvidia" && nvidiaSttBase(entry.doc.base_url)
419
+ if (!apiKey && !KEYLESS.has(providerId) && !nvidiaSpeech) return { provider: providerId, ok: false, skipped: "sin clave guardada" }
372
420
  const headers = stringHeaders(await (deps.loadHeaders ?? loadProviderHeaders)(providerId).catch(() => ({})))
373
421
  try {
374
422
  const found = await fetchProviderModels({
@@ -376,7 +424,11 @@ export async function syncProviderModels(providerId: string, deps: SyncDeps = {}
376
424
  fetch: deps.fetch ?? fetch, timeoutMs: deps.timeoutMs ?? 10_000,
377
425
  })
378
426
  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)())
427
+ const latest = await providers.get(providerId)
428
+ if (!latest || latest.doc.base_url !== entry.doc.base_url) {
429
+ return { provider: providerId, ok: false, error: "la configuración del proveedor cambió durante la sincronización" }
430
+ }
431
+ const applied = await applyDiscoveredModels(latest.doc, found, (deps.now ?? Date.now)())
380
432
  return { provider: providerId, ok: true, found: found.length, ...applied }
381
433
  } catch (err) {
382
434
  if (err instanceof ProviderHttpError) return { provider: providerId, ok: false, error: `el proveedor respondió ${err.status}`, status: err.status }
@@ -1,6 +1,7 @@
1
1
  import { logger } from "../utils/logger.ts";
2
2
  import { ensureHiveDb } from "./bootstrap";
3
3
  import { col, toIndexable, fromIndexable } from "./hive";
4
+ import { reconcileProviderVoiceModels } from "./model-activation";
4
5
  import {
5
6
  storeProviderApiKey,
6
7
  storeChannelConfig,
@@ -49,6 +50,9 @@ Para cualquier pedido operativo, compáralo primero con este mapa y delega al es
49
50
  - \`a2ui_builder\`: construye formularios, dashboards y flujos interactivos A2UI.
50
51
  - \`schedule_automation_agent\`: crea y administra jobs, recordatorios y automatizaciones de Hive.
51
52
  - \`api_operator\`: ejecuta y verifica operaciones contra APIs REST autorizadas.
53
+ - \`google_mail_agent\`: busca, lee, responde, envía, organiza (leído, etiquetas, archivo), borradores y adjuntos de la cuenta de Gmail conectada.
54
+ - \`google_calendar_agent\`: consulta, crea y modifica eventos y disponibilidad en Google Calendar.
55
+ - \`google_drive_agent\`: busca, descarga y sube archivos en Google Drive.
52
56
  - Especialistas MCP del usuario: workers con integraciones específicas; encuéntralos con \`agent_find\` antes de usar una tool MCP.
53
57
 
54
58
  **Regla de prioridad:** primero elige un agente de este mapa y usa \`task_delegate\`, pero verifica antes que aparezca activo en la COLMENA; el mapa describe roles y no garantiza disponibilidad. Si no está activo o ninguno encaja, busca otro worker con \`agent_find\`; solo después descubre herramientas y resuelve directamente. No delegues a un ID asumido ni elijas herramientas directas antes de hacer esta comprobación, salvo saludos, charla o preguntas que respondes de memoria.
@@ -242,6 +246,8 @@ export async function saveUserProfile(data: {
242
246
  master_key_hash: existing?.doc.master_key_hash ?? null,
243
247
  email: normalizedEmail ?? existing?.doc.email ?? null,
244
248
  password_hash: existing?.doc.password_hash ?? null,
249
+ google_sub: existing?.doc.google_sub ?? null,
250
+ google_email: existing?.doc.google_email ?? null,
245
251
  preferred_cron_channel: existing?.doc.preferred_cron_channel ?? "auto",
246
252
  created_at: existing?.doc.created_at ?? Date.now(),
247
253
  }, existing ? { expectedVersion: existing.version } : undefined);
@@ -374,9 +380,11 @@ export async function saveProviderConfig(data: {
374
380
  // 1️⃣ Primero: Actualizar provider global con API key del usuario
375
381
  const existingProvider = await providersCol.get(data.provider);
376
382
  if (existingProvider) {
377
- await providersCol.put(data.provider, {
383
+ const provider = {
378
384
  ...existingProvider.doc, base_url: data.baseUrl || null, enabled: true, active: true,
379
- }, { expectedVersion: existingProvider.version });
385
+ };
386
+ await providersCol.put(data.provider, provider, { expectedVersion: existingProvider.version });
387
+ await reconcileProviderVoiceModels(provider);
380
388
  }
381
389
 
382
390
  if (data.apiKey) {