claqueta-mcp 0.8.2 → 0.9.0

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 (3) hide show
  1. package/README.md +3 -0
  2. package/dist/cli.js +117 -14
  3. package/package.json +28 -7
package/README.md CHANGED
@@ -82,6 +82,9 @@ Opciones: `--url`, `--agente <nombre>` (por defecto el hostname), `--intervalo <
82
82
  - **Motor**: comprueba que Docker responda; si la imagen no está local, o al arrancar (salvo `--sin-actualizar-motor`), hace `docker pull` de la imagen pública (sin shell, sin credenciales). Solo con una imagen privada de ECR hace antes `aws ecr get-login-password | docker login`. El `docker run` lleva `--cap-drop=ALL`, `--security-opt no-new-privileges` y `--pids-limit=1024`, y el contenedor no recibe tu token. Si ya hay imagen local y la actualización falla, avisa y sigue con la local. Con `AWS_ACCESS_KEY_ID` en el entorno usa esas variables en vez del perfil, salvo que pases `--perfil-aws`.
83
83
  - **Revisión automática (código 15 del motor)**: decisión de producto pendiente. Por defecto (`adjuntar`) el video se adjunta y queda en revisión con una advertencia; con `rechazar` pasa a error y se reintenta según el límite. También: `WORKER_SI_FALLA_REVISION`.
84
84
  - **Servicio (macOS)**: `--instalar-servicio` escribe `~/Library/LaunchAgents/me.claqueta.worker.plist` (`RunAtLoad`, `KeepAlive`, logs en `~/Library/Logs/claqueta-worker.log`) y lo carga con `launchctl bootstrap`. Conserva las opciones que le pases; ejecuta `npx -y claqueta-mcp@latest worker`, así que usa la versión publicada más reciente. `--quitar-servicio` lo descarga y borra.
85
+ - **Archivos del pedido (0.9.0)**: antes de gastar un contenedor el worker baja las **imágenes** del pedido (`media`, storyboard y logo) a `<carpeta de trabajo>/media/`, verifica `bytes` y `sha256` y se las pasa al motor en `archivos_locales`. Un archivo que no baja por red reintenta; uno que no coincide o no existe falla con causa legible. Hace falta una imagen del motor que ya las use (`--motor-imagen`).
86
+ - **Carruseles e imágenes (0.9.0)**: si el pedido es `entregable: "carrusel"` o `"imagen"`, el worker sube las piezas PNG del primer render antes del MP4 (una por petición, con reintentos).
87
+ - **Cuidado al probar en local**: el worker usa `--url` > `CLAQUETA_URL` > `~/.config/claqueta/config.json` > producción. Para probar contra tu API local pasa siempre `--url http://localhost:PUERTO`.
85
88
  - Otras variables del worker (`WORKER_TRABAJO_DIR`, `WORKER_TIMEOUT_MIN`, `MOTOR_CACHE`, ...): ver [docs/worker-app.md](docs/worker-app.md). La carpeta de trabajo por defecto es `~/.cache/claqueta/trabajo`.
86
89
 
87
90
  ### `npx claqueta-mcp@latest doctor`
package/dist/cli.js CHANGED
@@ -50,7 +50,7 @@ function ayudaConexionTodas(plataforma = process.platform) {
50
50
  }
51
51
 
52
52
  // src/config.ts
