@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,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 {
|
|
@@ -23,6 +23,9 @@ import { officeLeerXlsxTool } from "./office-leer-xlsx.ts";
|
|
|
23
23
|
import { officeEscribirXlsxTool } from "./office-escribir-xlsx.ts";
|
|
24
24
|
import { officeLeerPptxTool } from "./office-leer-pptx.ts";
|
|
25
25
|
import { officeEscribirPptxTool } from "./office-escribir-pptx.ts";
|
|
26
|
+
import { officeEditarDocxTool } from "./office-editar-docx.ts";
|
|
27
|
+
import { officeEditarXlsxTool } from "./office-editar-xlsx.ts";
|
|
28
|
+
import { officeEditarPptxTool } from "./office-editar-pptx.ts";
|
|
26
29
|
|
|
27
30
|
export function createTools(): Tool[] {
|
|
28
31
|
return [
|
|
@@ -34,6 +37,9 @@ export function createTools(): Tool[] {
|
|
|
34
37
|
officeEscribirXlsxTool,
|
|
35
38
|
officeLeerPptxTool,
|
|
36
39
|
officeEscribirPptxTool,
|
|
40
|
+
officeEditarDocxTool,
|
|
41
|
+
officeEditarXlsxTool,
|
|
42
|
+
officeEditarPptxTool,
|
|
37
43
|
];
|
|
38
44
|
}
|
|
39
45
|
|
|
@@ -45,3 +51,6 @@ export * from "./office-leer-xlsx.ts";
|
|
|
45
51
|
export * from "./office-escribir-xlsx.ts";
|
|
46
52
|
export * from "./office-leer-pptx.ts";
|
|
47
53
|
export * from "./office-escribir-pptx.ts";
|
|
54
|
+
export * from "./office-editar-docx.ts";
|
|
55
|
+
export * from "./office-editar-xlsx.ts";
|
|
56
|
+
export * from "./office-editar-pptx.ts";
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* office_editar_docx - Modificar un Word existente conservando su formato
|
|
3
|
+
*
|
|
4
|
+
* Trabaja sobre el XML del documento: reemplaza texto aunque Word lo haya
|
|
5
|
+
* partido en varios fragmentos con formato distinto, y deja intactos estilos,
|
|
6
|
+
* tablas, imágenes, encabezados y pie. Opcionalmente añade párrafos al final.
|
|
7
|
+
* Nunca pisa el original: guarda una copia («<nombre>_corregido.docx»).
|
|
8
|
+
*
|
|
9
|
+
* @category office
|
|
10
|
+
* @seedId office_editar_docx
|
|
11
|
+
* @spanish editar word, corregir word, reemplazar texto en docx, mejorar documento word
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import type { Tool } from "../types.ts";
|
|
15
|
+
import { logger } from "../../utils/logger.ts";
|
|
16
|
+
import * as fs from "node:fs";
|
|
17
|
+
import * as path from "node:path";
|
|
18
|
+
import { resolveOfficeInput, ARTIFACT_ID_PARAM } from "./resolve-input.ts";
|
|
19
|
+
import { resolveInWorkspace, getWorkspace } from "../filesystem/workspace-guard.ts";
|
|
20
|
+
|
|
21
|
+
const log = logger.child("office-editar-docx");
|
|
22
|
+
|
|
23
|
+
const unescapeXml = (s: string) =>
|
|
24
|
+
s.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, "&");
|
|
25
|
+
const escapeXml = (s: string) =>
|
|
26
|
+
s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Reemplaza en un párrafo (XML de <w:p>) todas las apariciones de `buscar`.
|
|
30
|
+
* El texto de un párrafo vive repartido en <w:t>; se une, se localizan las
|
|
31
|
+
* coincidencias y cada una se escribe en el fragmento donde empieza (así hereda
|
|
32
|
+
* su formato) vaciando el resto de fragmentos que cubría.
|
|
33
|
+
*/
|
|
34
|
+
export function reemplazarEnParrafo(parrafo: string, buscar: string, reemplazar: string, etiqueta: "w:t" | "a:t" = "w:t"): { xml: string; cuenta: number } {
|
|
35
|
+
const re = new RegExp(`(<${etiqueta}(?:\\s[^>]*)?>)([^<]*)(<\\/${etiqueta}>)`, "g");
|
|
36
|
+
const partes: { start: number; end: number; open: string; text: string }[] = [];
|
|
37
|
+
let m: RegExpExecArray | null;
|
|
38
|
+
while ((m = re.exec(parrafo))) {
|
|
39
|
+
partes.push({ start: m.index, end: m.index + m[0].length, open: m[1], text: unescapeXml(m[2]) });
|
|
40
|
+
}
|
|
41
|
+
if (partes.length === 0) return { xml: parrafo, cuenta: 0 };
|
|
42
|
+
const textos = partes.map((p) => p.text);
|
|
43
|
+
const completo = textos.join("");
|
|
44
|
+
if (!buscar || !completo.includes(buscar)) return { xml: parrafo, cuenta: 0 };
|
|
45
|
+
|
|
46
|
+
// Offset de inicio de cada fragmento dentro del texto completo.
|
|
47
|
+
const offsets: number[] = [];
|
|
48
|
+
let acc = 0;
|
|
49
|
+
for (const t of textos) { offsets.push(acc); acc += t.length; }
|
|
50
|
+
|
|
51
|
+
let cuenta = 0;
|
|
52
|
+
let desde = 0;
|
|
53
|
+
const nuevos = [...textos];
|
|
54
|
+
// Se procesa de derecha a izquierda para no invalidar offsets.
|
|
55
|
+
const coincidencias: number[] = [];
|
|
56
|
+
while (true) {
|
|
57
|
+
const i = completo.indexOf(buscar, desde);
|
|
58
|
+
if (i === -1) break;
|
|
59
|
+
coincidencias.push(i);
|
|
60
|
+
desde = i + buscar.length;
|
|
61
|
+
}
|
|
62
|
+
for (const inicio of coincidencias.reverse()) {
|
|
63
|
+
const fin = inicio + buscar.length;
|
|
64
|
+
let primero = true;
|
|
65
|
+
for (let k = 0; k < partes.length; k++) {
|
|
66
|
+
const ini = offsets[k], finK = offsets[k] + textos[k].length;
|
|
67
|
+
if (finK <= inicio || ini >= fin) continue;
|
|
68
|
+
const localIni = Math.max(inicio, ini) - ini;
|
|
69
|
+
const localFin = Math.min(fin, finK) - ini;
|
|
70
|
+
const t = nuevos[k];
|
|
71
|
+
nuevos[k] = t.slice(0, localIni) + (primero ? reemplazar : "") + t.slice(localFin);
|
|
72
|
+
primero = false;
|
|
73
|
+
}
|
|
74
|
+
cuenta++;
|
|
75
|
+
}
|
|
76
|
+
// Reconstruir el párrafo de derecha a izquierda con los textos nuevos.
|
|
77
|
+
let xml = parrafo;
|
|
78
|
+
for (let k = partes.length - 1; k >= 0; k--) {
|
|
79
|
+
const p = partes[k];
|
|
80
|
+
let open = p.open;
|
|
81
|
+
if (etiqueta === "w:t" && nuevos[k] !== textos[k] && !/xml:space/.test(open)) open = open.replace(/>$/, ' xml:space="preserve">');
|
|
82
|
+
xml = xml.slice(0, p.start) + open + escapeXml(nuevos[k]) + `</${etiqueta}>` + xml.slice(p.end);
|
|
83
|
+
}
|
|
84
|
+
return { xml, cuenta };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export const officeEditarDocxTool: Tool = {
|
|
88
|
+
name: "office_editar_docx",
|
|
89
|
+
description:
|
|
90
|
+
"Editar un Word (.docx) existente: reemplazar texto y/o añadir párrafos al final, conservando estilos, tablas e imágenes. Guarda una copia (no pisa el original) y devuelve su ruta para enviarla con send_file. Spanish: editar word, corregir word, reemplazar texto en docx, mejorar documento",
|
|
91
|
+
parameters: {
|
|
92
|
+
type: "object",
|
|
93
|
+
properties: {
|
|
94
|
+
ruta: { type: "string", description: "Ruta del .docx a editar" },
|
|
95
|
+
artifact_id: ARTIFACT_ID_PARAM,
|
|
96
|
+
reemplazos: {
|
|
97
|
+
type: "array",
|
|
98
|
+
description: "Pares buscar → reemplazar (todas las apariciones, en el cuerpo del documento). Para borrar un texto usa reemplazar vacío.",
|
|
99
|
+
items: {
|
|
100
|
+
type: "object",
|
|
101
|
+
properties: { buscar: { type: "string" }, reemplazar: { type: "string" } },
|
|
102
|
+
required: ["buscar", "reemplazar"],
|
|
103
|
+
},
|
|
104
|
+
},
|
|
105
|
+
anadir_parrafos: { type: "array", items: { type: "string" }, description: "Párrafos nuevos al final del documento" },
|
|
106
|
+
guardar_como: { type: "string", description: "Ruta de salida (default: <nombre>_corregido.docx junto al original)" },
|
|
107
|
+
},
|
|
108
|
+
required: [],
|
|
109
|
+
},
|
|
110
|
+
execute: async (params: Record<string, unknown>, config?: any) => {
|
|
111
|
+
const entrada = await resolveOfficeInput(params);
|
|
112
|
+
if ("error" in entrada) return { ok: false, error: entrada.error };
|
|
113
|
+
const reemplazos = Array.isArray(params.reemplazos) ? (params.reemplazos as { buscar: string; reemplazar: string }[]) : [];
|
|
114
|
+
const nuevos = Array.isArray(params.anadir_parrafos) ? (params.anadir_parrafos as unknown[]).map(String) : [];
|
|
115
|
+
if (reemplazos.length === 0 && nuevos.length === 0) {
|
|
116
|
+
return { ok: false, error: "Indica 'reemplazos' y/o 'anadir_parrafos'." };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
try {
|
|
120
|
+
const workspace = getWorkspace(config);
|
|
121
|
+
const origen = path.resolve(entrada.ruta);
|
|
122
|
+
if (!fs.existsSync(origen)) return { ok: false, error: `Archivo no encontrado: ${origen}` };
|
|
123
|
+
if (!/\.docx$/i.test(origen)) return { ok: false, error: "Solo se pueden editar archivos .docx." };
|
|
124
|
+
|
|
125
|
+
const base = path.basename(origen).replace(/\.docx$/i, "");
|
|
126
|
+
const pedido = typeof params.guardar_como === "string" && params.guardar_como.trim() ? params.guardar_como.trim() : null;
|
|
127
|
+
const destino = path.resolve(
|
|
128
|
+
pedido
|
|
129
|
+
? resolveInWorkspace(pedido, workspace)
|
|
130
|
+
: workspace
|
|
131
|
+
? resolveInWorkspace(`${base}_corregido.docx`, workspace)
|
|
132
|
+
: path.join(path.dirname(origen), `${base}_corregido.docx`),
|
|
133
|
+
);
|
|
134
|
+
if (destino === origen) return { ok: false, error: "El destino no puede ser el archivo original." };
|
|
135
|
+
|
|
136
|
+
const JSZip = (await import("jszip")).default;
|
|
137
|
+
const zip = await JSZip.loadAsync(fs.readFileSync(origen));
|
|
138
|
+
const entradaXml = zip.file("word/document.xml");
|
|
139
|
+
if (!entradaXml) return { ok: false, error: "El archivo no parece un .docx válido (falta word/document.xml)." };
|
|
140
|
+
let xml = await entradaXml.async("string");
|
|
141
|
+
|
|
142
|
+
const resumen: { buscar: string; apariciones: number }[] = [];
|
|
143
|
+
for (const r of reemplazos) {
|
|
144
|
+
if (typeof r.buscar !== "string" || !r.buscar) continue;
|
|
145
|
+
let total = 0;
|
|
146
|
+
xml = xml.replace(/<w:p[ >][\s\S]*?<\/w:p>/g, (parrafo) => {
|
|
147
|
+
const res = reemplazarEnParrafo(parrafo, r.buscar, String(r.reemplazar ?? ""));
|
|
148
|
+
total += res.cuenta;
|
|
149
|
+
return res.xml;
|
|
150
|
+
});
|
|
151
|
+
resumen.push({ buscar: r.buscar, apariciones: total });
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
if (nuevos.length) {
|
|
155
|
+
const parrafos = nuevos
|
|
156
|
+
.map((t) => `<w:p><w:r><w:t xml:space="preserve">${escapeXml(t)}</w:t></w:r></w:p>`)
|
|
157
|
+
.join("");
|
|
158
|
+
// Antes de sectPr (propiedades de página) para que el texto quede dentro del cuerpo.
|
|
159
|
+
xml = /<w:sectPr(?=[\s/>])/.test(xml)
|
|
160
|
+
? xml.replace(/(<w:sectPr(?=[\s/>])(?![\s\S]*<w:sectPr(?=[\s/>])))/, `${parrafos}$1`)
|
|
161
|
+
: xml.replace("</w:body>", `${parrafos}</w:body>`);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const sinCambios = resumen.length > 0 && resumen.every((r) => r.apariciones === 0) && nuevos.length === 0;
|
|
165
|
+
if (sinCambios) {
|
|
166
|
+
return { ok: false, error: "Ninguno de los textos a buscar aparece en el cuerpo del documento.", resumen };
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
zip.file("word/document.xml", xml);
|
|
170
|
+
fs.mkdirSync(path.dirname(destino), { recursive: true });
|
|
171
|
+
fs.writeFileSync(destino, await zip.generateAsync({ type: "nodebuffer", compression: "DEFLATE" }));
|
|
172
|
+
log.info(`DOCX editado → ${destino}`);
|
|
173
|
+
return {
|
|
174
|
+
ok: true,
|
|
175
|
+
ruta: destino,
|
|
176
|
+
reemplazos: resumen,
|
|
177
|
+
parrafos_anadidos: nuevos.length,
|
|
178
|
+
nota: "Solo se edita el cuerpo del documento (no encabezados ni pies). Envíalo con send_file.",
|
|
179
|
+
};
|
|
180
|
+
} catch (error) {
|
|
181
|
+
return { ok: false, error: `No se pudo editar el Word: ${(error as Error).message}` };
|
|
182
|
+
}
|
|
183
|
+
},
|
|
184
|
+
};
|