@johpaz/hive-sdk 0.4.3 → 0.4.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 (49) hide show
  1. package/CHANGELOG.md +20 -4
  2. package/README.md +48 -7
  3. package/SECURITY.md +17 -0
  4. package/docs/API-AGENTS.md +430 -0
  5. package/docs/API-ARTIFACTS.md +55 -0
  6. package/docs/API-CONTEXT-COMPILER.md +285 -0
  7. package/docs/API-CRON.md +188 -0
  8. package/docs/API-DAG-SCHEDULER.md +291 -0
  9. package/docs/API-HOOKS.md +147 -0
  10. package/docs/API-RESILIENCE.md +45 -0
  11. package/docs/API-SERVICES.md +458 -0
  12. package/docs/API-SESSIONS.md +146 -0
  13. package/docs/API-TOOLS-SKILLS-CHANNELS.md +499 -0
  14. package/docs/API-WORKERS-EVENTS.md +311 -0
  15. package/docs/HIVE-HARNESS.md +232 -0
  16. package/docs/INDEX.md +198 -0
  17. package/docs/SECURITY-GUARDRAILS.md +87 -0
  18. package/docs/TEMPLATE-HIVE-APP.md +360 -0
  19. package/docs/UPGRADING.md +65 -0
  20. package/docs/assets/logoblack.png +0 -0
  21. package/docs/assets/logocolor-dark.png +0 -0
  22. package/docs/assets/logocolorbg.png +0 -0
  23. package/docs/plans/2026-09-05-office-dependency-hardening-design.md +28 -0
  24. package/docs/plans/2026-09-06-dependency-audit-remediation-design.md +25 -0
  25. package/docs/plans/2026-09-06-pptx-image-size-remediation-design.md +54 -0
  26. package/docs/plans/2026-09-06-typescript7-bun142-documentation-design.md +48 -0
  27. package/package.json +9 -8
  28. package/packages/cli/templates/hive-app/package.json +3 -0
  29. package/packages/core/src/agent/llm-providers/hiveagents.ts +2 -2
  30. package/packages/core/src/agent/providers/index.ts +17 -1
  31. package/packages/core/src/api/createAgent.ts +4 -2
  32. package/packages/core/src/config/loader.ts +2 -1
  33. package/packages/core/src/gateway/server.ts +1 -1
  34. package/packages/core/src/mcp/transports/sse.ts +22 -8
  35. package/packages/core/src/mcp/transports/websocket.ts +11 -9
  36. package/packages/core/src/scheduler/CronScheduler.ts +4 -2
  37. package/packages/core/src/scheduler/cron/job.ts +2 -1
  38. package/packages/core/src/scheduler/cron/zoned-time.ts +2 -1
  39. package/packages/core/src/tool-runtime/tool-worker.ts +3 -1
  40. package/packages/core/src/tools/office/office-escribir-pptx.ts +3 -1
  41. package/packages/core/src/tools/office/office-leer-pdf.ts +93 -44
  42. package/packages/core/src/tools/office/office-leer-xlsx.ts +36 -10
  43. package/packages/core/src/tools/office/security-limits.ts +28 -0
  44. package/packages/core/src/utils/port.ts +33 -0
  45. package/packages/core/src/vendor/pptxgenjs/LICENSE +21 -0
  46. package/packages/core/src/vendor/pptxgenjs/README.md +17 -0
  47. package/packages/core/src/vendor/pptxgenjs/pptxgen.es.d.ts +17 -0
  48. package/packages/core/src/vendor/pptxgenjs/pptxgen.es.js +7368 -0
  49. package/packages/core/src/voice/index.ts +6 -5
