claqueta-mcp 0.9.2 → 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.
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.9.2" : "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:
@@ -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:febdff070d5246ecb1f070d35f5e804201ac87e35ad4d8e15c8cda75a39d003c";
407
+ var IMAGEN_POR_DEFECTO = "public.ecr.aws/v9d5u4i8/claqueta-motor@sha256:f37b8e0f9c4f7a77470c9e7c73a0ef3054f25873735387a76f092fb9cfe1cc31";
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) => {
@@ -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 };
@@ -1 +1 @@
1
- 0.3.1
1
+ 0.4.0
package/motor/README.md CHANGED
@@ -42,6 +42,7 @@ export CLAQUETA_CACHE_DIR=$HOME/.cache/claqueta-motor
42
42
  ./motor.sh ejemplo-renders # mismo guion en 4 renders (ejemplos/pedido-4-renders.json)
43
43
  ./motor.sh ejemplo-imagenes # imágenes por escena y logo (ejemplos/pedido-con-imagenes.json)
44
44
  ./motor.sh ejemplo-carrusel # carrusel 4:5: video + 3 piezas PNG (ejemplos/pedido-carrusel.json)
45
+ ./motor.sh ejemplo-paleta # paleta propia: fondo claro, texto oscuro y colores extra (ejemplos/pedido-paleta.json)
45
46
 
46
47
  # 3) Correr tu propio pedido (la carpeta del pedido se monta de solo lectura en el contenedor)
47
48
  ./motor.sh generar ruta/a/pedido.json [/salida/nombre]
@@ -60,7 +61,7 @@ También `make build|ejemplo|ejemplo-renders|test|e2e` y `docker compose run --r
60
61
  (que además te dice qué falta con `npx claqueta-mcp@latest doctor --modo local`).
61
62
 
62
63
  ```bash
63
- # 1) Requisitos (macOS; en Linux: Node 22, uv, ffmpeg, chromium y espeak-ng con tu gestor de paquetes)
64
+ # 1) Requisitos (macOS; en Linux (Debian/Ubuntu): sudo apt install nodejs(22) ffmpeg chromium y uv desde https://docs.astral.sh/uv)
64
65
  brew install node@22 uv ffmpeg
65
66
  brew install --cask google-chrome
66
67
 
@@ -77,7 +78,7 @@ export CLAQUETA_VENDOR=$HOME/.cache/claqueta/vendor/node_modules
77
78
  export CLAQUETA_PLANTILLAS=$PWD/plantillas
78
79
  export CLAQUETA_CACHE=$HOME/.cache/claqueta/modelos
79
80
  export HF_HOME=$CLAQUETA_CACHE/hf
80
- export HYPERFRAMES_BROWSER_PATH="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
81
+ export HYPERFRAMES_BROWSER_PATH="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" # Linux: /usr/bin/chromium
81
82
  export HYPERFRAMES_NO_TELEMETRY=1 DO_NOT_TRACK=1 HYPERFRAMES_SKIP_SKILLS=1
82
83
  export PATH=$HOME/.cache/claqueta/vendor/node_modules/.bin:$HOME/.cache/claqueta/venv/bin:$PATH
83
84
 
@@ -85,8 +86,12 @@ export PATH=$HOME/.cache/claqueta/vendor/node_modules/.bin:$HOME/.cache/claqueta
85
86
  claqueta-motor version
86
87
  claqueta-motor generar --pedido ejemplos/pedido-con-imagenes.json --salida salida/ejemplo-imagenes
87
88
  claqueta-motor generar --pedido ejemplos/pedido-carrusel.json --salida salida/ejemplo-carrusel
