claqueta-mcp 0.10.0 → 0.11.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 (2) hide show
  1. package/dist/cli.js +175 -37
  2. package/package.json +1 -1
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.10.0" : "dev";
53
+ var VERSION = true ? "0.11.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:
@@ -1166,14 +1166,14 @@ var SetupCancelado = class extends Error {
1166
1166
  }
1167
1167
  };
1168
1168
  function preguntarEnTerminal(pregunta, entrada = process.stdin, salida = process.stderr) {
1169
- return new Promise((resolve3) => {
1169
+ return new Promise((resolve4) => {
1170
1170
  const rl = createInterface({ input: entrada, output: salida });
1171
1171
  let listo = false;
1172
1172
  const fin = (r2) => {
1173
1173
  if (listo) return;
1174
1174
  listo = true;
1175
1175
  rl.close();
1176
- resolve3(r2);
1176
+ resolve4(r2);
1177
1177
  };
1178
1178
  rl.on("SIGINT", () => {
1179
1179
  salida.write("\n");
@@ -1185,14 +1185,14 @@ function preguntarEnTerminal(pregunta, entrada = process.stdin, salida = process
1185
1185
  }
1186
1186
  var CMD_NO_ENCONTRADO = 9009;
1187
1187
  function crearEjecutarClaude(plataforma = process.platform, exec = execFile2) {
1188
- return (args2) => new Promise((resolve3) => {
1188
+ return (args2) => new Promise((resolve4) => {
1189
1189
  const [cmd, argv] = plataforma === "win32" ? ["cmd.exe", ["/c", "claude", ...args2]] : ["claude", args2];
1190
1190
  exec(cmd, argv, { timeout: 3e4 }, (err, stdout, stderr) => {
1191
1191
  const code = err?.code;
1192
- if (err && (code === "ENOENT" || code === "EINVAL")) return resolve3({ ausente: true, codigo: 127, salida: "" });
1192
+ if (err && (code === "ENOENT" || code === "EINVAL")) return resolve4({ ausente: true, codigo: 127, salida: "" });
1193
1193
  const codigo = err ? typeof code === "number" ? code : 1 : 0;
1194
- if (plataforma === "win32" && codigo === CMD_NO_ENCONTRADO) return resolve3({ ausente: true, codigo: 127, salida: "" });
1195
- resolve3({ ausente: false, codigo, salida: `${stdout}${stderr}` });
1194
+ if (plataforma === "win32" && codigo === CMD_NO_ENCONTRADO) return resolve4({ ausente: true, codigo: 127, salida: "" });
1195
+ resolve4({ ausente: false, codigo, salida: `${stdout}${stderr}` });
1196
1196
  });
1197
1197
  });
1198
1198
  }
@@ -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 join10 } from "node:path";
1954
+ import { join as join11 } 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 camposCosto = (o) => o.costoUsd === void 0 ? {} : { costo_usd: o.costoUsd, ...o.desglose && Object.keys(o.desglose).length ? { desglose: o.desglose } : {} };
2006
2007
  var MIME_PIEZA = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", webp: "image/webp" };
2007
2008
  function crearClienteApi(base, token, f = fetch) {
2008
2009
  const cab = (extra = {}) => ({ ...token ? { authorization: `Bearer ${token}` } : {}, ...extra });
@@ -2024,18 +2025,34 @@ function crearClienteApi(base, token, f = fetch) {
2024
2025
  }
2025
2026
  throw new ErrorApi(r2.status, msg);
2026
2027
  }
2028
+ async function subirRender(id, version, clave, ruta, revision) {
2029
+ const bytes = await readFile2(ruta);
2030
+ const ajustes = await llamar("GET", "/api/ajustes");
2031
+ const base_rd = `/api/videos/${id}/versiones/${version}/renders/${encodeURIComponent(clave)}`;
2032
+ if (ajustes.s3?.bucket) {
2033
+ const sub = await llamar("POST", `${base_rd}/url`, {});
2034
+ const put = await f(sub.url, { method: "PUT", headers: sub.cabeceras, body: bytes });
2035
+ if (!put.ok) throw new ErrorApi(put.status, `la subida a S3 del render ${clave} fall\xF3 (HTTP ${put.status})`);
2036
+ await llamar("POST", `${base_rd}/confirmar`, { nombre: basename2(ruta), ...revision ? { revision } : {} });
2037
+ return;
2038
+ }
2039
+ const form = new FormData();
2040
+ if (revision) form.append("revision", JSON.stringify(revision));
2041
+ form.append("archivo", new Blob([bytes], { type: "video/mp4" }), basename2(ruta));
2042
+ await leer(await f(`${base}${base_rd}`, { method: "POST", headers: cab(), body: form }));
2043
+ }
2027
2044
  return {
2028
2045
  reclamar: (o) => {
2029
2046
  const huerfanos = acotarHuerfanosMin(o.huerfanosMin);
2030
2047
  const host = acotarOpcional(o.hostname, LIMITES.hostname);
2031
2048
  const ver = acotarOpcional(o.version, LIMITES.version);
2032
- return llamar("POST", "/api/cola/reclamar", { agente: acotarTexto(o.agente, LIMITES.agente, "worker"), max_reintentos: o.maxReintentos, ...host ? { hostname: host } : {}, ...ver ? { version: ver } : {}, ...huerfanos > 0 ? { huerfanos_min: huerfanos } : {} });
2049
+ return llamar("POST", "/api/cola/reclamar", { agente: acotarTexto(o.agente, LIMITES.agente, "worker"), max_reintentos: o.maxReintentos, ...host ? { hostname: host } : {}, ...ver ? { version: ver } : {}, ...huerfanos > 0 ? { huerfanos_min: huerfanos } : {}, ...o.formatosSoportados?.length ? { formatos_soportados: [...o.formatosSoportados] } : {} });
2033
2050
  },
2034
2051
  async progreso(id, p) {
2035
2052
  await llamar("POST", `/api/videos/${id}/progreso`, { ...p, etapa: acotarTexto(p.etapa, LIMITES.etapa, "desconocida"), porcentaje: acotarPorcentaje(p.porcentaje), mensaje: acotarTexto(p.mensaje, LIMITES.mensaje, "sin mensaje") });
2036
2053
  },
2037
- fallo: (id, x) => llamar("POST", `/api/videos/${id}/fallo`, { etapa: acotarOpcional(x.etapa, LIMITES.etapa) ?? null, causa: acotarTexto(x.causa, LIMITES.causa, "fallo sin causa conocida"), codigo: Number.isInteger(x.codigo) ? x.codigo : null, max_reintentos: x.maxReintentos, reintentable: x.reintentable }),
2038
- async adjuntarMp4(id, version, ruta) {
2054
+ fallo: (id, x) => llamar("POST", `/api/videos/${id}/fallo`, { etapa: acotarOpcional(x.etapa, LIMITES.etapa) ?? null, causa: acotarTexto(x.causa, LIMITES.causa, "fallo sin causa conocida"), codigo: Number.isInteger(x.codigo) ? x.codigo : null, max_reintentos: x.maxReintentos, reintentable: x.reintentable, ...camposCosto(x) }),
2055
+ async adjuntarMp4(id, version, ruta, o = {}) {
2039
2056
  const bytes = await readFile2(ruta);
2040
2057
  const ajustes = await llamar("GET", "/api/ajustes");
2041
2058
  const base_mp4 = `/api/videos/${id}/versiones/${version}/mp4`;
@@ -2043,12 +2060,25 @@ function crearClienteApi(base, token, f = fetch) {
2043
2060
  const sub = await llamar("POST", `${base_mp4}/url`, {});
2044
2061
  const put = await f(sub.url, { method: "PUT", headers: sub.cabeceras, body: bytes });
2045
2062
  if (!put.ok) throw new ErrorApi(put.status, `la subida a S3 fall\xF3 (HTTP ${put.status})`);
2046
- return llamar("POST", `${base_mp4}/confirmar`, { nombre: basename2(ruta) });
2063
+ return llamar("POST", `${base_mp4}/confirmar`, { nombre: basename2(ruta), ...camposCosto(o), ...o.revision ? { revision: o.revision } : {}, ...o.renders?.length ? { renders: o.renders } : {} });
2047
2064
  }
2048
2065
  const form = new FormData();
2066
+ const costo = camposCosto(o);
2067
+ if (costo["costo_usd"] !== void 0) form.append("costo_usd", String(costo["costo_usd"]));
2068
+ if (costo["desglose"]) form.append("desglose", JSON.stringify(costo["desglose"]));
2069
+ if (o.revision) form.append("revision", JSON.stringify(o.revision));
2070
+ if (o.renders?.length) form.append("renders", JSON.stringify(o.renders));
2049
2071
  form.append("archivo", new Blob([bytes], { type: "video/mp4" }), basename2(ruta));
2050
2072
  return leer(await f(`${base}${base_mp4}`, { method: "POST", headers: cab(), body: form }));
2051
2073
  },
2074
+ async adjuntarRender(id, version, clave, ruta, revision) {
2075
+ try {
2076
+ await subirRender(id, version, clave, ruta, revision);
2077
+ } catch (e) {
2078
+ if (e instanceof ErrorApi && e.estado === 404 && e.message === "Not Found") throw new ErrorApi(501, "la API no admite renders m\xFAltiples todav\xEDa (CLA-57): actualiza el servidor antes que el worker");
2079
+ throw e;
2080
+ }
2081
+ },
2052
2082
  async adjuntarPieza(id, version, ruta) {
2053
2083
  const nombre = basename2(ruta);
2054
2084
  const tipo = MIME_PIEZA[nombre.split(".").pop().toLowerCase()] ?? "application/octet-stream";
@@ -2071,8 +2101,8 @@ function crearClienteApi(base, token, f = fetch) {
2071
2101
 
2072
2102
  // src/worker/worker.ts
2073
2103
  import { hostname as hostname2 } from "node:os";
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";
2104
+ import { access, mkdir as mkdir2, readFile as readFile5, rm, writeFile as writeFile2 } from "node:fs/promises";
2105
+ import { join as join10, resolve as resolve2, sep } from "node:path";
2076
2106
 
2077
2107
  // src/worker/motor.ts
2078
2108
  import { spawn as spawn2, spawnSync } from "node:child_process";
@@ -2190,7 +2220,64 @@ function causaLegible(r2, timeoutMin) {
2190
2220
  return cola ? `${base} (${cola.slice(0, 300)})` : base;
2191
2221
  }
2192
2222
 
2223
+ // src/worker/manifiesto.ts
2224
+ import { readFile as readFile4 } from "node:fs/promises";
2225
+ import { join as join8 } from "node:path";
2226
+ var esEntero = (x) => Number.isInteger(x) && x > 0;
2227
+ var dosDecimales = (x) => Math.round(x * 100) / 100;
2228
+ async function leerManifiesto(salidaDir, log = () => {
2229
+ }) {
2230
+ let crudo;
2231
+ try {
2232
+ crudo = JSON.parse(await readFile4(join8(salidaDir, "manifiesto.json"), "utf8"));
2233
+ if (!crudo || typeof crudo !== "object") throw new Error("no es un objeto");
2234
+ } catch {
2235
+ return { renders: [], costo: void 0 };
2236
+ }
2237
+ return { renders: leerRenders(crudo["renders"], log), costo: leerCosto(crudo["costos_usd"]) };
2238
+ }
2239
+ function leerRenders(lista, log) {
2240
+ if (!Array.isArray(lista)) return [];
2241
+ const renders = [];
2242
+ lista.forEach((r2, i) => {
2243
+ const x = r2 ?? {};
2244
+ if (!esEntero(x["ancho"]) || !esEntero(x["alto"])) {
2245
+ log(`manifiesto: renders[${i}] sin ancho/alto v\xE1lidos; lo ignoro`);
2246
+ return;
2247
+ }
2248
+ const rev = x["revision"] ?? {};
2249
+ const ruta = (x["archivos"] ?? {}).video?.ruta;
2250
+ const etiqueta = `${x["ancho"]}x${x["alto"]}`;
2251
+ renders.push({
2252
+ aspecto: typeof x["aspecto"] === "string" ? x["aspecto"] : void 0,
2253
+ ancho: x["ancho"],
2254
+ alto: x["alto"],
2255
+ etiqueta,
2256
+ ruta: typeof ruta === "string" && ruta ? ruta : `renders/${etiqueta}/video.mp4`,
2257
+ destinos: Array.isArray(x["destinos"]) ? x["destinos"].filter((d) => typeof d === "string") : [],
2258
+ aprobada: typeof rev["aprobada"] === "boolean" ? rev["aprobada"] : void 0,
2259
+ checksFallidos: Array.isArray(rev["checks_fallidos"]) ? rev["checks_fallidos"].filter((c) => typeof c === "string") : []
2260
+ });
2261
+ });
2262
+ return renders;
2263
+ }
2264
+ function leerCosto(c) {
2265
+ if (!c || typeof c !== "object") return void 0;
2266
+ const costos = c;
2267
+ const total = costos["total"];
2268
+ if (typeof total !== "number" || !Number.isFinite(total) || total <= 0) return void 0;
2269
+ const fuente = costos["desglose"] && typeof costos["desglose"] === "object" ? costos["desglose"] : costos;
2270
+ const desglose = {};
2271
+ for (const [k, v] of Object.entries(fuente)) {
2272
+ if (k === "total" || k === "desglose") continue;
2273
+ if (typeof v === "number" && Number.isFinite(v) && v >= 0) desglose[k] = dosDecimales(v);
2274
+ }
2275
+ return { costoUsd: dosDecimales(total), ...Object.keys(desglose).length ? { desglose } : {} };
2276
+ }
2277
+
2193
2278
  // src/worker/pedido.ts
2279
+ var FORMATOS_SOPORTADOS = ["9:16", "16:9", "1:1", "4:5"];
2280
+ var RESOLUCIONES = { "9:16": [1080, 1920], "16:9": [1920, 1080], "1:1": [1080, 1080], "4:5": [1080, 1350] };
2194
2281
  var PedidoNoSoportado = class extends Error {
2195
2282
  constructor(mensaje) {
2196
2283
  super(mensaje);
@@ -2206,17 +2293,30 @@ function traducirPedido(r2) {
2206
2293
  if (plantilla !== void 0 && plantilla !== "plantilla-vertical-a") {
2207
2294
  throw new PedidoNoSoportado(`el motor solo tiene la plantilla \xABplantilla-vertical-a\xBB (el pedido pide \xAB${String(plantilla)}\xBB)`);
2208
2295
  }
2209
- const f = p["formato"];
2210
- if (f && (f.ancho !== void 0 && f.ancho !== 1080 || f.alto !== void 0 && f.alto !== 1920 || f.aspecto !== void 0 && f.aspecto !== "9:16")) {
2211
- throw new PedidoNoSoportado("el motor solo genera 1080x1920 (9:16)");
2296
+ if (p["formato"] !== void 0) validarFormato(p["formato"], "formato");
2297
+ const renders = p["renders"];
2298
+ if (renders !== void 0) {
2299
+ if (!Array.isArray(renders)) throw new PedidoNoSoportado("renders debe ser una lista");
2300
+ renders.forEach((x, i) => validarFormato(x, `renders[${i}]`));
2212
2301
  }
2213
2302
  return p;
2214
2303
  }
2304
+ function validarFormato(f, donde) {
2305
+ const soportados = `soportados: ${FORMATOS_SOPORTADOS.map((a) => `${a} (${RESOLUCIONES[a].join("x")})`).join(", ")}`;
2306
+ if (!f || typeof f !== "object") throw new PedidoNoSoportado(`${donde} debe ser un objeto; ${soportados}`);
2307
+ const { aspecto, ancho, alto } = f;
2308
+ const porAspecto = aspecto === void 0 ? void 0 : RESOLUCIONES[String(aspecto)];
2309
+ if (aspecto !== void 0 && !porAspecto) throw new PedidoNoSoportado(`${donde}: aspecto \xAB${String(aspecto)}\xBB no soportado; ${soportados}`);
2310
+ if (ancho === void 0 && alto === void 0) return;
2311
+ const porTamano = Object.values(RESOLUCIONES).find(([w, h]) => w === ancho && h === alto);
2312
+ if (!porTamano) throw new PedidoNoSoportado(`${donde}: resoluci\xF3n ${String(ancho)}x${String(alto)} no soportada; ${soportados}`);
2313
+ if (porAspecto && porAspecto !== porTamano) throw new PedidoNoSoportado(`${donde}: el aspecto ${String(aspecto)} no corresponde a ${String(ancho)}x${String(alto)}`);
2314
+ }
2215
2315
 
2216
2316
  // src/worker/media.ts
2217
2317
  import { createHash as createHash2 } from "node:crypto";
2218
2318
  import { mkdir, writeFile } from "node:fs/promises";
2219
- import { extname as extname2, join as join8 } from "node:path";
2319
+ import { extname as extname2, join as join9 } from "node:path";
2220
2320
  var ErrorMedia = class extends Error {
2221
2321
  constructor(mensaje, reintentable) {
2222
2322
  super(mensaje);
@@ -2237,7 +2337,7 @@ async function descargarMedia(media, pedidoDir, descargar2 = (u) => fetch(u)) {
2237
2337
  const salida = {};
2238
2338
  const ids = Object.keys(media ?? {}).filter((id) => TIPOS_DESCARGABLES.includes(media[id].tipo));
2239
2339
  if (ids.length === 0) return salida;
2240
- await mkdir(join8(pedidoDir, "media"), { recursive: true });
2340
+ await mkdir(join9(pedidoDir, "media"), { recursive: true });
2241
2341
  for (const id of ids) {
2242
2342
  const a = media[id];
2243
2343
  if (!/^as_[A-Za-z0-9_-]+$/.test(id)) throw new ErrorMedia(`id de asset no v\xE1lido: ${id}`, false);
@@ -2254,7 +2354,7 @@ async function descargarMedia(media, pedidoDir, descargar2 = (u) => fetch(u)) {
2254
2354
  const sha = createHash2("sha256").update(datos).digest("hex");
2255
2355
  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
2356
  const ruta = `media/${id}${extensionDe(a)}`;
2257
- await writeFile(join8(pedidoDir, ruta), datos);
2357
+ await writeFile(join9(pedidoDir, ruta), datos);
2258
2358
  salida[id] = { ruta, tipo: a.tipo, nombre: a.nombre, mime: a.mime };
2259
2359
  }
2260
2360
  return salida;
@@ -2267,7 +2367,7 @@ async function procesarSiguiente(c, d) {
2267
2367
  const log = d.log ?? (() => {
2268
2368
  });
2269
2369
  const { api } = d;
2270
- const { rescatados, reclamado } = await api.reclamar({ agente: c.nombre, huerfanosMin: c.huerfanosMin, maxReintentos: c.maxReintentos, hostname: hostname2(), ...process.env["CLAQUETA_VERSION"] ? { version: process.env["CLAQUETA_VERSION"] } : {} });
2370
+ const { rescatados, reclamado } = await api.reclamar({ agente: c.nombre, huerfanosMin: c.huerfanosMin, maxReintentos: c.maxReintentos, hostname: hostname2(), formatosSoportados: FORMATOS_SOPORTADOS, ...process.env["CLAQUETA_VERSION"] ? { version: process.env["CLAQUETA_VERSION"] } : {} });
2271
2371
  for (const id of rescatados) log(`rescatado ${id}: estaba en generando sin latidos`);
2272
2372
  if (!reclamado) return { tipo: "vacio" };
2273
2373
  return trabajar(c, d, reclamado);
@@ -2278,13 +2378,14 @@ async function trabajar(c, d, r2) {
2278
2378
  const dormir = d.dormir ?? dormirReal;
2279
2379
  const { api } = d;
2280
2380
  const id = r2.video_id;
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");
2381
+ const raiz = join10(c.trabajoDir, `${id}-v${r2.version}-i${r2.intento}`);
2382
+ const pedidoDir = join10(raiz, "pedido");
2383
+ const salidaDir = join10(raiz, "salida");
2284
2384
  log(`reclamado ${id} v${r2.version} (intento ${r2.intento}): ${r2.titulo}`);
2385
+ let costo;
2285
2386
  const fallar = async (etapa, causa, codigo, reintentable) => {
2286
2387
  log(`fall\xF3 ${id}: ${causa}`);
2287
- const f = await api.fallo(id, { etapa, causa, codigo, maxReintentos: c.maxReintentos, reintentable });
2388
+ const f = await api.fallo(id, { etapa, causa, codigo, maxReintentos: c.maxReintentos, reintentable, ...costo ?? {} });
2288
2389
  return { tipo: "fallo", videoId: id, causa, reencolado: f.reencolado };
2289
2390
  };
2290
2391
  try {
@@ -2304,7 +2405,7 @@ async function trabajar(c, d, r2) {
2304
2405
  if (e instanceof ErrorMedia) return await fallar("media", e.message, null, e.reintentable);
2305
2406
  throw e;
2306
2407
  }
2307
- await writeFile2(join9(pedidoDir, "pedido.json"), JSON.stringify(pedido, null, 2));
2408
+ await writeFile2(join10(pedidoDir, "pedido.json"), JSON.stringify(pedido, null, 2));
2308
2409
  const parar = new AbortController();
2309
2410
  const alCerrar = () => parar.abort();
2310
2411
  d.senal?.addEventListener("abort", alCerrar, { once: true });
@@ -2348,10 +2449,14 @@ async function trabajar(c, d, r2) {
2348
2449
  }
2349
2450
  if (cancelado) return { tipo: "cancelado", videoId: id };
2350
2451
  if (res.abortado) return await fallar(ultimo.etapa, "el worker se detuvo mientras generaba; se reintentar\xE1", null, true);
2351
- const mp4 = join9(salidaDir, "video.mp4");
2452
+ const mp4 = join10(salidaDir, "video.mp4");
2352
2453
  const advertencias = [];
2353
2454
  if (res.codigo === 0 || res.codigo === 15) {
2354
2455
  if (!await existe(mp4)) return await fallar(ultimo.etapa, `el motor termin\xF3 bien pero no dej\xF3 video.mp4`, res.codigo, true);
2456
+ const manifiesto = await leerManifiesto(salidaDir, log);
2457
+ costo = manifiesto.costo;
2458
+ const avisar = (mensaje, nivel, datos) => api.progreso(id, { etapa: "revision", porcentaje: 100, mensaje, ...nivel ? { nivel } : {}, ...datos ? { datos } : {} }).catch(() => {
2459
+ });
2355
2460
  if (res.codigo === 15) {
2356
2461
  const f = await checksFallidos(salidaDir);
2357
2462
  if (c.siFallaRevision === "rechazar") return await fallar("revision", `La revisi\xF3n autom\xE1tica no pas\xF3: ${f}`, 15, true);
@@ -2362,7 +2467,33 @@ async function trabajar(c, d, r2) {
2362
2467
  const sub = await subirPiezas(d, id, r2.version, salidaDir, dormir, log);
2363
2468
  if (sub === "cancelado") return { tipo: "cancelado", videoId: id };
2364
2469
  if (sub instanceof Error) return await fallar("piezas", `no se pudieron subir las piezas: ${sub.message}`, null, true);
2365
- const adj = await adjuntar(d, id, r2.version, mp4, dormir, log);
2470
+ const renders = manifiesto.renders;
2471
+ const total = Math.max(renders.length, 1);
2472
+ const subidos = [];
2473
+ for (const [k, render] of renders.slice(1).entries()) {
2474
+ const ruta = rutaDeRender(salidaDir, render);
2475
+ if (!ruta || !await existe(ruta)) return await fallar("revision", `el manifiesto anuncia el render ${render.etiqueta} pero no est\xE1 ${render.ruta}`, res.codigo, true);
2476
+ if (render.aprobada === false) {
2477
+ const aviso = `El render ${render.etiqueta} no pas\xF3 la revisi\xF3n autom\xE1tica: ${render.checksFallidos.join(", ") || "sin detalle"}; se adjunta igual`;
2478
+ advertencias.push(aviso);
2479
+ await avisar(aviso, "advertencia");
2480
+ }
2481
+ await avisar(`subiendo render ${k + 2}/${total} (${render.etiqueta})`, void 0, { render: render.etiqueta, indice: k + 2, total, destinos: render.destinos });
2482
+ const adj2 = await reintentar(`render ${render.etiqueta}`, () => d.api.adjuntarRender(id, r2.version, render.etiqueta, ruta, revisionDe(render)), dormir, log);
2483
+ if (adj2 === "cancelado") return { tipo: "cancelado", videoId: id };
2484
+ if (adj2 instanceof Error) return await fallar("revision", `no se pudo adjuntar el render ${render.etiqueta}: ${adj2.message}`, null, true);
2485
+ subidos.push(render.etiqueta);
2486
+ }
2487
+ const pedidos = Array.isArray(pedido["renders"]) ? pedido["renders"].length : 1;
2488
+ if (pedidos > total) {
2489
+ const aviso = `El motor gener\xF3 ${total} de los ${pedidos} renders pedidos; los dem\xE1s quedan pendientes (\xBFimagen del motor anterior a 0.4.0?)`;
2490
+ advertencias.push(aviso);
2491
+ await avisar(aviso, "advertencia");
2492
+ }
2493
+ const principal = renders[0];
2494
+ if (total > 1) await avisar(`subiendo render 1/${total} (${principal.etiqueta})`, void 0, { render: principal.etiqueta, indice: 1, total, destinos: principal.destinos });
2495
+ const opciones = { ...manifiesto.costo ?? {}, ...principal && revisionDe(principal) ? { revision: revisionDe(principal) } : {}, ...subidos.length ? { renders: subidos } : {} };
2496
+ const adj = await reintentar("MP4", () => d.api.adjuntarMp4(id, r2.version, mp4, opciones), dormir, log);
2366
2497
  if (adj === "cancelado") return { tipo: "cancelado", videoId: id };
2367
2498
  if (adj instanceof Error) return await fallar("revision", `no se pudo adjuntar el MP4: ${adj.message}`, null, true);
2368
2499
  log(`listo ${id}: ${adj.estado}`);
@@ -2375,7 +2506,7 @@ async function trabajar(c, d, r2) {
2375
2506
  }
2376
2507
  async function checksFallidos(salidaDir) {
2377
2508
  try {
2378
- const rev = JSON.parse(await readFile4(join9(salidaDir, "revision.json"), "utf8"));
2509
+ const rev = JSON.parse(await readFile5(join10(salidaDir, "revision.json"), "utf8"));
2379
2510
  const malos = (rev.checks ?? []).filter((x) => !x.ok && x.nivel === "requerido").map((x) => x.detalle ? `${x.id} (${x.detalle})` : x.id);
2380
2511
  return malos.length ? malos.join(", ") : "sin detalle";
2381
2512
  } catch {
@@ -2384,8 +2515,8 @@ async function checksFallidos(salidaDir) {
2384
2515
  }
2385
2516
  async function piezasDelManifiesto(salidaDir) {
2386
2517
  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)] : []);
2518
+ const m = JSON.parse(await readFile5(join10(salidaDir, "manifiesto.json"), "utf8"));
2519
+ return (m.renders?.[0]?.archivos?.piezas ?? []).flatMap((p) => typeof p.ruta === "string" ? [join10(salidaDir, p.ruta)] : []);
2389
2520
  } catch {
2390
2521
  return [];
2391
2522
  }
@@ -2410,15 +2541,22 @@ async function subirPiezas(d, id, version, salidaDir, dormir, log) {
2410
2541
  }
2411
2542
  return "ok";
2412
2543
  }
2413
- async function adjuntar(d, id, version, mp4, dormir, log) {
2544
+ function revisionDe(r2) {
2545
+ return r2.aprobada === void 0 ? void 0 : { aprobada: r2.aprobada, checks_fallidos: r2.checksFallidos };
2546
+ }
2547
+ function rutaDeRender(salidaDir, r2) {
2548
+ const ruta = resolve2(salidaDir, r2.ruta);
2549
+ return ruta.startsWith(resolve2(salidaDir) + sep) ? ruta : null;
2550
+ }
2551
+ async function reintentar(que, accion, dormir, log) {
2414
2552
  let ultimo = new Error("sin intentos");
2415
2553
  for (let i = 1; i <= 3; i++) {
2416
2554
  try {
2417
- return await d.api.adjuntarMp4(id, version, mp4);
2555
+ return await accion();
2418
2556
  } catch (e) {
2419
2557
  if (e instanceof ErrorApi && (e.conflicto || e.estado === 404)) return "cancelado";
2420
2558
  ultimo = e;
2421
- log(`adjuntar fall\xF3 (intento ${i}/3): ${ultimo.message}`);
2559
+ log(`adjuntar ${que} fall\xF3 (intento ${i}/3): ${ultimo.message}`);
2422
2560
  if (i < 3) await dormir(1e3 * 2 ** i);
2423
2561
  }
2424
2562
  }
@@ -2454,7 +2592,7 @@ async function correrBucle(c, d) {
2454
2592
 
2455
2593
  // src/worker/config.ts
2456
2594
  import { hostname as hostname3 } from "node:os";
2457
- import { resolve as resolve2 } from "node:path";
2595
+ import { resolve as resolve3 } from "node:path";
2458
2596
  var num = (v, def, nombre) => {
2459
2597
  if (v === void 0 || v === "") return def;
2460
2598
  const n = Number(v);
@@ -2479,7 +2617,7 @@ function leerConfig2(env = process.env, argv = [], aviso = (m) => process.stderr
2479
2617
  apiUrl: (env["CLAQUETA_API_URL"] || "http://localhost:4848").replace(/\/+$/, ""),
2480
2618
  apiToken: env["CLAQUETA_API_TOKEN"] || void 0,
2481
2619
  nombre,
2482
- trabajoDir: resolve2(env["WORKER_TRABAJO_DIR"] || "./trabajo"),
2620
+ trabajoDir: resolve3(env["WORKER_TRABAJO_DIR"] || "./trabajo"),
2483
2621
  sondeoMs: num(env["WORKER_SONDEO_S"], 5, "WORKER_SONDEO_S") * 1e3,
2484
2622
  timeoutMs: timeoutMin * 6e4,
2485
2623
  maxReintentos: Math.min(5, Math.floor(num(env["WORKER_MAX_REINTENTOS"], 2, "WORKER_MAX_REINTENTOS"))),
@@ -2593,7 +2731,7 @@ function configWorker(o, conexion, env, nombreEquipo, casa) {
2593
2731
  CLAQUETA_API_URL: conexion.url,
2594
2732
  WORKER_NOMBRE: o.agente ?? nombreEquipo,
2595
2733
  MOTOR_IMAGEN: o.motorImagen ?? IMAGEN_POR_DEFECTO,
2596
- WORKER_TRABAJO_DIR: env["WORKER_TRABAJO_DIR"] || join10(casa, ".cache", "claqueta", "trabajo"),
2734
+ WORKER_TRABAJO_DIR: env["WORKER_TRABAJO_DIR"] || join11(casa, ".cache", "claqueta", "trabajo"),
2597
2735
  WORKER_SONDEO_S: String(o.intervaloS ?? (env["WORKER_SONDEO_S"] || 10))
2598
2736
  });
2599
2737
  return { ...c, apiToken: conexion.token, unaVez: o.unaVez, siFallaRevision: o.siFallaRevision };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claqueta-mcp",
3
- "version": "0.10.0",
3
+ "version": "0.11.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
6
  "bin": {