Binary file
Binary file
@@ -0,0 +1,28 @@
1
+ # Office dependency hardening
2
+
3
+ ## Scope
4
+
5
+ Remediate the five high-severity advisories reported for the Office tools without
6
+ changing their public names or successful result shapes. The XLSX reader is the
7
+ highest-priority path because it parses user-selected files synchronously. The
8
+ PDF reader only extracts text and does not render the viewer or annotation layer,
9
+ but its vulnerable dependency is still upgraded. The `image-size` findings are
10
+ documented rather than forcing a PPTX replacement because the dependency is not
11
+ loaded by the published `pptxgenjs` path used by Hive.
12
+
13
+ ## Design
14
+
15
+ Use the current safe PDF.js major and the official SheetJS CE tarball, updating
16
+ both manifests so workspace and published metadata remain aligned. Before loading
17
+ PDF or XLSX data into memory, inspect the regular file and reject inputs above a
18
+ fixed byte limit. PDF processing explicitly disables scripting/eval, bounds the
19
+ number of pages returned per call, and checks a processing deadline between
20
+ pages. XLSX processing bounds workbook sheet count, rows returned per sheet, and
21
+ checks a deadline between sheets. These controls are defense in depth; dependency
22
+ updates remain the remediation for the reported CVEs.
23
+
24
+ Tests exercise rejection before parsing, page-range validation, XLSX row limits,
25
+ and normal PDF/XLSX behavior. A repository security note records the exact
26
+ `image-size` dependency chain, why it is currently unreachable, the evidence
27
+ required before suppressing it in scanners, and the conditions that invalidate
28
+ the exception (adding image input or an upstream package change).
@@ -0,0 +1,25 @@
1
+ # Dependency audit remediation
2
+
3
+ ## Scope
4
+
5
+ Remove the critical Baileys advisory and every remaining audit finding that can
6
+ be fixed inside the dependency ranges already accepted by the SDK. Preserve the
7
+ public API and avoid package overrides unless a direct dependency cannot express
8
+ the safe version. The unpatched and unreachable `image-size` findings retain the
9
+ documented exception in `SECURITY.md`.
10
+
11
+ ## Design
12
+
13
+ Pin `@whiskeysockets/baileys` to the latest official release candidate in both
14
+ published manifests. This moves beyond the security fix in rc12 and includes the
15
+ follow-up protocol-message regression fix. Refresh transitive packages only
16
+ within their parents' declared semver ranges so patched `ws`, `protobufjs`,
17
+ `nanoid`, `fast-uri`, `hono`, `undici`, and related HTTP packages can resolve
18
+ without changing Hive application code.
19
+
20
+ Use `bun audit` as the failing security regression check: the baseline must show
21
+ the critical advisory before the change and no critical finding afterward. Run
22
+ the channel tests, typecheck, and complete suite to detect API or runtime drift.
23
+ Inspect the final lockfile and audit output before committing. Any advisory that
24
+ cannot be removed by a compatible update is reported separately rather than
25
+ hidden with a broad suppression.
@@ -0,0 +1,54 @@
1
+ # Remediación de `image-size` en la generación PPTX
2
+
3
+ ## Contexto y decisión
4
+
5
+ `pptxgenjs@4.0.1` declara `image-size@^1.2.1`, afectado por
6
+ GHSA-w3rx-r6r6-pgpr y GHSA-5p2g-fcmc-qvqq. No existe una versión corregida de
7
+ `image-size`, y el repositorio oficial de PptxGenJS todavía conserva la
8
+ dependencia. Sin embargo, el artefacto ESM publicado de PptxGenJS no importa
9
+ `image-size`: sólo usa `jszip`. Hive tampoco expone imágenes en
10
+ `office_escribir_pptx`; el flujo acepta texto, viñetas y notas del presentador.
11
+
12
+ Se conservará una copia vendorizada del artefacto ESM oficial de
13
+ PptxGenJS 4.0.1, junto con su licencia MIT y un archivo de procedencia. El
14
+ wrapper de Hive importará ese artefacto local y mantendrá deliberadamente una
15
+ API limitada a texto y notas. Se eliminará `pptxgenjs` de los manifiestos y del
16
+ lockfile, lo que también elimina `image-size` y `queue` del grafo instalable.
17
+
18
+ Se descartan dos alternativas. Mantener la excepción conserva funcionalidad,
19
+ pero deja el auditor en rojo. Reimplementar directamente el paquete OOXML
20
+ evitaría código vendorizado, pero introduce un riesgo mayor de incompatibilidad
21
+ con PowerPoint, Keynote y LibreOffice, especialmente para notas y relaciones
22
+ internas.
23
+
24
+ ## Integración, errores y mantenimiento
25
+
26
+ El código vendorizado vivirá bajo `packages/core/src/vendor/pptxgenjs/` y no
27
+ tendrá un `package.json` con dependencias. Un módulo TypeScript local expondrá
28
+ únicamente los métodos que usa la herramienta (`addSlide`, `addText`,
29
+ `addNotes`, `writeFile`), evitando que el resto del SDK dependa de la API amplia
30
+ de PptxGenJS. La herramienta conservará su manejo actual de directorios,
31
+ errores y forma de respuesta.
32
+
33
+ El archivo de procedencia fijará versión, URL oficial y licencia. Las futuras
34
+ actualizaciones deben reemplazar el artefacto desde una versión oficial,
35
+ verificar su hash y volver a ejecutar las pruebas y el audit. No se añadirá
36
+ soporte para imágenes mediante esta copia: cualquier ampliación de esa API
37
+ requiere una revisión de seguridad nueva.
38
+
39
+ ## Verificación
40
+
41
+ Una prueba funcional generará una presentación temporal con portada, texto,
42
+ viñetas y notas. Después abrirá el resultado como ZIP y comprobará las partes
43
+ OOXML principales, el número de diapositivas y la presencia del contenido y de
44
+ las notas. Esto protege el comportamiento que Hive usa realmente, sin probar
45
+ detalles internos del proveedor.
46
+
47
+ La aceptación requiere:
48
+
49
+ 1. La prueba PPTX nueva y la suite de Office pasan.
50
+ 2. El typecheck del workspace pasa.
51
+ 3. `bun audit` reporta cero vulnerabilidades.
52
+ 4. `rg` no encuentra `image-size` ni `pptxgenjs` como dependencias en los
53
+ manifiestos o el lockfile.
54
+
@@ -0,0 +1,48 @@
1
+ # Cierre de migración a TypeScript 7 y Bun 1.4.2
2
+
3
+ ## Objetivo y decisión
4
+
5
+ Hive adoptará TypeScript 7.0.2 para su desarrollo y mantendrá Bun 1.4.2 como
6
+ runtime mínimo y versión de referencia en CI. La migración debe terminar con el
7
+ typecheck limpio; no se conservarán `@ts-ignore` ni conversiones a `any` para
8
+ ocultar incompatibilidades. Los puntos donde los tipos DOM y Bun describen de
9
+ forma distinta una misma API tendrán adaptadores locales y estrechos que
10
+ expresen sólo el contrato usado por Hive.
11
+
12
+ La documentación se dividirá en dos referencias. `UPGRADING.md` explicará los
13
+ requisitos de Bun y TypeScript, los pasos de actualización, los cambios de tipos
14
+ y la validación. `SECURITY-GUARDRAILS.md` inventariará los controles que ya
15
+ existen en dependencias, documentos Office, transporte y CI. README, el índice,
16
+ la API de cron y el changelog enlazarán estas referencias.
17
+
18
+ Se descartan dos alternativas: documentar únicamente en el changelog dificulta
19
+ encontrar instrucciones operativas; mezclar migración y seguridad en una sola
20
+ página confunde requisitos de plataforma con controles de entrada.
21
+
22
+ ## Compatibilidad y correcciones de tipos
23
+
24
+ El lector SSE consumirá un contrato estructural mínimo (`read`) en vez de exigir
25
+ la extensión `readMany` que Bun añade al lector global. El cliente WebSocket
26
+ usará un constructor tipado localmente con `Bun.WebSocketOptions`, porque al
27
+ incluir `DOM` TypeScript selecciona el constructor estándar y omite la
28
+ sobrecarga de opciones de Bun. Audio convertirá toda entrada a bytes propios
29
+ respaldados por `ArrayBuffer` antes de crear un `Blob`; esto satisface el modelo
30
+ genérico de typed arrays de TypeScript 7 y evita compartir memoria mutable.
31
+
32
+ Los demás cambios de migración se conservarán sólo si el typecheck y las pruebas
33
+ demuestran que son compatibles con Bun 1.4.2. Los casts se limitarán a fronteras
34
+ con APIs externas y tendrán comentarios que expliquen la divergencia.
35
+
36
+ ## Guardrails y validación
37
+
38
+ La referencia de guardrails documentará límites exactos y el comportamiento al
39
+ rechazar entradas: PDF de 25 MiB, máximo 200 páginas, scripting/eval apagados y
40
+ deadline; XLSX de 15 MiB, máximo 25 hojas y 10.000 filas por hoja; PPTX sólo de
41
+ texto con artefacto vendorizado; dependencias auditadas y distribuciones
42
+ oficiales fijadas. También cubrirá el mínimo de Bun, CI con lockfile congelado y
43
+ typecheck de TypeScript 7.
44
+
45
+ La aceptación requiere `bun --version` 1.4.2, `bun run typecheck` limpio, pruebas
46
+ de los componentes modificados, suite completa, `bun audit` sin hallazgos y
47
+ `git diff --check` limpio. Cualquier prueba intermitente se repetirá aislada y
48
+ se informará explícitamente.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johpaz/hive-sdk",
3
- "version": "0.4.3",
3
+ "version": "0.4.5",
4
4
  "private": false,