89
+ claqueta-motor generar --pedido ejemplos/pedido-paleta.json --salida salida/ejemplo-paleta
88
90
  ```
89
91
 
92
+ Verificado el 2026-11-15 con estos mismos comandos en un Linux limpio (Node 22, uv 0.13, ffmpeg 5.1, Chromium 156; usuario sin
93
+ privilegios): `claqueta-motor version` da 0.3.1 y los dos ejemplos terminan con la revisión aprobada y sin advertencias.
94
+
90
95
  ### Con el worker de la cola (lo habitual)
91
96
 
92
97
  El worker de `claqueta-mcp` baja los pedidos de la API, ejecuta el motor por ti (en Docker por defecto) y sube el MP4 y las piezas:
@@ -15,10 +15,10 @@ body { font-family: "Inter", sans-serif; color: var(--cq-texto); }
15
15
  #barra-izq { position: absolute; left: 0; top: 0; width: 28px; height: 100%;
16
16
  background: linear-gradient(180deg, var(--cq-primario), var(--cq-secundario) 55%, var(--cq-terciario)); }
17
17
  #brillo { position: absolute; right: -260px; top: 120px; width: 700px; height: 700px; border-radius: 50%;
18
- background: radial-gradient(circle, rgba(255,255,255,0.07) 0%, rgba(255,255,255,0) 70%); }
18
+ background: radial-gradient(circle, rgba(var(--cq-texto-rgb, 255,255,255),0.07) 0%, rgba(var(--cq-texto-rgb, 255,255,255),0) 70%); }
19
19
  #progreso { position: absolute; left: var(--m-izq); right: var(--m-der); top: var(--prog-top); height: 12px;
20
20
  display: flex; gap: 12px; }
21
- #progreso .seg { flex: 1; background: rgba(255,255,255,0.16); border-radius: 6px; overflow: hidden; }
21
+ #progreso .seg { flex: 1; background: rgba(var(--cq-texto-rgb, 255,255,255),0.16); border-radius: 6px; overflow: hidden; }
22
22
  #progreso .seg i { display: block; width: 100%; height: 100%; border-radius: 6px; transform-origin: left center; }
23
23
  #franja-inf { position: absolute; left: 28px; right: 0; bottom: 0; height: 18px;
24
24
  background: linear-gradient(90deg, var(--cq-primario), var(--cq-secundario), var(--cq-terciario)); }
@@ -50,8 +50,8 @@ body { font-family: "Inter", sans-serif; color: var(--cq-texto); }
50
50
  .cap { position: absolute; left: var(--cap-x); top: var(--cap-y); width: var(--cap-w); height: var(--cap-h);
51
51
  display: flex; align-items: center; justify-content: center; }
52
52
  .cap-in { text-align: center; font-weight: 900; font-size: calc(68px * var(--esc-cap)); line-height: 1.22;
53
- padding: calc(22px * var(--esc-cap)) calc(34px * var(--esc-cap)); background: rgba(8, 10, 28, 0.72);
54
- border-radius: calc(36px * var(--esc-cap)); text-shadow: 0 3px 10px rgba(0,0,0,0.45); }
53
+ padding: calc(22px * var(--esc-cap)) calc(34px * var(--esc-cap)); background: rgba(var(--cq-fondo-rgb, 8,10,28), 0.86);
54
+ border-radius: calc(36px * var(--esc-cap)); text-shadow: 0 3px 10px rgba(var(--cq-fondo-rgb, 0,0,0), 0.45); }
55
55
  .cap-in .w { display: inline-block; color: var(--cq-texto); margin: 0; }
56
56
 
57
57
  /* CLA-75: imagen de escena (fondo a pantalla completa o completa dentro del cuadro) con un velo oscuro para que el texto se lea */
@@ -60,7 +60,7 @@ body { font-family: "Inter", sans-serif; color: var(--cq-texto); }
60
60
  .foto-cubrir .foto { object-fit: cover; }
61
61
  .foto-contener .foto { object-fit: contain; }
62
62
  .foto-velo { position: absolute; inset: 0;
63
- background: linear-gradient(180deg, rgba(8,10,28,0.62) 0%, rgba(8,10,28,0.48) 45%, rgba(8,10,28,0.78) 100%); }
63
+ background: linear-gradient(180deg, rgba(var(--cq-fondo-rgb, 8,10,28),0.62) 0%, rgba(var(--cq-fondo-rgb, 8,10,28),0.48) 45%, rgba(var(--cq-fondo-rgb, 8,10,28),0.78) 100%); }
64
64
  .escena-in { z-index: 1; }
65
65
  /* logo del kit de marca: abajo a la derecha, bajo los subtítulos y sobre la franja inferior de cada aspecto */
66
66
  #logo { position: absolute; z-index: 5; height: calc(72px * var(--esc)); max-width: calc(300px * var(--esc)); width: auto;
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "claqueta-motor"
3
- version = "0.3.1"
3
+ version = "0.4.0"
4
4
  description = "Motor de generación de Claqueta: VideoRequest -> MP4 vertical con voz y subtítulos"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -16,7 +16,7 @@ from .contrato import leer_json, normalizar
16
16
  from .errores import ErrorMotor
17
17
  from .progreso import Progreso, ahora, log
18
18
 
19
- VERSION = "0.3.1"
19
+ VERSION = "0.4.0"
20
20
 
21
21
 
22
22
  def _guion(escenas: list[esc.EscenaPlan]) -> str:
@@ -12,6 +12,7 @@ from .contrato import ASPECTOS, PedidoNormalizado, RenderPlan
12
12
  from .errores import ErrorMotor
13
13
  from .escenas import EscenaPlan
14
14
  from .medios import Medios
15
+ from .paleta import rgb_css, tokens_de_marca
15
16
  from .subtitulos import Cue
16
17
 
17
18
  TOKENS_MARCA = {
@@ -127,6 +128,10 @@ def componer(n: PedidoNormalizado, escenas: list[EscenaPlan], cues: list[Cue], t
127
128
  if tokens is None:
128
129
  advertencias.append(f"tokens de marca '{n.marca_tokens}' desconocidos: se usa brand-default")
129
130
  tokens = TOKENS_MARCA["brand-default"]
131
+ # CLA-87: la paleta de la marca (colores y extras ya resueltos por la API) manda sobre los tokens por defecto.
132
+ paleta = tokens_de_marca(tokens, (n.pedido.marca.colores if n.pedido.marca else None), (n.pedido.marca.colores_extra if n.pedido.marca else None))
133
+ tokens = paleta.tokens
134
+ advertencias.extend(paleta.advertencias)
130
135
 
131
136
  for e in escenas: # los ids de escena son ids de elemento HTML: deben ser seguros
132
137
  if not e.id.replace("-", "").replace("_", "").isalnum():
@@ -158,8 +163,10 @@ def componer(n: PedidoNormalizado, escenas: list[EscenaPlan], cues: list[Cue], t
158
163
  nombres[origen] = f"media/{nombre}"
159
164
  return nombres[origen]
160
165
 
161
- acentos = [tokens["primario"], tokens["secundario"], tokens["terciario"]]
162
- css_vars = ":root{" + "".join(f"--cq-{k}:{v};" for k, v in tokens.items()) + _css_geometria(render.aspecto) + "}"
166
+ acentos = paleta.acentos
167
+ css_vars = (":root{" + "".join(f"--cq-{k}:{v};" for k, v in tokens.items())
168
+ + f"--cq-fondo-rgb:{rgb_css(tokens['fondo'])};--cq-texto-rgb:{rgb_css(tokens['texto'])};"
169
+ + _css_geometria(render.aspecto) + "}")
163
170
 
164
171
  ne = len(escenas)
165
172
  partes: list[str] = []
@@ -199,7 +206,7 @@ def componer(n: PedidoNormalizado, escenas: list[EscenaPlan], cues: list[Cue], t
199
206
  "palabras": [{"i": j, "ini": p.ini, "fin": p.fin} for j, p in enumerate(c.palabras)]})
200
207
 
201
208
  datos = {
202
- "total": total_s, "acento": tokens["primario"], "texto": tokens["texto"],
209
+ "total": total_s, "acento": acentos[0], "texto": tokens["texto"],
203
210
  "escenas": [{"id": e.id, "inicio": e.inicio_s, "dur": e.duracion_s,
204
211
  "foto": medios.por_escena[e.id].movimiento if e.id in medios.por_escena else None} for e in escenas],
205
212
  "cues": datos_cues,
@@ -85,6 +85,11 @@ class Marca(_Base):
85
85
  tokens: str | None = None
86
86
  logo_asset_id: str | None = None
87
87
  cierre: str | None = None
88
+ # CLA-87: lo que la API ya resolvió del kit del workspace (paleta y variante elegidas).
89
+ colores: dict[str, Any] | None = None
90
+ colores_extra: list[dict[str, Any]] | None = None
91
+ paleta: str | None = None
92
+ logo: str | None = None
88
93
 
89
94
 
90
95
  class Origen(_Base):
@@ -0,0 +1,123 @@
1
+ """Paleta de la marca (CLA-87): convierte `marca.colores` y `marca.colores_extra` (ya resueltos por la API desde el kit) en los
2
+ tokens de la plantilla. Sin colores en el pedido, la plantilla sigue con su paleta por defecto (`brand-default`).
3
+
4
+ Reglas: lo que falta se completa de forma legible (si hay fondo pero no texto, el texto es blanco o casi negro según el contraste);
5
+ los acentos de escena salen del primario, el secundario y los extras, descartando los que no se ven sobre el fondo;
6
+ el fondo del degradado se deriva mezclando el fondo con el texto. Todo lo dudoso queda como advertencia, nunca como fallo."""
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from dataclasses import dataclass, field
12
+
13
+ HEX = re.compile(r"^#[0-9a-fA-F]{6}$")
14
+ CONTRASTE_TEXTO = 4.5 # WCAG AA para texto normal
15
+ CONTRASTE_ACENTO = 3.0 # AA para elementos gráficos grandes: lo que se ve sobre el fondo
16
+ CLARO = "#ffffff"
17
+ OSCURO = "#0e1330"
18
+
19
+
20
+ def a_rgb(c: str) -> tuple[int, int, int]:
21
+ n = int(c[1:], 16)
22
+ return (n >> 16) & 255, (n >> 8) & 255, n & 255
23
+
24
+
25
+ def a_hex(rgb: tuple[float, float, float]) -> str:
26
+ r, g, b = (max(0, min(255, round(x))) for x in rgb)
27
+ return f"#{r:02x}{g:02x}{b:02x}"
28
+
29
+
30
+ def _canal(c: float) -> float:
31
+ s = c / 255
32
+ return s / 12.92 if s <= 0.04045 else ((s + 0.055) / 1.055) ** 2.4
33
+
34
+
35
+ def luminancia(c: str) -> float:
36
+ r, g, b = a_rgb(c)
37
+ return 0.2126 * _canal(r) + 0.7152 * _canal(g) + 0.0722 * _canal(b)
38
+
39
+
40
+ def contraste(a: str, b: str) -> float:
41
+ la, lb = luminancia(a), luminancia(b)
42
+ claro, oscuro = (la, lb) if la >= lb else (lb, la)
43
+ return (claro + 0.05) / (oscuro + 0.05)
44
+
45
+
46
+ def mezclar(a: str, b: str, t: float) -> str:
47
+ """`a` con una fracción `t` (0 a 1) de `b`."""
48
+ (r1, g1, b1), (r2, g2, b2) = a_rgb(a), a_rgb(b)
49
+ return a_hex((r1 + (r2 - r1) * t, g1 + (g2 - g1) * t, b1 + (b2 - b1) * t))
50
+
51
+
52
+ def contrastante(fondo: str) -> str:
53
+ """Blanco u oscuro, el que mejor se lee sobre `fondo`."""
54
+ return CLARO if contraste(CLARO, fondo) >= contraste(OSCURO, fondo) else OSCURO
55
+
56
+
57
+ @dataclass
58
+ class TokensMarca:
59
+ tokens: dict[str, str]
60
+ acentos: list[str]
61
+ advertencias: list[str] = field(default_factory=list)
62
+ de_marca: bool = False # True si algún color vino de la marca del pedido
63
+
64
+
65
+ def _valido(c: object) -> str | None:
66
+ return c.lower() if isinstance(c, str) and HEX.match(c) else None
67
+
68
+
69
+ def tokens_de_marca(base: dict[str, str], colores: dict | None, extra: list[dict] | None) -> TokensMarca:
70
+ """`base` son los tokens por defecto (brand-default). `colores` = {primario, secundario, fondo, texto}; `extra` = [{nombre, hex}]."""
71
+ adv: list[str] = []
72
+ tokens = dict(base)
73
+ pedidos: dict[str, str] = {}
74
+ for k in ("primario", "secundario", "fondo", "texto"):
75
+ v = (colores or {}).get(k)
76
+ if v is None:
77
+ continue
78
+ ok = _valido(v)
79
+ if ok:
80
+ pedidos[k] = ok
81
+ else:
82
+ adv.append(f"marca.colores.{k}: '{v}' no es un color #RRGGBB; se usa el de la plantilla")
83
+ extras: list[str] = []
84
+ for x in extra or []:
85
+ ok = _valido(x.get("hex") if isinstance(x, dict) else None)
86
+ if ok:
87
+ extras.append(ok)
88
+ else:
89
+ adv.append(f"marca.colores_extra: se ignora un color inválido ({x!r})")
90
+ if not pedidos and not extras:
91
+ return TokensMarca(tokens, [tokens["primario"], tokens["secundario"], tokens["terciario"]], adv, False)
92
+
93
+ tokens.update(pedidos)
94
+ # Lo que falta se completa de forma legible respecto a lo que sí vino.
95
+ if "fondo" in pedidos and "texto" not in pedidos:
96
+ tokens["texto"] = contrastante(tokens["fondo"])
97
+ adv.append(f"marca.colores sin texto: se usa {tokens['texto']} por contraste con el fondo")
98
+ elif "texto" in pedidos and "fondo" not in pedidos:
99
+ tokens["fondo"] = contrastante(tokens["texto"])
100
+ adv.append(f"marca.colores sin fondo: se usa {tokens['fondo']} por contraste con el texto")
101
+ if "fondo" in pedidos or "texto" in pedidos:
102
+ # Degradado del fondo: el fondo mezclado un poco con el texto (más claro en temas oscuros y al revés), siempre sutil.
103
+ tokens["fondo2"] = mezclar(tokens["fondo"], tokens["texto"], 0.10)
104
+ c = contraste(tokens["texto"], tokens["fondo"])
105
+ if c < CONTRASTE_TEXTO:
106
+ adv.append(f"contraste texto/fondo de {int(c * 100) / 100:.2f}:1 en la marca, por debajo de {CONTRASTE_TEXTO}:1 (WCAG AA): los textos pueden leerse mal")
107
+
108
+ # Acentos de escena: primario, secundario y extras; sin los que no se ven sobre el fondo. El terciario sale del primer extra
109
+ # (o, sin extras, de mezclar primario y secundario) para las barras de color.
110
+ candidatos = [tokens["primario"], tokens["secundario"], *extras]
111
+ acentos = [a for a in dict.fromkeys(candidatos) if contraste(a, tokens["fondo"]) >= CONTRASTE_ACENTO]
112
+ descartados = [a for a in dict.fromkeys(candidatos) if a not in acentos]
113
+ if descartados:
114
+ adv.append(f"acentos sin contraste suficiente con el fondo (< {CONTRASTE_ACENTO}:1) no se usan en las escenas: {', '.join(descartados)}")
115
+ if not acentos:
116
+ acentos = [tokens["texto"]]
117
+ tokens["terciario"] = extras[0] if extras else mezclar(tokens["primario"], tokens["secundario"], 0.5)
118
+ return TokensMarca(tokens, acentos, adv, True)
119
+
120
+
121
+ def rgb_css(c: str) -> str:
122
+ r, g, b = a_rgb(c)
123
+ return f"{r},{g},{b}"
package/motor/uv.lock CHANGED
@@ -195,7 +195,7 @@ wheels = [
195
195
 
196
196
  [[package]]
197
197
  name = "claqueta-motor"
198
- version = "0.3.1"
198
+ version = "0.4.0"
199
199
  source = { editable = "." }
200
200
  dependencies = [
201
201
  { name = "faster-whisper" },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claqueta-mcp",
3
- "version": "0.9.2",
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": {