@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.
- package/README.md +4 -10
- package/dist/hive.js +5258 -2985
- package/dist/tool-worker.js +197 -75
- package/dist/ui/assets/{A2UIPage-CxE3jH4_.js → A2UIPage-v-VggXW3.js} +4 -4
- package/dist/ui/assets/{AgentCreateForm-SGj5AqAX.js → AgentCreateForm-Dr1l4Cvg.js} +1 -1
- package/dist/ui/assets/AgentDetailPage-Dsh_grrr.js +1 -0
- package/dist/ui/assets/{AgentNewPage-xvAmX6kw.js → AgentNewPage-D7557C0J.js} +1 -1
- package/dist/ui/assets/AgentsPage-C_Z56LL1.js +10 -0
- package/dist/ui/assets/{ApiClientPage-NLw2wHjH.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-G9d2G1nL.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-Dr6qKgV5.js → RecoverPage-B6qvBBIl.js} +1 -1
- package/dist/ui/assets/SettingsPage-Br4PfWuc.js +9 -0
- package/dist/ui/assets/{SetupPage-BoVKIf4r.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-ns_ZfKgg.js → conversationsStore-D6XgjMr1.js} +1 -1
- package/dist/ui/assets/{dialog-C3n2xYF2.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-CsPrtpWY.js → useAudioDevices-wZArmV3m.js} +1 -1
- package/dist/ui/assets/{useHiveAgentsModelLoad-nn4gON9g.js → useHiveAgentsModelLoad-CqJkzTOT.js} +1 -1
- package/dist/ui/assets/useOfficeModel-DZvwZRCw.js +1 -0
- package/dist/ui/assets/{useProviders-9tvEC3hX.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/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/prompt-builder.ts +17 -1
- package/packages/core/src/agent/tool-selector.ts +8 -0
- package/packages/core/src/artifacts/store.ts +66 -8
- package/packages/core/src/canvas/emitter.ts +0 -19
- 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/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 +19 -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 +58 -32
- 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/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 +19 -4
- package/packages/core/src/multimodal/image-generation.ts +244 -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 +81 -18
- package/packages/core/src/storage/usage.ts +0 -52
- package/packages/core/src/tools/agents/get-available-models.ts +1 -3
- package/packages/core/src/tools/core/index.ts +1 -1
- 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/office-images.ts +137 -0
- package/packages/core/src/tools/office/office-leer-docx.ts +10 -1
- package/packages/core/src/tools/office/office-leer-pdf.ts +1 -1
- package/packages/core/src/tools/office/office-leer-pptx.ts +4 -1
- package/packages/core/src/tools/office/office-pdf-images.ts +225 -0
- package/packages/core/src/tools/office/pdf-text.ts +2 -2
- 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-CyYbqzHr.js +0 -1
- package/dist/ui/assets/AgentsPage-CEWNs4Lt.js +0 -10
- package/dist/ui/assets/ChannelsPage-CmeXP-hI.js +0 -8
- package/dist/ui/assets/DashboardPage-C3z4kZXD.js +0 -6
- package/dist/ui/assets/LoginPage-DDisP8hm.js +0 -1
- package/dist/ui/assets/MeetingPage-CKyjxtFr.js +0 -1
- package/dist/ui/assets/ModelSelector-VVwpDrYF.js +0 -1
- package/dist/ui/assets/Office3DPage-CYxB6z2p.js +0 -727
- package/dist/ui/assets/ProvidersPage-CM9-E-Pf.js +0 -1
- package/dist/ui/assets/SettingsPage-BvD-vs5g.js +0 -9
- package/dist/ui/assets/VoicePage-CmudxYny.js +0 -307
- package/dist/ui/assets/WebChatPage-CnoXpEOl.js +0 -29
- package/dist/ui/assets/dist-js-jWCEHSkB.js +0 -1
- package/dist/ui/assets/index-C0W6p0lk.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,80 @@
|
|
|
1
|
+
import type { Tool } from "../types.ts";
|
|
2
|
+
import {
|
|
3
|
+
GoogleNotConfiguredError, GoogleNotConnectedError, GoogleScopeError,
|
|
4
|
+
} from "../../google/config.ts";
|
|
5
|
+
import { GoogleApiError } from "../../google/client.ts";
|
|
6
|
+
import { GoogleOAuthError } from "../../google/oauth.ts";
|
|
7
|
+
|
|
8
|
+
type Params = Record<string, unknown>;
|
|
9
|
+
type Ctx = { userId: string; config: any };
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Envuelve una tool de Google: resuelve el usuario, traduce los errores de
|
|
13
|
+
* conexión a una respuesta que el agente sabe interpretar y nunca deja escapar
|
|
14
|
+
* tokens en el mensaje.
|
|
15
|
+
*/
|
|
16
|
+
export function googleTool(def: Omit<Tool, "execute"> & {
|
|
17
|
+
run: (params: Params, ctx: Ctx) => Promise<object>;
|
|
18
|
+
}): Tool {
|
|
19
|
+
const { run, ...rest } = def;
|
|
20
|
+
return {
|
|
21
|
+
...rest,
|
|
22
|
+
execute: async (params: Params, config?: any) => {
|
|
23
|
+
const userId = config?.configurable?.user_id;
|
|
24
|
+
if (!userId) return { ok: false, error: "No se pudo determinar el usuario de la sesión." };
|
|
25
|
+
try {
|
|
26
|
+
return await run(params ?? {}, { userId, config });
|
|
27
|
+
} catch (err) {
|
|
28
|
+
if (err instanceof GoogleNotConfiguredError) {
|
|
29
|
+
return { ok: false, error: err.message, hint: "El administrador debe configurar las credenciales de Google." };
|
|
30
|
+
}
|
|
31
|
+
if (err instanceof GoogleNotConnectedError || err instanceof GoogleScopeError) {
|
|
32
|
+
return { ok: false, error: err.message, needs_connection: true, hint: "Pídele al usuario que conecte su cuenta de Google en Ajustes → Integraciones." };
|
|
33
|
+
}
|
|
34
|
+
if (err instanceof GoogleApiError) {
|
|
35
|
+
return { ok: false, error: err.message, status: err.status };
|
|
36
|
+
}
|
|
37
|
+
if (err instanceof GoogleOAuthError) {
|
|
38
|
+
return { ok: false, error: err.message };
|
|
39
|
+
}
|
|
40
|
+
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
|
41
|
+
}
|
|
42
|
+
},
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function str(v: unknown): string | undefined {
|
|
47
|
+
return typeof v === "string" && v.trim() ? v.trim() : undefined;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function num(v: unknown, def: number, min: number, max: number): number {
|
|
51
|
+
const n = typeof v === "number" && Number.isFinite(v) ? v : def;
|
|
52
|
+
return Math.min(max, Math.max(min, Math.floor(n)));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Las acciones con efecto externo irreversible (enviar, borrar, modificar) no
|
|
57
|
+
* se ejecutan hasta que el coordinador confirma con el usuario y repite la
|
|
58
|
+
* llamada con `confirmed: true`.
|
|
59
|
+
*/
|
|
60
|
+
export function needsConfirmation(params: Params, preview: Record<string, unknown>) {
|
|
61
|
+
if (params.confirmed === true) return null;
|
|
62
|
+
return {
|
|
63
|
+
ok: false,
|
|
64
|
+
needs_confirmation: true,
|
|
65
|
+
error: "Acción pendiente de confirmación del usuario.",
|
|
66
|
+
preview,
|
|
67
|
+
hint: "Devuelve status=needs_input al agente principal con este preview. Cuando el usuario confirme, repite la llamada con confirmed=true.",
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export const CONFIRMED_PARAM = {
|
|
72
|
+
type: "boolean",
|
|
73
|
+
description: "Debe ser true solo después de que el usuario aprobó explícitamente la acción.",
|
|
74
|
+
} as const;
|
|
75
|
+
|
|
76
|
+
/** Rechaza saltos de línea en valores que irán a una cabecera (inyección de cabeceras). */
|
|
77
|
+
export function headerSafe(value: string, field: string): string {
|
|
78
|
+
if (/[\r\n]/.test(value)) throw new Error(`${field} no puede contener saltos de línea.`);
|
|
79
|
+
return value;
|
|
80
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* image_generate — crea una imagen a partir de una descripción.
|
|
3
|
+
*
|
|
4
|
+
* Usa el modelo elegido en Providers → Imagen. La imagen se guarda como
|
|
5
|
+
* artifact y se devuelve como `artifact_ref`: el agent loop la detecta y la
|
|
6
|
+
* entrega al chat web o al canal (Telegram, etc.) junto con la respuesta, sin
|
|
7
|
+
* pasar los bytes por el contexto del modelo.
|
|
8
|
+
*
|
|
9
|
+
* @category image
|
|
10
|
+
* @seedId image_generate
|
|
11
|
+
* @spanish crear imagen, generar imagen, dibujar, ilustración, logo, foto, póster
|
|
12
|
+
*/
|
|
13
|
+
import type { Tool } from "../types";
|
|
14
|
+
import { getWorkspace } from "../filesystem/workspace-guard";
|
|
15
|
+
import { createArtifact } from "../../artifacts/store";
|
|
16
|
+
import {
|
|
17
|
+
ASPECT_RATIOS, ImageGenerationError, ImageModelNotConfiguredError, generateImage, type AspectRatio,
|
|
18
|
+
} from "../../multimodal/image-generation";
|
|
19
|
+
|
|
20
|
+
export const imageGenerateTool: Tool = {
|
|
21
|
+
name: "image_generate",
|
|
22
|
+
// La generación tarda segundos, pero NVIDIA puede encolar: margen sobre el timeout interno de 120 s.
|
|
23
|
+
timeoutMs: 150_000,
|
|
24
|
+
description:
|
|
25
|
+
"Create a NEW image from a text description (illustration, logo, photo-style picture, poster, concept art). " +
|
|
26
|
+
"The finished image is delivered to the user automatically in the chat or channel — do NOT paste a link or base64. " +
|
|
27
|
+
"Write the prompt in English or Spanish with subject, style, lighting and composition. It cannot edit or modify an existing image. " +
|
|
28
|
+
"Spanish: crear imagen, generar imagen, dibujar, hazme una imagen, ilustración, logo, póster, foto",
|
|
29
|
+
parameters: {
|
|
30
|
+
type: "object",
|
|
31
|
+
properties: {
|
|
32
|
+
prompt: { type: "string", description: "Detailed description of the image to create." },
|
|
33
|
+
aspect_ratio: {
|
|
34
|
+
type: "string",
|
|
35
|
+
enum: [...ASPECT_RATIOS],
|
|
36
|
+
description: "square (default, 1:1), landscape (16:9), portrait (9:16), 4:3 or 3:4.",
|
|
37
|
+
},
|
|
38
|
+
},
|
|
39
|
+
required: ["prompt"],
|
|
40
|
+
},
|
|
41
|
+
execute: async (params, config) => {
|
|
42
|
+
const userId = String(config?.configurable?.user_id ?? "");
|
|
43
|
+
const prompt = typeof params.prompt === "string" ? params.prompt : "";
|
|
44
|
+
const aspect = typeof params.aspect_ratio === "string" && (ASPECT_RATIOS as readonly string[]).includes(params.aspect_ratio)
|
|
45
|
+
? (params.aspect_ratio as AspectRatio)
|
|
46
|
+
: "square";
|
|
47
|
+
try {
|
|
48
|
+
const img = await generateImage({ prompt, aspectRatio: aspect });
|
|
49
|
+
const artifact = await createArtifact({
|
|
50
|
+
bytes: img.bytes,
|
|
51
|
+
mimeType: img.mimeType,
|
|
52
|
+
kind: "generated_image",
|
|
53
|
+
userId,
|
|
54
|
+
runId: config?.configurable?.run_id ?? null,
|
|
55
|
+
taskId: config?.configurable?.task_id ?? null,
|
|
56
|
+
// Es contenido que el usuario pidió y verá en su historial: no caduca como la basura transitoria.
|
|
57
|
+
expiresAt: null,
|
|
58
|
+
// Carpeta visible del usuario (workspace o ~/Hive), no la oculta de la base de datos.
|
|
59
|
+
visible: { workspace: getWorkspace(config), folder: "imagenes", label: prompt },
|
|
60
|
+
});
|
|
61
|
+
return [
|
|
62
|
+
{
|
|
63
|
+
type: "artifact_ref",
|
|
64
|
+
artifact_id: artifact.id,
|
|
65
|
+
mime_type: artifact.mime_type,
|
|
66
|
+
size: artifact.size,
|
|
67
|
+
sha256: artifact.sha256,
|
|
68
|
+
expires_at: artifact.expires_at,
|
|
69
|
+
},
|
|
70
|
+
{
|
|
71
|
+
type: "text",
|
|
72
|
+
text:
|
|
73
|
+
`Imagen creada con ${img.modelId} (${aspect}). Ya se muestra al usuario junto a tu respuesta y quedó guardada en su equipo: ${artifact.path}. ` +
|
|
74
|
+
"Si te preguntan dónde está, dales esa ruta. No incluyas enlaces ni base64. Cierra con una frase breve sobre lo que creaste y ofrece ajustes (otro estilo, formato u otra idea).",
|
|
75
|
+
},
|
|
76
|
+
];
|
|
77
|
+
} catch (err) {
|
|
78
|
+
if (err instanceof ImageModelNotConfiguredError) {
|
|
79
|
+
return {
|
|
80
|
+
ok: false,
|
|
81
|
+
error: err.message,
|
|
82
|
+
needs_configuration: true,
|
|
83
|
+
hint: "Dile al usuario que elija el modelo en Providers → Imagen → «Modelo generador de imágenes».",
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
if (err instanceof ImageGenerationError) return { ok: false, error: err.message, retryable: err.retryable };
|
|
87
|
+
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
|
88
|
+
}
|
|
89
|
+
},
|
|
90
|
+
};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Image tools — generación de imágenes y lectura de las imágenes de un documento, con el modelo elegido en Providers → Imagen.
|
|
3
|
+
*/
|
|
4
|
+
import type { Tool } from "../types";
|
|
5
|
+
import { imageGenerateTool } from "./image-generate";
|
|
6
|
+
import { officeLeerImagenesTool } from "./office-leer-imagenes";
|
|
7
|
+
|
|
8
|
+
export function createTools(): Tool[] {
|
|
9
|
+
return [imageGenerateTool, officeLeerImagenesTool];
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export { imageGenerateTool } from "./image-generate";
|
|
13
|
+
export { officeLeerImagenesTool } from "./office-leer-imagenes";
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* office_leer_imagenes — lee las imágenes DENTRO de un Word, PowerPoint o PDF.
|
|
3
|
+
*
|
|
4
|
+
* `office_leer_docx`, `office_leer_pptx` y `office_leer_pdf` solo devuelven texto:
|
|
5
|
+
* una captura, un gráfico, un diagrama o un escaneo dentro del documento no existe
|
|
6
|
+
* para el agente. Esta tool las extrae del propio archivo (Word y PowerPoint son
|
|
7
|
+
* ZIP; en un PDF se decodifican las imágenes incrustadas, que en un escaneado son
|
|
8
|
+
* la página entera) y las describe/transcribe con el modelo analizador del sistema
|
|
9
|
+
* (Providers → Imagen), que es independiente del modelo de chat.
|
|
10
|
+
*
|
|
11
|
+
* Corre en el hilo principal, no en el worker de office: el analizador lee su
|
|
12
|
+
* modelo de HiveDB y el worker no puede tocarlo.
|
|
13
|
+
*
|
|
14
|
+
* @category image
|
|
15
|
+
* @seedId office_leer_imagenes
|
|
16
|
+
* @spanish leer imágenes de un documento, ocr de pdf escaneado, ocr de word, ocr de powerpoint, capturas dentro de un documento
|
|
17
|
+
*/
|
|
18
|
+
import { createHash } from "node:crypto"
|
|
19
|
+
import * as fs from "node:fs"
|
|
20
|
+
import * as path from "node:path"
|
|
21
|
+
import type { Tool } from "../types"
|
|
22
|
+
import { resolveOfficeInput, ARTIFACT_ID_PARAM } from "../office/resolve-input"
|
|
23
|
+
import { listarImagenes } from "../office/office-images"
|
|
24
|
+
import { abrirPdf } from "../office/office-pdf-images"
|
|
25
|
+
import { multimodalService } from "../../multimodal"
|
|
26
|
+
import { logger } from "../../utils/logger"
|
|
27
|
+
|
|
28
|
+
const log = logger.child("office-leer-imagenes")
|
|
29
|
+
|
|
30
|
+
const POR_DEFECTO = 8
|
|
31
|
+
const MAXIMO = 20
|
|
32
|
+
const EN_PARALELO = 3
|
|
33
|
+
const CACHE_MAX = 300
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Resultados ya obtenidos, por hash de la imagen. Releer el mismo documento (o un
|
|
37
|
+
* logo repetido en varios) no vuelve a pagar una llamada al modelo. Vive en
|
|
38
|
+
* memoria: se pierde al reiniciar el gateway, que es aceptable.
|
|
39
|
+
*/
|
|
40
|
+
const cache = new Map<string, string>()
|
|
41
|
+
function recordar(hash: string, texto: string): void {
|
|
42
|
+
if (cache.size >= CACHE_MAX) cache.delete(cache.keys().next().value as string)
|
|
43
|
+
cache.set(hash, texto)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function mapaConLimite<T, R>(items: T[], limite: number, fn: (item: T) => Promise<R>): Promise<R[]> {
|
|
47
|
+
const salida: R[] = new Array(items.length)
|
|
48
|
+
let siguiente = 0
|
|
49
|
+
await Promise.all(Array.from({ length: Math.min(limite, items.length) }, async () => {
|
|
50
|
+
while (siguiente < items.length) {
|
|
51
|
+
const i = siguiente++
|
|
52
|
+
salida[i] = await fn(items[i])
|
|
53
|
+
}
|
|
54
|
+
}))
|
|
55
|
+
return salida
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
interface RefImagen { numero: number; ubicacion: string; mimeType: string }
|
|
59
|
+
interface Fuente {
|
|
60
|
+
imagenes: Array<RefImagen & Record<string, unknown>>
|
|
61
|
+
omitidas: number
|
|
62
|
+
bytes(ref: RefImagen & Record<string, unknown>): Promise<Buffer>
|
|
63
|
+
cerrar?: () => Promise<void>
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Word y PowerPoint (ZIP) o PDF, detrás de la misma forma: lista de imágenes + cómo obtener los bytes de cada una. */
|
|
67
|
+
async function abrirFuente(ext: string, contenido: Buffer): Promise<Fuente> {
|
|
68
|
+
if (ext === ".pdf") {
|
|
69
|
+
const pdf = await abrirPdf(new Uint8Array(contenido))
|
|
70
|
+
try {
|
|
71
|
+
const { imagenes, omitidas } = await pdf.listar()
|
|
72
|
+
return {
|
|
73
|
+
imagenes: imagenes.map((i) => ({ ...i, mimeType: "image/png" })),
|
|
74
|
+
omitidas,
|
|
75
|
+
bytes: (ref) => pdf.extraer(ref as never),
|
|
76
|
+
cerrar: () => pdf.cerrar(),
|
|
77
|
+
}
|
|
78
|
+
} catch (err) {
|
|
79
|
+
await pdf.cerrar()
|
|
80
|
+
throw err
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
const formato = ext === ".docx" ? "docx" : "pptx"
|
|
84
|
+
const JSZip = (await import("jszip")).default
|
|
85
|
+
const zip = await JSZip.loadAsync(contenido).catch(() => {
|
|
86
|
+
throw new Error(`El archivo no es un .${formato} válido o está dañado.`)
|
|
87
|
+
})
|
|
88
|
+
const { imagenes, omitidas } = await listarImagenes(zip, formato)
|
|
89
|
+
return {
|
|
90
|
+
imagenes: imagenes as never,
|
|
91
|
+
omitidas,
|
|
92
|
+
bytes: async (ref) => Buffer.from(await zip.file((ref as { archivo?: string }).archivo as string)!.async("uint8array")),
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export const officeLeerImagenesTool: Tool = {
|
|
97
|
+
name: "office_leer_imagenes",
|
|
98
|
+
timeoutMs: 180_000,
|
|
99
|
+
description:
|
|
100
|
+
"Read the IMAGES inside a Word (.docx), PowerPoint (.pptx) or PDF file — screenshots, charts, diagrams, photos and SCANNED pages — " +
|
|
101
|
+
"which office_leer_docx / office_leer_pptx / office_leer_pdf cannot see because they only return text. Each image is described and its text " +
|
|
102
|
+
"transcribed with the vision model chosen in Providers → Imagen, and comes with where it was in the document (slide, page, nearby text). " +
|
|
103
|
+
"Use it when the document mentions figures, its text looks incomplete, or a PDF has no extractable text (scanned). In a PDF each page image " +
|
|
104
|
+
"is one model call. Returns up to max_imagenes per call; continue with desde_imagen. Vector drawings inside a PDF are not images and are not covered. " +
|
|
105
|
+
"Spanish: leer imágenes de un documento, ocr de pdf escaneado, ocr de word, ocr de powerpoint, capturas dentro de un documento, gráficos de una presentación",
|
|
106
|
+
parameters: {
|
|
107
|
+
type: "object",
|
|
108
|
+
properties: {
|
|
109
|
+
artifact_id: ARTIFACT_ID_PARAM,
|
|
110
|
+
ruta: { type: "string", description: "Ruta absoluta o relativa al archivo .docx, .pptx o .pdf" },
|
|
111
|
+
desde_imagen: { type: "number", description: "Número de imagen desde el que empezar (default 1), para continuar tras un corte." },
|
|
112
|
+
max_imagenes: { type: "number", description: `Cuántas imágenes analizar en esta llamada (default ${POR_DEFECTO}, máximo ${MAXIMO}). Cada una es una llamada al modelo.` },
|
|
113
|
+
},
|
|
114
|
+
required: [],
|
|
115
|
+
},
|
|
116
|
+
execute: async (params: Record<string, unknown>) => {
|
|
117
|
+
const entrada = await resolveOfficeInput(params)
|
|
118
|
+
if ("error" in entrada) return { ok: false, error: entrada.error }
|
|
119
|
+
const rutaAbsoluta = path.resolve(entrada.ruta)
|
|
120
|
+
if (!fs.existsSync(rutaAbsoluta)) return { ok: false, error: `Archivo no encontrado: ${rutaAbsoluta}` }
|
|
121
|
+
|
|
122
|
+
const ext = path.extname(rutaAbsoluta).toLowerCase()
|
|
123
|
+
if (ext !== ".docx" && ext !== ".pptx" && ext !== ".pdf") {
|
|
124
|
+
return { ok: false, error: `Solo se admiten .docx, .pptx y .pdf (recibí ${ext || "un archivo sin extensión"}). Para una imagen suelta no hace falta esta herramienta.` }
|
|
125
|
+
}
|
|
126
|
+
const desde = Math.max(1, Math.floor(Number(params.desde_imagen) || 1))
|
|
127
|
+
const cuantas = Math.min(Math.max(Math.floor(Number(params.max_imagenes) || POR_DEFECTO), 1), MAXIMO)
|
|
128
|
+
let cerrar: (() => Promise<void>) | undefined
|
|
129
|
+
|
|
130
|
+
try {
|
|
131
|
+
const fuente = await abrirFuente(ext, fs.readFileSync(rutaAbsoluta))
|
|
132
|
+
cerrar = fuente.cerrar
|
|
133
|
+
const { imagenes, omitidas } = fuente
|
|
134
|
+
if (imagenes.length === 0) {
|
|
135
|
+
return {
|
|
136
|
+
ok: true, ruta: rutaAbsoluta, totalImagenes: 0, imagenes: [],
|
|
137
|
+
aviso: omitidas
|
|
138
|
+
? `El documento no tiene imágenes que valga la pena analizar (${omitidas} descartadas por ser íconos muy pequeños o de un formato que el modelo no lee, como EMF o SVG).`
|
|
139
|
+
: "El documento no contiene imágenes.",
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const lote = imagenes.filter((i) => i.numero >= desde).slice(0, cuantas)
|
|
144
|
+
if (lote.length === 0) {
|
|
145
|
+
return { ok: false, error: `Hay ${imagenes.length} imágenes y pediste desde la ${desde}. Usa un número entre 1 y ${imagenes.length}.` }
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const resultados = await mapaConLimite(lote, EN_PARALELO, async (ref) => {
|
|
149
|
+
let bytes: Buffer
|
|
150
|
+
try { bytes = await fuente.bytes(ref) } catch (err) { return { ref, error: (err as Error).message } }
|
|
151
|
+
const hash = createHash("sha256").update(bytes).digest("hex")
|
|
152
|
+
const previo = cache.get(hash)
|
|
153
|
+
if (previo !== undefined) return { ref, texto: previo }
|
|
154
|
+
try {
|
|
155
|
+
const texto = (await multimodalService.ocrImage({
|
|
156
|
+
type: "buffer", data: bytes, mimeType: ref.mimeType, caption: `Estaba en el documento: ${ref.ubicacion}.`,
|
|
157
|
+
})).trim()
|
|
158
|
+
recordar(hash, texto)
|
|
159
|
+
return { ref, texto }
|
|
160
|
+
} catch (err) {
|
|
161
|
+
return { ref, error: (err as Error).message }
|
|
162
|
+
}
|
|
163
|
+
})
|
|
164
|
+
|
|
165
|
+
const analizadas = resultados.filter((r) => "texto" in r)
|
|
166
|
+
if (analizadas.length === 0) {
|
|
167
|
+
const motivo = (resultados[0] as { error: string }).error
|
|
168
|
+
log.warn(`No se pudo analizar ninguna imagen de ${path.basename(rutaAbsoluta)}: ${motivo}`)
|
|
169
|
+
return {
|
|
170
|
+
ok: false,
|
|
171
|
+
error: `No se pudo analizar las imágenes: ${motivo} Revisa que haya un modelo con visión elegido en Providers → Imagen.`,
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const ultima = lote[lote.length - 1].numero
|
|
176
|
+
log.info(`Imágenes de ${path.basename(rutaAbsoluta)}: ${analizadas.length}/${lote.length} analizadas (total ${imagenes.length})`)
|
|
177
|
+
return {
|
|
178
|
+
ok: true,
|
|
179
|
+
ruta: rutaAbsoluta,
|
|
180
|
+
totalImagenes: imagenes.length,
|
|
181
|
+
...(omitidas ? { omitidas } : {}),
|
|
182
|
+
imagenes: resultados.map((r) => ({
|
|
183
|
+
numero: r.ref.numero,
|
|
184
|
+
ubicacion: r.ref.ubicacion,
|
|
185
|
+
...("texto" in r ? { descripcion: r.texto } : { error: r.error }),
|
|
186
|
+
})),
|
|
187
|
+
...(ultima < imagenes.length
|
|
188
|
+
? { truncado: true, siguiente_imagen: ultima + 1, aviso: `Quedan ${imagenes.length - ultima} imágenes: vuelve a llamar con desde_imagen=${ultima + 1}.` }
|
|
189
|
+
: {}),
|
|
190
|
+
}
|
|
191
|
+
} catch (error) {
|
|
192
|
+
log.error(`Error leyendo imágenes: ${(error as Error).message}`)
|
|
193
|
+
return { ok: false, error: `No se pudieron leer las imágenes: ${(error as Error).message}` }
|
|
194
|
+
} finally {
|
|
195
|
+
await cerrar?.()
|
|
196
|
+
}
|
|
197
|
+
},
|
|
198
|
+
}
|
|
@@ -38,6 +38,13 @@ import * as office from "./office/index.ts";
|
|
|
38
38
|
// API (1) - HTTP client for REST APIs
|
|
39
39
|
import * as api from "./api/index.ts";
|
|
40
40
|
|
|
41
|
+
// Image (1) - generación de imágenes con el modelo elegido en Providers → Imagen
|
|
42
|
+
import * as image from "./image/index.ts";
|
|
43
|
+
|
|
44
|
+
// Google Workspace (21) - Gmail, Calendar, Drive. Sólo si el host configuró Google.
|
|
45
|
+
import * as google from "./google/index.ts";
|
|
46
|
+
import { isGoogleConfigured } from "../google/config.ts";
|
|
47
|
+
|
|
41
48
|
/**
|
|
42
49
|
* Creates all tools with proper configuration
|
|
43
50
|
*/
|
|
@@ -73,6 +80,12 @@ export function createAllTools(config: Config): Tool[] {
|
|
|
73
80
|
// API (1)
|
|
74
81
|
...api.createTools(),
|
|
75
82
|
|
|
83
|
+
// IMAGE (1)
|
|
84
|
+
...image.createTools(),
|
|
85
|
+
|
|
86
|
+
// GOOGLE (21) — opt-in: sin credenciales no hay tools que fallen en silencio
|
|
87
|
+
...(isGoogleConfigured() ? google.createTools() : []),
|
|
88
|
+
|
|
76
89
|
];
|
|
77
90
|
}
|
|
78
91
|
|
|
@@ -101,6 +114,10 @@ export function createToolsByCategory(category: string, config: Config): Tool[]
|
|
|
101
114
|
return office.createTools();
|
|
102
115
|
case "api":
|
|
103
116
|
return api.createTools();
|
|
117
|
+
case "image":
|
|
118
|
+
return image.createTools();
|
|
119
|
+
case "google":
|
|
120
|
+
return google.createTools();
|
|
104
121
|
default:
|
|
105
122
|
return [];
|
|
106
123
|
}
|
|
@@ -109,6 +126,16 @@ export function createToolsByCategory(category: string, config: Config): Tool[]
|
|
|
109
126
|
// Export types
|
|
110
127
|
export * from "./types.ts";
|
|
111
128
|
|
|
129
|
+
export { imageGenerateTool } from "./image/index.ts";
|
|
130
|
+
|
|
131
|
+
export {
|
|
132
|
+
gmailSearchTool, gmailReadTool, gmailThreadTool, gmailSendTool, gmailReplyTool, gmailForwardTool,
|
|
133
|
+
gmailDraftSaveTool, gmailDraftListTool, gmailDraftSendTool, gmailDraftDeleteTool,
|
|
134
|
+
gmailModifyTool, gmailLabelsTool, gmailAttachmentTool,
|
|
135
|
+
gcalListEventsTool, gcalCreateEventTool, gcalUpdateEventTool, gcalDeleteEventTool, gcalFreebusyTool,
|
|
136
|
+
gdriveSearchTool, gdriveDownloadTool, gdriveUploadTool,
|
|
137
|
+
} from "./google/index.ts";
|
|
138
|
+
|
|
112
139
|
// Export tools by category (avoiding createTools name collisions)
|
|
113
140
|
// Use category-specific imports or createAllTools/createToolsByCategory
|
|
114
141
|
export {
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Imágenes incrustadas en Word (.docx) y PowerPoint (.pptx).
|
|
3
|
+
*
|
|
4
|
+
* Ambos formatos son ZIP: las imágenes ya están dentro (`word/media/*`,
|
|
5
|
+
* `ppt/media/*`), no hay que renderizar nada. Este módulo solo las localiza,
|
|
6
|
+
* en el orden en que aparecen, con una pista de dónde estaban; el análisis con
|
|
7
|
+
* el modelo de visión lo hace quien lo llama. Sin estado ni acceso a HiveDB, así
|
|
8
|
+
* que sirve tanto en el worker de herramientas como en el hilo principal.
|
|
9
|
+
*/
|
|
10
|
+
import type JSZip from "jszip"
|
|
11
|
+
import { listarSlides } from "./pptx-slides.ts"
|
|
12
|
+
|
|
13
|
+
/** Por debajo de esto casi siempre es un ícono, una viñeta o un fondo: no aporta al análisis. */
|
|
14
|
+
export const MIN_BYTES_IMAGEN = 5_000
|
|
15
|
+
|
|
16
|
+
const MIME_POR_EXT: Record<string, string> = {
|
|
17
|
+
png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp",
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface ImagenRef {
|
|
21
|
+
/** Posición entre las imágenes útiles, desde 1. */
|
|
22
|
+
numero: number
|
|
23
|
+
/** Ruta dentro del zip, p. ej. ppt/media/image3.png. */
|
|
24
|
+
archivo: string
|
|
25
|
+
mimeType: string
|
|
26
|
+
/** Dónde estaba: "Diapositiva 4" o "Después de: «…»". */
|
|
27
|
+
ubicacion: string
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface ListadoImagenes {
|
|
31
|
+
imagenes: ImagenRef[]
|
|
32
|
+
/** Imágenes descartadas por ser demasiado pequeñas o de un formato que el modelo no lee (emf, svg…). */
|
|
33
|
+
omitidas: number
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const unescapeXml = (s: string) =>
|
|
37
|
+
s.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, "&")
|
|
38
|
+
|
|
39
|
+
/** Resuelve un Target relativo de un .rels contra la carpeta de la parte que lo declara. */
|
|
40
|
+
function resolverRuta(carpetaBase: string[], target: string): string {
|
|
41
|
+
const partes = target.startsWith("/") ? target.slice(1).split("/") : [...carpetaBase, ...target.split("/")]
|
|
42
|
+
const resueltas: string[] = []
|
|
43
|
+
for (const p of partes) { if (p === "..") resueltas.pop(); else if (p !== ".") resueltas.push(p) }
|
|
44
|
+
return resueltas.join("/")
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Relaciones de tipo imagen de un .rels: rId → ruta absoluta dentro del zip. */
|
|
48
|
+
async function relacionesDeImagen(zip: JSZip, relsPath: string, carpetaBase: string[]): Promise<Map<string, string>> {
|
|
49
|
+
const rels = await zip.file(relsPath)?.async("string")
|
|
50
|
+
const mapa = new Map<string, string>()
|
|
51
|
+
if (!rels) return mapa
|
|
52
|
+
for (const m of rels.matchAll(/<Relationship\b[^>]*>/g)) {
|
|
53
|
+
if (!/\bType="[^"]*\/image"/.test(m[0]) || /\bTargetMode="External"/.test(m[0])) continue
|
|
54
|
+
const id = m[0].match(/\bId="([^"]+)"/)?.[1]
|
|
55
|
+
const target = m[0].match(/\bTarget="([^"]+)"/)?.[1]
|
|
56
|
+
if (id && target) mapa.set(id, resolverRuta(carpetaBase, target))
|
|
57
|
+
}
|
|
58
|
+
return mapa
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Tamaño sin descomprimir si JSZip lo conoce; undefined si no (entonces no se filtra por tamaño aquí). */
|
|
62
|
+
function tamanoDe(zip: JSZip, archivo: string): number | undefined {
|
|
63
|
+
const size = (zip.file(archivo) as unknown as { _data?: { uncompressedSize?: number } } | null)?._data?.uncompressedSize
|
|
64
|
+
return typeof size === "number" ? size : undefined
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function mimeDe(archivo: string): string | null {
|
|
68
|
+
return MIME_POR_EXT[archivo.split(".").pop()?.toLowerCase() ?? ""] ?? null
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Acumula referencias sin repetir el mismo archivo (un logo en cada diapositiva cuenta una sola vez). */
|
|
72
|
+
class Acumulador {
|
|
73
|
+
readonly imagenes: ImagenRef[] = []
|
|
74
|
+
omitidas = 0
|
|
75
|
+
private vistos = new Map<string, ImagenRef>()
|
|
76
|
+
private descartados = new Set<string>()
|
|
77
|
+
|
|
78
|
+
constructor(private zip: JSZip) {}
|
|
79
|
+
|
|
80
|
+
agregar(archivo: string, ubicacion: string): void {
|
|
81
|
+
const previo = this.vistos.get(archivo)
|
|
82
|
+
if (previo) {
|
|
83
|
+
if (!previo.ubicacion.includes(ubicacion) && previo.ubicacion.split(" · ").length < 3) previo.ubicacion += ` · ${ubicacion}`
|
|
84
|
+
return
|
|
85
|
+
}
|
|
86
|
+
if (this.descartados.has(archivo)) return
|
|
87
|
+
const mimeType = mimeDe(archivo)
|
|
88
|
+
const tamano = tamanoDe(this.zip, archivo)
|
|
89
|
+
if (!this.zip.file(archivo) || !mimeType || (tamano !== undefined && tamano < MIN_BYTES_IMAGEN)) {
|
|
90
|
+
this.descartados.add(archivo)
|
|
91
|
+
this.omitidas++
|
|
92
|
+
return
|
|
93
|
+
}
|
|
94
|
+
const ref: ImagenRef = { numero: this.imagenes.length + 1, archivo, mimeType, ubicacion }
|
|
95
|
+
this.imagenes.push(ref)
|
|
96
|
+
this.vistos.set(archivo, ref)
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async function imagenesDocx(zip: JSZip): Promise<ListadoImagenes> {
|
|
101
|
+
const xml = await zip.file("word/document.xml")?.async("string")
|
|
102
|
+
if (!xml) return { imagenes: [], omitidas: 0 }
|
|
103
|
+
const rels = await relacionesDeImagen(zip, "word/_rels/document.xml.rels", ["word"])
|
|
104
|
+
const acc = new Acumulador(zip)
|
|
105
|
+
let ultimoTexto = ""
|
|
106
|
+
for (const p of xml.matchAll(/<w:p[ >][\s\S]*?<\/w:p>/g)) {
|
|
107
|
+
const texto = [...p[0].matchAll(/<w:t(?:\s[^>]*)?>([^<]*)<\/w:t>/g)].map((m) => unescapeXml(m[1])).join("").trim()
|
|
108
|
+
const recorte = texto.length > 80 ? `${texto.slice(0, 80)}…` : texto
|
|
109
|
+
for (const e of p[0].matchAll(/\br:embed="([^"]+)"/g)) {
|
|
110
|
+
const archivo = rels.get(e[1])
|
|
111
|
+
if (!archivo) continue
|
|
112
|
+
const ubicacion = recorte ? `Junto a: «${recorte}»` : ultimoTexto ? `Después de: «${ultimoTexto}»` : "Al inicio del documento"
|
|
113
|
+
acc.agregar(archivo, ubicacion)
|
|
114
|
+
}
|
|
115
|
+
if (recorte) ultimoTexto = recorte
|
|
116
|
+
}
|
|
117
|
+
return { imagenes: acc.imagenes, omitidas: acc.omitidas }
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async function imagenesPptx(zip: JSZip): Promise<ListadoImagenes> {
|
|
121
|
+
const acc = new Acumulador(zip)
|
|
122
|
+
for (const slide of await listarSlides(zip)) {
|
|
123
|
+
const xml = await zip.file(slide.archivo)!.async("string")
|
|
124
|
+
const relsPath = slide.archivo.replace(/slides\/(slide\d+\.xml)$/, "slides/_rels/$1.rels")
|
|
125
|
+
const rels = await relacionesDeImagen(zip, relsPath, slide.archivo.split("/").slice(0, -1))
|
|
126
|
+
for (const e of xml.matchAll(/\br:embed="([^"]+)"/g)) {
|
|
127
|
+
const archivo = rels.get(e[1])
|
|
128
|
+
if (archivo) acc.agregar(archivo, `Diapositiva ${slide.numero}`)
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return { imagenes: acc.imagenes, omitidas: acc.omitidas }
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Localiza las imágenes útiles de un .docx o .pptx, en el orden en que aparecen. */
|
|
135
|
+
export async function listarImagenes(zip: JSZip, formato: "docx" | "pptx"): Promise<ListadoImagenes> {
|
|
136
|
+
return formato === "docx" ? imagenesDocx(zip) : imagenesPptx(zip)
|
|
137
|
+
}
|
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
9
|
import { resolveOfficeInput, ARTIFACT_ID_PARAM } from "./resolve-input.ts";
|
|
10
|
+
import { listarImagenes } from "./office-images.ts";
|
|
10
11
|
import type { Tool } from "../types.ts";
|
|
11
12
|
import { logger } from "../../utils/logger.ts";
|
|
12
13
|
import * as fs from "node:fs";
|
|
@@ -77,7 +78,14 @@ export const officeLeerDocxTool: Tool = {
|
|
|
77
78
|
.filter((m: any) => m.type === "warning")
|
|
78
79
|
.map((m: any) => m.message);
|
|
79
80
|
|
|
80
|
-
|
|
81
|
+
// Las imágenes no entran en el texto: se avisa para que el agente sepa que existen.
|
|
82
|
+
let imagenes = 0;
|
|
83
|
+
try {
|
|
84
|
+
const JSZip = (await import("jszip")).default;
|
|
85
|
+
imagenes = (await listarImagenes(await JSZip.loadAsync(buffer), "docx")).imagenes.length;
|
|
86
|
+
} catch { /* sin aviso de imágenes: el texto ya se leyó */ }
|
|
87
|
+
|
|
88
|
+
log.info(`DOCX leído: ${resultadoTexto.value.length} caracteres, ${imagenes} imágenes`);
|
|
81
89
|
|
|
82
90
|
return {
|
|
83
91
|
ok: true,
|
|
@@ -85,6 +93,7 @@ export const officeLeerDocxTool: Tool = {
|
|
|
85
93
|
texto: resultadoTexto.value,
|
|
86
94
|
tablas: textoTablas,
|
|
87
95
|
advertencias: advertencias.length > 0 ? advertencias : undefined,
|
|
96
|
+
...(imagenes ? { imagenes, aviso_imagenes: `El documento tiene ${imagenes} ${imagenes === 1 ? "imagen" : "imágenes"} que NO están en este texto (capturas, gráficos, diagramas). Si hacen falta, usa la tool office_leer_imagenes con la misma ruta.` } : {}),
|
|
88
97
|
};
|
|
89
98
|
} catch (error) {
|
|
90
99
|
log.error(`Error leyendo DOCX: ${(error as Error).message}`);
|
|
@@ -71,7 +71,7 @@ export const officeLeerPdfTool: Tool = {
|
|
|
71
71
|
totalPaginas: r.totalPaginas,
|
|
72
72
|
paginasLeidas: r.paginasLeidas,
|
|
73
73
|
texto: "",
|
|
74
|
-
aviso: "Estas páginas no tienen texto extraíble: el PDF parece escaneado (solo imágenes). Esta herramienta no hace OCR
|
|
74
|
+
aviso: "Estas páginas no tienen texto extraíble: el PDF parece escaneado (solo imágenes). Esta herramienta no hace OCR: para leerlo usa office_leer_imagenes con la misma ruta (transcribe cada página con el modelo de visión, una llamada por página). Si no hay modelo de visión configurado, pídele al usuario el documento en formato editable o que copie el texto.",
|
|
75
75
|
};
|
|
76
76
|
}
|
|
77
77
|
const vacias = r.caracteresPorPagina.filter((c) => c === 0).length;
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
|
|
12
12
|
import { resolveOfficeInput, ARTIFACT_ID_PARAM } from "./resolve-input.ts";
|
|
13
13
|
import { listarSlides, textoDeXml, tituloDeXml, archivoDeNotas } from "./pptx-slides.ts";
|
|
14
|
+
import { listarImagenes } from "./office-images.ts";
|
|
14
15
|
import type { Tool } from "../types.ts";
|
|
15
16
|
import { logger } from "../../utils/logger.ts";
|
|
16
17
|
import * as fs from "node:fs";
|
|
@@ -83,12 +84,14 @@ export const officeLeerPptxTool: Tool = {
|
|
|
83
84
|
usados += tam;
|
|
84
85
|
}
|
|
85
86
|
|
|
86
|
-
|
|
87
|
+
const imagenes = (await listarImagenes(zip, "pptx").catch(() => ({ imagenes: [] }))).imagenes.length;
|
|
88
|
+
log.info(`PPTX leído: ${slides.length} slides totales, ${diapositivas.length} leídas, ${imagenes} imágenes`);
|
|
87
89
|
return {
|
|
88
90
|
ok: true,
|
|
89
91
|
ruta: rutaAbsoluta,
|
|
90
92
|
totalDiapositivas: slides.length,
|
|
91
93
|
diapositivas,
|
|
94
|
+
...(imagenes ? { imagenes, aviso_imagenes: `La presentación tiene ${imagenes} ${imagenes === 1 ? "imagen" : "imágenes"} que NO están en este texto (capturas, gráficos, diagramas). Si hacen falta, usa la tool office_leer_imagenes con la misma ruta.` } : {}),
|
|
92
95
|
...(siguiente ? { truncado: true, siguiente_diapositiva: siguiente, aviso: `Hay más diapositivas: vuelve a llamar con desde_diapositiva=${siguiente}.` } : {}),
|
|
93
96
|
};
|
|
94
97
|
} catch (error) {
|