@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,10 @@
1
1
  /**
2
- * office_escribir_pptx - Generar un archivo PowerPoint (.pptx)
2
+ * office_escribir_pptx - Generar un archivo PowerPoint (.pptx) con estilos
3
+ *
4
+ * Mismo modelo que `office_write_pptx` del SDK de Rust: portada opcional, una
5
+ * diapositiva por entrada con título y texto libre o viñetas, notas del
6
+ * presentador y un tema (modern, light, dark, corporate, warm) cuyos colores y
7
+ * fuentes se pueden sobreescribir.
3
8
  *
4
9
  * @category office
5
10
  * @seedId office_escribir_pptx
@@ -10,6 +15,7 @@ import type { Tool } from "../types.ts";
10
15
  import { logger } from "../../utils/logger.ts";
11
16
  import * as path from "node:path";
12
17
  import * as fs from "node:fs";
18
+ import { resolverPaleta } from "./office-style";
13
19
 
14
20
  const log = logger.child("office-escribir-pptx");
15
21
 
@@ -23,22 +29,21 @@ interface DiapositivaInput {
23
29
  export const officeEscribirPptxTool: Tool = {
24
30
  name: "office_escribir_pptx",
25
31
  description:
26
- "Generar un archivo PowerPoint (.pptx) desde un array de diapositivas con título y contenido. Spanish: crear powerpoint, generar pptx, escribir presentacion, exportar a pptx",
32
+ "Generar una presentación PowerPoint (.pptx) 16:9 con estilo: portada opcional con fondo propio, diapositivas con título, acento de color, texto libre o viñetas, número de diapositiva y notas del presentador. `tema.preset` elige modern, light, dark, corporate o warm y puede sobreescribir colores y fuentes. Spanish: crear powerpoint, generar pptx, escribir presentacion, exportar a pptx, diapositivas, slides",
27
33
  parameters: {
28
34
  type: "object",
29
35
  properties: {
30
- ruta: {
31
- type: "string",
32
- description: "Ruta donde guardar el archivo .pptx generado",
33
- },
34
- titulo_presentacion: {
35
- type: "string",
36
- description: "Título de la presentación (aparece en la primera diapositiva)",
36
+ ruta: { type: "string", description: "Ruta donde guardar el archivo .pptx generado" },
37
+ titulo_presentacion: { type: "string", description: "Título de la presentación (portada)" },
38
+ subtitulo_presentacion: { type: "string", description: "Subtítulo de la portada (autor, fecha, empresa…)" },
39
+ tema: {
40
+ type: "object",
41
+ description: "{preset: modern|light|dark|corporate|warm, colores: {fondo, titulo, texto, acento, acento2, portada_fondo, portada_texto} (hex de 6 dígitos), fuentes: {titulo, cuerpo} (nombre de tipografía)}",
37
42
  },
38
43
  diapositivas: {
39
44
  type: "array",
40
45
  description:
41
- "Array de diapositivas. Cada una tiene: titulo (string), contenido (string, texto libre), puntos (string[], lista de viñetas), notas (string, notas del presentador)",
46
+ "Diapositivas. Cada una: titulo (string), contenido (texto libre), puntos (string[] viñetas; tienen prioridad sobre contenido), notas (notas del presentador)",
42
47
  items: {
43
48
  type: "object",
44
49
  properties: {
@@ -55,112 +60,109 @@ export const officeEscribirPptxTool: Tool = {
55
60
  execute: async (params: Record<string, unknown>) => {
56
61
  const ruta = params.ruta as string;
57
62
  const tituloPresentacion = params.titulo_presentacion as string | undefined;
63
+ const subtitulo = params.subtitulo_presentacion as string | undefined;
58
64
  const diapositivasInput = params.diapositivas as DiapositivaInput[];
59
65
 
60
66
  log.debug(`Generando PPTX: ${ruta}`);
61
67
 
62
68
  try {
69
+ if (!Array.isArray(diapositivasInput)) {
70
+ return { ok: false, error: "`diapositivas` debe ser un array." };
71
+ }
72
+ const paleta = resolverPaleta(params.tema);
63
73
  const pptxgen = (await import("pptxgenjs")).default;
64
74
  const pres = new pptxgen();
75
+ pres.layout = "LAYOUT_16x9"; // 10 x 5.625 in
76
+ if (tituloPresentacion) pres.title = tituloPresentacion;
77
+ pres.author = "Hive Agent";
65
78
 
66
- // Configuración básica
67
- pres.layout = "LAYOUT_16x9";
79
+ const ANCHO = 10;
80
+ const ALTO = 5.625;
68
81
 
69
- // Diapositiva de título (si se proporciona título de presentación)
82
+ // ─── Portada ────────────────────────────────────────────────────────
70
83
  if (tituloPresentacion) {
71
- const slidePortada = pres.addSlide();
72
- slidePortada.addText(tituloPresentacion, {
73
- x: "10%",
74
- y: "35%",
75
- w: "80%",
76
- h: "30%",
77
- fontSize: 36,
78
- bold: true,
79
- align: "center",
80
- color: "363636",
84
+ const s = pres.addSlide();
85
+ s.background = { color: paleta.portadaFondo };
86
+ s.addShape(pres.ShapeType.rect, { x: 0, y: 0, w: 0.35, h: ALTO, fill: { color: paleta.acento }, line: { color: paleta.acento, width: 0 } });
87
+ s.addText(tituloPresentacion, {
88
+ x: 0.9, y: 1.5, w: 8.2, h: 1.7,
89
+ fontFace: paleta.fuenteTitulo, fontSize: tituloPresentacion.length > 60 ? 32 : 42, bold: true,
90
+ color: paleta.portadaTexto, align: "left", valign: "bottom", fit: "shrink",
81
91
  });
92
+ s.addShape(pres.ShapeType.rect, { x: 0.9, y: 3.4, w: 1.2, h: 0.06, fill: { color: paleta.acento2 }, line: { color: paleta.acento2, width: 0 } });
93
+ if (subtitulo) {
94
+ s.addText(subtitulo, {
95
+ x: 0.9, y: 3.6, w: 8.2, h: 1.0,
96
+ fontFace: paleta.fuenteCuerpo, fontSize: 20, color: paleta.portadaTexto,
97
+ align: "left", valign: "top", fit: "shrink",
98
+ });
99
+ }
82
100
  }
83
101
 
84
- // Diapositivas de contenido
85
- for (const diapoInput of diapositivasInput) {
86
- const slide = pres.addSlide();
87
-
88
- // Título de la diapositiva
89
- if (diapoInput.titulo) {
90
- slide.addText(diapoInput.titulo, {
91
- x: "5%",
92
- y: "5%",
93
- w: "90%",
94
- h: "15%",
95
- fontSize: 24,
96
- bold: true,
97
- color: "363636",
98
- valign: "middle",
102
+ // ─── Diapositivas de contenido ──────────────────────────────────────
103
+ for (const d of diapositivasInput) {
104
+ const s = pres.addSlide();
105
+ s.background = { color: paleta.fondo };
106
+ s.addShape(pres.ShapeType.rect, { x: 0, y: 0, w: 0.18, h: ALTO, fill: { color: paleta.acento }, line: { color: paleta.acento, width: 0 } });
107
+
108
+ if (d.titulo) {
109
+ s.addText(d.titulo, {
110
+ x: 0.6, y: 0.35, w: ANCHO - 1.2, h: 0.9,
111
+ fontFace: paleta.fuenteTitulo, fontSize: d.titulo.length > 55 ? 24 : 30, bold: true,
112
+ color: paleta.titulo, align: "left", valign: "middle", fit: "shrink",
99
113
  });
114
+ s.addShape(pres.ShapeType.rect, { x: 0.6, y: 1.28, w: 0.9, h: 0.06, fill: { color: paleta.acento2 }, line: { color: paleta.acento2, width: 0 } });
100
115
  }
101
116
 
102
- const yContenido = diapoInput.titulo ? "22%" : "10%";
103
- const hContenido = diapoInput.titulo ? "70%" : "82%";
104
-
105
- // Puntos de viñeta (tienen prioridad sobre contenido libre)
106
- if (diapoInput.puntos && diapoInput.puntos.length > 0) {
107
- const textoPuntos = diapoInput.puntos.map((punto) => ({
108
- text: punto,
109
- options: {
110
- bullet: true,
111
- fontSize: 18,
112
- color: "595959",
113
- breakLine: true,
114
- } as any,
115
- }));
116
-
117
- slide.addText(textoPuntos, {
118
- x: "5%",
119
- y: yContenido,
120
- w: "90%",
121
- h: hContenido,
122
- valign: "top",
123
- });
124
- } else if (diapoInput.contenido) {
125
- // Texto libre
126
- slide.addText(diapoInput.contenido, {
127
- x: "5%",
128
- y: yContenido,
129
- w: "90%",
130
- h: hContenido,
131
- fontSize: 16,
132
- color: "595959",
133
- valign: "top",
134
- wrap: true,
117
+ const y = d.titulo ? 1.6 : 0.6;
118
+ const h = ALTO - y - 0.6;
119
+
120
+ if (d.puntos && d.puntos.length > 0) {
121
+ const largoTotal = d.puntos.reduce((a, p) => a + p.length, 0);
122
+ const tam = d.puntos.length > 7 || largoTotal > 520 ? 15 : d.puntos.length > 5 || largoTotal > 360 ? 17 : 20;
123
+ s.addText(
124
+ d.puntos.map((punto) => ({
125
+ text: punto,
126
+ options: { bullet: { indent: 20 }, breakLine: true, paraSpaceAfter: 8 },
127
+ })),
128
+ {
129
+ x: 0.6, y, w: ANCHO - 1.2, h,
130
+ fontFace: paleta.fuenteCuerpo, fontSize: tam, color: paleta.texto,
131
+ valign: "top", fit: "shrink",
132
+ },
133
+ );
134
+ } else if (d.contenido) {
135
+ s.addText(d.contenido, {
136
+ x: 0.6, y, w: ANCHO - 1.2, h,
137
+ fontFace: paleta.fuenteCuerpo, fontSize: d.contenido.length > 600 ? 15 : d.contenido.length > 350 ? 17 : 20,
138
+ color: paleta.texto, valign: "top", paraSpaceAfter: 8, fit: "shrink",
135
139
  });
136
140
  }
137
141
 
138
- // Notas del presentador
139
- if (diapoInput.notas) {
140
- slide.addNotes(diapoInput.notas);
142
+ if (tituloPresentacion) {
143
+ s.addText(tituloPresentacion, {
144
+ x: 0.6, y: ALTO - 0.45, w: 6, h: 0.3,
145
+ fontFace: paleta.fuenteCuerpo, fontSize: 10, color: paleta.texto, transparency: 40, align: "left",
146
+ });
141
147
  }
148
+ s.slideNumber = { x: ANCHO - 1.0, y: ALTO - 0.45, w: 0.6, h: 0.3, fontFace: paleta.fuenteCuerpo, fontSize: 10, color: paleta.acento, align: "right", bold: true };
149
+
150
+ if (d.notas) s.addNotes(d.notas);
142
151
  }
143
152
 
144
153
  const rutaAbsoluta = path.resolve(ruta);
145
154
  const dirDestino = path.dirname(rutaAbsoluta);
146
- if (!fs.existsSync(dirDestino)) {
147
- fs.mkdirSync(dirDestino, { recursive: true });
148
- }
155
+ if (!fs.existsSync(dirDestino)) fs.mkdirSync(dirDestino, { recursive: true });
149
156
 
150
- // Escribir el archivo
151
157
  await pres.writeFile({ fileName: rutaAbsoluta });
152
-
153
158
  const stats = fs.statSync(rutaAbsoluta);
154
159
 
155
- log.info(
156
- `PPTX generado: ${rutaAbsoluta} (${diapositivasInput.length} diapositivas)`
157
- );
160
+ log.info(`PPTX generado: ${rutaAbsoluta} (${diapositivasInput.length} diapositivas)`);
158
161
 
159
162
  return {
160
163
  ok: true,
161
164
  ruta: rutaAbsoluta,
162
- totalDiapositivas:
163
- diapositivasInput.length + (tituloPresentacion ? 1 : 0),
165
+ totalDiapositivas: diapositivasInput.length + (tituloPresentacion ? 1 : 0),
164
166
  bytesEscritos: stats.size,
165
167
  };
166
168
  } catch (error) {
@@ -1,5 +1,13 @@
1
1
  /**
2
- * office_escribir_xlsx - Generar un archivo Excel (.xlsx)
2
+ * office_escribir_xlsx - Generar un archivo Excel (.xlsx) con estilos
3
+ *
4
+ * Mismo modelo que `office_write_xlsx` del SDK de Rust: por hoja, `columnas`
5
+ * fija formato (fecha, moneda, porcentaje…), ancho, negrita, color, relleno,
6
+ * alineación y ajuste de texto; `estilo_encabezado` da estilo a la primera fila,
7
+ * `congelar_encabezado` la fija y `autofiltro` añade los botones de filtro.
8
+ * Por defecto el encabezado sale con estilo, la fila fija y los anchos se
9
+ * ajustan al contenido. Las celdas son siempre valores: un texto que empieza
10
+ * por «=» nunca se evalúa como fórmula.
3
11
  *
4
12
  * @category office
5
13
  * @seedId office_escribir_xlsx
@@ -10,39 +18,105 @@ import type { Tool } from "../types.ts";
10
18
  import { logger } from "../../utils/logger.ts";
11
19
  import * as path from "node:path";
12
20
  import * as fs from "node:fs";
13
- import { cargarXlsx } from "./xlsx-loader";
21
+ import { hexValido } from "./office-style";
14
22
 
15
23
  const log = logger.child("office-escribir-xlsx");
16
24
 
25
+ interface ColumnaInput {
26
+ columna: string | number;
27
+ formato?: string;
28
+ ancho?: number;
29
+ negrita?: boolean;
30
+ color?: string;
31
+ relleno?: string;
32
+ alineacion?: "left" | "center" | "right" | "izquierda" | "centro" | "derecha";
33
+ ajustar?: boolean;
34
+ }
35
+
17
36
  interface HojaInput {
18
37
  nombre: string;
19
38
  datos: Record<string, any>[] | any[][];
20
39
  encabezados?: string[];
40
+ columnas?: ColumnaInput[];
41
+ estilo_encabezado?: { negrita?: boolean; color?: string; relleno?: string; alineacion?: string };
42
+ congelar_encabezado?: boolean;
43
+ autofiltro?: boolean;
44
+ }
45
+
46
+ const FORMATOS: Record<string, string> = {
47
+ date: "yyyy-mm-dd", fecha: "yyyy-mm-dd",
48
+ datetime: "yyyy-mm-dd hh:mm:ss", fecha_hora: "yyyy-mm-dd hh:mm:ss",
49
+ time: "hh:mm:ss", hora: "hh:mm:ss",
50
+ integer: "0", entero: "0",
51
+ decimal: "0.00",
52
+ thousands: "#,##0", miles: "#,##0",
53
+ percent: "0.00%", porcentaje: "0.00%",
54
+ currency: '"$"#,##0.00', moneda: '"$"#,##0.00',
55
+ text: "@", texto: "@",
56
+ };
57
+ const ES_FECHA = new Set(["date", "fecha", "datetime", "fecha_hora", "time", "hora"]);
58
+
59
+ const ISO = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2}))?)?$/;
60
+ const ISO_HORA = /^(\d{2}):(\d{2})(?::(\d{2}))?$/;
61
+
62
+ /** Fecha ISO → Date en UTC (Excel guarda la fecha sin zona; así no se corre un día). */
63
+ function aFecha(valor: unknown): Date | null {
64
+ if (typeof valor !== "string") return null;
65
+ const t = ISO.exec(valor.trim());
66
+ if (t) return new Date(Date.UTC(+t[1]!, +t[2]! - 1, +t[3]!, +(t[4] ?? 0), +(t[5] ?? 0), +(t[6] ?? 0)));
67
+ const h = ISO_HORA.exec(valor.trim());
68
+ if (h) return new Date(Date.UTC(1899, 11, 30, +h[1]!, +h[2]!, +(h[3] ?? 0)));
69
+ return null;
70
+ }
71
+
72
+ const alineacionExcel = (a?: string): "left" | "center" | "right" | undefined =>
73
+ a === "center" || a === "centro" ? "center" : a === "right" || a === "derecha" ? "right" : a === "left" || a === "izquierda" ? "left" : undefined;
74
+
75
+ const relleno = (hex: string) => ({ type: "pattern" as const, pattern: "solid" as const, fgColor: { argb: `FF${hex}` } });
76
+
77
+ /** Largo aproximado del texto que Excel mostrará, para dimensionar la columna. */
78
+ function largoVisible(v: unknown, formato?: string): number {
79
+ if (v === null || v === undefined) return 0;
80
+ if (v instanceof Date) return formato === "datetime" || formato === "fecha_hora" ? 19 : 12;
81
+ if (typeof v === "number") {
82
+ const f = formato ?? "";
83
+ if (/^(currency|moneda)$/.test(f) || f.includes("$")) return `$${v.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`.length + 1;
84
+ if (/^(percent|porcentaje)$/.test(f)) return `${(v * 100).toFixed(2)}%`.length;
85
+ if (/^(thousands|miles)$/.test(f)) return v.toLocaleString("en-US").length;
86
+ if (f === "decimal") return v.toFixed(2).length;
87
+ return String(v).length;
88
+ }
89
+ return String(v).length;
90
+ }
91
+
92
+ function letraDeColumna(n: number): string {
93
+ let s = "";
94
+ for (let i = n; i > 0; i = Math.floor((i - 1) / 26)) s = String.fromCharCode(65 + ((i - 1) % 26)) + s;
95
+ return s;
21
96
  }
