@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
@@ -6,6 +6,7 @@
6
6
  * @spanish leer word, abrir docx, extraer texto de word, contenido word
7
7
  */
8
8
 
9
+ import { resolveOfficeInput, ARTIFACT_ID_PARAM } from "./resolve-input.ts";
9
10
  import type { Tool } from "../types.ts";
10
11
  import { logger } from "../../utils/logger.ts";
11
12
  import * as fs from "node:fs";
@@ -20,6 +21,7 @@ export const officeLeerDocxTool: Tool = {
20
21
  parameters: {
21
22
  type: "object",
22
23
  properties: {
24
+ artifact_id: ARTIFACT_ID_PARAM,
23
25
  ruta: {
24
26
  type: "string",
25
27
  description: "Ruta absoluta o relativa al archivo .docx",
@@ -29,10 +31,12 @@ export const officeLeerDocxTool: Tool = {
29
31
  description: "Incluir contenido de tablas en la extracción (default: true)",
30
32
  },
31
33
  },
32
- required: ["ruta"],
34
+ required: [],
33
35
  },
34
36
  execute: async (params: Record<string, unknown>) => {
35
- const ruta = params.ruta as string;
37
+ const entrada = await resolveOfficeInput(params);
38
+ if ("error" in entrada) return { ok: false, error: entrada.error };
39
+ const ruta = entrada.ruta;
36
40
  const incluirTablas = (params.incluir_tablas as boolean) ?? true;
37
41
 
38
42
  log.debug(`Leyendo DOCX: ${ruta}`);
@@ -6,6 +6,8 @@
6
6
  * @spanish leer pdf, abrir pdf, extraer texto de pdf, contenido pdf
7
7
  */
8
8
 
9
+ import { extraerTextoPdf } from "./pdf-text.ts";
10
+ import { resolveOfficeInput, ARTIFACT_ID_PARAM } from "./resolve-input.ts";
9
11
  import type { Tool } from "../types.ts";
10
12
  import { logger } from "../../utils/logger.ts";
11
13
  import * as fs from "node:fs";
@@ -13,13 +15,16 @@ import * as path from "node:path";
13
15
 
14
16
  const log = logger.child("office-leer-pdf");
15
17
 
18
+ const DEFAULT_MAX_CHARS = 40_000;
19
+
16
20
  export const officeLeerPdfTool: Tool = {
17
21
  name: "office_leer_pdf",
18
22
  description:
19
- "Leer contenido de un archivo PDF y retornar texto plano con metadata. Spanish: leer pdf, abrir pdf, extraer texto de pdf, pdf a texto",
23
+ "Leer el texto de un PDF (capa de texto nativa, sin OCR ni modelos), conservando renglones y columnas, por páginas y con tope de tamaño. Un PDF escaneado devuelve aviso en vez de texto. Spanish: leer pdf, abrir pdf, extraer texto de pdf, pdf a texto",
20
24
  parameters: {
21
25
  type: "object",
22
26
  properties: {
27
+ artifact_id: ARTIFACT_ID_PARAM,
23
28
  ruta: {
24
29
  type: "string",
25
30
  description: "Ruta absoluta o relativa al archivo PDF",
@@ -30,15 +35,22 @@ export const officeLeerPdfTool: Tool = {
30
35
  },
31
36
  pagina_fin: {
32
37
  type: "number",
33
- description: "Última página a leer (default: todas las páginas)",
38
+ description: "Última página a leer (default: hasta donde quepa en max_caracteres)",
39
+ },
40
+ max_caracteres: {
41
+ type: "number",
42
+ description: "Tope de caracteres por llamada (default 40000). Si hay más, la respuesta trae siguiente_pagina para continuar.",
34
43
  },
35
44
  },
36
- required: ["ruta"],
45
+ required: [],
37
46
  },
38
47
  execute: async (params: Record<string, unknown>) => {
39
- const ruta = params.ruta as string;
40
- const paginaInicio = Math.max(1, (params.pagina_inicio as number) ?? 1);
41
- const paginaFin = params.pagina_fin as number | undefined;
48
+ const entrada = await resolveOfficeInput(params);
49
+ if ("error" in entrada) return { ok: false, error: entrada.error };
50
+ const ruta = entrada.ruta;
51
+ const paginaInicio = Math.max(1, Number(params.pagina_inicio) || 1);
52
+ const paginaFin = params.pagina_fin ? Number(params.pagina_fin) : undefined;
53
+ const maxCaracteres = Math.min(Math.max(Number(params.max_caracteres) || DEFAULT_MAX_CHARS, 1000), 200_000);
42
54
 
43
55
  log.debug(`Leyendo PDF: ${ruta}`);
44
56
 
@@ -47,61 +59,33 @@ export const officeLeerPdfTool: Tool = {
47
59
  if (!fs.existsSync(rutaAbsoluta)) {
48
60
  return { ok: false, error: `Archivo no encontrado: ${rutaAbsoluta}` };
49
61
  }
50
-
51
- const buffer = fs.readFileSync(rutaAbsoluta);
52
- const uint8Array = new Uint8Array(buffer);
53
-
54
- // Importar pdfjs-dist (compatible con Bun, sin worker)
55
- const pdfjsLib = await import("pdfjs-dist/legacy/build/pdf.mjs" as any).catch(
56
- () => import("pdfjs-dist" as any)
57
- );
58
-
59
- // Desactivar worker para entorno Node/Bun
60
- const lib = pdfjsLib.default ?? pdfjsLib;
61
- if (lib.GlobalWorkerOptions) {
62
- lib.GlobalWorkerOptions.workerSrc = "";
63
- }
64
-
65
- const doc = await lib.getDocument({ data: uint8Array, disableWorker: true }).promise;
66
- const totalPaginas = doc.numPages;
67
-
68
- // Metadata
69
- let titulo: string | undefined;
70
- try {
71
- const meta = await doc.getMetadata();
72
- titulo = (meta?.info as any)?.Title ?? undefined;
73
- } catch {
74
- // metadata opcional
75
- }
76
-
77
- const inicio = paginaInicio;
78
- const fin = paginaFin ? Math.min(paginaFin, totalPaginas) : totalPaginas;
79
-
80
- const textosPorPagina: Array<{ pagina: number; texto: string }> = [];
81
-
82
- for (let i = inicio; i <= fin; i++) {
83
- const pagina = await doc.getPage(i);
84
- const contenido = await pagina.getTextContent();
85
- const texto = (contenido.items as any[])
86
- .map((item: any) => item.str ?? "")
87
- .join(" ")
88
- .replace(/\s+/g, " ")
89
- .trim();
90
- textosPorPagina.push({ pagina: i, texto });
62
+ const r = await extraerTextoPdf(new Uint8Array(fs.readFileSync(rutaAbsoluta)), {
63
+ desde: paginaInicio, hasta: paginaFin, maxCaracteres,
64
+ });
65
+ log.info(`PDF leído: ${r.paginasLeidas}/${r.totalPaginas} páginas, ${r.texto.length} caracteres`);
66
+
67
+ if (r.sinTexto) {
68
+ return {
69
+ ok: true,
70
+ ruta: rutaAbsoluta,
71
+ totalPaginas: r.totalPaginas,
72
+ paginasLeidas: r.paginasLeidas,
73
+ texto: "",
74
+ aviso: "Estas páginas no tienen texto extraíble: el PDF parece escaneado (solo imágenes). Esta herramienta no hace OCR; pídele al usuario el documento en formato editable o que copie el texto.",
75
+ };
91
76
  }
92
-
93
- const textoCompleto = textosPorPagina.map((p) => p.texto).join("\n\n");
94
-
95
- log.info(`PDF leído: ${totalPaginas} páginas, ${textoCompleto.length} caracteres`);
96
-
77
+ const vacias = r.caracteresPorPagina.filter((c) => c === 0).length;
97
78
  return {
98
79
  ok: true,
99
80
  ruta: rutaAbsoluta,
100
- totalPaginas,
101
- paginasLeidas: fin - inicio + 1,
102
- titulo,
103
- texto: textoCompleto,
104
- paginas: textosPorPagina,
81
+ totalPaginas: r.totalPaginas,
82
+ paginasLeidas: r.paginasLeidas,
83
+ titulo: r.titulo,
84
+ texto: r.texto,
85
+ ...(r.truncado || r.siguientePagina
86
+ ? { truncado: r.truncado, siguiente_pagina: r.siguientePagina, aviso: `Hay más contenido: vuelve a llamar con pagina_inicio=${r.siguientePagina}.` }
87
+ : {}),
88
+ ...(vacias ? { paginas_sin_texto: vacias } : {}),
105
89
  };
106
90
  } catch (error) {
107
91
  log.error(`Error leyendo PDF: ${(error as Error).message}`);
@@ -1,11 +1,16 @@
1
1
  /**
2
2
  * office_leer_pptx - Leer contenido de un archivo PowerPoint (.pptx)
3
3
  *
4
+ * Texto nativo por diapositiva (un párrafo por línea), en el orden real de la
5
+ * presentación y con las notas del orador. Sin modelos.
6
+ *
4
7
  * @category office
5
8
  * @seedId office_leer_pptx
6
9
  * @spanish leer powerpoint, abrir pptx, extraer texto de presentacion, contenido slides
7
10
  */
8
11
 
12
+ import { resolveOfficeInput, ARTIFACT_ID_PARAM } from "./resolve-input.ts";
13
+ import { listarSlides, textoDeXml, tituloDeXml, archivoDeNotas } from "./pptx-slides.ts";
9
14
  import type { Tool } from "../types.ts";
10
15
  import { logger } from "../../utils/logger.ts";
11
16
  import * as fs from "node:fs";
@@ -13,124 +18,82 @@ import * as path from "node:path";
13
18
 
14
19
  const log = logger.child("office-leer-pptx");
15
20
 
21
+ const DEFAULT_MAX_CHARS = 40_000;
22
+
16
23
  export const officeLeerPptxTool: Tool = {
17
24
  name: "office_leer_pptx",
18
25
  description:
19
- "Leer un archivo PowerPoint (.pptx) y retornar el texto de cada diapositiva como array estructurado. Spanish: leer powerpoint, abrir pptx, extraer texto de presentacion, contenido slides",
26
+ "Leer un PowerPoint (.pptx): texto de cada diapositiva en su orden real, con título y notas del orador, con tope de tamaño. Spanish: leer powerpoint, abrir pptx, extraer texto de presentacion, contenido slides",
20
27
  parameters: {
21
28
  type: "object",
22
29
  properties: {
30
+ artifact_id: ARTIFACT_ID_PARAM,
23
31
  ruta: {
24
32
  type: "string",
25
33
  description: "Ruta absoluta o relativa al archivo .pptx",
26
34
  },
27
35
  solo_diapositiva: {
28
36
  type: "number",
29
- description:
30
- "Número de diapositiva específica a leer (1-indexed, default: todas)",
37
+ description: "Número de diapositiva específica a leer (1-indexed, default: todas)",
38
+ },
39
+ max_caracteres: {
40
+ type: "number",
41
+ description: "Tope de caracteres por llamada (default 40000). Si hay más, trae siguiente_diapositiva para continuar.",
42
+ },
43
+ desde_diapositiva: {
44
+ type: "number",
45
+ description: "Diapositiva desde la que empezar a leer (default 1), para continuar tras un corte.",
31
46
  },
32
47
  },
33
- required: ["ruta"],
48
+ required: [],
34
49
  },
35
50
  execute: async (params: Record<string, unknown>) => {
36
- const ruta = params.ruta as string;
37
- const soloSlide = params.solo_diapositiva as number | undefined;
51
+ const entrada = await resolveOfficeInput(params);
52
+ if ("error" in entrada) return { ok: false, error: entrada.error };
53
+ const soloSlide = params.solo_diapositiva ? Number(params.solo_diapositiva) : undefined;
54
+ const desde = Math.max(1, Number(params.desde_diapositiva) || 1);
55
+ const tope = Math.min(Math.max(Number(params.max_caracteres) || DEFAULT_MAX_CHARS, 1000), 200_000);
38
56
 
39
- log.debug(`Leyendo PPTX: ${ruta}`);
57
+ log.debug(`Leyendo PPTX: ${entrada.ruta}`);
40
58
 
41
59
  try {
42
- const rutaAbsoluta = path.resolve(ruta);
43
- if (!fs.existsSync(rutaAbsoluta)) {
44
- return { ok: false, error: `Archivo no encontrado: ${rutaAbsoluta}` };
45
- }
60
+ const rutaAbsoluta = path.resolve(entrada.ruta);
61
+ if (!fs.existsSync(rutaAbsoluta)) return { ok: false, error: `Archivo no encontrado: ${rutaAbsoluta}` };
46
62
 
47
63
  const JSZip = (await import("jszip")).default;
48
- const buffer = fs.readFileSync(rutaAbsoluta);
49
- const zip = await JSZip.loadAsync(buffer);
50
-
51
- // Encontrar todos los archivos de slides
52
- const archivosSlides = Object.keys(zip.files)
53
- .filter((nombre) => /^ppt\/slides\/slide\d+\.xml$/i.test(nombre))
54
- .sort((a, b) => {
55
- const numA = parseInt(a.match(/slide(\d+)/)?.[1] ?? "0");
56
- const numB = parseInt(b.match(/slide(\d+)/)?.[1] ?? "0");
57
- return numA - numB;
58
- });
59
-
60
- const diapositivas: Array<{
61
- numero: number;
62
- titulo?: string;
63
- texto: string;
64
- fragmentos: string[];
65
- }> = [];
66
-
67
- for (let i = 0; i < archivosSlides.length; i++) {
68
- const numeroSlide = i + 1;
69
-
70
- if (soloSlide !== undefined && numeroSlide !== soloSlide) {
71
- continue;
72
- }
73
-
74
- const archivoSlide = archivosSlides[i];
75
- const xmlContenido = await zip.files[archivoSlide].async("string");
76
-
77
- // Extraer texto de elementos <a:t> (texto en slides de OOXML)
78
- const fragmentos: string[] = [];
79
- const regexTexto = /<a:t[^>]*>([\s\S]*?)<\/a:t>/g;
80
- let match;
81
-
82
- while ((match = regexTexto.exec(xmlContenido)) !== null) {
83
- const texto = match[1]
84
- .replace(/&amp;/g, "&")
85
- .replace(/&lt;/g, "<")
86
- .replace(/&gt;/g, ">")
87
- .replace(/&quot;/g, '"')
88
- .replace(/&apos;/g, "'")
89
- .trim();
90
-
91
- if (texto) {
92
- fragmentos.push(texto);
93
- }
94
- }
95
-
96
- // Intentar extraer el título (elemento <p:sp> con tipo "title")
97
- let titulo: string | undefined;
98
- const regexTitulo =
99
- /<p:ph[^>]*type="title"[^>]*\/>[\s\S]*?<a:t[^>]*>([\s\S]*?)<\/a:t>/;
100
- const matchTitulo = regexTitulo.exec(xmlContenido);
101
- if (matchTitulo) {
102
- titulo = matchTitulo[1].trim();
103
- } else if (fragmentos.length > 0) {
104
- // Primer fragmento como título tentativo
105
- titulo = fragmentos[0];
106
- }
107
-
108
- const texto = fragmentos.join(" ").replace(/\s+/g, " ").trim();
109
-
110
- diapositivas.push({
111
- numero: numeroSlide,
112
- titulo,
113
- texto,
114
- fragmentos,
115
- });
64
+ const zip = await JSZip.loadAsync(fs.readFileSync(rutaAbsoluta)).catch(() => {
65
+ throw new Error("El archivo no es un .pptx válido o está dañado.");
66
+ });
67
+ const slides = await listarSlides(zip);
68
+
69
+ const diapositivas: Array<{ numero: number; titulo?: string; texto: string; notas?: string }> = [];
70
+ let usados = 0;
71
+ let siguiente: number | undefined;
72
+
73
+ for (const slide of slides) {
74
+ if (soloSlide !== undefined ? slide.numero !== soloSlide : slide.numero < desde) continue;
75
+ const xml = await zip.file(slide.archivo)!.async("string");
76
+ const texto = textoDeXml(xml);
77
+ const archivoNotas = await archivoDeNotas(zip, slide);
78
+ const notas = archivoNotas ? textoDeXml(await zip.file(archivoNotas)!.async("string")) : "";
79
+ const item = { numero: slide.numero, titulo: tituloDeXml(xml, texto), texto, ...(notas ? { notas } : {}) };
80
+ const tam = JSON.stringify(item).length;
81
+ if (diapositivas.length > 0 && usados + tam > tope) { siguiente = slide.numero; break; }
82
+ diapositivas.push(item);
83
+ usados += tam;
116
84
  }
117
85
 
118
- log.info(
119
- `PPTX leído: ${archivosSlides.length} slides totales, ${diapositivas.length} leídas`
120
- );
121
-
86
+ log.info(`PPTX leído: ${slides.length} slides totales, ${diapositivas.length} leídas`);
122
87
  return {
123
88
  ok: true,
124
89
  ruta: rutaAbsoluta,
125
- totalDiapositivas: archivosSlides.length,
90
+ totalDiapositivas: slides.length,
126
91
  diapositivas,
92
+ ...(siguiente ? { truncado: true, siguiente_diapositiva: siguiente, aviso: `Hay más diapositivas: vuelve a llamar con desde_diapositiva=${siguiente}.` } : {}),
127
93
  };
128
94
  } catch (error) {
129
95
  log.error(`Error leyendo PPTX: ${(error as Error).message}`);
130
- return {
131
- ok: false,
132
- error: `No se pudo leer el archivo PowerPoint: ${(error as Error).message}`,
133
- };
96
+ return { ok: false, error: `No se pudo leer el PPTX: ${(error as Error).message}` };
134
97
  }
135
98
  },
136
99
  };
@@ -6,6 +6,7 @@
6
6
  * @spanish leer excel, abrir xlsx, extraer datos de excel, hojas excel
7
7
  */
8
8
 
9
+ import { resolveOfficeInput, ARTIFACT_ID_PARAM } from "./resolve-input.ts";
9
10
  import type { Tool } from "../types.ts";
10
11
  import { logger } from "../../utils/logger.ts";
11
12
  import * as fs from "node:fs";
@@ -21,6 +22,7 @@ export const officeLeerXlsxTool: Tool = {
21
22
  parameters: {
22
23
  type: "object",
23
24
  properties: {
25
+ artifact_id: ARTIFACT_ID_PARAM,
24
26
  ruta: {
25
27
  type: "string",
26
28
  description: "Ruta absoluta o relativa al archivo .xlsx",
@@ -40,10 +42,12 @@ export const officeLeerXlsxTool: Tool = {
40
42
  "Rango de celdas a leer en notación Excel (ej: 'A1:D10', default: toda la hoja)",
41
43
  },
42
44
  },
43
- required: ["ruta"],
45
+ required: [],
44
46
  },
45
47
  execute: async (params: Record<string, unknown>) => {
46
- const ruta = params.ruta as string;
48
+ const entrada = await resolveOfficeInput(params);
49
+ if ("error" in entrada) return { ok: false, error: entrada.error };
50
+ const ruta = entrada.ruta;
47
51
  const hojaFiltro = params.hoja as string | undefined;
48
52
  const incluirEncabezados = (params.incluir_encabezados as boolean) ?? true;
49
53
  const rango = params.rango as string | undefined;
@@ -0,0 +1,186 @@
1
+ /**
2
+ * Extracción de texto de PDF sin modelos: solo la capa de texto del archivo
3
+ * (pdfjs). Reconstruye renglones y columnas a partir de las posiciones, en vez
4
+ * de aplastar todo en una línea, para que tablas y párrafos sigan legibles.
5
+ *
6
+ * Un PDF escaneado no tiene capa de texto: aquí se informa como tal
7
+ * (`sinTexto`) y no se intenta adivinar con un modelo.
8
+ */
9
+
10
+ export interface PdfTextResult {
11
+ totalPaginas: number
12
+ paginasLeidas: number
13
+ titulo?: string
14
+ texto: string
15
+ /** Caracteres de texto por página leída (sirve para ver cuáles están vacías). */
16
+ caracteresPorPagina: number[]
17
+ /** true si ninguna de las páginas leídas tiene texto extraíble (PDF escaneado o solo imágenes). */
18
+ sinTexto: boolean
19
+ /** true si se cortó por el tope de caracteres. */
20
+ truncado: boolean
21
+ /** Primera página que no se llegó a leer (para continuar), si hubo corte o rango. */
22
+ siguientePagina?: number
23
+ }
24
+
25
+ const MAX_PDF_BYTES = 100 * 1024 * 1024
26
+
27
+ /**
28
+ * pdfjs v5 sin worker real monta uno "falso" en el mismo hilo, y para eso exige
29
+ * `workerSrc` no vacío o el módulo ya cargado en `globalThis.pdfjsWorker`. Dejar
30
+ * `workerSrc = ""` (como hacía la tool) lo rompe: "No GlobalWorkerOptions.workerSrc
31
+ * specified". Registrar el módulo evita depender de rutas de archivo, que además
32
+ * cambian en el binario empaquetado.
33
+ */
34
+ let workerListo = false
35
+
36
+ /**
37
+ * pdfjs hace referencia a DOMMatrix, ImageData y Path2D al cargarse. En desarrollo se
38
+ * las presta `@napi-rs/canvas`, pero en el ejecutable compilado (app de escritorio,
39
+ * paquete) ese módulo no existe y la carga muere con «DOMMatrix is not defined». Para
40
+ * extraer texto no hace falta dibujar nada: bastan clases mínimas, solo si faltan.
41
+ */
42
+ function instalarPolyfillsPdf(): void {
43
+ const g = globalThis as any
44
+ if (typeof g.DOMMatrix === "undefined") {
45
+ g.DOMMatrix = class DOMMatrix {
46
+ a = 1; b = 0; c = 0; d = 1; e = 0; f = 0
47
+ constructor(init?: ArrayLike<number> | string) {
48
+ if (init && typeof init !== "string" && init.length >= 6) {
49
+ [this.a, this.b, this.c, this.d, this.e, this.f] = Array.from(init)
50
+ }
51
+ }
52
+ multiplySelf(): this { return this }
53
+ preMultiplySelf(): this { return this }
54
+ translateSelf(): this { return this }
55
+ scaleSelf(): this { return this }
56
+ invertSelf(): this { return this }
57
+ }
58
+ }
59
+ if (typeof g.ImageData === "undefined") {
60
+ g.ImageData = class ImageData { constructor(public width = 0, public height = 0, public data: Uint8ClampedArray = new Uint8ClampedArray(0)) {} }
61
+ }
62
+ if (typeof g.Path2D === "undefined") {
63
+ g.Path2D = class Path2D {}
64
+ }
65
+ }
66
+
67
+ async function registrarWorker(lib: any): Promise<void> {
68
+ if (workerListo) return
69
+ const g = globalThis as any
70
+ if (!g.pdfjsWorker) {
71
+ g.pdfjsWorker = await import("pdfjs-dist/legacy/build/pdf.worker.mjs" as any)
72
+ }
73
+ if (lib.GlobalWorkerOptions && !lib.GlobalWorkerOptions.workerSrc) {
74
+ try { lib.GlobalWorkerOptions.workerSrc = import.meta.resolve("pdfjs-dist/legacy/build/pdf.worker.mjs") } catch { /* basta con pdfjsWorker */ }
75
+ }
76
+ workerListo = true
77
+ }
78
+
79
+ export function textoDePagina(items: any[]): string {
80
+ const lineas: string[] = []
81
+ let actual = ""
82
+ let prevY: number | null = null
83
+ let prevFin = 0
84
+
85
+ const cerrar = (blanco: boolean) => {
86
+ if (actual.trim()) lineas.push(actual.replace(/[ \t]+$/g, ""))
87
+ if (blanco && lineas.length && lineas[lineas.length - 1] !== "") lineas.push("")
88
+ actual = ""
89
+ prevFin = 0
90
+ }
91
+
92
+ for (const it of items) {
93
+ if (typeof it?.str !== "string") continue
94
+ const x: number | undefined = it.transform?.[4]
95
+ const y: number | undefined = it.transform?.[5]
96
+ const alto = Math.abs(it.transform?.[3] ?? it.height ?? 10) || 10
97
+
98
+ if (prevY !== null && y !== undefined) {
99
+ const salto = Math.abs(y - prevY)
100
+ if (salto > alto * 0.5) cerrar(salto > alto * 1.9)
101
+ }
102
+ if (actual && x !== undefined && it.str) {
103
+ const hueco = x - prevFin
104
+ if (hueco > alto * 1.5) actual += " " // columna distinta
105
+ else if (hueco > alto * 0.15 && !/\s$/.test(actual) && !/^\s/.test(it.str)) actual += " "
106
+ }
107
+ actual += it.str
108
+ if (x !== undefined) prevFin = x + (it.width ?? 0)
109
+ if (y !== undefined) prevY = y
110
+ if (it.hasEOL) { cerrar(false); prevY = null }
111
+ }
112
+ cerrar(false)
113
+ return lineas.join("\n").replace(/\n{3,}/g, "\n\n").trim()
114
+ }
115
+
116
+ export async function extraerTextoPdf(
117
+ bytes: Uint8Array,
118
+ opts: { desde?: number; hasta?: number; maxCaracteres?: number } = {},
119
+ ): Promise<PdfTextResult> {
120
+ if (bytes.byteLength > MAX_PDF_BYTES) {
121
+ throw new Error(`El PDF pesa ${(bytes.byteLength / 1048576).toFixed(0)} MB; el máximo es ${MAX_PDF_BYTES / 1048576} MB.`)
122
+ }
123
+ instalarPolyfillsPdf()
124
+ const pdfjs: any = await import("pdfjs-dist/legacy/build/pdf.mjs" as any).catch(() => import("pdfjs-dist" as any))
125
+ const lib = pdfjs.default ?? pdfjs
126
+ await registrarWorker(lib)
127
+
128
+ let doc: any
129
+ try {
130
+ doc = await lib.getDocument({ data: new Uint8Array(bytes), disableWorker: true }).promise
131
+ } catch (err: any) {
132
+ if (err?.name === "PasswordException") throw new Error("El PDF está protegido con contraseña.")
133
+ if (err?.name === "InvalidPDFException") throw new Error("El archivo no es un PDF válido o está dañado.")
134
+ throw err
135
+ }
136
+
137
+ const total: number = doc.numPages
138
+ const desde = Math.min(Math.max(1, Math.floor(opts.desde ?? 1)), total)
139
+ const hasta = Math.min(Math.max(desde, Math.floor(opts.hasta ?? total)), total)
140
+ const tope = opts.maxCaracteres ?? Infinity
141
+
142
+ let titulo: string | undefined
143
+ try { titulo = (await doc.getMetadata())?.info?.Title || undefined } catch { /* metadata opcional */ }
144
+
145
+ const bloques: string[] = []
146
+ const caracteres: number[] = []
147
+ let usados = 0
148
+ let truncado = false
149
+ let siguiente: number | undefined
150
+ let ultimaLeida = desde - 1
151
+
152
+ for (let n = desde; n <= hasta; n++) {
153
+ const texto = textoDePagina((await (await doc.getPage(n)).getTextContent()).items as any[])
154
+ const bloque = `--- Página ${n} ---\n${texto}`
155
+ if (usados > 0 && usados + bloque.length > tope) { truncado = true; siguiente = n; break }
156
+ if (bloque.length > tope) {
157
+ // Una sola página ya excede el tope: se recorta, pero siempre se entrega algo.
158
+ bloques.push(bloque.slice(0, tope))
159
+ caracteres.push(texto.length)
160
+ ultimaLeida = n
161
+ truncado = true
162
+ siguiente = n < total ? n + 1 : undefined
163
+ usados += tope
164
+ break
165
+ }
166
+ bloques.push(bloque)
167
+ caracteres.push(texto.length)
168
+ usados += bloque.length
169
+ ultimaLeida = n
170
+ }
171
+ if (!truncado && ultimaLeida < total) siguiente = ultimaLeida + 1
172
+
173
+ try { await doc.destroy() } catch { /* best effort */ }
174
+
175
+ const sinTexto = caracteres.length > 0 && caracteres.every((c) => c === 0)
176
+ return {
177
+ totalPaginas: total,
178
+ paginasLeidas: caracteres.length,
179
+ titulo,
180
+ texto: bloques.join("\n\n"),
181
+ caracteresPorPagina: caracteres,
182
+ sinTexto,
183
+ truncado,
184
+ ...(siguiente !== undefined && siguiente <= total ? { siguientePagina: siguiente } : {}),
185
+ }
186
+ }
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Utilidades de PowerPoint (.pptx) sobre su XML: orden real de diapositivas,
3
+ * texto por párrafo y notas del orador. Sin modelos.
4
+ *
5
+ * El número de archivo (slide7.xml) NO es la posición: al reordenar en
6
+ * PowerPoint los archivos conservan su nombre. El orden de verdad está en
7
+ * `ppt/presentation.xml` (sldIdLst) resuelto con `ppt/_rels/presentation.xml.rels`.
8
+ */
9
+ import type JSZip from "jszip"
10
+
11
+ export interface SlideRef {
12
+ /** Posición en la presentación, desde 1. */
13
+ numero: number
14
+ /** Ruta dentro del zip, p. ej. ppt/slides/slide7.xml. */
15
+ archivo: string
16
+ }
17
+
18
+ const unescapeXml = (s: string) =>
19
+ s.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&amp;/g, "&")
20
+
21
+ export async function listarSlides(zip: JSZip): Promise<SlideRef[]> {
22
+ const porNumeroDeArchivo = () =>
23
+ Object.keys(zip.files)
24
+ .filter((n) => /^ppt\/slides\/slide\d+\.xml$/i.test(n))
25
+ .sort((a, b) => Number(a.match(/slide(\d+)/)![1]) - Number(b.match(/slide(\d+)/)![1]))
26
+ .map((archivo, i) => ({ numero: i + 1, archivo }))
27
+
28
+ const pres = await zip.file("ppt/presentation.xml")?.async("string")
29
+ const rels = await zip.file("ppt/_rels/presentation.xml.rels")?.async("string")
30
+ if (!pres || !rels) return porNumeroDeArchivo()
31
+
32
+ const destinos = new Map<string, string>()
33
+ for (const m of rels.matchAll(/<Relationship\b[^>]*>/g)) {
34
+ const id = m[0].match(/\bId="([^"]+)"/)?.[1]
35
+ const target = m[0].match(/\bTarget="([^"]+)"/)?.[1]
36
+ if (id && target) destinos.set(id, target)
37
+ }
38
+ const ordenados: SlideRef[] = []
39
+ for (const m of pres.matchAll(/<p:sldId\b[^>]*\br:id="([^"]+)"/g)) {
40
+ const target = destinos.get(m[1])
41
+ if (!target) continue
42
+ const archivo = target.startsWith("/") ? target.slice(1) : `ppt/${target.replace(/^\.\//, "")}`
43
+ if (zip.file(archivo)) ordenados.push({ numero: ordenados.length + 1, archivo })
44
+ }
45
+ return ordenados.length ? ordenados : porNumeroDeArchivo()
46
+ }
47
+
48
+ /** Texto de un XML de diapositiva o de notas: un párrafo por línea. */
49
+ export function textoDeXml(xml: string): string {
50
+ const parrafos: string[] = []
51
+ for (const p of xml.matchAll(/<a:p[ >][\s\S]*?<\/a:p>/g)) {
52
+ const partes = [...p[0].matchAll(/<a:t(?:\s[^>]*)?>([^<]*)<\/a:t>|<a:br\s*\/>/g)]
53
+ .map((m) => (m[1] === undefined ? "\n" : unescapeXml(m[1])))
54
+ const linea = partes.join("").trim()
55
+ if (linea) parrafos.push(linea)
56
+ }
57
+ return parrafos.join("\n")
58
+ }
59
+
60
+ /** Título: primer texto del shape cuyo placeholder es title/ctrTitle; si no hay, la primera línea. */
61
+ export function tituloDeXml(xml: string, texto: string): string | undefined {
62
+ for (const sp of xml.matchAll(/<p:sp\b[\s\S]*?<\/p:sp>/g)) {
63
+ if (/<p:ph\b[^>]*\btype="(?:title|ctrTitle)"/.test(sp[0])) {
64
+ const t = textoDeXml(sp[0])
65
+ if (t) return t.split("\n")[0]
66
+ }
67
+ }
68
+ return texto.split("\n")[0] || undefined
69
+ }
70
+
71
+ /** Ruta del XML de notas de una diapositiva, si tiene. */
72
+ export async function archivoDeNotas(zip: JSZip, slide: SlideRef): Promise<string | null> {
73
+ const relsPath = slide.archivo.replace(/slides\/(slide\d+\.xml)$/, "slides/_rels/$1.rels")
74
+ const rels = await zip.file(relsPath)?.async("string")
75
+ const target = rels?.match(/<Relationship\b[^>]*\bType="[^"]*\/notesSlide"[^>]*>/)?.[0].match(/\bTarget="([^"]+)"/)?.[1]
76
+ if (!target) return null
77
+ const base = slide.archivo.split("/").slice(0, -1)
78
+ const partes = target.startsWith("/") ? target.slice(1).split("/") : [...base, ...target.split("/")]
79
+ const resueltas: string[] = []
80
+ for (const p of partes) { if (p === "..") resueltas.pop(); else if (p !== ".") resueltas.push(p) }
81
+ const ruta = resueltas.join("/")
82
+ return zip.file(ruta) ? ruta : null
83
+ }