5
5
  "description": "Hive SDK — The Agent Harness SDK. Build, deploy, and scale AI agent applications with multi-channel support, context engineering, and swarm orchestration.",
6
6
  "license": "MIT",
@@ -77,10 +77,12 @@
77
77
  "!packages/**/*.test.ts",
78
78
  "README.md",
79
79
  "CHANGELOG.md",
80
+ "SECURITY.md",
81
+ "docs",
80
82
  "LICENSE"
81
83
  ],
82
84
  "engines": {
83
- "bun": ">=1.4.0"
85
+ "bun": ">=1.4.2"
84
86
  },
85
87
  "workspaces": [
86
88
  "packages/core",
@@ -103,7 +105,7 @@
103
105
  "@modelcontextprotocol/sdk": "^1.26.0",
104
106
  "@sapphire/snowflake": "^3.5.5",
105
107
  "@slack/bolt": "^4.7.2",
106
- "@whiskeysockets/baileys": "7.0.0-rc11",
108
+ "@whiskeysockets/baileys": "7.0.0-rc14",
107
109
  "async-mutex": "^0.5.0",
108
110
  "discord.js": "^14.26.4",
109
111
  "docx": "^9.6.1",
@@ -115,16 +117,15 @@
115
117
  "mammoth": "^1.12.0",
116
118
  "ollama": "^0.6.3",
117
119
  "openai": "^6.18.0",
118
- "pdfjs-dist": "^5.6.205",
119
- "pptxgenjs": "^4.0.1",
120
+ "pdfjs-dist": "^6.3.289",
120
121
  "qrcode-terminal": "^0.12.0",
121
122
  "toon-format-parser": "^1.1.0",
122
- "xlsx": "^0.18.5",
123
+ "xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz",
123
124
  "zod": "^4.4.3"
124
125
  },