22
97
 
23
98
  export const officeEscribirXlsxTool: Tool = {
24
99
  name: "office_escribir_xlsx",
25
100
  description:
26
- "Generar un archivo Excel (.xlsx) desde un objeto JSON con hojas, filas y columnas. Spanish: crear excel, generar xlsx, escribir excel, exportar a xlsx",
101
+ "Generar un archivo Excel (.xlsx) con estilo desde hojas de objetos o de arrays. La primera fila es el encabezado (se estiliza, se fija y recibe autofiltro por defecto). Por hoja, `columnas` fija formato (fecha, fecha_hora, hora, entero, decimal, miles, porcentaje, moneda, texto o un código de formato de Excel; los textos ISO como 2025-03-01 en una columna de fecha se guardan como fechas reales), ancho, negrita, color, relleno, alineacion y ajustar para una columna indicada por el texto de su encabezado o su índice. Colores #RRGGBB. Las celdas son siempre valores: un texto que empieza por = nunca es fórmula. Spanish: crear excel, generar xlsx, escribir excel, exportar a xlsx, hoja de cálculo, reporte",
27
102
  parameters: {
28
103
  type: "object",
29
104
  properties: {
30
- ruta: {
31
- type: "string",
32
- description: "Ruta donde guardar el archivo .xlsx generado",
33
- },
105
+ ruta: { type: "string", description: "Ruta donde guardar el archivo .xlsx generado" },
34
106
  hojas: {
35
107
  type: "array",
36
108
  description:
37
- "Array de hojas a crear. Cada hoja tiene: nombre (string), datos (array de objetos o array de arrays), encabezados (string[], opcional para forzar orden de columnas)",
109
+ "Hojas a crear. Cada una: nombre, datos (array de objetos o array de arrays), encabezados (orden de columnas, opcional), columnas ([{columna, formato, ancho, negrita, color, relleno, alineacion, ajustar}]), estilo_encabezado ({negrita, color, relleno, alineacion}), congelar_encabezado (default true), autofiltro (default true)",
38
110
  items: {
39
111
  type: "object",
40
112
  properties: {
41
113
  nombre: { type: "string" },
42
- // datos puede ser array de objetos o array de arrays (aoa) — el tool
43
- // acepta ambos en runtime (ver Array.isArray(datos[0]) más abajo).
44
114
  datos: { type: "array", items: { type: "object" } },
45
115
  encabezados: { type: "array", items: { type: "string" } },
116
+ columnas: { type: "array", items: { type: "object" } },
117
+ estilo_encabezado: { type: "object" },
118
+ congelar_encabezado: { type: "boolean" },
119
+ autofiltro: { type: "boolean" },
46
120
  },
47
121
  },
48
122
  },
@@ -56,49 +130,131 @@ export const officeEscribirXlsxTool: Tool = {
56
130
  log.debug(`Generando XLSX: ${ruta}`);
57
131
 
58
132
  try {
59
- const XLSX = await cargarXlsx();
133
+ if (!Array.isArray(hojasInput) || hojasInput.length === 0) {
134
+ return { ok: false, error: "`hojas` debe tener al menos una hoja." };
135
+ }
136
+ const ExcelJS = (await import("exceljs")).default;
137
+ const libro = new ExcelJS.Workbook();
138
+ libro.creator = "Hive Agent";
139
+ libro.created = new Date();
60
140
 
61
- const workbook = XLSX.utils.book_new();
141
+ let totalFilas = 0;
142
+ const usados = new Set<string>();
62
143
 
63
144
  for (const hojaInput of hojasInput) {
64
- let worksheet: any;
65
-
66
- if (
67
- hojasInput.length > 0 &&
68
- Array.isArray(hojaInput.datos) &&
69
- hojaInput.datos.length > 0 &&
70
- Array.isArray(hojaInput.datos[0])
71
- ) {
72
- // Si los datos son array de arrays
73
- worksheet = XLSX.utils.aoa_to_sheet(hojaInput.datos as any[][]);
145
+ let nombre = String(hojaInput.nombre ?? "Hoja").replace(/[\\/?*[\]:]/g, " ").slice(0, 31).trim() || "Hoja";
146
+ for (let n = 2; usados.has(nombre.toLowerCase()); n++) nombre = `${nombre.slice(0, 28)} ${n}`;
147
+ usados.add(nombre.toLowerCase());
148
+
149
+ const datos = Array.isArray(hojaInput.datos) ? hojaInput.datos : [];
150
+ const hoja = libro.addWorksheet(nombre);
151
+
152
+ // Matriz de filas: la primera es el encabezado.
153
+ let matriz: unknown[][];
154
+ if (datos.length > 0 && Array.isArray(datos[0])) {
155
+ matriz = datos as unknown[][];
156
+ if (hojaInput.encabezados?.length) matriz = [hojaInput.encabezados, ...matriz];
74
157
  } else {
75
- // Si los datos son array de objetos
76
- worksheet = XLSX.utils.json_to_sheet(
77
- hojaInput.datos as Record<string, any>[],
78
- hojaInput.encabezados ? { header: hojaInput.encabezados } : undefined
79
- );
158
+ const objetos = datos as Record<string, unknown>[];
159
+ const claves = hojaInput.encabezados?.length
160
+ ? hojaInput.encabezados
161
+ : [...new Set(objetos.flatMap((o) => Object.keys(o ?? {})))];
162
+ matriz = [claves, ...objetos.map((o) => claves.map((k) => (o ?? {})[k]))];
163
+ }
164
+ const encabezados = (matriz[0] ?? []).map((c) => String(c ?? ""));
165
+ const nCols = Math.max(1, ...matriz.map((f) => f.length));
166
+
167
+ // Resolución de columnas (por texto del encabezado o por índice, desde 0).
168
+ const reglas = new Map<number, ColumnaInput>();
169
+ for (const c of hojaInput.columnas ?? []) {
170
+ const idx = typeof c.columna === "number" ? c.columna : encabezados.indexOf(String(c.columna));
171
+ if (idx >= 0 && idx < nCols) reglas.set(idx, c);
172
+ }
173
+
174
+ matriz.forEach((fila, i) => {
175
+ const valores = Array.from({ length: nCols }, (_, c) => {
176
+ const v = fila[c];
177
+ if (v === null || v === undefined) return null;
178
+ if (i > 0) {
179
+ const formato = reglas.get(c)?.formato;
180
+ if (formato && ES_FECHA.has(formato)) return aFecha(v) ?? v;
181
+ }
182
+ if (v instanceof Date || typeof v === "number" || typeof v === "boolean") return v;
183
+ if (typeof v === "object") return JSON.stringify(v);
184
+ return String(v); // texto: nunca fórmula
185
+ });
186
+ hoja.addRow(valores as any);
187
+ });
188
+
189
+ // Anchos: los de `columnas`, o ajustados al contenido (con tope).
190
+ for (let c = 0; c < nCols; c++) {
191
+ const regla = reglas.get(c);
192
+ let ancho = regla?.ancho;
193
+ if (!ancho) {
194
+ let max = 6;
195
+ for (const f of matriz) {
196
+ const v = f[c];
197
+ const largo = largoVisible(v, regla?.formato);
198
+ if (largo > max) max = largo;
199
+ }
200
+ ancho = Math.min(60, Math.ceil(max * (regla?.negrita ? 1.15 : 1.05)) + 3);
201
+ }
202
+ hoja.getColumn(c + 1).width = ancho;
203
+ }
204
+
205
+ // Estilo por columna (celdas de datos).
206
+ for (const [idx, r] of reglas) {
207
+ const formato = r.formato ? (FORMATOS[r.formato] ?? r.formato) : undefined;
208
+ for (let f = 2; f <= matriz.length; f++) {
209
+ const celda = hoja.getCell(f, idx + 1);
210
+ if (formato) celda.numFmt = formato;
211
+ const color = hexValido(r.color);
212
+ if (r.negrita || color) celda.font = { name: "Calibri", size: 11, bold: r.negrita, color: color ? { argb: `FF${color}` } : undefined };
213
+ const fondo = hexValido(r.relleno);
214
+ if (fondo) celda.fill = relleno(fondo);
215
+ const al = alineacionExcel(r.alineacion);
216
+ if (al || r.ajustar) celda.alignment = { horizontal: al, wrapText: r.ajustar, vertical: r.ajustar ? "top" : undefined };
217
+ }
80
218
  }
81
219
 
82
- XLSX.utils.book_append_sheet(workbook, worksheet, hojaInput.nombre);
220
+ // Encabezado: con estilo por defecto (el usuario puede cambiarlo).
221
+ const eh = hojaInput.estilo_encabezado ?? {};
222
+ const ehFondo = hexValido(eh.relleno) ?? "1E293B";
223
+ const ehColor = hexValido(eh.color) ?? "FFFFFF";
224
+ const fila1 = hoja.getRow(1);
225
+ fila1.height = 22;
226
+ for (let c = 1; c <= nCols; c++) {
227
+ const celda = fila1.getCell(c);
228
+ celda.font = { name: "Calibri", size: 11, bold: eh.negrita !== false, color: { argb: `FF${ehColor}` } };
229
+ celda.fill = relleno(ehFondo);
230
+ celda.alignment = { horizontal: alineacionExcel(eh.alineacion) ?? alineacionExcel(reglas.get(c - 1)?.alineacion) ?? "left", vertical: "middle", wrapText: true };
231
+ }
232
+ // Bordes finos en toda la tabla, para que se lea como tabla.
233
+ for (let f = 1; f <= matriz.length; f++) {
234
+ for (let c = 1; c <= nCols; c++) {
235
+ const lado = { style: "thin" as const, color: { argb: "FFCBD5E1" } };
236
+ hoja.getCell(f, c).border = { top: lado, left: lado, bottom: lado, right: lado };
237
+ }
238
+ }
239
+
240
+ if (hojaInput.congelar_encabezado !== false && matriz.length > 1) {
241
+ hoja.views = [{ state: "frozen", ySplit: 1 }];
242
+ }
243
+ if (hojaInput.autofiltro !== false && matriz.length > 1) {
244
+ hoja.autoFilter = { from: "A1", to: `${letraDeColumna(nCols)}1` };
245
+ }
246
+
247
+ totalFilas += Math.max(0, matriz.length - 1);
83
248
  }
84
249
 
85
250
  const rutaAbsoluta = path.resolve(ruta);
86
251
  const dirDestino = path.dirname(rutaAbsoluta);
87
- if (!fs.existsSync(dirDestino)) {
88
- fs.mkdirSync(dirDestino, { recursive: true });
89
- }
252
+ if (!fs.existsSync(dirDestino)) fs.mkdirSync(dirDestino, { recursive: true });
90
253
 
91
- const buffer = XLSX.write(workbook, { type: "buffer", bookType: "xlsx" });
254
+ const buffer = Buffer.from(await libro.xlsx.writeBuffer());
92
255
  fs.writeFileSync(rutaAbsoluta, buffer);
93
256
 
94
- const totalFilas = hojasInput.reduce(
95
- (acc, h) => acc + h.datos.length,
96
- 0
97
- );
98
-
99
- log.info(
100
- `XLSX generado: ${rutaAbsoluta} (${hojasInput.length} hojas, ${totalFilas} filas)`
101
- );
257
+ log.info(`XLSX generado: ${rutaAbsoluta} (${hojasInput.length} hojas, ${totalFilas} filas)`);
102
258
 
103
259
  return {
104
260
  ok: true,