@johpaz/hive-agents 1.1.5 → 1.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +3 -3
  2. package/dist/hive.js +229813 -162547
  3. package/dist/tool-worker.js +68298 -1620
  4. package/dist/ui/assets/{A2UIPage-Dr3p75oE.js → A2UIPage-CxE3jH4_.js} +1 -1
  5. package/dist/ui/assets/{AgentCreateForm-DqYhH_gm.js → AgentCreateForm-SGj5AqAX.js} +1 -1
  6. package/dist/ui/assets/{AgentDetailPage-BVtE88U5.js → AgentDetailPage-CyYbqzHr.js} +1 -1
  7. package/dist/ui/assets/{AgentNewPage-BRpFxJIT.js → AgentNewPage-xvAmX6kw.js} +1 -1
  8. package/dist/ui/assets/{AgentsPage-BOIJ55cj.js → AgentsPage-CEWNs4Lt.js} +1 -1
  9. package/dist/ui/assets/{ApiClientPage-R9UDWfR2.js → ApiClientPage-NLw2wHjH.js} +1 -1
  10. package/dist/ui/assets/{ChannelsPage-C5V2BmjL.js → ChannelsPage-CmeXP-hI.js} +1 -1
  11. package/dist/ui/assets/{DashboardPage-B18gMzNj.js → DashboardPage-C3z4kZXD.js} +1 -1
  12. package/dist/ui/assets/{LoginPage-nrsYF9AY.js → LoginPage-DDisP8hm.js} +1 -1
  13. package/dist/ui/assets/{LogsPage-DICMU_7m.js → LogsPage-G9d2G1nL.js} +1 -1
  14. package/dist/ui/assets/{MeetingPage-xslJGfIz.js → MeetingPage-CKyjxtFr.js} +1 -1
  15. package/dist/ui/assets/{ModelSelector-BX4IvuYY.js → ModelSelector-VVwpDrYF.js} +1 -1
  16. package/dist/ui/assets/{Office3DPage-a6cuzt5X.js → Office3DPage-CYxB6z2p.js} +1 -1
  17. package/dist/ui/assets/ProvidersPage-CM9-E-Pf.js +1 -0
  18. package/dist/ui/assets/{RecoverPage-Blms3NBa.js → RecoverPage-Dr6qKgV5.js} +1 -1
  19. package/dist/ui/assets/{SettingsPage-BBeeq_QS.js → SettingsPage-BvD-vs5g.js} +1 -1
  20. package/dist/ui/assets/{SetupPage-CAjLseE_.js → SetupPage-BoVKIf4r.js} +1 -1
  21. package/dist/ui/assets/{VoicePage-BeSSYstD.js → VoicePage-CmudxYny.js} +1 -1
  22. package/dist/ui/assets/WebChatPage-CnoXpEOl.js +29 -0
  23. package/dist/ui/assets/{conversationsStore-DhM07qYi.js → conversationsStore-ns_ZfKgg.js} +1 -1
  24. package/dist/ui/assets/{dialog-BP3GTCPn.js → dialog-C3n2xYF2.js} +1 -1
  25. package/dist/ui/assets/{index-BG3nUPKq.js → index-C0W6p0lk.js} +3 -3
  26. package/dist/ui/assets/{useAudioDevices-zj0fuGwZ.js → useAudioDevices-CsPrtpWY.js} +1 -1
  27. package/dist/ui/assets/{useHiveAgentsModelLoad-Cd9p-bjs.js → useHiveAgentsModelLoad-nn4gON9g.js} +1 -1
  28. package/dist/ui/assets/{useProviders-Dj1k5PCk.js → useProviders-9tvEC3hX.js} +1 -1
  29. package/dist/ui/index.html +1 -1
  30. package/package.json +1 -1
  31. package/packages/cli/src/commands/onboard.ts +3 -2
  32. package/packages/core/src/agent/minimal-loadout.ts +1 -0
  33. package/packages/core/src/agent/tool-selector.ts +4 -0
  34. package/packages/core/src/artifacts/store.ts +8 -2
  35. package/packages/core/src/channels/base.ts +26 -0
  36. package/packages/core/src/channels/discord.ts +18 -2
  37. package/packages/core/src/channels/slack.ts +37 -7
  38. package/packages/core/src/channels/telegram.ts +39 -11
  39. package/packages/core/src/channels/whatsapp.ts +16 -1
  40. package/packages/core/src/gateway/channel-notify.ts +42 -0
  41. package/packages/core/src/gateway/routes/artifacts.ts +4 -0
  42. package/packages/core/src/gateway/routes/multimodal.ts +19 -0
  43. package/packages/core/src/gateway/server.ts +40 -17
  44. package/packages/core/src/gateway/webchat-turn.ts +15 -13
  45. package/packages/core/src/multimodal/attachment-ingest.ts +175 -0
  46. package/packages/core/src/multimodal/vision-analyzer.ts +94 -0
  47. package/packages/core/src/multimodal/vision-service.ts +25 -0
  48. package/packages/core/src/storage/seed.ts +26 -6
  49. package/packages/core/src/tool-runtime/index.ts +2 -0
  50. package/packages/core/src/tools/core/index.ts +79 -1
  51. package/packages/core/src/tools/office/index.ts +9 -0
  52. package/packages/core/src/tools/office/office-editar-docx.ts +184 -0
  53. package/packages/core/src/tools/office/office-editar-pptx.ts +126 -0
  54. package/packages/core/src/tools/office/office-editar-xlsx.ts +122 -0
  55. package/packages/core/src/tools/office/office-escribir-docx.ts +3 -2
  56. package/packages/core/src/tools/office/office-escribir-pdf.ts +3 -2
  57. package/packages/core/src/tools/office/office-escribir-pptx.ts +3 -2
  58. package/packages/core/src/tools/office/office-escribir-xlsx.ts +3 -2
  59. package/packages/core/src/tools/office/office-leer-docx.ts +6 -2
  60. package/packages/core/src/tools/office/office-leer-pdf.ts +41 -57
  61. package/packages/core/src/tools/office/office-leer-pptx.ts +51 -88
  62. package/packages/core/src/tools/office/office-leer-xlsx.ts +6 -2
  63. package/packages/core/src/tools/office/pdf-text.ts +186 -0
  64. package/packages/core/src/tools/office/pptx-slides.ts +83 -0
  65. package/packages/core/src/tools/office/resolve-input.ts +49 -0
  66. package/dist/ui/assets/ProvidersPage-C8-xGoeh.js +0 -1
  67. package/dist/ui/assets/WebChatPage-Bat7uUfd.js +0 -29
