@johpaz/hive-agents 1.1.3 → 1.1.5

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 (53) hide show
  1. package/README.md +3 -3
  2. package/dist/hive.js +52087 -4376
  3. package/dist/tool-worker.js +49660 -1160
  4. package/dist/ui/assets/{A2UIPage-EDS7lN-K.js → A2UIPage-Dr3p75oE.js} +1 -1
  5. package/dist/ui/assets/{AgentCreateForm-KvhVhAFP.js → AgentCreateForm-DqYhH_gm.js} +1 -1
  6. package/dist/ui/assets/{AgentDetailPage-B2dCpO92.js → AgentDetailPage-BVtE88U5.js} +1 -1
  7. package/dist/ui/assets/{AgentNewPage-CF2B4dbu.js → AgentNewPage-BRpFxJIT.js} +1 -1
  8. package/dist/ui/assets/{AgentsPage-CMvz-CtA.js → AgentsPage-BOIJ55cj.js} +1 -1
  9. package/dist/ui/assets/{ApiClientPage-tzzL3rZC.js → ApiClientPage-R9UDWfR2.js} +1 -1
  10. package/dist/ui/assets/{ChannelsPage-fE2vRwup.js → ChannelsPage-C5V2BmjL.js} +1 -1
  11. package/dist/ui/assets/{DashboardPage-57SaHnBL.js → DashboardPage-B18gMzNj.js} +1 -1
  12. package/dist/ui/assets/{LoginPage-Fag9Bp5h.js → LoginPage-nrsYF9AY.js} +1 -1
  13. package/dist/ui/assets/{LogsPage-GVJd_a65.js → LogsPage-DICMU_7m.js} +1 -1
  14. package/dist/ui/assets/{MeetingPage-TKQu8Nr-.js → MeetingPage-xslJGfIz.js} +1 -1
  15. package/dist/ui/assets/{ModelSelector-DciHLo7R.js → ModelSelector-BX4IvuYY.js} +1 -1
  16. package/dist/ui/assets/Office3DPage-a6cuzt5X.js +727 -0
  17. package/dist/ui/assets/{ProvidersPage-BsWFvzqz.js → ProvidersPage-C8-xGoeh.js} +1 -1
  18. package/dist/ui/assets/{RecoverPage-BkdOyljs.js → RecoverPage-Blms3NBa.js} +1 -1
  19. package/dist/ui/assets/{SettingsPage-D_43Rc2I.js → SettingsPage-BBeeq_QS.js} +1 -1
  20. package/dist/ui/assets/{SetupPage-D6Z3SYZu.js → SetupPage-CAjLseE_.js} +1 -1
  21. package/dist/ui/assets/{Vignette-bSrGVyRd.js → Vignette-DrI2yK2m.js} +1 -1
  22. package/dist/ui/assets/VoicePage-BeSSYstD.js +307 -0
  23. package/dist/ui/assets/{WebChatPage-Dzk3FhiR.js → WebChatPage-Bat7uUfd.js} +1 -1
  24. package/dist/ui/assets/{bia-csMImkVQ.glb → bia-qdLMQRFi.glb} +0 -0
  25. package/dist/ui/assets/{conversationsStore-5hf5grlP.js → conversationsStore-DhM07qYi.js} +1 -1
  26. package/dist/ui/assets/{dialog-DKnsGLwr.js → dialog-BP3GTCPn.js} +1 -1
  27. package/dist/ui/assets/{index-mBw9Tl7u.js → index-BG3nUPKq.js} +2 -2
  28. package/dist/ui/assets/{useAudioDevices-BYFaA0X-.js → useAudioDevices-zj0fuGwZ.js} +1 -1
  29. package/dist/ui/assets/{useHiveAgentsModelLoad-RRQ6-ANC.js → useHiveAgentsModelLoad-Cd9p-bjs.js} +1 -1
  30. package/dist/ui/assets/{useProviders-DXr4pJ57.js → useProviders-Dj1k5PCk.js} +1 -1
  31. package/dist/ui/index.html +1 -1
  32. package/package.json +1 -1
  33. package/packages/cli/src/commands/onboard.ts +8 -7
  34. package/packages/core/src/agent/agent-catalog.ts +2 -2
  35. package/packages/core/src/gateway/routes/providers.ts +26 -79
  36. package/packages/core/src/gateway/server.ts +20 -0
  37. package/packages/core/src/scheduler/integration.ts +26 -20
  38. package/packages/core/src/storage/collections.ts +7 -0
  39. package/packages/core/src/storage/model-sync.ts +404 -0
  40. package/packages/core/src/storage/seed.ts +33 -3
  41. package/packages/core/src/tools/a2ui/index.ts +76 -0
  42. package/packages/core/src/tools/cron/index.ts +25 -3
  43. package/packages/core/src/tools/office/office-escribir-docx.ts +275 -97
  44. package/packages/core/src/tools/office/office-escribir-pdf.ts +489 -99
  45. package/packages/core/src/tools/office/office-escribir-pptx.ts +86 -84
  46. package/packages/core/src/tools/office/office-escribir-xlsx.ts +196 -40
  47. package/packages/core/src/tools/office/office-style.ts +452 -0
  48. package/packages/core/src/tools/web/obscura-install.ts +119 -0
  49. package/packages/core/src/tools/web/obscura.ts +26 -4
  50. package/packages/core/src/utils/date.ts +29 -0
  51. package/packages/skills/src/bundled-data.generated.ts +780 -780
  52. package/dist/ui/assets/Office3DPage-CQnO522l.js +0 -727
  53. package/dist/ui/assets/VoicePage-CCE2EOE9.js +0 -307
