@johpaz/hive-agents 1.1.5 → 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.
- package/README.md +4 -10
- package/dist/hive.js +218257 -148718
- package/dist/tool-worker.js +68422 -1622
- package/dist/ui/assets/{A2UIPage-Dr3p75oE.js → A2UIPage-v-VggXW3.js} +4 -4
- package/dist/ui/assets/{AgentCreateForm-DqYhH_gm.js → AgentCreateForm-Dr1l4Cvg.js} +1 -1
- package/dist/ui/assets/AgentDetailPage-Dsh_grrr.js +1 -0
- package/dist/ui/assets/{AgentNewPage-BRpFxJIT.js → AgentNewPage-D7557C0J.js} +1 -1
- package/dist/ui/assets/AgentsPage-C_Z56LL1.js +10 -0
- package/dist/ui/assets/{ApiClientPage-R9UDWfR2.js → ApiClientPage-uuBnrh0y.js} +1 -1
- package/dist/ui/assets/ChannelsPage-BI4mAgRU.js +8 -0
- package/dist/ui/assets/DashboardPage-BjAxvzYP.js +6 -0
- package/dist/ui/assets/LoginPage-D7IZKON0.js +1 -0
- package/dist/ui/assets/{LogsPage-DICMU_7m.js → LogsPage-mcqOYvGw.js} +1 -1
- package/dist/ui/assets/MeetingPage-qPJ1z5HA.js +1 -0
- package/dist/ui/assets/ModelSelector-njfNhkng.js +1 -0
- package/dist/ui/assets/{NotFound-D4ZlDVg9.js → NotFound-DY8e1RKh.js} +1 -1
- package/dist/ui/assets/{Office3DPage-31AMJ-LN.css → Office3DPage-C3SIzd2H.css} +1 -1
- package/dist/ui/assets/Office3DPage-Du42LRwi.js +319 -0
- package/dist/ui/assets/ProvidersPage-GDCJs8Zb.js +1 -0
- package/dist/ui/assets/{RecoverPage-Blms3NBa.js → RecoverPage-B6qvBBIl.js} +1 -1
- package/dist/ui/assets/SettingsPage-Br4PfWuc.js +9 -0
- package/dist/ui/assets/{SetupPage-CAjLseE_.js → SetupPage-OaouFLGD.js} +1 -1
- package/dist/ui/assets/{Vignette-DrI2yK2m.js → Vignette-GSZ-owcN.js} +17 -17
- package/dist/ui/assets/VoicePage-DRQZBl3j.js +307 -0
- package/dist/ui/assets/WebChatPage-Cypq-SYi.js +29 -0
- package/dist/ui/assets/{agentCapabilities-CDSfJWhw.js → agentCapabilities-Bf71Gir4.js} +1 -1
- package/dist/ui/assets/{alert-CjiX20jI.js → alert-Dn604uVs.js} +1 -1
- package/dist/ui/assets/{badge-B5AKge1b.js → badge-C6H33ePv.js} +1 -1
- package/dist/ui/assets/{card-mTJ4oZbL.js → card-D0qneq1i.js} +1 -1
- package/dist/ui/assets/{conversationsStore-DhM07qYi.js → conversationsStore-D6XgjMr1.js} +1 -1
- package/dist/ui/assets/{dialog-BP3GTCPn.js → dialog-DO1fQCF7.js} +1 -1
- package/dist/ui/assets/dist-js-C2MfmbEW.js +1 -0
- package/dist/ui/assets/{dist-js-CkNhvsFc.js → dist-js-Djxbxbst.js} +1 -1
- package/dist/ui/assets/google-external-e9lvWjy4.js +1 -0
- package/dist/ui/assets/index-BKNFH2al.css +2 -0
- package/dist/ui/assets/index-U0e4e5mL.js +156 -0
- package/dist/ui/assets/{key-DPkOY-J0.js → key-round-Ca0Ns34v.js} +1 -1
- package/dist/ui/assets/{label-D_fvqJyD.js → label-CvAtVE-v.js} +1 -1
- package/dist/ui/assets/{scroll-area-CbH8FOo8.js → scroll-area-CYMu7sU0.js} +1 -1
- package/dist/ui/assets/select-BjBXxyxL.js +1 -0
- package/dist/ui/assets/{slider-DXS4h1LB.js → slider-DR31eN3r.js} +1 -1
- package/dist/ui/assets/{switch-ndx8VCpm.js → switch-B5dAwb54.js} +1 -1
- package/dist/ui/assets/{tabs-epu-3Tl4.js → tabs-Ct92cLXr.js} +1 -1
- package/dist/ui/assets/{earth-BJRGJbVn.js → terminal-CpBDERBE.js} +1 -1
- package/dist/ui/assets/{textarea-BgZJFZTX.js → textarea-xtFAVuPf.js} +1 -1
- package/dist/ui/assets/{useAudioDevices-zj0fuGwZ.js → useAudioDevices-wZArmV3m.js} +1 -1
- package/dist/ui/assets/{useHiveAgentsModelLoad-Cd9p-bjs.js → useHiveAgentsModelLoad-CqJkzTOT.js} +1 -1
- package/dist/ui/assets/useOfficeModel-DZvwZRCw.js +1 -0
- package/dist/ui/assets/{useProviders-Dj1k5PCk.js → useProviders-CeSzDnx-.js} +1 -1
- package/dist/ui/assets/vendor-router-DxU0Uf4R.js +3 -0
- package/dist/ui/index.html +5 -5
- package/package.json +1 -3
- package/packages/cli/src/commands/onboard.ts +3 -2
- package/packages/core/src/agent/agent-catalog.ts +98 -1
- package/packages/core/src/agent/agent-loop.ts +5 -44
- package/packages/core/src/agent/context-compiler.ts +6 -94
- package/packages/core/src/agent/conversation-store.ts +23 -1
- package/packages/core/src/agent/llm-providers/openai-compat-base.ts +1 -1
- package/packages/core/src/agent/minimal-loadout.ts +1 -0
- package/packages/core/src/agent/prompt-builder.ts +17 -1
- package/packages/core/src/agent/tool-selector.ts +12 -0
- package/packages/core/src/artifacts/store.ts +73 -9
- package/packages/core/src/canvas/emitter.ts +0 -19
- package/packages/core/src/channels/base.ts +26 -0
- package/packages/core/src/channels/discord.ts +18 -2
- package/packages/core/src/channels/slack.ts +37 -7
- package/packages/core/src/channels/telegram.ts +39 -11
- package/packages/core/src/channels/whatsapp.ts +16 -1
- package/packages/core/src/gateway/channel-notify.ts +42 -0
- package/packages/core/src/gateway/google-host.ts +228 -0
- package/packages/core/src/gateway/initializer.ts +8 -0
- package/packages/core/src/gateway/routes/agents.ts +14 -0
- package/packages/core/src/gateway/routes/artifacts.ts +4 -0
- package/packages/core/src/gateway/routes/auth.ts +25 -3
- package/packages/core/src/gateway/routes/chat.ts +14 -1
- package/packages/core/src/gateway/routes/google.ts +252 -0
- package/packages/core/src/gateway/routes/meeting.ts +11 -3
- package/packages/core/src/gateway/routes/models.ts +27 -11
- package/packages/core/src/gateway/routes/multimodal.ts +38 -0
- package/packages/core/src/gateway/routes/providers.ts +19 -18
- package/packages/core/src/gateway/routes/system.ts +1 -3
- package/packages/core/src/gateway/routes/tts-local.ts +20 -374
- package/packages/core/src/gateway/routes/voice.ts +29 -35
- package/packages/core/src/gateway/server.ts +97 -48
- package/packages/core/src/gateway/tts/README.md +7 -86
- package/packages/core/src/gateway/tts/build.py +105 -0
- package/packages/core/src/gateway/tts/kitten.ts +282 -0
- package/packages/core/src/gateway/tts/python.d.ts +4 -0
- package/packages/core/src/gateway/tts/src/detect.ts +33 -39
- package/packages/core/src/gateway/tts/worker.py +80 -0
- package/packages/core/src/gateway/webchat-turn.ts +15 -13
- package/packages/core/src/google/client.ts +123 -0
- package/packages/core/src/google/config.ts +60 -0
- package/packages/core/src/google/google.test.ts +287 -0
- package/packages/core/src/google/index.ts +5 -0
- package/packages/core/src/google/oauth.ts +144 -0
- package/packages/core/src/google/scopes.ts +41 -0
- package/packages/core/src/google/token-store.ts +33 -0
- package/packages/core/src/multimodal/attachment-ingest.ts +190 -0
- package/packages/core/src/multimodal/image-generation.ts +244 -0
- package/packages/core/src/multimodal/vision-analyzer.ts +94 -0
- package/packages/core/src/multimodal/vision-service.ts +25 -0
- package/packages/core/src/storage/collections.ts +8 -8
- package/packages/core/src/storage/google-capabilities.ts +91 -0
- package/packages/core/src/storage/model-activation.ts +18 -0
- package/packages/core/src/storage/model-sync.ts +66 -14
- package/packages/core/src/storage/onboarding.ts +10 -2
- package/packages/core/src/storage/seed.ts +107 -24
- package/packages/core/src/storage/usage.ts +0 -52
- package/packages/core/src/tool-runtime/index.ts +2 -0
- package/packages/core/src/tools/agents/get-available-models.ts +1 -3
- package/packages/core/src/tools/core/index.ts +80 -2
- package/packages/core/src/tools/google/calendar.ts +204 -0
- package/packages/core/src/tools/google/drive.ts +160 -0
- package/packages/core/src/tools/google/gmail.ts +579 -0
- package/packages/core/src/tools/google/index.ts +18 -0
- package/packages/core/src/tools/google/shared.ts +80 -0
- package/packages/core/src/tools/image/image-generate.ts +90 -0
- package/packages/core/src/tools/image/index.ts +13 -0
- package/packages/core/src/tools/image/office-leer-imagenes.ts +198 -0
- package/packages/core/src/tools/index.ts +27 -0
- package/packages/core/src/tools/office/index.ts +9 -0
- package/packages/core/src/tools/office/office-editar-docx.ts +184 -0
- package/packages/core/src/tools/office/office-editar-pptx.ts +126 -0
- package/packages/core/src/tools/office/office-editar-xlsx.ts +122 -0
- package/packages/core/src/tools/office/office-escribir-docx.ts +3 -2
- package/packages/core/src/tools/office/office-escribir-pdf.ts +3 -2
- package/packages/core/src/tools/office/office-escribir-pptx.ts +3 -2
- package/packages/core/src/tools/office/office-escribir-xlsx.ts +3 -2
- package/packages/core/src/tools/office/office-images.ts +137 -0
- package/packages/core/src/tools/office/office-leer-docx.ts +16 -3
- package/packages/core/src/tools/office/office-leer-pdf.ts +41 -57
- package/packages/core/src/tools/office/office-leer-pptx.ts +54 -88
- package/packages/core/src/tools/office/office-leer-xlsx.ts +6 -2
- package/packages/core/src/tools/office/office-pdf-images.ts +225 -0
- package/packages/core/src/tools/office/pdf-text.ts +186 -0
- package/packages/core/src/tools/office/pptx-slides.ts +83 -0
- package/packages/core/src/tools/office/resolve-input.ts +49 -0
- package/packages/core/src/tools/web/browser-screenshot.ts +7 -0
- package/packages/core/src/voice/index.ts +123 -155
- package/packages/core/src/voice/local-model.ts +8 -0
- package/packages/core/src/voice/stt-models.ts +39 -0
- package/packages/skills/src/bundled/google/google_calendar/SKILL.md +51 -0
- package/packages/skills/src/bundled/google/google_drive/SKILL.md +50 -0
- package/packages/skills/src/bundled/google/google_gmail/SKILL.md +61 -0
- package/packages/skills/src/bundled-data.generated.ts +45 -0
- package/dist/ui/assets/AgentDetailPage-BVtE88U5.js +0 -1
- package/dist/ui/assets/AgentsPage-BOIJ55cj.js +0 -10
- package/dist/ui/assets/ChannelsPage-C5V2BmjL.js +0 -8
- package/dist/ui/assets/DashboardPage-B18gMzNj.js +0 -6
- package/dist/ui/assets/LoginPage-nrsYF9AY.js +0 -1
- package/dist/ui/assets/MeetingPage-xslJGfIz.js +0 -1
- package/dist/ui/assets/ModelSelector-BX4IvuYY.js +0 -1
- package/dist/ui/assets/Office3DPage-a6cuzt5X.js +0 -727
- package/dist/ui/assets/ProvidersPage-C8-xGoeh.js +0 -1
- package/dist/ui/assets/SettingsPage-BBeeq_QS.js +0 -9
- package/dist/ui/assets/VoicePage-BeSSYstD.js +0 -307
- package/dist/ui/assets/WebChatPage-Bat7uUfd.js +0 -29
- package/dist/ui/assets/dist-js-jWCEHSkB.js +0 -1
- package/dist/ui/assets/index-BG3nUPKq.js +0 -156
- package/dist/ui/assets/index-DmFPF9xQ.css +0 -2
- package/dist/ui/assets/lock-open-v0EphssG.js +0 -1
- package/dist/ui/assets/select-v_3QBYrD.js +0 -1
- package/dist/ui/assets/terminal-BEcTK780.js +0 -1
- package/dist/ui/assets/useOfficeModel-BaDn7U-X.js +0 -1
- package/dist/ui/assets/vendor-router-DSMCk-Ka.js +0 -3
- package/packages/core/src/agent/jev-decisions.ts +0 -242
- package/packages/core/src/agent/jev-planner.ts +0 -293
- package/packages/core/src/gateway/tts/package.json +0 -25
- package/packages/core/src/gateway/tts/src/client.ts +0 -59
- package/packages/core/src/gateway/tts/src/index.ts +0 -15
- package/packages/core/src/gateway/tts/src/install.ts +0 -137
- package/packages/core/src/gateway/tts/src/models.ts +0 -50
- package/packages/core/src/gateway/tts/src/server.ts +0 -253
- /package/dist/ui/assets/{core-p4c5dns5.js → core-npANj14X.js} +0 -0
- /package/dist/ui/assets/{download-BQXrpH0m.js → download-D0aDV8Y_.js} +0 -0
- /package/dist/ui/assets/{ellipsis-vertical-D7uFJLGh.js → ellipsis-vertical-BOW_iEOO.js} +0 -0
- /package/dist/ui/assets/{external-link-6oTH9pUM.js → external-link-DNJH7epD.js} +0 -0
- /package/dist/ui/assets/{eye-CxvxtQT5.js → eye-BVfTWOME.js} +0 -0
- /package/dist/ui/assets/{file-text-D5ZJEx3E.js → file-text-ByqNMpXm.js} +0 -0
- /package/dist/ui/assets/{gateway-url-BALS_wVh.js → gateway-url-BzQV75Ig.js} +0 -0
- /package/dist/ui/assets/{gauge-CEu7PhTW.js → gauge-CB4np0Vz.js} +0 -0
- /package/dist/ui/assets/{history-DLK5rTlP.js → history-CbhJX41s.js} +0 -0
- /package/dist/ui/assets/{info-8ReWzubE.js → info-BCD3-QX9.js} +0 -0
- /package/dist/ui/assets/{lock-3IApZyVy.js → lock-DpBean4K.js} +0 -0
- /package/dist/ui/assets/{mail-vwCEHyhQ.js → mail-Biwn8WrV.js} +0 -0
- /package/dist/ui/assets/{mic-CpDU_2as.js → mic-Rq4BxU1R.js} +0 -0
- /package/dist/ui/assets/{pause-BAMsNQkh.js → pause-87NGXbsz.js} +0 -0
- /package/dist/ui/assets/{pencil-CKritjT_.js → pencil-BG8EFaS3.js} +0 -0
- /package/dist/ui/assets/{play-Cwpe4tp6.js → play-D3De6YsQ.js} +0 -0
- /package/dist/ui/assets/{plus-RD44ce15.js → plus-Bp8-V68t.js} +0 -0
- /package/dist/ui/assets/{radio-lFPMHi6-.js → radio-m7rzuDKK.js} +0 -0
- /package/dist/ui/assets/{refresh-cw-DtJMHRHO.js → refresh-cw-D6F1zoC6.js} +0 -0
- /package/dist/ui/assets/{rotate-ccw-b3E_4PoX.js → rotate-ccw-DUlEC1_D.js} +0 -0
- /package/dist/ui/assets/{search-z2oZt00P.js → search-CfNwwpMW.js} +0 -0
- /package/dist/ui/assets/{send-CpoY_2F-.js → send-CI868CBV.js} +0 -0
- /package/dist/ui/assets/{settings-qV3kVkeG.js → settings-AEM2uWiD.js} +0 -0
- /package/dist/ui/assets/{shield-CIarwBvx.js → shield-DvVIcbzd.js} +0 -0
- /package/dist/ui/assets/{sparkles-DVvY6jDT.js → sparkles-DRe4GbSH.js} +0 -0
- /package/dist/ui/assets/{square-D5zdNkAY.js → square-DTWkjTT3.js} +0 -0
- /package/dist/ui/assets/{trash-2-D6oziYAK.js → trash-2-BZsMCfso.js} +0 -0
- /package/dist/ui/assets/{utils-DEmd_M8c.js → utils-lc8H6VGT.js} +0 -0
- /package/dist/ui/assets/{volume-2-EaA0JRvD.js → volume-2-CBMYsuF3.js} +0 -0
- /package/dist/ui/assets/{volume-x-CROXNMGT.js → volume-x-vNFf2e4-.js} +0 -0
- /package/dist/ui/assets/{wifi-BUJuOcgP.js → wifi-DNv53AfN.js} +0 -0
- /package/dist/ui/assets/{zap-DSoX9NDk.js → zap-Yed86Sh8.js} +0 -0
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ingesta única de documentos adjuntos (pdf, docx, xlsx, pptx, csv, txt…).
|
|
3
|
+
*
|
|
4
|
+
* Antes cada canal mandaba el documento a un modelo de visión como si fuera una
|
|
5
|
+
* imagen (falla con Word/Excel y recorta los PDF). Ahora el archivo se guarda en
|
|
6
|
+
* el artifact store, se extrae una vista previa corta de forma nativa y el
|
|
7
|
+
* agente recibe un manifiesto; el contenido completo lo lee bajo demanda con
|
|
8
|
+
* las tools office_leer_* / fs_read usando la ruta que figura en el manifiesto.
|
|
9
|
+
*/
|
|
10
|
+
import { extname } from "node:path"
|
|
11
|
+
import { createArtifact } from "../artifacts/store"
|
|
12
|
+
import { cargarXlsx } from "../tools/office/xlsx-loader"
|
|
13
|
+
import { extraerTextoPdf } from "../tools/office/pdf-text"
|
|
14
|
+
import { listarSlides, textoDeXml } from "../tools/office/pptx-slides"
|
|
15
|
+
import { listarImagenes } from "../tools/office/office-images"
|
|
16
|
+
import { logger } from "../utils/logger"
|
|
17
|
+
|
|
18
|
+
const log = logger.child("attachment-ingest")
|
|
19
|
+
|
|
20
|
+
/** Tope duro de tamaño de un adjunto (los canales ya limitan antes, esto es la red de seguridad). */
|
|
21
|
+
export const MAX_ATTACHMENT_BYTES = 50 * 1024 * 1024
|
|
22
|
+
const PREVIEW_CHARS = 1500
|
|
23
|
+
|
|
24
|
+
export type AttachmentKind = "pdf" | "docx" | "xlsx" | "pptx" | "text" | "other"
|
|
25
|
+
|
|
26
|
+
export interface IngestedAttachment {
|
|
27
|
+
fileName: string
|
|
28
|
+
mimeType: string
|
|
29
|
+
size: number
|
|
30
|
+
kind: AttachmentKind
|
|
31
|
+
artifactId: string
|
|
32
|
+
/** Ruta absoluta en disco, con la extensión original. */
|
|
33
|
+
path: string
|
|
34
|
+
/** Primeros caracteres del contenido; vacío si no hay texto extraíble. */
|
|
35
|
+
preview: string
|
|
36
|
+
/** Páginas del PDF (solo PDF). */
|
|
37
|
+
pages?: number
|
|
38
|
+
/** Imágenes útiles dentro de un Word o PowerPoint (el texto de la vista previa no las incluye). */
|
|
39
|
+
images?: number
|
|
40
|
+
/** true si es un PDF sin capa de texto (escaneado): no se puede leer sin OCR. */
|
|
41
|
+
scanned: boolean
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const EXT_KIND: Record<string, AttachmentKind> = {
|
|
45
|
+
".pdf": "pdf", ".docx": "docx", ".xlsx": "xlsx", ".xlsm": "xlsx", ".pptx": "pptx",
|
|
46
|
+
".txt": "text", ".md": "text", ".csv": "text", ".tsv": "text", ".json": "text",
|
|
47
|
+
".xml": "text", ".yaml": "text", ".yml": "text", ".log": "text", ".html": "text",
|
|
48
|
+
}
|
|
49
|
+
const EXT_MIME: Record<string, string> = {
|
|
50
|
+
".pdf": "application/pdf",
|
|
51
|
+
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
52
|
+
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
53
|
+
".xlsm": "application/vnd.ms-excel.sheet.macroEnabled.12",
|
|
54
|
+
".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
|
55
|
+
".csv": "text/csv", ".md": "text/markdown", ".txt": "text/plain", ".json": "application/json",
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** La extensión manda sobre el mime: WhatsApp, por ejemplo, declara pdf por defecto. */
|
|
59
|
+
export function classifyAttachment(fileName: string, mimeType: string): { kind: AttachmentKind; mimeType: string } {
|
|
60
|
+
const ext = extname(fileName).toLowerCase()
|
|
61
|
+
if (EXT_KIND[ext]) return { kind: EXT_KIND[ext], mimeType: EXT_MIME[ext] ?? mimeType }
|
|
62
|
+
if (/pdf/i.test(mimeType)) return { kind: "pdf", mimeType }
|
|
63
|
+
if (/wordprocessingml/i.test(mimeType)) return { kind: "docx", mimeType }
|
|
64
|
+
if (/spreadsheetml|ms-excel/i.test(mimeType)) return { kind: "xlsx", mimeType }
|
|
65
|
+
if (/presentationml/i.test(mimeType)) return { kind: "pptx", mimeType }
|
|
66
|
+
if (/^text\//i.test(mimeType)) return { kind: "text", mimeType }
|
|
67
|
+
return { kind: "other", mimeType }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function clip(text: string): string {
|
|
71
|
+
const t = text.replace(/\r/g, "").replace(/\n{3,}/g, "\n\n").trim()
|
|
72
|
+
return t.length > PREVIEW_CHARS ? `${t.slice(0, PREVIEW_CHARS)}…` : t
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function extractPreview(kind: AttachmentKind, bytes: Buffer, info: { pages?: number; sinTexto?: boolean; images?: number }): Promise<string> {
|
|
76
|
+
try {
|
|
77
|
+
switch (kind) {
|
|
78
|
+
case "text":
|
|
79
|
+
return clip(bytes.toString("utf8"))
|
|
80
|
+
case "docx": {
|
|
81
|
+
const mammoth = await import("mammoth")
|
|
82
|
+
info.images = await contarImagenes(bytes, "docx")
|
|
83
|
+
return clip((await mammoth.extractRawText({ buffer: bytes })).value)
|
|
84
|
+
}
|
|
85
|
+
case "xlsx": {
|
|
86
|
+
const XLSX = await cargarXlsx()
|
|
87
|
+
const wb = XLSX.read(bytes, { type: "buffer" })
|
|
88
|
+
const parts = wb.SheetNames.slice(0, 3).map((name) => {
|
|
89
|
+
const csv = XLSX.utils.sheet_to_csv(wb.Sheets[name]).split("\n").slice(0, 15).join("\n")
|
|
90
|
+
return `# Hoja "${name}"\n${csv}`
|
|
91
|
+
})
|
|
92
|
+
const extra = wb.SheetNames.length > 3 ? `\n(+${wb.SheetNames.length - 3} hojas más)` : ""
|
|
93
|
+
return clip(parts.join("\n\n") + extra)
|
|
94
|
+
}
|
|
95
|
+
case "pdf": {
|
|
96
|
+
const r = await extraerTextoPdf(new Uint8Array(bytes), { hasta: 3, maxCaracteres: PREVIEW_CHARS * 2 })
|
|
97
|
+
info.pages = r.totalPaginas
|
|
98
|
+
info.sinTexto = r.sinTexto
|
|
99
|
+
return r.sinTexto ? "" : clip(r.texto.replace(/--- Página \d+ ---\n?/g, ""))
|
|
100
|
+
}
|
|
101
|
+
case "pptx": {
|
|
102
|
+
const JSZip = (await import("jszip")).default
|
|
103
|
+
const zip = await JSZip.loadAsync(bytes)
|
|
104
|
+
const slides = await listarSlides(zip)
|
|
105
|
+
info.pages = slides.length
|
|
106
|
+
info.images = (await listarImagenes(zip, "pptx")).imagenes.length
|
|
107
|
+
const partes: string[] = []
|
|
108
|
+
for (const slide of slides.slice(0, 5)) {
|
|
109
|
+
const t = textoDeXml(await zip.file(slide.archivo)!.async("string"))
|
|
110
|
+
partes.push(`# Diapositiva ${slide.numero}\n${t}`)
|
|
111
|
+
}
|
|
112
|
+
return clip(partes.join("\n\n"))
|
|
113
|
+
}
|
|
114
|
+
default:
|
|
115
|
+
return ""
|
|
116
|
+
}
|
|
117
|
+
} catch (err) {
|
|
118
|
+
log.warn(`No se pudo extraer vista previa (${kind}): ${(err as Error).message}`)
|
|
119
|
+
return ""
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async function contarImagenes(bytes: Buffer, formato: "docx" | "pptx"): Promise<number> {
|
|
124
|
+
try {
|
|
125
|
+
const JSZip = (await import("jszip")).default
|
|
126
|
+
return (await listarImagenes(await JSZip.loadAsync(bytes), formato)).imagenes.length
|
|
127
|
+
} catch { return 0 }
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async function toBytes(input: { buffer?: Buffer; base64?: string; url?: string }): Promise<Buffer> {
|
|
131
|
+
if (input.buffer) return Buffer.from(input.buffer)
|
|
132
|
+
if (input.base64) return Buffer.from(input.base64.replace(/^data:[^,]+,/, ""), "base64")
|
|
133
|
+
if (input.url) {
|
|
134
|
+
const res = await fetch(input.url, { signal: AbortSignal.timeout(60_000) })
|
|
135
|
+
if (!res.ok) throw new Error(`no se pudo descargar el archivo (HTTP ${res.status})`)
|
|
136
|
+
return Buffer.from(await res.arrayBuffer())
|
|
137
|
+
}
|
|
138
|
+
throw new Error("el adjunto no trae contenido (ni buffer, ni base64, ni url)")
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export async function ingestDocument(input: {
|
|
142
|
+
buffer?: Buffer
|
|
143
|
+
base64?: string
|
|
144
|
+
url?: string
|
|
145
|
+
mimeType?: string
|
|
146
|
+
fileName?: string
|
|
147
|
+
userId: string
|
|
148
|
+
}): Promise<IngestedAttachment> {
|
|
149
|
+
const bytes = await toBytes(input)
|
|
150
|
+
if (bytes.byteLength === 0) throw new Error("el archivo está vacío")
|
|
151
|
+
if (bytes.byteLength > MAX_ATTACHMENT_BYTES) {
|
|
152
|
+
throw new Error(`el archivo pesa ${(bytes.byteLength / 1048576).toFixed(1)} MB y el máximo es ${MAX_ATTACHMENT_BYTES / 1048576} MB`)
|
|
153
|
+
}
|
|
154
|
+
const fileName = (input.fileName || "adjunto").replace(/[\\/\0]/g, "_")
|
|
155
|
+
const { kind, mimeType } = classifyAttachment(fileName, input.mimeType || "application/octet-stream")
|
|
156
|
+
const artifact = await createArtifact({
|
|
157
|
+
bytes, mimeType, kind: "attachment", userId: input.userId, extension: extname(fileName),
|
|
158
|
+
})
|
|
159
|
+
const info: { pages?: number; sinTexto?: boolean; images?: number } = {}
|
|
160
|
+
const preview = await extractPreview(kind, bytes, info)
|
|
161
|
+
return {
|
|
162
|
+
fileName, mimeType: artifact.mime_type, size: bytes.byteLength, kind,
|
|
163
|
+
artifactId: artifact.id, path: artifact.path, preview,
|
|
164
|
+
pages: info.pages, images: info.images, scanned: !!info.sinTexto,
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const READER: Record<AttachmentKind, string> = {
|
|
169
|
+
pdf: "office_leer_pdf", docx: "office_leer_docx", xlsx: "office_leer_xlsx",
|
|
170
|
+
pptx: "office_leer_pptx", text: "fs_read", other: "",
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Texto que se antepone al mensaje del usuario para que el agente sepa qué recibió y cómo leerlo. */
|
|
174
|
+
export function formatAttachmentManifest(a: IngestedAttachment): string {
|
|
175
|
+
const kb = a.size < 1048576 ? `${Math.max(1, Math.round(a.size / 1024))} KB` : `${(a.size / 1048576).toFixed(1)} MB`
|
|
176
|
+
const reader = READER[a.kind]
|
|
177
|
+
const lines = [
|
|
178
|
+
`[Archivo adjunto: ${a.fileName} · ${a.mimeType} · ${kb}${a.pages ? ` · ${a.pages} ${a.kind === "pptx" ? "diapositivas" : "páginas"}` : ""}]`,
|
|
179
|
+
`Ruta: ${a.path}`,
|
|
180
|
+
`artifact_id: ${a.artifactId}`,
|
|
181
|
+
reader ? `Para leerlo completo usa la tool ${reader} con esa ruta.` : "Formato sin lector nativo.",
|
|
182
|
+
]
|
|
183
|
+
if (a.preview) lines.push(`Vista previa:\n${a.preview}`)
|
|
184
|
+
else if (a.scanned) lines.push("Este PDF no tiene texto extraíble (parece escaneado: solo imágenes). Para leerlo usa la tool office_leer_imagenes con esa ruta: transcribe cada página con el modelo de visión. Si responde que no hay modelo configurado, díselo al usuario o pídele el documento en formato editable.")
|
|
185
|
+
else lines.push("No se pudo extraer texto.")
|
|
186
|
+
if (a.images) {
|
|
187
|
+
lines.push(`Contiene ${a.images} ${a.images === 1 ? "imagen" : "imágenes"} (capturas, gráficos, diagramas) que el texto NO incluye. Para verlas usa la tool office_leer_imagenes con esa ruta.`)
|
|
188
|
+
}
|
|
189
|
+
return lines.join("\n")
|
|
190
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Modelo analizador de imágenes del sistema.
|
|
3
|
+
*
|
|
4
|
+
* Es independiente del modelo de chat: cuando el modelo del agente no ve
|
|
5
|
+
* imágenes (o hay que leer un adjunto), se le pide a ESTE modelo que describa y
|
|
6
|
+
* transcriba la imagen, y el agente recibe el texto. Un solo modelo para todos
|
|
7
|
+
* los canales, elegido en la pestaña Imagen de Providers.
|
|
8
|
+
*/
|
|
9
|
+
import { col } from "../storage/hive"
|
|
10
|
+
import type { ModelDoc } from "../storage/collections"
|
|
11
|
+
import { logger } from "../utils/logger"
|
|
12
|
+
import type { ImageInput } from "./types"
|
|
13
|
+
|
|
14
|
+
const log = logger.child("vision-analyzer")
|
|
15
|
+
|
|
16
|
+
const SETTINGS_COLLECTION = "system_settings"
|
|
17
|
+
const SETTING_ID = "vision_analyzer"
|
|
18
|
+
const IMAGE_MIME = /^image\/(png|jpe?g|webp|gif)$/i
|
|
19
|
+
|
|
20
|
+
export const ANALYZER_PROMPT =
|
|
21
|
+
"Describe el contenido de esta imagen en detalle. Si hay texto, tablas o números, transcríbelos exactamente. " +
|
|
22
|
+
"Si es un documento, un recibo o una captura de pantalla, resume su estructura y lo importante."
|
|
23
|
+
|
|
24
|
+
function hasVision(model: ModelDoc): boolean {
|
|
25
|
+
try { return (JSON.parse(model.capabilities || "[]") as string[]).includes("vision") } catch { return false }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export async function getVisionAnalyzerModelId(): Promise<string | null> {
|
|
29
|
+
const entry = await (await col<{ model_id: string | null }>(SETTINGS_COLLECTION)).get(SETTING_ID)
|
|
30
|
+
return entry?.doc.model_id || null
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Guarda el modelo analizador (null lo quita). Solo acepta modelos LLM con visión. */
|
|
34
|
+
export async function setVisionAnalyzerModelId(modelId: string | null): Promise<void> {
|
|
35
|
+
if (modelId) {
|
|
36
|
+
const entry = await (await col<ModelDoc>("models")).get(modelId)
|
|
37
|
+
if (!entry) throw new Error(`El modelo ${modelId} no existe`)
|
|
38
|
+
if (entry.doc.model_type !== "llm" || !hasVision(entry.doc)) {
|
|
39
|
+
throw new Error(`El modelo ${entry.doc.name} no tiene capacidad de visión`)
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const settings = await col<{ model_id: string | null }>(SETTINGS_COLLECTION)
|
|
43
|
+
const current = await settings.get(SETTING_ID)
|
|
44
|
+
await settings.put(SETTING_ID, { model_id: modelId }, { expectedVersion: current?.version ?? 0 })
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async function toDataUrl(image: ImageInput): Promise<string | null> {
|
|
48
|
+
const mime = image.mimeType || "image/jpeg"
|
|
49
|
+
if (!IMAGE_MIME.test(mime)) return null // PDF y otros formatos: los atiende el OCR de siempre
|
|
50
|
+
if (image.type === "url") return image.data as string
|
|
51
|
+
const base64 = image.type === "buffer" ? Buffer.from(image.data as Buffer).toString("base64") : (image.data as string)
|
|
52
|
+
return `data:${mime};base64,${base64}`
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Describe la imagen con el modelo analizador. Devuelve null si no hay modelo
|
|
57
|
+
* configurado o la entrada no es una imagen (el llamador usa su respaldo);
|
|
58
|
+
* lanza si el modelo configurado falla, para que el fallo quede en el log.
|
|
59
|
+
*/
|
|
60
|
+
export async function analyzeImage(image: ImageInput): Promise<string | null> {
|
|
61
|
+
const modelId = await getVisionAnalyzerModelId()
|
|
62
|
+
if (!modelId) return null
|
|
63
|
+
const url = await toDataUrl(image)
|
|
64
|
+
if (!url) return null
|
|
65
|
+
|
|
66
|
+
const entry = await (await col<ModelDoc>("models")).get(modelId)
|
|
67
|
+
if (!entry) throw new Error(`El modelo analizador ${modelId} ya no existe`)
|
|
68
|
+
|
|
69
|
+
const { callLLM, resolveProviderConfig, LLM_ERROR_PREFIX } = await import("../agent/llm-client")
|
|
70
|
+
const cfg = await resolveProviderConfig(entry.doc.provider_id, modelId)
|
|
71
|
+
if (!cfg.apiKey && entry.doc.provider_id !== "ollama") {
|
|
72
|
+
throw new Error(`Falta la API key de ${entry.doc.provider_id} para el modelo analizador`)
|
|
73
|
+
}
|
|
74
|
+
const res = await callLLM({
|
|
75
|
+
...cfg,
|
|
76
|
+
// La clave tal cual: el adaptador del provider ya quita su propio prefijo al armar el request.
|
|
77
|
+
// Quitarlo aquí también lo recortaba dos veces (nvidia/nvidia/x → x) y daba 404.
|
|
78
|
+
model: modelId,
|
|
79
|
+
maxTokens: 2000,
|
|
80
|
+
temperature: 0.1,
|
|
81
|
+
messages: [{
|
|
82
|
+
role: "user",
|
|
83
|
+
content: [
|
|
84
|
+
{ type: "text", text: image.caption ? `${ANALYZER_PROMPT}\nContexto del usuario: ${image.caption}` : ANALYZER_PROMPT },
|
|
85
|
+
{ type: "image_url", image_url: { url } },
|
|
86
|
+
],
|
|
87
|
+
}],
|
|
88
|
+
})
|
|
89
|
+
if (res.stop_reason === "error" || res.content.startsWith(LLM_ERROR_PREFIX)) {
|
|
90
|
+
throw new Error(res.content.replace(LLM_ERROR_PREFIX, "").trim() || "el modelo analizador falló")
|
|
91
|
+
}
|
|
92
|
+
log.info(`Imagen analizada con ${entry.doc.provider_id}/${modelId} (${res.content.length} caracteres)`)
|
|
93
|
+
return res.content
|
|
94
|
+
}
|
|
@@ -63,6 +63,31 @@ class MultimodalService {
|
|
|
63
63
|
}
|
|
64
64
|
|
|
65
65
|
async ocrImage(image: ImageInput, providerId?: string): Promise<string> {
|
|
66
|
+
// Primero el modelo analizador del sistema (elegido en la pestaña Imagen); si no hay
|
|
67
|
+
// uno o no es una imagen, se usa el OCR por provider de siempre.
|
|
68
|
+
let analyzerError: string | null = null
|
|
69
|
+
try {
|
|
70
|
+
const { analyzeImage } = await import("./vision-analyzer")
|
|
71
|
+
const text = await analyzeImage(image)
|
|
72
|
+
if (text !== null) return text
|
|
73
|
+
} catch (err) {
|
|
74
|
+
analyzerError = (err as Error).message
|
|
75
|
+
log.warn(`El modelo analizador falló, pruebo el OCR por provider: ${analyzerError}`)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
try {
|
|
79
|
+
return await this.ocrWithProvider(image, providerId)
|
|
80
|
+
} catch (err) {
|
|
81
|
+
// Si el analizador ya había fallado, el error útil es ese: el del respaldo (casi siempre
|
|
82
|
+
// "falta la clave de OpenAI") solo confunde.
|
|
83
|
+
if (analyzerError) {
|
|
84
|
+
throw new Error(`El modelo analizador falló: ${analyzerError} Además el OCR de respaldo no está disponible (${(err as Error).message}).`)
|
|
85
|
+
}
|
|
86
|
+
throw err
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
private async ocrWithProvider(image: ImageInput, providerId?: string): Promise<string> {
|
|
66
91
|
const resolved = providerId || "openai"
|
|
67
92
|
|
|
68
93
|
if (resolved === "openai") {
|
|
@@ -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" | "
|
|
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
|
-
|
|
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 {
|