@@ -362,6 +362,84 @@ export const notifyTool: Tool = {
362
362
  },
363
363
  };
364
364
 
365
+ // ─── send_file ───────────────────────────────────────────────────────────────
366
+
367
+ const SEND_FILE_MIME: Record<string, string> = {
368
+ pdf: "application/pdf",
369
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
370
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
371
+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
372
+ csv: "text/csv", txt: "text/plain", md: "text/markdown", json: "application/json",
373
+ png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", webp: "image/webp", zip: "application/zip",
374
+ }
375
+ const SEND_FILE_MAX_BYTES = 50 * 1024 * 1024
376
+
377
+ export const sendFileTool: Tool = {
378
+ name: "send_file",
379
+ description:
380
+ "Send a file (Word, Excel, PDF, PowerPoint, image, text…) to the user in the chat they are writing from. Use it to hand back a document you created or corrected. Spanish: enviar archivo, enviar documento, devolver archivo corregido, mandar el excel/word/pdf al usuario",
381
+ parameters: {
382
+ type: "object",
383
+ properties: {
384
+ ruta: { type: "string", description: "Path of the file to send (inside the workspace, or the path of an attachment)" },
385
+ artifact_id: { type: "string", description: "Alternative to 'ruta': artifact_id of a file already stored" },
386
+ nombre: { type: "string", description: "File name the user will see (default: the file's own name)" },
387
+ mensaje: { type: "string", description: "Short caption shown with the file" },
388
+ },
389
+ required: [],
390
+ },
391
+ execute: async (params: Record<string, unknown>, config?: any) => {
392
+ const fs = await import("node:fs");
393
+ const nodePath = await import("node:path");
394
+ const { createArtifact } = await import("../../artifacts/store.ts");
395
+ const { resolveInWorkspace, getWorkspace } = await import("../filesystem/workspace-guard.ts");
396
+ const { sendFileToUserChannel } = await import("../../gateway/channel-notify");
397
+
398
+ const channel = (config?.configurable?.channel as string) ?? "webchat";
399
+ const userId = (config?.configurable?.user_id as string) ?? "";
400
+ const threadId = config?.configurable?.thread_id as string | undefined;
401
+
402
+ let artifactId = typeof params.artifact_id === "string" ? params.artifact_id.trim() : "";
403
+ let filename = typeof params.nombre === "string" ? params.nombre.trim() : "";
404
+ let mimeType = "application/octet-stream";
405
+
406
+ if (artifactId) {
407
+ const { col } = await import("../../storage/hive.ts");
408
+ const entry = await (await col<import("../../storage/collections.ts").ArtifactDoc>("artifacts")).get(artifactId);
409
+ if (!entry || entry.doc.status !== "active") return { ok: false, error: `El archivo ${artifactId} no existe o expiró.` };
410
+ mimeType = entry.doc.mime_type;
411
+ if (!filename) filename = nodePath.basename(entry.doc.path);
412
+ } else {
413
+ const ruta = typeof params.ruta === "string" ? params.ruta.trim() : "";
414
+ if (!ruta) return { ok: false, error: "Indica 'ruta' o 'artifact_id'." };
415
+ let abs: string;
416
+ try {
417
+ abs = resolveInWorkspace(ruta, getWorkspace(config));
418
+ } catch (err) {
419
+ return { ok: false, error: (err as Error).message };
420
+ }
421
+ abs = nodePath.resolve(abs);
422
+ if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) return { ok: false, error: `No existe el archivo: ${abs}` };
423
+ const size = fs.statSync(abs).size;
424
+ if (size === 0) return { ok: false, error: "El archivo está vacío." };
425
+ if (size > SEND_FILE_MAX_BYTES) return { ok: false, error: `El archivo pesa ${(size / 1048576).toFixed(1)} MB; el máximo es 50 MB.` };
426
+ const ext = nodePath.extname(abs).replace(".", "").toLowerCase();
427
+ mimeType = SEND_FILE_MIME[ext] ?? "application/octet-stream";
428
+ if (!filename) filename = nodePath.basename(abs);
429
+ const artifact = await createArtifact({
430
+ bytes: fs.readFileSync(abs), mimeType, kind: "outgoing", userId: userId || "unknown", extension: ext,
431
+ });
432
+ artifactId = artifact.id;
433
+ }
434
+
435
+ const caption = typeof params.mensaje === "string" ? params.mensaje : undefined;
436
+ log.info(`[send_file] ${channel}/${userId}: ${filename} (${mimeType})`);
437
+ const result = await sendFileToUserChannel(channel, userId, { artifactId, filename, mimeType, caption }, { threadId });
438
+ if (!result.ok) return { ok: false, error: `No se pudo enviar el archivo: ${result.error}` };
439
+ return { ok: true, sent: filename };
440
+ },
441
+ };
442
+
365
443
  // ─── save_note (scratchpad) ──────────────────────────────────────────────────