@@ -1,5 +1,11 @@
1
1
  /**
2
- * office_escribir_docx - Generar un archivo Word (.docx)
2
+ * office_escribir_docx - Generar un archivo Word (.docx) con estilos
3
+ *
4
+ * Comparte tema y bloques con el PDF (modern, classic, corporate, minimal): los
5
+ * títulos, la fuente, los colores, las tablas (encabezado con fondo, cebra,
6
+ * bordes) y las listas salen como estilos reales de Word, no como texto suelto.
7
+ * Admite encabezado y pie con {page}, {pages} y {title}. Los parámetros antiguos
8
+ * (`parrafos`, `tablas`) siguen funcionando.
3
9
  *
4
10
  * @category office
5
11
  * @seedId office_escribir_docx
@@ -10,40 +16,46 @@ import type { Tool } from "../types.ts";
10
16
  import { logger } from "../../utils/logger.ts";
11
17
  import * as path from "node:path";
12
18
  import * as fs from "node:fs";
19
+ import {
20
+ bloquesDeParametros,
21
+ hexValido,
22
+ resolverTemaDocumento,
23
+ type Bloque,
24
+ type ElementoLista,
25
+ type Familia,
26
+ type Tramo,
27
+ } from "./office-style";
13
28
 
14
29
  const log = logger.child("office-escribir-docx");
15
30
 
16
- interface ParrafoInput {
17
- texto: string;
18
- tipo?: "titulo1" | "titulo2" | "titulo3" | "parrafo" | "lista";
19
- negrita?: boolean;
20
- cursiva?: boolean;
21
- }
22
-
23
- interface TablaInput {
24
- filas: Array<{ celdas: string[] }>;
25
- encabezado?: boolean;
26
- }
31
+ const FUENTE_WORD: Record<Familia, string> = { sans: "Calibri", serif: "Cambria", mono: "Consolas" };
27
32
 
28
33
  export const officeEscribirDocxTool: Tool = {
29
34
  name: "office_escribir_docx",
30
35
  description:
31
- "Generar un archivo Word (.docx) con párrafos, títulos y tablas. Spanish: crear word, generar docx, escribir documento word, exportar a docx",
36
+ "Generar un archivo Word (.docx) con estilo: títulos, párrafos (con `tramos` de negrita/cursiva/subrayado/color/enlace), listas (viñetas o numeradas), tablas con encabezado en color y cebra, citas, código, reglas y saltos de página. `tema.preset` elige modern, classic, corporate o minimal. `encabezado`/`pie` ({texto, alineacion}) se repiten en cada página y aceptan {page}, {pages} y {title}. Spanish: crear word, generar docx, escribir documento word, exportar a docx, informe, carta, propuesta",
32
37
  parameters: {
33
38
  type: "object",
34
39
  properties: {
35
- ruta: {
36
- type: "string",
37
- description: "Ruta donde guardar el archivo .docx generado",
40
+ ruta: { type: "string", description: "Ruta donde guardar el archivo .docx generado" },
41
+ titulo: { type: "string", description: "Título del documento (opcional)" },
42
+ autor: { type: "string", description: "Autor (metadatos)" },
43
+ tamaño_pagina: { type: "string", enum: ["A4", "Letter"], description: "Tamaño de página (default A4)" },
44
+ tema: {
45
+ type: "object",
46
+ description: "{preset: modern|classic|corporate|minimal, colores: {texto, titulo, acento, atenuado, encabezado_tabla_fondo, encabezado_tabla_texto, borde_tabla, cebra, codigo_fondo} (hex de 6 dígitos), fuentes: {cuerpo, titulos} (sans|serif|mono)}",
38
47
  },
39
- titulo: {
40
- type: "string",
41
- description: "Título del documento (opcional)",
48
+ encabezado: { type: "object", description: "Encabezado de página: {texto, alineacion: left|center|right}" },
49
+ pie: { type: "object", description: "Pie de página: {texto, alineacion}. Ej: {texto: 'Página {page} de {pages}', alineacion: 'center'}" },
50
+ bloques: {
51
+ type: "array",
52
+ description: "Contenido ordenado en bloques. tipo: titulo(nivel 1-3) | parrafo(texto|tramos, alineacion, negrita, cursiva, color) | lista(estilo vinetas|numerada, elementos) | tabla(encabezado, cebra, columnas: pesos, alineacion: [..], filas: [[celda]]) | cita(texto, autor) | codigo(texto) | regla | espacio(alto) | salto_pagina",
53
+ items: { type: "object" },
42
54
  },
43
55
  parrafos: {
44
56
  type: "array",
45
57
  description:
46
- "Array de párrafos a incluir. Cada párrafo tiene: texto (string), tipo ('titulo1'|'titulo2'|'titulo3'|'parrafo'|'lista'), negrita (bool), cursiva (bool)",
58
+ "Formato simple (alternativa a `bloques`): párrafos con texto, tipo ('titulo1'|'titulo2'|'titulo3'|'parrafo'|'lista'), negrita, cursiva",
47
59
  items: {
48
60
  type: "object",
49
61
  properties: {
@@ -56,8 +68,7 @@ export const officeEscribirDocxTool: Tool = {
56
68
  },
57
69
  tablas: {
58
70
  type: "array",
59
- description:
60
- "Array de tablas a incluir. Cada tabla tiene: filas (array de {celdas: string[]}), encabezado (bool, primera fila como encabezado)",
71
+ description: "Formato simple: tablas con filas ({celdas: string[]}) y encabezado (bool, primera fila como encabezado). Van después de los párrafos; para mezclar el orden usa `bloques`.",
61
72
  items: {
62
73
  type: "object",
63
74
  properties: {
@@ -71,103 +82,269 @@ export const officeEscribirDocxTool: Tool = {
71
82
  },
72
83
  execute: async (params: Record<string, unknown>) => {
73
84
  const ruta = params.ruta as string;
74
- const titulo = params.titulo as string | undefined;
75
- const parrafosInput = (params.parrafos as ParrafoInput[]) ?? [];
76
- const tablasInput = (params.tablas as TablaInput[]) ?? [];
85
+ const titulo = typeof params.titulo === "string" ? params.titulo : "";
77
86
 
78
87
  log.debug(`Generando DOCX: ${ruta}`);
79
88
 
80
89
  try {
90
+ const d = await import("docx");
81
91
  const {
82
- Document,
83
- Packer,
84
- Paragraph,
85
- TextRun,
86
- HeadingLevel,
87
- Table,
88
- TableRow,
89
- TableCell,
90
- WidthType,
91
- BorderStyle,
92
- } = await import("docx");
93
-
94
- const seccionChildren: any[] = [];
95
-
96
- // Título del documento
97
- if (titulo) {
98
- seccionChildren.push(
99
- new Paragraph({
100
- text: titulo,
101
- heading: HeadingLevel.TITLE,
102
- })
103
- );
92
+ Document, Packer, Paragraph, TextRun, HeadingLevel, Table, TableRow, TableCell, WidthType,
93
+ BorderStyle, ShadingType, AlignmentType, LevelFormat, PageBreak, Header, Footer,
94
+ PageNumber, ExternalHyperlink, TableLayoutType,
95
+ } = d;
96
+
97
+ const tema = resolverTemaDocumento(params.tema);
98
+ const bloques = bloquesDeParametros(params);
99
+ if (!titulo && bloques.length === 0) {
100
+ return { ok: false, error: "Falta contenido: da `bloques`, `parrafos` o `tablas`." };
104
101
  }
105
102
 
106
- // Párrafos
107
- for (const p of parrafosInput) {
103
+ const fCuerpo = FUENTE_WORD[tema.fuenteCuerpo];
104
+ const fTitulos = FUENTE_WORD[tema.fuenteTitulos];
105
+ const letter = (params.tamaño_pagina ?? params["tamaño_pagina"]) === "Letter";
106
+ const pagAncho = letter ? 12240 : 11906;
107
+ const pagAlto = letter ? 15840 : 16838;
108
+ const margen = 1134; // 2 cm
109
+ const anchoUtil = pagAncho - margen * 2;
110
+
111
+ const alin = (a?: string) =>
112
+ a === "center" ? AlignmentType.CENTER : a === "right" ? AlignmentType.RIGHT : a === "justify" ? AlignmentType.JUSTIFIED : AlignmentType.LEFT;
113
+
114
+ // ─── Runs ──────────────────────────────────────────────────────────
115
+ const hacerRun = (t: Tramo, base?: { bold?: boolean; italic?: boolean; color?: string; size?: number }) => {
108
116
  const run = new TextRun({
109
- text: p.texto,
110
- bold: p.negrita ?? false,
111
- italics: p.cursiva ?? false,
117
+ text: t.text,
118
+ bold: t.bold ?? base?.bold,
119
+ italics: t.italic ?? base?.italic,
120
+ underline: t.underline ? {} : undefined,
121
+ color: hexValido(t.color) ?? base?.color,
122
+ size: t.size ? Math.round(t.size * 2) : base?.size,
123
+ font: t.font ? FUENTE_WORD[t.font] : undefined,
112
124
  });
125
+ if (t.link) {
126
+ return new ExternalHyperlink({
127
+ link: t.link,
128
+ children: [new TextRun({ text: t.text, bold: t.bold, italics: t.italic, color: tema.acento, underline: {}, size: t.size ? Math.round(t.size * 2) : base?.size })],
129
+ });
130
+ }
131
+ return run;
132
+ };
133
+ const runsDe = (b: { text: string; runs?: Tramo[] }, base?: Parameters<typeof hacerRun>[1]) =>
134
+ (b.runs && b.runs.length ? b.runs : [{ text: b.text }]).map((t) => hacerRun(t, base));
113
135
 
114
- let heading: any = undefined;
115
- if (p.tipo === "titulo1") heading = HeadingLevel.HEADING_1;
116
- else if (p.tipo === "titulo2") heading = HeadingLevel.HEADING_2;
117
- else if (p.tipo === "titulo3") heading = HeadingLevel.HEADING_3;
136
+ // ─── Numeración ────────────────────────────────────────────────────
137
+ const numeraciones: any[] = [
138
+ {
139
+ reference: "viñetas",
140
+ levels: [
141
+ { level: 0, format: LevelFormat.BULLET, text: "•", alignment: AlignmentType.LEFT, style: { paragraph: { indent: { left: 540, hanging: 270 } }, run: { color: tema.acento } } },
142
+ { level: 1, format: LevelFormat.BULLET, text: "–", alignment: AlignmentType.LEFT, style: { paragraph: { indent: { left: 1080, hanging: 270 } }, run: { color: tema.acento } } },
143
+ ],
144
+ },
145
+ ];
146
+ let contadorListas = 0;
147
+ const nuevaNumerada = () => {
148
+ const reference = `numerada-${++contadorListas}`;
149
+ numeraciones.push({
150
+ reference,
151
+ levels: [
152
+ { level: 0, format: LevelFormat.DECIMAL, text: "%1.", alignment: AlignmentType.LEFT, style: { paragraph: { indent: { left: 540, hanging: 360 } }, run: { color: tema.acento } } },
153
+ { level: 1, format: LevelFormat.LOWER_LETTER, text: "%2.", alignment: AlignmentType.LEFT, style: { paragraph: { indent: { left: 1080, hanging: 360 } }, run: { color: tema.acento } } },
154
+ ],
155
+ });
156
+ return reference;
157
+ };
118
158
 
119
- const opciones: any = { children: [run] };
120
- if (heading) opciones.heading = heading;
121
- if (p.tipo === "lista") opciones.bullet = { level: 0 };
159
+ // ─── Bloques → hijos de la sección ─────────────────────────────────
160
+ const hijos: any[] = [];
122
161
 
123
- seccionChildren.push(new Paragraph(opciones));
124
- }
162
+ const itemsLista = (items: ElementoLista[], estilo: "bullet" | "numbered", nivel: number, ref: string) => {
163
+ for (const it of items) {
164
+ hijos.push(new Paragraph({
165
+ children: [new TextRun({ text: it.text })],
166
+ numbering: { reference: nivel === 0 || estilo === "numbered" ? ref : "viñetas", level: nivel },
167
+ spacing: { after: 60 },
168
+ }));
169
+ if (it.items?.length && nivel < 1) itemsLista(it.items, estilo, nivel + 1, estilo === "numbered" ? ref : "viñetas");
170
+ }
171
+ };
172
+
173
+ const borde = (color: string, size = 4) => ({ style: BorderStyle.SINGLE, size, color, space: 0 });
125
174
 
126
- // Tablas
127
- for (const tablaInput of tablasInput) {
128
- const filas = tablaInput.filas.map((fila, filaIdx) => {
129
- const celdas = fila.celdas.map((textoCelda) => {
130
- const esEncabezado = tablaInput.encabezado && filaIdx === 0;
131
- return new TableCell({
132
- children: [
133
- new Paragraph({
134
- children: [
135
- new TextRun({
136
- text: textoCelda,
137
- bold: esEncabezado,
138
- }),
139
- ],
140
- }),
141
- ],
142
- });
175
+ const tabla = (b: Extract<Bloque, { type: "table" }>) => {
176
+ const nCols = Math.max(1, ...b.rows.map((r) => r.length));
177
+ const pesos = Array.from({ length: nCols }, (_, i) => b.columns?.[i] ?? 1);
178
+ const suma = pesos.reduce((a, c) => a + c, 0);
179
+ const anchos = pesos.map((p) => Math.floor((p / suma) * anchoUtil));
180
+ const conEnc = b.header && b.rows.length > 1;
181
+ const lado = borde(tema.bordeTabla);
182
+ const filas = b.rows.map((fila, i) => {
183
+ const esEnc = conEnc && i === 0;
184
+ const indiceCuerpo = conEnc ? i - 1 : i;
185
+ return new TableRow({
186
+ tableHeader: esEnc,
187
+ cantSplit: true,
188
+ children: Array.from({ length: nCols }, (_, c) => {
189
+ const celda = fila[c] ?? { text: "" };
190
+ const relleno = celda.fill ?? (esEnc ? tema.encabezadoTablaFondo : b.zebra && indiceCuerpo % 2 === 1 ? tema.cebra : undefined);
191
+ return new TableCell({
192
+ width: { size: anchos[c]!, type: WidthType.DXA },
193
+ margins: { top: 70, bottom: 70, left: 110, right: 110 },
194
+ shading: relleno ? { type: ShadingType.CLEAR, fill: relleno, color: "auto" } : undefined,
195
+ children: [new Paragraph({
196
+ alignment: alin(celda.align ?? b.align?.[c]),
197
+ children: [new TextRun({
198
+ text: celda.text,
199
+ bold: esEnc || celda.bold,
200
+ color: hexValido(celda.color) ?? (esEnc ? tema.encabezadoTablaTexto : tema.texto),
201
+ size: 20,
202
+ })],
203
+ })],
204
+ });
205
+ }),
143
206
  });
144
- return new TableRow({ children: celdas });
145
207
  });
208
+ hijos.push(new Table({
209
+ rows: filas,
210
+ width: { size: anchoUtil, type: WidthType.DXA },
211
+ columnWidths: anchos,
212
+ layout: TableLayoutType.FIXED,
213
+ borders: { top: lado, bottom: lado, left: lado, right: lado, insideHorizontal: lado, insideVertical: lado },
214
+ }));
215
+ hijos.push(new Paragraph({ text: "", spacing: { after: 120 } }));
216
+ };
146
217
 
147
- seccionChildren.push(
148
- new Table({
149
- rows: filas,
150
- width: { size: 100, type: WidthType.PERCENTAGE },
151
- })
152
- );
218
+ if (titulo) {
219
+ hijos.push(new Paragraph({ heading: HeadingLevel.TITLE, children: [new TextRun({ text: titulo })] }));
220
+ }
153
221
 
154
- // Línea en blanco después de la tabla
155
- seccionChildren.push(new Paragraph({ text: "" }));
222
+ for (const b of bloques) {
223
+ switch (b.type) {
224
+ case "heading":
225
+ hijos.push(new Paragraph({
226
+ heading: b.level === 1 ? HeadingLevel.HEADING_1 : b.level === 2 ? HeadingLevel.HEADING_2 : HeadingLevel.HEADING_3,
227
+ alignment: alin(b.align),
228
+ children: runsDe(b, b.color ? { color: hexValido(b.color) ?? undefined } : undefined),
229
+ }));
230
+ break;
231
+ case "paragraph":
232
+ hijos.push(new Paragraph({
233
+ alignment: alin(b.align),
234
+ indent: b.indent ? { left: Math.round(b.indent * 20) } : undefined,
235
+ spacing: { after: b.spaceAfter !== undefined ? Math.round(b.spaceAfter * 20) : 140, line: 300 },
236
+ children: runsDe(b, { bold: b.bold, italic: b.italic, color: hexValido(b.color) ?? undefined, size: b.size ? Math.round(b.size * 2) : undefined }),
237
+ }));
238
+ break;
239
+ case "list":
240
+ itemsLista(b.items, b.style, 0, b.style === "numbered" ? nuevaNumerada() : "viñetas");
241
+ hijos.push(new Paragraph({ text: "", spacing: { after: 60 } }));
242
+ break;
243
+ case "table":
244
+ tabla(b);
245
+ break;
246
+ case "quote":
247
+ hijos.push(new Paragraph({
248
+ indent: { left: 360 },
249
+ spacing: { before: 120, after: b.author ? 40 : 160 },
250
+ border: { left: { style: BorderStyle.SINGLE, size: 18, color: tema.acento, space: 10 } },
251
+ children: [new TextRun({ text: b.text, italics: true, color: tema.atenuado })],
252
+ }));
253
+ if (b.author) {
254
+ hijos.push(new Paragraph({
255
+ alignment: AlignmentType.RIGHT,
256
+ spacing: { after: 160 },
257
+ children: [new TextRun({ text: `— ${b.author}`, color: tema.atenuado, size: 20 })],
258
+ }));
259
+ }
260
+ break;
261
+ case "code":
262
+ for (const linea of b.text.replace(/\r\n?/g, "\n").split("\n")) {
263
+ hijos.push(new Paragraph({
264
+ shading: { type: ShadingType.CLEAR, fill: tema.codigoFondo, color: "auto" },
265
+ border: { left: { style: BorderStyle.SINGLE, size: 18, color: tema.acento, space: 6 } },
266
+ spacing: { after: 0, line: 260 },
267
+ indent: { left: 120 },
268
+ children: [new TextRun({ text: linea || " ", font: FUENTE_WORD.mono, size: 19, color: tema.texto })],
269
+ }));
270
+ }
271
+ hijos.push(new Paragraph({ text: "", spacing: { after: 120 } }));
272
+ break;
273
+ case "rule":
274
+ hijos.push(new Paragraph({
275
+ spacing: { before: 120, after: 120 },
276
+ border: { bottom: borde(tema.bordeTabla, 6) },
277
+ children: [],
278
+ }));
279
+ break;
280
+ case "spacer":
281
+ hijos.push(new Paragraph({ text: "", spacing: { after: Math.round(Math.min(400, Math.max(0, b.height)) * 20) } }));
282
+ break;
283
+ case "page_break":
284
+ hijos.push(new Paragraph({ children: [new PageBreak()] }));
285
+ break;
286
+ }
156
287
  }
288
+ if (hijos.length === 0) hijos.push(new Paragraph({ text: "" }));
289
+
290
+ // ─── Encabezado y pie ──────────────────────────────────────────────
291
+ const zona = (valor: unknown) => {
292
+ if (!valor || typeof valor !== "object") return undefined;
293
+ const o = valor as Record<string, any>;
294
+ const texto = String(o.texto ?? o.text ?? "");
295
+ if (!texto) return undefined;
296
+ // Convierte los marcadores en campos reales de Word, para que el número
297
+ // de página sea el de cada página y no un valor fijo.
298
+ const partes = texto.split(/(\{page\}|\{pagina\}|\{pages\}|\{paginas\}|\{title\}|\{titulo\})/);
299
+ const children = partes.filter(Boolean).map((p) => {
300
+ const opts = { size: 18, color: tema.atenuado, font: fCuerpo };
301
+ if (p === "{page}" || p === "{pagina}") return new TextRun({ ...opts, children: [PageNumber.CURRENT] });
302
+ if (p === "{pages}" || p === "{paginas}") return new TextRun({ ...opts, children: [PageNumber.TOTAL_PAGES] });
303
+ if (p === "{title}" || p === "{titulo}") return new TextRun({ ...opts, text: titulo });
304
+ return new TextRun({ ...opts, text: p });
305
+ });
306
+ return new Paragraph({ style: "HiveBanda", alignment: alin(o.alineacion ?? o.align), children });
307
+ };
308
+ const enc = zona(params.encabezado ?? params.header);
309
+ const pie = zona(params.pie ?? params.footer);
310
+
311
+ // ─── Documento con estilos reales ──────────────────────────────────
312
+ const estiloTitulo = (id: string, name: string, size: number, antes: number, despues: number, conLinea = false) => ({
313
+ id, name, basedOn: "Normal", next: "Normal", quickFormat: true,
314
+ run: { font: fTitulos, size, bold: true, color: tema.titulo },
315
+ paragraph: {
316
+ spacing: { before: antes, after: despues },
317
+ keepNext: true,
318
+ ...(conLinea ? { border: { bottom: { style: BorderStyle.SINGLE, size: 8, color: tema.acento, space: 4 } } } : {}),
319
+ },
320
+ });
157
321
 
158
322
  const doc = new Document({
159
- sections: [
160
- {
161
- children: seccionChildren,
162
- },
163
- ],
323
+ creator: typeof params.autor === "string" ? params.autor : "Hive Agent",
324
+ title: titulo || undefined,
325
+ styles: {
326
+ default: { document: { run: { font: fCuerpo, size: 22, color: tema.texto }, paragraph: { spacing: { line: 300 } } } },
327
+ paragraphStyles: [
328
+ estiloTitulo("Title", "Title", 52, 0, 240),
329
+ estiloTitulo("Heading1", "Heading 1", 36, 360, 160, true),
330
+ estiloTitulo("Heading2", "Heading 2", 28, 280, 100),
331
+ estiloTitulo("Heading3", "Heading 3", 24, 220, 80),
332
+ // Encabezado y pie: el estilo de párrafo alcanza también a los campos (número de página).
333
+ { id: "HiveBanda", name: "Hive Banda", basedOn: "Normal", run: { font: fCuerpo, size: 18, color: tema.atenuado } },
334
+ ],
335
+ },
336
+ numbering: { config: numeraciones },
337
+ sections: [{
338
+ properties: { page: { size: { width: pagAncho, height: pagAlto }, margin: { top: margen, bottom: margen, left: margen, right: margen } } },
339
+ headers: enc ? { default: new Header({ children: [enc] }) } : undefined,
340
+ footers: pie ? { default: new Footer({ children: [pie] }) } : undefined,
341
+ children: hijos,
342
+ }],
164
343
  });
165
344
 
166
345
  const rutaAbsoluta = path.resolve(ruta);
167
346
  const dirDestino = path.dirname(rutaAbsoluta);
168
- if (!fs.existsSync(dirDestino)) {
169
- fs.mkdirSync(dirDestino, { recursive: true });
170
- }
347
+ if (!fs.existsSync(dirDestino)) fs.mkdirSync(dirDestino, { recursive: true });
171
348
 
172
349
  const buffer = await Packer.toBuffer(doc);
173
350
  fs.writeFileSync(rutaAbsoluta, buffer);
@@ -178,8 +355,9 @@ export const officeEscribirDocxTool: Tool = {
178
355
  ok: true,
179
356
  ruta: rutaAbsoluta,
180
357
  bytesEscritos: buffer.length,
181
- parrafos: parrafosInput.length,
182
- tablas: tablasInput.length,
358
+ bloques: bloques.length,
359
+ parrafos: bloques.filter((b) => b.type === "paragraph" || b.type === "heading").length,
360
+ tablas: bloques.filter((b) => b.type === "table").length,
183
361
  };
184
362
  } catch (error) {
185
363
  log.error(`Error generando DOCX: ${(error as Error).message}`);