125
126
  "devDependencies": {
126
- "@types/bun": "^1.3.13",
127
+ "@types/bun": "^1.4.1",
127
128
  "@types/jsonwebtoken": "^9.0.10",
128
- "typescript": "6.0.2"
129
+ "typescript": "7.0.2"
129
130
  }
130
131
  }
@@ -12,5 +12,8 @@
12
12
  },
13
13
  "devDependencies": {
14
14
  "@types/bun": "latest"
15
+ },
16
+ "engines": {
17
+ "bun": ">=1.4.2"
15
18
  }
16
19
  }
@@ -135,8 +135,8 @@ export class HiveAgentsProvider extends OpenAICompatBase {
135
135
  return new OpenAI({
136
136
  apiKey,
137
137
  baseURL,
138
- fetch: async (url: RequestInfo | URL, init?: RequestInit) => {
139
- const headers = new Headers(init?.headers as HeadersInit | undefined)
138
+ fetch: async (url: string | URL | Request, init?: RequestInit) => {
139
+ const headers = new Headers(init?.headers)
140
140
  for (const h of BLOCKED_HEADERS) headers.delete(h)
141
141
 
142
142
  // Debug: log exact request so we can replicate with curl
@@ -13,6 +13,19 @@ import type { ContentPart } from "../../multimodal/types.ts"
13
13
  import type { TurnSource } from "../../storage/collections.ts"
14
14
  import type { MCPClientManager } from "../../mcp/index.ts"
15
15
 
16
+ /**
17
+ * Bloque de contenido de un mensaje del loop.
18
+ *
19
+ * El mensaje llega con `content` laxo (`string` o arreglo), y acá sólo se
20
+ * consumen los bloques de texto. Declarar la forma quita el `any` implícito
21
+ * del filtro y, de paso, el `as any` que hacía falta para leer `.text`.
22
+ * Bajo el `strict: false` de este repo el `any` era invisible; en un
23
+ * consumidor que compile en estricto es un error, y el SDK se publica en
24
+ * fuente, así que lo compilan con SU configuración.
25
+ */
26
+ interface ContentBlock { type?: string }
27
+ interface TextBlock extends ContentBlock { type: "text"; text: string }
28
+
16
29
  export type Provider = "openai" | "anthropic" | "gemini" | "mistral" | "kimi" | "ollama" | "openrouter" | "deepseek" | "nvidia" | "hiveagents" | "z-ai" | "modelscope" | "minimax" | "qwen" | "groq" | "opencode-go"
17
30
 
18
31
  export interface StepEvent {
@@ -164,7 +177,10 @@ export class AgentRunner {
164
177
  const content = typeof lastMsg.content === "string"
165
178
  ? lastMsg.content
166
179
  : Array.isArray(lastMsg.content)
167
- ? lastMsg.content.filter(p => p.type === "text").map(p => (p as any).text).join("\n")
180
+ ? (lastMsg.content as ContentBlock[])
181
+ .filter((p): p is TextBlock => p.type === "text")
182
+ .map((p) => p.text)
183
+ .join("\n")
168
184
  : ""
169
185
  lastAgentContent = content
170
186
  // Accumulate non-empty content that's not just whitespace
@@ -285,7 +285,7 @@ export async function createAgent(config: AgentConfig): Promise<Agent> {
285
285
 
286
286
  const { runAgent } = await import("../agent/agent-loop.ts");
287
287
 
288
- return {
288
+ const agente: Agent = {
289
289
  name: config.name,
290
290
  id: agentId,
291
291
  config,
@@ -340,13 +340,15 @@ export async function createAgent(config: AgentConfig): Promise<Agent> {
340
340
  // El loop emite el texto acumulado del turno, no deltas: quedarse con el
341
341
  // último evento evita duplicar la respuesta al concatenar.
342
342
  let response = "";
343
- for await (const event of this.chat(task, opts)) {
343
+ for await (const event of agente.chat(task, opts)) {
344
344
  if (event.type === "text") response = event.content;
345
345
  if (event.type === "done" && event.response) response = event.response;
346
346
  }
347
347
  return response;
348
348
  },
349
349
  };
350
+
351
+ return agente;
350
352
  }
351
353
 
352
354
  function safeParse(raw: string): Record<string, unknown> {
@@ -1,3 +1,4 @@
1
+ import { resolvePort } from "../utils/port.ts";
1
2
  import * as z from "zod";
2
3
  import { mkdirSync, existsSync, readFileSync } from "node:fs";
3
4
  import * as path from "node:path";
@@ -407,7 +408,7 @@ function buildDefaultConfig(): Config {
407
408
  return {
408
409
  gateway: {
409
410
  host: process.env.HIVE_HOST || "127.0.0.1",
410
- port: parseInt(process.env.HIVE_PORT || "18790", 10),
411
+ port: resolvePort(process.env.HIVE_PORT, 18790),
411
412
  pidFile: path.join(hiveDir, "gateway.pid"),
412
413
  authToken: process.env.HIVE_AUTH_TOKEN || undefined,
413
414
  tools: {
@@ -98,7 +98,7 @@ async function handleChat(
98
98
  mcpManager?: MCPClientManager | null
99
99
  ): Promise<Response> {
100
100
  try {
101
- const body = await req.json();
101
+ const body = (await req.json()) as { message?: string; threadId?: string };
102
102
  const message = body.message ?? "";
103
103
  const threadId = body.threadId ?? crypto.randomUUID();
104
104
 
@@ -6,6 +6,14 @@ export interface SSETransportConfig {
6
6
  headers?: Record<string, string>;
7
7
  }
8
8
 
9
+ interface ByteStreamReader {
10
+ read(): Promise<{ done: boolean; value?: Uint8Array }>;
11
+ }
12
+
13
+ interface ByteStream {
14
+ getReader(): ByteStreamReader;
15
+ }
16
+
9
17
  export class SSETransport implements Transport {
10
18
  private baseUrl: string;
11
19
  private messagesUrl: string | null = null; // Endpoint recibido del servidor
@@ -96,16 +104,22 @@ export class SSETransport implements Transport {
96
104
  this.sessionId = sessionId;
97
105
  }
98
106
 
99
- // Track cookies for session affinity (important for n8n/proxies)
100
- const setCookie = response.headers.get("set-cookie");
101
- if (setCookie) {
102
- // Simple cookie extraction: just keep the keys and values
103
- const newCookies = setCookie.split(',').map(c => c.split(';')[0].trim());
107
+ // Track cookies for session affinity (important for n8n/proxies).
108
+ //
109
+ // `getSetCookie()` y no `get("set-cookie")`: Set-Cookie es la única cabecera
110
+ // que puede repetirse sin combinarse, y `get()` devuelve las repeticiones
111
+ // unidas con ", " (Bun 1.4 lo alineó con la spec de Fetch). Partir eso por
112
+ // coma rompe cualquier cookie cuyo valor lleve una —`Expires=Wed, 09 Jun
113
+ // 2027 10:18:14 GMT` es el caso de todos los días— y dejaba fragmentos como
114
+ // "09 Jun 2027 10:18:14 GMT" haciéndose pasar por cookies.
115
+ const setCookies = response.headers.getSetCookie();
116
+ if (setCookies.length > 0) {
117
+ const newCookies = setCookies.map(c => c.split(";")[0].trim());
104
118
  this.cookies = [...new Set([...this.cookies, ...newCookies])];
105
119
  }
106
120
  }
107
121
 
108
- private startReading(stream: ReadableStream<Uint8Array>) {
122
+ private startReading(stream: ByteStream) {
109
123
  const reader = stream.getReader();
110
124
  const decoder = new TextDecoder();
111
125
  let buffer = "";
@@ -118,7 +132,7 @@ export class SSETransport implements Transport {
118
132
  }
119
133
 
120
134
  private async processStream(
121
- reader: ReadableStreamDefaultReader<Uint8Array>,
135
+ reader: ByteStreamReader,
122
136
  decoder: TextDecoder,
123
137
  buffer: string
124
138
  ): Promise<void> {
@@ -238,4 +252,4 @@ export class SSETransport implements Transport {
238
252
 
239
253
  export function createSSETransport(config: SSETransportConfig): Transport {
240
254
  return new SSETransport(config) as unknown as Transport;
241
- }
255
+ }
@@ -8,6 +8,11 @@ export interface WebSocketTransportConfig {
8
8
  reconnectMaxAttempts?: number; // máximo de intentos (default: 10)
9
9
  }
10
10
 
11
+ type BunWebSocketConstructor = new (
12
+ url: string | URL,
13
+ options?: Bun.WebSocketOptions,
14
+ ) => WebSocket;
15
+
11
16
  export class WebSocketTransport implements Transport {
12
17
  private url: string;
13
18
  private ws: WebSocket | null = null;
@@ -40,15 +45,12 @@ export class WebSocketTransport implements Transport {
40
45
  return new Promise((resolve, reject) => {
41
46
 
42
47
  // CORRECCIÓN 1 — headers en Bun WebSocket
43
- // Bun acepta las opciones como segundo argumento cuando no hay subprotocols,
44
- // o como objeto con `headers` dentro de un array de subprotocols vacío.
45
- // La forma más segura y compatible:
48
+ // Con la lib DOM activa, TypeScript expone sólo la sobrecarga estándar
49
+ // (subprotocols). El runtime de Bun acepta Bun.WebSocketOptions.
50
+ const BunWebSocket = WebSocket as unknown as BunWebSocketConstructor;
46
51
  const ws = this.headers && Object.keys(this.headers).length > 0
47
- ? new WebSocket(this.url, {
48
- // @ts-expect-error — Bun extiende la API estándar de WebSocket
49
- headers: this.headers,
50
- })
51
- : new WebSocket(this.url);
52
+ ? new BunWebSocket(this.url, { headers: this.headers })
53
+ : new BunWebSocket(this.url);
52
54
 
53
55
  this.ws = ws;
54
56
  let resolved = false;
@@ -156,4 +158,4 @@ export function createWebSocketTransport(
156
158
  config: WebSocketTransportConfig
157
159
  ): Transport {
158
160
  return new WebSocketTransport(config) as unknown as Transport;
159
- }
161
+ }
@@ -7,9 +7,11 @@
7
7
  * El motor de cron es propio (`./cron`), sin dependencias: sólo `setTimeout` e
8
8
  * `Intl` del runtime. Antes era `croner`.
9
9
  *
10
- * `Bun.cron()` no sirve como reemplazo —se evaluó contra el runtime 1.4.0—:
10
+ * `Bun.cron()` no sirve como reemplazo —reevaluado contra el runtime 1.4.2—:
11
11
  * acepta sólo 5 campos y rechaza el sexto, no admite una fecha ISO como patrón
12
- * (que es como se agendan los jobs `one_shot`), ignora la zona horaria, y su
12
+ * (que es como se agendan los jobs `one_shot`), no toma una zona por job (usa la
13
+ * local del proceso desde 1.4; antes era UTC, y ese cambio silencioso es
14
+ * justamente por qué no conviene delegarle la conversión), y su
13
15
  * handle no expone la próxima corrida, que es de donde sale `next_run_at` y con
14
16
  * lo que se detectan las corridas perdidas al arrancar. Tampoco tiene
15
17
  * equivalente de `protect`, `maxRuns`, `interval`, `startAt`/`stopAt` ni
@@ -8,7 +8,8 @@
8
8
  * habría sido migrar la base para no ganar nada.
9
9
  *
10
10
  * No usa `Bun.cron()`: ese sólo acepta 5 campos, no admite una fecha ISO como
11
- * patrón —que es como se agendan los jobs `one_shot`—, ignora la zona horaria y
11
+ * patrón —que es como se agendan los jobs `one_shot`—, no toma una zona por job
12
+ * (usa la local del proceso desde Bun 1.4; antes era UTC) y
12
13
  * su handle no expone la próxima corrida, que es de donde sale `next_run_at` y
13
14
  * con lo que el scheduler detecta las corridas perdidas al arrancar. Lo que sí
14
15
  * se usa de Bun es el runtime pelado: `setTimeout` e `Intl`.
@@ -2,7 +2,8 @@
2
2
  * Reloj de pared ↔ instante, en una zona horaria IANA.
3
3
  *
4
4
  * Es la parte difícil de un cron con zona horaria y la razón por la que no
5
- * alcanza con `Bun.cron.parse()`, que sólo trabaja en UTC. "Todos los días a
5
+ * alcanza con `Bun.cron.parse()`, que resuelve en una sola zona —UTC hasta Bun
6
+ * 1.3, la local del proceso desde 1.4— y nunca en la del job. "Todos los días a
6
7
  * las 9" significa las 9 **del reloj de la pared en Bogotá**, y ese instante se
7
8
  * corre una hora dos veces al año en las zonas con horario de verano. Calcular
8
9
  * el offset una sola vez y sumarlo produce un cron que se desfasa un día al año
@@ -100,7 +100,9 @@ async function runTool(message: WorkerRunMessage): Promise<void> {
100
100
  }
101
101
  }
102
102
 
103
- onmessage = (event: MessageEvent<WorkerRunMessage | WorkerRpcResponse>) => {
103
+ declare const self: Worker
104
+
105
+ self.onmessage = (event: MessageEvent<WorkerRunMessage | WorkerRpcResponse>) => {
104
106
  const message = event.data
105
107
 
106
108
  if (message.type === "rpc_result") {
@@ -60,7 +60,9 @@ export const officeEscribirPptxTool: Tool = {
60
60
  log.debug(`Generando PPTX: ${ruta}`);
61
61
 
62
62
  try {
63
- const pptxgen = (await import("pptxgenjs")).default;
63
+ // PptxGenJS 4.0.1 ESM is vendored without its unused image parser.
64
+ // Keep this tool text-only; image support requires a new security review.
65
+ const pptxgen = (await import("../../vendor/pptxgenjs/pptxgen.es.js")).default;
64
66
  const pres = new pptxgen();
65
67
 
66
68
  // Configuración básica
@@ -10,6 +10,14 @@ import type { Tool } from "../types.ts";
10
10
  import { logger } from "../../utils/logger.ts";
11
11
  import * as fs from "node:fs";
12
12
  import * as path from "node:path";
13
+ import { fileURLToPath } from "node:url";
14
+ import {
15
+ assertBeforeDeadline,
16
+ MAX_PDF_INPUT_BYTES,
17
+ MAX_PDF_PAGES_PER_REQUEST,
18
+ OFFICE_PROCESSING_TIMEOUT_MS,
19
+ validateOfficeInput,
20
+ } from "./security-limits.ts";
13
21
 
14
22
  const log = logger.child("office-leer-pdf");
15
23
 
@@ -48,61 +56,102 @@ export const officeLeerPdfTool: Tool = {
48
56
  return { ok: false, error: `Archivo no encontrado: ${rutaAbsoluta}` };
49
57
  }
50
58
 
59
+ const inputError = validateOfficeInput(
60
+ rutaAbsoluta,
61
+ MAX_PDF_INPUT_BYTES,
62
+ "El PDF",
63
+ );
64
+ if (inputError) return { ok: false, error: inputError };
65
+
51
66
  const buffer = fs.readFileSync(rutaAbsoluta);
52
67
  const uint8Array = new Uint8Array(buffer);
53
68
 
54
- // Importar pdfjs-dist (compatible con Bun, sin worker)
69
+ // La build legacy conserva compatibilidad con Bun. PDF.js configura su
70
+ // propio fake worker en Node/Bun; borrar workerSrc rompe PDF.js 6+.
55
71
  const pdfjsLib = await import("pdfjs-dist/legacy/build/pdf.mjs" as any).catch(
56
72
  () => import("pdfjs-dist" as any)
57
73
  );
58
74
 
59
- // Desactivar worker para entorno Node/Bun
60
75
  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;
76
+ const pdfjsPackageUrl = import.meta.resolve("pdfjs-dist/package.json");
77
+ const loadingTask = lib.getDocument({
78
+ data: uint8Array,
79
+ enableScripting: false,
80
+ isEvalSupported: false,
81
+ // Bun's process.getBuiltinModule("fs/promises") expects a filesystem
82
+ // path here; a file:// URL string is not accepted.
83
+ standardFontDataUrl: fileURLToPath(
84
+ new URL("./standard_fonts/", pdfjsPackageUrl),
85
+ ),
86
+ });
67
87
 
68
- // Metadata
69
- let titulo: string | undefined;
70
88
  try {
71
- const meta = await doc.getMetadata();
72
- titulo = (meta?.info as any)?.Title ?? undefined;
73
- } catch {
74
- // metadata opcional
89
+ const deadline = Date.now() + OFFICE_PROCESSING_TIMEOUT_MS;
90
+ const doc = await loadingTask.promise;
91
+ const totalPaginas = doc.numPages;
92
+
93
+ // Metadata
94
+ let titulo: string | undefined;
95
+ try {
96
+ const meta = await doc.getMetadata();
97
+ titulo = (meta?.info as any)?.Title ?? undefined;
98
+ } catch {
99
+ // metadata opcional
100
+ }
101
+
102
+ const inicio = paginaInicio;
103
+ if (!Number.isInteger(inicio) || inicio > totalPaginas) {
104
+ return {
105
+ ok: false,
106
+ error: `La página inicial debe estar entre 1 y ${totalPaginas}`,
107
+ };
108
+ }
109
+ if (paginaFin !== undefined && (!Number.isInteger(paginaFin) || paginaFin < inicio)) {
110
+ return {
111
+ ok: false,
112
+ error: "La página final debe ser un entero mayor o igual a la página inicial",
113
+ };
114
+ }
115
+
116
+ const fin = paginaFin ? Math.min(paginaFin, totalPaginas) : totalPaginas;
117
+ const paginasSolicitadas = fin - inicio + 1;
118
+ if (paginasSolicitadas > MAX_PDF_PAGES_PER_REQUEST) {
119
+ return {
120
+ ok: false,
121
+ error: `Se pueden leer como máximo ${MAX_PDF_PAGES_PER_REQUEST} páginas por solicitud`,
122
+ };
123
+ }
124
+
125
+ const textosPorPagina: Array<{ pagina: number; texto: string }> = [];
126
+
127
+ for (let i = inicio; i <= fin; i++) {
128
+ assertBeforeDeadline(deadline, "La lectura del PDF");
129
+ const pagina = await doc.getPage(i);
130
+ const contenido = await pagina.getTextContent();
131
+ const texto = (contenido.items as any[])
132
+ .map((item: any) => item.str ?? "")
133
+ .join(" ")
134
+ .replace(/\s+/g, " ")
135
+ .trim();
136
+ textosPorPagina.push({ pagina: i, texto });
137
+ }
138
+
139
+ const textoCompleto = textosPorPagina.map((p) => p.texto).join("\n\n");
140
+
141
+ log.info(`PDF leído: ${totalPaginas} páginas, ${textoCompleto.length} caracteres`);
142
+
143
+ return {
144
+ ok: true,
145
+ ruta: rutaAbsoluta,
146
+ totalPaginas,
147
+ paginasLeidas: paginasSolicitadas,
148
+ titulo,
149
+ texto: textoCompleto,
150
+ paginas: textosPorPagina,
151
+ };
152
+ } finally {
153
+ await loadingTask.destroy();
75
154
  }
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 });
91
- }
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
-
97
- return {
98
- ok: true,
99
- ruta: rutaAbsoluta,
100
- totalPaginas,
101
- paginasLeidas: fin - inicio + 1,
102
- titulo,
103
- texto: textoCompleto,
104
- paginas: textosPorPagina,
105
- };
106
155
  } catch (error) {
107
156
  log.error(`Error leyendo PDF: ${(error as Error).message}`);
108
157
  return {