366
444
 
367
445
  export const saveNoteTool: Tool = {
@@ -504,5 +582,5 @@ export const conversationReadTool: Tool = {
504
582
  };
505
583
 
506
584
  export function createTools(): Tool[] {
507
- return [searchKnowledgeTool, notifyTool, saveNoteTool, reportProgressTool, conversationReadTool];
585
+ return [searchKnowledgeTool, notifyTool, sendFileTool, saveNoteTool, reportProgressTool, conversationReadTool];
508
586
  }
@@ -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(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&amp;/g, "&");
25
+ const escapeXml = (s: string) =>
26
+ s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
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
+ };
@@ -0,0 +1,126 @@
1
+ /**
2
+ * office_editar_pptx - Modificar el texto de un PowerPoint existente conservando su diseño
3
+ *
4
+ * Reemplaza texto en las diapositivas (y opcionalmente en las notas) aunque
5
+ * PowerPoint lo haya partido en varios fragmentos con formato distinto; layouts,
6
+ * imágenes, gráficos y animaciones no se tocan. Nunca pisa el original: guarda
7
+ * una copia («<nombre>_corregido.pptx»). No añade ni quita diapositivas.
8
+ *
9
+ * @category office
10
+ * @seedId office_editar_pptx
11
+ * @spanish editar powerpoint, corregir presentación, reemplazar texto en diapositivas, mejorar pptx
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
+ import { reemplazarEnParrafo } from "./office-editar-docx.ts";
21
+ import { listarSlides, archivoDeNotas } from "./pptx-slides.ts";
22
+
23
+ const log = logger.child("office-editar-pptx");
24
+
25
+ interface Reemplazo { buscar: string; reemplazar: string; diapositiva?: number }
26
+
27
+ export const officeEditarPptxTool: Tool = {
28
+ name: "office_editar_pptx",
29
+ description:
30
+ "Editar un PowerPoint (.pptx) existente reemplazando texto en diapositivas (y notas si se pide), conservando diseño, imágenes y gráficos. Guarda una copia (no pisa el original) y devuelve su ruta para enviarla con send_file. No añade ni elimina diapositivas. Spanish: editar powerpoint, corregir presentación, reemplazar texto en diapositivas",
31
+ parameters: {
32
+ type: "object",
33
+ properties: {
34
+ ruta: { type: "string", description: "Ruta del .pptx a editar" },
35
+ artifact_id: ARTIFACT_ID_PARAM,
36
+ reemplazos: {
37
+ type: "array",
38
+ description: "Pares buscar → reemplazar. 'diapositiva' (opcional) limita el cambio a esa diapositiva; sin ella se aplica a todas. Para borrar un texto usa reemplazar vacío.",
39
+ items: {
40
+ type: "object",
41
+ properties: {
42
+ buscar: { type: "string" },
43
+ reemplazar: { type: "string" },
44
+ diapositiva: { type: "number", description: "Número de diapositiva (1-indexed) al que limitar el cambio" },
45
+ },
46
+ required: ["buscar", "reemplazar"],
47
+ },
48
+ },
49
+ incluir_notas: { type: "boolean", description: "Aplicar también a las notas del orador (default: false)" },
50
+ guardar_como: { type: "string", description: "Ruta de salida (default: <nombre>_corregido.pptx junto al original)" },
51
+ },
52
+ required: ["reemplazos"],
53
+ },
54
+ execute: async (params: Record<string, unknown>, config?: any) => {
55
+ const entrada = await resolveOfficeInput(params);
56
+ if ("error" in entrada) return { ok: false, error: entrada.error };
57
+ const reemplazos = (Array.isArray(params.reemplazos) ? params.reemplazos : []) as Reemplazo[];
58
+ if (reemplazos.length === 0) return { ok: false, error: "Indica al menos un reemplazo en 'reemplazos'." };
59
+ const incluirNotas = params.incluir_notas === true;
60
+
61
+ try {
62
+ const workspace = getWorkspace(config);
63
+ const origen = path.resolve(entrada.ruta);
64
+ if (!fs.existsSync(origen)) return { ok: false, error: `Archivo no encontrado: ${origen}` };
65
+ if (!/\.pptx$/i.test(origen)) return { ok: false, error: "Solo se pueden editar archivos .pptx." };
66
+
67
+ const base = path.basename(origen).replace(/\.pptx$/i, "");
68
+ const pedido = typeof params.guardar_como === "string" && params.guardar_como.trim() ? params.guardar_como.trim() : null;
69
+ const destino = path.resolve(
70
+ pedido
71
+ ? resolveInWorkspace(pedido, workspace)
72
+ : workspace
73
+ ? resolveInWorkspace(`${base}_corregido.pptx`, workspace)
74
+ : path.join(path.dirname(origen), `${base}_corregido.pptx`),
75
+ );
76
+ if (destino === origen) return { ok: false, error: "El destino no puede ser el archivo original." };
77
+
78
+ const JSZip = (await import("jszip")).default;
79
+ const zip = await JSZip.loadAsync(fs.readFileSync(origen)).catch(() => {
80
+ throw new Error("El archivo no es un .pptx válido o está dañado.");
81
+ });
82
+ const slides = await listarSlides(zip);
83
+ if (slides.length === 0) return { ok: false, error: "La presentación no tiene diapositivas." };
84
+
85
+ const conteo = reemplazos.map(() => 0);
86
+ const aplicar = (xml: string, numero: number): string => {
87
+ let salida = xml;
88
+ reemplazos.forEach((r, i) => {
89
+ if (typeof r.buscar !== "string" || !r.buscar) return;
90
+ if (r.diapositiva !== undefined && Number(r.diapositiva) !== numero) return;
91
+ salida = salida.replace(/<a:p[ >][\s\S]*?<\/a:p>/g, (parrafo) => {
92
+ const res = reemplazarEnParrafo(parrafo, r.buscar, String(r.reemplazar ?? ""), "a:t");
93
+ conteo[i] += res.cuenta;
94
+ return res.xml;
95
+ });
96
+ });
97
+ return salida;
98
+ };
99
+
100
+ for (const slide of slides) {
101
+ zip.file(slide.archivo, aplicar(await zip.file(slide.archivo)!.async("string"), slide.numero));
102
+ if (incluirNotas) {
103
+ const notas = await archivoDeNotas(zip, slide);
104
+ if (notas) zip.file(notas, aplicar(await zip.file(notas)!.async("string"), slide.numero));
105
+ }
106
+ }
107
+
108
+ const resumen = reemplazos.map((r, i) => ({ buscar: r.buscar, diapositiva: r.diapositiva, apariciones: conteo[i] }));
109
+ if (conteo.every((c) => c === 0)) {
110
+ return { ok: false, error: "Ninguno de los textos a buscar aparece en las diapositivas indicadas.", resumen };
111
+ }
112
+
113
+ fs.mkdirSync(path.dirname(destino), { recursive: true });
114
+ fs.writeFileSync(destino, await zip.generateAsync({ type: "nodebuffer", compression: "DEFLATE" }));
115
+ log.info(`PPTX editado → ${destino}`);
116
+ return {
117
+ ok: true,
118
+ ruta: destino,
119
+ reemplazos: resumen,
120
+ nota: "Solo se edita texto existente (no se añaden ni quitan diapositivas). Envíalo con send_file.",
121
+ };
122
+ } catch (error) {
123
+ return { ok: false, error: `No se pudo editar el PowerPoint: ${(error as Error).message}` };
124
+ }
125
+ },
126
+ };
@@ -0,0 +1,122 @@
1
+ /**
2
+ * office_editar_xlsx - Modificar celdas de un Excel existente conservando su formato
3
+ *
4
+ * A diferencia de office_escribir_xlsx (crea desde cero), esta abre el archivo,
5
+ * cambia solo las celdas indicadas y lo guarda: estilos, anchos, formatos y
6
+ * fórmulas de las demás celdas quedan como estaban. Nunca pisa el original:
7
+ * guarda una copia (por defecto «<nombre>_corregido.xlsx»).
8
+ *
9
+ * @category office
10
+ * @seedId office_editar_xlsx
11
+ * @spanish editar excel, corregir excel, modificar celdas, mejorar hoja de cálculo
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-xlsx");
22
+
23
+ interface Cambio {
24
+ hoja: string;
25
+ celda: string;
26
+ valor?: string | number | boolean | null;
27
+ formula?: string;
28
+ }
29
+
30
+ export const officeEditarXlsxTool: Tool = {
31
+ name: "office_editar_xlsx",
32
+ description:
33
+ "Editar un Excel (.xlsx) existente cambiando solo las celdas indicadas, conservando el formato del resto. Guarda una copia (no pisa el original) y devuelve su ruta para enviarla con send_file. Spanish: editar excel, corregir excel, modificar celdas, mejorar hoja de cálculo",
34
+ parameters: {
35
+ type: "object",
36
+ properties: {
37
+ ruta: { type: "string", description: "Ruta del .xlsx a editar" },
38
+ artifact_id: ARTIFACT_ID_PARAM,
39
+ cambios: {
40
+ type: "array",
41
+ description: "Celdas a modificar. Usa 'valor' para texto/número o 'formula' (sin el signo =) para una fórmula.",
42
+ items: {
43
+ type: "object",
44
+ properties: {
45
+ hoja: { type: "string", description: "Nombre de la hoja" },
46
+ celda: { type: "string", description: "Referencia, p. ej. B7" },
47
+ valor: { type: "string", description: "Nuevo valor (texto o número; vacío para limpiar la celda)" },
48
+ formula: { type: "string", description: "Fórmula sin '=', p. ej. SUM(B2:B6)" },
49
+ },
50
+ required: ["hoja", "celda"],
51
+ },
52
+ },
53
+ guardar_como: { type: "string", description: "Ruta de salida (default: <nombre>_corregido.xlsx junto al original)" },
54
+ },
55
+ required: ["cambios"],
56
+ },
57
+ execute: async (params: Record<string, unknown>, config?: any) => {
58
+ const entrada = await resolveOfficeInput(params);
59
+ if ("error" in entrada) return { ok: false, error: entrada.error };
60
+ const cambios = Array.isArray(params.cambios) ? (params.cambios as Cambio[]) : [];
61
+ if (cambios.length === 0) return { ok: false, error: "Indica al menos un cambio en 'cambios'." };
62
+ if (cambios.length > 2000) return { ok: false, error: "Demasiados cambios en una llamada (máximo 2000)." };
63
+
64
+ try {
65
+ const workspace = getWorkspace(config);
66
+ const origen = path.resolve(entrada.ruta);
67
+ if (!fs.existsSync(origen)) return { ok: false, error: `Archivo no encontrado: ${origen}` };
68
+ if (!/\.xlsx$/i.test(origen)) return { ok: false, error: "Solo se pueden editar archivos .xlsx." };
69
+
70
+ // El origen puede ser un adjunto del usuario (fuera del workspace) y eso es lícito;
71
+ // el destino sí debe quedar dentro del workspace si el agente tiene uno.
72
+ const base = path.basename(origen).replace(/\.xlsx$/i, "");
73
+ const pedido = typeof params.guardar_como === "string" && params.guardar_como.trim()
74
+ ? params.guardar_como.trim()
75
+ : null;
76
+ const destino = path.resolve(
77
+ pedido
78
+ ? resolveInWorkspace(pedido, workspace)
79
+ : workspace
80
+ ? resolveInWorkspace(`${base}_corregido.xlsx`, workspace)
81
+ : path.join(path.dirname(origen), `${base}_corregido.xlsx`),
82
+ );
83
+ if (destino === origen) return { ok: false, error: "El destino no puede ser el archivo original." };
84
+
85
+ const ExcelJS = (await import("exceljs")).default;
86
+ const wb = new ExcelJS.Workbook();
87
+ await wb.xlsx.readFile(origen);
88
+
89
+ const aplicados: string[] = [];
90
+ const omitidos: string[] = [];
91
+ for (const c of cambios) {
92
+ const hoja = wb.getWorksheet(c.hoja);
93
+ if (!hoja) { omitidos.push(`${c.hoja}!${c.celda} (no existe la hoja)`); continue; }
94
+ if (!/^[A-Za-z]{1,3}[0-9]{1,7}$/.test(c.celda ?? "")) { omitidos.push(`${c.hoja}!${c.celda} (referencia inválida)`); continue; }
95
+ const celda = hoja.getCell(c.celda.toUpperCase());
96
+ if (typeof c.formula === "string" && c.formula.trim()) {
97
+ celda.value = { formula: c.formula.trim().replace(/^=/, "") } as any;
98
+ } else if ("valor" in c) {
99
+ celda.value = c.valor as any;
100
+ } else {
101
+ omitidos.push(`${c.hoja}!${c.celda} (falta 'valor' o 'formula')`);
102
+ continue;
103
+ }
104
+ aplicados.push(`${c.hoja}!${c.celda.toUpperCase()}`);
105
+ }
106
+ if (aplicados.length === 0) return { ok: false, error: `No se aplicó ningún cambio. ${omitidos.join("; ")}` };
107
+
108
+ fs.mkdirSync(path.dirname(destino), { recursive: true });
109
+ await wb.xlsx.writeFile(destino);
110
+ log.info(`XLSX editado: ${aplicados.length} celdas → ${destino}`);
111
+ return {
112
+ ok: true,
113
+ ruta: destino,
114
+ celdas_modificadas: aplicados.length,
115
+ ...(omitidos.length ? { omitidos } : {}),
116
+ nota: "Las fórmulas se recalculan al abrir el archivo en Excel. Envíalo con send_file.",
117
+ };
118
+ } catch (error) {
119
+ return { ok: false, error: `No se pudo editar el Excel: ${(error as Error).message}` };
120
+ }
121
+ },
122
+ };
@@ -12,6 +12,7 @@
12
12
  * @spanish crear word, generar docx, escribir documento word, exportar a docx
13
13
  */