53
- var VERSION = true ? "0.8.2" : "dev";
53
+ var VERSION = true ? "0.9.0" : "dev";
54
54
  var construirAyuda = (plataforma = process.platform) => `claqueta-mcp ${VERSION}: puente stdio hacia el servidor MCP remoto de Claqueta.
55
55
 
56
56
  Uso:
@@ -404,7 +404,7 @@ import { dirname as dirname2, join as join4 } from "node:path";
404
404
 
405
405
  // src/motor-docker.ts
406
406
  import { spawn } from "node:child_process";
407
- var IMAGEN_POR_DEFECTO = "public.ecr.aws/v9d5u4i8/claqueta-motor@sha256:2c4978924d55e686fd5e7aa1e4c53e379eab577336030f8b25af5d84fd3b8cdb";
407
+ var IMAGEN_POR_DEFECTO = "public.ecr.aws/v9d5u4i8/claqueta-motor@sha256:35e4181b5d22de7d96c91feddd7c609fc58b4b2858f0c1060b1d697cc6026df8";
408
408
  var PERFIL_AWS_POR_DEFECTO = "claqueta-motor";
409
409
  var REGION_POR_DEFECTO = "us-west-1";
410
410
  var ejecutarReal = (cmd, args2, opc) => new Promise((resolver) => {
@@ -1951,7 +1951,7 @@ function ejecutarPuente(o) {
1951
1951
  // src/worker-cli.ts
1952
1952
  import { mkdirSync as mkdirSync6 } from "node:fs";
1953
1953
  import { homedir as homedir5, hostname as hostname4 } from "node:os";
1954
- import { join as join9 } from "node:path";
1954
+ import { join as join10 } from "node:path";
1955
1955
 
1956
1956
  // src/worker/api.ts
1957
1957
  import { readFile as readFile2 } from "node:fs/promises";
@@ -2003,6 +2003,7 @@ var ErrorApi = class extends Error {
2003
2003
  return this.estado === 409;
2004
2004
  }
2005
2005
  };
2006
+ var MIME_PIEZA = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", webp: "image/webp" };
2006
2007
  function crearClienteApi(base, token, f = fetch) {
2007
2008
  const cab = (extra = {}) => ({ ...token ? { authorization: `Bearer ${token}` } : {}, ...extra });
2008
2009
  async function llamar(metodo, ruta, cuerpo) {
@@ -2047,14 +2048,31 @@ function crearClienteApi(base, token, f = fetch) {
2047
2048
  const form = new FormData();
2048
2049
  form.append("archivo", new Blob([bytes], { type: "video/mp4" }), basename2(ruta));
2049
2050
  return leer(await f(`${base}${base_mp4}`, { method: "POST", headers: cab(), body: form }));
2051
+ },
2052
+ async adjuntarPieza(id, version, ruta) {
2053
+ const nombre = basename2(ruta);
2054
+ const tipo = MIME_PIEZA[nombre.split(".").pop().toLowerCase()] ?? "application/octet-stream";
2055
+ const bytes = await readFile2(ruta);
2056
+ const ajustes = await llamar("GET", "/api/ajustes");
2057
+ const base_pz = `/api/videos/${id}/versiones/${version}/piezas/${encodeURIComponent(nombre)}`;
2058
+ if (ajustes.s3?.bucket) {
2059
+ const sub = await llamar("POST", `${base_pz}/url`, {});
2060
+ const put = await f(sub.url, { method: "PUT", headers: sub.cabeceras, body: bytes });
2061
+ if (!put.ok) throw new ErrorApi(put.status, `la subida a S3 de ${nombre} fall\xF3 (HTTP ${put.status})`);
2062
+ await llamar("POST", `${base_pz}/confirmar`, {});
2063
+ return;
2064
+ }
2065
+ const form = new FormData();
2066
+ form.append("archivo", new Blob([bytes], { type: tipo }), nombre);
2067
+ await leer(await f(`${base}${base_pz}`, { method: "POST", headers: cab(), body: form }));
2050
2068
  }
2051
2069
  };
2052
2070
  }
2053
2071
 
2054
2072
  // src/worker/worker.ts
2055
2073
  import { hostname as hostname2 } from "node:os";
2056
- import { access, mkdir, readFile as readFile4, rm, writeFile } from "node:fs/promises";
2057
- import { join as join8 } from "node:path";
2074
+ import { access, mkdir as mkdir2, readFile as readFile4, rm, writeFile as writeFile2 } from "node:fs/promises";
2075
+ import { join as join9 } from "node:path";
2058
2076
 
2059
2077
  // src/worker/motor.ts
2060
2078
  import { spawn as spawn2, spawnSync } from "node:child_process";
@@ -2195,6 +2213,53 @@ function traducirPedido(r2) {
2195
2213
  return p;
2196
2214
  }
2197
2215
 
2216
+ // src/worker/media.ts
2217
+ import { createHash as createHash2 } from "node:crypto";
2218
+ import { mkdir, writeFile } from "node:fs/promises";
2219
+ import { extname as extname2, join as join8 } from "node:path";
2220
+ var ErrorMedia = class extends Error {
2221
+ constructor(mensaje, reintentable) {
2222
+ super(mensaje);
2223
+ this.reintentable = reintentable;
2224
+ this.name = "ErrorMedia";
2225
+ }
2226
+ reintentable;
2227
+ };
2228
+ var TIPOS_DESCARGABLES = ["imagen"];
2229
+ var EXTENSION_SEGURA = /^\.[a-z0-9]{1,5}$/;
2230
+ function extensionDe(a) {
2231
+ const e = extname2(a.nombre ?? "").toLowerCase();
2232
+ if (EXTENSION_SEGURA.test(e)) return e;
2233
+ const porMime = { "image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp", "image/gif": ".gif", "image/svg+xml": ".svg" };
2234
+ return porMime[a.mime ?? ""] ?? "";
2235
+ }
2236
+ async function descargarMedia(media, pedidoDir, descargar2 = (u) => fetch(u)) {
2237
+ const salida = {};
2238
+ const ids = Object.keys(media ?? {}).filter((id) => TIPOS_DESCARGABLES.includes(media[id].tipo));
2239
+ if (ids.length === 0) return salida;
2240
+ await mkdir(join8(pedidoDir, "media"), { recursive: true });
2241
+ for (const id of ids) {
2242
+ const a = media[id];
2243
+ if (!/^as_[A-Za-z0-9_-]+$/.test(id)) throw new ErrorMedia(`id de asset no v\xE1lido: ${id}`, false);
2244
+ if (!a.url) throw new ErrorMedia(`el asset ${id} (${a.nombre ?? "sin nombre"}) no tiene archivo en el servidor`, false);
2245
+ let r2;
2246
+ try {
2247
+ r2 = await descargar2(a.url);
2248
+ } catch (e) {
2249
+ throw new ErrorMedia(`no se pudo bajar el asset ${id}: ${e.message}`, true);
2250
+ }
2251
+ if (!r2.ok) throw new ErrorMedia(`el servidor respondi\xF3 ${r2.status} al bajar el asset ${id}`, r2.status >= 500 || r2.status === 429);
2252
+ const datos = Buffer.from(await r2.arrayBuffer());
2253
+ if (a.bytes > 0 && datos.length !== a.bytes) throw new ErrorMedia(`el asset ${id} baj\xF3 con ${datos.length} bytes y deber\xEDa tener ${a.bytes}`, true);
2254
+ const sha = createHash2("sha256").update(datos).digest("hex");
2255
+ if (a.sha256 && sha !== a.sha256) throw new ErrorMedia(`el asset ${id} no coincide con su sha256 (baj\xF3 ${sha.slice(0, 12)}\u2026, esperado ${a.sha256.slice(0, 12)}\u2026)`, true);
2256
+ const ruta = `media/${id}${extensionDe(a)}`;
2257
+ await writeFile(join8(pedidoDir, ruta), datos);
2258
+ salida[id] = { ruta, tipo: a.tipo, nombre: a.nombre, mime: a.mime };
2259
+ }
2260
+ return salida;
2261
+ }
2262
+
2198
2263
  // src/worker/worker.ts
2199
2264
  var dormirReal = (ms) => new Promise((r2) => setTimeout(r2, ms));
2200
2265
  var existe = (ruta) => access(ruta).then(() => true, () => false);
@@ -2213,9 +2278,9 @@ async function trabajar(c, d, r2) {
2213
2278
  const dormir = d.dormir ?? dormirReal;
2214
2279
  const { api } = d;
2215
2280
  const id = r2.video_id;
2216
- const raiz = join8(c.trabajoDir, `${id}-v${r2.version}-i${r2.intento}`);
2217
- const pedidoDir = join8(raiz, "pedido");
2218
- const salidaDir = join8(raiz, "salida");
2281
+ const raiz = join9(c.trabajoDir, `${id}-v${r2.version}-i${r2.intento}`);
2282
+ const pedidoDir = join9(raiz, "pedido");
2283
+ const salidaDir = join9(raiz, "salida");
2219
2284
  log(`reclamado ${id} v${r2.version} (intento ${r2.intento}): ${r2.titulo}`);
2220
2285
  const fallar = async (etapa, causa, codigo, reintentable) => {
2221
2286
  log(`fall\xF3 ${id}: ${causa}`);
@@ -2230,9 +2295,16 @@ async function trabajar(c, d, r2) {
2230
2295
  if (e instanceof PedidoNoSoportado) return await fallar("voz", e.message, null, false);
2231
2296
  throw e;
2232
2297
  }
2233
- await mkdir(pedidoDir, { recursive: true });
2234
- await mkdir(salidaDir, { recursive: true });
2235
- await writeFile(join8(pedidoDir, "pedido.json"), JSON.stringify(pedido, null, 2));
2298
+ await mkdir2(pedidoDir, { recursive: true });
2299
+ await mkdir2(salidaDir, { recursive: true });
2300
+ try {
2301
+ const locales = await descargarMedia(r2.media, pedidoDir, d.descargar);
2302
+ if (Object.keys(locales).length) pedido["archivos_locales"] = locales;
2303
+ } catch (e) {
2304
+ if (e instanceof ErrorMedia) return await fallar("media", e.message, null, e.reintentable);
2305
+ throw e;
2306
+ }
2307
+ await writeFile2(join9(pedidoDir, "pedido.json"), JSON.stringify(pedido, null, 2));
2236
2308
  const parar = new AbortController();
2237
2309
  const alCerrar = () => parar.abort();
2238
2310
  d.senal?.addEventListener("abort", alCerrar, { once: true });
@@ -2276,7 +2348,7 @@ async function trabajar(c, d, r2) {
2276
2348
  }
2277
2349
  if (cancelado) return { tipo: "cancelado", videoId: id };
2278
2350
  if (res.abortado) return await fallar(ultimo.etapa, "el worker se detuvo mientras generaba; se reintentar\xE1", null, true);
2279
- const mp4 = join8(salidaDir, "video.mp4");
2351
+ const mp4 = join9(salidaDir, "video.mp4");
2280
2352
  const advertencias = [];
2281
2353
  if (res.codigo === 0 || res.codigo === 15) {
2282
2354
  if (!await existe(mp4)) return await fallar(ultimo.etapa, `el motor termin\xF3 bien pero no dej\xF3 video.mp4`, res.codigo, true);
@@ -2287,6 +2359,9 @@ async function trabajar(c, d, r2) {
2287
2359
  await api.progreso(id, { etapa: "revision", porcentaje: 100, mensaje: advertencias[0], nivel: "advertencia" }).catch(() => {
2288
2360
  });
2289
2361
  }
2362
+ const sub = await subirPiezas(d, id, r2.version, salidaDir, dormir, log);
2363
+ if (sub === "cancelado") return { tipo: "cancelado", videoId: id };
2364
+ if (sub instanceof Error) return await fallar("piezas", `no se pudieron subir las piezas: ${sub.message}`, null, true);
2290
2365
  const adj = await adjuntar(d, id, r2.version, mp4, dormir, log);
2291
2366
  if (adj === "cancelado") return { tipo: "cancelado", videoId: id };
2292
2367
  if (adj instanceof Error) return await fallar("revision", `no se pudo adjuntar el MP4: ${adj.message}`, null, true);
@@ -2300,13 +2375,41 @@ async function trabajar(c, d, r2) {
2300
2375
  }
2301
2376
  async function checksFallidos(salidaDir) {
2302
2377
  try {
2303
- const rev = JSON.parse(await readFile4(join8(salidaDir, "revision.json"), "utf8"));
2378
+ const rev = JSON.parse(await readFile4(join9(salidaDir, "revision.json"), "utf8"));
2304
2379
  const malos = (rev.checks ?? []).filter((x) => !x.ok && x.nivel === "requerido").map((x) => x.detalle ? `${x.id} (${x.detalle})` : x.id);
2305
2380
  return malos.length ? malos.join(", ") : "sin detalle";
2306
2381
  } catch {
2307
2382
  return "sin detalle (no se pudo leer revision.json)";
2308
2383
  }
2309
2384
  }
2385
+ async function piezasDelManifiesto(salidaDir) {
2386
+ try {
2387
+ const m = JSON.parse(await readFile4(join9(salidaDir, "manifiesto.json"), "utf8"));
2388
+ return (m.renders?.[0]?.archivos?.piezas ?? []).flatMap((p) => typeof p.ruta === "string" ? [join9(salidaDir, p.ruta)] : []);
2389
+ } catch {
2390
+ return [];
2391
+ }
2392
+ }
2393
+ async function subirPiezas(d, id, version, salidaDir, dormir, log) {
2394
+ for (const ruta of await piezasDelManifiesto(salidaDir)) {
2395
+ let hecho = false;
2396
+ let ultimo = new Error("sin intentos");
2397
+ for (let i = 1; i <= 3 && !hecho; i++) {
2398
+ try {
2399
+ await d.api.adjuntarPieza(id, version, ruta);
2400
+ hecho = true;
2401
+ } catch (e) {
2402
+ if (e instanceof ErrorApi && (e.conflicto || e.estado === 404)) return "cancelado";
2403
+ ultimo = e;
2404
+ log(`subir pieza fall\xF3 (intento ${i}/3): ${ultimo.message}`);
2405
+ if (i < 3) await dormir(1e3 * 2 ** i);
2406
+ }
2407
+ }
2408
+ if (!hecho) return ultimo;
2409
+ log(`pieza subida: ${ruta.split("/").pop()}`);
2410
+ }
2411
+ return "ok";
2412
+ }
2310
2413
  async function adjuntar(d, id, version, mp4, dormir, log) {
2311
2414
  let ultimo = new Error("sin intentos");
2312
2415
  for (let i = 1; i <= 3; i++) {
@@ -2490,7 +2593,7 @@ function configWorker(o, conexion, env, nombreEquipo, casa) {
2490
2593
  CLAQUETA_API_URL: conexion.url,
2491
2594
  WORKER_NOMBRE: o.agente ?? nombreEquipo,
2492
2595
  MOTOR_IMAGEN: o.motorImagen ?? IMAGEN_POR_DEFECTO,
2493
- WORKER_TRABAJO_DIR: env["WORKER_TRABAJO_DIR"] || join9(casa, ".cache", "claqueta", "trabajo"),
2596
+ WORKER_TRABAJO_DIR: env["WORKER_TRABAJO_DIR"] || join10(casa, ".cache", "claqueta", "trabajo"),
2494
2597
  WORKER_SONDEO_S: String(o.intervaloS ?? (env["WORKER_SONDEO_S"] || 10))
2495
2598
  });
2496
2599
  return { ...c, apiToken: conexion.token, unaVez: o.unaVez, siFallaRevision: o.siFallaRevision };
package/package.json CHANGED
@@ -1,11 +1,20 @@
1
1
  {
2
2
  "name": "claqueta-mcp",
3
- "version": "0.8.2",
3
+ "version": "0.9.0",
4
4
  "description": "Cliente de Claqueta: puente stdio para el servidor MCP remoto, comando setup y worker de la cola. Úsalo con npx en Claude Desktop o Claude Code.",
5
5
  "type": "module",
6
- "bin": { "claqueta-mcp": "dist/cli.js" },
7
- "files": ["dist/cli.js", "motor/", "README.md", "LICENSE"],
8
- "engines": { "node": ">=18" },
6
+ "bin": {
7
+ "claqueta-mcp": "dist/cli.js"
8
+ },
9
+ "files": [
10
+ "dist/cli.js",
11
+ "motor/",
12
+ "README.md",
13
+ "LICENSE"
14
+ ],
15
+ "engines": {
16
+ "node": ">=18"
17
+ },
9
18
  "license": "MIT",
10
19
  "author": "Itzamnai",
11
20
  "repository": {
@@ -13,9 +22,21 @@
13
22
  "url": "git+https://github.com/ajuarez93/claqueta-mcp.git"
14
23
  },
15
24
  "homepage": "https://github.com/ajuarez93/claqueta-mcp#readme",
16
- "bugs": { "url": "https://github.com/ajuarez93/claqueta-mcp/issues" },
17
- "keywords": ["mcp", "model-context-protocol", "claqueta", "claude", "stdio", "bridge", "video"],
18
- "publishConfig": { "access": "public" },
25
+ "bugs": {
26
+ "url": "https://github.com/ajuarez93/claqueta-mcp/issues"
27
+ },
28
+ "keywords": [
29
+ "mcp",
30
+ "model-context-protocol",
31
+ "claqueta",
32
+ "claude",
33
+ "stdio",
34
+ "bridge",
35
+ "video"
36
+ ],
37
+ "publishConfig": {
38
+ "access": "public"
39
+ },
19
40
  "scripts": {
20
41
  "build": "node scripts/build.mjs",
21
42
  "sincronizar-motor": "node scripts/sincronizar-motor.mjs",