claqueta-mcp 0.68.0 → 0.69.1
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 +856 -236
- package/motor/MOTOR_VERSION +1 -1
- package/motor/esteticas/base/base.css +6 -2
- package/motor/esteticas/base/explicativo-personaje.css +1 -1
- package/motor/esteticas/cine-3d/explicativo-personaje.css +2 -1
- package/motor/esteticas/consola-oscura/demo-producto.css +3 -2
- package/motor/esteticas/interfaz-3d/demo-producto.css +3 -2
- package/motor/esteticas/pizarra-negra/componentes.css +6 -0
- package/motor/esteticas/pizarra-negra/estetica.json +91 -0
- package/motor/esteticas/pizarra-negra/matematica-animada.css +45 -0
- package/motor/esteticas/poster-oscuro/explicativo-personaje.css +1 -1
- package/motor/esteticas/transmision-deportiva/anuncio-producto.css +6 -0
- package/motor/esteticas/transmision-deportiva/demo-producto.css +4 -3
- package/motor/esteticas/transmision-deportiva/transmision.css +1 -1
- package/motor/esteticas/vector-plano/anuncio-producto.css +5 -0
- package/motor/esteticas/vector-plano/demo-producto.css +3 -2
- package/motor/esteticas/vitrina/anuncio-producto.css +6 -1
- package/motor/novedades-agentes.json +46 -0
- package/motor/plantillas/_comun/ambiente.css +6 -4
- package/motor/plantillas/_comun/ambiente.js +11 -0
- package/motor/plantillas/_comun/audio-reactivo.css +14 -7
- package/motor/plantillas/_comun/audio-reactivo.js +16 -1
- package/motor/plantillas/_comun/bloques/bloques.json +50 -0
- package/motor/plantillas/_comun/bloques/capas-apiladas.html +142 -0
- package/motor/plantillas/_comun/bloques/traza-recorrido.html +105 -0
- package/motor/plantillas/_comun/capas.css +2 -1
- package/motor/plantillas/_comun/navegador.css +36 -0
- package/motor/plantillas/_comun/paneles.js +2 -1
- package/motor/plantillas/_comun/subtitulos.js +147 -0
- package/motor/plantillas/_comun/transiciones.js +61 -2
- package/motor/plantillas/algoritmo-visual/familia.json +1 -0
- package/motor/plantillas/anuncio-producto/animacion.js +7 -10
- package/motor/plantillas/anuncio-producto/estilos.css +3 -0
- package/motor/plantillas/anuncio-producto/familia.json +1 -0
- package/motor/plantillas/asi-se-hizo/animacion.js +17 -10
- package/motor/plantillas/asi-se-hizo/estilos.css +3 -2
- package/motor/plantillas/asi-se-hizo/familia.json +1 -0
- package/motor/plantillas/base/animacion.js +34 -15
- package/motor/plantillas/base/familia.json +1 -0
- package/motor/plantillas/demo-producto/animacion.js +11 -12
- package/motor/plantillas/demo-producto/estilos.css +4 -3
- package/motor/plantillas/demo-producto/familia.json +1 -0
- package/motor/plantillas/explicativo-personaje/animacion.js +4 -12
- package/motor/plantillas/explicativo-personaje/familia.json +1 -0
- package/motor/plantillas/leccion-diagrama/SKILL.md +21 -1
- package/motor/plantillas/leccion-diagrama/animacion.js +16 -16
- package/motor/plantillas/leccion-diagrama/estilos.css +2 -0
- package/motor/plantillas/leccion-diagrama/familia.json +3 -1
- package/motor/plantillas/lista-top-n/animacion.js +10 -13
- package/motor/plantillas/lista-top-n/familia.json +1 -0
- package/motor/plantillas/matematica-animada/SKILL.md +47 -0
- package/motor/plantillas/matematica-animada/animacion.js +46 -0
- package/motor/plantillas/matematica-animada/estilos.css +37 -0
- package/motor/plantillas/matematica-animada/familia.json +440 -0
- package/motor/plantillas/poster-oscuro/animacion.js +33 -2
- package/motor/plantillas/poster-oscuro/estilos.css +1 -1
- package/motor/plantillas/poster-oscuro/familia.json +1 -0
- package/motor/plantillas/tres-objeciones/animacion.js +1 -5
- package/motor/plantillas/tres-objeciones/familia.json +1 -0
- package/motor/pyproject.toml +1 -1
- package/motor/src/claqueta_motor/audio_reactivo.py +15 -11
- package/motor/src/claqueta_motor/banding.py +287 -0
- package/motor/src/claqueta_motor/bloques.py +1 -1
- package/motor/src/claqueta_motor/bloques_leccion.py +217 -0
- package/motor/src/claqueta_motor/chequeo_previo.py +217 -18
- package/motor/src/claqueta_motor/cli.py +88 -9
- package/motor/src/claqueta_motor/composicion.py +33 -15
- package/motor/src/claqueta_motor/composicion_anuncio.py +62 -23
- package/motor/src/claqueta_motor/composicion_asi.py +10 -11
- package/motor/src/claqueta_motor/composicion_demo.py +30 -24
- package/motor/src/claqueta_motor/composicion_explicativo.py +3 -9
- package/motor/src/claqueta_motor/composicion_leccion.py +85 -16
- package/motor/src/claqueta_motor/composicion_lista.py +2 -9
- package/motor/src/claqueta_motor/composicion_matematica.py +946 -0
- package/motor/src/claqueta_motor/composicion_objeciones.py +2 -10
- package/motor/src/claqueta_motor/contrato.py +55 -4
- package/motor/src/claqueta_motor/correccion.py +29 -2
- package/motor/src/claqueta_motor/diagramas.py +205 -9
- package/motor/src/claqueta_motor/diagramas_gen.py +52 -0
- package/motor/src/claqueta_motor/esteticas.py +15 -3
- package/motor/src/claqueta_motor/familias.py +2 -0
- package/motor/src/claqueta_motor/ffmpeg.py +156 -8
- package/motor/src/claqueta_motor/matematica/__init__.py +8 -0
- package/motor/src/claqueta_motor/matematica/calculo.py +297 -0
- package/motor/src/claqueta_motor/matematica/catalogo.py +319 -0
- package/motor/src/claqueta_motor/matematica/katex.cjs +69 -0
- package/motor/src/claqueta_motor/matematica/katex.py +101 -0
- package/motor/src/claqueta_motor/medios.py +1 -0
- package/motor/src/claqueta_motor/musica.py +68 -1
- package/motor/src/claqueta_motor/navegador.py +72 -0
- package/motor/src/claqueta_motor/pasos.py +6 -3
- package/motor/src/claqueta_motor/progreso.py +10 -5
- package/motor/src/claqueta_motor/subtitulos_estilo.py +280 -0
- package/motor/src/claqueta_motor/tablero.py +9 -2
- package/motor/src/claqueta_motor/transiciones.py +129 -19
- package/motor/uv.lock +1 -1
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -83,7 +83,7 @@ function ayudaConexionTodas(plataforma = process.platform) {
|
|
|
83
83
|
}
|
|
84
84
|
|
|
85
85
|
// src/config.ts
|
|
86
|
-
var VERSION = true ? "0.
|
|
86
|
+
var VERSION = true ? "0.69.1" : "dev";
|
|
87
87
|
var construirAyuda = (plataforma = process.platform) => `claqueta-mcp ${VERSION}: puente stdio hacia el servidor MCP remoto de Claqueta.
|
|
88
88
|
|
|
89
89
|
Uso:
|
|
@@ -245,13 +245,13 @@ function leerConfig(argv, env, archivo2 = {}) {
|
|
|
245
245
|
|
|
246
246
|
// src/local/cli-local.ts
|
|
247
247
|
import { homedir as homedir7 } from "node:os";
|
|
248
|
-
import { join as
|
|
248
|
+
import { join as join31 } from "node:path";
|
|
249
249
|
|
|
250
250
|
// src/motor-docker.ts
|
|
251
251
|
import { spawn } from "node:child_process";
|
|
252
|
-
var IMAGEN_POR_DEFECTO = "public.ecr.aws/v9d5u4i8/claqueta-motor@sha256:
|
|
253
|
-
var IMAGEN_CLONACION_POR_DEFECTO = "public.ecr.aws/v9d5u4i8/claqueta-motor@sha256:
|
|
254
|
-
var MOTOR_VERSION_POR_DEFECTO = "0.
|
|
252
|
+
var IMAGEN_POR_DEFECTO = "public.ecr.aws/v9d5u4i8/claqueta-motor@sha256:28f5e4d0e790bba0ecde69dff47124d64de2c3945438d30f21f5a44fcfd4ee72";
|
|
253
|
+
var IMAGEN_CLONACION_POR_DEFECTO = "public.ecr.aws/v9d5u4i8/claqueta-motor@sha256:cb943fdbc2c923613af4bca67d3843a31180b4b5003decf4db70948f89f804c9";
|
|
254
|
+
var MOTOR_VERSION_POR_DEFECTO = "0.33.1";
|
|
255
255
|
var PERFIL_AWS_POR_DEFECTO = "claqueta-motor";
|
|
256
256
|
var REGION_POR_DEFECTO = "us-west-1";
|
|
257
257
|
var ejecutarReal = (cmd, args2, opc) => new Promise((resolver) => {
|
|
@@ -10637,13 +10637,13 @@ async function prepararReutilizar(r2, raiz, descargar2, senal) {
|
|
|
10637
10637
|
}
|
|
10638
10638
|
var insumosDeSalida = (salidaDir) => insumosDe(join6(salidaDir, "insumos"));
|
|
10639
10639
|
async function insumosDe(base) {
|
|
10640
|
-
let
|
|
10640
|
+
let entradas2;
|
|
10641
10641
|
try {
|
|
10642
|
-
|
|
10642
|
+
entradas2 = (await readdir(base, { recursive: true, withFileTypes: true })).filter((e7) => e7.isFile()).map((e7) => join6(e7.parentPath ?? e7.path, e7.name));
|
|
10643
10643
|
} catch {
|
|
10644
10644
|
return [];
|
|
10645
10645
|
}
|
|
10646
|
-
const salida =
|
|
10646
|
+
const salida = entradas2.map((archivo2) => ({ ruta: relative(base, archivo2).split(sep).join("/"), archivo: archivo2 })).filter((x2) => RUTA_INSUMO.test(x2.ruta));
|
|
10647
10647
|
return salida.sort((a, b) => Number(a.ruta === "huellas.json") - Number(b.ruta === "huellas.json") || a.ruta.localeCompare(b.ruta));
|
|
10648
10648
|
}
|
|
10649
10649
|
var RUTAS_EDICION = {
|
|
@@ -10755,6 +10755,19 @@ async function ejecutarMotor(c, e7, timeoutMs = c.timeoutMs) {
|
|
|
10755
10755
|
tiempoAgotado = true;
|
|
10756
10756
|
matar();
|
|
10757
10757
|
}, timeoutMs);
|
|
10758
|
+
let etapaAgotada;
|
|
10759
|
+
let etapaActual = null;
|
|
10760
|
+
let relojEtapa;
|
|
10761
|
+
const armarEtapa = (etapa) => {
|
|
10762
|
+
if (!e7.topeEtapaMs || etapa === etapaActual) return;
|
|
10763
|
+
etapaActual = etapa;
|
|
10764
|
+
clearTimeout(relojEtapa);
|
|
10765
|
+
relojEtapa = setTimeout(() => {
|
|
10766
|
+
tiempoAgotado = true;
|
|
10767
|
+
etapaAgotada = { etapa, topeMin: Math.round(e7.topeEtapaMs / 6e4) };
|
|
10768
|
+
matar();
|
|
10769
|
+
}, e7.topeEtapaMs);
|
|
10770
|
+
};
|
|
10758
10771
|
const alAbortar = () => {
|
|
10759
10772
|
abortado = true;
|
|
10760
10773
|
matar();
|
|
@@ -10763,7 +10776,10 @@ async function ejecutarMotor(c, e7, timeoutMs = c.timeoutMs) {
|
|
|
10763
10776
|
else e7.senal?.addEventListener("abort", alAbortar, { once: true });
|
|
10764
10777
|
createInterface({ input: hijo.stdout }).on("line", (linea) => {
|
|
10765
10778
|
const ev2 = parsearEvento(linea);
|
|
10766
|
-
if (ev2)
|
|
10779
|
+
if (ev2) {
|
|
10780
|
+
armarEtapa(ev2.etapa);
|
|
10781
|
+
e7.onEvento(ev2);
|
|
10782
|
+
}
|
|
10767
10783
|
});
|
|
10768
10784
|
createInterface({ input: hijo.stderr }).on("line", (linea) => {
|
|
10769
10785
|
stderrCola.push(linea);
|
|
@@ -10777,19 +10793,21 @@ async function ejecutarMotor(c, e7, timeoutMs = c.timeoutMs) {
|
|
|
10777
10793
|
hijo.on("close", (cod, sig) => resolver(cod ?? (sig ? 128 + 15 : 1)));
|
|
10778
10794
|
});
|
|
10779
10795
|
clearTimeout(temporizador);
|
|
10796
|
+
clearTimeout(relojEtapa);
|
|
10780
10797
|
e7.senal?.removeEventListener("abort", alAbortar);
|
|
10781
10798
|
let error2 = null;
|
|
10782
10799
|
try {
|
|
10783
10800
|
error2 = JSON.parse(await readFile(join7(e7.salidaDir, "error.json"), "utf8"));
|
|
10784
10801
|
} catch {
|
|
10785
10802
|
}
|
|
10786
|
-
return { codigo, tiempoAgotado, abortado, error: error2, stderrCola };
|
|
10803
|
+
return { codigo, tiempoAgotado, abortado, error: error2, stderrCola, ...etapaAgotada ? { etapaAgotada } : {} };
|
|
10787
10804
|
}
|
|
10788
10805
|
function parsearEvento(linea) {
|
|
10789
10806
|
try {
|
|
10790
10807
|
const j = JSON.parse(linea);
|
|
10791
10808
|
if (typeof j.etapa !== "string" || typeof j.porcentaje !== "number" || typeof j.mensaje !== "string") return null;
|
|
10792
|
-
|
|
10809
|
+
const datos = j.datos && typeof j.datos === "object" && !Array.isArray(j.datos) ? { datos: j.datos } : {};
|
|
10810
|
+
return { etapa: j.etapa, porcentaje: Math.max(0, Math.min(100, Math.round(j.porcentaje))), mensaje: j.mensaje, ...j.nivel ? { nivel: j.nivel } : {}, ...j.en ? { en: j.en } : {}, ...datos };
|
|
10793
10811
|
} catch {
|
|
10794
10812
|
return null;
|
|
10795
10813
|
}
|
|
@@ -10812,7 +10830,8 @@ var conDetalle = (motivo, crudo) => {
|
|
|
10812
10830
|
return d ? `${motivo}. Detalle t\xE9cnico: ${d}` : motivo;
|
|
10813
10831
|
};
|
|
10814
10832
|
function causaLegible(r2, timeoutMin) {
|
|
10815
|
-
if (r2.
|
|
10833
|
+
if (r2.etapaAgotada) return `el motor pas\xF3 m\xE1s de ${r2.etapaAgotada.topeMin} min en la etapa \xAB${r2.etapaAgotada.etapa}\xBB sin pasar a la siguiente (\xBFcolgado?) y se detuvo; el tope por etapa se cambia con WORKER_TIMEOUT_ETAPA_MIN o --tope-etapa`;
|
|
10834
|
+
if (r2.tiempoAgotado) return `el motor super\xF3 el l\xEDmite de ${timeoutMin} min del video y se detuvo; el tope por formato se cambia con WORKER_TIMEOUT_MIN o --tope-formato`;
|
|
10816
10835
|
const crudoCompleto = [r2.error?.mensaje ?? "", ...r2.stderrCola].join(" ");
|
|
10817
10836
|
const motivo = motivoDe(crudoCompleto);
|
|
10818
10837
|
if (motivo) return conDetalle(motivo, r2.error?.mensaje || r2.stderrCola.filter((l) => l.trim()).slice(-2).join(" | "));
|
|
@@ -11791,12 +11810,17 @@ function lineasComponentes(i) {
|
|
|
11791
11810
|
return i.componentes.map((c) => `${c.componente}: ${c.version ? `v${c.version}` : "versi\xF3n desconocida"}${c.digest ? ` (${corto(c.digest)})` : ""}${c.detalle ? ` \xB7 ${c.detalle}` : ""}`);
|
|
11792
11811
|
}
|
|
11793
11812
|
async function consultarCompatibilidad(o) {
|
|
11794
|
-
const
|
|
11795
|
-
|
|
11796
|
-
|
|
11797
|
-
|
|
11813
|
+
const consulta = (conCapacidades) => {
|
|
11814
|
+
const q2 = new URLSearchParams({ version: o.version, ...conCapacidades ? { capacidades: o.capacidades.join(",") } : {} });
|
|
11815
|
+
if (o.agente) q2.set("agente", o.agente);
|
|
11816
|
+
if (o.motor.version) q2.set("motor_version", o.motor.version);
|
|
11817
|
+
if (o.motor.digest) q2.set("motor_digest", o.motor.digest);
|
|
11818
|
+
return `${o.url}/api/cola/compatibilidad?${q2}`;
|
|
11819
|
+
};
|
|
11820
|
+
const pedir = (conCapacidades) => o.fetch(consulta(conCapacidades), { headers: { authorization: `Bearer ${o.token}`, [CABECERA_VERSION]: o.version }, redirect: "manual", signal: AbortSignal.timeout(o.timeoutMs ?? 8e3) });
|
|
11798
11821
|
try {
|
|
11799
|
-
|
|
11822
|
+
let res = await pedir(true);
|
|
11823
|
+
if (res.status === 400 && o.capacidades.length > 1 && /capacidades/.test(await res.text().catch(() => ""))) res = await pedir(false);
|
|
11800
11824
|
if (res.status === 426) return { r: null, motivo: mensajeClienteDesactualizado(leerClienteDesactualizado(await res.text().catch(() => "")), o.version) };
|
|
11801
11825
|
if (res.status === 404) return { r: null, motivo: "La API desplegada a\xFAn no tiene el diagn\xF3stico de compatibilidad (se muestra solo lo local)." };
|
|
11802
11826
|
if (res.status === 401 || res.status === 403) return { r: null, motivo: "La API no acepta este token para el diagn\xF3stico de compatibilidad (solo el token de escritura del worker, el de `setup`, puede leerlo); se muestra solo lo local." };
|
|
@@ -11818,6 +11842,54 @@ import { createHash as createHash4 } from "node:crypto";
|
|
|
11818
11842
|
import { readFile as readFile2 } from "node:fs/promises";
|
|
11819
11843
|
import { basename as basename3 } from "node:path";
|
|
11820
11844
|
|
|
11845
|
+
// src/worker/red.ts
|
|
11846
|
+
var CAUSAS = {
|
|
11847
|
+
ENOTFOUND: "no se resolvi\xF3 el nombre del servidor (DNS)",
|
|
11848
|
+
EAI_AGAIN: "el DNS no respondi\xF3 a tiempo",
|
|
11849
|
+
ECONNREFUSED: "el servidor rechaz\xF3 la conexi\xF3n",
|
|
11850
|
+
ECONNRESET: "la conexi\xF3n se cort\xF3",
|
|
11851
|
+
EPIPE: "la conexi\xF3n se cort\xF3",
|
|
11852
|
+
ETIMEDOUT: "tiempo agotado al conectar",
|
|
11853
|
+
ENETUNREACH: "sin red (red inalcanzable)",
|
|
11854
|
+
EHOSTUNREACH: "sin red (servidor inalcanzable)",
|
|
11855
|
+
ENETDOWN: "sin red (interfaz ca\xEDda)",
|
|
11856
|
+
UND_ERR_SOCKET: "la conexi\xF3n se cort\xF3",
|
|
11857
|
+
UND_ERR_CONNECT_TIMEOUT: "tiempo agotado al conectar",
|
|
11858
|
+
UND_ERR_HEADERS_TIMEOUT: "el servidor no respondi\xF3 a tiempo",
|
|
11859
|
+
UND_ERR_BODY_TIMEOUT: "el servidor dej\xF3 de mandar datos",
|
|
11860
|
+
UND_ERR_CLOSED: "la conexi\xF3n se cerr\xF3"
|
|
11861
|
+
};
|
|
11862
|
+
var TLS = /^(ERR_TLS_|CERT_|UNABLE_TO_|SELF_SIGNED|DEPTH_ZERO|ERR_SSL_)/;
|
|
11863
|
+
function codigoDe(e7) {
|
|
11864
|
+
for (let x2 = e7, i = 0; x2 && typeof x2 === "object" && i < 5; x2 = x2.cause, i++) {
|
|
11865
|
+
const c = x2.code;
|
|
11866
|
+
if (typeof c === "string" && c) return c;
|
|
11867
|
+
}
|
|
11868
|
+
return null;
|
|
11869
|
+
}
|
|
11870
|
+
function causaDeRed(e7) {
|
|
11871
|
+
const nombre = e7?.name;
|
|
11872
|
+
if (nombre === "TimeoutError") return "tiempo agotado";
|
|
11873
|
+
const codigo = codigoDe(e7);
|
|
11874
|
+
if (codigo && CAUSAS[codigo]) return `${CAUSAS[codigo]} (${codigo})`;
|
|
11875
|
+
if (codigo && TLS.test(codigo)) return `error de TLS (${codigo})`;
|
|
11876
|
+
const interna = e7?.cause?.message;
|
|
11877
|
+
const msg = typeof interna === "string" && interna ? interna : e7?.message ?? String(e7);
|
|
11878
|
+
return codigo ? `${msg} (${codigo})` : msg;
|
|
11879
|
+
}
|
|
11880
|
+
function rutaSinQuery(metodo, url) {
|
|
11881
|
+
try {
|
|
11882
|
+
const u2 = new URL(url);
|
|
11883
|
+
return `${metodo} ${u2.host}${u2.pathname}`;
|
|
11884
|
+
} catch {
|
|
11885
|
+
return `${metodo} ${url.split("?")[0]}`;
|
|
11886
|
+
}
|
|
11887
|
+
}
|
|
11888
|
+
function esperaConJitter(n, baseMs, topeMs, azar = Math.random) {
|
|
11889
|
+
const techo = Math.min(topeMs, baseMs * 2 ** Math.max(0, n - 1));
|
|
11890
|
+
return Math.round(techo / 2 + azar() * (techo / 2));
|
|
11891
|
+
}
|
|
11892
|
+
|
|
11821
11893
|
// src/worker/limites.ts
|
|
11822
11894
|
var LIMITES = {
|
|
11823
11895
|
agente: 80,
|
|
@@ -11855,12 +11927,21 @@ function acotarHuerfanosMin(n) {
|
|
|
11855
11927
|
// src/worker/api.ts
|
|
11856
11928
|
var MAX_BYTES_PNG_BASE64 = 4 * 1024 * 1024;
|
|
11857
11929
|
var ErrorApi = class extends Error {
|
|
11858
|
-
constructor(estado2, mensaje) {
|
|
11930
|
+
constructor(estado2, mensaje, o = {}) {
|
|
11859
11931
|
super(mensaje);
|
|
11860
11932
|
this.estado = estado2;
|
|
11861
11933
|
this.name = "ErrorApi";
|
|
11934
|
+
this.ruta = o.ruta ?? null;
|
|
11935
|
+
this.red = o.red === true;
|
|
11862
11936
|
}
|
|
11863
11937
|
estado;
|
|
11938
|
+
/** CLA-383: método y ruta (sin query) de la llamada que falló, y si fue la red (sin respuesta HTTP: `estado` 0). */
|
|
11939
|
+
ruta;
|
|
11940
|
+
red;
|
|
11941
|
+
/** CLA-383: vale la pena reintentar: corte de red, 429 o 5xx (un 4xx es una respuesta firme de la API). */
|
|
11942
|
+
get transitorio() {
|
|
11943
|
+
return this.red || this.estado === 429 || this.estado >= 500;
|
|
11944
|
+
}
|
|
11864
11945
|
get conflicto() {
|
|
11865
11946
|
return this.estado === 409;
|
|
11866
11947
|
}
|
|
@@ -11871,6 +11952,7 @@ var ErrorApi = class extends Error {
|
|
|
11871
11952
|
};
|
|
11872
11953
|
var duracionValida = (d) => typeof d === "number" && Number.isFinite(d) && d > 0;
|
|
11873
11954
|
var cabReclamo = (reclamo) => reclamo ? { "x-claqueta-reclamo": reclamo } : {};
|
|
11955
|
+
var PLAZO_PROGRESO_MS = 2e4;
|
|
11874
11956
|
var PLAZO_TRANSFERENCIA_MS = 10 * 6e4;
|
|
11875
11957
|
function conPlazo(senal, ms2 = PLAZO_TRANSFERENCIA_MS) {
|
|
11876
11958
|
const c = new AbortController();
|
|
@@ -11888,16 +11970,27 @@ var camposCosto = (o) => o.costoUsd === void 0 ? {} : { costo_usd: o.costoUsd, .
|
|
|
11888
11970
|
var MIME_PIEZA = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", webp: "image/webp" };
|
|
11889
11971
|
function crearClienteApi(base, token, f = fetch) {
|
|
11890
11972
|
const cab = (extra = {}) => ({ ...token ? { authorization: `Bearer ${token}` } : {}, [CABECERA_VERSION]: process.env["CLAQUETA_VERSION"] || VERSION, ...extra });
|
|
11973
|
+
const fr2 = async (url, init = {}) => {
|
|
11974
|
+
try {
|
|
11975
|
+
return await f(url, init);
|
|
11976
|
+
} catch (e7) {
|
|
11977
|
+
const razon = init.signal?.aborted ? init.signal.reason : void 0;
|
|
11978
|
+
if (init.signal?.aborted && (!razon || razon.name === "AbortError")) throw e7;
|
|
11979
|
+
const ruta = rutaSinQuery(init.method ?? "GET", url);
|
|
11980
|
+
const causa = razon ? razon.name === "TimeoutError" ? "tiempo agotado" : razon.message : causaDeRed(e7);
|
|
11981
|
+
throw new ErrorApi(0, `sin respuesta de ${ruta}: ${causa}`, { ruta, red: true });
|
|
11982
|
+
}
|
|
11983
|
+
};
|
|
11891
11984
|
async function llamar(metodo, ruta, cuerpo, extra = {}, signal) {
|
|
11892
|
-
const r2 = await
|
|
11985
|
+
const r2 = await fr2(`${base}${ruta}`, {
|
|
11893
11986
|
method: metodo,
|
|
11894
11987
|
...signal ? { signal } : {},
|
|
11895
11988
|
headers: cab({ ...cuerpo === void 0 ? {} : { "content-type": "application/json" }, ...extra }),
|
|
11896
11989
|
...cuerpo === void 0 ? {} : { body: JSON.stringify(cuerpo) }
|
|
11897
11990
|
});
|
|
11898
|
-
return leer2(r2);
|
|
11991
|
+
return leer2(r2, `${metodo} ${ruta.split("?")[0]}`);
|
|
11899
11992
|
}
|
|
11900
|
-
async function leer2(r2) {
|
|
11993
|
+
async function leer2(r2, ruta) {
|
|
11901
11994
|
if (r2.ok) return r2.status === 204 ? void 0 : await r2.json();
|
|
11902
11995
|
let msg = `HTTP ${r2.status}`;
|
|
11903
11996
|
if (r2.status === 426) throw new ErrorApi(426, mensajeClienteDesactualizado(leerClienteDesactualizado(await r2.text().catch(() => "")), process.env["CLAQUETA_VERSION"] || VERSION));
|
|
@@ -11906,7 +11999,8 @@ function crearClienteApi(base, token, f = fetch) {
|
|
|
11906
11999
|
if (j.error) msg = j.error;
|
|
11907
12000
|
} catch {
|
|
11908
12001
|
}
|
|
11909
|
-
|
|
12002
|
+
const donde = ruta ?? (r2.url ? rutaSinQuery("", r2.url).trim() : null);
|
|
12003
|
+
throw new ErrorApi(r2.status, r2.status >= 500 && donde ? `${msg} en ${donde}` : msg, { ruta: donde });
|
|
11910
12004
|
}
|
|
11911
12005
|
async function subirRender(id3, version2, clave, ruta, revision, o = {}) {
|
|
11912
12006
|
const signal = conPlazo(o.senal);
|
|
@@ -11916,7 +12010,7 @@ function crearClienteApi(base, token, f = fetch) {
|
|
|
11916
12010
|
const base_rd = `/api/videos/${id3}/versiones/${version2}/renders/${encodeURIComponent(clave)}`;
|
|
11917
12011
|
if (ajustes.s3?.bucket) {
|
|
11918
12012
|
const sub = await llamar("POST", `${base_rd}/url`, {}, rec);
|
|
11919
|
-
const put = await
|
|
12013
|
+
const put = await fr2(sub.url, { method: "PUT", headers: sub.cabeceras, body: bytes, signal });
|
|
11920
12014
|
if (!put.ok) throw new ErrorApi(put.status, `la subida a S3 del render ${clave} fall\xF3 (HTTP ${put.status})`);
|
|
11921
12015
|
await llamar("POST", `${base_rd}/confirmar`, { nombre: basename3(ruta), ...revision ? { revision } : {}, ...duracionValida(o.duracionS) ? { duracion_s: o.duracionS } : {} }, rec);
|
|
11922
12016
|
return;
|
|
@@ -11925,7 +12019,7 @@ function crearClienteApi(base, token, f = fetch) {
|
|
|
11925
12019
|
if (revision) form.append("revision", JSON.stringify(revision));
|
|
11926
12020
|
if (duracionValida(o.duracionS)) form.append("duracion_s", String(o.duracionS));
|
|
11927
12021
|
form.append("archivo", new Blob([bytes], { type: "video/mp4" }), basename3(ruta));
|
|
11928
|
-
await leer2(await
|
|
12022
|
+
await leer2(await fr2(`${base}${base_rd}`, { method: "POST", headers: cab(rec), body: form, signal }));
|
|
11929
12023
|
}
|
|
11930
12024
|
async function subirPoster(id3, version2, clave, ruta, o = {}, archivo2 = "poster") {
|
|
11931
12025
|
const signal = conPlazo(o.senal);
|
|
@@ -11936,14 +12030,14 @@ function crearClienteApi(base, token, f = fetch) {
|
|
|
11936
12030
|
if (ajustes.s3?.bucket) {
|
|
11937
12031
|
const sub = await llamar("POST", `${base_rd}/url?archivo=${archivo2}`, {}, rec);
|
|
11938
12032
|
if (!sub.clave?.endsWith(archivo2 === "poster" ? "/poster.jpg" : "/parecido.jpg")) throw new ErrorApi(501, archivo2 === "poster" ? "la API no admite p\xF3sters todav\xEDa (CLA-171): actualiza el servidor" : "la API no admite la hoja de parecido todav\xEDa (CLA-167): actualiza el servidor");
|
|
11939
|
-
const put = await
|
|
12033
|
+
const put = await fr2(sub.url, { method: "PUT", headers: sub.cabeceras, body: bytes, signal });
|
|
11940
12034
|
if (!put.ok) throw new ErrorApi(put.status, `la subida a S3 del ${archivo2 === "poster" ? "p\xF3ster" : "hoja de parecido"} ${clave} fall\xF3 (HTTP ${put.status})`);
|
|
11941
12035
|
await llamar("POST", `${base_rd}/confirmar?archivo=${archivo2}`, { nombre: basename3(ruta) }, rec);
|
|
11942
12036
|
return;
|
|
11943
12037
|
}
|
|
11944
12038
|
const form = new FormData();
|
|
11945
12039
|
form.append("archivo", new Blob([bytes], { type: "image/jpeg" }), basename3(ruta));
|
|
11946
|
-
await leer2(await
|
|
12040
|
+
await leer2(await fr2(`${base}${base_rd}?archivo=${archivo2}`, { method: "POST", headers: cab(rec), body: form, signal }));
|
|
11947
12041
|
}
|
|
11948
12042
|
async function subirPrevia(id3, version2, ruta, o = {}) {
|
|
11949
12043
|
const signal = conPlazo(o.senal);
|
|
@@ -11953,14 +12047,14 @@ function crearClienteApi(base, token, f = fetch) {
|
|
|
11953
12047
|
const base_pv = `/api/videos/${id3}/versiones/${version2}/previa`;
|
|
11954
12048
|
if (ajustes.s3?.bucket) {
|
|
11955
12049
|
const sub = await llamar("POST", `${base_pv}/url`, {}, rec);
|
|
11956
|
-
const put = await
|
|
12050
|
+
const put = await fr2(sub.url, { method: "PUT", headers: sub.cabeceras, body: bytes, signal });
|
|
11957
12051
|
if (!put.ok) throw new ErrorApi(put.status, `la subida a S3 de la previa fall\xF3 (HTTP ${put.status})`);
|
|
11958
12052
|
await llamar("POST", `${base_pv}/confirmar`, { nombre: basename3(ruta) }, rec);
|
|
11959
12053
|
return;
|
|
11960
12054
|
}
|
|
11961
12055
|
const form = new FormData();
|
|
11962
12056
|
form.append("archivo", new Blob([bytes], { type: "video/mp4" }), basename3(ruta));
|
|
11963
|
-
await leer2(await
|
|
12057
|
+
await leer2(await fr2(`${base}${base_pv}`, { method: "POST", headers: cab(rec), body: form, signal }));
|
|
11964
12058
|
}
|
|
11965
12059
|
async function subirInsumo(id3, version2, ruta, rutaArchivo, o = {}) {
|
|
11966
12060
|
const signal = conPlazo(o.senal);
|
|
@@ -11971,7 +12065,7 @@ function crearClienteApi(base, token, f = fetch) {
|
|
|
11971
12065
|
const base_in = `/api/videos/${id3}/versiones/${version2}/insumos`;
|
|
11972
12066
|
if (ajustes.s3?.bucket) {
|
|
11973
12067
|
const sub = await llamar("POST", `${base_in}/url`, meta, rec);
|
|
11974
|
-
const put = await
|
|
12068
|
+
const put = await fr2(sub.url, { method: "PUT", headers: sub.cabeceras ?? {}, body: bytes, signal });
|
|
11975
12069
|
if (!put.ok) throw new ErrorApi(put.status, `la subida a S3 del insumo ${ruta} fall\xF3 (HTTP ${put.status})`);
|
|
11976
12070
|
await llamar("POST", `${base_in}/confirmar`, meta, rec);
|
|
11977
12071
|
return;
|
|
@@ -11980,7 +12074,7 @@ function crearClienteApi(base, token, f = fetch) {
|
|
|
11980
12074
|
form.append("ruta", ruta);
|
|
11981
12075
|
form.append("sha256", meta.sha256);
|
|
11982
12076
|
form.append("archivo", new Blob([bytes], { type: ruta.endsWith(".wav") ? "audio/wav" : ruta.endsWith(".srt") ? "application/x-subrip" : ruta.endsWith(".vtt") ? "text/vtt" : "application/json" }), basename3(ruta));
|
|
11983
|
-
await leer2(await
|
|
12077
|
+
await leer2(await fr2(`${base}${base_in}`, { method: "POST", headers: cab(rec), body: form, signal }));
|
|
11984
12078
|
}
|
|
11985
12079
|
return {
|
|
11986
12080
|
reclamar: (o) => {
|
|
@@ -12005,7 +12099,7 @@ function crearClienteApi(base, token, f = fetch) {
|
|
|
12005
12099
|
return;
|
|
12006
12100
|
}
|
|
12007
12101
|
const sub = await llamar("POST", `${ruta}/url`, {}, {}, senal);
|
|
12008
|
-
const put = await
|
|
12102
|
+
const put = await fr2(sub.url, { method: "PUT", headers: sub.cabeceras, body: new Uint8Array(png), signal: conPlazo(senal) });
|
|
12009
12103
|
if (!put.ok) throw new ErrorApi(put.status, `la subida a S3 del PNG sin fondo fall\xF3 (HTTP ${put.status})`);
|
|
12010
12104
|
await llamar("POST", `${ruta}/resultado`, { ...resto, clave: sub.clave }, {}, senal);
|
|
12011
12105
|
},
|
|
@@ -12023,7 +12117,7 @@ function crearClienteApi(base, token, f = fetch) {
|
|
|
12023
12117
|
const meta = { bytes: bytes.byteLength, sha256: createHash4("sha256").update(bytes).digest("hex") };
|
|
12024
12118
|
if (ajustes.s3?.bucket) {
|
|
12025
12119
|
const sub = await llamar("POST", `${ruta}/url`, { archivo: k }, {}, senal);
|
|
12026
|
-
const put = await
|
|
12120
|
+
const put = await fr2(sub.url, { method: "PUT", headers: sub.cabeceras, body: new Uint8Array(bytes), signal: conPlazo(senal) });
|
|
12027
12121
|
if (!put.ok) throw new ErrorApi(put.status, `la subida a S3 de ${basename3(rutaLocal)} fall\xF3 (HTTP ${put.status})`);
|
|
12028
12122
|
archivos[k] = meta;
|
|
12029
12123
|
} else archivos[k] = { ...meta, contenido_base64: bytes.toString("base64") };
|
|
@@ -12037,7 +12131,25 @@ function crearClienteApi(base, token, f = fetch) {
|
|
|
12037
12131
|
},
|
|
12038
12132
|
abrirStoryboardDeVersion: (videoId, version2, agente, senal) => llamar("POST", `/api/videos/${encodeURIComponent(videoId)}/versiones/${version2}/storyboard`, { agente: acotarTexto(agente, LIMITES.agente, "worker") }, {}, senal),
|
|
12039
12133
|
async progreso(id3, p) {
|
|
12040
|
-
await llamar("POST", `/api/videos/${id3}/progreso`, { ...p, etapa: acotarTexto(p.etapa, LIMITES.etapa, "desconocida"), porcentaje: acotarPorcentaje(p.porcentaje), mensaje: acotarTexto(p.mensaje, LIMITES.mensaje, "sin mensaje") });
|
|
12134
|
+
await llamar("POST", `/api/videos/${id3}/progreso`, { ...p, etapa: acotarTexto(p.etapa, LIMITES.etapa, "desconocida"), porcentaje: acotarPorcentaje(p.porcentaje), mensaje: acotarTexto(p.mensaje, LIMITES.mensaje, "sin mensaje") }, {}, AbortSignal.timeout(PLAZO_PROGRESO_MS));
|
|
12135
|
+
},
|
|
12136
|
+
async compatibilidad(q2) {
|
|
12137
|
+
const qs2 = new URLSearchParams({ version: process.env["CLAQUETA_VERSION"] || VERSION, ...q2.motorVersion ? { motor_version: q2.motorVersion } : {} });
|
|
12138
|
+
try {
|
|
12139
|
+
const j = await llamar("GET", `/api/cola/compatibilidad?${qs2}`, void 0, {}, AbortSignal.timeout(PLAZO_PROGRESO_MS));
|
|
12140
|
+
return typeof j?.api?.motor_esperado === "string" ? { motor_esperado: j.api.motor_esperado } : null;
|
|
12141
|
+
} catch (e7) {
|
|
12142
|
+
if (e7 instanceof ErrorApi && e7.estado === 404) return null;
|
|
12143
|
+
throw e7;
|
|
12144
|
+
}
|
|
12145
|
+
},
|
|
12146
|
+
async devolver(id3, x2) {
|
|
12147
|
+
try {
|
|
12148
|
+
return await llamar("POST", `/api/videos/${id3}/devolver`, { motivo: acotarTexto(x2.motivo, LIMITES.causa, "apagado del worker"), etapa: acotarOpcional(x2.etapa ?? void 0, LIMITES.etapa) ?? null, ...x2.reclamo ? { reclamo: x2.reclamo } : {} }, cabReclamo(x2.reclamo));
|
|
12149
|
+
} catch (e7) {
|
|
12150
|
+
if (e7 instanceof ErrorApi && e7.estado === 404 && e7.message === "Not Found") throw new ErrorApi(501, "la API no admite devolver un video a la cola sin gastar un reintento (POST /api/videos/:id/devolver, CLA-385)");
|
|
12151
|
+
throw e7;
|
|
12152
|
+
}
|
|
12041
12153
|
},
|
|
12042
12154
|
fallo: (id3, x2) => llamar("POST", `/api/videos/${id3}/fallo`, { etapa: acotarOpcional(x2.etapa, LIMITES.etapa) ?? null, causa: acotarTexto(x2.causa, LIMITES.causa, "fallo sin causa conocida"), codigo: Number.isInteger(x2.codigo) ? x2.codigo : null, max_reintentos: x2.maxReintentos, reintentable: x2.reintentable, ...camposCosto(x2), ...x2.reclamo ? { reclamo: x2.reclamo } : {} }),
|
|
12043
12155
|
async adjuntarMp4(id3, version2, ruta, o = {}) {
|
|
@@ -12048,7 +12160,7 @@ function crearClienteApi(base, token, f = fetch) {
|
|
|
12048
12160
|
const base_mp4 = `/api/videos/${id3}/versiones/${version2}/mp4`;
|
|
12049
12161
|
if (ajustes.s3?.bucket) {
|
|
12050
12162
|
const sub = await llamar("POST", `${base_mp4}/url`, {}, rec);
|
|
12051
|
-
const put = await
|
|
12163
|
+
const put = await fr2(sub.url, { method: "PUT", headers: sub.cabeceras, body: bytes, signal });
|
|
12052
12164
|
if (!put.ok) throw new ErrorApi(put.status, `la subida a S3 fall\xF3 (HTTP ${put.status})`);
|
|
12053
12165
|
return llamar("POST", `${base_mp4}/confirmar`, { nombre: basename3(ruta), ...camposCosto(o), ...o.revision ? { revision: o.revision } : {}, ...o.renders?.length ? { renders: o.renders } : {}, ...duracionValida(o.duracionS) ? { duracion_s: o.duracionS } : {} }, rec);
|
|
12054
12166
|
}
|
|
@@ -12060,7 +12172,7 @@ function crearClienteApi(base, token, f = fetch) {
|
|
|
12060
12172
|
if (duracionValida(o.duracionS)) form.append("duracion_s", String(o.duracionS));
|
|
12061
12173
|
if (o.renders?.length) form.append("renders", JSON.stringify(o.renders));
|
|
12062
12174
|
form.append("archivo", new Blob([bytes], { type: "video/mp4" }), basename3(ruta));
|
|
12063
|
-
return leer2(await
|
|
12175
|
+
return leer2(await fr2(`${base}${base_mp4}`, { method: "POST", headers: cab(rec), body: form, signal }));
|
|
12064
12176
|
},
|
|
12065
12177
|
async adjuntarRender(id3, version2, clave, ruta, revision, o = {}) {
|
|
12066
12178
|
try {
|
|
@@ -12100,7 +12212,7 @@ function crearClienteApi(base, token, f = fetch) {
|
|
|
12100
12212
|
},
|
|
12101
12213
|
async adjuntarArtefacto(id3, version2, tipo, clave, contenido, o = {}) {
|
|
12102
12214
|
try {
|
|
12103
|
-
await leer2(await
|
|
12215
|
+
await leer2(await fr2(`${base}/api/videos/${id3}/versiones/${version2}/artefactos/${encodeURIComponent(tipo)}/${encodeURIComponent(clave)}`, {
|
|
12104
12216
|
method: "POST",
|
|
12105
12217
|
headers: cab({ "content-type": "application/json", ...cabReclamo(o.reclamo) }),
|
|
12106
12218
|
body: JSON.stringify(contenido),
|
|
@@ -12121,14 +12233,14 @@ function crearClienteApi(base, token, f = fetch) {
|
|
|
12121
12233
|
const base_pz = `/api/videos/${id3}/versiones/${version2}/piezas/${encodeURIComponent(nombre)}`;
|
|
12122
12234
|
if (ajustes.s3?.bucket) {
|
|
12123
12235
|
const sub = await llamar("POST", `${base_pz}/url`, {}, rec);
|
|
12124
|
-
const put = await
|
|
12236
|
+
const put = await fr2(sub.url, { method: "PUT", headers: sub.cabeceras, body: bytes, signal });
|
|
12125
12237
|
if (!put.ok) throw new ErrorApi(put.status, `la subida a S3 de ${nombre} fall\xF3 (HTTP ${put.status})`);
|
|
12126
12238
|
await llamar("POST", `${base_pz}/confirmar`, {}, rec);
|
|
12127
12239
|
return;
|
|
12128
12240
|
}
|
|
12129
12241
|
const form = new FormData();
|
|
12130
12242
|
form.append("archivo", new Blob([bytes], { type: tipo }), nombre);
|
|
12131
|
-
await leer2(await
|
|
12243
|
+
await leer2(await fr2(`${base}${base_pz}`, { method: "POST", headers: cab(rec), body: form, signal }));
|
|
12132
12244
|
},
|
|
12133
12245
|
async adjuntarInsumo(id3, version2, ruta, rutaArchivo, o = {}) {
|
|
12134
12246
|
try {
|
|
@@ -12140,7 +12252,7 @@ function crearClienteApi(base, token, f = fetch) {
|
|
|
12140
12252
|
},
|
|
12141
12253
|
descargar(url, senal) {
|
|
12142
12254
|
const deLaApi = url.startsWith("/") || url.startsWith(`${base}/`);
|
|
12143
|
-
return
|
|
12255
|
+
return fr2(url.startsWith("/") ? `${base}${url}` : url, { ...deLaApi ? { headers: cab() } : {}, signal: conPlazo(senal) });
|
|
12144
12256
|
}
|
|
12145
12257
|
};
|
|
12146
12258
|
}
|
|
@@ -12420,6 +12532,12 @@ var rutasServicio = (casa = homedir4()) => ({
|
|
|
12420
12532
|
log: join15(casa, "Library", "Logs", "claqueta-worker.log")
|
|
12421
12533
|
});
|
|
12422
12534
|
var xml = (t) => t.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
12535
|
+
function esperaSalidaDe(args2) {
|
|
12536
|
+
const i = args2.findIndex((a) => a === "--gracia" || a.startsWith("--gracia="));
|
|
12537
|
+
const valor = i < 0 ? void 0 : args2[i].includes("=") ? args2[i].split("=")[1] : args2[i + 1];
|
|
12538
|
+
const min2 = valor !== void 0 && Number.isFinite(Number(valor)) && Number(valor) >= 0 ? Number(valor) : 10;
|
|
12539
|
+
return Math.round(min2 * 60) + 60;
|
|
12540
|
+
}
|
|
12423
12541
|
function generarPlist(e7) {
|
|
12424
12542
|
const argv = [e7.npx, "-y", "claqueta-mcp@latest", "worker", ...e7.args];
|
|
12425
12543
|
const items = argv.map((a) => ` <string>${xml(a)}</string>`).join("\n");
|
|
@@ -12438,7 +12556,9 @@ ${items}
|
|
|
12438
12556
|
<key>KeepAlive</key>
|
|
12439
12557
|
<true/>
|
|
12440
12558
|
<key>ThrottleInterval</key>
|
|
12441
|
-
<integer>30</integer
|
|
12559
|
+
<integer>30</integer>${e7.esperaSalidaS ? `
|
|
12560
|
+
<key>ExitTimeOut</key>
|
|
12561
|
+
<integer>${e7.esperaSalidaS}</integer>` : ""}
|
|
12442
12562
|
<key>WorkingDirectory</key>
|
|
12443
12563
|
<string>${xml(e7.casa)}</string>
|
|
12444
12564
|
<key>EnvironmentVariables</key>
|
|
@@ -12469,7 +12589,7 @@ async function instalarServicio(args2, d) {
|
|
|
12469
12589
|
const path = [.../* @__PURE__ */ new Set([nodeDir, "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin"])].join(":");
|
|
12470
12590
|
mkdirSync10(dirname6(r2.plist), { recursive: true });
|
|
12471
12591
|
mkdirSync10(dirname6(r2.log), { recursive: true });
|
|
12472
|
-
writeFileSync8(r2.plist, generarPlist({ npx: join15(nodeDir, "npx"), args: args2, casa, rutaLog: r2.log, path }), { mode: 420 });
|
|
12592
|
+
writeFileSync8(r2.plist, generarPlist({ npx: join15(nodeDir, "npx"), args: args2, casa, rutaLog: r2.log, path, esperaSalidaS: esperaSalidaDe(args2) }), { mode: 420 });
|
|
12473
12593
|
chmodSync3(r2.plist, 420);
|
|
12474
12594
|
const dominio = `gui/${d.uid ?? process.getuid?.() ?? 501}`;
|
|
12475
12595
|
await d.launchctl(["bootout", `${dominio}/${ETIQUETA}`]);
|
|
@@ -13628,7 +13748,7 @@ async function llamarHerramientaMcp(op2, nombre, args2, fetchFn = fetch) {
|
|
|
13628
13748
|
try {
|
|
13629
13749
|
const r2 = await fetchFn(`${op2.url.replace(/\/+$/, "")}/mcp`, {
|
|
13630
13750
|
method: "POST",
|
|
13631
|
-
headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${op2.token}
|
|
13751
|
+
headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${op2.token}`, [CABECERA_VERSION]: VERSION },
|
|
13632
13752
|
body: JSON.stringify({ jsonrpc: "2.0", id: "setup", method: "tools/call", params: { name: nombre, arguments: args2 } }),
|
|
13633
13753
|
redirect: "manual",
|
|
13634
13754
|
signal: AbortSignal.timeout(8e3)
|
|
@@ -14237,6 +14357,17 @@ function explicarErrorRed(e7, url, secretos2 = []) {
|
|
|
14237
14357
|
if (code === "EHOSTUNREACH" || code === "ENETUNREACH" || code === "ENETDOWN") return `No hay ruta de red hacia ${host} (${code}): revisa tu conexi\xF3n a internet.`;
|
|
14238
14358
|
return `Sin conexi\xF3n con ${url}: ${una([err.message, err.cause?.message].filter(Boolean).join(" - "), secretos2)}${code ? ` (${code})` : ""}.`;
|
|
14239
14359
|
}
|
|
14360
|
+
function chequeoTopes(d, o) {
|
|
14361
|
+
const num5 = (v2) => v2 && Number.isFinite(Number(v2)) && Number(v2) > 0 ? Number(v2) : void 0;
|
|
14362
|
+
const formato = o.topeFormatoMin ?? num5(d.env["WORKER_TIMEOUT_MIN"]) ?? 30;
|
|
14363
|
+
const etapa = o.topeEtapaMin ?? num5(d.env["WORKER_TIMEOUT_ETAPA_MIN"]);
|
|
14364
|
+
return {
|
|
14365
|
+
id: "topes",
|
|
14366
|
+
titulo: "Topes de tiempo del worker",
|
|
14367
|
+
estado: "ok",
|
|
14368
|
+
mensaje: `${formato} min por formato renderizado (un video de 3 formatos: ${formato * 3} min; uno largo, m\xE1s) y ${etapa ?? formato} min por etapa del motor${etapa ? "" : " (el del formato)"}. Se cambian con --tope-formato / --tope-etapa o WORKER_TIMEOUT_MIN / WORKER_TIMEOUT_ETAPA_MIN.`
|
|
14369
|
+
};
|
|
14370
|
+
}
|
|
14240
14371
|
function chequeoDisco(d, local = false) {
|
|
14241
14372
|
const titulo = "Espacio en disco";
|
|
14242
14373
|
const dir = d.env["WORKER_TRABAJO_DIR"] || join20(d.os.casa, ".cache", "claqueta", "trabajo");
|
|
@@ -14457,7 +14588,7 @@ async function ejecutarDoctor(o, d) {
|
|
|
14457
14588
|
if (o.modo === "local") {
|
|
14458
14589
|
const apiL = await chequeoApi(d, conf.cred);
|
|
14459
14590
|
compat = await chequeosCompatibilidad(d, o, conf.cred);
|
|
14460
|
-
chequeos = [...await chequeosLocal(d), ...conf.chequeos, apiL, ...compat.chequeos, chequeoDisco(d, true), chequeoServicio(d)].map(enmascara);
|
|
14591
|
+
chequeos = [...await chequeosLocal(d), ...conf.chequeos, apiL, ...compat.chequeos, chequeoDisco(d, true), chequeoTopes(d, o), chequeoServicio(d)].map(enmascara);
|
|
14461
14592
|
} else {
|
|
14462
14593
|
const apiP = chequeoApi(d, conf.cred);
|
|
14463
14594
|
const compatP = chequeosCompatibilidad(d, o, conf.cred);
|
|
@@ -14465,7 +14596,7 @@ async function ejecutarDoctor(o, d) {
|
|
|
14465
14596
|
const awsP = chequeosAws(d, o, imagen2, dockerP.then((x2) => x2.img.local));
|
|
14466
14597
|
const [{ dk: dk2, img }, aws, api, comp] = await Promise.all([dockerP, awsP, apiP, compatP]);
|
|
14467
14598
|
compat = comp;
|
|
14468
|
-
chequeos = [chequeoNode(d), dk2.binario, dk2.demonio, aws.cli, aws.perfil, ...conf.chequeos, api, ...comp.chequeos, img.chequeo, chequeoDisco(d), chequeoServicio(d)].map(enmascara);
|
|
14599
|
+
chequeos = [chequeoNode(d), dk2.binario, dk2.demonio, aws.cli, aws.perfil, ...conf.chequeos, api, ...comp.chequeos, img.chequeo, chequeoDisco(d), chequeoTopes(d, o), chequeoServicio(d)].map(enmascara);
|
|
14469
14600
|
}
|
|
14470
14601
|
if (o.compositor) chequeos = [...chequeos, ...(await chequeosCompositor(d)).map(enmascara)];
|
|
14471
14602
|
if (o.guionista) chequeos = [...chequeos, ...(await chequeosGuionista(d, o.guionistaActivado === true)).map(enmascara)];
|
|
@@ -14509,7 +14640,7 @@ var codigoSalida = (inf) => inf.resumen.bloqueo > 0 ? 1 : 0;
|
|
|
14509
14640
|
// src/worker-cli.ts
|
|
14510
14641
|
import { mkdirSync as mkdirSync12 } from "node:fs";
|
|
14511
14642
|
import { homedir as homedir6, hostname as hostname6 } from "node:os";
|
|
14512
|
-
import { dirname as dirname12, join as
|
|
14643
|
+
import { dirname as dirname12, join as join30 } from "node:path";
|
|
14513
14644
|
|
|
14514
14645
|
// src/worker/avance.ts
|
|
14515
14646
|
var NOMBRES = {
|
|
@@ -14630,18 +14761,241 @@ function crearAvance(salida, ops = {}) {
|
|
|
14630
14761
|
};
|
|
14631
14762
|
}
|
|
14632
14763
|
|
|
14764
|
+
// src/worker/motor-nuevo.ts
|
|
14765
|
+
var REVISAR_MOTOR_CADA_MS = 6 * 60 * 6e4;
|
|
14766
|
+
function avisoMotorNuevo(motorWorker, motorEsperado) {
|
|
14767
|
+
if (!motorWorker || !motorEsperado || !esMayor(motorEsperado, motorWorker)) return null;
|
|
14768
|
+
return `La API ya usa el motor ${motorEsperado} y este worker corre el ${motorWorker}: actualiza claqueta-mcp (npm i -g claqueta-mcp@latest, o reinicia el servicio, que usa @latest) y reinicia el worker. Si npm a\xFAn no tiene la versi\xF3n nueva, la publicaci\xF3n va en camino; mientras, las funciones nuevas del motor quedan sin usar en este worker.`;
|
|
14769
|
+
}
|
|
14770
|
+
async function revisarMotorNuevo(c, api) {
|
|
14771
|
+
if (!api.compatibilidad) return null;
|
|
14772
|
+
const motor2 = motorDeclarado(c);
|
|
14773
|
+
const r2 = await api.compatibilidad({ motorVersion: motor2.version }).catch(() => null);
|
|
14774
|
+
return avisoMotorNuevo(motor2.version, r2?.motor_esperado ?? null);
|
|
14775
|
+
}
|
|
14776
|
+
|
|
14777
|
+
// src/worker/pendientes.ts
|
|
14778
|
+
import { randomBytes as randomBytes4 } from "node:crypto";
|
|
14779
|
+
import { copyFile, mkdir as mkdir7, readdir as readdir2, readFile as readFile6, rm as rm4, stat, writeFile as writeFile5 } from "node:fs/promises";
|
|
14780
|
+
import { join as join21 } from "node:path";
|
|
14781
|
+
var ARCHIVO = "datos";
|
|
14782
|
+
var ENTRADA = "pendiente.json";
|
|
14783
|
+
function colaPendientesDe(c, env = process.env) {
|
|
14784
|
+
const num5 = (k, def) => {
|
|
14785
|
+
const v2 = Number(env[k]);
|
|
14786
|
+
return env[k]?.trim() && Number.isFinite(v2) && v2 >= 0 ? v2 : def;
|
|
14787
|
+
};
|
|
14788
|
+
return { dir: join21(c.trabajoDir, ".pendientes"), maxBytes: num5("WORKER_PENDIENTES_MB", 1024) * 1024 * 1024, caducidadMs: num5("WORKER_PENDIENTES_DIAS", 3) * 864e5 };
|
|
14789
|
+
}
|
|
14790
|
+
async function entradas(q2) {
|
|
14791
|
+
let nombres;
|
|
14792
|
+
try {
|
|
14793
|
+
nombres = await readdir2(q2.dir);
|
|
14794
|
+
} catch {
|
|
14795
|
+
return [];
|
|
14796
|
+
}
|
|
14797
|
+
const r2 = [];
|
|
14798
|
+
for (const n of nombres) {
|
|
14799
|
+
const carpeta2 = join21(q2.dir, n);
|
|
14800
|
+
try {
|
|
14801
|
+
r2.push({ carpeta: carpeta2, p: JSON.parse(await readFile6(join21(carpeta2, ENTRADA), "utf8")) });
|
|
14802
|
+
} catch {
|
|
14803
|
+
await rm4(carpeta2, { recursive: true, force: true });
|
|
14804
|
+
}
|
|
14805
|
+
}
|
|
14806
|
+
return r2.sort((a, b) => a.p.creado - b.p.creado);
|
|
14807
|
+
}
|
|
14808
|
+
async function tamanoCola(q2) {
|
|
14809
|
+
return (await entradas(q2)).reduce((s, e7) => s + e7.p.bytes, 0);
|
|
14810
|
+
}
|
|
14811
|
+
async function encolar(q2, x2, log, ahora = Date.now()) {
|
|
14812
|
+
try {
|
|
14813
|
+
const bytes = (await stat(x2.archivo)).size;
|
|
14814
|
+
const ocupado = await tamanoCola(q2);
|
|
14815
|
+
if (ocupado + bytes > q2.maxBytes) {
|
|
14816
|
+
log(`pendientes: no guardo ${x2.destino} de ${x2.videoId} (${Math.round(bytes / 1e6)} MB): la cola local llegar\xEDa a su tope de ${Math.round(q2.maxBytes / 1048576)} MB (WORKER_PENDIENTES_MB)`);
|
|
14817
|
+
return false;
|
|
14818
|
+
}
|
|
14819
|
+
const carpeta2 = join21(q2.dir, `${x2.videoId}-v${x2.version}-${randomBytes4(4).toString("hex")}`.replace(/[^A-Za-z0-9_.-]/g, "_"));
|
|
14820
|
+
await mkdir7(carpeta2, { recursive: true });
|
|
14821
|
+
await copyFile(x2.archivo, join21(carpeta2, ARCHIVO));
|
|
14822
|
+
const p = { tipo: x2.tipo, video_id: x2.videoId, version: x2.version, destino: x2.destino, bytes, creado: ahora, intentos: 0, ...x2.error ? { ultimo_error: x2.error.slice(0, 300) } : {} };
|
|
14823
|
+
await writeFile5(join21(carpeta2, ENTRADA), JSON.stringify(p, null, 2));
|
|
14824
|
+
return true;
|
|
14825
|
+
} catch (e7) {
|
|
14826
|
+
log(`pendientes: no pude guardar ${x2.destino} de ${x2.videoId}: ${e7.message}`);
|
|
14827
|
+
return false;
|
|
14828
|
+
}
|
|
14829
|
+
}
|
|
14830
|
+
async function reintentarPendientes(q2, api, o = { log: () => {
|
|
14831
|
+
} }) {
|
|
14832
|
+
const ahora = o.ahora ?? Date.now();
|
|
14833
|
+
const r2 = { subidos: [], descartados: [], quedan: 0 };
|
|
14834
|
+
for (const { carpeta: carpeta2, p } of await entradas(q2)) {
|
|
14835
|
+
if (o.soloVideo && p.video_id !== o.soloVideo) {
|
|
14836
|
+
r2.quedan += 1;
|
|
14837
|
+
continue;
|
|
14838
|
+
}
|
|
14839
|
+
if (o.senal?.aborted) {
|
|
14840
|
+
r2.quedan += 1;
|
|
14841
|
+
continue;
|
|
14842
|
+
}
|
|
14843
|
+
if (ahora - p.creado > q2.caducidadMs) {
|
|
14844
|
+
await rm4(carpeta2, { recursive: true, force: true });
|
|
14845
|
+
r2.descartados.push({ p, motivo: "caduc\xF3" });
|
|
14846
|
+
o.log(`pendientes: descarto ${p.destino} de ${p.video_id} v${p.version}: caduc\xF3 (WORKER_PENDIENTES_DIAS)`);
|
|
14847
|
+
continue;
|
|
14848
|
+
}
|
|
14849
|
+
const archivo2 = join21(carpeta2, ARCHIVO);
|
|
14850
|
+
try {
|
|
14851
|
+
if (p.tipo === "insumo") await api.adjuntarInsumo(p.video_id, p.version, p.destino, archivo2, o.senal ? { senal: o.senal } : {});
|
|
14852
|
+
else await api.adjuntarPoster(p.video_id, p.version, p.destino, archivo2, o.senal ? { senal: o.senal } : {});
|
|
14853
|
+
await rm4(carpeta2, { recursive: true, force: true });
|
|
14854
|
+
r2.subidos.push(p);
|
|
14855
|
+
o.log(`pendientes: sub\xED ${p.tipo === "insumo" ? p.destino : `p\xF3ster ${p.destino}`} de ${p.video_id} v${p.version} (estaba pendiente desde ${new Date(p.creado).toISOString()})`);
|
|
14856
|
+
await o.alSubir?.(p).catch(() => {
|
|
14857
|
+
});
|
|
14858
|
+
} catch (e7) {
|
|
14859
|
+
const firme = e7 instanceof ErrorApi && (e7.conflicto || e7.estado === 404 || e7.estado === 501 || e7.estado === 400 && !e7.transitorio);
|
|
14860
|
+
if (firme) {
|
|
14861
|
+
await rm4(carpeta2, { recursive: true, force: true });
|
|
14862
|
+
r2.descartados.push({ p, motivo: e7.message });
|
|
14863
|
+
o.log(`pendientes: descarto ${p.destino} de ${p.video_id} v${p.version}: ${e7.message}`);
|
|
14864
|
+
continue;
|
|
14865
|
+
}
|
|
14866
|
+
r2.quedan += 1;
|
|
14867
|
+
await writeFile5(join21(carpeta2, ENTRADA), JSON.stringify({ ...p, intentos: p.intentos + 1, ultimo_error: e7.message.slice(0, 300) }, null, 2)).catch(() => {
|
|
14868
|
+
});
|
|
14869
|
+
}
|
|
14870
|
+
}
|
|
14871
|
+
return r2;
|
|
14872
|
+
}
|
|
14873
|
+
|
|
14633
14874
|
// src/worker/worker.ts
|
|
14634
14875
|
import { hostname as hostname4 } from "node:os";
|
|
14635
|
-
import { access as access3, mkdir as
|
|
14636
|
-
import { dirname as dirname11, join as
|
|
14876
|
+
import { access as access3, mkdir as mkdir11, readFile as readFile13, rm as rm8, writeFile as writeFile10 } from "node:fs/promises";
|
|
14877
|
+
import { dirname as dirname11, join as join29, resolve as resolve9, sep as sep5 } from "node:path";
|
|
14878
|
+
|
|
14879
|
+
// src/worker/tiempos.ts
|
|
14880
|
+
var PRODUCCION = /* @__PURE__ */ new Set(["composicion", "render", "mezcla"]);
|
|
14881
|
+
var Cronometro = class {
|
|
14882
|
+
constructor(reloj = Date.now) {
|
|
14883
|
+
this.reloj = reloj;
|
|
14884
|
+
}
|
|
14885
|
+
reloj;
|
|
14886
|
+
tramos = [];
|
|
14887
|
+
/** Se llama con cada evento: abre un tramo nuevo cuando cambia la etapa. */
|
|
14888
|
+
marcar(etapa) {
|
|
14889
|
+
const u2 = this.tramos.at(-1);
|
|
14890
|
+
if (u2?.etapa === etapa) return;
|
|
14891
|
+
const ahora = this.reloj();
|
|
14892
|
+
if (u2) u2.fin = ahora;
|
|
14893
|
+
this.tramos.push({ etapa, ini: ahora });
|
|
14894
|
+
}
|
|
14895
|
+
resumen() {
|
|
14896
|
+
if (!this.tramos.length) return null;
|
|
14897
|
+
const fin = this.reloj();
|
|
14898
|
+
const etapas = {};
|
|
14899
|
+
const formatos = [];
|
|
14900
|
+
let actual = null;
|
|
14901
|
+
let previa = null;
|
|
14902
|
+
for (const t of this.tramos) {
|
|
14903
|
+
const s = ((t.fin ?? fin) - t.ini) / 1e3;
|
|
14904
|
+
etapas[t.etapa] = (etapas[t.etapa] ?? 0) + s;
|
|
14905
|
+
if (PRODUCCION.has(t.etapa)) {
|
|
14906
|
+
const nuevo = !actual || !PRODUCCION.has(previa ?? "") || actual.vioRender && (t.etapa === "composicion" || t.etapa === "render" && previa === "mezcla");
|
|
14907
|
+
if (nuevo) {
|
|
14908
|
+
actual = { s: 0, vioRender: false };
|
|
14909
|
+
formatos.push(0);
|
|
14910
|
+
}
|
|
14911
|
+
actual.s += s;
|
|
14912
|
+
if (t.etapa === "render") actual.vioRender = true;
|
|
14913
|
+
formatos[formatos.length - 1] = actual.s;
|
|
14914
|
+
}
|
|
14915
|
+
previa = t.etapa;
|
|
14916
|
+
}
|
|
14917
|
+
const r1 = (x2) => Math.round(x2 * 10) / 10;
|
|
14918
|
+
return { etapas: Object.fromEntries(Object.entries(etapas).map(([k, v2]) => [k, r1(v2)])), formatos: formatos.map(r1), total_s: r1((fin - this.tramos[0].ini) / 1e3) };
|
|
14919
|
+
}
|
|
14920
|
+
};
|
|
14921
|
+
var min = (s) => `${(s / 60).toFixed(1)} min`;
|
|
14922
|
+
function mensajeTiempos(r2, topes) {
|
|
14923
|
+
const partes3 = Object.entries(r2.etapas).filter(([k]) => !PRODUCCION.has(k)).map(([k, v2]) => `${k} ${min(v2)}`);
|
|
14924
|
+
if (r2.formatos.length) partes3.splice(Math.min(2, partes3.length), 0, `formato${r2.formatos.length === 1 ? "" : "s"} ${r2.formatos.map((s) => (s / 60).toFixed(1)).join(" / ")} min`);
|
|
14925
|
+
return `tiempos del motor: ${partes3.join(" \xB7 ")} \xB7 total ${min(r2.total_s)} (topes: ${topes.formatoMin} min por formato, ${topes.etapaMin} por etapa)`;
|
|
14926
|
+
}
|
|
14927
|
+
|
|
14928
|
+
// src/worker/segunda-pasada.ts
|
|
14929
|
+
var RE_MENSAJE = /^re-componiendo una vez por (.+?)(?: \((.*)\))?$/;
|
|
14930
|
+
function segundaPasadaDe(e7) {
|
|
14931
|
+
const d = e7.datos?.["segunda_pasada"];
|
|
14932
|
+
if (d && typeof d === "object" && !Array.isArray(d)) {
|
|
14933
|
+
const x2 = d;
|
|
14934
|
+
const fallidos = Array.isArray(x2["fallidos"]) ? x2["fallidos"].filter((f) => typeof f === "string") : [];
|
|
14935
|
+
return {
|
|
14936
|
+
fallidos,
|
|
14937
|
+
ajustes: x2["ajustes"] && typeof x2["ajustes"] === "object" ? x2["ajustes"] : {},
|
|
14938
|
+
...x2["valores"] && typeof x2["valores"] === "object" ? { valores: x2["valores"] } : {},
|
|
14939
|
+
...Array.isArray(x2["renders"]) ? { renders: x2["renders"].filter((r2) => typeof r2 === "string") } : {},
|
|
14940
|
+
motivo: typeof x2["motivo"] === "string" && x2["motivo"] ? x2["motivo"] : e7.mensaje
|
|
14941
|
+
};
|
|
14942
|
+
}
|
|
14943
|
+
if (e7.etapa !== "revision" || e7.nivel !== "advertencia") return null;
|
|
14944
|
+
const m = RE_MENSAJE.exec(e7.mensaje.trim());
|
|
14945
|
+
if (!m) return null;
|
|
14946
|
+
const ajustes = Object.fromEntries((m[2] ?? "").split(",").map((p) => p.trim()).filter(Boolean).map((p) => {
|
|
14947
|
+
const [k, ...v2] = p.split("=");
|
|
14948
|
+
return [k.trim(), v2.join("=").trim()];
|
|
14949
|
+
}));
|
|
14950
|
+
return { fallidos: m[1].split(",").map((f) => f.trim()).filter(Boolean), ajustes, motivo: e7.mensaje };
|
|
14951
|
+
}
|
|
14952
|
+
var QUE_ES = {
|
|
14953
|
+
choque_cajas: "cajas o etiquetas del diagrama encimadas",
|
|
14954
|
+
area_vacia: "demasiado espacio vac\xEDo en el cuadro",
|
|
14955
|
+
texto_cortado: "texto cortado en el borde"
|
|
14956
|
+
};
|
|
14957
|
+
var AJUSTE = {
|
|
14958
|
+
separacion_nodos: "separar los nodos",
|
|
14959
|
+
recolocar_etiquetas: "recolocar las etiquetas",
|
|
14960
|
+
escala_diagrama: "agrandar el diagrama"
|
|
14961
|
+
};
|
|
14962
|
+
var valorDe = (v2) => {
|
|
14963
|
+
const x2 = v2 && typeof v2 === "object" ? v2.valor : v2;
|
|
14964
|
+
if (x2 === void 0 || x2 === null) return null;
|
|
14965
|
+
return typeof x2 === "object" ? JSON.stringify(x2).slice(0, 60) : String(x2);
|
|
14966
|
+
};
|
|
14967
|
+
function mensajeSegundaPasada(s) {
|
|
14968
|
+
const fall = s.fallidos.map((f) => {
|
|
14969
|
+
const v2 = valorDe(s.valores?.[f]);
|
|
14970
|
+
return `${f} (${QUE_ES[f] ?? "chequeo de la revisi\xF3n"}${v2 !== null ? `; valor ${v2}` : ""})`;
|
|
14971
|
+
});
|
|
14972
|
+
const aj = Object.entries(s.ajustes).map(([k, v2]) => `${AJUSTE[k] ?? k}${v2 === true || v2 === "True" ? "" : ` \xD7${v2}`}`);
|
|
14973
|
+
return `Segunda pasada del motor: fall\xF3 ${fall.join(", ") || "un chequeo de la revisi\xF3n"}${s.renders?.length ? ` en ${s.renders.join(", ")}` : ""}; se re-compone una vez${aj.length ? ` para ${aj.join(" y ")}` : ""}`;
|
|
14974
|
+
}
|
|
14975
|
+
function resumenCorreccion(construccion) {
|
|
14976
|
+
const reg = construccion?.["revision_correccion"];
|
|
14977
|
+
if (!reg || typeof reg !== "object") return null;
|
|
14978
|
+
const r2 = reg;
|
|
14979
|
+
const fallidos = Array.isArray(r2.fallidos) ? r2.fallidos : [];
|
|
14980
|
+
const cambio = fallidos.map((f) => {
|
|
14981
|
+
const a = valorDe(r2.antes?.[f]);
|
|
14982
|
+
const d = valorDe(r2.despues?.[f]);
|
|
14983
|
+
return `${f}${a !== null ? ` ${a}${d !== null ? ` \u2192 ${d}` : ""}` : ""}`;
|
|
14984
|
+
}).join(", ");
|
|
14985
|
+
const datos = { segunda_pasada: reg };
|
|
14986
|
+
if (r2.resultado === "corregido") return { mensaje: `Segunda pasada del motor: corregido (${cambio})`, datos };
|
|
14987
|
+
if (r2.resultado === "sigue_fallando") return { mensaje: `Segunda pasada del motor: siguen fallando ${(r2.siguen_fallando ?? fallidos).join(", ")} (${cambio}); se entrega con la revisi\xF3n NO aprobada`, nivel: "advertencia", datos };
|
|
14988
|
+
if (r2.resultado === "sin_reintento") return { mensaje: `Revisi\xF3n: fall\xF3 ${cambio || fallidos.join(", ")} y no hubo segunda pasada (${r2.motivo ?? "sin motivo"})`, nivel: "advertencia", datos };
|
|
14989
|
+
return null;
|
|
14990
|
+
}
|
|
14637
14991
|
|
|
14638
14992
|
// src/worker/informe.ts
|
|
14639
|
-
import { access, readFile as
|
|
14640
|
-
import { join as
|
|
14993
|
+
import { access, readFile as readFile7 } from "node:fs/promises";
|
|
14994
|
+
import { join as join22, resolve as resolve8, sep as sep4 } from "node:path";
|
|
14641
14995
|
var existe = (ruta) => access(ruta).then(() => true, () => false);
|
|
14642
14996
|
async function leerJson3(ruta) {
|
|
14643
14997
|
try {
|
|
14644
|
-
const x2 = JSON.parse(await
|
|
14998
|
+
const x2 = JSON.parse(await readFile7(ruta, "utf8"));
|
|
14645
14999
|
return x2 && typeof x2 === "object" && !Array.isArray(x2) ? x2 : null;
|
|
14646
15000
|
} catch {
|
|
14647
15001
|
return null;
|
|
@@ -14657,17 +15011,17 @@ function clavePrincipalDePedido(pedido) {
|
|
|
14657
15011
|
}
|
|
14658
15012
|
async function leerInformes(salidaDir, manifiesto, pedido) {
|
|
14659
15013
|
const raiz = resolve8(salidaDir);
|
|
14660
|
-
const sinCarpetaRenders = !await existe(
|
|
15014
|
+
const sinCarpetaRenders = !await existe(join22(raiz, "renders"));
|
|
14661
15015
|
const candidatos = manifiesto.renders.length ? manifiesto.renders.map((r2, i) => {
|
|
14662
15016
|
const ruta = resolve8(raiz, r2.rutaRevision ?? `renders/${r2.etiqueta}/revision.json`);
|
|
14663
15017
|
return { clave: r2.etiqueta, ruta: ruta.startsWith(raiz + sep4) ? ruta : null, respaldoRaiz: i === 0 && sinCarpetaRenders };
|
|
14664
|
-
}) : [{ clave: clavePrincipalDePedido(pedido), ruta:
|
|
15018
|
+
}) : [{ clave: clavePrincipalDePedido(pedido), ruta: join22(raiz, "revision.json"), respaldoRaiz: false }];
|
|
14665
15019
|
const por = manifiesto.tiempos?.["por_render"] ?? {};
|
|
14666
15020
|
const { por_render: _omitido, ...generales } = manifiesto.tiempos ?? {};
|
|
14667
15021
|
const salida = [];
|
|
14668
15022
|
for (const c of candidatos) {
|
|
14669
15023
|
let informe = c.ruta ? await leerJson3(c.ruta) : null;
|
|
14670
|
-
if (!informe && c.respaldoRaiz) informe = await leerJson3(
|
|
15024
|
+
if (!informe && c.respaldoRaiz) informe = await leerJson3(join22(raiz, "revision.json"));
|
|
14671
15025
|
if (!informe) continue;
|
|
14672
15026
|
const propios = por[c.clave];
|
|
14673
15027
|
salida.push({
|
|
@@ -14683,8 +15037,8 @@ async function leerInformes(salidaDir, manifiesto, pedido) {
|
|
|
14683
15037
|
}
|
|
14684
15038
|
|
|
14685
15039
|
// src/worker/manifiesto.ts
|
|
14686
|
-
import { readFile as
|
|
14687
|
-
import { join as
|
|
15040
|
+
import { readFile as readFile8 } from "node:fs/promises";
|
|
15041
|
+
import { join as join23 } from "node:path";
|
|
14688
15042
|
var SEMVER = /^\d+\.\d+\.\d+$/;
|
|
14689
15043
|
function versionEsquema(crudo) {
|
|
14690
15044
|
const v2 = crudo["version_esquema"];
|
|
@@ -14700,7 +15054,7 @@ async function leerManifiesto(salidaDir, log = () => {
|
|
|
14700
15054
|
}) {
|
|
14701
15055
|
let crudo;
|
|
14702
15056
|
try {
|
|
14703
|
-
crudo = JSON.parse(await
|
|
15057
|
+
crudo = JSON.parse(await readFile8(join23(salidaDir, "manifiesto.json"), "utf8"));
|
|
14704
15058
|
if (!crudo || typeof crudo !== "object") throw new Error("no es un objeto");
|
|
14705
15059
|
} catch {
|
|
14706
15060
|
return { renders: [], costo: void 0, tiempos: void 0, construccion: void 0, edicion: void 0, duracionS: void 0 };
|
|
@@ -14797,6 +15151,7 @@ var ESTETICAS_POR_FAMILIA = {
|
|
|
14797
15151
|
"explicativo-personaje": ["claro-puntos", "pizarra", "marca-clara", "poster-oscuro", "base", ...ESTETICAS_2D, ...ESTETICAS_TODAS, ...ESTETICAS_3D],
|
|
14798
15152
|
"leccion-diagrama": ["tablero-plano", "pizarra", ...ESTETICAS_2D, ...ESTETICAS_TODAS],
|
|
14799
15153
|
"lista-top-n": ["base", "marca-clara", "pizarra", ...ESTETICAS_2D, ...ESTETICAS_TODAS],
|
|
15154
|
+
"matematica-animada": ["pizarra-negra"],
|
|
14800
15155
|
"poster-oscuro": ["poster-oscuro", ...ESTETICAS_TODAS],
|
|
14801
15156
|
"tres-objeciones": ["flat-editorial", ...ESTETICAS_TODAS]
|
|
14802
15157
|
};
|
|
@@ -14878,17 +15233,18 @@ function formatosDelPedido(p) {
|
|
|
14878
15233
|
const r2 = p["renders"];
|
|
14879
15234
|
return Array.isArray(r2) && r2.length > 0 ? r2.length : 1;
|
|
14880
15235
|
}
|
|
14881
|
-
function topeDelPedido(p,
|
|
15236
|
+
function topeDelPedido(p, minimoPorFormatoMs) {
|
|
14882
15237
|
const duracionS = duracionEstimadaS(p);
|
|
14883
15238
|
const formatos = formatosDelPedido(p);
|
|
14884
15239
|
const proporcionalMin = duracionS === void 0 ? 0 : TOPE_BASE_MIN + Math.ceil(duracionS / 60 * MIN_RENDER_POR_MIN_VIDEO * formatos);
|
|
14885
|
-
const ms2 = Math.max(
|
|
14886
|
-
|
|
15240
|
+
const ms2 = Math.max(minimoPorFormatoMs * formatos, proporcionalMin * 6e4);
|
|
15241
|
+
const porFormatoMs = Math.max(minimoPorFormatoMs, Math.round(ms2 / formatos));
|
|
15242
|
+
return { ms: ms2, porFormatoMs, duracionS, formatos, ampliado: ms2 > minimoPorFormatoMs };
|
|
14887
15243
|
}
|
|
14888
15244
|
|
|
14889
15245
|
// src/worker/quitar-fondo.ts
|
|
14890
|
-
import { mkdir as
|
|
14891
|
-
import { join as
|
|
15246
|
+
import { mkdir as mkdir8, readFile as readFile9, rm as rm5, writeFile as writeFile6 } from "node:fs/promises";
|
|
15247
|
+
import { join as join24 } from "node:path";
|
|
14892
15248
|
var TIMEOUT_FONDO_MS = 5 * 6e4;
|
|
14893
15249
|
var MAX_BYTES_ORIGINAL = 60 * 1024 * 1024;
|
|
14894
15250
|
var EXT = { "image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp" };
|
|
@@ -14901,9 +15257,9 @@ var num3 = (v2) => typeof v2 === "number" && Number.isFinite(v2) ? v2 : 0;
|
|
|
14901
15257
|
async function resolverQuitarFondo(c, d, t) {
|
|
14902
15258
|
const log = d.log ?? (() => {
|
|
14903
15259
|
});
|
|
14904
|
-
const raiz =
|
|
14905
|
-
const pedidoDir =
|
|
14906
|
-
const salidaDir =
|
|
15260
|
+
const raiz = join24(c.trabajoDir, `quitar-fondo-${t.id}`.replace(/[^a-zA-Z0-9_.-]/g, "_"));
|
|
15261
|
+
const pedidoDir = join24(raiz, "pedido");
|
|
15262
|
+
const salidaDir = join24(raiz, "salida");
|
|
14907
15263
|
const ignorarVencido2 = (e7) => {
|
|
14908
15264
|
if (e7 instanceof ErrorApi && (e7.conflicto || e7.estado === 404)) return;
|
|
14909
15265
|
throw e7;
|
|
@@ -14919,15 +15275,15 @@ async function resolverQuitarFondo(c, d, t) {
|
|
|
14919
15275
|
if (!ext) return await error2(`el original no es PNG, JPG ni WebP (${t.nombre ?? t.mime ?? "sin nombre"})`);
|
|
14920
15276
|
if (!t.url) return await error2("el original no tiene archivo en el servidor");
|
|
14921
15277
|
if (t.bytes > MAX_BYTES_ORIGINAL) return await error2(`el original pesa ${Math.round(t.bytes / 1024 / 1024)} MB (tope ${MAX_BYTES_ORIGINAL / 1024 / 1024} MB)`);
|
|
14922
|
-
await
|
|
14923
|
-
await
|
|
15278
|
+
await mkdir8(pedidoDir, { recursive: true });
|
|
15279
|
+
await mkdir8(salidaDir, { recursive: true });
|
|
14924
15280
|
const r2 = await (d.descargar ?? ((u2, s) => fetch(u2, s ? { signal: s } : {})))(t.url, conPlazo(d.senal));
|
|
14925
15281
|
if (!r2.ok) return await error2(`el servidor respondi\xF3 ${r2.status} al bajar el original`);
|
|
14926
15282
|
const datos = Buffer.from(await r2.arrayBuffer());
|
|
14927
15283
|
if (datos.byteLength === 0) return await error2("el original est\xE1 vac\xEDo");
|
|
14928
15284
|
const entrada = `original${ext}`;
|
|
14929
|
-
await
|
|
14930
|
-
await
|
|
15285
|
+
await writeFile6(join24(pedidoDir, entrada), datos);
|
|
15286
|
+
await writeFile6(join24(pedidoDir, "pedido.json"), JSON.stringify({ entrada, recortar: t.recortar }));
|
|
14931
15287
|
const res = await (d.motor ?? ejecutarMotor)(
|
|
14932
15288
|
c,
|
|
14933
15289
|
{
|
|
@@ -14948,8 +15304,8 @@ async function resolverQuitarFondo(c, d, t) {
|
|
|
14948
15304
|
if (res.stderrCola.some((l) => /invalid choice|unrecognized arguments/i.test(l))) return await error2("el motor de esta computadora es anterior y no sabe quitar fondos: actualiza claqueta-mcp y su imagen del motor");
|
|
14949
15305
|
return await error2(res.error?.mensaje ? `el motor fall\xF3: ${res.error.mensaje}` : causaLegible(res, Math.round(TIMEOUT_FONDO_MS / 6e4)));
|
|
14950
15306
|
}
|
|
14951
|
-
const j = JSON.parse(await
|
|
14952
|
-
const png = await
|
|
15307
|
+
const j = JSON.parse(await readFile9(join24(salidaDir, "fondo.json"), "utf8"));
|
|
15308
|
+
const png = await readFile9(join24(salidaDir, "fondo.png"));
|
|
14953
15309
|
const modelo = j["modelo"] ?? {};
|
|
14954
15310
|
for (const a of Array.isArray(j["avisos"]) ? j["avisos"] : []) log(`quitar fondo ${t.id}: ${String(a)}`);
|
|
14955
15311
|
await d.api.resultadoQuitarFondo(t.id, {
|
|
@@ -14965,13 +15321,13 @@ async function resolverQuitarFondo(c, d, t) {
|
|
|
14965
15321
|
} catch (e7) {
|
|
14966
15322
|
return await error2(`no se pudo quitar el fondo: ${e7.message}`);
|
|
14967
15323
|
} finally {
|
|
14968
|
-
if (!c.conservar) await
|
|
15324
|
+
if (!c.conservar) await rm5(raiz, { recursive: true, force: true });
|
|
14969
15325
|
}
|
|
14970
15326
|
}
|
|
14971
15327
|
|
|
14972
15328
|
// src/worker/storyboard.ts
|
|
14973
|
-
import { mkdir as
|
|
14974
|
-
import { join as
|
|
15329
|
+
import { mkdir as mkdir9, readFile as readFile10, rm as rm6, writeFile as writeFile7 } from "node:fs/promises";
|
|
15330
|
+
import { join as join25, relative as relative3 } from "node:path";
|
|
14975
15331
|
var TIMEOUT_STORYBOARD_MS = 10 * 6e4;
|
|
14976
15332
|
var PROGRESO_MS = 45e3;
|
|
14977
15333
|
var seguro2 = (s) => s.replace(/[^a-zA-Z0-9_.-]/g, "_");
|
|
@@ -14987,12 +15343,12 @@ function causaStoryboard(res, timeoutMin) {
|
|
|
14987
15343
|
return causaLegible(res, timeoutMin);
|
|
14988
15344
|
}
|
|
14989
15345
|
async function resultadoDeCarpeta(carpeta2, tiempoS) {
|
|
14990
|
-
const dir =
|
|
14991
|
-
const sb2 = JSON.parse(await
|
|
15346
|
+
const dir = join25(carpeta2, "storyboard");
|
|
15347
|
+
const sb2 = JSON.parse(await readFile10(join25(dir, "storyboard.json"), "utf8"));
|
|
14992
15348
|
const avisos = Array.isArray(sb2["avisos"]) ? sb2["avisos"].map(String) : [];
|
|
14993
15349
|
return {
|
|
14994
15350
|
estado: "lista",
|
|
14995
|
-
archivos: { html:
|
|
15351
|
+
archivos: { html: join25(dir, "storyboard.html"), json: join25(dir, "storyboard.json"), md: join25(dir, "STORYBOARD.md") },
|
|
14996
15352
|
datos: { duracion_total_s: sb2["duracion_total_s"] ?? null, cortinilla_s: sb2["cortinilla_s"] ?? null, cuadros: sb2["cuadros"] ?? [], escenas: Array.isArray(sb2["escenas"]) ? sb2["escenas"].length : 0 },
|
|
14997
15353
|
avisos,
|
|
14998
15354
|
motor_version: String(sb2["motor_version"] ?? ""),
|
|
@@ -15016,9 +15372,9 @@ async function resolverStoryboard(c, d, t) {
|
|
|
15016
15372
|
});
|
|
15017
15373
|
const ahora = d.ahora ?? Date.now;
|
|
15018
15374
|
const t0 = ahora();
|
|
15019
|
-
const raiz =
|
|
15020
|
-
const pedidoDir =
|
|
15021
|
-
const salidaDir =
|
|
15375
|
+
const raiz = join25(c.trabajoDir, seguro2(`storyboard-${t.id}`));
|
|
15376
|
+
const pedidoDir = join25(raiz, "pedido");
|
|
15377
|
+
const salidaDir = join25(raiz, "salida");
|
|
15022
15378
|
const error2 = async (causa) => {
|
|
15023
15379
|
log(`storyboard ${t.id} fall\xF3: ${causa}`);
|
|
15024
15380
|
await d.api.resultadoStoryboard(t.id, { estado: "error", causa }, d.senal).catch(ignorarVencido);
|
|
@@ -15046,8 +15402,8 @@ async function resolverStoryboard(c, d, t) {
|
|
|
15046
15402
|
if (e7 instanceof PedidoNoSoportado) return await error2(e7.message);
|
|
15047
15403
|
throw e7;
|
|
15048
15404
|
}
|
|
15049
|
-
await
|
|
15050
|
-
await
|
|
15405
|
+
await mkdir9(pedidoDir, { recursive: true });
|
|
15406
|
+
await mkdir9(salidaDir, { recursive: true });
|
|
15051
15407
|
try {
|
|
15052
15408
|
const locales = await descargarMedia(t.media, pedidoDir, d.descargar, d.senal, idsDeClips(pedido));
|
|
15053
15409
|
if (Object.keys(locales).length) pedido["archivos_locales"] = locales;
|
|
@@ -15055,7 +15411,7 @@ async function resolverStoryboard(c, d, t) {
|
|
|
15055
15411
|
if (e7 instanceof ErrorMedia) return await error2(`media: ${e7.message}`);
|
|
15056
15412
|
throw e7;
|
|
15057
15413
|
}
|
|
15058
|
-
await
|
|
15414
|
+
await writeFile7(join25(pedidoDir, "pedido.json"), JSON.stringify(pedido, null, 2));
|
|
15059
15415
|
const res = await correrMotor(c, d, pedidoDir, salidaDir, t.id, { formato: t.formato });
|
|
15060
15416
|
if (res.abortado) return await error2("el worker se detuvo mientras armaba el storyboard");
|
|
15061
15417
|
if (res.codigo !== 0) return await error2(causaStoryboard(res, Math.round(TIMEOUT_STORYBOARD_MS / 6e4)));
|
|
@@ -15069,7 +15425,7 @@ async function resolverStoryboard(c, d, t) {
|
|
|
15069
15425
|
return await error2(`no se pudo armar el storyboard: ${e7.message}`);
|
|
15070
15426
|
} finally {
|
|
15071
15427
|
clearInterval(latido);
|
|
15072
|
-
if (!c.conservar) await
|
|
15428
|
+
if (!c.conservar) await rm6(raiz, { recursive: true, force: true });
|
|
15073
15429
|
}
|
|
15074
15430
|
}
|
|
15075
15431
|
async function regenerarStoryboardDeVersion(c, d, v2) {
|
|
@@ -15091,7 +15447,7 @@ async function regenerarStoryboardDeVersion(c, d, v2) {
|
|
|
15091
15447
|
try {
|
|
15092
15448
|
const desdeVideo = relative3(v2.salidaDir, v2.mp4);
|
|
15093
15449
|
if (desdeVideo.startsWith("..")) return await falla(`el MP4 ${v2.mp4} no est\xE1 dentro de la carpeta de salida`);
|
|
15094
|
-
await
|
|
15450
|
+
await rm6(join25(v2.salidaDir, "storyboard"), { recursive: true, force: true });
|
|
15095
15451
|
const res = await correrMotor(c, d, v2.pedidoDir, v2.salidaDir, `${v2.videoId}-v${v2.version}`, { desdeVideo });
|
|
15096
15452
|
if (res.abortado) return await falla("el worker se detuvo");
|
|
15097
15453
|
if (res.codigo !== 0) return await falla(causaStoryboard(res, Math.round(TIMEOUT_STORYBOARD_MS / 6e4)));
|
|
@@ -15104,31 +15460,31 @@ async function regenerarStoryboardDeVersion(c, d, v2) {
|
|
|
15104
15460
|
}
|
|
15105
15461
|
|
|
15106
15462
|
// src/worker/paso-compositor.ts
|
|
15107
|
-
import { access as access2, readFile as
|
|
15108
|
-
import { join as
|
|
15463
|
+
import { access as access2, readFile as readFile11, writeFile as writeFile8 } from "node:fs/promises";
|
|
15464
|
+
import { join as join26 } from "node:path";
|
|
15109
15465
|
var ALIAS = { "plantilla-vertical-a": "base" };
|
|
15110
15466
|
var existe2 = (r2) => access2(r2).then(() => true, () => false);
|
|
15111
15467
|
async function leerJson4(ruta) {
|
|
15112
15468
|
try {
|
|
15113
|
-
const j = JSON.parse(await
|
|
15469
|
+
const j = JSON.parse(await readFile11(ruta, "utf8"));
|
|
15114
15470
|
return j && typeof j === "object" && !Array.isArray(j) ? j : null;
|
|
15115
15471
|
} catch {
|
|
15116
15472
|
return null;
|
|
15117
15473
|
}
|
|
15118
15474
|
}
|
|
15119
15475
|
async function anotarManifiesto(salidaDir, registro) {
|
|
15120
|
-
const ruta =
|
|
15476
|
+
const ruta = join26(salidaDir, "manifiesto.json");
|
|
15121
15477
|
const m = await leerJson4(ruta);
|
|
15122
15478
|
if (!m) return;
|
|
15123
15479
|
m["compositor"] = registro;
|
|
15124
15480
|
const k = m["construccion"];
|
|
15125
15481
|
if (k && typeof k === "object" && !Array.isArray(k)) k["compositor"] = registro;
|
|
15126
|
-
await
|
|
15482
|
+
await writeFile8(ruta, JSON.stringify(m, null, 2));
|
|
15127
15483
|
}
|
|
15128
15484
|
var resumen2 = (r2) => [`${r2.vueltas} ${r2.vueltas === 1 ? "vuelta" : "vueltas"}`, `${(r2.segundos / 60).toFixed(1)} min`, r2.costo_usd !== null ? `${r2.costo_usd.toFixed(2)} USD equivalentes` : null, r2.modelo].filter(Boolean).join(", ");
|
|
15129
15485
|
var conReferencias = (r2) => r2.referencias?.length ? `; referencias: ${resumenReferencias(r2.referencias)}` : "";
|
|
15130
15486
|
async function pasoCompositor(p) {
|
|
15131
|
-
const man = await leerJson4(
|
|
15487
|
+
const man = await leerJson4(join26(p.salidaDir, "manifiesto.json"));
|
|
15132
15488
|
const construccion = man?.["construccion"] ?? {};
|
|
15133
15489
|
const delPedido = String(p.pedido["estilo"] ?? p.pedido["plantilla"] ?? "base");
|
|
15134
15490
|
const nombre = typeof construccion.familia?.nombre === "string" ? construccion.familia.nombre : ALIAS[delPedido] ?? delPedido;
|
|
@@ -15142,8 +15498,8 @@ async function pasoCompositor(p) {
|
|
|
15142
15498
|
await p.bitacora(`compositor omitido: el pedido tiene ${renders.length} formatos y el compositor arma uno solo; sale la composici\xF3n de la familia`, void 0, { compositor: { omitido: true, razon: "varios formatos" } });
|
|
15143
15499
|
return { tipo: "sin_cambios" };
|
|
15144
15500
|
}
|
|
15145
|
-
const base =
|
|
15146
|
-
if (!await existe2(
|
|
15501
|
+
const base = join26(p.salidaDir, "fuentes", "composicion");
|
|
15502
|
+
if (!await existe2(join26(base, "index.html"))) {
|
|
15147
15503
|
p.log("compositor: el motor no dej\xF3 fuentes/composicion; queda la composici\xF3n del motor");
|
|
15148
15504
|
return { tipo: "sin_cambios" };
|
|
15149
15505
|
}
|
|
@@ -15198,7 +15554,7 @@ async function pasoCompositor(p) {
|
|
|
15198
15554
|
const comun = { pedidoDir: p.pedidoDir, salidaDir: p.salidaDir, nombreContenedor: `${p.nombreContenedor}-c`, senal: p.senal, onEvento: p.onEvento, subcomando: "renderizar" };
|
|
15199
15555
|
const res = await p.motor(p.c, { ...comun, composicionDir: r2.dir });
|
|
15200
15556
|
if (res.abortado) return { tipo: "renderizado", res };
|
|
15201
|
-
if ((res.codigo === 0 || res.codigo === 15) && await existe2(
|
|
15557
|
+
if ((res.codigo === 0 || res.codigo === 15) && await existe2(join26(p.salidaDir, "video.mp4"))) {
|
|
15202
15558
|
await anotarManifiesto(p.salidaDir, r2.registro);
|
|
15203
15559
|
await p.bitacora(`composici\xF3n del agente: ${resumen2(r2.registro)}${conReferencias(r2.registro)}${r2.notas.length ? `. ${r2.notas.join(" \xB7 ")}` : ""}`.slice(0, 480), void 0, { compositor: r2.registro });
|
|
15204
15560
|
return { tipo: "renderizado", res, registro: r2.registro };
|
|
@@ -15215,8 +15571,8 @@ async function pasoCompositor(p) {
|
|
|
15215
15571
|
// src/worker/guionista.ts
|
|
15216
15572
|
import { createHash as createHash7 } from "node:crypto";
|
|
15217
15573
|
import { existsSync as existsSync10, readFileSync as readFileSync14 } from "node:fs";
|
|
15218
|
-
import { mkdir as
|
|
15219
|
-
import { dirname as dirname10, join as
|
|
15574
|
+
import { mkdir as mkdir10, readFile as readFile12, rm as rm7, writeFile as writeFile9 } from "node:fs/promises";
|
|
15575
|
+
import { dirname as dirname10, join as join27 } from "node:path";
|
|
15220
15576
|
var TOPE_GUIONISTA_MS = 5 * 6e4;
|
|
15221
15577
|
var PRESUPUESTO_GUIONISTA_USD = 1;
|
|
15222
15578
|
var MAX_VUELTAS_GUIONISTA = 2;
|
|
@@ -15272,7 +15628,7 @@ function argumentosGuionista(prompt, dir, presupuestoUsd) {
|
|
|
15272
15628
|
];
|
|
15273
15629
|
}
|
|
15274
15630
|
function catalogoIconos(motorDir) {
|
|
15275
|
-
const comun =
|
|
15631
|
+
const comun = join27(motorDir, "plantillas", "_comun");
|
|
15276
15632
|
const leer2 = (ruta) => {
|
|
15277
15633
|
try {
|
|
15278
15634
|
return JSON.parse(readFileSync14(ruta, "utf8"));
|
|
@@ -15280,12 +15636,12 @@ function catalogoIconos(motorDir) {
|
|
|
15280
15636
|
return null;
|
|
15281
15637
|
}
|
|
15282
15638
|
};
|
|
15283
|
-
const lucide = leer2(
|
|
15639
|
+
const lucide = leer2(join27(comun, "lucide", "iconos.json"));
|
|
15284
15640
|
if (!lucide) return null;
|
|
15285
15641
|
const nombres = new Set(Object.keys(lucide));
|
|
15286
|
-
for (const set of ["phosphor", "tabler"]) for (const k of Object.keys(leer2(
|
|
15642
|
+
for (const set of ["phosphor", "tabler"]) for (const k of Object.keys(leer2(join27(comun, "recursos", set, "iconos.json")) ?? {})) nombres.add(`${set}:${k}`);
|
|
15287
15643
|
for (const set of ["aws", "azure", "gcp", "k8s", "ia", "marca", "emoji", "bandera", "dev", "salud", "clima", "lugar", "cripto"]) {
|
|
15288
|
-
const d = leer2(
|
|
15644
|
+
const d = leer2(join27(comun, "recursos", set, "iconos.json"));
|
|
15289
15645
|
for (const k of [...Object.keys(d?.iconos ?? {}), ...Object.keys(d?.alias ?? {})]) nombres.add(`${set}:${k}`);
|
|
15290
15646
|
}
|
|
15291
15647
|
return nombres;
|
|
@@ -15405,12 +15761,12 @@ function crearGuionista(o, d = depsReales4(o.motorDir)) {
|
|
|
15405
15761
|
const respaldo2 = (motivo, detalle, x2 = {}) => ({ tipo: "respaldo", registro: reg({ ...x2, respaldo: true, motivo: `${motivo}${detalle ? `: ${detalle}` : ""}`.slice(0, 300) }) });
|
|
15406
15762
|
const claude = d.buscarEjecutable(o.comando, o.env);
|
|
15407
15763
|
if (!claude) return respaldo2("ausente", `no encuentro \`${o.comando}\` en el PATH`);
|
|
15408
|
-
await
|
|
15409
|
-
await
|
|
15410
|
-
await
|
|
15411
|
-
await
|
|
15764
|
+
await rm7(e7.dir, { recursive: true, force: true });
|
|
15765
|
+
await mkdir10(join27(e7.dir, "_encargo"), { recursive: true });
|
|
15766
|
+
await writeFile9(join27(e7.dir, "pedido.json"), JSON.stringify(original, null, 2));
|
|
15767
|
+
await writeFile9(join27(e7.dir, "_encargo", "encargo.md"), encargoMd(e7, original["formato"]?.duracion_objetivo_s));
|
|
15412
15768
|
const iconos = d.iconos();
|
|
15413
|
-
await
|
|
15769
|
+
await writeFile9(join27(e7.dir, "_encargo", "iconos.txt"), iconos ? [...iconos].sort().join("\n") : "");
|
|
15414
15770
|
let costo = null;
|
|
15415
15771
|
let tokens = null;
|
|
15416
15772
|
let turnos = null;
|
|
@@ -15434,7 +15790,7 @@ function crearGuionista(o, d = depsReales4(o.motorDir)) {
|
|
|
15434
15790
|
if (s.codigo !== 0 || uso.error) return respaldo2("error", uso.error ?? `sali\xF3 con c\xF3digo ${s.codigo}: ${s.stderr.trim().slice(-160)}`, uso_);
|
|
15435
15791
|
let nuevo;
|
|
15436
15792
|
try {
|
|
15437
|
-
nuevo = JSON.parse(await
|
|
15793
|
+
nuevo = JSON.parse(await readFile12(join27(e7.dir, "pedido.json"), "utf8"));
|
|
15438
15794
|
} catch {
|
|
15439
15795
|
nuevo = null;
|
|
15440
15796
|
}
|
|
@@ -15466,10 +15822,10 @@ function depsReales4(motorDir) {
|
|
|
15466
15822
|
};
|
|
15467
15823
|
}
|
|
15468
15824
|
async function anotarGuionistaEnManifiesto(salidaDir, registro, guionFinal) {
|
|
15469
|
-
const ruta =
|
|
15825
|
+
const ruta = join27(salidaDir, "manifiesto.json");
|
|
15470
15826
|
let m;
|
|
15471
15827
|
try {
|
|
15472
|
-
m = JSON.parse(await
|
|
15828
|
+
m = JSON.parse(await readFile12(ruta, "utf8"));
|
|
15473
15829
|
} catch {
|
|
15474
15830
|
return;
|
|
15475
15831
|
}
|
|
@@ -15477,7 +15833,7 @@ async function anotarGuionistaEnManifiesto(salidaDir, registro, guionFinal) {
|
|
|
15477
15833
|
m["guionista"] = valor;
|
|
15478
15834
|
const k = m["construccion"];
|
|
15479
15835
|
if (k && typeof k === "object" && !Array.isArray(k)) k["guionista"] = valor;
|
|
15480
|
-
await
|
|
15836
|
+
await writeFile9(ruta, JSON.stringify(m, null, 2));
|
|
15481
15837
|
}
|
|
15482
15838
|
function mensajeGuionista(r2) {
|
|
15483
15839
|
if (r2.respaldo) return `guionista no disponible: ${r2.motivo ?? "sin motivo"}; sale el guion original`.slice(0, 480);
|
|
@@ -15486,7 +15842,7 @@ function mensajeGuionista(r2) {
|
|
|
15486
15842
|
}
|
|
15487
15843
|
|
|
15488
15844
|
// src/worker/paso-parecido.ts
|
|
15489
|
-
import { join as
|
|
15845
|
+
import { join as join28 } from "node:path";
|
|
15490
15846
|
function crearParecidoDelVideo(o) {
|
|
15491
15847
|
let ruta = null;
|
|
15492
15848
|
let metricasRef = null;
|
|
@@ -15495,7 +15851,7 @@ function crearParecidoDelVideo(o) {
|
|
|
15495
15851
|
const b = await o.bajarReferencias();
|
|
15496
15852
|
const local = b.archivos[o.referencia.asset_id];
|
|
15497
15853
|
if (!local) throw new Error(`no se pudo bajar la referencia ${o.referencia.asset_id}${b.fallos[o.referencia.asset_id] ? `: ${b.fallos[o.referencia.asset_id]}` : ""}`);
|
|
15498
|
-
return
|
|
15854
|
+
return join28(o.pedidoDir, local.ruta);
|
|
15499
15855
|
})();
|
|
15500
15856
|
const ref = { asset_id: o.referencia.asset_id, nombre: o.referencia.nombre, origen: o.referencia.origen };
|
|
15501
15857
|
return {
|
|
@@ -15506,7 +15862,7 @@ function crearParecidoDelVideo(o) {
|
|
|
15506
15862
|
return { referencia: ref, ref: refM, base, medir: (v2) => o.medidor.medir(v2) };
|
|
15507
15863
|
},
|
|
15508
15864
|
async final(mp42, registro) {
|
|
15509
|
-
const c = await o.medidor.comparar(mp42, await rutaRef(),
|
|
15865
|
+
const c = await o.medidor.comparar(mp42, await rutaRef(), join28(o.raiz, "parecido"), `${o.titulo} vs ${o.referencia.nombre ?? "referencia"}`);
|
|
15510
15866
|
const vueltas = [...registro?.parecido?.vueltas ?? []];
|
|
15511
15867
|
if (registro && !registro.respaldo && registro.vuelta_usada && !vueltas.some((v2) => v2.vuelta === registro.vuelta_usada)) {
|
|
15512
15868
|
vueltas.push({ vuelta: registro.vuelta_usada, cambios_por_minuto: c.este.cambios_por_minuto, escena_media_s: c.este.escena_media_s, lectura_ritmo: c.lectura["ritmo_de_cortes"]?.lectura ?? null });
|
|
@@ -15577,10 +15933,12 @@ async function trabajar(c, d, r2, turno) {
|
|
|
15577
15933
|
if (d.agenteB && buzon.trabajo?.estado === "aprobado") actualizarTrabajo(d.agenteB, buzon.trabajo, { estado: estado2, ...extra });
|
|
15578
15934
|
};
|
|
15579
15935
|
try {
|
|
15580
|
-
|
|
15936
|
+
let res = await trabajarVideo(c, d, r2, turno, buzon);
|
|
15937
|
+
if (res.tipo === "cancelado" && d.senal?.aborted) res = await devolverAlApagar(c, d, r2, null);
|
|
15581
15938
|
if (res.tipo === "listo") cerrar("entregado", { entrega: { estado: res.estado, advertencias: res.advertencias } });
|
|
15582
15939
|
else if (res.tipo === "fallo") cerrar("fallido", { motivo: res.causa });
|
|
15583
15940
|
else if (res.tipo === "cancelado") cerrar("cancelado", { motivo: "la nube cancel\xF3 el video o el worker se detuvo" });
|
|
15941
|
+
else if (res.tipo === "devuelto") cerrar("cancelado", { motivo: "el worker se apag\xF3: el video volvi\xF3 a la cola" });
|
|
15584
15942
|
return res;
|
|
15585
15943
|
} catch (e7) {
|
|
15586
15944
|
cerrar("fallido", { motivo: e7.message });
|
|
@@ -15594,9 +15952,9 @@ async function trabajarVideo(c, d, r2, turno, buzon) {
|
|
|
15594
15952
|
const { api } = d;
|
|
15595
15953
|
const id3 = r2.video_id;
|
|
15596
15954
|
const agenteB = d.agenteB && r2.pedido?.["previa"] !== true && agentesPresentes(d.agenteB.presenciaDir).length ? d.agenteB : null;
|
|
15597
|
-
const raiz = agenteB ?
|
|
15598
|
-
const pedidoDir =
|
|
15599
|
-
let salidaDir =
|
|
15955
|
+
const raiz = agenteB ? join29(agenteB.trabajoDir, `nube-${id3}-v${r2.version}-i${r2.intento}`) : join29(c.trabajoDir, `${id3}-v${r2.version}-i${r2.intento}`);
|
|
15956
|
+
const pedidoDir = join29(raiz, agenteB ? "entrada" : "pedido");
|
|
15957
|
+
let salidaDir = join29(raiz, "salida");
|
|
15600
15958
|
log(`reclamado ${id3} v${r2.version} (intento ${r2.intento}): ${r2.titulo}${agenteB ? " (hay un Agente B presente: compongo por pasos y lo dejo en el buz\xF3n)" : ""}`);
|
|
15601
15959
|
d.avance?.iniciar({ id: id3, titulo: r2.titulo, version: r2.version, intento: r2.intento });
|
|
15602
15960
|
let costo;
|
|
@@ -15605,11 +15963,16 @@ async function trabajarVideo(c, d, r2, turno, buzon) {
|
|
|
15605
15963
|
d.avance?.terminar(`${r2.titulo}: fall\xF3 (${causa})`, false);
|
|
15606
15964
|
log(`fall\xF3 ${id3}: ${causa}`);
|
|
15607
15965
|
let f;
|
|
15608
|
-
|
|
15609
|
-
|
|
15610
|
-
|
|
15611
|
-
|
|
15612
|
-
|
|
15966
|
+
for (let i = 1; ; i++) {
|
|
15967
|
+
try {
|
|
15968
|
+
f = await api.fallo(id3, { etapa, causa, codigo, maxReintentos: c.maxReintentos, reintentable, ...costo ?? {}, ...r_2 });
|
|
15969
|
+
break;
|
|
15970
|
+
} catch (e7) {
|
|
15971
|
+
if (e7 instanceof ErrorApi && (e7.conflicto || e7.estado === 404)) return { tipo: "cancelado", videoId: id3 };
|
|
15972
|
+
if (!(e7 instanceof ErrorApi && e7.transitorio) || i >= INTENTOS_TRANSITORIO) throw e7;
|
|
15973
|
+
log(`reportar el fallo de ${id3} fall\xF3 (intento ${i}/${INTENTOS_TRANSITORIO}): ${e7.message}`);
|
|
15974
|
+
await dormir(esperaConJitter(i, ESPERA_BASE_MS, ESPERA_TOPE_MS));
|
|
15975
|
+
}
|
|
15613
15976
|
}
|
|
15614
15977
|
return { tipo: "fallo", videoId: id3, causa, reencolado: f.reencolado };
|
|
15615
15978
|
};
|
|
@@ -15626,36 +15989,48 @@ async function trabajarVideo(c, d, r2, turno, buzon) {
|
|
|
15626
15989
|
log(`${id3}: narra con la voz clonada (Chatterbox${c.modo === "docker" ? `, imagen ${c.imagen}` : ", motor local"})`);
|
|
15627
15990
|
}
|
|
15628
15991
|
const tope = topeDelPedido(pedido, c.timeoutMs);
|
|
15992
|
+
const topeEtapaMs = c.timeoutEtapaMs ?? tope.porFormatoMs;
|
|
15993
|
+
const topes = { formatoMin: Math.round(tope.porFormatoMs / 6e4), etapaMin: Math.round(topeEtapaMs / 6e4) };
|
|
15629
15994
|
if (tope.ampliado) {
|
|
15630
15995
|
c = { ...c, timeoutMs: tope.ms };
|
|
15631
|
-
log(`${id3}: video largo (~${tope.duracionS} s, ${tope.formatos} formato${tope.formatos === 1 ? "" : "s"}): tope ${Math.round(tope.ms / 6e4)} min`);
|
|
15996
|
+
log(`${id3}: ${tope.duracionS && tope.duracionS >= 300 ? `video largo (~${tope.duracionS} s, ` : "("}${tope.formatos} formato${tope.formatos === 1 ? "" : "s"}): tope ${Math.round(tope.ms / 6e4)} min (${topes.formatoMin} por formato, ${topes.etapaMin} por etapa)`);
|
|
15632
15997
|
}
|
|
15633
|
-
await
|
|
15634
|
-
await
|
|
15998
|
+
await mkdir11(pedidoDir, { recursive: true });
|
|
15999
|
+
await mkdir11(salidaDir, { recursive: true });
|
|
15635
16000
|
const parar = new AbortController();
|
|
15636
16001
|
const alCerrar = () => parar.abort();
|
|
15637
16002
|
d.senal?.addEventListener("abort", alCerrar, { once: true });
|
|
15638
16003
|
let cancelado = false;
|
|
15639
16004
|
let ultimo = { etapa: "voz", porcentaje: 0, mensaje: "Preparando el motor" };
|
|
15640
16005
|
let publicado = { etapa: "", porcentaje: -10 };
|
|
16006
|
+
let fallosLatido = 0;
|
|
15641
16007
|
let cadena2 = Promise.resolve();
|
|
15642
16008
|
const publicar = (e7, forzar = false) => {
|
|
15643
16009
|
cadena2 = cadena2.then(async () => {
|
|
15644
16010
|
if (cancelado) return;
|
|
15645
16011
|
if (!forzar && e7.etapa === publicado.etapa && e7.porcentaje < publicado.porcentaje + 5 && e7.nivel !== "advertencia" && e7.porcentaje < 100) return;
|
|
15646
16012
|
try {
|
|
15647
|
-
await api.progreso(id3, { ...r_2, etapa: e7.etapa, porcentaje: e7.porcentaje, mensaje: e7.mensaje, ...e7.nivel === "advertencia" ? { nivel: "advertencia" } : {} });
|
|
16013
|
+
await api.progreso(id3, { ...r_2, etapa: e7.etapa, porcentaje: e7.porcentaje, mensaje: e7.mensaje, ...e7.nivel === "advertencia" ? { nivel: "advertencia" } : {}, ...e7.datos ? { datos: e7.datos } : {} });
|
|
15648
16014
|
publicado = { etapa: e7.etapa, porcentaje: e7.porcentaje };
|
|
16015
|
+
if (fallosLatido) log(`el progreso volvi\xF3 a llegar a la API tras ${fallosLatido} intento${fallosLatido === 1 ? "" : "s"} fallido${fallosLatido === 1 ? "" : "s"}`);
|
|
16016
|
+
fallosLatido = 0;
|
|
15649
16017
|
} catch (err) {
|
|
15650
16018
|
if (err instanceof ErrorApi && (err.conflicto || err.estado === 404)) {
|
|
15651
16019
|
cancelado = true;
|
|
15652
16020
|
parar.abort();
|
|
15653
|
-
} else
|
|
16021
|
+
} else {
|
|
16022
|
+
if (fallosLatido++ % 10 === 0) log(`no pude reportar progreso (el trabajo sigue; ${fallosLatido} seguido${fallosLatido === 1 ? "" : "s"}): ${err.message}`);
|
|
16023
|
+
}
|
|
15654
16024
|
}
|
|
15655
16025
|
});
|
|
15656
16026
|
};
|
|
15657
16027
|
const latido = setInterval(() => publicar(ultimo, true), d.latidoMs ?? 3e4);
|
|
15658
16028
|
publicar(ultimo, true);
|
|
16029
|
+
if (d.avisoMotor) {
|
|
16030
|
+
const aviso = d.avisoMotor;
|
|
16031
|
+
cadena2 = cadena2.then(() => api.progreso(id3, { ...r_2, etapa: "voz", porcentaje: 0, mensaje: aviso, nivel: "advertencia", datos: { motor_nuevo: true } }).catch(() => {
|
|
16032
|
+
}));
|
|
16033
|
+
}
|
|
15659
16034
|
try {
|
|
15660
16035
|
const guion = await pasoGuionista(d, r2, pedido, raiz, parar.signal, log, async (mensaje, nivel, datos) => {
|
|
15661
16036
|
d.avance?.nota(mensaje);
|
|
@@ -15674,10 +16049,18 @@ async function trabajarVideo(c, d, r2, turno, buzon) {
|
|
|
15674
16049
|
if (e7 instanceof ErrorMedia) return await fallar("media", e7.message, null, e7.reintentable);
|
|
15675
16050
|
throw e7;
|
|
15676
16051
|
}
|
|
15677
|
-
await
|
|
16052
|
+
await writeFile10(join29(pedidoDir, "pedido.json"), JSON.stringify(pedido, null, 2));
|
|
15678
16053
|
if (cancelado) return { tipo: "cancelado", videoId: id3 };
|
|
15679
16054
|
let res;
|
|
16055
|
+
const crono = new Cronometro();
|
|
15680
16056
|
const onEvento = (e7) => {
|
|
16057
|
+
crono.marcar(e7.etapa);
|
|
16058
|
+
const sp2 = segundaPasadaDe(e7);
|
|
16059
|
+
if (sp2) {
|
|
16060
|
+
const mensaje = mensajeSegundaPasada(sp2);
|
|
16061
|
+
log(`${id3}: ${mensaje}`);
|
|
16062
|
+
e7 = { ...e7, mensaje, nivel: "advertencia", datos: { ...e7.datos ?? {}, segunda_pasada: { fallidos: sp2.fallidos, ajustes: sp2.ajustes, ...sp2.valores ? { valores: sp2.valores } : {}, ...sp2.renders ? { renders: sp2.renders } : {}, motivo: sp2.motivo } } };
|
|
16063
|
+
}
|
|
15681
16064
|
ultimo = e7;
|
|
15682
16065
|
d.avance?.etapa(e7);
|
|
15683
16066
|
publicar(e7);
|
|
@@ -15686,12 +16069,12 @@ async function trabajarVideo(c, d, r2, turno, buzon) {
|
|
|
15686
16069
|
const bajarReferencias = () => bajadas ??= descargarReferenciasVideo(r2.media, pedido["referencias"], pedidoDir, d.descargar, parar.signal);
|
|
15687
16070
|
let porAgente = false;
|
|
15688
16071
|
if (agenteB) {
|
|
15689
|
-
const b = await caminoAgenteB(c, d, r2, agenteB, { raiz, rutaPedido:
|
|
16072
|
+
const b = await caminoAgenteB(c, d, r2, agenteB, { raiz, rutaPedido: join29(pedidoDir, "pedido.json"), pedido, bajarReferencias, turno, senal: parar.signal, onEvento, log, buzon });
|
|
15690
16073
|
await cadena2;
|
|
15691
16074
|
if (cancelado || b.tipo === "cancelado") return { tipo: "cancelado", videoId: id3 };
|
|
15692
16075
|
if (b.tipo === "listo") {
|
|
15693
16076
|
res = b.res;
|
|
15694
|
-
salidaDir =
|
|
16077
|
+
salidaDir = join29(raiz, "final");
|
|
15695
16078
|
porAgente = true;
|
|
15696
16079
|
}
|
|
15697
16080
|
}
|
|
@@ -15701,18 +16084,25 @@ async function trabajarVideo(c, d, r2, turno, buzon) {
|
|
|
15701
16084
|
if (cancelado) return { tipo: "cancelado", videoId: id3 };
|
|
15702
16085
|
try {
|
|
15703
16086
|
const motor2 = d.motor ?? ejecutarMotor;
|
|
15704
|
-
res = await motor2(c, { pedidoDir, salidaDir, nombreContenedor: nombreContenedor2, senal: parar.signal, onEvento, versionVideo: r2.version, ...reutilizarDir ? { reutilizarDir } : {} });
|
|
16087
|
+
res = await motor2(c, { pedidoDir, salidaDir, nombreContenedor: nombreContenedor2, senal: parar.signal, onEvento, versionVideo: r2.version, topeEtapaMs, ...reutilizarDir ? { reutilizarDir } : {} });
|
|
15705
16088
|
if (reutilizarDir && motorSinReutilizar(res) && !cancelado) {
|
|
15706
16089
|
log(`${id3}: el motor no conoce --reutilizar (anterior a CLA-203); genero la versi\xF3n completa`);
|
|
15707
|
-
res = await motor2(c, { pedidoDir, salidaDir, nombreContenedor: nombreContenedor2, senal: parar.signal, onEvento, versionVideo: r2.version });
|
|
16090
|
+
res = await motor2(c, { pedidoDir, salidaDir, nombreContenedor: nombreContenedor2, senal: parar.signal, onEvento, versionVideo: r2.version, topeEtapaMs });
|
|
15708
16091
|
}
|
|
15709
16092
|
} finally {
|
|
15710
16093
|
await cadena2;
|
|
15711
16094
|
}
|
|
16095
|
+
const tiempos = crono.resumen();
|
|
16096
|
+
if (tiempos && !cancelado) {
|
|
16097
|
+
const mensaje = mensajeTiempos(tiempos, topes);
|
|
16098
|
+
log(`${id3}: ${mensaje}`);
|
|
16099
|
+
await api.progreso(id3, { ...r_2, etapa: ultimo.etapa, porcentaje: ultimo.porcentaje, mensaje, datos: { tiempos: { ...tiempos, tope_formato_min: topes.formatoMin, tope_etapa_min: topes.etapaMin } } }).catch(() => {
|
|
16100
|
+
});
|
|
16101
|
+
}
|
|
15712
16102
|
}
|
|
15713
16103
|
if (cancelado) return { tipo: "cancelado", videoId: id3 };
|
|
15714
|
-
if (res.abortado) return await fallar(ultimo.etapa, "el worker se detuvo mientras generaba; se reintentar\xE1", null, true);
|
|
15715
|
-
const mp42 =
|
|
16104
|
+
if (res.abortado) return d.senal?.aborted ? await devolverAlApagar(c, d, r2, ultimo.etapa) : await fallar(ultimo.etapa, "el worker se detuvo mientras generaba; se reintentar\xE1", null, true);
|
|
16105
|
+
const mp42 = join29(salidaDir, "video.mp4");
|
|
15716
16106
|
const refParecido = d.parecido && pedido["previa"] !== true ? elegirReferencia(pedido, r2.media, r2.origen, d.motorDir) : null;
|
|
15717
16107
|
const parecido = refParecido && d.parecido ? crearParecidoDelVideo({ medidor: d.parecido, referencia: refParecido, pedidoDir, raiz, titulo: r2.titulo, bajarReferencias }) : null;
|
|
15718
16108
|
let registroCompositor;
|
|
@@ -15744,7 +16134,7 @@ async function trabajarVideo(c, d, r2, turno, buzon) {
|
|
|
15744
16134
|
if (cancelado || paso2.tipo === "cancelado") return { tipo: "cancelado", videoId: id3 };
|
|
15745
16135
|
if (paso2.tipo === "renderizado") res = paso2.res;
|
|
15746
16136
|
registroCompositor = paso2.registro;
|
|
15747
|
-
if (res.abortado) return await fallar(ultimo.etapa, "el worker se detuvo mientras generaba; se reintentar\xE1", null, true);
|
|
16137
|
+
if (res.abortado) return d.senal?.aborted ? await devolverAlApagar(c, d, r2, ultimo.etapa) : await fallar(ultimo.etapa, "el worker se detuvo mientras generaba; se reintentar\xE1", null, true);
|
|
15748
16138
|
}
|
|
15749
16139
|
const advertencias = [];
|
|
15750
16140
|
if (res.codigo === 0 || res.codigo === 15) {
|
|
@@ -15752,6 +16142,12 @@ async function trabajarVideo(c, d, r2, turno, buzon) {
|
|
|
15752
16142
|
if (registroGuionista) await anotarGuionistaEnManifiesto(salidaDir, registroGuionista.tipo === "omitido" ? { omitido: true, razon: registroGuionista.razon } : registroGuionista.registro, registroGuionista.tipo === "ok" ? pedido["guion"] : null);
|
|
15753
16143
|
const manifiesto = await leerManifiesto(salidaDir, log);
|
|
15754
16144
|
costo = manifiesto.costo;
|
|
16145
|
+
const correccion = resumenCorreccion(manifiesto.construccion);
|
|
16146
|
+
if (correccion) {
|
|
16147
|
+
log(`${id3}: ${correccion.mensaje}`);
|
|
16148
|
+
await api.progreso(id3, { ...r_2, etapa: "revision", porcentaje: 100, mensaje: correccion.mensaje, ...correccion.nivel ? { nivel: correccion.nivel } : {}, datos: correccion.datos }).catch(() => {
|
|
16149
|
+
});
|
|
16150
|
+
}
|
|
15755
16151
|
if (pedido["previa"] === true) {
|
|
15756
16152
|
if (!await esPrevia(salidaDir)) return await fallar("render", "el pedido es una previa pero el motor no la gener\xF3 (imagen del motor anterior a 0.9.0): actualiza la imagen del motor", null, false);
|
|
15757
16153
|
const subida = await reintentar("previa 360p", () => d.api.adjuntarPrevia(id3, r2.version, mp42, { senal: parar.signal, ...r2.reclamo ? { reclamo: r2.reclamo } : {} }), dormir, log, parar.signal);
|
|
@@ -15816,6 +16212,8 @@ async function trabajarVideo(c, d, r2, turno, buzon) {
|
|
|
15816
16212
|
}
|
|
15817
16213
|
const insumos = await insumosDeSalida(salidaDir);
|
|
15818
16214
|
const insumosFallidos = [];
|
|
16215
|
+
const cola = d.pendientes === null ? null : d.pendientes ?? (c.trabajoDir ? colaPendientesDe(c) : null);
|
|
16216
|
+
let guardados = 0;
|
|
15819
16217
|
for (const x2 of insumos) {
|
|
15820
16218
|
const sube = await reintentar(`insumo ${x2.ruta}`, () => d.api.adjuntarInsumo(id3, r2.version, x2.ruta, x2.archivo, transfP), dormir, log, parar.signal, true);
|
|
15821
16219
|
if (sube === "cancelado") return { tipo: "cancelado", videoId: id3 };
|
|
@@ -15823,10 +16221,13 @@ async function trabajarVideo(c, d, r2, turno, buzon) {
|
|
|
15823
16221
|
log(`insumos: ${sube.message}`);
|
|
15824
16222
|
break;
|
|
15825
16223
|
}
|
|
15826
|
-
if (sube instanceof Error)
|
|
16224
|
+
if (sube instanceof Error) {
|
|
16225
|
+
insumosFallidos.push(x2.ruta);
|
|
16226
|
+
if (cola) guardados += Number(await encolar(cola, { tipo: "insumo", videoId: id3, version: r2.version, destino: x2.ruta, archivo: x2.archivo, error: sube.message }, log));
|
|
16227
|
+
}
|
|
15827
16228
|
}
|
|
15828
16229
|
if (insumosFallidos.length) {
|
|
15829
|
-
const aviso = `No se pudieron subir ${insumosFallidos.length} de ${insumos.length} insumos de la versi\xF3n (${insumosFallidos.slice(0, 3).join(", ")}${insumosFallidos.length > 3 ? "\u2026" : ""}): una correcci\xF3n posterior regenerar\xE1 esas piezas`;
|
|
16230
|
+
const aviso = `No se pudieron subir ${insumosFallidos.length} de ${insumos.length} insumos de la versi\xF3n (${insumosFallidos.slice(0, 3).join(", ")}${insumosFallidos.length > 3 ? "\u2026" : ""}): ${guardados ? "quedan en la cola local de pendientes y se reintentan despu\xE9s" : "una correcci\xF3n posterior regenerar\xE1 esas piezas"}`;
|
|
15830
16231
|
advertencias.push(aviso);
|
|
15831
16232
|
await avisar(aviso, "advertencia");
|
|
15832
16233
|
}
|
|
@@ -15834,6 +16235,7 @@ async function trabajarVideo(c, d, r2, turno, buzon) {
|
|
|
15834
16235
|
const sinSubir = [];
|
|
15835
16236
|
let total2 = 0;
|
|
15836
16237
|
let rechazada = false;
|
|
16238
|
+
let enCola = 0;
|
|
15837
16239
|
for (const [clave, ruta] of Object.entries(RUTAS_EDICION)) {
|
|
15838
16240
|
const rel = manifiesto.edicion[clave];
|
|
15839
16241
|
const archivo2 = rel ? rutaDentro(salidaDir, rel) : null;
|
|
@@ -15849,9 +16251,12 @@ async function trabajarVideo(c, d, r2, turno, buzon) {
|
|
|
15849
16251
|
rechazada = true;
|
|
15850
16252
|
break;
|
|
15851
16253
|
}
|
|
15852
|
-
if (sube instanceof Error)
|
|
16254
|
+
if (sube instanceof Error) {
|
|
16255
|
+
sinSubir.push(ruta);
|
|
16256
|
+
if (cola) enCola += Number(await encolar(cola, { tipo: "insumo", videoId: id3, version: r2.version, destino: ruta, archivo: archivo2, error: sube.message }, log));
|
|
16257
|
+
}
|
|
15853
16258
|
}
|
|
15854
|
-
const aviso = rechazada ? "La API no admite todav\xEDa el paquete para editar (rechaz\xF3 las rutas edicion/*): el video se entrega sin pistas separadas ni subt\xEDtulos descargables" : sinSubir.length ? `No se pudieron subir ${sinSubir.length} de ${total2} archivos del paquete para editar (${sinSubir.slice(0, 3).join(", ")}${sinSubir.length > 3 ? "\u2026" : ""}): el video se entrega igual` : void 0;
|
|
16259
|
+
const aviso = rechazada ? "La API no admite todav\xEDa el paquete para editar (rechaz\xF3 las rutas edicion/*): el video se entrega sin pistas separadas ni subt\xEDtulos descargables" : sinSubir.length ? `No se pudieron subir ${sinSubir.length} de ${total2} archivos del paquete para editar (${sinSubir.slice(0, 3).join(", ")}${sinSubir.length > 3 ? "\u2026" : ""}): el video se entrega igual${enCola ? " y quedan en la cola local de pendientes para reintentarse despu\xE9s" : ""}` : void 0;
|
|
15855
16260
|
if (aviso) {
|
|
15856
16261
|
advertencias.push(aviso);
|
|
15857
16262
|
await avisar(aviso, "advertencia");
|
|
@@ -15905,11 +16310,15 @@ async function trabajarVideo(c, d, r2, turno, buzon) {
|
|
|
15905
16310
|
break;
|
|
15906
16311
|
}
|
|
15907
16312
|
if (sube instanceof Error) {
|
|
15908
|
-
const
|
|
16313
|
+
const guardado = cola ? await encolar(cola, { tipo: "poster", videoId: id3, version: r2.version, destino: render.etiqueta, archivo: ruta, error: sube.message }, log) : false;
|
|
16314
|
+
const aviso = `No se pudo subir la miniatura del render ${render.etiqueta}: ${sube.message}${guardado ? " (queda en la cola local de pendientes)" : ""}`;
|
|
15909
16315
|
advertencias.push(aviso);
|
|
15910
16316
|
await avisar(aviso, "advertencia");
|
|
15911
16317
|
}
|
|
15912
16318
|
}
|
|
16319
|
+
if (cola) {
|
|
16320
|
+
await reintentarPendientes(cola, d.api, { log, soloVideo: id3, senal: parar.signal, alSubir: async (p) => void await avisar(`Recuperada la subida pendiente ${p.tipo === "insumo" ? p.destino : `del p\xF3ster ${p.destino}`}`, void 0, { pendiente: { tipo: p.tipo, destino: p.destino, recuperado: true } }) });
|
|
16321
|
+
}
|
|
15913
16322
|
const principal = renders[0];
|
|
15914
16323
|
if (total > 1) await avisar(`subiendo render 1/${total} (${principal.etiqueta})`, void 0, { render: principal.etiqueta, indice: 1, total, destinos: principal.destinos });
|
|
15915
16324
|
const durPrincipal = await duracionDe(mp42);
|
|
@@ -15936,7 +16345,7 @@ async function trabajarVideo(c, d, r2, turno, buzon) {
|
|
|
15936
16345
|
await cadena2;
|
|
15937
16346
|
}
|
|
15938
16347
|
} finally {
|
|
15939
|
-
if (!c.conservar && !agenteB) await
|
|
16348
|
+
if (!c.conservar && !agenteB) await rm8(raiz, { recursive: true, force: true });
|
|
15940
16349
|
}
|
|
15941
16350
|
}
|
|
15942
16351
|
async function caminoAgenteB(c, d, r2, cfg, x2) {
|
|
@@ -15961,7 +16370,7 @@ async function caminoAgenteB(c, d, r2, cfg, x2) {
|
|
|
15961
16370
|
pedido_ruta: x2.rutaPedido,
|
|
15962
16371
|
referencias: {
|
|
15963
16372
|
pedido: Array.isArray(x2.pedido["referencias"]) ? x2.pedido["referencias"] : [],
|
|
15964
|
-
archivos: Object.fromEntries(Object.entries(refs.archivos).map(([k, v2]) => [k,
|
|
16373
|
+
archivos: Object.fromEntries(Object.entries(refs.archivos).map(([k, v2]) => [k, join29(dirname11(x2.rutaPedido), v2.ruta)])),
|
|
15965
16374
|
fallos: refs.fallos
|
|
15966
16375
|
},
|
|
15967
16376
|
carpeta: x2.raiz,
|
|
@@ -15987,7 +16396,7 @@ async function caminoAgenteB(c, d, r2, cfg, x2) {
|
|
|
15987
16396
|
}
|
|
15988
16397
|
actualizarTrabajo(cfg, trabajo, { estado: "aprobado" });
|
|
15989
16398
|
await x2.turno.tomar();
|
|
15990
|
-
const final =
|
|
16399
|
+
const final = join29(x2.raiz, "final", "video.mp4");
|
|
15991
16400
|
if (fin.respuesta.usar_final === true && await existe3(final)) {
|
|
15992
16401
|
x2.log(`buz\xF3n ${r2.video_id}: aprobado; uso el final/ que renderiz\xF3 el Agente B`);
|
|
15993
16402
|
return { tipo: "listo", res: { codigo: 0, tiempoAgotado: false, abortado: false, error: null, stderrCola: [] } };
|
|
@@ -16016,7 +16425,7 @@ async function pasoGuionista(d, r2, pedido, raiz, senal, log, bitacora2) {
|
|
|
16016
16425
|
return { tipo: "omitido", razon: omitir };
|
|
16017
16426
|
}
|
|
16018
16427
|
log(`${r2.video_id}: guionista: reescribiendo el guion con ${d.guionista.ejecutor}`);
|
|
16019
|
-
const res = await d.guionista.reescribir({ r: r2, encargo, dir:
|
|
16428
|
+
const res = await d.guionista.reescribir({ r: r2, encargo, dir: join29(raiz, "guionista"), senal });
|
|
16020
16429
|
if (res.tipo === "cancelado") return res;
|
|
16021
16430
|
const mensaje = mensajeGuionista(res.registro);
|
|
16022
16431
|
log(`${r2.video_id}: ${mensaje}`);
|
|
@@ -16045,17 +16454,44 @@ async function prepararInsumos(d, r2, raiz, senal, log, cadena2) {
|
|
|
16045
16454
|
});
|
|
16046
16455
|
return p.dir;
|
|
16047
16456
|
}
|
|
16457
|
+
async function devolverAlApagar(c, d, r2, etapa) {
|
|
16458
|
+
const log = d.log ?? (() => {
|
|
16459
|
+
});
|
|
16460
|
+
const id3 = r2.video_id;
|
|
16461
|
+
const motivo = "el worker se apag\xF3 antes de terminar; el video vuelve a la cola sin gastar un reintento";
|
|
16462
|
+
try {
|
|
16463
|
+
if (!d.api.devolver) throw new ErrorApi(501, "este cliente no sabe devolver videos");
|
|
16464
|
+
await d.api.devolver(id3, { motivo, etapa, ...r2.reclamo ? { reclamo: r2.reclamo } : {} });
|
|
16465
|
+
log(`devuelto ${id3} a la cola (apagado ordenado, sin gastar un reintento)`);
|
|
16466
|
+
d.avance?.terminar(`${r2.titulo}: vuelve a la cola (apagado)`, false);
|
|
16467
|
+
return { tipo: "devuelto", videoId: id3, gastoIntento: false };
|
|
16468
|
+
} catch (e7) {
|
|
16469
|
+
if (e7 instanceof ErrorApi && (e7.conflicto || e7.estado === 404)) return { tipo: "cancelado", videoId: id3 };
|
|
16470
|
+
if (!(e7 instanceof ErrorApi && e7.estado === 501)) {
|
|
16471
|
+
log(`no pude devolver ${id3} a la cola: ${e7.message}; el siguiente reclamo lo rescatar\xE1 como hu\xE9rfano`);
|
|
16472
|
+
return { tipo: "devuelto", videoId: id3, gastoIntento: true };
|
|
16473
|
+
}
|
|
16474
|
+
log(`${e7.message}: reporto un fallo reintentable (gasta un intento)`);
|
|
16475
|
+
try {
|
|
16476
|
+
await d.api.fallo(id3, { etapa, causa: "el worker se detuvo mientras generaba; se reintentar\xE1", codigo: null, maxReintentos: c.maxReintentos, reintentable: true, ...r2.reclamo ? { reclamo: r2.reclamo } : {} });
|
|
16477
|
+
} catch (x2) {
|
|
16478
|
+
if (x2 instanceof ErrorApi && (x2.conflicto || x2.estado === 404)) return { tipo: "cancelado", videoId: id3 };
|
|
16479
|
+
log(`no pude reportar el fallo de ${id3}: ${x2.message}`);
|
|
16480
|
+
}
|
|
16481
|
+
return { tipo: "devuelto", videoId: id3, gastoIntento: true };
|
|
16482
|
+
}
|
|
16483
|
+
}
|
|
16048
16484
|
var renders0 = (m) => m.renders[0]?.etiqueta ?? null;
|
|
16049
16485
|
async function esPrevia(salidaDir) {
|
|
16050
16486
|
try {
|
|
16051
|
-
return JSON.parse(await
|
|
16487
|
+
return JSON.parse(await readFile13(join29(salidaDir, "manifiesto.json"), "utf8")).previa === true;
|
|
16052
16488
|
} catch {
|
|
16053
16489
|
return false;
|
|
16054
16490
|
}
|
|
16055
16491
|
}
|
|
16056
16492
|
async function checksFallidos(salidaDir) {
|
|
16057
16493
|
try {
|
|
16058
|
-
const rev = JSON.parse(await
|
|
16494
|
+
const rev = JSON.parse(await readFile13(join29(salidaDir, "revision.json"), "utf8"));
|
|
16059
16495
|
const malos = (rev.checks ?? []).filter((x2) => !x2.ok && x2.nivel === "requerido").map((x2) => x2.detalle ? `${x2.id} (${x2.detalle})` : x2.id);
|
|
16060
16496
|
return malos.length ? malos.join(", ") : "sin detalle";
|
|
16061
16497
|
} catch {
|
|
@@ -16064,29 +16500,16 @@ async function checksFallidos(salidaDir) {
|
|
|
16064
16500
|
}
|
|
16065
16501
|
async function piezasDelManifiesto(salidaDir) {
|
|
16066
16502
|
try {
|
|
16067
|
-
const m = JSON.parse(await
|
|
16068
|
-
return (m.renders?.[0]?.archivos?.piezas ?? []).flatMap((p) => typeof p.ruta === "string" ? [
|
|
16503
|
+
const m = JSON.parse(await readFile13(join29(salidaDir, "manifiesto.json"), "utf8"));
|
|
16504
|
+
return (m.renders?.[0]?.archivos?.piezas ?? []).flatMap((p) => typeof p.ruta === "string" ? [join29(salidaDir, p.ruta)] : []);
|
|
16069
16505
|
} catch {
|
|
16070
16506
|
return [];
|
|
16071
16507
|
}
|
|
16072
16508
|
}
|
|
16073
16509
|
async function subirPiezas(d, id3, version2, salidaDir, dormir, log, senal, reclamo) {
|
|
16074
16510
|
for (const ruta of await piezasDelManifiesto(salidaDir)) {
|
|
16075
|
-
|
|
16076
|
-
|
|
16077
|
-
for (let i = 1; i <= 3 && !hecho; i++) {
|
|
16078
|
-
if (senal?.aborted) return "cancelado";
|
|
16079
|
-
try {
|
|
16080
|
-
await d.api.adjuntarPieza(id3, version2, ruta, senal, reclamo);
|
|
16081
|
-
hecho = true;
|
|
16082
|
-
} catch (e7) {
|
|
16083
|
-
if (e7 instanceof ErrorApi && (e7.conflicto || e7.estado === 404)) return "cancelado";
|
|
16084
|
-
ultimo = e7;
|
|
16085
|
-
log(`subir pieza fall\xF3 (intento ${i}/3): ${ultimo.message}`);
|
|
16086
|
-
if (i < 3) await dormir(1e3 * 2 ** i);
|
|
16087
|
-
}
|
|
16088
|
-
}
|
|
16089
|
-
if (!hecho) return ultimo;
|
|
16511
|
+
const sube = await reintentar(`pieza ${ruta.split("/").pop()}`, () => d.api.adjuntarPieza(id3, version2, ruta, senal, reclamo), dormir, log, senal);
|
|
16512
|
+
if (sube === "cancelado" || sube instanceof Error) return sube;
|
|
16090
16513
|
log(`pieza subida: ${ruta.split("/").pop()}`);
|
|
16091
16514
|
}
|
|
16092
16515
|
return "ok";
|
|
@@ -16101,32 +16524,62 @@ function rutaDentro(salidaDir, relativa) {
|
|
|
16101
16524
|
const ruta = resolve9(salidaDir, relativa);
|
|
16102
16525
|
return ruta.startsWith(resolve9(salidaDir) + sep5) ? ruta : null;
|
|
16103
16526
|
}
|
|
16527
|
+
var INTENTOS_TRANSITORIO = 5;
|
|
16528
|
+
var INTENTOS_OTRO = 3;
|
|
16529
|
+
var ESPERA_BASE_MS = 2e3;
|
|
16530
|
+
var ESPERA_TOPE_MS = 3e4;
|
|
16531
|
+
var intentosPara = (e7) => e7 instanceof ErrorApi && e7.transitorio ? INTENTOS_TRANSITORIO : INTENTOS_OTRO;
|
|
16104
16532
|
async function reintentar(que, accion, dormir, log, senal, sinReintentar501 = false) {
|
|
16105
|
-
let
|
|
16106
|
-
for (let i = 1; i <= 3; i++) {
|
|
16533
|
+
for (let i = 1; ; i++) {
|
|
16107
16534
|
if (senal?.aborted) return "cancelado";
|
|
16108
16535
|
try {
|
|
16109
16536
|
return await accion();
|
|
16110
16537
|
} catch (e7) {
|
|
16111
16538
|
if (e7 instanceof ErrorApi && (e7.conflicto || e7.estado === 404)) return "cancelado";
|
|
16112
16539
|
if (sinReintentar501 && e7 instanceof ErrorApi && e7.estado === 501) return e7;
|
|
16113
|
-
|
|
16114
|
-
log(`adjuntar ${que} fall\xF3 (intento ${i}
|
|
16115
|
-
if (i
|
|
16540
|
+
const max = intentosPara(e7);
|
|
16541
|
+
log(`adjuntar ${que} fall\xF3 (intento ${i}/${max}): ${e7.message}`);
|
|
16542
|
+
if (i >= max) return e7;
|
|
16543
|
+
await dormir(esperaConJitter(i, ESPERA_BASE_MS, ESPERA_TOPE_MS));
|
|
16116
16544
|
}
|
|
16117
16545
|
}
|
|
16118
|
-
return ultimo;
|
|
16119
16546
|
}
|
|
16120
16547
|
|
|
16121
16548
|
// src/worker/bucle.ts
|
|
16549
|
+
var TOPE_ESPERA_ERROR_MS = 5 * 6e4;
|
|
16550
|
+
var PENDIENTES_CADA_MS = 6e4;
|
|
16122
16551
|
async function correrBucle(c, d) {
|
|
16123
16552
|
const { log, senal } = d;
|
|
16124
16553
|
let codigo = 0;
|
|
16125
16554
|
let ocupadoAvisado = false;
|
|
16126
16555
|
let desactualizadoAvisado = false;
|
|
16127
|
-
|
|
16556
|
+
let seguidos = 0;
|
|
16557
|
+
const sigue = () => !senal.aborted && !d.apagando?.aborted;
|
|
16558
|
+
const cola = d.pendientes === null ? null : d.pendientes ?? (c.trabajoDir ? colaPendientesDe(c) : null);
|
|
16559
|
+
let proximoPendientes = 0;
|
|
16560
|
+
let proximoMotor = 0;
|
|
16561
|
+
let avisoMotor = null;
|
|
16562
|
+
while (sigue()) {
|
|
16563
|
+
let espera = c.sondeoMs;
|
|
16564
|
+
if (Date.now() >= proximoMotor) {
|
|
16565
|
+
proximoMotor = Date.now() + REVISAR_MOTOR_CADA_MS;
|
|
16566
|
+
const aviso = await revisarMotorNuevo(c, d.api);
|
|
16567
|
+
if (aviso && aviso !== avisoMotor) log(`aviso: ${aviso}`);
|
|
16568
|
+
avisoMotor = aviso;
|
|
16569
|
+
}
|
|
16570
|
+
if (cola && Date.now() >= proximoPendientes) {
|
|
16571
|
+
proximoPendientes = Date.now() + PENDIENTES_CADA_MS;
|
|
16572
|
+
const rp2 = await reintentarPendientes(cola, d.api, {
|
|
16573
|
+
log,
|
|
16574
|
+
senal,
|
|
16575
|
+
alSubir: (p) => d.api.progreso(p.video_id, { etapa: "revision", porcentaje: 100, mensaje: `Recuperada la subida pendiente ${p.tipo === "insumo" ? p.destino : `del p\xF3ster ${p.destino}`}`, datos: { pendiente: { tipo: p.tipo, destino: p.destino, recuperado: true } } })
|
|
16576
|
+
}).catch((e7) => (log(`pendientes: ${e7.message}`), null));
|
|
16577
|
+
if (rp2 && (rp2.subidos.length || rp2.descartados.length)) log(`pendientes: ${rp2.subidos.length} subidas recuperadas, ${rp2.descartados.length} descartadas, ${rp2.quedan} siguen en la cola`);
|
|
16578
|
+
}
|
|
16128
16579
|
try {
|
|
16129
|
-
const r2 = await procesarSiguiente(c, { api: d.api, log, senal, ...d.motor ? { motor: d.motor } : {}, ...d.avance ? { avance: d.avance } : {}, ...d.compositor ? { compositor: d.compositor } : {}, ...d.guionista ? { guionista: d.guionista } : {}, ...d.parecido ? { parecido: d.parecido } : {}, ...d.motorDir ? { motorDir: d.motorDir } : {}, ...d.bloqueo ? { bloqueo: d.bloqueo } : {}, ...d.agenteB ? { agenteB: d.agenteB } : {} });
|
|
16580
|
+
const r2 = await procesarSiguiente(c, { api: d.api, log, senal, ...avisoMotor ? { avisoMotor } : {}, ...d.motor ? { motor: d.motor } : {}, ...d.avance ? { avance: d.avance } : {}, ...d.compositor ? { compositor: d.compositor } : {}, ...d.guionista ? { guionista: d.guionista } : {}, ...d.parecido ? { parecido: d.parecido } : {}, ...d.motorDir ? { motorDir: d.motorDir } : {}, ...d.bloqueo ? { bloqueo: d.bloqueo } : {}, ...d.agenteB ? { agenteB: d.agenteB } : {} });
|
|
16581
|
+
if (seguidos) log(`la API volvi\xF3 a responder tras ${seguidos} ciclo${seguidos === 1 ? "" : "s"} fallido${seguidos === 1 ? "" : "s"}`);
|
|
16582
|
+
seguidos = 0;
|
|
16130
16583
|
if (r2.tipo === "ocupado") {
|
|
16131
16584
|
if (!ocupadoAvisado) log(`motor ocupado en esta m\xE1quina, espero: ${r2.motivo}`);
|
|
16132
16585
|
ocupadoAvisado = true;
|
|
@@ -16138,18 +16591,25 @@ async function correrBucle(c, d) {
|
|
|
16138
16591
|
}
|
|
16139
16592
|
if (c.unaVez) break;
|
|
16140
16593
|
} catch (e7) {
|
|
16141
|
-
|
|
16594
|
+
seguidos += 1;
|
|
16595
|
+
espera = Math.max(c.sondeoMs, esperaConJitter(seguidos, c.sondeoMs, TOPE_ESPERA_ERROR_MS, d.azar));
|
|
16596
|
+
const cuando = c.unaVez ? "" : ` (${seguidos} seguido${seguidos === 1 ? "" : "s"}; reintento en ${Math.round(espera / 1e3)} s)`;
|
|
16597
|
+
if (!(e7 instanceof ErrorApi && e7.clienteDesactualizado && desactualizadoAvisado)) log(`error del ciclo${cuando}: ${e7.message}`);
|
|
16142
16598
|
if (e7 instanceof ErrorApi && e7.clienteDesactualizado) desactualizadoAvisado = true;
|
|
16143
16599
|
if (c.unaVez) {
|
|
16144
16600
|
codigo = 1;
|
|
16145
16601
|
break;
|
|
16146
16602
|
}
|
|
16147
16603
|
}
|
|
16604
|
+
if (!sigue()) break;
|
|
16148
16605
|
await new Promise((res) => {
|
|
16149
|
-
const t = setTimeout(res,
|
|
16150
|
-
|
|
16606
|
+
const t = setTimeout(res, espera);
|
|
16607
|
+
const fin = () => (clearTimeout(t), res());
|
|
16608
|
+
senal.addEventListener("abort", fin, { once: true });
|
|
16609
|
+
d.apagando?.addEventListener("abort", fin, { once: true });
|
|
16151
16610
|
});
|
|
16152
16611
|
}
|
|
16612
|
+
if (d.apagando?.aborted && !senal.aborted) log("apagado ordenado: sin trabajo en curso, salgo");
|
|
16153
16613
|
return codigo;
|
|
16154
16614
|
}
|
|
16155
16615
|
|
|
@@ -16183,6 +16643,7 @@ function leerConfig2(env = process.env, argv = [], aviso = (m) => process.stderr
|
|
|
16183
16643
|
trabajoDir: resolve10(env["WORKER_TRABAJO_DIR"] || "./trabajo"),
|
|
16184
16644
|
sondeoMs: num4(env["WORKER_SONDEO_S"], 5, "WORKER_SONDEO_S") * 1e3,
|
|
16185
16645
|
timeoutMs: timeoutMin * 6e4,
|
|
16646
|
+
...env["WORKER_TIMEOUT_ETAPA_MIN"] ? { timeoutEtapaMs: num4(env["WORKER_TIMEOUT_ETAPA_MIN"], timeoutMin, "WORKER_TIMEOUT_ETAPA_MIN") * 6e4 } : {},
|
|
16186
16647
|
maxReintentos: Math.min(5, Math.floor(num4(env["WORKER_MAX_REINTENTOS"], 2, "WORKER_MAX_REINTENTOS"))),
|
|
16187
16648
|
huerfanosMin,
|
|
16188
16649
|
imagen: env["MOTOR_IMAGEN"] || "claqueta-motor:dev",
|
|
@@ -16230,6 +16691,13 @@ Opciones:
|
|
|
16230
16691
|
Sin esta opci\xF3n, esos videos salen con su guion original y la bit\xE1cora lo dice.
|
|
16231
16692
|
--guionista-tiempo <min> Tope del guionista por video (1 a 30; por defecto ${TOPE_GUIONISTA_MS / 6e4}).
|
|
16232
16693
|
--una-vez Procesa lo que haya en la cola y sale.
|
|
16694
|
+
--gracia <min> Apagado ordenado (SIGTERM, Ctrl+C, launchd, local_worker_detener): deja de reclamar y da este plazo
|
|
16695
|
+
al video en curso (0 a 120; por defecto 10, o WORKER_GRACIA_MIN). Si no termina, o llega otra se\xF1al,
|
|
16696
|
+
corta el motor y devuelve el video a la cola sin gastar un reintento.
|
|
16697
|
+
--tope-formato <min> Tope por formato renderizado (5 a 600; por defecto 30, o WORKER_TIMEOUT_MIN): un video de 3 formatos
|
|
16698
|
+
tiene 3 veces este tope (un video largo, m\xE1s). La bit\xE1cora anota cu\xE1nto tard\xF3 cada formato.
|
|
16699
|
+
--tope-etapa <min> Tope de cada etapa del motor (voz, render de un formato\u2026; 1 a 600; por defecto el del formato, o
|
|
16700
|
+
WORKER_TIMEOUT_ETAPA_MIN): corta un motor colgado sin esperar al tope del video.
|
|
16233
16701
|
--voz-clonada Acepta la voz clonada del usuario (Chatterbox): renders finales, pruebas del laboratorio y purgas
|
|
16234
16702
|
de su cach\xE9. En Docker usa la imagen del motor con etiqueta \xAB-clonacion\xBB (--motor-imagen-clonacion);
|
|
16235
16703
|
con --modo local instala el extra \xABclonacion\xBB y usa MPS en Apple Silicon. Los pesos (~3 GB) se bajan
|
|
@@ -16262,7 +16730,7 @@ function leerArgsWorker(argv) {
|
|
|
16262
16730
|
else if (a === "--instalar-servicio") op2.accion = "instalar-servicio";
|
|
16263
16731
|
else if (a === "--quitar-servicio") op2.accion = "quitar-servicio";
|
|
16264
16732
|
else {
|
|
16265
|
-
const m = /^--(url|agente|intervalo|motor-imagen|perfil-aws|si-falla-revision|modo|compositor|compositor-tiempo|guionista-tiempo|motor-imagen-clonacion)(?:=(.*))?$/.exec(a);
|
|
16733
|
+
const m = /^--(url|agente|intervalo|motor-imagen|perfil-aws|si-falla-revision|modo|compositor|compositor-tiempo|guionista-tiempo|motor-imagen-clonacion|tope-formato|tope-etapa|gracia)(?:=(.*))?$/.exec(a);
|
|
16266
16734
|
if (!m) return { tipo: "error", mensaje: `Opci\xF3n desconocida de worker: ${a}. Usa --help.` };
|
|
16267
16735
|
const valor = (m[2] ?? argv[++i])?.trim();
|
|
16268
16736
|
if (!valor) return { tipo: "error", mensaje: `Falta el valor de --${m[1]}.` };
|
|
@@ -16274,6 +16742,16 @@ function leerArgsWorker(argv) {
|
|
|
16274
16742
|
const n = Number(valor);
|
|
16275
16743
|
if (!Number.isFinite(n) || n < 1 || n > 60) return { tipo: "error", mensaje: "--compositor-tiempo debe ser de 1 a 60 minutos." };
|
|
16276
16744
|
op2.compositorTiempoMin = n;
|
|
16745
|
+
} else if (m[1] === "gracia") {
|
|
16746
|
+
const n = Number(valor);
|
|
16747
|
+
if (!Number.isFinite(n) || n < 0 || n > 120) return { tipo: "error", mensaje: "--gracia debe ser de 0 a 120 minutos." };
|
|
16748
|
+
op2.graciaMin = n;
|
|
16749
|
+
} else if (m[1] === "tope-formato" || m[1] === "tope-etapa") {
|
|
16750
|
+
const n = Number(valor);
|
|
16751
|
+
const minimo = m[1] === "tope-formato" ? 5 : 1;
|
|
16752
|
+
if (!Number.isFinite(n) || n < minimo || n > 600) return { tipo: "error", mensaje: `--${m[1]} debe ser de ${minimo} a 600 minutos.` };
|
|
16753
|
+
if (m[1] === "tope-formato") op2.topeFormatoMin = n;
|
|
16754
|
+
else op2.topeEtapaMin = n;
|
|
16277
16755
|
} else if (m[1] === "guionista-tiempo") {
|
|
16278
16756
|
const n = Number(valor);
|
|
16279
16757
|
if (!Number.isFinite(n) || n < 1 || n > 30) return { tipo: "error", mensaje: "--guionista-tiempo debe ser de 1 a 30 minutos." };
|
|
@@ -16325,7 +16803,10 @@ function argsParaServicio(o) {
|
|
|
16325
16803
|
...o.guionista ? ["--guionista"] : [],
|
|
16326
16804
|
...o.guionistaTiempoMin ? ["--guionista-tiempo", String(o.guionistaTiempoMin)] : [],
|
|
16327
16805
|
...o.vozClonada ? ["--voz-clonada"] : [],
|
|
16328
|
-
...o.motorImagenClonacion ? ["--motor-imagen-clonacion", o.motorImagenClonacion] : []
|
|
16806
|
+
...o.motorImagenClonacion ? ["--motor-imagen-clonacion", o.motorImagenClonacion] : [],
|
|
16807
|
+
...o.topeFormatoMin ? ["--tope-formato", String(o.topeFormatoMin)] : [],
|
|
16808
|
+
...o.topeEtapaMin ? ["--tope-etapa", String(o.topeEtapaMin)] : [],
|
|
16809
|
+
...o.graciaMin !== void 0 ? ["--gracia", String(o.graciaMin)] : []
|
|
16329
16810
|
];
|
|
16330
16811
|
}
|
|
16331
16812
|
function resolverConexion(o, env, archivo2) {
|
|
@@ -16341,8 +16822,10 @@ function configWorker(o, conexion, env, nombreEquipo, casa) {
|
|
|
16341
16822
|
CLAQUETA_API_URL: conexion.url,
|
|
16342
16823
|
WORKER_NOMBRE: o.agente ?? nombreEquipo,
|
|
16343
16824
|
MOTOR_IMAGEN: o.motorImagen ?? IMAGEN_POR_DEFECTO,
|
|
16344
|
-
WORKER_TRABAJO_DIR: env["WORKER_TRABAJO_DIR"] ||
|
|
16345
|
-
WORKER_SONDEO_S: String(o.intervaloS ?? (env["WORKER_SONDEO_S"] || 10))
|
|
16825
|
+
WORKER_TRABAJO_DIR: env["WORKER_TRABAJO_DIR"] || join30(casa, ".cache", "claqueta", "trabajo"),
|
|
16826
|
+
WORKER_SONDEO_S: String(o.intervaloS ?? (env["WORKER_SONDEO_S"] || 10)),
|
|
16827
|
+
...o.topeFormatoMin ? { WORKER_TIMEOUT_MIN: String(o.topeFormatoMin) } : {},
|
|
16828
|
+
...o.topeEtapaMin ? { WORKER_TIMEOUT_ETAPA_MIN: String(o.topeEtapaMin) } : {}
|
|
16346
16829
|
});
|
|
16347
16830
|
const imagenClonacion = o.motorImagenClonacion ?? (IMAGEN_CLONACION_POR_DEFECTO || void 0);
|
|
16348
16831
|
return { ...c, apiToken: conexion.token, unaVez: o.unaVez, siFallaRevision: o.siFallaRevision, ...o.vozClonada ? { vozClonada: true, ...imagenClonacion ? { imagenClonacion } : {} } : {} };
|
|
@@ -16354,16 +16837,16 @@ var dormirReal2 = (ms2, senal) => new Promise((resolver) => {
|
|
|
16354
16837
|
});
|
|
16355
16838
|
function configAgenteB(env, casa) {
|
|
16356
16839
|
if (env["WORKER_AGENTE_B"] === "0") return void 0;
|
|
16357
|
-
const
|
|
16840
|
+
const min2 = (k, def) => {
|
|
16358
16841
|
const n = Number(env[k]);
|
|
16359
16842
|
return (env[k] && Number.isFinite(n) && n > 0 ? n : def) * 6e4;
|
|
16360
16843
|
};
|
|
16361
16844
|
return {
|
|
16362
|
-
presenciaDir:
|
|
16363
|
-
buzonDir:
|
|
16845
|
+
presenciaDir: join30(casa, "Claqueta", "presencia"),
|
|
16846
|
+
buzonDir: join30(casa, "Claqueta", "buzon"),
|
|
16364
16847
|
trabajoDir: carpetaBasePorDefecto(env, casa),
|
|
16365
|
-
tomaMs:
|
|
16366
|
-
maxMs:
|
|
16848
|
+
tomaMs: min2("WORKER_AGENTE_B_TOMA_MIN", 5),
|
|
16849
|
+
maxMs: min2("WORKER_AGENTE_B_MAX_MIN", 45),
|
|
16367
16850
|
sondeoMs: 2e3
|
|
16368
16851
|
};
|
|
16369
16852
|
}
|
|
@@ -16385,7 +16868,7 @@ async function ejecutarWorker(o, d) {
|
|
|
16385
16868
|
return 0;
|
|
16386
16869
|
}
|
|
16387
16870
|
if (!o.sinVerificar) {
|
|
16388
|
-
const verificar = d.verificar ?? ((x2) => ejecutarDoctor({ json: false, ...x2.compositor ? { compositor: x2.compositor } : {}, ...guionistaActivado(x2, d.env) ? { guionista: true, guionistaActivado: true } : {}, ...x2.url ? { url: x2.url } : {}, ...x2.perfilAws ? { perfilAws: x2.perfilAws } : {}, ...x2.motorImagen ? { motorImagen: x2.motorImagen } : {}, modo: x2.modo }, { ...depsReales2(d.env), ejecutar, os: { plataforma: d.plataforma ?? process.platform, casa } }));
|
|
16871
|
+
const verificar = d.verificar ?? ((x2) => ejecutarDoctor({ json: false, ...x2.compositor ? { compositor: x2.compositor } : {}, ...guionistaActivado(x2, d.env) ? { guionista: true, guionistaActivado: true } : {}, ...x2.url ? { url: x2.url } : {}, ...x2.perfilAws ? { perfilAws: x2.perfilAws } : {}, ...x2.motorImagen ? { motorImagen: x2.motorImagen } : {}, ...x2.topeFormatoMin ? { topeFormatoMin: x2.topeFormatoMin } : {}, ...x2.topeEtapaMin ? { topeEtapaMin: x2.topeEtapaMin } : {}, modo: x2.modo }, { ...depsReales2(d.env), ejecutar, os: { plataforma: d.plataforma ?? process.platform, casa } }));
|
|
16389
16872
|
let informe = await verificar(o);
|
|
16390
16873
|
if (!informe.listo && d.env["CLAQUETA_SERVICIO"] === "1" && o.accion === "correr") {
|
|
16391
16874
|
const dormir = d.dormir ?? dormirReal2;
|
|
@@ -16398,8 +16881,8 @@ async function ejecutarWorker(o, d) {
|
|
|
16398
16881
|
${texto7}`);
|
|
16399
16882
|
}
|
|
16400
16883
|
const espera = ESPERAS_SERVICIO_MS[Math.min(i, ESPERAS_SERVICIO_MS.length - 1)];
|
|
16401
|
-
await dormir(espera, d.senal);
|
|
16402
|
-
if (d.senal?.aborted) return 0;
|
|
16884
|
+
await dormir(espera, d.apagando ?? d.senal);
|
|
16885
|
+
if (d.senal?.aborted || d.apagando?.aborted) return 0;
|
|
16403
16886
|
informe = await verificar(o);
|
|
16404
16887
|
}
|
|
16405
16888
|
log("verificaci\xF3n previa: ya no hay bloqueos; arranco.");
|
|
@@ -16467,10 +16950,10 @@ ${formatearInforme(informe, false)}Corrige lo marcado con \u2716 o salta la veri
|
|
|
16467
16950
|
env: d.env,
|
|
16468
16951
|
motorDir: motorEmpaquetado
|
|
16469
16952
|
});
|
|
16470
|
-
const parecido = d.crearMedidor ? d.crearMedidor(c) : c.modo === "local" ? c.comando ? crearMedidor({ modo: "local", python:
|
|
16953
|
+
const parecido = d.crearMedidor ? d.crearMedidor(c) : c.modo === "local" ? c.comando ? crearMedidor({ modo: "local", python: join30(dirname12(c.comando), "python3"), scripts: join30(motorEmpaquetado, "scripts"), ffmpeg: buscarFfmpeg((cmd) => buscarEnPath(cmd, d.env))?.ffmpeg ?? "ffmpeg", env: c.entornoMotor ?? {} }, correrReal) : void 0 : crearMedidor({ modo: "docker", imagen: c.imagen, ...typeof process.getuid === "function" ? { usuario: `${process.getuid()}:${process.getgid()}` } : {} }, correrReal);
|
|
16471
16954
|
const agenteB = configAgenteB(d.env, casa);
|
|
16472
16955
|
log(`worker ${c.nombre} \u2192 ${c.apiUrl} (${c.modo === "local" ? "motor local sin Docker" : `imagen ${c.imagen}`}, trabajo en ${c.trabajoDir}, si falla la revisi\xF3n: ${c.siFallaRevision}${c.vozClonada ? `, voz clonada${c.modo === "docker" ? ` (${c.imagenClonacion})` : ""}` : ""}${compositor ? `, compositor ${compositor.ejecutor}${o.compositorTiempoMin ? ` (tope ${o.compositorTiempoMin} min)` : ""}` : ""}${guionista ? "" : ", sin guionista"})`);
|
|
16473
|
-
const salida = await (d.bucle ?? correrBucle)(c, { api, log, senal: parar.signal, ...avance ? { avance } : {}, ...compositor ? { compositor } : {}, ...guionista ? { guionista } : {}, ...parecido ? { parecido, motorDir: motorEmpaquetado } : {}, bloqueo: rutaBloqueoMotor(casa), ...agenteB ? { agenteB } : {} });
|
|
16956
|
+
const salida = await (d.bucle ?? correrBucle)(c, { api, log, senal: parar.signal, ...avance ? { avance } : {}, ...compositor ? { compositor } : {}, ...guionista ? { guionista } : {}, ...parecido ? { parecido, motorDir: motorEmpaquetado } : {}, bloqueo: rutaBloqueoMotor(casa), ...agenteB ? { agenteB } : {}, ...d.apagando ? { apagando: d.apagando } : {} });
|
|
16474
16957
|
log("worker detenido");
|
|
16475
16958
|
return salida;
|
|
16476
16959
|
}
|
|
@@ -16543,7 +17026,7 @@ function crearContextoLocal(o, d) {
|
|
|
16543
17026
|
const simulado = d.env["CLAQUETA_MOTOR_COMANDO"]?.trim();
|
|
16544
17027
|
let listo = null;
|
|
16545
17028
|
const preparar = async () => {
|
|
16546
|
-
if (simulado) return { modo: o.modo, imagen: imagen2, cache:
|
|
17029
|
+
if (simulado) return { modo: o.modo, imagen: imagen2, cache: join31(casa, ".cache", "claqueta", "simulado"), shm: "1g", comando: simulado };
|
|
16547
17030
|
if (o.modo === "local") {
|
|
16548
17031
|
d.log(AVISO_SIN_AISLAMIENTO);
|
|
16549
17032
|
const l = await prepararMotorLocal({ ejecutar, env: d.env, plataforma: process.platform, versionNode: process.version, casa, log: d.log, motorEmpaquetado: d.motorEmpaquetado });
|
|
@@ -16608,7 +17091,7 @@ import { createInterface as createInterface4 } from "node:readline";
|
|
|
16608
17091
|
|
|
16609
17092
|
// src/local/herramientas-agente-b.ts
|
|
16610
17093
|
import { hostname as hostname7 } from "node:os";
|
|
16611
|
-
import { join as
|
|
17094
|
+
import { join as join32 } from "node:path";
|
|
16612
17095
|
var esObjeto3 = (v2) => typeof v2 === "object" && v2 !== null && !Array.isArray(v2);
|
|
16613
17096
|
var MINUTOS_POR_DEFECTO = 10;
|
|
16614
17097
|
var MINUTOS_MAX = 120;
|
|
@@ -16698,7 +17181,7 @@ function resumirPedido(p) {
|
|
|
16698
17181
|
if (Array.isArray(p["media"])) r2["media"] = p["media"].length;
|
|
16699
17182
|
return r2;
|
|
16700
17183
|
}
|
|
16701
|
-
var absolutas = (carpeta2, v2) => esObjeto3(v2) ? Object.fromEntries(Object.entries(v2).map(([k, x2]) => [k, typeof x2 === "string" && !x2.startsWith("/") ?
|
|
17184
|
+
var absolutas = (carpeta2, v2) => esObjeto3(v2) ? Object.fromEntries(Object.entries(v2).map(([k, x2]) => [k, typeof x2 === "string" && !x2.startsWith("/") ? join32(carpeta2, x2) : x2])) : v2;
|
|
16702
17185
|
function motor(ctx) {
|
|
16703
17186
|
const d = duenoActivo(ctx.bloqueo, { esVivo: ctx.esVivo ?? vivoPorDefecto2 });
|
|
16704
17187
|
return d ? { libre: false, ocupado_con: d.paso, carpeta: d.carpeta, desde: d.desde, pid: d.pid } : { libre: true };
|
|
@@ -16908,7 +17391,7 @@ async function llamarHerramientaAgenteB(nombre, argumentos, ctx, l = {}) {
|
|
|
16908
17391
|
// src/local/herramientas-almacen.ts
|
|
16909
17392
|
import { existsSync as existsSync11 } from "node:fs";
|
|
16910
17393
|
import { homedir as homedir8 } from "node:os";
|
|
16911
|
-
import { join as
|
|
17394
|
+
import { join as join33 } from "node:path";
|
|
16912
17395
|
var esObjeto4 = (v2) => typeof v2 === "object" && v2 !== null && !Array.isArray(v2);
|
|
16913
17396
|
function simuladorDelEsquema() {
|
|
16914
17397
|
const de2 = (nombre) => Object.entries(core_exports).find(([k]) => k === nombre)?.[1];
|
|
@@ -17030,7 +17513,7 @@ function llamarHerramientaAlmacen(nombre, argumentos, ctx) {
|
|
|
17030
17513
|
version: video.versionActual,
|
|
17031
17514
|
existia,
|
|
17032
17515
|
avisos,
|
|
17033
|
-
almacen:
|
|
17516
|
+
almacen: join33(alm.raiz, "videos", video.id),
|
|
17034
17517
|
siguiente: existia ? "Ya exist\xEDa un video con ese solicitud_id; no se duplic\xF3." : "En la cola local: el worker local lo genera en segundo plano. Consulta con local_ver_video."
|
|
17035
17518
|
});
|
|
17036
17519
|
}
|
|
@@ -17079,7 +17562,7 @@ function llamarHerramientaAlmacen(nombre, argumentos, ctx) {
|
|
|
17079
17562
|
if (!ruta) return fallo2("Falta \xABruta\xBB (ruta absoluta del archivo).");
|
|
17080
17563
|
const etiquetas = Array.isArray(a["etiquetas"]) ? a["etiquetas"].filter((x2) => typeof x2 === "string") : void 0;
|
|
17081
17564
|
const { asset, existia } = alm.registrarAsset({
|
|
17082
|
-
ruta: ruta === "~" || ruta.startsWith("~/") ?
|
|
17565
|
+
ruta: ruta === "~" || ruta.startsWith("~/") ? join33(homedir8(), ruta.slice(1)) : ruta,
|
|
17083
17566
|
...cadena2("rol") ? { rol: cadena2("rol") } : {},
|
|
17084
17567
|
...cadena2("nombre") ? { nombre: cadena2("nombre") } : {},
|
|
17085
17568
|
...etiquetas ? { etiquetas } : {},
|
|
@@ -17091,7 +17574,7 @@ function llamarHerramientaAlmacen(nombre, argumentos, ctx) {
|
|
|
17091
17574
|
const f = {};
|
|
17092
17575
|
if (cadena2("rol")) f.rol = cadena2("rol");
|
|
17093
17576
|
if (cadena2("tipo")) f.tipo = cadena2("tipo");
|
|
17094
|
-
return texto4({ biblioteca:
|
|
17577
|
+
return texto4({ biblioteca: join33(alm.raiz, "biblioteca"), assets: alm.listarAssets(f).map((x2) => resumenAsset(alm, x2)) });
|
|
17095
17578
|
}
|
|
17096
17579
|
}
|
|
17097
17580
|
} catch (e7) {
|
|
@@ -17104,13 +17587,59 @@ function llamarHerramientaAlmacen(nombre, argumentos, ctx) {
|
|
|
17104
17587
|
// src/local/herramientas-maquina.ts
|
|
17105
17588
|
import { spawn as spawn5 } from "node:child_process";
|
|
17106
17589
|
import { closeSync as closeSync3, existsSync as existsSync12, mkdirSync as mkdirSync13, openSync as openSync3, readFileSync as readFileSync15, readSync, renameSync as renameSync6, rmSync as rmSync8, statSync as statSync9, writeFileSync as writeFileSync10 } from "node:fs";
|
|
17107
|
-
import { join as
|
|
17590
|
+
import { join as join34 } from "node:path";
|
|
17108
17591
|
|
|
17109
17592
|
// novedades-agentes.json
|
|
17110
17593
|
var novedades_agentes_default = {
|
|
17111
17594
|
componente: "cliente",
|
|
17112
17595
|
nota: "Novedades de claqueta-mcp (puente, worker y MCP local) para el agente que lo maneja (CLA-350). Una entrada por versi\xF3n publicada en npm, la m\xE1s nueva primero. Al subir la versi\xF3n de package.json agrega su entrada aqu\xED (src/novedades.test.ts lo exige) y sincroniza la API: claqueta-api `node packages/core/scripts/sincronizar-novedades.mjs`. Las l\xEDneas \xABMCP remoto\xBB son cambios de claqueta-api que llegaron con esta versi\xF3n del cliente. destacados: 1-5 frases cortas (van en las instructions); requiere: motor m\xEDnimo con el que se aprovecha.",
|
|
17113
17596
|
versiones: [
|
|
17597
|
+
{
|
|
17598
|
+
version: "0.69.1",
|
|
17599
|
+
fecha: "2026-11-29",
|
|
17600
|
+
resumen: "Motor 0.33.1: el tablero de leccion-diagrama ya no se bloquea cuando cambia una fila de contenido, y el audio del MP4 queda bajo -1 dBTP tambi\xE9n con voz sola.",
|
|
17601
|
+
destacados: [
|
|
17602
|
+
"Motor 0.33.1 (base y voz clonada) fijado por digest: CLA-398 (filas de tablero sin fundido cruzado) y CLA-399 (pasa bajos antes del AAC)."
|
|
17603
|
+
],
|
|
17604
|
+
hacer_distinto: [
|
|
17605
|
+
"Actualiza el worker (npx -y claqueta-mcp@latest worker) para renderizar con el motor 0.33.1."
|
|
17606
|
+
],
|
|
17607
|
+
campos_nuevos: [],
|
|
17608
|
+
obsoleto: [],
|
|
17609
|
+
requiere: {
|
|
17610
|
+
motor: "0.33.1"
|
|
17611
|
+
}
|
|
17612
|
+
},
|
|
17613
|
+
{
|
|
17614
|
+
version: "0.69.0",
|
|
17615
|
+
fecha: "2026-11-29",
|
|
17616
|
+
resumen: "Trae el motor 0.33.0 (tanda 3 de HyperFrames, matematica-animada, voz por idioma y prevenci\xF3n antes del render) y un worker m\xE1s confiable: tope de tiempo por formato, cortes de red sin tumbar el video, apagado ordenado y subidas que no se pierden.",
|
|
17617
|
+
destacados: [
|
|
17618
|
+
"Motor 0.33.0: subt\xEDtulos por tono, familia matematica-animada y choques/\xE1reas vac\xEDas medidos antes del render (c\xF3digo 12).",
|
|
17619
|
+
"Tope de tiempo por formato (--tope-formato / WORKER_TIMEOUT_MIN) y por etapa (--tope-etapa); un video de 3 formatos ya no se corta a los 30 min.",
|
|
17620
|
+
"Cortes de red con causa y ruta, reintentos con espera creciente y latidos que no cancelan el video por una ca\xEDda corta.",
|
|
17621
|
+
"Apagado ordenado: la primera se\xF1al deja de reclamar y da gracia al video en curso (--gracia); si no alcanza, lo devuelve a la cola sin gastar intento.",
|
|
17622
|
+
"Subidas que fallan (insumos, edicion/*, p\xF3sters) quedan en una cola local y se reintentan; la segunda pasada del motor se explica en la bit\xE1cora."
|
|
17623
|
+
],
|
|
17624
|
+
hacer_distinto: [
|
|
17625
|
+
"Actualiza el worker (npm i -g claqueta-mcp@latest) para renderizar con el motor 0.33.0; si la API anuncia un motor m\xE1s nuevo, el worker lo avisa en el log y la bit\xE1cora.",
|
|
17626
|
+
"En m\xE1quinas lentas ajusta el tope con --tope-formato o WORKER_TIMEOUT_MIN (minutos por formato) en vez de subirlo para todo el video.",
|
|
17627
|
+
"Para reiniciar el worker ya no esperes a que termine: det\xE9nlo una vez y esperar\xE1 (o devolver\xE1 el video a la cola); una segunda se\xF1al corta."
|
|
17628
|
+
],
|
|
17629
|
+
campos_nuevos: [
|
|
17630
|
+
"--tope-formato / WORKER_TIMEOUT_MIN (por formato)",
|
|
17631
|
+
"--tope-etapa / WORKER_TIMEOUT_ETAPA_MIN",
|
|
17632
|
+
"--gracia (apagado ordenado)",
|
|
17633
|
+
"cola local de subidas pendientes (.pendientes)",
|
|
17634
|
+
"datos.segunda_pasada en la bit\xE1cora"
|
|
17635
|
+
],
|
|
17636
|
+
obsoleto: [
|
|
17637
|
+
"WORKER_TIMEOUT_MIN como tope del video completo (ahora es por formato)."
|
|
17638
|
+
],
|
|
17639
|
+
requiere: {
|
|
17640
|
+
motor: "0.33.0"
|
|
17641
|
+
}
|
|
17642
|
+
},
|
|
17114
17643
|
{
|
|
17115
17644
|
version: "0.68.0",
|
|
17116
17645
|
fecha: "2026-11-27",
|
|
@@ -17235,6 +17764,52 @@ var novedades_agentes_default2 = {
|
|
|
17235
17764
|
componente: "motor",
|
|
17236
17765
|
nota: "Novedades del motor para el agente que arma pedidos o maneja el worker (CLA-350). Una entrada por versi\xF3n publicada, la m\xE1s nueva primero. Al subir VERSION (src/claqueta_motor/cli.py) y pyproject.toml, agrega su entrada aqu\xED (tests/test_novedades_agentes.py lo exige) y sincroniza: claqueta-mcp `node scripts/sincronizar-motor.mjs` y claqueta-api `node packages/core/scripts/sincronizar-novedades.mjs`. destacados: 1-5 frases cortas (van en las instructions del MCP); hacer_distinto: qu\xE9 cambia en c\xF3mo pides; campos_nuevos: rutas del pedido, del manifiesto o de revision.json; obsoleto: lo que ya no sirve; requiere: versi\xF3n m\xEDnima de claqueta-mcp que trae este motor.",
|
|
17237
17766
|
versiones: [
|
|
17767
|
+
{
|
|
17768
|
+
version: "0.33.1",
|
|
17769
|
+
fecha: "2026-11-29",
|
|
17770
|
+
resumen: "Arreglos: en leccion-diagrama modo tablero, una fila de contenido que cambia ya no bloquea el render por texto encimado, y el pico del audio ya no se pasa de -1 dBTP al codificar con voz sola.",
|
|
17771
|
+
destacados: [
|
|
17772
|
+
"Tablero: la fila que cambia (p. ej. solo pierde la marca) releva a la vieja sin fundido cruzado; el 12-09 vuelve a pasar el chequeo previo (CLA-398).",
|
|
17773
|
+
"Audio: pasa bajos a 20 kHz antes del AAC; el MP4 queda \u2264 -1.9 dBTP con la misma sonoridad (CLA-399)."
|
|
17774
|
+
],
|
|
17775
|
+
hacer_distinto: [
|
|
17776
|
+
"Un pedido de tablero que sal\xEDa con c\xF3digo 12 por content_overlap en filas de contenido de un nodo ya no necesita cambios: vuelve a pedirlo."
|
|
17777
|
+
],
|
|
17778
|
+
campos_nuevos: [],
|
|
17779
|
+
obsoleto: [],
|
|
17780
|
+
requiere: {
|
|
17781
|
+
cliente: "0.69.1"
|
|
17782
|
+
}
|
|
17783
|
+
},
|
|
17784
|
+
{
|
|
17785
|
+
version: "0.33.0",
|
|
17786
|
+
fecha: "2026-11-28",
|
|
17787
|
+
resumen: "Tanda 3 de HyperFrames (subt\xEDtulos por tono, transiciones con acentos, h\xE9roe inclinado, audio-reactivo, p\xF3ster en el cuadro 0, banding), familia matematica-animada, voz validada por idioma y prevenci\xF3n antes del render (\xE1rboles sin aristas, choques y \xE1reas vac\xEDas).",
|
|
17788
|
+
destacados: [
|
|
17789
|
+
"Familia matematica-animada (pizarra negra): curvas, f\xF3rmulas KaTeX, convoluci\xF3n y redes neuronales; sin voz y con cortes al golpe.",
|
|
17790
|
+
"Subt\xEDtulos por tono: subtitulos.tono = tutorial | social | corporativo.",
|
|
17791
|
+
"Transiciones: primaria en \u226560 % de los cortes y acentos (whip-pan, flash, iris\u2026) solo en cambios de tema.",
|
|
17792
|
+
"H\xE9roe en todas las familias (tarjeta-navegador inclinada con URL en mono) y p\xF3ster en el cuadro 0.",
|
|
17793
|
+
"Con diagrama, choque_cajas y area_vacia se miden antes del render (c\xF3digo 12); el \xE1rbol deriva aristas de \xABpadre\xBB."
|
|
17794
|
+
],
|
|
17795
|
+
hacer_distinto: [
|
|
17796
|
+
"Si un pedido con diagrama sale con c\xF3digo 12 en el chequeo previo, corrige el pedido (menos nodos, etiquetas m\xE1s cortas, m\xE1s espacio) seg\xFAn la escena y el porcentaje que indica; ya no se renderiza para descubrirlo.",
|
|
17797
|
+
"Revisa los avisos de validar_encargo antes de pedir: marca_contraste_bajo ahora dice si el motor lo rechazar\xE1, y arbol_aristas_derivadas avisa que el motor dibujar\xE1 las l\xEDneas padre \u2192 hijo.",
|
|
17798
|
+
"La voz se valida contra las verificadas del idioma del pedido: en ingl\xE9s usa am_michael, af_heart, af_bella o am_fenrir; ya no hay aviso falso por no ser voz en espa\xF1ol.",
|
|
17799
|
+
"Para videos de matem\xE1ticas usa la familia matematica-animada; no pidas voz si no la necesitas."
|
|
17800
|
+
],
|
|
17801
|
+
campos_nuevos: [
|
|
17802
|
+
"subtitulos.tono (tutorial | social | corporativo)",
|
|
17803
|
+
"familia matematica-animada y est\xE9tica pizarra-negra",
|
|
17804
|
+
"esquemas/chequeo-previo.json: inventario de lo que bloquea con c\xF3digo 12 (umbrales y si se predice desde el pedido)",
|
|
17805
|
+
"evento de progreso con datos.segunda_pasada (chequeo, valor, formatos, ajuste, momento)",
|
|
17806
|
+
"manifiesto: construccion.revision_correccion en el esquema"
|
|
17807
|
+
],
|
|
17808
|
+
obsoleto: [],
|
|
17809
|
+
requiere: {
|
|
17810
|
+
cliente: "0.69.0"
|
|
17811
|
+
}
|
|
17812
|
+
},
|
|
17238
17813
|
{
|
|
17239
17814
|
version: "0.32.0",
|
|
17240
17815
|
fecha: "2026-11-27",
|
|
@@ -17414,7 +17989,7 @@ function novedadesParaVersion(desde) {
|
|
|
17414
17989
|
|
|
17415
17990
|
// src/local/herramientas-maquina.ts
|
|
17416
17991
|
var esObjeto5 = (v2) => typeof v2 === "object" && v2 !== null && !Array.isArray(v2);
|
|
17417
|
-
var rutasWorkerFondo = (casa) => ({ pid:
|
|
17992
|
+
var rutasWorkerFondo = (casa) => ({ pid: join34(casa, ".cache", "claqueta", "worker.pid"), log: join34(casa, ".cache", "claqueta", "worker.log") });
|
|
17418
17993
|
var TOPE_LOG = 5 * 1024 * 1024;
|
|
17419
17994
|
var esquema3 = (props, requeridos = []) => ({ type: "object", properties: props, required: requeridos, additionalProperties: false });
|
|
17420
17995
|
var PROPS_WORKER = {
|
|
@@ -17451,9 +18026,10 @@ var HERRAMIENTAS_MAQUINA = [
|
|
|
17451
18026
|
},
|
|
17452
18027
|
{
|
|
17453
18028
|
name: "local_worker_detener",
|
|
17454
|
-
description: "CAMBIA ESTA M\xC1QUINA: detiene el worker en segundo plano que arranc\xF3 local_worker_iniciar (SIGTERM y
|
|
18029
|
+
description: "CAMBIA ESTA M\xC1QUINA: detiene el worker en segundo plano que arranc\xF3 local_worker_iniciar con un apagado ordenado (SIGTERM: deja de reclamar y le da al video en curso la gracia del worker, --gracia, 10 min por defecto; si no termina, lo devuelve a la cola sin gastar un reintento). Con `cortar`, una segunda se\xF1al corta ya el video en curso y lo devuelve a la cola; con `forzar`, SIGKILL si aun as\xED no termin\xF3 a tiempo. No toca el servicio launchd: para eso local_servicio_quitar.",
|
|
17455
18030
|
inputSchema: esquema3({
|
|
17456
18031
|
esperar_s: { type: "integer", minimum: 1, maximum: 600, description: "Segundos de espera tras SIGTERM (por defecto 30)." },
|
|
18032
|
+
cortar: { type: "boolean", description: "No esperar la gracia: segunda se\xF1al, corta el video en curso y lo devuelve a la cola sin gastar un reintento." },
|
|
17457
18033
|
forzar: { type: "boolean", description: "Si no termin\xF3 tras la espera, SIGKILL al proceso y a sus hijos." }
|
|
17458
18034
|
}),
|
|
17459
18035
|
annotations: cambia(true)
|
|
@@ -17531,10 +18107,10 @@ var bool = (a, k) => {
|
|
|
17531
18107
|
if (typeof v2 !== "boolean") throw new ErrorUso2(`\xAB${k}\xBB debe ser true o false`);
|
|
17532
18108
|
return v2;
|
|
17533
18109
|
};
|
|
17534
|
-
var ent = (a, k,
|
|
18110
|
+
var ent = (a, k, min2, max) => {
|
|
17535
18111
|
const v2 = a[k];
|
|
17536
18112
|
if (v2 === void 0 || v2 === null) return void 0;
|
|
17537
|
-
if (typeof v2 !== "number" || !Number.isInteger(v2) || v2 <
|
|
18113
|
+
if (typeof v2 !== "number" || !Number.isInteger(v2) || v2 < min2 || v2 > max) throw new ErrorUso2(`\xAB${k}\xBB debe ser un entero de ${min2} a ${max}`);
|
|
17538
18114
|
return v2;
|
|
17539
18115
|
};
|
|
17540
18116
|
function argsWorkerDesde(ctx, a, conUnaVez) {
|
|
@@ -17664,7 +18240,7 @@ async function iniciar(ctx, a) {
|
|
|
17664
18240
|
);
|
|
17665
18241
|
}
|
|
17666
18242
|
const r2 = rutasWorkerFondo(ctx.casa);
|
|
17667
|
-
mkdirSync13(
|
|
18243
|
+
mkdirSync13(join34(ctx.casa, ".cache", "claqueta"), { recursive: true });
|
|
17668
18244
|
try {
|
|
17669
18245
|
if (existsSync12(r2.log) && statSync9(r2.log).size > TOPE_LOG) renameSync6(r2.log, `${r2.log}.1`);
|
|
17670
18246
|
} catch {
|
|
@@ -17698,6 +18274,7 @@ async function iniciar(ctx, a) {
|
|
|
17698
18274
|
async function detener(ctx, a) {
|
|
17699
18275
|
const esperar2 = ent(a, "esperar_s", 1, 600) ?? 30;
|
|
17700
18276
|
const forzar = bool(a, "forzar");
|
|
18277
|
+
const cortar = bool(a, "cortar");
|
|
17701
18278
|
const info = await fondoVivo(ctx);
|
|
17702
18279
|
if (!info) {
|
|
17703
18280
|
const sv2 = await estadoServicio(ctx);
|
|
@@ -17708,6 +18285,10 @@ async function detener(ctx, a) {
|
|
|
17708
18285
|
const dormir = ctx.dormir ?? dormirReal3;
|
|
17709
18286
|
const vivo2 = ctx.pidVivo ?? pidVivoReal2;
|
|
17710
18287
|
enviar(info.pid, "SIGTERM");
|
|
18288
|
+
if (cortar) {
|
|
18289
|
+
await dormir(500);
|
|
18290
|
+
if (vivo2(info.pid)) enviar(info.pid, "SIGTERM");
|
|
18291
|
+
}
|
|
17711
18292
|
const fin = Date.now() + esperar2 * 1e3;
|
|
17712
18293
|
let sigue = vivo2(info.pid);
|
|
17713
18294
|
while (sigue && Date.now() < fin) {
|
|
@@ -17715,7 +18296,7 @@ async function detener(ctx, a) {
|
|
|
17715
18296
|
sigue = vivo2(info.pid);
|
|
17716
18297
|
}
|
|
17717
18298
|
const { pid: rutaPid, log } = rutasWorkerFondo(ctx.casa);
|
|
17718
|
-
if (sigue && !forzar) return texto5(`Mand\xE9 SIGTERM al worker (pid ${info.pid}) y tras ${esperar2} s sigue terminando
|
|
18299
|
+
if (sigue && !forzar) return texto5(`Mand\xE9 SIGTERM al worker (pid ${info.pid}) y tras ${esperar2} s sigue terminando: est\xE1 en apagado ordenado (ya no reclama; termina el video en curso dentro de su gracia o lo devuelve a la cola). Vuelve a mirar con local_worker_estado, espera m\xE1s con esperar_s, usa cortar=true para devolver ya el video a la cola, o forzar=true.`);
|
|
17719
18300
|
if (sigue) {
|
|
17720
18301
|
try {
|
|
17721
18302
|
enviar(-info.pid, "SIGKILL");
|
|
@@ -17880,22 +18461,22 @@ async function llamarHerramientaMaquina(nombre, argumentos, ctx) {
|
|
|
17880
18461
|
// src/local/skill.ts
|
|
17881
18462
|
import { cpSync as cpSync2, existsSync as existsSync13, mkdirSync as mkdirSync14, readFileSync as readFileSync16 } from "node:fs";
|
|
17882
18463
|
import { homedir as homedir9 } from "node:os";
|
|
17883
|
-
import { join as
|
|
18464
|
+
import { join as join35, resolve as resolve11 } from "node:path";
|
|
17884
18465
|
var NOMBRE_SKILL = "claqueta-motor";
|
|
17885
18466
|
var PROMPT_SKILL = "dirigir-motor";
|
|
17886
18467
|
var ARCHIVOS_SKILL = ["SKILL.md", "reglas.md", "referencia.md"];
|
|
17887
18468
|
var URI = (archivo2) => `claqueta://skill/${PROMPT_SKILL}/${archivo2}`;
|
|
17888
|
-
var destinoPorDefecto = (casa = homedir9()) =>
|
|
18469
|
+
var destinoPorDefecto = (casa = homedir9()) => join35(casa, ".claude", "skills", NOMBRE_SKILL);
|
|
17889
18470
|
function leer(dir, archivo2) {
|
|
17890
18471
|
try {
|
|
17891
|
-
return readFileSync16(
|
|
18472
|
+
return readFileSync16(join35(dir, archivo2), "utf8");
|
|
17892
18473
|
} catch {
|
|
17893
18474
|
return null;
|
|
17894
18475
|
}
|
|
17895
18476
|
}
|
|
17896
18477
|
function recursosSkill(dir) {
|
|
17897
18478
|
if (!dir) return [];
|
|
17898
|
-
return ARCHIVOS_SKILL.filter((a) => existsSync13(
|
|
18479
|
+
return ARCHIVOS_SKILL.filter((a) => existsSync13(join35(dir, a))).map((a) => ({
|
|
17899
18480
|
uri: URI(a),
|
|
17900
18481
|
name: `${PROMPT_SKILL}/${a}`,
|
|
17901
18482
|
description: a === "SKILL.md" ? "Skill \xABdirigir el motor\xBB: flujo del compositor con las herramientas local_*" : a === "reglas.md" ? "Reglas del compositor (comunes con el worker)" : "Herramientas locales, carpeta de trabajo y c\xF3mo leer el parecido",
|
|
@@ -17908,7 +18489,7 @@ function leerRecursoSkill(dir, uri) {
|
|
|
17908
18489
|
return texto7 === null ? null : { uri, mimeType: "text/markdown", text: texto7 };
|
|
17909
18490
|
}
|
|
17910
18491
|
function promptsSkill(dir) {
|
|
17911
|
-
if (!dir || !existsSync13(
|
|
18492
|
+
if (!dir || !existsSync13(join35(dir, "SKILL.md"))) return [];
|
|
17912
18493
|
return [{
|
|
17913
18494
|
name: PROMPT_SKILL,
|
|
17914
18495
|
description: "Dirige el motor local como compositor: componer \u2192 previa \u2192 fotogramas \u2192 parecido \u2192 editar (2 vueltas) \u2192 render \u2192 revisar.",
|
|
@@ -17937,11 +18518,11 @@ ${partes3.join("\n\n---\n\n")}` } }]
|
|
|
17937
18518
|
};
|
|
17938
18519
|
}
|
|
17939
18520
|
function instalarSkill(origen, destino = destinoPorDefecto()) {
|
|
17940
|
-
const faltan = ARCHIVOS_SKILL.filter((a) => !existsSync13(
|
|
18521
|
+
const faltan = ARCHIVOS_SKILL.filter((a) => !existsSync13(join35(origen, a)));
|
|
17941
18522
|
if (faltan.length) throw new Error(`el paquete no trae la skill completa en ${origen} (faltan ${faltan.join(", ")})`);
|
|
17942
18523
|
const d = resolve11(destino);
|
|
17943
18524
|
mkdirSync14(d, { recursive: true });
|
|
17944
|
-
for (const a of ARCHIVOS_SKILL) cpSync2(
|
|
18525
|
+
for (const a of ARCHIVOS_SKILL) cpSync2(join35(origen, a), join35(d, a));
|
|
17945
18526
|
return { destino: d, archivos: [...ARCHIVOS_SKILL] };
|
|
17946
18527
|
}
|
|
17947
18528
|
var AYUDA_SKILL = `claqueta-mcp skill: la skill \xABdirigir el motor\xBB (la sesi\xF3n de Claude como compositor del motor local).
|
|
@@ -18082,15 +18663,16 @@ var DEFINICION_HERRAMIENTA = {
|
|
|
18082
18663
|
inputSchema: { type: "object", properties: {}, additionalProperties: false }
|
|
18083
18664
|
};
|
|
18084
18665
|
var INSTRUCCIONES_SIN_CONFIG = "claqueta-mcp arranc\xF3 sin configuraci\xF3n (no hay URL ni token de Claqueta), as\xED que las herramientas de Claqueta no est\xE1n disponibles todav\xEDa. Si la persona pide algo de Claqueta (videos, proyectos, workspaces, media), llama primero a diagnostico_conexion y transm\xEDtele lo que diga: ah\xED est\xE1n el motivo y los pasos para arreglarlo.";
|
|
18085
|
-
var probarReal = (fetchFn = fetch, timeoutMs = 5e3) => async (endpoint, token) => {
|
|
18666
|
+
var probarReal = (fetchFn = fetch, timeoutMs = 5e3, version2 = VERSION) => async (endpoint, token) => {
|
|
18086
18667
|
try {
|
|
18087
18668
|
const r2 = await fetchFn(endpoint, {
|
|
18088
18669
|
method: "POST",
|
|
18089
|
-
headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}
|
|
18670
|
+
headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}`, [CABECERA_VERSION]: version2 },
|
|
18090
18671
|
body: JSON.stringify({ jsonrpc: "2.0", id: "diagnostico", method: "ping" }),
|
|
18091
18672
|
redirect: "manual",
|
|
18092
18673
|
signal: AbortSignal.timeout(timeoutMs)
|
|
18093
18674
|
});
|
|
18675
|
+
if (r2.status === 426) return { status: r2.status, cuerpo: await r2.text().catch(() => "") };
|
|
18094
18676
|
return { status: r2.status };
|
|
18095
18677
|
} catch (e7) {
|
|
18096
18678
|
const causa = e7.cause?.code;
|
|
@@ -18139,7 +18721,8 @@ async function textoDiagnostico(e7) {
|
|
|
18139
18721
|
else if (r2.status === 401 || r2.status === 403) {
|
|
18140
18722
|
l.push(`Prueba del token: la API rechaz\xF3 el token (HTTP ${r2.status}): fue revocado, es inv\xE1lido o se cre\xF3 para otro servidor.`);
|
|
18141
18723
|
l.push(`Renu\xE9valo con: npx ${PAQUETE} setup --herramienta ${slug} (y reconecta el MCP).`);
|
|
18142
|
-
} else if (r2.status ===
|
|
18724
|
+
} else if (r2.status === 426) l.push(`Prueba del token: ${mensajeClienteDesactualizado(leerClienteDesactualizado(r2.cuerpo ?? ""), e7.version)}`);
|
|
18725
|
+
else if (r2.status === 503) l.push("Prueba del token: el servidor respondi\xF3 503 (no disponible o sin token configurado); avisa a quien lo administra.");
|
|
18143
18726
|
else if (r2.status >= 200 && r2.status < 300) l.push(`Prueba del token: la API acept\xF3 el token (HTTP ${r2.status}).`);
|
|
18144
18727
|
else l.push(`Prueba del token: la API respondi\xF3 HTTP ${r2.status} en ${endpoint}; revisa que la URL sea la de Claqueta.`);
|
|
18145
18728
|
}
|
|
@@ -18221,7 +18804,7 @@ import { createInterface as createInterface6 } from "node:readline";
|
|
|
18221
18804
|
|
|
18222
18805
|
// src/local.ts
|
|
18223
18806
|
import { createHash as createHash8 } from "node:crypto";
|
|
18224
|
-
import { readFile as
|
|
18807
|
+
import { readFile as readFile14, stat as stat2 } from "node:fs/promises";
|
|
18225
18808
|
import { homedir as homedir10 } from "node:os";
|
|
18226
18809
|
import { basename as basename5, extname as extname5, resolve as resolve12 } from "node:path";
|
|
18227
18810
|
var LIMITE_BASE64_BYTES = 3 * 1024 * 1024;
|
|
@@ -18263,7 +18846,7 @@ async function interceptarSubirMedia(msg, deps) {
|
|
|
18263
18846
|
const ruta = resolve12(pedida === "~" ? homedir10() : pedida.startsWith("~/") ? `${homedir10()}/${pedida.slice(2)}` : pedida);
|
|
18264
18847
|
let tam;
|
|
18265
18848
|
try {
|
|
18266
|
-
const st2 = await
|
|
18849
|
+
const st2 = await stat2(ruta);
|
|
18267
18850
|
if (!st2.isFile()) return falloHerramienta(id3, `La ruta "${pedida}" no es un archivo.`);
|
|
18268
18851
|
tam = st2.size;
|
|
18269
18852
|
} catch {
|
|
@@ -18275,7 +18858,7 @@ async function interceptarSubirMedia(msg, deps) {
|
|
|
18275
18858
|
if (tam > limite) return falloGrande(id3, tam, limite);
|
|
18276
18859
|
let datos;
|
|
18277
18860
|
try {
|
|
18278
|
-
datos = await
|
|
18861
|
+
datos = await readFile14(ruta);
|
|
18279
18862
|
} catch {
|
|
18280
18863
|
return falloHerramienta(id3, `No se pudo leer el archivo local "${pedida}".`);
|
|
18281
18864
|
}
|
|
@@ -18346,19 +18929,19 @@ function falloGrande(id3, tam, limite) {
|
|
|
18346
18929
|
import { createHash as createHash9 } from "node:crypto";
|
|
18347
18930
|
import { existsSync as existsSync14, readFileSync as readFileSync17, statSync as statSync10 } from "node:fs";
|
|
18348
18931
|
import { homedir as homedir11, hostname as hostname8 } from "node:os";
|
|
18349
|
-
import { basename as basename6, isAbsolute as isAbsolute4, join as
|
|
18932
|
+
import { basename as basename6, isAbsolute as isAbsolute4, join as join36, resolve as resolve13 } from "node:path";
|
|
18350
18933
|
var esObjeto9 = (v2) => typeof v2 === "object" && v2 !== null && !Array.isArray(v2);
|
|
18351
18934
|
var LIMITE_VIDEO_LOCAL_BYTES = 1024 * 1024 * 1024;
|
|
18352
18935
|
var LIMITE_JSON = 256 * 1024;
|
|
18353
18936
|
var RE_ID4 = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
|
|
18354
18937
|
var RE_CLAVE = /^\d{1,5}x\d{1,5}$/;
|
|
18355
|
-
var carpetaTrabajoBase = (env = process.env, casa = homedir11()) => resolve13(env["CLAQUETA_TRABAJO_DIR"]?.trim() ||
|
|
18938
|
+
var carpetaTrabajoBase = (env = process.env, casa = homedir11()) => resolve13(env["CLAQUETA_TRABAJO_DIR"]?.trim() || join36(casa, "Claqueta", "trabajo"));
|
|
18356
18939
|
var ErrorCarpeta = class extends Error {
|
|
18357
18940
|
};
|
|
18358
18941
|
function resolverCarpeta2(valor, base) {
|
|
18359
|
-
const v2 = valor.trim() === "~" ? homedir11() : valor.trim().startsWith("~/") ?
|
|
18942
|
+
const v2 = valor.trim() === "~" ? homedir11() : valor.trim().startsWith("~/") ? join36(homedir11(), valor.trim().slice(2)) : valor.trim();
|
|
18360
18943
|
if (isAbsolute4(v2)) return resolve13(v2);
|
|
18361
|
-
if (RE_ID4.test(v2) && !v2.includes("..")) return
|
|
18944
|
+
if (RE_ID4.test(v2) && !v2.includes("..")) return join36(base, v2);
|
|
18362
18945
|
throw new ErrorCarpeta(`carpeta \xAB${valor}\xBB no v\xE1lida: usa el id de la carpeta de trabajo (p. ej. 20261119-1530-billar) o una ruta absoluta`);
|
|
18363
18946
|
}
|
|
18364
18947
|
function leerJson5(ruta) {
|
|
@@ -18382,7 +18965,7 @@ function archivo(ruta) {
|
|
|
18382
18965
|
function bitacoraDe(carpeta2, pasos) {
|
|
18383
18966
|
const salida = [];
|
|
18384
18967
|
try {
|
|
18385
|
-
const lineas = readFileSync17(
|
|
18968
|
+
const lineas = readFileSync17(join36(carpeta2, "bitacora.jsonl"), "utf8").split("\n").filter((l) => l.trim());
|
|
18386
18969
|
for (const l of lineas.slice(-60)) {
|
|
18387
18970
|
try {
|
|
18388
18971
|
const e7 = JSON.parse(l);
|
|
@@ -18405,11 +18988,11 @@ function bitacoraDe(carpeta2, pasos) {
|
|
|
18405
18988
|
}
|
|
18406
18989
|
function leerCarpetaLocal(carpeta2, opciones = {}) {
|
|
18407
18990
|
if (!existsSync14(carpeta2) || !statSync10(carpeta2).isDirectory()) throw new ErrorCarpeta(`no existe la carpeta ${carpeta2}`);
|
|
18408
|
-
const final =
|
|
18409
|
-
const manifiesto = leerJson5(
|
|
18991
|
+
const final = join36(carpeta2, "final");
|
|
18992
|
+
const manifiesto = leerJson5(join36(final, "manifiesto.json"));
|
|
18410
18993
|
if (!manifiesto) throw new ErrorCarpeta(`${carpeta2} no tiene un video terminado (falta final/manifiesto.json): termina con local_render`);
|
|
18411
|
-
const pasos = leerJson5(
|
|
18412
|
-
const pedido = leerJson5(
|
|
18994
|
+
const pasos = leerJson5(join36(carpeta2, "pasos.json"));
|
|
18995
|
+
const pedido = leerJson5(join36(carpeta2, "fuentes", "pedido.json")) ?? leerJson5(join36(final, "fuentes", "pedido.json"));
|
|
18413
18996
|
const rutas = {};
|
|
18414
18997
|
const revisiones = {};
|
|
18415
18998
|
const lista = Array.isArray(manifiesto["renders"]) ? manifiesto["renders"].filter(esObjeto9) : [];
|
|
@@ -18417,13 +19000,13 @@ function leerCarpetaLocal(carpeta2, opciones = {}) {
|
|
|
18417
19000
|
for (const [i, r2] of lista.entries()) {
|
|
18418
19001
|
const clave = `${numero2(r2["ancho"]) ?? ""}x${numero2(r2["alto"]) ?? ""}`;
|
|
18419
19002
|
if (!RE_CLAVE.test(clave) || renders.some((x2) => x2["clave"] === clave)) continue;
|
|
18420
|
-
const dir =
|
|
18421
|
-
const video = archivo(
|
|
19003
|
+
const dir = join36(final, "renders", clave);
|
|
19004
|
+
const video = archivo(join36(dir, "video.mp4")) ?? (i === 0 ? archivo(join36(final, "video.mp4")) : null);
|
|
18422
19005
|
if (!video) throw new ErrorCarpeta(`falta el MP4 del render ${clave} en ${dir}: vuelve a correr local_render`);
|
|
18423
|
-
const poster = archivo(
|
|
19006
|
+
const poster = archivo(join36(dir, "poster.jpg")) ?? (i === 0 ? archivo(join36(final, "poster.jpg")) : null);
|
|
18424
19007
|
rutas[`video:${clave}`] = video.ruta;
|
|
18425
19008
|
if (poster) rutas[`poster:${clave}`] = poster.ruta;
|
|
18426
|
-
const revisionJson = leerJson5(
|
|
19009
|
+
const revisionJson = leerJson5(join36(dir, "revision.json"));
|
|
18427
19010
|
if (revisionJson && Buffer.byteLength(JSON.stringify(revisionJson)) <= LIMITE_JSON) revisiones[clave] = revisionJson;
|
|
18428
19011
|
const rev = esObjeto9(r2["revision"]) ? r2["revision"] : null;
|
|
18429
19012
|
renders.push({
|
|
@@ -18438,14 +19021,14 @@ function leerCarpetaLocal(carpeta2, opciones = {}) {
|
|
|
18438
19021
|
if (!renders.length) {
|
|
18439
19022
|
const f = esObjeto9(manifiesto["formato"]) ? manifiesto["formato"] : {};
|
|
18440
19023
|
const clave = `${numero2(f["ancho"]) ?? 1080}x${numero2(f["alto"]) ?? 1920}`;
|
|
18441
|
-
const video = archivo(
|
|
19024
|
+
const video = archivo(join36(final, "video.mp4"));
|
|
18442
19025
|
if (!video) throw new ErrorCarpeta(`falta final/video.mp4 en ${carpeta2}: termina con local_render`);
|
|
18443
|
-
const poster = archivo(
|
|
19026
|
+
const poster = archivo(join36(final, "poster.jpg"));
|
|
18444
19027
|
rutas[`video:${clave}`] = video.ruta;
|
|
18445
19028
|
if (poster) rutas[`poster:${clave}`] = poster.ruta;
|
|
18446
19029
|
renders.push({ clave, video: { bytes: video.bytes, md5: video.md5 }, ...poster ? { poster: { bytes: poster.bytes, md5: poster.md5 } } : {} });
|
|
18447
19030
|
}
|
|
18448
|
-
const man = archivo(
|
|
19031
|
+
const man = archivo(join36(final, "manifiesto.json"));
|
|
18449
19032
|
rutas["manifiesto:null"] = man.ruta;
|
|
18450
19033
|
const construccion = esObjeto9(manifiesto["construccion"]) ? construccionConVersion(manifiesto["construccion"], manifiesto) : null;
|
|
18451
19034
|
const composicion = construccion && esObjeto9(construccion["composicion"]) ? construccion["composicion"] : null;
|
|
@@ -18484,18 +19067,18 @@ function leerCarpetaLocal(carpeta2, opciones = {}) {
|
|
|
18484
19067
|
var RE_VID = /^vid_[A-Za-z0-9_-]{1,40}$/;
|
|
18485
19068
|
function leerVideoDelAlmacen(raiz, vid, n, opciones = {}) {
|
|
18486
19069
|
if (!RE_VID.test(vid)) throw new ErrorCarpeta(`video local \xAB${vid}\xBB no v\xE1lido: usa el id vid_\u2026 de local_listar_videos`);
|
|
18487
|
-
const dir =
|
|
18488
|
-
const video = leerJson5(
|
|
19070
|
+
const dir = join36(raiz, "videos", vid);
|
|
19071
|
+
const video = leerJson5(join36(dir, "video.json"));
|
|
18489
19072
|
if (!video) throw new ErrorCarpeta(`no existe el video ${vid} en el almac\xE9n local ${raiz}`);
|
|
18490
19073
|
const version2 = n ?? numero2(video["versionActual"]) ?? 1;
|
|
18491
|
-
const ver = leerJson5(
|
|
19074
|
+
const ver = leerJson5(join36(dir, "versiones", String(version2), "version.json"));
|
|
18492
19075
|
const carpeta2 = esObjeto9(ver?.["archivos"]) ? texto6(ver["archivos"]["carpeta_trabajo"]) : void 0;
|
|
18493
19076
|
if (!carpeta2) throw new ErrorCarpeta(`la versi\xF3n ${version2} de ${vid} no tiene carpeta de trabajo: todav\xEDa no se genera`);
|
|
18494
19077
|
const titulo = opciones.titulo ?? texto6(video["titulo"]);
|
|
18495
19078
|
const l = leerCarpetaLocal(carpeta2, { ...titulo ? { titulo } : {}, ...opciones.maquina ? { maquina: opciones.maquina } : {} });
|
|
18496
19079
|
const bitacora2 = [];
|
|
18497
19080
|
try {
|
|
18498
|
-
for (const linea of readFileSync17(
|
|
19081
|
+
for (const linea of readFileSync17(join36(dir, "bitacora.jsonl"), "utf8").split("\n").filter((x2) => x2.trim()).slice(-60)) {
|
|
18499
19082
|
try {
|
|
18500
19083
|
const e7 = JSON.parse(linea);
|
|
18501
19084
|
const datos = esObjeto9(e7["datos"]) ? e7["datos"] : {};
|
|
@@ -18757,6 +19340,43 @@ function ejecutarPuente(o) {
|
|
|
18757
19340
|
});
|
|
18758
19341
|
}
|
|
18759
19342
|
|
|
19343
|
+
// src/worker/apagado.ts
|
|
19344
|
+
var GRACIA_POR_DEFECTO_MIN = 10;
|
|
19345
|
+
function crearApagado(o) {
|
|
19346
|
+
const apagando = new AbortController();
|
|
19347
|
+
const parar = new AbortController();
|
|
19348
|
+
let reloj;
|
|
19349
|
+
const cortar = (motivo) => {
|
|
19350
|
+
if (parar.signal.aborted) return;
|
|
19351
|
+
clearTimeout(reloj);
|
|
19352
|
+
o.log(motivo);
|
|
19353
|
+
parar.abort();
|
|
19354
|
+
};
|
|
19355
|
+
return {
|
|
19356
|
+
apagando: apagando.signal,
|
|
19357
|
+
parar: parar.signal,
|
|
19358
|
+
pedir(origen) {
|
|
19359
|
+
if (!apagando.signal.aborted) {
|
|
19360
|
+
const min2 = Math.round(o.graciaMs / 6e4 * 10) / 10;
|
|
19361
|
+
o.log(`${origen}: apagado ordenado: dejo de reclamar; si hay un video en curso tiene ${min2} min para terminar y si no, vuelve a la cola sin gastar un reintento (otra se\xF1al lo corta ya)`);
|
|
19362
|
+
apagando.abort();
|
|
19363
|
+
reloj = setTimeout(() => cortar(`se acabaron los ${min2} min de gracia: corto el trabajo en curso y lo devuelvo a la cola`), o.graciaMs);
|
|
19364
|
+
reloj.unref?.();
|
|
19365
|
+
return;
|
|
19366
|
+
}
|
|
19367
|
+
cortar(`${origen} otra vez: corto ya el trabajo en curso y lo devuelvo a la cola`);
|
|
19368
|
+
}
|
|
19369
|
+
};
|
|
19370
|
+
}
|
|
19371
|
+
function escucharSenales(a, proc = process) {
|
|
19372
|
+
for (const s of ["SIGINT", "SIGTERM"]) proc.on(s, () => a.pedir(s));
|
|
19373
|
+
}
|
|
19374
|
+
function graciaMs(env, opcionMin) {
|
|
19375
|
+
const crudo = opcionMin ?? (env["WORKER_GRACIA_MIN"]?.trim() ? Number(env["WORKER_GRACIA_MIN"]) : GRACIA_POR_DEFECTO_MIN);
|
|
19376
|
+
if (!Number.isFinite(crudo) || crudo < 0) throw new Error(`WORKER_GRACIA_MIN debe ser un n\xFAmero de minutos (0 o m\xE1s); recib\xED \xAB${env["WORKER_GRACIA_MIN"]}\xBB`);
|
|
19377
|
+
return Math.round(crudo * 6e4);
|
|
19378
|
+
}
|
|
19379
|
+
|
|
18760
19380
|
// src/cli.ts
|
|
18761
19381
|
var mayorNode = Number(/^v?(\d+)/.exec(process.version)?.[1] ?? NaN);
|
|
18762
19382
|
if (Number.isFinite(mayorNode) && mayorNode < 20 && process.argv[2] !== "doctor") {
|
|
@@ -18840,10 +19460,10 @@ if (args[0] === "worker") {
|
|
|
18840
19460
|
`);
|
|
18841
19461
|
process.exit(1);
|
|
18842
19462
|
}
|
|
18843
|
-
const parar = new AbortController();
|
|
18844
|
-
for (const s of ["SIGINT", "SIGTERM"]) process.on(s, () => (console.log(`${s}: deteniendo`), parar.abort()));
|
|
18845
19463
|
try {
|
|
18846
|
-
const
|
|
19464
|
+
const parada = crearApagado({ graciaMs: graciaMs(process.env, w2.opciones.graciaMin), log: (m) => console.log(`${(/* @__PURE__ */ new Date()).toISOString()} ${m}`) });
|
|
19465
|
+
escucharSenales(parada);
|
|
19466
|
+
const codigo = await ejecutarWorker(w2.opciones, { env: process.env, archivo: leerArchivoConfig(process.env).datos, senal: parada.parar, apagando: parada.apagando });
|
|
18847
19467
|
process.exit(codigo);
|
|
18848
19468
|
} catch (e7) {
|
|
18849
19469
|
process.stderr.write(`claqueta-mcp worker: ${enmascarar(e7.message)}
|