14
14
 
15
+ import { resolveInWorkspace, getWorkspace } from "../filesystem/workspace-guard.ts";
15
16
  import type { Tool } from "../types.ts";
16
17
  import { logger } from "../../utils/logger.ts";
17
18
  import * as path from "node:path";
@@ -80,7 +81,7 @@ export const officeEscribirDocxTool: Tool = {
80
81
  },
81
82
  required: ["ruta"],
82
83
  },
83
- execute: async (params: Record<string, unknown>) => {
84
+ execute: async (params: Record<string, unknown>, config?: any) => {
84
85
  const ruta = params.ruta as string;
85
86
  const titulo = typeof params.titulo === "string" ? params.titulo : "";
86
87
 
@@ -342,7 +343,7 @@ export const officeEscribirDocxTool: Tool = {
342
343
  }],
343
344
  });
344
345
 
345
- const rutaAbsoluta = path.resolve(ruta);
346
+ const rutaAbsoluta = path.resolve(resolveInWorkspace(ruta, getWorkspace(config)));
346
347
  const dirDestino = path.dirname(rutaAbsoluta);
347
348
  if (!fs.existsSync(dirDestino)) fs.mkdirSync(dirDestino, { recursive: true });
348
349
 
@@ -13,6 +13,7 @@
13
13
  * @spanish crear pdf, generar pdf, escribir pdf, exportar a pdf
