claqueta-mcp 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +76 -5
- package/dist/cli.js +1076 -26
- package/package.json +11 -7
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# claqueta-mcp
|
|
2
2
|
|
|
3
|
-
Puente **stdio ↔ HTTP** para el servidor MCP remoto de
|
|
3
|
+
Puente **stdio ↔ HTTP** para el servidor MCP remoto de Claqueta. Reenvía cada mensaje MCP que recibe por stdin a `POST {CLAQUETA_URL}/mcp` y devuelve la respuesta por stdout. Las herramientas viven (y se actualizan) en el servidor; este paquete solo es el cable. Así funciona en **Claude Desktop** (que solo admite comandos locales) y en **Claude Code**.
|
|
4
4
|
|
|
5
5
|
Sin base de datos ni dependencias nativas: un único archivo de Node.js.
|
|
6
6
|
|
|
@@ -9,7 +9,50 @@ Sin base de datos ni dependencias nativas: un único archivo de Node.js.
|
|
|
9
9
|
- Node.js 18 o superior.
|
|
10
10
|
- La URL de tu servidor Claqueta y un token de acceso (te lo da quien administra tu Claqueta).
|
|
11
11
|
|
|
12
|
-
##
|
|
12
|
+
## Conexión rápida: `npx claqueta-mcp setup`
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npx claqueta-mcp setup
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
1. El comando abre un servidor de retorno **solo en `127.0.0.1`** (puerto efímero) y genera un `state` aleatorio de un solo uso.
|
|
19
|
+
2. Abre tu navegador en `https://app.claqueta.me/conectar` (si no se abre solo, imprime el enlace). Ya tienes sesión de Google ahí: ves el nombre del agente, el modo y los workspaces, y pulsas **Confirmar**.
|
|
20
|
+
3. El backoffice crea el token **a tu nombre** y lo entrega una sola vez a tu terminal. No se muestra en pantalla.
|
|
21
|
+
4. El comando guarda `CLAQUETA_URL` y `CLAQUETA_TOKEN` en `~/.config/claqueta/config.json` (carpeta `0700`, archivo `0600`) y registra el MCP: si existe el CLI `claude` ejecuta `claude mcp add claqueta -- npx -y claqueta-mcp`; si no, imprime el comando listo para pegar. El comando **no lleva el token**: el puente lo lee del archivo.
|
|
22
|
+
|
|
23
|
+
Opciones: `--url <api>` (por defecto `https://api.claqueta.me`), `--modo lectura|escritura` (por defecto escritura), `--workspaces a,b` (por defecto `*`; lo confirmas en el navegador), `--agente <nombre>` (por defecto `claude-code @ <equipo>`) y `--sin-registrar` (solo guarda la configuración).
|
|
24
|
+
|
|
25
|
+
**Prioridad de configuración del puente:** argumentos `--url/--token` > variables `CLAQUETA_*` > archivo de `setup`. Con las variables definidas nada cambia respecto a antes. Para pruebas, `CLAQUETA_CONFIG_DIR` cambia la carpeta del archivo y `CLAQUETA_ADMIN_URL` el backoffice que se abre.
|
|
26
|
+
|
|
27
|
+
### Salvaguardas de `setup`
|
|
28
|
+
|
|
29
|
+
- La URL de la API debe ser **https**, salvo `localhost`/`127.0.0.1`/`[::1]`; `http://` hacia otro host se rechaza (solo para pruebas existe `CLAQUETA_ALLOW_INSECURE_API=1`). Tampoco se admiten credenciales embebidas en la URL.
|
|
30
|
+
- El retorno escucha solo en loopback, exige `Host` local (anti DNS-rebinding), limita CORS al origen del backoffice, acepta **un único** callback válido, compara el `state` en tiempo constante, rechaza cuerpos grandes y se cancela tras 5 intentos inválidos o a los **5 minutos**.
|
|
31
|
+
- Un `state` distinto, un token sin el formato `cq_…` o un origen ajeno se rechazan; nada se guarda.
|
|
32
|
+
- El navegador se abre con `execFile` (sin shell), y solo con URLs http(s).
|
|
33
|
+
- El token se enmascara (`cq_***`) en cualquier salida y nunca se imprime completo; el archivo se escribe de forma atómica con `0600`.
|
|
34
|
+
- Si el backoffice no logra entregar el token a tu terminal, lo revoca.
|
|
35
|
+
- Para dejar de usar un equipo, revoca su token en Ajustes del backoffice y borra `~/.config/claqueta/config.json`.
|
|
36
|
+
|
|
37
|
+
## Worker de la cola en otra laptop: `npx claqueta-mcp worker`
|
|
38
|
+
|
|
39
|
+
Corre el worker que genera los videos en cola (motor en Docker) sin clonar el repo. Requisitos: Node 18+, Docker Desktop abierto y, para bajar el motor, el AWS CLI con la access key de descarga. Paso a paso en [docs/worker-remoto.md](docs/worker-remoto.md).
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
npx claqueta-mcp setup --modo escritura # una vez: token de escritura en ~/.config/claqueta/config.json
|
|
43
|
+
npx claqueta-mcp worker # sondea la cola y genera
|
|
44
|
+
npx claqueta-mcp worker --instalar-servicio # macOS: arranca solo (launchd)
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Opciones: `--url`, `--agente <nombre>` (por defecto el hostname), `--intervalo <s>` (10), `--motor-imagen <imagen>` (por defecto `868827002370.dkr.ecr.us-west-1.amazonaws.com/claqueta-motor:dev`), `--una-vez` (procesa lo que haya y sale), `--sin-actualizar-motor`, `--perfil-aws <perfil>` (por defecto `claqueta-motor`), `--si-falla-revision adjuntar|rechazar`, `--instalar-servicio` y `--quitar-servicio`.
|
|
48
|
+
|
|
49
|
+
- **Configuración**: lee URL y token de escritura del archivo de `setup`; `CLAQUETA_URL` y `CLAQUETA_TOKEN` del entorno mandan sobre él. El token nunca se imprime ni va en el plist.
|
|
50
|
+
- **Motor**: comprueba que Docker responda; si la imagen no está local, o al arrancar (salvo `--sin-actualizar-motor`), hace `aws ecr get-login-password | docker login` y `docker pull` (sin shell). Si ya hay imagen local y la actualización falla, avisa y sigue con la local. Con `AWS_ACCESS_KEY_ID` en el entorno usa esas variables en vez del perfil, salvo que pases `--perfil-aws`.
|
|
51
|
+
- **Revisión automática (código 15 del motor)**: decisión de producto pendiente. Por defecto (`adjuntar`) el video se adjunta y queda en revisión con una advertencia; con `rechazar` pasa a error y se reintenta según el límite. También: `WORKER_SI_FALLA_REVISION`.
|
|
52
|
+
- **Servicio (macOS)**: `--instalar-servicio` escribe `~/Library/LaunchAgents/me.claqueta.worker.plist` (`RunAtLoad`, `KeepAlive`, logs en `~/Library/Logs/claqueta-worker.log`) y lo carga con `launchctl bootstrap`. Conserva las opciones que le pases; ejecuta `npx -y claqueta-mcp worker`, así que usa la versión publicada más reciente. `--quitar-servicio` lo descarga y borra.
|
|
53
|
+
- Otras variables del worker (`WORKER_TRABAJO_DIR`, `WORKER_TIMEOUT_MIN`, `MOTOR_CACHE`, ...): ver [docs/worker-app.md](docs/worker-app.md). La carpeta de trabajo por defecto es `~/.cache/claqueta/trabajo`.
|
|
54
|
+
|
|
55
|
+
## Configuración manual
|
|
13
56
|
|
|
14
57
|
### Claude Code
|
|
15
58
|
|
|
@@ -45,10 +88,12 @@ Reinicia Claude Desktop después de guardar.
|
|
|
45
88
|
|
|
46
89
|
| Variable | Obligatoria | Descripción |
|
|
47
90
|
| --- | --- | --- |
|
|
48
|
-
| `CLAQUETA_URL` |
|
|
49
|
-
| `CLAQUETA_TOKEN` |
|
|
91
|
+
| `CLAQUETA_URL` | sí* | URL del servidor. Vale con o sin `/mcp` final y con o sin barra final. |
|
|
92
|
+
| `CLAQUETA_TOKEN` | sí* | Token enviado como `Authorization: Bearer`. |
|
|
50
93
|
| `CLAQUETA_TIMEOUT_MS` | no | Timeout por petición en milisegundos (60000 por defecto). |
|
|
51
94
|
|
|
95
|
+
\* Si corriste `setup`, el puente las toma del archivo cuando no están definidas.
|
|
96
|
+
|
|
52
97
|
También existen `--url` y `--token`, pero **los argumentos quedan visibles en la lista de procesos** de la máquina (`ps`). Prefiere siempre las variables de entorno.
|
|
53
98
|
|
|
54
99
|
## Qué hace el puente
|
|
@@ -70,7 +115,8 @@ También existen `--url` y `--token`, pero **los argumentos quedan visibles en l
|
|
|
70
115
|
|
|
71
116
|
| Síntoma | Qué revisar |
|
|
72
117
|
| --- | --- |
|
|
73
|
-
| Sale al arrancar con `Falta CLAQUETA_URL` / `Falta CLAQUETA_TOKEN` |
|
|
118
|
+
| Sale al arrancar con `Falta CLAQUETA_URL` / `Falta CLAQUETA_TOKEN` | Corre `npx claqueta-mcp setup` o revisa el bloque `env` de tu configuración. |
|
|
119
|
+
| `setup` dice que se agotó el tiempo | Confirmaste tarde o el navegador no pudo llegar a `127.0.0.1` (algunos navegadores o extensiones bloquean llamar a `127.0.0.1` desde una página https; prueba con otro navegador o desactiva el bloqueador para `app.claqueta.me`). |
|
|
74
120
|
| Error `-32001` (HTTP 401/403) | Token incorrecto o caducado. |
|
|
75
121
|
| Error `-32003` (HTTP 503) | El servidor no tiene token configurado; avisa a su administrador. |
|
|
76
122
|
| Error `-32004` | Sin conexión o URL mal escrita. |
|
|
@@ -80,6 +126,31 @@ También existen `--url` y `--token`, pero **los argumentos quedan visibles en l
|
|
|
80
126
|
|
|
81
127
|
Los mensajes de diagnóstico aparecen en los logs MCP del cliente (stderr del proceso).
|
|
82
128
|
|
|
129
|
+
## Desarrollo
|
|
130
|
+
|
|
131
|
+
Este repo es solo el **cliente** (paquete npm `claqueta-mcp`). El backend (API, servidor MCP, almacenes) vive en otro repo; lo único que comparten es el contrato HTTP de [docs/contrato-api.md](docs/contrato-api.md). Las pruebas usan un servidor HTTP simulado (`src/test/`), no necesitan el backend ni Docker.
|
|
132
|
+
|
|
133
|
+
```bash
|
|
134
|
+
npm install
|
|
135
|
+
npm run typecheck
|
|
136
|
+
npm test
|
|
137
|
+
npm run build # dist/cli.js (esbuild, un solo archivo)
|
|
138
|
+
node dist/cli.js --help
|
|
139
|
+
npm run publicar:simulacro # = npm pack --dry-run: deben salir 4 archivos: dist/cli.js, README.md, LICENSE, package.json
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
## Publicar
|
|
143
|
+
|
|
144
|
+
Es **público e irreversible** (una versión no se puede reutilizar). Lo hace una persona con su cuenta de npm (con 2FA); nunca guardes tokens en el repo.
|
|
145
|
+
|
|
146
|
+
```bash
|
|
147
|
+
npm view claqueta-mcp version # confirma la versión publicada y sube "version" en package.json
|
|
148
|
+
npm login && npm whoami
|
|
149
|
+
npm publish # el camino normal: prepublishOnly corre typecheck + tests + build
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
> **No uses `--ignore-scripts`** (ni `npm_config_ignore_scripts=true`) al publicar o empaquetar. `dist/` está en `.gitignore` y el tarball solo lleva `dist/cli.js`: sin `prepublishOnly` (que lo compila) publicarías un paquete vacío o con un build viejo. Antes de publicar, `npm run publicar:simulacro` debe listar `dist/cli.js`.
|
|
153
|
+
|
|
83
154
|
## Licencia
|
|
84
155
|
|
|
85
156
|
MIT © Itzamnai
|
package/dist/cli.js
CHANGED
|
@@ -1,19 +1,60 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
//
|
|
4
|
-
var VERSION = true ? "0.
|
|
3
|
+
// src/config.ts
|
|
4
|
+
var VERSION = true ? "0.2.0" : "dev";
|
|
5
5
|
var AYUDA = `claqueta-mcp ${VERSION}: puente stdio hacia el servidor MCP remoto de Claqueta.
|
|
6
6
|
|
|
7
|
-
Uso:
|
|
7
|
+
Uso:
|
|
8
|
+
npx -y claqueta-mcp Arranca el puente MCP (lo lanza tu cliente MCP).
|
|
9
|
+
npx claqueta-mcp setup [opciones] Conecta este equipo: abre el navegador, creas el token ah\xED y
|
|
10
|
+
se guarda en ~/.config/claqueta/config.json (permisos 0600).
|
|
11
|
+
npx claqueta-mcp worker [opciones] Corre el worker de la cola en este equipo (Docker). Ver: worker --help.
|
|
12
|
+
npx -y claqueta-mcp [--url <url>] [--token <token>]
|
|
8
13
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
14
|
+
Opciones de setup:
|
|
15
|
+
--url <url> API de Claqueta (por defecto https://api.claqueta.me). https obligatorio salvo localhost.
|
|
16
|
+
--modo <modo> "escritura" (por defecto) o "lectura".
|
|
17
|
+
--workspaces <a,b> Workspaces sugeridos ("*" = todos, por defecto). Lo confirmas en el navegador.
|
|
18
|
+
--agente <nombre> Nombre del agente (por defecto "claude-code @ <equipo>").
|
|
19
|
+
--sin-registrar No ejecuta "claude mcp add"; solo guarda la configuraci\xF3n.
|
|
20
|
+
|
|
21
|
+
Variables de entorno (mandan sobre el archivo de configuraci\xF3n):
|
|
22
|
+
CLAQUETA_URL URL del servidor Claqueta (con o sin /mcp final).
|
|
23
|
+
CLAQUETA_TOKEN Token de acceso.
|
|
12
24
|
CLAQUETA_TIMEOUT_MS Timeout por petici\xF3n en ms (por defecto 60000).
|
|
25
|
+
CLAQUETA_CONFIG_DIR Carpeta del archivo de configuraci\xF3n (por defecto ~/.config/claqueta).
|
|
26
|
+
CLAQUETA_ADMIN_URL Backoffice que abre setup (por defecto https://app.claqueta.me).
|
|
27
|
+
CLAQUETA_ALLOW_INSECURE_API=1 Solo pruebas: permite http:// hacia hosts no locales.
|
|
13
28
|
|
|
14
|
-
Argumentos (--url, --token): quedan visibles en la lista de procesos; prefiere el entorno.
|
|
29
|
+
Argumentos (--url, --token): quedan visibles en la lista de procesos; prefiere el entorno o "setup".
|
|
15
30
|
El protocolo MCP va por stdin/stdout; los mensajes de diagn\xF3stico, por stderr.
|
|
16
31
|
`;
|
|
32
|
+
function leerArgsSetup(argv) {
|
|
33
|
+
const op = { modo: "escritura", workspaces: ["*"], registrar: true };
|
|
34
|
+
for (let i = 0; i < argv.length; i++) {
|
|
35
|
+
const a = argv[i];
|
|
36
|
+
if (a === "--help" || a === "-h") return { tipo: "ayuda" };
|
|
37
|
+
if (a === "--sin-registrar") {
|
|
38
|
+
op.registrar = false;
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
const m = /^--(url|modo|workspaces|agente)(?:=(.*))?$/.exec(a);
|
|
42
|
+
if (!m) return { tipo: "error", mensaje: `Opci\xF3n desconocida de setup: ${a}. Usa --help.` };
|
|
43
|
+
const valor = m[2] ?? argv[++i];
|
|
44
|
+
if (valor === void 0 || valor.trim() === "") return { tipo: "error", mensaje: `Falta el valor de --${m[1]}.` };
|
|
45
|
+
if (m[1] === "url") op.url = valor.trim();
|
|
46
|
+
else if (m[1] === "agente") op.agente = valor.trim();
|
|
47
|
+
else if (m[1] === "modo") {
|
|
48
|
+
if (valor !== "lectura" && valor !== "escritura") return { tipo: "error", mensaje: '--modo debe ser "lectura" o "escritura".' };
|
|
49
|
+
op.modo = valor;
|
|
50
|
+
} else {
|
|
51
|
+
const ws = [...new Set(valor.split(",").map((w) => w.trim()).filter(Boolean))];
|
|
52
|
+
if (ws.length === 0 || ws.includes("*") && ws.length > 1) return { tipo: "error", mensaje: '--workspaces: usa "*" solo o una lista de slugs.' };
|
|
53
|
+
op.workspaces = ws;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return { tipo: "setup", opciones: op };
|
|
57
|
+
}
|
|
17
58
|
function normalizarUrl(bruta) {
|
|
18
59
|
let u;
|
|
19
60
|
try {
|
|
@@ -31,9 +72,10 @@ function normalizarUrl(bruta) {
|
|
|
31
72
|
u.pathname = `${ruta}/mcp`;
|
|
32
73
|
return u.toString();
|
|
33
74
|
}
|
|
34
|
-
function leerConfig(argv, env) {
|
|
35
|
-
|
|
36
|
-
let
|
|
75
|
+
function leerConfig(argv, env, archivo = {}) {
|
|
76
|
+
if (argv[0] === "setup") return leerArgsSetup(argv.slice(1));
|
|
77
|
+
let url = env["CLAQUETA_URL"]?.trim() ? env["CLAQUETA_URL"] : archivo.url;
|
|
78
|
+
let token = env["CLAQUETA_TOKEN"]?.trim() ? env["CLAQUETA_TOKEN"] : archivo.token;
|
|
37
79
|
const timeout = env["CLAQUETA_TIMEOUT_MS"];
|
|
38
80
|
for (let i = 0; i < argv.length; i++) {
|
|
39
81
|
const a = argv[i];
|
|
@@ -47,9 +89,9 @@ function leerConfig(argv, env) {
|
|
|
47
89
|
else token = valor;
|
|
48
90
|
}
|
|
49
91
|
if (!url?.trim()) {
|
|
50
|
-
return { tipo: "error", mensaje: "Falta CLAQUETA_URL (o --url).
|
|
92
|
+
return { tipo: "error", mensaje: "Falta CLAQUETA_URL (o --url). Corre \xABnpx claqueta-mcp setup\xBB o define CLAQUETA_URL=https://tu-servidor.example.com" };
|
|
51
93
|
}
|
|
52
|
-
if (!token?.trim()) return { tipo: "error", mensaje: "Falta CLAQUETA_TOKEN (o --token).
|
|
94
|
+
if (!token?.trim()) return { tipo: "error", mensaje: "Falta CLAQUETA_TOKEN (o --token). Corre \xABnpx claqueta-mcp setup\xBB o pide el token a quien administra tu Claqueta." };
|
|
53
95
|
let timeoutMs = 6e4;
|
|
54
96
|
if (timeout !== void 0 && timeout.trim() !== "") {
|
|
55
97
|
timeoutMs = Number(timeout);
|
|
@@ -71,12 +113,53 @@ function leerConfig(argv, env) {
|
|
|
71
113
|
return { tipo: "ok", config: { endpoint, token: token.trim(), timeoutMs }, avisos };
|
|
72
114
|
}
|
|
73
115
|
|
|
74
|
-
//
|
|
116
|
+
// src/almacen-config.ts
|
|
117
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
118
|
+
import { homedir } from "node:os";
|
|
119
|
+
import { join } from "node:path";
|
|
120
|
+
function directorioConfig(env = process.env) {
|
|
121
|
+
const propio = env["CLAQUETA_CONFIG_DIR"]?.trim();
|
|
122
|
+
if (propio) return propio;
|
|
123
|
+
const xdg = env["XDG_CONFIG_HOME"]?.trim();
|
|
124
|
+
return join(xdg || join(homedir(), ".config"), "claqueta");
|
|
125
|
+
}
|
|
126
|
+
var rutaConfig = (env = process.env) => join(directorioConfig(env), "config.json");
|
|
127
|
+
function guardarConfig(datos, env = process.env) {
|
|
128
|
+
const dir = directorioConfig(env);
|
|
129
|
+
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
130
|
+
chmodSync(dir, 448);
|
|
131
|
+
const destino = rutaConfig(env);
|
|
132
|
+
const tmp = `${destino}.${process.pid}.tmp`;
|
|
133
|
+
writeFileSync(tmp, `${JSON.stringify({ CLAQUETA_URL: datos.url, CLAQUETA_TOKEN: datos.token }, null, 2)}
|
|
134
|
+
`, { mode: 384 });
|
|
135
|
+
chmodSync(tmp, 384);
|
|
136
|
+
renameSync(tmp, destino);
|
|
137
|
+
return destino;
|
|
138
|
+
}
|
|
139
|
+
function leerArchivoConfig(env = process.env) {
|
|
140
|
+
const ruta = rutaConfig(env);
|
|
141
|
+
const avisos = [];
|
|
142
|
+
if (!existsSync(ruta)) return { datos: {}, avisos };
|
|
143
|
+
try {
|
|
144
|
+
if (process.platform !== "win32" && (statSync(ruta).mode & 63) !== 0) {
|
|
145
|
+
avisos.push(`Aviso: ${ruta} es legible por otros usuarios; corrige con: chmod 600 "${ruta}"`);
|
|
146
|
+
}
|
|
147
|
+
const j = JSON.parse(readFileSync(ruta, "utf8"));
|
|
148
|
+
const url = typeof j["CLAQUETA_URL"] === "string" ? j["CLAQUETA_URL"] : void 0;
|
|
149
|
+
const token = typeof j["CLAQUETA_TOKEN"] === "string" ? j["CLAQUETA_TOKEN"] : void 0;
|
|
150
|
+
return { datos: { ...url ? { url } : {}, ...token ? { token } : {} }, avisos };
|
|
151
|
+
} catch {
|
|
152
|
+
avisos.push(`Aviso: no pude leer ${ruta} (JSON inv\xE1lido); se ignora. Corre "npx claqueta-mcp setup" para regenerarlo.`);
|
|
153
|
+
return { datos: {}, avisos };
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// src/puente.ts
|
|
75
158
|
import { createInterface } from "node:readline";
|
|
76
159
|
|
|
77
|
-
//
|
|
160
|
+
// src/local.ts
|
|
78
161
|
import { readFile, stat } from "node:fs/promises";
|
|
79
|
-
import { homedir } from "node:os";
|
|
162
|
+
import { homedir as homedir2 } from "node:os";
|
|
80
163
|
import { basename, resolve } from "node:path";
|
|
81
164
|
var LIMITE_BASE64_BYTES = 3 * 1024 * 1024;
|
|
82
165
|
var esObjeto = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
@@ -87,12 +170,12 @@ async function interceptarSubirMedia(msg) {
|
|
|
87
170
|
if (!esObjeto(msg) || msg["method"] !== "tools/call" || msg["id"] === void 0) return null;
|
|
88
171
|
const params = msg["params"];
|
|
89
172
|
if (!esObjeto(params) || params["name"] !== "subir_media") return null;
|
|
90
|
-
const
|
|
91
|
-
if (!esObjeto(
|
|
92
|
-
if (
|
|
173
|
+
const args2 = params["arguments"];
|
|
174
|
+
if (!esObjeto(args2) || typeof args2["ruta"] !== "string" || args2["ruta"].trim() === "") return null;
|
|
175
|
+
if (args2["base64"] !== void 0) return null;
|
|
93
176
|
const id = msg["id"];
|
|
94
|
-
const pedida =
|
|
95
|
-
const ruta = resolve(pedida === "~" ?
|
|
177
|
+
const pedida = args2["ruta"].trim();
|
|
178
|
+
const ruta = resolve(pedida === "~" ? homedir2() : pedida.startsWith("~/") ? `${homedir2()}/${pedida.slice(2)}` : pedida);
|
|
96
179
|
let tam;
|
|
97
180
|
try {
|
|
98
181
|
const s = await stat(ruta);
|
|
@@ -114,12 +197,12 @@ async function interceptarSubirMedia(msg) {
|
|
|
114
197
|
} catch {
|
|
115
198
|
return falloHerramienta(id, `No se pudo leer el archivo local "${pedida}".`);
|
|
116
199
|
}
|
|
117
|
-
const { ruta: _r, url: _u, ...resto } =
|
|
118
|
-
const nuevos = { ...resto, base64: datos.toString("base64"), nombre: typeof
|
|
200
|
+
const { ruta: _r, url: _u, ...resto } = args2;
|
|
201
|
+
const nuevos = { ...resto, base64: datos.toString("base64"), nombre: typeof args2["nombre"] === "string" && args2["nombre"] ? args2["nombre"] : basename(ruta) };
|
|
119
202
|
return { tipo: "reenviar", mensaje: { ...msg, params: { ...params, arguments: nuevos } } };
|
|
120
203
|
}
|
|
121
204
|
|
|
122
|
-
//
|
|
205
|
+
// src/puente.ts
|
|
123
206
|
var esObjeto2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
124
207
|
var COD = { auth: -32001, timeout: -32002, noDisponible: -32003, red: -32004, http: -32005 };
|
|
125
208
|
var ErrorPuente = class extends Error {
|
|
@@ -274,8 +357,966 @@ function ejecutarPuente(o) {
|
|
|
274
357
|
});
|
|
275
358
|
}
|
|
276
359
|
|
|
277
|
-
//
|
|
278
|
-
|
|
360
|
+
// src/setup.ts
|
|
361
|
+
import { execFile } from "node:child_process";
|
|
362
|
+
import { randomBytes, timingSafeEqual } from "node:crypto";
|
|
363
|
+
import { createServer } from "node:http";
|
|
364
|
+
import { hostname } from "node:os";
|
|
365
|
+
var API_POR_DEFECTO = "https://api.claqueta.me";
|
|
366
|
+
var ADMIN_POR_DEFECTO = "https://app.claqueta.me";
|
|
367
|
+
var CALLBACK_EXPIRA_MS = 5 * 60 * 1e3;
|
|
368
|
+
var MAX_CUERPO = 16 * 1024;
|
|
369
|
+
var MAX_INTENTOS_FALLIDOS = 5;
|
|
370
|
+
var RE_TOKEN = /^cq_[0-9A-Za-z]{10}_[A-Za-z0-9_-]{43}$/;
|
|
371
|
+
var LOCALES = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
372
|
+
function enmascarar(texto) {
|
|
373
|
+
return String(texto ?? "").replace(/cq_[A-Za-z0-9_-]+/g, "cq_***").replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi, "$1***");
|
|
374
|
+
}
|
|
375
|
+
function validarUrlBase(bruta, etiqueta, env = process.env) {
|
|
376
|
+
let u;
|
|
377
|
+
try {
|
|
378
|
+
u = new URL(String(bruta).trim());
|
|
379
|
+
} catch {
|
|
380
|
+
throw new Error(`${etiqueta} no es una URL v\xE1lida.`);
|
|
381
|
+
}
|
|
382
|
+
if (u.protocol !== "https:" && u.protocol !== "http:") throw new Error(`${etiqueta} debe ser http(s).`);
|
|
383
|
+
if (u.username || u.password) throw new Error(`${etiqueta} no puede llevar usuario:contrase\xF1a embebidos.`);
|
|
384
|
+
if (u.protocol === "http:" && !LOCALES.has(u.hostname) && env["CLAQUETA_ALLOW_INSECURE_API"] !== "1") {
|
|
385
|
+
throw new Error(
|
|
386
|
+
`${etiqueta} usa http:// hacia ${u.host}: el token viajar\xEDa en texto plano. Usa https://. Solo para pruebas puedes anularlo con CLAQUETA_ALLOW_INSECURE_API=1.`
|
|
387
|
+
);
|
|
388
|
+
}
|
|
389
|
+
u.search = "";
|
|
390
|
+
u.hash = "";
|
|
391
|
+
return u.href.replace(/\/+$/, "");
|
|
392
|
+
}
|
|
393
|
+
var iguales = (a, b) => {
|
|
394
|
+
const x = Buffer.from(String(a ?? ""));
|
|
395
|
+
const y = Buffer.from(b);
|
|
396
|
+
return x.length === y.length && timingSafeEqual(x, y);
|
|
397
|
+
};
|
|
398
|
+
async function iniciarCallback(o) {
|
|
399
|
+
const origenPermitido = new URL(o.adminUrl).origin;
|
|
400
|
+
let hecho = false;
|
|
401
|
+
let fallos = 0;
|
|
402
|
+
let resolver;
|
|
403
|
+
let rechazar;
|
|
404
|
+
const token = new Promise((res, rej) => {
|
|
405
|
+
resolver = res;
|
|
406
|
+
rechazar = rej;
|
|
407
|
+
});
|
|
408
|
+
token.catch(() => void 0);
|
|
409
|
+
const json = (res, status, cuerpo) => {
|
|
410
|
+
res.writeHead(status, { "Content-Type": "application/json", "Cache-Control": "no-store" });
|
|
411
|
+
res.end(JSON.stringify(cuerpo));
|
|
412
|
+
};
|
|
413
|
+
const cerrarServidor = () => {
|
|
414
|
+
clearTimeout(temporizador);
|
|
415
|
+
srv.close();
|
|
416
|
+
srv.closeAllConnections?.();
|
|
417
|
+
};
|
|
418
|
+
const srv = createServer((req, res) => {
|
|
419
|
+
const puerto2 = srv.address().port;
|
|
420
|
+
if (![`127.0.0.1:${puerto2}`, `localhost:${puerto2}`].includes(req.headers.host ?? "")) return json(res, 403, { ok: false, error: "host no permitido" });
|
|
421
|
+
const origen = req.headers.origin;
|
|
422
|
+
if (origen && origen !== origenPermitido) return json(res, 403, { ok: false, error: "origen no permitido" });
|
|
423
|
+
if (origen) {
|
|
424
|
+
res.setHeader("Access-Control-Allow-Origin", origenPermitido);
|
|
425
|
+
res.setHeader("Vary", "Origin");
|
|
426
|
+
res.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
|
|
427
|
+
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
|
|
428
|
+
if (req.headers["access-control-request-private-network"]) res.setHeader("Access-Control-Allow-Private-Network", "true");
|
|
429
|
+
}
|
|
430
|
+
if (req.method === "OPTIONS") {
|
|
431
|
+
res.writeHead(204);
|
|
432
|
+
res.end();
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
if (req.method !== "POST" || req.url !== "/callback") return json(res, 404, { ok: false });
|
|
436
|
+
if (hecho) return json(res, 410, { ok: false, error: "la conexi\xF3n ya se complet\xF3 o expir\xF3" });
|
|
437
|
+
if (Number(req.headers["content-length"]) > MAX_CUERPO) {
|
|
438
|
+
res.setHeader("Connection", "close");
|
|
439
|
+
return json(res, 413, { ok: false, error: "cuerpo demasiado grande" });
|
|
440
|
+
}
|
|
441
|
+
const trozos = [];
|
|
442
|
+
let tam = 0;
|
|
443
|
+
let grande = false;
|
|
444
|
+
req.on("data", (t) => {
|
|
445
|
+
if (grande) return;
|
|
446
|
+
tam += t.length;
|
|
447
|
+
if (tam > MAX_CUERPO) {
|
|
448
|
+
grande = true;
|
|
449
|
+
res.setHeader("Connection", "close");
|
|
450
|
+
json(res, 413, { ok: false, error: "cuerpo demasiado grande" });
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
trozos.push(t);
|
|
454
|
+
});
|
|
455
|
+
req.on("end", () => {
|
|
456
|
+
if (grande || res.writableEnded) return;
|
|
457
|
+
let p;
|
|
458
|
+
try {
|
|
459
|
+
p = JSON.parse(Buffer.concat(trozos).toString("utf8"));
|
|
460
|
+
} catch {
|
|
461
|
+
return json(res, 400, { ok: false, error: "JSON inv\xE1lido" });
|
|
462
|
+
}
|
|
463
|
+
const valido = iguales(p?.state, o.state) && typeof p?.token === "string" && RE_TOKEN.test(p.token);
|
|
464
|
+
if (!valido) {
|
|
465
|
+
json(res, 400, { ok: false, error: "state o token inv\xE1lido" });
|
|
466
|
+
if (++fallos >= MAX_INTENTOS_FALLIDOS) {
|
|
467
|
+
hecho = true;
|
|
468
|
+
cerrarServidor();
|
|
469
|
+
rechazar(new Error('Demasiados callbacks inv\xE1lidos; se cancel\xF3 la conexi\xF3n. Vuelve a correr "npx claqueta-mcp setup".'));
|
|
470
|
+
}
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
if (hecho) return json(res, 410, { ok: false, error: "la conexi\xF3n ya se complet\xF3 o expir\xF3" });
|
|
474
|
+
hecho = true;
|
|
475
|
+
res.on("finish", cerrarServidor);
|
|
476
|
+
json(res, 200, { ok: true });
|
|
477
|
+
resolver(p.token);
|
|
478
|
+
});
|
|
479
|
+
});
|
|
480
|
+
const temporizador = setTimeout(() => {
|
|
481
|
+
hecho = true;
|
|
482
|
+
cerrarServidor();
|
|
483
|
+
rechazar(new Error('Se agot\xF3 el tiempo esperando la confirmaci\xF3n (5 min). Corre "npx claqueta-mcp setup" de nuevo.'));
|
|
484
|
+
}, o.expiraMs ?? CALLBACK_EXPIRA_MS);
|
|
485
|
+
await new Promise((res, rej) => {
|
|
486
|
+
srv.once("error", rej);
|
|
487
|
+
srv.listen(0, "127.0.0.1", res);
|
|
488
|
+
}).catch((e) => {
|
|
489
|
+
clearTimeout(temporizador);
|
|
490
|
+
throw e;
|
|
491
|
+
});
|
|
492
|
+
const puerto = srv.address().port;
|
|
493
|
+
return {
|
|
494
|
+
puerto,
|
|
495
|
+
url: `http://127.0.0.1:${puerto}/callback`,
|
|
496
|
+
token,
|
|
497
|
+
cerrar() {
|
|
498
|
+
hecho = true;
|
|
499
|
+
cerrarServidor();
|
|
500
|
+
}
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
function comandoNavegador(url, plataforma = process.platform) {
|
|
504
|
+
const u = new URL(url);
|
|
505
|
+
if (u.protocol !== "http:" && u.protocol !== "https:") throw new Error("Solo se abren URLs http(s).");
|
|
506
|
+
if (plataforma === "darwin") return { cmd: "open", args: [u.href] };
|
|
507
|
+
if (plataforma === "win32") return { cmd: "rundll32", args: ["url.dll,FileProtocolHandler", u.href] };
|
|
508
|
+
return { cmd: "xdg-open", args: [u.href] };
|
|
509
|
+
}
|
|
510
|
+
function abrirNavegador(url) {
|
|
511
|
+
try {
|
|
512
|
+
const { cmd, args: args2 } = comandoNavegador(url);
|
|
513
|
+
execFile(cmd, args2, () => void 0).on("error", () => void 0);
|
|
514
|
+
} catch {
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
function nombreAgente(equipo = hostname()) {
|
|
518
|
+
const limpio = equipo.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "equipo";
|
|
519
|
+
return `claude-code @ ${limpio}`;
|
|
520
|
+
}
|
|
521
|
+
function sanearNombre(n) {
|
|
522
|
+
return n.replace(/[^\p{L}\p{N} ._@-]+/gu, "-").trim().slice(0, 80);
|
|
523
|
+
}
|
|
524
|
+
var COMANDO_CLAUDE = ["mcp", "add", "claqueta", "--", "npx", "-y", "claqueta-mcp"];
|
|
525
|
+
function claqueReal(args2) {
|
|
526
|
+
return new Promise((resolve3) => {
|
|
527
|
+
execFile("claude", args2, { timeout: 3e4 }, (err, stdout, stderr) => {
|
|
528
|
+
if (err && err.code === "ENOENT") return resolve3({ ausente: true, codigo: 127, salida: "" });
|
|
529
|
+
const codigo = err ? typeof err.code === "number" ? err.code : 1 : 0;
|
|
530
|
+
resolve3({ ausente: false, codigo, salida: `${stdout}${stderr}` });
|
|
531
|
+
});
|
|
532
|
+
});
|
|
533
|
+
}
|
|
534
|
+
var depsReales = () => ({
|
|
535
|
+
env: process.env,
|
|
536
|
+
salida: (l) => process.stderr.write(`${l}
|
|
537
|
+
`),
|
|
538
|
+
abrir: abrirNavegador,
|
|
539
|
+
ejecutarClaude: claqueReal
|
|
540
|
+
});
|
|
541
|
+
async function ejecutarSetup(op, deps = depsReales()) {
|
|
542
|
+
const { env, salida } = deps;
|
|
543
|
+
const apiUrl = validarUrlBase(op.url ?? env["CLAQUETA_URL"] ?? API_POR_DEFECTO, "La URL de la API (--url / CLAQUETA_URL)", env).replace(/\/mcp$/, "");
|
|
544
|
+
const adminUrl = validarUrlBase(env["CLAQUETA_ADMIN_URL"] ?? ADMIN_POR_DEFECTO, "CLAQUETA_ADMIN_URL", env);
|
|
545
|
+
const state = randomBytes(16).toString("hex");
|
|
546
|
+
const agente = sanearNombre(op.agente ?? nombreAgente());
|
|
547
|
+
const cb = await iniciarCallback({ state, adminUrl, expiraMs: op.expiraMs });
|
|
548
|
+
const q = new URLSearchParams({ callback: cb.url, state, agente, modo: op.modo, workspaces: op.workspaces.join(",") });
|
|
549
|
+
const url = `${adminUrl}/conectar?${q.toString()}`;
|
|
550
|
+
salida("Abriendo el navegador para conectar este equipo con tu cuenta de Claqueta...");
|
|
551
|
+
salida(`Si no se abre solo, entra a: ${url}`);
|
|
552
|
+
salida("Confirma ah\xED y vuelve a la terminal (la espera dura 5 minutos).");
|
|
553
|
+
deps.abrir(url);
|
|
554
|
+
let token;
|
|
555
|
+
try {
|
|
556
|
+
token = await cb.token;
|
|
557
|
+
} finally {
|
|
558
|
+
cb.cerrar();
|
|
559
|
+
}
|
|
560
|
+
const ruta = guardarConfig({ url: apiUrl, token }, env);
|
|
561
|
+
salida(`Token recibido (${enmascarar(token)}) y guardado en ${ruta} (permisos 0600).`);
|
|
562
|
+
let registrado = false;
|
|
563
|
+
if (op.registrar) {
|
|
564
|
+
const r2 = await deps.ejecutarClaude(COMANDO_CLAUDE);
|
|
565
|
+
if (r2.ausente) {
|
|
566
|
+
salida('No encontr\xE9 el CLI "claude". Registra el MCP con este comando (no lleva el token; el puente lo lee del archivo anterior):');
|
|
567
|
+
salida(` claude ${COMANDO_CLAUDE.join(" ")}`);
|
|
568
|
+
} else if (r2.codigo === 0) {
|
|
569
|
+
registrado = true;
|
|
570
|
+
salida('MCP "claqueta" registrado en Claude Code. Reinicia o reconecta con /mcp.');
|
|
571
|
+
} else {
|
|
572
|
+
salida(`No pude registrar el MCP autom\xE1ticamente: ${enmascarar(r2.salida).trim().split("\n")[0] ?? ""}`);
|
|
573
|
+
salida('Si ya estaba agregado, qu\xEDtalo con "claude mcp remove claqueta" y corre:');
|
|
574
|
+
salida(` claude ${COMANDO_CLAUDE.join(" ")}`);
|
|
575
|
+
}
|
|
576
|
+
} else {
|
|
577
|
+
salida("Registro omitido (--sin-registrar). Para registrarlo en Claude Code:");
|
|
578
|
+
salida(` claude ${COMANDO_CLAUDE.join(" ")}`);
|
|
579
|
+
}
|
|
580
|
+
salida("Para Claude Desktop agrega a claude_desktop_config.json (sin env: el token sale del archivo):");
|
|
581
|
+
salida(' { "mcpServers": { "claqueta": { "command": "npx", "args": ["-y", "claqueta-mcp"] } } }');
|
|
582
|
+
return { rutaConfig: ruta, apiUrl, registrado };
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
// src/worker-cli.ts
|
|
586
|
+
import { mkdirSync as mkdirSync3 } from "node:fs";
|
|
587
|
+
import { homedir as homedir4, hostname as hostname4 } from "node:os";
|
|
588
|
+
import { join as join5 } from "node:path";
|
|
589
|
+
|
|
590
|
+
// src/worker/api.ts
|
|
591
|
+
import { readFile as readFile2 } from "node:fs/promises";
|
|
592
|
+
import { basename as basename2 } from "node:path";
|
|
593
|
+
|
|
594
|
+
// src/worker/limites.ts
|
|
595
|
+
var LIMITES = {
|
|
596
|
+
agente: 80,
|
|
597
|
+
hostname: 120,
|
|
598
|
+
version: 40,
|
|
599
|
+
etapa: 40,
|
|
600
|
+
mensaje: 500,
|
|
601
|
+
causa: 1e3,
|
|
602
|
+
huerfanosMinMax: 1440
|
|
603
|
+
};
|
|
604
|
+
function truncar(s, max) {
|
|
605
|
+
if (s.length <= max) return s;
|
|
606
|
+
let corte = max - 1;
|
|
607
|
+
const c = s.charCodeAt(corte - 1);
|
|
608
|
+
if (c >= 55296 && c <= 56319) corte -= 1;
|
|
609
|
+
return `${s.slice(0, corte)}\u2026`;
|
|
610
|
+
}
|
|
611
|
+
function acotarTexto(s, max, relleno) {
|
|
612
|
+
const t = typeof s === "string" ? s.trim() : "";
|
|
613
|
+
return truncar(t === "" ? relleno : t, max);
|
|
614
|
+
}
|
|
615
|
+
function acotarOpcional(s, max) {
|
|
616
|
+
const t = typeof s === "string" ? s.trim() : "";
|
|
617
|
+
return t === "" ? void 0 : truncar(t, max);
|
|
618
|
+
}
|
|
619
|
+
function acotarPorcentaje(n) {
|
|
620
|
+
const v = typeof n === "number" && Number.isFinite(n) ? n : 0;
|
|
621
|
+
return Math.max(0, Math.min(100, Math.round(v)));
|
|
622
|
+
}
|
|
623
|
+
function acotarHuerfanosMin(n) {
|
|
624
|
+
if (!(n > 0)) return 0;
|
|
625
|
+
return Math.min(LIMITES.huerfanosMinMax, Math.ceil(n));
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
// src/worker/api.ts
|
|
629
|
+
var ErrorApi = class extends Error {
|
|
630
|
+
constructor(estado, mensaje) {
|
|
631
|
+
super(mensaje);
|
|
632
|
+
this.estado = estado;
|
|
633
|
+
this.name = "ErrorApi";
|
|
634
|
+
}
|
|
635
|
+
get conflicto() {
|
|
636
|
+
return this.estado === 409;
|
|
637
|
+
}
|
|
638
|
+
};
|
|
639
|
+
function crearClienteApi(base, token, f = fetch) {
|
|
640
|
+
const cab = (extra = {}) => ({ ...token ? { authorization: `Bearer ${token}` } : {}, ...extra });
|
|
641
|
+
async function llamar(metodo, ruta, cuerpo) {
|
|
642
|
+
const r2 = await f(`${base}${ruta}`, {
|
|
643
|
+
method: metodo,
|
|
644
|
+
headers: cab(cuerpo === void 0 ? {} : { "content-type": "application/json" }),
|
|
645
|
+
...cuerpo === void 0 ? {} : { body: JSON.stringify(cuerpo) }
|
|
646
|
+
});
|
|
647
|
+
return leer(r2);
|
|
648
|
+
}
|
|
649
|
+
async function leer(r2) {
|
|
650
|
+
if (r2.ok) return r2.status === 204 ? void 0 : await r2.json();
|
|
651
|
+
let msg = `HTTP ${r2.status}`;
|
|
652
|
+
try {
|
|
653
|
+
const j = await r2.json();
|
|
654
|
+
if (j.error) msg = j.error;
|
|
655
|
+
} catch {
|
|
656
|
+
}
|
|
657
|
+
throw new ErrorApi(r2.status, msg);
|
|
658
|
+
}
|
|
659
|
+
return {
|
|
660
|
+
reclamar: (o) => {
|
|
661
|
+
const huerfanos = acotarHuerfanosMin(o.huerfanosMin);
|
|
662
|
+
const host = acotarOpcional(o.hostname, LIMITES.hostname);
|
|
663
|
+
const ver = acotarOpcional(o.version, LIMITES.version);
|
|
664
|
+
return llamar("POST", "/api/cola/reclamar", { agente: acotarTexto(o.agente, LIMITES.agente, "worker"), max_reintentos: o.maxReintentos, ...host ? { hostname: host } : {}, ...ver ? { version: ver } : {}, ...huerfanos > 0 ? { huerfanos_min: huerfanos } : {} });
|
|
665
|
+
},
|
|
666
|
+
async progreso(id, p) {
|
|
667
|
+
await llamar("POST", `/api/videos/${id}/progreso`, { ...p, etapa: acotarTexto(p.etapa, LIMITES.etapa, "desconocida"), porcentaje: acotarPorcentaje(p.porcentaje), mensaje: acotarTexto(p.mensaje, LIMITES.mensaje, "sin mensaje") });
|
|
668
|
+
},
|
|
669
|
+
fallo: (id, x) => llamar("POST", `/api/videos/${id}/fallo`, { etapa: acotarOpcional(x.etapa, LIMITES.etapa) ?? null, causa: acotarTexto(x.causa, LIMITES.causa, "fallo sin causa conocida"), codigo: Number.isInteger(x.codigo) ? x.codigo : null, max_reintentos: x.maxReintentos, reintentable: x.reintentable }),
|
|
670
|
+
async adjuntarMp4(id, version, ruta) {
|
|
671
|
+
const bytes = await readFile2(ruta);
|
|
672
|
+
const ajustes = await llamar("GET", "/api/ajustes");
|
|
673
|
+
const base_mp4 = `/api/videos/${id}/versiones/${version}/mp4`;
|
|
674
|
+
if (ajustes.s3?.bucket) {
|
|
675
|
+
const sub = await llamar("POST", `${base_mp4}/url`, {});
|
|
676
|
+
const put = await f(sub.url, { method: "PUT", headers: sub.cabeceras, body: bytes });
|
|
677
|
+
if (!put.ok) throw new ErrorApi(put.status, `la subida a S3 fall\xF3 (HTTP ${put.status})`);
|
|
678
|
+
return llamar("POST", `${base_mp4}/confirmar`, { nombre: basename2(ruta) });
|
|
679
|
+
}
|
|
680
|
+
const form = new FormData();
|
|
681
|
+
form.append("archivo", new Blob([bytes], { type: "video/mp4" }), basename2(ruta));
|
|
682
|
+
return leer(await f(`${base}${base_mp4}`, { method: "POST", headers: cab(), body: form }));
|
|
683
|
+
}
|
|
684
|
+
};
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
// src/worker/worker.ts
|
|
688
|
+
import { hostname as hostname2 } from "node:os";
|
|
689
|
+
import { access, mkdir, readFile as readFile4, rm, writeFile } from "node:fs/promises";
|
|
690
|
+
import { join as join3 } from "node:path";
|
|
691
|
+
|
|
692
|
+
// src/worker/motor.ts
|
|
693
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
694
|
+
import { readFile as readFile3 } from "node:fs/promises";
|
|
695
|
+
import { join as join2 } from "node:path";
|
|
696
|
+
import { createInterface as createInterface2 } from "node:readline";
|
|
697
|
+
function argumentosDocker(c, e, usuario) {
|
|
698
|
+
const entorno = ["CLAQUETA_WHISPER_MODELO", "CLAQUETA_KOKORO_MODELO", "CLAQUETA_RENDER_WORKERS", "CLAQUETA_RENDER_CALIDAD"].filter((k) => process.env[k]).flatMap((k) => ["-e", `${k}=${process.env[k]}`]);
|
|
699
|
+
return [
|
|
700
|
+
"run",
|
|
701
|
+
"--rm",
|
|
702
|
+
"--name",
|
|
703
|
+
e.nombreContenedor,
|
|
704
|
+
`--shm-size=${c.shm}`,
|
|
705
|
+
...usuario ? ["--user", usuario] : [],
|
|
706
|
+
...entorno,
|
|
707
|
+
"-v",
|
|
708
|
+
`${c.cache}:/cache`,
|
|
709
|
+
"-v",
|
|
710
|
+
`${e.pedidoDir}:/pedido:ro`,
|
|
711
|
+
"-v",
|
|
712
|
+
`${e.salidaDir}:/salida`,
|
|
713
|
+
c.imagen,
|
|
714
|
+
"generar",
|
|
715
|
+
"--pedido",
|
|
716
|
+
"/pedido/pedido.json",
|
|
717
|
+
"--salida",
|
|
718
|
+
"/salida"
|
|
719
|
+
];
|
|
720
|
+
}
|
|
721
|
+
async function ejecutarMotor(c, e, timeoutMs = c.timeoutMs) {
|
|
722
|
+
const usuario = typeof process.getuid === "function" ? `${process.getuid()}:${process.getgid()}` : void 0;
|
|
723
|
+
const [bin, args2] = c.comando ? [c.comando, ["generar", "--pedido", join2(e.pedidoDir, "pedido.json"), "--salida", e.salidaDir]] : ["docker", argumentosDocker(c, e, usuario)];
|
|
724
|
+
const hijo = spawn(
|
|
725
|
+
bin,
|
|
726
|
+
args2,
|
|
727
|
+
{ stdio: ["ignore", "pipe", "pipe"], detached: true }
|
|
728
|
+
/* grupo propio: se mata todo el árbol */
|
|
729
|
+
);
|
|
730
|
+
const stderrCola = [];
|
|
731
|
+
let tiempoAgotado = false;
|
|
732
|
+
let abortado = false;
|
|
733
|
+
const matar = () => {
|
|
734
|
+
if (!c.comando) spawnSync("docker", ["kill", e.nombreContenedor], { stdio: "ignore" });
|
|
735
|
+
try {
|
|
736
|
+
if (hijo.pid) process.kill(-hijo.pid, "SIGTERM");
|
|
737
|
+
} catch {
|
|
738
|
+
hijo.kill("SIGTERM");
|
|
739
|
+
}
|
|
740
|
+
};
|
|
741
|
+
const temporizador = setTimeout(() => {
|
|
742
|
+
tiempoAgotado = true;
|
|
743
|
+
matar();
|
|
744
|
+
}, timeoutMs);
|
|
745
|
+
const alAbortar = () => {
|
|
746
|
+
abortado = true;
|
|
747
|
+
matar();
|
|
748
|
+
};
|
|
749
|
+
if (e.senal?.aborted) alAbortar();
|
|
750
|
+
else e.senal?.addEventListener("abort", alAbortar, { once: true });
|
|
751
|
+
createInterface2({ input: hijo.stdout }).on("line", (linea) => {
|
|
752
|
+
const ev = parsearEvento(linea);
|
|
753
|
+
if (ev) e.onEvento(ev);
|
|
754
|
+
});
|
|
755
|
+
createInterface2({ input: hijo.stderr }).on("line", (linea) => {
|
|
756
|
+
stderrCola.push(linea);
|
|
757
|
+
if (stderrCola.length > 20) stderrCola.shift();
|
|
758
|
+
});
|
|
759
|
+
const codigo = await new Promise((resolver) => {
|
|
760
|
+
hijo.on("error", (err) => {
|
|
761
|
+
stderrCola.push(`no se pudo lanzar \xAB${bin}\xBB: ${err.message}`);
|
|
762
|
+
resolver(127);
|
|
763
|
+
});
|
|
764
|
+
hijo.on("close", (cod, sig) => resolver(cod ?? (sig ? 128 + 15 : 1)));
|
|
765
|
+
});
|
|
766
|
+
clearTimeout(temporizador);
|
|
767
|
+
e.senal?.removeEventListener("abort", alAbortar);
|
|
768
|
+
let error = null;
|
|
769
|
+
try {
|
|
770
|
+
error = JSON.parse(await readFile3(join2(e.salidaDir, "error.json"), "utf8"));
|
|
771
|
+
} catch {
|
|
772
|
+
}
|
|
773
|
+
return { codigo, tiempoAgotado, abortado, error, stderrCola };
|
|
774
|
+
}
|
|
775
|
+
function parsearEvento(linea) {
|
|
776
|
+
try {
|
|
777
|
+
const j = JSON.parse(linea);
|
|
778
|
+
if (typeof j.etapa !== "string" || typeof j.porcentaje !== "number" || typeof j.mensaje !== "string") return null;
|
|
779
|
+
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 } : {} };
|
|
780
|
+
} catch {
|
|
781
|
+
return null;
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
function causaLegible(r2, timeoutMin) {
|
|
785
|
+
if (r2.tiempoAgotado) return `el motor super\xF3 el l\xEDmite de ${timeoutMin} min y se detuvo`;
|
|
786
|
+
if (r2.error?.mensaje) return r2.error.mensaje;
|
|
787
|
+
const significado = {
|
|
788
|
+
2: "el pedido no es v\xE1lido para el motor",
|
|
789
|
+
10: "fall\xF3 la s\xEDntesis de voz",
|
|
790
|
+
11: "fall\xF3 la alineaci\xF3n de subt\xEDtulos",
|
|
791
|
+
12: "fall\xF3 la composici\xF3n",
|
|
792
|
+
13: "fall\xF3 el render",
|
|
793
|
+
14: "fall\xF3 la mezcla de audio y video",
|
|
794
|
+
125: "Docker no pudo iniciar el contenedor del motor (imagen inexistente o daemon con error)",
|
|
795
|
+
127: "no se pudo lanzar el motor (\xBFDocker disponible y la imagen construida?)",
|
|
796
|
+
137: "el contenedor se detuvo por falta de memoria o fue detenido"
|
|
797
|
+
};
|
|
798
|
+
const base = significado[r2.codigo] ?? `el motor termin\xF3 con c\xF3digo ${r2.codigo}`;
|
|
799
|
+
const cola = r2.stderrCola.filter((l) => l.trim()).slice(-2).join(" | ");
|
|
800
|
+
return cola ? `${base} (${cola.slice(0, 300)})` : base;
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
// src/worker/pedido.ts
|
|
804
|
+
var PedidoNoSoportado = class extends Error {
|
|
805
|
+
constructor(mensaje) {
|
|
806
|
+
super(mensaje);
|
|
807
|
+
this.name = "PedidoNoSoportado";
|
|
808
|
+
}
|
|
809
|
+
};
|
|
810
|
+
function traducirPedido(r2) {
|
|
811
|
+
const p = { ...r2.pedido, workspace: r2.workspace, proyecto: r2.proyecto, solicitud_id: r2.solicitud_id, titulo: r2.titulo };
|
|
812
|
+
if (Object.keys(r2.origen ?? {}).length) p["origen"] = r2.origen;
|
|
813
|
+
const tienePedido = p["guion"]?.escenas?.length || typeof p["guion_libre"] === "string" && p["guion_libre"].trim();
|
|
814
|
+
if (!tienePedido) throw new PedidoNoSoportado("el pedido no trae guion ni guion_libre");
|
|
815
|
+
const plantilla = p["plantilla"];
|
|
816
|
+
if (plantilla !== void 0 && plantilla !== "plantilla-vertical-a") {
|
|
817
|
+
throw new PedidoNoSoportado(`el motor solo tiene la plantilla \xABplantilla-vertical-a\xBB (el pedido pide \xAB${String(plantilla)}\xBB)`);
|
|
818
|
+
}
|
|
819
|
+
const f = p["formato"];
|
|
820
|
+
if (f && (f.ancho !== void 0 && f.ancho !== 1080 || f.alto !== void 0 && f.alto !== 1920 || f.aspecto !== void 0 && f.aspecto !== "9:16")) {
|
|
821
|
+
throw new PedidoNoSoportado("el motor solo genera 1080x1920 (9:16)");
|
|
822
|
+
}
|
|
823
|
+
return p;
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
// src/worker/worker.ts
|
|
827
|
+
var dormirReal = (ms) => new Promise((r2) => setTimeout(r2, ms));
|
|
828
|
+
var existe = (ruta) => access(ruta).then(() => true, () => false);
|
|
829
|
+
async function procesarSiguiente(c, d) {
|
|
830
|
+
const log = d.log ?? (() => {
|
|
831
|
+
});
|
|
832
|
+
const { api } = d;
|
|
833
|
+
const { rescatados, reclamado } = await api.reclamar({ agente: c.nombre, huerfanosMin: c.huerfanosMin, maxReintentos: c.maxReintentos, hostname: hostname2(), ...process.env["CLAQUETA_VERSION"] ? { version: process.env["CLAQUETA_VERSION"] } : {} });
|
|
834
|
+
for (const id of rescatados) log(`rescatado ${id}: estaba en generando sin latidos`);
|
|
835
|
+
if (!reclamado) return { tipo: "vacio" };
|
|
836
|
+
return trabajar(c, d, reclamado);
|
|
837
|
+
}
|
|
838
|
+
async function trabajar(c, d, r2) {
|
|
839
|
+
const log = d.log ?? (() => {
|
|
840
|
+
});
|
|
841
|
+
const dormir = d.dormir ?? dormirReal;
|
|
842
|
+
const { api } = d;
|
|
843
|
+
const id = r2.video_id;
|
|
844
|
+
const raiz = join3(c.trabajoDir, `${id}-v${r2.version}-i${r2.intento}`);
|
|
845
|
+
const pedidoDir = join3(raiz, "pedido");
|
|
846
|
+
const salidaDir = join3(raiz, "salida");
|
|
847
|
+
log(`reclamado ${id} v${r2.version} (intento ${r2.intento}): ${r2.titulo}`);
|
|
848
|
+
const fallar = async (etapa, causa, codigo, reintentable) => {
|
|
849
|
+
log(`fall\xF3 ${id}: ${causa}`);
|
|
850
|
+
const f = await api.fallo(id, { etapa, causa, codigo, maxReintentos: c.maxReintentos, reintentable });
|
|
851
|
+
return { tipo: "fallo", videoId: id, causa, reencolado: f.reencolado };
|
|
852
|
+
};
|
|
853
|
+
try {
|
|
854
|
+
let pedido;
|
|
855
|
+
try {
|
|
856
|
+
pedido = traducirPedido(r2);
|
|
857
|
+
} catch (e) {
|
|
858
|
+
if (e instanceof PedidoNoSoportado) return await fallar("voz", e.message, null, false);
|
|
859
|
+
throw e;
|
|
860
|
+
}
|
|
861
|
+
await mkdir(pedidoDir, { recursive: true });
|
|
862
|
+
await mkdir(salidaDir, { recursive: true });
|
|
863
|
+
await writeFile(join3(pedidoDir, "pedido.json"), JSON.stringify(pedido, null, 2));
|
|
864
|
+
const parar = new AbortController();
|
|
865
|
+
const alCerrar = () => parar.abort();
|
|
866
|
+
d.senal?.addEventListener("abort", alCerrar, { once: true });
|
|
867
|
+
let cancelado = false;
|
|
868
|
+
let ultimo = { etapa: "voz", porcentaje: 0, mensaje: "Preparando el motor" };
|
|
869
|
+
let publicado = { etapa: "", porcentaje: -10 };
|
|
870
|
+
let cadena = Promise.resolve();
|
|
871
|
+
const publicar = (e, forzar = false) => {
|
|
872
|
+
cadena = cadena.then(async () => {
|
|
873
|
+
if (cancelado) return;
|
|
874
|
+
if (!forzar && e.etapa === publicado.etapa && e.porcentaje < publicado.porcentaje + 5 && e.nivel !== "advertencia" && e.porcentaje < 100) return;
|
|
875
|
+
try {
|
|
876
|
+
await api.progreso(id, { etapa: e.etapa, porcentaje: e.porcentaje, mensaje: e.mensaje, ...e.nivel === "advertencia" ? { nivel: "advertencia" } : {} });
|
|
877
|
+
publicado = { etapa: e.etapa, porcentaje: e.porcentaje };
|
|
878
|
+
} catch (err) {
|
|
879
|
+
if (err instanceof ErrorApi && (err.conflicto || err.estado === 404)) {
|
|
880
|
+
cancelado = true;
|
|
881
|
+
parar.abort();
|
|
882
|
+
} else log(`no pude reportar progreso: ${err.message}`);
|
|
883
|
+
}
|
|
884
|
+
});
|
|
885
|
+
};
|
|
886
|
+
const latido = setInterval(() => publicar(ultimo, true), d.latidoMs ?? 3e4);
|
|
887
|
+
publicar(ultimo, true);
|
|
888
|
+
let res;
|
|
889
|
+
try {
|
|
890
|
+
res = await (d.motor ?? ejecutarMotor)(c, {
|
|
891
|
+
pedidoDir,
|
|
892
|
+
salidaDir,
|
|
893
|
+
nombreContenedor: `claqueta-motor-${id}-${r2.intento}`.replace(/[^a-zA-Z0-9_.-]/g, "_"),
|
|
894
|
+
senal: parar.signal,
|
|
895
|
+
onEvento: (e) => {
|
|
896
|
+
ultimo = e;
|
|
897
|
+
publicar(e);
|
|
898
|
+
}
|
|
899
|
+
});
|
|
900
|
+
} finally {
|
|
901
|
+
clearInterval(latido);
|
|
902
|
+
d.senal?.removeEventListener("abort", alCerrar);
|
|
903
|
+
await cadena;
|
|
904
|
+
}
|
|
905
|
+
if (cancelado) return { tipo: "cancelado", videoId: id };
|
|
906
|
+
if (res.abortado) return await fallar(ultimo.etapa, "el worker se detuvo mientras generaba; se reintentar\xE1", null, true);
|
|
907
|
+
const mp4 = join3(salidaDir, "video.mp4");
|
|
908
|
+
const advertencias = [];
|
|
909
|
+
if (res.codigo === 0 || res.codigo === 15) {
|
|
910
|
+
if (!await existe(mp4)) return await fallar(ultimo.etapa, `el motor termin\xF3 bien pero no dej\xF3 video.mp4`, res.codigo, true);
|
|
911
|
+
if (res.codigo === 15) {
|
|
912
|
+
const f = await checksFallidos(salidaDir);
|
|
913
|
+
if (c.siFallaRevision === "rechazar") return await fallar("revision", `La revisi\xF3n autom\xE1tica no pas\xF3: ${f}`, 15, true);
|
|
914
|
+
advertencias.push(`La revisi\xF3n autom\xE1tica no pas\xF3: ${f}`);
|
|
915
|
+
await api.progreso(id, { etapa: "revision", porcentaje: 100, mensaje: advertencias[0], nivel: "advertencia" }).catch(() => {
|
|
916
|
+
});
|
|
917
|
+
}
|
|
918
|
+
const adj = await adjuntar(d, id, r2.version, mp4, dormir, log);
|
|
919
|
+
if (adj === "cancelado") return { tipo: "cancelado", videoId: id };
|
|
920
|
+
if (adj instanceof Error) return await fallar("revision", `no se pudo adjuntar el MP4: ${adj.message}`, null, true);
|
|
921
|
+
log(`listo ${id}: ${adj.estado}`);
|
|
922
|
+
return { tipo: "listo", videoId: id, estado: adj.estado, advertencias };
|
|
923
|
+
}
|
|
924
|
+
return await fallar(res.error?.etapa ?? ultimo.etapa, causaLegible(res, Math.round(c.timeoutMs / 6e4)), res.codigo, res.codigo !== 2 || res.tiempoAgotado);
|
|
925
|
+
} finally {
|
|
926
|
+
if (!c.conservar) await rm(raiz, { recursive: true, force: true });
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
async function checksFallidos(salidaDir) {
|
|
930
|
+
try {
|
|
931
|
+
const rev = JSON.parse(await readFile4(join3(salidaDir, "revision.json"), "utf8"));
|
|
932
|
+
const malos = (rev.checks ?? []).filter((x) => !x.ok && x.nivel === "requerido").map((x) => x.detalle ? `${x.id} (${x.detalle})` : x.id);
|
|
933
|
+
return malos.length ? malos.join(", ") : "sin detalle";
|
|
934
|
+
} catch {
|
|
935
|
+
return "sin detalle (no se pudo leer revision.json)";
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
async function adjuntar(d, id, version, mp4, dormir, log) {
|
|
939
|
+
let ultimo = new Error("sin intentos");
|
|
940
|
+
for (let i = 1; i <= 3; i++) {
|
|
941
|
+
try {
|
|
942
|
+
return await d.api.adjuntarMp4(id, version, mp4);
|
|
943
|
+
} catch (e) {
|
|
944
|
+
if (e instanceof ErrorApi && (e.conflicto || e.estado === 404)) return "cancelado";
|
|
945
|
+
ultimo = e;
|
|
946
|
+
log(`adjuntar fall\xF3 (intento ${i}/3): ${ultimo.message}`);
|
|
947
|
+
if (i < 3) await dormir(1e3 * 2 ** i);
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
return ultimo;
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
// src/worker/bucle.ts
|
|
954
|
+
async function correrBucle(c, d) {
|
|
955
|
+
const { log, senal } = d;
|
|
956
|
+
let codigo = 0;
|
|
957
|
+
while (!senal.aborted) {
|
|
958
|
+
try {
|
|
959
|
+
const r2 = await procesarSiguiente(c, { api: d.api, log, senal, ...d.motor ? { motor: d.motor } : {} });
|
|
960
|
+
if (r2.tipo !== "vacio") {
|
|
961
|
+
log(`resultado: ${JSON.stringify(r2)}`);
|
|
962
|
+
continue;
|
|
963
|
+
}
|
|
964
|
+
if (c.unaVez) break;
|
|
965
|
+
} catch (e) {
|
|
966
|
+
log(`error del ciclo: ${e.message}`);
|
|
967
|
+
if (c.unaVez) {
|
|
968
|
+
codigo = 1;
|
|
969
|
+
break;
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
await new Promise((res) => {
|
|
973
|
+
const t = setTimeout(res, c.sondeoMs);
|
|
974
|
+
senal.addEventListener("abort", () => (clearTimeout(t), res()), { once: true });
|
|
975
|
+
});
|
|
976
|
+
}
|
|
977
|
+
return codigo;
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
// src/worker/config.ts
|
|
981
|
+
import { hostname as hostname3 } from "node:os";
|
|
982
|
+
import { resolve as resolve2 } from "node:path";
|
|
983
|
+
var num = (v, def, nombre) => {
|
|
984
|
+
if (v === void 0 || v === "") return def;
|
|
985
|
+
const n = Number(v);
|
|
986
|
+
if (!Number.isFinite(n) || n < 0) throw new Error(`${nombre} debe ser un n\xFAmero positivo (recib\xED \xAB${v}\xBB)`);
|
|
987
|
+
return n;
|
|
988
|
+
};
|
|
989
|
+
function leerSiFallaRevision(v) {
|
|
990
|
+
if (v === void 0 || v === "") return "adjuntar";
|
|
991
|
+
if (v === "adjuntar" || v === "rechazar") return v;
|
|
992
|
+
throw new Error(`WORKER_SI_FALLA_REVISION debe ser \xABadjuntar\xBB o \xABrechazar\xBB (recib\xED \xAB${v}\xBB)`);
|
|
993
|
+
}
|
|
994
|
+
function leerConfig2(env = process.env, argv = [], aviso = (m) => process.stderr.write(`${m}
|
|
995
|
+
`)) {
|
|
996
|
+
const timeoutMin = num(env["WORKER_TIMEOUT_MIN"], 30, "WORKER_TIMEOUT_MIN");
|
|
997
|
+
const nombreCrudo = (env["WORKER_NOMBRE"] || `worker@${hostname3()}`).trim() || "worker";
|
|
998
|
+
const nombre = truncar(nombreCrudo, LIMITES.agente);
|
|
999
|
+
if (nombre !== nombreCrudo) aviso(`aviso: el nombre del worker pasa de ${LIMITES.agente} caracteres; lo recorto a \xAB${nombre}\xBB`);
|
|
1000
|
+
const huerfanosCrudo = num(env["WORKER_HUERFANOS_MIN"], timeoutMin + 5, "WORKER_HUERFANOS_MIN");
|
|
1001
|
+
const huerfanosMin = Math.min(LIMITES.huerfanosMinMax, huerfanosCrudo);
|
|
1002
|
+
if (huerfanosMin !== huerfanosCrudo) aviso(`aviso: WORKER_HUERFANOS_MIN (${huerfanosCrudo}) excede el m\xE1ximo de la API (${LIMITES.huerfanosMinMax} min); uso ${huerfanosMin}`);
|
|
1003
|
+
return {
|
|
1004
|
+
apiUrl: (env["CLAQUETA_API_URL"] || "http://localhost:4848").replace(/\/+$/, ""),
|
|
1005
|
+
apiToken: env["CLAQUETA_API_TOKEN"] || void 0,
|
|
1006
|
+
nombre,
|
|
1007
|
+
trabajoDir: resolve2(env["WORKER_TRABAJO_DIR"] || "./trabajo"),
|
|
1008
|
+
sondeoMs: num(env["WORKER_SONDEO_S"], 5, "WORKER_SONDEO_S") * 1e3,
|
|
1009
|
+
timeoutMs: timeoutMin * 6e4,
|
|
1010
|
+
maxReintentos: Math.min(5, Math.floor(num(env["WORKER_MAX_REINTENTOS"], 2, "WORKER_MAX_REINTENTOS"))),
|
|
1011
|
+
huerfanosMin,
|
|
1012
|
+
imagen: env["MOTOR_IMAGEN"] || "claqueta-motor:dev",
|
|
1013
|
+
cache: env["MOTOR_CACHE"] || "claqueta-cache",
|
|
1014
|
+
shm: env["MOTOR_SHM"] || "1g",
|
|
1015
|
+
comando: env["MOTOR_COMANDO"] || void 0,
|
|
1016
|
+
conservar: env["WORKER_CONSERVAR"] === "1",
|
|
1017
|
+
siFallaRevision: leerSiFallaRevision(env["WORKER_SI_FALLA_REVISION"]),
|
|
1018
|
+
unaVez: argv.includes("--una-vez") || env["WORKER_UNA_VEZ"] === "1"
|
|
1019
|
+
};
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
// src/motor-docker.ts
|
|
1023
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
1024
|
+
var IMAGEN_POR_DEFECTO = "868827002370.dkr.ecr.us-west-1.amazonaws.com/claqueta-motor:dev";
|
|
1025
|
+
var PERFIL_AWS_POR_DEFECTO = "claqueta-motor";
|
|
1026
|
+
var REGION_POR_DEFECTO = "us-west-1";
|
|
1027
|
+
var ejecutarReal = (cmd, args2, opc) => new Promise((resolver) => {
|
|
1028
|
+
const hijo = spawn2(cmd, args2, { stdio: ["pipe", "pipe", "pipe"] });
|
|
1029
|
+
let stdout = "";
|
|
1030
|
+
let stderr = "";
|
|
1031
|
+
hijo.stdout.on("data", (d) => stdout += d.toString());
|
|
1032
|
+
hijo.stderr.on("data", (d) => stderr += d.toString());
|
|
1033
|
+
hijo.on("error", (e) => resolver({ codigo: 127, stdout, stderr: e.message, noEncontrado: e.code === "ENOENT" }));
|
|
1034
|
+
hijo.on("close", (codigo) => resolver({ codigo: codigo ?? 1, stdout, stderr }));
|
|
1035
|
+
hijo.stdin.on("error", () => {
|
|
1036
|
+
});
|
|
1037
|
+
hijo.stdin.end(opc?.input ?? "");
|
|
1038
|
+
});
|
|
1039
|
+
function registroEcr(imagen) {
|
|
1040
|
+
const m = /^(\d{12}\.dkr\.ecr\.([a-z0-9-]+)\.amazonaws\.com)\//.exec(imagen);
|
|
1041
|
+
return m ? { registro: m[1], region: m[2] ?? REGION_POR_DEFECTO } : null;
|
|
1042
|
+
}
|
|
1043
|
+
var limpiar = (t) => t.trim().split("\n").slice(-3).join(" | ").slice(0, 300);
|
|
1044
|
+
function explicarErrorAws(s, o) {
|
|
1045
|
+
if (s.noEncontrado) return "No encuentro el AWS CLI (`aws`). Inst\xE1lalo (macOS: `brew install awscli`) o descarga la imagen a mano y usa --sin-actualizar-motor.";
|
|
1046
|
+
const t = s.stderr;
|
|
1047
|
+
if (/could not be found|profile .* not found/i.test(t)) {
|
|
1048
|
+
return `No existe el perfil AWS \xAB${o.perfilAws}\xBB. Cr\xE9alo con: aws configure --profile ${o.perfilAws} (regi\xF3n us-west-1, con la access key del usuario claqueta-motor-descarga), o exporta AWS_ACCESS_KEY_ID y AWS_SECRET_ACCESS_KEY.`;
|
|
1049
|
+
}
|
|
1050
|
+
if (/unable to locate credentials|no credentials/i.test(t)) {
|
|
1051
|
+
return `No hay credenciales de AWS. Configura el perfil con: aws configure --profile ${o.perfilAws} (access key del usuario claqueta-motor-descarga), o exporta AWS_ACCESS_KEY_ID y AWS_SECRET_ACCESS_KEY.`;
|
|
1052
|
+
}
|
|
1053
|
+
if (/ExpiredToken|InvalidClientTokenId|SignatureDoesNotMatch|security token/i.test(t)) {
|
|
1054
|
+
return "AWS rechaz\xF3 las credenciales (inv\xE1lidas o vencidas). Revisa la access key del perfil o genera una nueva.";
|
|
1055
|
+
}
|
|
1056
|
+
if (/AccessDenied|not authorized/i.test(t)) return "AWS neg\xF3 el acceso al registro de la imagen: la access key no tiene permiso de descarga de ECR (usuario claqueta-motor-descarga).";
|
|
1057
|
+
return `No pude obtener el token de ECR: ${limpiar(t) || `aws termin\xF3 con c\xF3digo ${s.codigo}`}`;
|
|
1058
|
+
}
|
|
1059
|
+
async function prepararMotor(o, d) {
|
|
1060
|
+
const info = await d.ejecutar("docker", ["info", "--format", "{{.ServerVersion}}"]);
|
|
1061
|
+
if (info.noEncontrado) throw new Error("No encuentro `docker`. Instala Docker Desktop (https://www.docker.com/products/docker-desktop) y vuelve a correr el comando.");
|
|
1062
|
+
if (info.codigo !== 0) throw new Error("Docker no responde. Abre Docker Desktop, espera a que diga \xABrunning\xBB y vuelve a correr el comando.");
|
|
1063
|
+
const local = (await d.ejecutar("docker", ["image", "inspect", o.imagen, "--format", "{{.Id}}"])).codigo === 0;
|
|
1064
|
+
if (local && o.sinActualizar) {
|
|
1065
|
+
d.log(`motor: imagen ${o.imagen} ya est\xE1 local (--sin-actualizar-motor)`);
|
|
1066
|
+
return;
|
|
1067
|
+
}
|
|
1068
|
+
try {
|
|
1069
|
+
await descargar(o, d);
|
|
1070
|
+
d.log(`motor: imagen ${o.imagen} lista`);
|
|
1071
|
+
} catch (e) {
|
|
1072
|
+
if (!local) throw e;
|
|
1073
|
+
d.log(`aviso: no pude actualizar el motor (${e.message}); sigo con la imagen local.`);
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
async function descargar(o, d) {
|
|
1077
|
+
const ecr = registroEcr(o.imagen);
|
|
1078
|
+
if (ecr) {
|
|
1079
|
+
const usarPerfil = o.perfilExplicito || !d.env["AWS_ACCESS_KEY_ID"];
|
|
1080
|
+
const args2 = ["ecr", "get-login-password", "--region", ecr.region, ...usarPerfil ? ["--profile", o.perfilAws] : []];
|
|
1081
|
+
const tok = await d.ejecutar("aws", args2);
|
|
1082
|
+
if (tok.codigo !== 0 || !tok.stdout.trim()) throw new Error(explicarErrorAws(tok, o));
|
|
1083
|
+
const login = await d.ejecutar("docker", ["login", "--username", "AWS", "--password-stdin", ecr.registro], { input: tok.stdout.trim() });
|
|
1084
|
+
if (login.codigo !== 0) throw new Error(`docker login contra ${ecr.registro} fall\xF3: ${limpiar(login.stderr).replace(tok.stdout.trim(), "***")}`);
|
|
1085
|
+
}
|
|
1086
|
+
d.log(`motor: descargando ${o.imagen} (la primera vez son ~1 GB)\u2026`);
|
|
1087
|
+
const pull = await d.ejecutar("docker", ["pull", o.imagen]);
|
|
1088
|
+
if (pull.codigo !== 0) {
|
|
1089
|
+
const t = limpiar(pull.stderr);
|
|
1090
|
+
if (/no basic auth|authorization token|denied|unauthorized/i.test(t)) throw new Error(`Docker no tiene permiso para bajar ${o.imagen}; repite el login (el token de ECR dura 12 h) y revisa la access key. Detalle: ${t}`);
|
|
1091
|
+
throw new Error(`docker pull ${o.imagen} fall\xF3: ${t}`);
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
|
|
1095
|
+
// src/servicio-launchd.ts
|
|
1096
|
+
import { chmodSync as chmodSync2, existsSync as existsSync2, mkdirSync as mkdirSync2, rmSync, writeFileSync as writeFileSync2 } from "node:fs";
|
|
1097
|
+
import { homedir as homedir3 } from "node:os";
|
|
1098
|
+
import { dirname, join as join4 } from "node:path";
|
|
1099
|
+
var ETIQUETA = "me.claqueta.worker";
|
|
1100
|
+
var rutasServicio = (casa = homedir3()) => ({
|
|
1101
|
+
plist: join4(casa, "Library", "LaunchAgents", `${ETIQUETA}.plist`),
|
|
1102
|
+
log: join4(casa, "Library", "Logs", "claqueta-worker.log")
|
|
1103
|
+
});
|
|
1104
|
+
var xml = (t) => t.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
1105
|
+
function generarPlist(e) {
|
|
1106
|
+
const argv = [e.npx, "-y", "claqueta-mcp", "worker", ...e.args];
|
|
1107
|
+
const items = argv.map((a) => ` <string>${xml(a)}</string>`).join("\n");
|
|
1108
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
1109
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
1110
|
+
<plist version="1.0">
|
|
1111
|
+
<dict>
|
|
1112
|
+
<key>Label</key>
|
|
1113
|
+
<string>${ETIQUETA}</string>
|
|
1114
|
+
<key>ProgramArguments</key>
|
|
1115
|
+
<array>
|
|
1116
|
+
${items}
|
|
1117
|
+
</array>
|
|
1118
|
+
<key>RunAtLoad</key>
|
|
1119
|
+
<true/>
|
|
1120
|
+
<key>KeepAlive</key>
|
|
1121
|
+
<true/>
|
|
1122
|
+
<key>ThrottleInterval</key>
|
|
1123
|
+
<integer>30</integer>
|
|
1124
|
+
<key>WorkingDirectory</key>
|
|
1125
|
+
<string>${xml(e.casa)}</string>
|
|
1126
|
+
<key>EnvironmentVariables</key>
|
|
1127
|
+
<dict>
|
|
1128
|
+
<key>PATH</key>
|
|
1129
|
+
<string>${xml(e.path)}</string>
|
|
1130
|
+
<key>HOME</key>
|
|
1131
|
+
<string>${xml(e.casa)}</string>
|
|
1132
|
+
</dict>
|
|
1133
|
+
<key>StandardOutPath</key>
|
|
1134
|
+
<string>${xml(e.rutaLog)}</string>
|
|
1135
|
+
<key>StandardErrorPath</key>
|
|
1136
|
+
<string>${xml(e.rutaLog)}</string>
|
|
1137
|
+
</dict>
|
|
1138
|
+
</plist>
|
|
1139
|
+
`;
|
|
1140
|
+
}
|
|
1141
|
+
function exigirMac(d) {
|
|
1142
|
+
if ((d.plataforma ?? process.platform) !== "darwin") throw new Error("El servicio launchd solo existe en macOS. En otros sistemas corre `claqueta-mcp worker` con tu gestor de servicios.");
|
|
1143
|
+
}
|
|
1144
|
+
async function instalarServicio(args2, d) {
|
|
1145
|
+
exigirMac(d);
|
|
1146
|
+
const casa = d.casa ?? homedir3();
|
|
1147
|
+
const r2 = rutasServicio(casa);
|
|
1148
|
+
const nodeDir = dirname(d.nodePath ?? process.execPath);
|
|
1149
|
+
const path = [.../* @__PURE__ */ new Set([nodeDir, "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin"])].join(":");
|
|
1150
|
+
mkdirSync2(dirname(r2.plist), { recursive: true });
|
|
1151
|
+
mkdirSync2(dirname(r2.log), { recursive: true });
|
|
1152
|
+
writeFileSync2(r2.plist, generarPlist({ npx: join4(nodeDir, "npx"), args: args2, casa, rutaLog: r2.log, path }), { mode: 420 });
|
|
1153
|
+
chmodSync2(r2.plist, 420);
|
|
1154
|
+
const dominio = `gui/${d.uid ?? process.getuid?.() ?? 501}`;
|
|
1155
|
+
await d.launchctl(["bootout", `${dominio}/${ETIQUETA}`]);
|
|
1156
|
+
const b = await d.launchctl(["bootstrap", dominio, r2.plist]);
|
|
1157
|
+
if (b.codigo !== 0) throw new Error(`Escrib\xED ${r2.plist} pero launchctl no pudo cargarlo: ${b.stderr.trim() || `c\xF3digo ${b.codigo}`}. Reintenta con: launchctl bootstrap ${dominio} "${r2.plist}"`);
|
|
1158
|
+
d.log(`servicio instalado y activo: ${r2.plist}
|
|
1159
|
+
logs: ${r2.log}`);
|
|
1160
|
+
return r2;
|
|
1161
|
+
}
|
|
1162
|
+
async function quitarServicio(d) {
|
|
1163
|
+
exigirMac(d);
|
|
1164
|
+
const r2 = rutasServicio(d.casa ?? homedir3());
|
|
1165
|
+
const dominio = `gui/${d.uid ?? process.getuid?.() ?? 501}`;
|
|
1166
|
+
await d.launchctl(["bootout", `${dominio}/${ETIQUETA}`]);
|
|
1167
|
+
if (existsSync2(r2.plist)) {
|
|
1168
|
+
rmSync(r2.plist);
|
|
1169
|
+
d.log(`servicio quitado: ${r2.plist}`);
|
|
1170
|
+
} else d.log("no hab\xEDa servicio instalado");
|
|
1171
|
+
return r2;
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
// src/worker-cli.ts
|
|
1175
|
+
var AYUDA_WORKER = `claqueta-mcp worker: corre el worker de la cola de Claqueta en este equipo (necesita Docker).
|
|
1176
|
+
|
|
1177
|
+
Uso:
|
|
1178
|
+
npx claqueta-mcp worker [opciones]
|
|
1179
|
+
|
|
1180
|
+
Lee la URL y el token de escritura de ~/.config/claqueta/config.json (lo crea "npx claqueta-mcp setup --modo escritura");
|
|
1181
|
+
CLAQUETA_URL y CLAQUETA_TOKEN en el entorno mandan sobre el archivo.
|
|
1182
|
+
|
|
1183
|
+
Opciones:
|
|
1184
|
+
--url <url> API de Claqueta (por defecto la del archivo de configuraci\xF3n).
|
|
1185
|
+
--agente <nombre> Nombre del worker en la API (por defecto el hostname).
|
|
1186
|
+
--intervalo <segundos> Espera entre sondeos con la cola vac\xEDa (por defecto 10).
|
|
1187
|
+
--motor-imagen <imagen> Imagen del motor (por defecto ${IMAGEN_POR_DEFECTO}).
|
|
1188
|
+
--una-vez Procesa lo que haya en la cola y sale.
|
|
1189
|
+
--sin-actualizar-motor No baja la imagen si ya est\xE1 en este equipo.
|
|
1190
|
+
--perfil-aws <perfil> Perfil AWS para bajar la imagen de ECR (por defecto ${PERFIL_AWS_POR_DEFECTO}; si hay
|
|
1191
|
+
AWS_ACCESS_KEY_ID en el entorno y no pasas este flag, se usan las variables AWS_*).
|
|
1192
|
+
--si-falla-revision <modo> Si la revisi\xF3n autom\xE1tica del motor falla (c\xF3digo 15): "adjuntar" (por defecto: el video
|
|
1193
|
+
queda en revisi\xF3n con una advertencia) o "rechazar" (el video pasa a error y se reintenta).
|
|
1194
|
+
--instalar-servicio macOS: instala ~/Library/LaunchAgents/me.claqueta.worker.plist (arranca al iniciar sesi\xF3n
|
|
1195
|
+
y se reinicia solo; logs en ~/Library/Logs/claqueta-worker.log). Sin tokens en el plist.
|
|
1196
|
+
--quitar-servicio macOS: descarga y borra ese servicio.
|
|
1197
|
+
`;
|
|
1198
|
+
function leerArgsWorker(argv) {
|
|
1199
|
+
const op = { unaVez: false, sinActualizarMotor: false, siFallaRevision: "adjuntar", accion: "correr" };
|
|
1200
|
+
for (let i = 0; i < argv.length; i++) {
|
|
1201
|
+
const a = argv[i];
|
|
1202
|
+
if (a === "--help" || a === "-h") return { tipo: "ayuda" };
|
|
1203
|
+
if (a === "--una-vez") op.unaVez = true;
|
|
1204
|
+
else if (a === "--sin-actualizar-motor") op.sinActualizarMotor = true;
|
|
1205
|
+
else if (a === "--instalar-servicio") op.accion = "instalar-servicio";
|
|
1206
|
+
else if (a === "--quitar-servicio") op.accion = "quitar-servicio";
|
|
1207
|
+
else {
|
|
1208
|
+
const m = /^--(url|agente|intervalo|motor-imagen|perfil-aws|si-falla-revision)(?:=(.*))?$/.exec(a);
|
|
1209
|
+
if (!m) return { tipo: "error", mensaje: `Opci\xF3n desconocida de worker: ${a}. Usa --help.` };
|
|
1210
|
+
const valor = (m[2] ?? argv[++i])?.trim();
|
|
1211
|
+
if (!valor) return { tipo: "error", mensaje: `Falta el valor de --${m[1]}.` };
|
|
1212
|
+
if (m[1] === "url") op.url = valor;
|
|
1213
|
+
else if (m[1] === "agente") op.agente = valor;
|
|
1214
|
+
else if (m[1] === "motor-imagen") op.motorImagen = valor;
|
|
1215
|
+
else if (m[1] === "perfil-aws") op.perfilAws = valor;
|
|
1216
|
+
else if (m[1] === "intervalo") {
|
|
1217
|
+
const n = Number(valor);
|
|
1218
|
+
if (!Number.isFinite(n) || n < 1) return { tipo: "error", mensaje: "--intervalo debe ser un n\xFAmero de segundos (1 o m\xE1s)." };
|
|
1219
|
+
op.intervaloS = n;
|
|
1220
|
+
} else {
|
|
1221
|
+
try {
|
|
1222
|
+
op.siFallaRevision = leerSiFallaRevision(valor);
|
|
1223
|
+
} catch {
|
|
1224
|
+
return { tipo: "error", mensaje: '--si-falla-revision debe ser "adjuntar" o "rechazar".' };
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
if (op.accion !== "correr" && op.unaVez) return { tipo: "error", mensaje: "--una-vez no tiene sentido con el servicio (se reiniciar\xEDa en bucle)." };
|
|
1230
|
+
return { tipo: "worker", opciones: op };
|
|
1231
|
+
}
|
|
1232
|
+
function argsParaServicio(o) {
|
|
1233
|
+
return [
|
|
1234
|
+
...o.url ? ["--url", o.url] : [],
|
|
1235
|
+
...o.agente ? ["--agente", o.agente] : [],
|
|
1236
|
+
...o.intervaloS ? ["--intervalo", String(o.intervaloS)] : [],
|
|
1237
|
+
...o.motorImagen ? ["--motor-imagen", o.motorImagen] : [],
|
|
1238
|
+
...o.perfilAws ? ["--perfil-aws", o.perfilAws] : [],
|
|
1239
|
+
...o.sinActualizarMotor ? ["--sin-actualizar-motor"] : [],
|
|
1240
|
+
...o.siFallaRevision !== "adjuntar" ? ["--si-falla-revision", o.siFallaRevision] : []
|
|
1241
|
+
];
|
|
1242
|
+
}
|
|
1243
|
+
function resolverConexion(o, env, archivo) {
|
|
1244
|
+
const bruta = o.url ?? (env["CLAQUETA_URL"]?.trim() ? env["CLAQUETA_URL"] : archivo.url) ?? API_POR_DEFECTO;
|
|
1245
|
+
const url = validarUrlBase(bruta.trim().replace(/\/+$/, "").replace(/\/mcp$/, ""), "La URL de la API", env);
|
|
1246
|
+
const token = (env["CLAQUETA_TOKEN"]?.trim() ? env["CLAQUETA_TOKEN"] : archivo.token)?.trim();
|
|
1247
|
+
if (!token) throw new Error("No hay token. Corre primero \xABnpx claqueta-mcp setup --modo escritura\xBB (guarda el token en ~/.config/claqueta/config.json) o define CLAQUETA_TOKEN.");
|
|
1248
|
+
return { url, token };
|
|
1249
|
+
}
|
|
1250
|
+
function configWorker(o, conexion, env, nombreEquipo, casa) {
|
|
1251
|
+
const c = leerConfig2({
|
|
1252
|
+
...env,
|
|
1253
|
+
CLAQUETA_API_URL: conexion.url,
|
|
1254
|
+
WORKER_NOMBRE: o.agente ?? nombreEquipo,
|
|
1255
|
+
MOTOR_IMAGEN: o.motorImagen ?? IMAGEN_POR_DEFECTO,
|
|
1256
|
+
WORKER_TRABAJO_DIR: env["WORKER_TRABAJO_DIR"] || join5(casa, ".cache", "claqueta", "trabajo"),
|
|
1257
|
+
WORKER_SONDEO_S: String(o.intervaloS ?? (env["WORKER_SONDEO_S"] || 10))
|
|
1258
|
+
});
|
|
1259
|
+
return { ...c, apiToken: conexion.token, unaVez: o.unaVez, siFallaRevision: o.siFallaRevision };
|
|
1260
|
+
}
|
|
1261
|
+
async function ejecutarWorker(o, d) {
|
|
1262
|
+
process.env["CLAQUETA_VERSION"] ??= VERSION;
|
|
1263
|
+
const log = d.log ?? ((m) => console.log(`${(/* @__PURE__ */ new Date()).toISOString()} ${enmascarar(m)}`));
|
|
1264
|
+
const casa = d.casa ?? homedir4();
|
|
1265
|
+
const ejecutar = d.ejecutar ?? ejecutarReal;
|
|
1266
|
+
const launchctl = d.launchctl ?? (async (args2) => {
|
|
1267
|
+
const r2 = await ejecutar("launchctl", args2);
|
|
1268
|
+
return { codigo: r2.codigo, stderr: r2.stderr };
|
|
1269
|
+
});
|
|
1270
|
+
const depsServicio = { casa, launchctl, log, ...d.plataforma ? { plataforma: d.plataforma } : {} };
|
|
1271
|
+
if (o.accion === "quitar-servicio") {
|
|
1272
|
+
await quitarServicio(depsServicio);
|
|
1273
|
+
return 0;
|
|
1274
|
+
}
|
|
1275
|
+
const conexion = resolverConexion(o, d.env, d.archivo);
|
|
1276
|
+
if (o.accion === "instalar-servicio") {
|
|
1277
|
+
await instalarServicio(argsParaServicio(o), depsServicio);
|
|
1278
|
+
return 0;
|
|
1279
|
+
}
|
|
1280
|
+
const c = configWorker(o, conexion, d.env, d.nombreEquipo ?? hostname4(), casa);
|
|
1281
|
+
await prepararMotor(
|
|
1282
|
+
{ imagen: c.imagen, perfilAws: o.perfilAws ?? d.env["CLAQUETA_AWS_PROFILE"] ?? PERFIL_AWS_POR_DEFECTO, perfilExplicito: Boolean(o.perfilAws), sinActualizar: o.sinActualizarMotor },
|
|
1283
|
+
{ ejecutar, env: d.env, log }
|
|
1284
|
+
);
|
|
1285
|
+
mkdirSync3(c.trabajoDir, { recursive: true });
|
|
1286
|
+
const api = (d.crearApi ?? ((b, t) => crearClienteApi(b, t)))(c.apiUrl, conexion.token);
|
|
1287
|
+
const parar = new AbortController();
|
|
1288
|
+
d.senal?.addEventListener("abort", () => parar.abort(), { once: true });
|
|
1289
|
+
log(`worker ${c.nombre} \u2192 ${c.apiUrl} (imagen ${c.imagen}, trabajo en ${c.trabajoDir}, si falla la revisi\xF3n: ${c.siFallaRevision})`);
|
|
1290
|
+
const salida = await (d.bucle ?? correrBucle)(c, { api, log, senal: parar.signal });
|
|
1291
|
+
log("worker detenido");
|
|
1292
|
+
return salida;
|
|
1293
|
+
}
|
|
1294
|
+
|
|
1295
|
+
// src/cli.ts
|
|
1296
|
+
var args = process.argv.slice(2);
|
|
1297
|
+
if (args[0] === "worker") {
|
|
1298
|
+
const w = leerArgsWorker(args.slice(1));
|
|
1299
|
+
if (w.tipo === "ayuda") {
|
|
1300
|
+
process.stderr.write(AYUDA_WORKER);
|
|
1301
|
+
process.exit(0);
|
|
1302
|
+
} else if (w.tipo === "error") {
|
|
1303
|
+
process.stderr.write(`claqueta-mcp worker: ${w.mensaje}
|
|
1304
|
+
`);
|
|
1305
|
+
process.exit(1);
|
|
1306
|
+
}
|
|
1307
|
+
const parar = new AbortController();
|
|
1308
|
+
for (const s of ["SIGINT", "SIGTERM"]) process.on(s, () => (console.log(`${s}: deteniendo`), parar.abort()));
|
|
1309
|
+
try {
|
|
1310
|
+
const codigo = await ejecutarWorker(w.opciones, { env: process.env, archivo: leerArchivoConfig(process.env).datos, senal: parar.signal });
|
|
1311
|
+
process.exit(codigo);
|
|
1312
|
+
} catch (e) {
|
|
1313
|
+
process.stderr.write(`claqueta-mcp worker: ${enmascarar(e.message)}
|
|
1314
|
+
`);
|
|
1315
|
+
process.exit(1);
|
|
1316
|
+
}
|
|
1317
|
+
}
|
|
1318
|
+
var respaldo = args[0] === "setup" ? { datos: {}, avisos: [] } : leerArchivoConfig(process.env);
|
|
1319
|
+
var r = leerConfig(args, process.env, respaldo.datos);
|
|
279
1320
|
if (r.tipo === "ayuda") {
|
|
280
1321
|
process.stderr.write(AYUDA);
|
|
281
1322
|
process.exit(0);
|
|
@@ -283,6 +1324,15 @@ if (r.tipo === "ayuda") {
|
|
|
283
1324
|
process.stderr.write(`${VERSION}
|
|
284
1325
|
`);
|
|
285
1326
|
process.exit(0);
|
|
1327
|
+
} else if (r.tipo === "setup") {
|
|
1328
|
+
try {
|
|
1329
|
+
await ejecutarSetup(r.opciones);
|
|
1330
|
+
process.exit(0);
|
|
1331
|
+
} catch (e) {
|
|
1332
|
+
process.stderr.write(`claqueta-mcp setup: ${enmascarar(e.message)}
|
|
1333
|
+
`);
|
|
1334
|
+
process.exit(1);
|
|
1335
|
+
}
|
|
286
1336
|
} else if (r.tipo === "error") {
|
|
287
1337
|
process.stderr.write(`claqueta-mcp: ${r.mensaje}
|
|
288
1338
|
`);
|
|
@@ -291,7 +1341,7 @@ if (r.tipo === "ayuda") {
|
|
|
291
1341
|
const { config, avisos } = r;
|
|
292
1342
|
const log = (m) => process.stderr.write(`claqueta-mcp: ${m.split(config.token).join("***")}
|
|
293
1343
|
`);
|
|
294
|
-
for (const a of avisos) log(a);
|
|
1344
|
+
for (const a of [...respaldo.avisos, ...avisos]) log(a);
|
|
295
1345
|
process.stdout.on("error", () => process.exit(0));
|
|
296
1346
|
const salir = () => process.exit(0);
|
|
297
1347
|
process.on("SIGINT", salir);
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "claqueta-mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Cliente de Claqueta: puente stdio para el servidor MCP remoto, comando setup y worker de la cola. Úsalo con npx en Claude Desktop o Claude Code.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": { "claqueta-mcp": "dist/cli.js" },
|
|
7
7
|
"files": ["dist/cli.js", "README.md", "LICENSE"],
|
|
@@ -10,19 +10,23 @@
|
|
|
10
10
|
"author": "Itzamnai",
|
|
11
11
|
"repository": {
|
|
12
12
|
"type": "git",
|
|
13
|
-
"url": "git+https://github.com/ajuarez93/claqueta-mcp.git"
|
|
14
|
-
"directory": "packages/cli"
|
|
13
|
+
"url": "git+https://github.com/ajuarez93/claqueta-mcp.git"
|
|
15
14
|
},
|
|
16
|
-
"homepage": "https://github.com/ajuarez93/claqueta-mcp
|
|
15
|
+
"homepage": "https://github.com/ajuarez93/claqueta-mcp#readme",
|
|
17
16
|
"bugs": { "url": "https://github.com/ajuarez93/claqueta-mcp/issues" },
|
|
18
17
|
"keywords": ["mcp", "model-context-protocol", "claqueta", "claude", "stdio", "bridge", "video"],
|
|
19
18
|
"publishConfig": { "access": "public" },
|
|
20
19
|
"scripts": {
|
|
21
20
|
"build": "node scripts/build.mjs",
|
|
22
21
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
23
|
-
"
|
|
22
|
+
"test": "vitest run",
|
|
23
|
+
"publicar:simulacro": "npm pack --dry-run",
|
|
24
|
+
"prepublishOnly": "npm run typecheck && npm test && npm run build"
|
|
24
25
|
},
|
|
25
26
|
"devDependencies": {
|
|
26
|
-
"
|
|
27
|
+
"@types/node": "^20.14.0",
|
|
28
|
+
"esbuild": "^0.24.0",
|
|
29
|
+
"typescript": "^5.6.0",
|
|
30
|
+
"vitest": "^2.1.0"
|
|
27
31
|
}
|
|
28
32
|
}
|