14
14
  */
15
15
 
16
+ import { resolveInWorkspace, getWorkspace } from "../filesystem/workspace-guard.ts";
16
17
  import type { Tool } from "../types.ts";
17
18
  import { logger } from "../../utils/logger.ts";
18
19
  import * as path from "node:path";
@@ -106,7 +107,7 @@ export const officeEscribirPdfTool: Tool = {
106
107
  },
107
108
  required: ["ruta"],
108
109
  },
109
- execute: async (params: Record<string, unknown>) => {
110
+ execute: async (params: Record<string, unknown>, config?: any) => {
110
111
  const ruta = params.ruta as string;
111
112
  log.debug(`Generando PDF: ${ruta}`);
112
113
 
@@ -533,7 +534,7 @@ export const officeEscribirPdfTool: Tool = {
533
534
  if (pie) dibujarBanda(pie, pg, i + 1, true);
534
535
  });
535
536
 
536
- const rutaAbsoluta = path.resolve(ruta);
537
+ const rutaAbsoluta = path.resolve(resolveInWorkspace(ruta, getWorkspace(config)));
537
538
  const dirDestino = path.dirname(rutaAbsoluta);
538
539
  if (!fs.existsSync(dirDestino)) fs.mkdirSync(dirDestino, { recursive: true });
539
540
 
@@ -11,6 +11,7 @@
11
11
  * @spanish crear powerpoint, generar pptx, escribir presentacion, exportar a pptx
12
12
  */
13
13
 
14
+ import { resolveInWorkspace, getWorkspace } from "../filesystem/workspace-guard.ts";
14
15
  import type { Tool } from "../types.ts";
15
16
  import { logger } from "../../utils/logger.ts";
16
17
  import * as path from "node:path";
@@ -57,7 +58,7 @@ export const officeEscribirPptxTool: Tool = {
57
58
  },
58
59
  required: ["ruta", "diapositivas"],
59
60
  },
60
- execute: async (params: Record<string, unknown>) => {
61
+ execute: async (params: Record<string, unknown>, config?: any) => {
61
62
  const ruta = params.ruta as string;
62
63
  const tituloPresentacion = params.titulo_presentacion as string | undefined;
63
64
  const subtitulo = params.subtitulo_presentacion as string | undefined;
@@ -150,7 +151,7 @@ export const officeEscribirPptxTool: Tool = {
150
151
  if (d.notas) s.addNotes(d.notas);
151
152
  }
152
153
 
153
- const rutaAbsoluta = path.resolve(ruta);
154
+ const rutaAbsoluta = path.resolve(resolveInWorkspace(ruta, getWorkspace(config)));
154
155
  const dirDestino = path.dirname(rutaAbsoluta);
155
156
  if (!fs.existsSync(dirDestino)) fs.mkdirSync(dirDestino, { recursive: true });
156
157
 
@@ -14,6 +14,7 @@
14
14
  * @spanish crear excel, generar xlsx, escribir excel, exportar a xlsx
15
15
  */
16
16
 
17
+ import { resolveInWorkspace, getWorkspace } from "../filesystem/workspace-guard.ts";
17
18
  import type { Tool } from "../types.ts";
18
19
  import { logger } from "../../utils/logger.ts";
19
20
  import * as path from "node:path";
@@ -123,7 +124,7 @@ export const officeEscribirXlsxTool: Tool = {
123
124
  },
124
125
  required: ["ruta", "hojas"],
125
126
  },
126
- execute: async (params: Record<string, unknown>) => {
127
+ execute: async (params: Record<string, unknown>, config?: any) => {
127
128
  const ruta = params.ruta as string;
128
129
  const hojasInput = params.hojas as HojaInput[];
129
130
 
@@ -247,7 +248,7 @@ export const officeEscribirXlsxTool: Tool = {
247
248
  totalFilas += Math.max(0, matriz.length - 1);
248
249
  }
249
250
 
250
- const rutaAbsoluta = path.resolve(ruta);
251
+ const rutaAbsoluta = path.resolve(resolveInWorkspace(ruta, getWorkspace(config)));
251
252
  const dirDestino = path.dirname(rutaAbsoluta);
252
253
  if (!fs.existsSync(dirDestino)) fs.mkdirSync(dirDestino, { recursive: true });
253
254