@redcumbrecl/cli 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -352,7 +352,7 @@ function mensajeEntornoLlaveInvalido(valor) {
352
352
  return `El entorno \xAB${recibido}\xBB no existe. Usa ${ENTORNOS_LLAVE.map((e) => `\xAB${e}\xBB`).join(" o ")}.`;
353
353
  }
354
354
  var PAQUETE_DEL_CLI = "@redcumbrecl/cli";
355
- var COMANDO_DE_ACTUALIZACION_DEL_CLI = `npx ${PAQUETE_DEL_CLI}@latest`;
355
+ var COMANDO_DE_ACTUALIZACION_DEL_CLI = `npx ${PAQUETE_DEL_CLI}@latest instalar`;
356
356
  var CODIGO_CLI_DESACTUALIZADO = "CLI_DESACTUALIZADO";
357
357
  var ALCANCES_LLAVE_VALIDAFIRMA = ["carpetas", "cuenta"];
358
358
  var ALCANCE_LLAVE_VALIDAFIRMA_REGISTRY = {
@@ -397,6 +397,7 @@ var SOLICITUD_CUENTA_CAMPOS = [
397
397
  ];
398
398
  var SOLICITUD_CUENTA_FINALIDAD = "solo para crear tu cuenta y contactarte";
399
399
  var SOLICITUD_CUENTA_URL_PRIVACIDAD = "https://redcumbre.cl/privacidad";
400
+ var SOLICITUD_CUENTA_URL_FORMULARIO_SITIO = "https://docs.redcumbre.cl/solicitar-cuenta/";
400
401
  var SOLICITUD_CUENTA_TEXTO_INFORMACION = `REDCUMBRE usa estos datos ${SOLICITUD_CUENTA_FINALIDAD}.`;
401
402
  var SOLICITUD_CUENTA_AVISO = `REDCUMBRE usa estos datos ${SOLICITUD_CUENTA_FINALIDAD}. Pol\xEDtica de Privacidad: ${SOLICITUD_CUENTA_URL_PRIVACIDAD}`;
402
403
 
@@ -469,6 +470,7 @@ var SERVICIOS_DE_PASO_A_PRODUCCION = [
469
470
  "reactivarEmisorDte",
470
471
  "cancelarCertificacionEmisorDte",
471
472
  "registrarEmisorDteEnPortalMipyme",
473
+ "volverEmisorDteAlPortalMipyme",
472
474
  "archivarEmisorTributario",
473
475
  "reactivarEmisorTributario"
474
476
  ],
@@ -855,6 +857,112 @@ function parClaveValor(texto2) {
855
857
  return [texto2.slice(0, i), texto2.slice(i + 1)];
856
858
  }
857
859
 
860
+ // src/nucleo/aviso-version.ts
861
+ import fs3 from "node:fs";
862
+ import path3 from "node:path";
863
+ var PAQUETE_CLI = PAQUETE_DEL_CLI;
864
+ var REGISTRO_NPM = "https://registry.npmjs.org/";
865
+ var urlUltimaVersion = (registro = REGISTRO_NPM) => `${registro.replace(/\/+$/, "")}/${PAQUETE_CLI}/latest`;
866
+ var TIEMPO_MAXIMO_MS = 1500;
867
+ var UN_DIA_MS = 24 * 60 * 60 * 1e3;
868
+ var rutaMarcaVersion = (carpeta) => path3.join(carpeta, "aviso-version.json");
869
+ function leerMarca(carpeta) {
870
+ try {
871
+ const marca = JSON.parse(fs3.readFileSync(rutaMarcaVersion(carpeta), "utf8"));
872
+ return typeof marca.revisadoEn === "string" ? { revisadoEn: marca.revisadoEn, ultima: typeof marca.ultima === "string" ? marca.ultima : null } : null;
873
+ } catch {
874
+ return null;
875
+ }
876
+ }
877
+ function escribirMarca(carpeta, marca) {
878
+ try {
879
+ fs3.mkdirSync(carpeta, { recursive: true, mode: 448 });
880
+ fs3.writeFileSync(rutaMarcaVersion(carpeta), `${JSON.stringify(marca)}
881
+ `);
882
+ } catch {
883
+ }
884
+ }
885
+ function compararVersiones(a, b) {
886
+ const partes = (v) => v.replace(/^v/, "").split("-")[0].split(".").map((n) => Number.parseInt(n, 10));
887
+ const pa = partes(a);
888
+ const pb = partes(b);
889
+ if ([...pa, ...pb].some((n) => !Number.isFinite(n))) return 0;
890
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
891
+ const d = (pa[i] ?? 0) - (pb[i] ?? 0);
892
+ if (d !== 0) return d > 0 ? 1 : -1;
893
+ }
894
+ return 0;
895
+ }
896
+ async function consultarRegistro(url, senal) {
897
+ const r = await fetch(url, { signal: senal, headers: { accept: "application/json" } });
898
+ if (!r.ok) return null;
899
+ const cuerpo = await r.json();
900
+ return typeof cuerpo.version === "string" ? cuerpo.version : null;
901
+ }
902
+ var COMANDO_ACTUALIZAR = "redcumbre actualizar";
903
+ var COMANDO_ACTUALIZAR_CONFIRMADO = `${COMANDO_ACTUALIZAR} --confirmar`;
904
+ async function ultimaVersionConocida(opciones) {
905
+ const marca = leerMarca(opciones.carpeta);
906
+ if (marca && opciones.ahora.getTime() - Date.parse(marca.revisadoEn) < UN_DIA_MS) return { ultima: marca.ultima, consultado: false };
907
+ let ultima = null;
908
+ try {
909
+ const senal = AbortSignal.timeout(TIEMPO_MAXIMO_MS);
910
+ ultima = opciones.consultar ? await opciones.consultar(senal) : await consultarRegistro(urlUltimaVersion(opciones.registro || void 0), senal);
911
+ } catch {
912
+ ultima = null;
913
+ }
914
+ escribirMarca(opciones.carpeta, { revisadoEn: opciones.ahora.toISOString(), ultima });
915
+ return { ultima, consultado: true };
916
+ }
917
+ async function avisarSiHayVersionNueva(opciones) {
918
+ const { ultima, consultado } = await ultimaVersionConocida(opciones);
919
+ if (consultado && ultima && compararVersiones(ultima, opciones.version) > 0) {
920
+ opciones.humano.write(`\u2139 Hay una versi\xF3n m\xE1s nueva del CLI: ${ultima} (tienes ${opciones.version}). Actual\xEDzala con \xAB${opciones.comando ?? COMANDO_ACTUALIZAR}\xBB, que deja al d\xEDa el CLI y la skill.
921
+ `);
922
+ }
923
+ }
924
+ async function actualizacionDisponible(opciones) {
925
+ const { ultima } = await ultimaVersionConocida(opciones);
926
+ if (!ultima || compararVersiones(ultima, opciones.version) <= 0) return null;
927
+ return { instalada: opciones.version, disponible: ultima, comando: COMANDO_ACTUALIZAR_CONFIRMADO };
928
+ }
929
+ var avisoDeActualizacion = (a) => `Hay una versi\xF3n m\xE1s nueva del CLI: ${a.disponible} (tienes ${a.instalada}). D\xEDselo a la persona y prop\xF3nle actualizar; si acepta, corre \xAB${a.comando}\xBB.`;
930
+ var SITIO_DOCS = PRODUCCION.docs;
931
+ var ARCHIVO_VERSION_MINIMA = "cli-version-minima.txt";
932
+ var COMANDO_DE_ACTUALIZACION = COMANDO_DE_ACTUALIZACION_DEL_CLI;
933
+ var VERSION_VALIDA = /^\d+\.\d+\.\d+$/;
934
+ function urlVersionMinima(env = process.env) {
935
+ return `${origenDeDocs(env)}/${ARCHIVO_VERSION_MINIMA}`;
936
+ }
937
+ async function leerArchivoMinimo(url, senal) {
938
+ const r = await fetch(url, { signal: senal, headers: { accept: "text/plain" }, credentials: "omit" });
939
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
940
+ return r.text();
941
+ }
942
+ async function exigirVersionMinima(opciones) {
943
+ const depurar = opciones.depurar ?? (() => void 0);
944
+ const url = urlVersionMinima(opciones.env);
945
+ let minima;
946
+ try {
947
+ const texto2 = await (opciones.consultar ?? leerArchivoMinimo)(url, AbortSignal.timeout(TIEMPO_MAXIMO_MS));
948
+ minima = texto2.trim();
949
+ } catch (error) {
950
+ depurar(`no pude leer la versi\xF3n m\xEDnima en ${url} (${error instanceof Error ? error.message : String(error)}); sigo sin comprobarla`);
951
+ return;
952
+ }
953
+ if (!VERSION_VALIDA.test(minima)) {
954
+ depurar(`la versi\xF3n m\xEDnima de ${url} no es una versi\xF3n (${JSON.stringify(minima.slice(0, 40))}); sigo sin comprobarla`);
955
+ return;
956
+ }
957
+ if (compararVersiones(minima, opciones.version) > 0) {
958
+ throw new ErrorCli(
959
+ `Este CLI (${opciones.version}) est\xE1 por debajo de la versi\xF3n m\xEDnima que se puede usar (${minima}). Actual\xEDzalo con \xAB${COMANDO_DE_ACTUALIZACION}\xBB.`,
960
+ 1,
961
+ { codigo: CODIGO_CLI_DESACTUALIZADO, comando: COMANDO_DE_ACTUALIZACION, datos: { version: opciones.version, minima } }
962
+ );
963
+ }
964
+ }
965
+
858
966
  // src/comandos/buscar.ts
859
967
  var SITIO_DE_DOCUMENTACION = PRODUCCION.docs;
860
968
  var RUTA_CON_LLAVE = "/global/busqueda";
@@ -904,7 +1012,7 @@ async function buscar(ctx, palabras) {
904
1012
  throw apuntandoAlSitio(error);
905
1013
  }
906
1014
  if (!Array.isArray(respuesta?.resultados)) {
907
- throw new ErrorCli("La b\xFAsqueda respondi\xF3 algo que el CLI no entiende (falta \xABresultados\xBB). Actualiza el CLI con \xABnpx @redcumbrecl/cli@latest\xBB y vuelve a intentarlo.", CODIGOS_DE_SALIDA.error, {
1015
+ throw new ErrorCli(`La b\xFAsqueda respondi\xF3 algo que el CLI no entiende (falta \xABresultados\xBB). Actualiza el CLI con \xAB${COMANDO_DE_ACTUALIZACION}\xBB y vuelve a intentarlo.`, CODIGOS_DE_SALIDA.error, {
908
1016
  codigo: "RESPUESTA_INESPERADA"
909
1017
  });
910
1018
  }
@@ -926,8 +1034,8 @@ async function buscar(ctx, palabras) {
926
1034
  }
927
1035
 
928
1036
  // src/comandos/api.ts
929
- import fs4 from "node:fs";
930
- import path4 from "node:path";
1037
+ import fs5 from "node:fs";
1038
+ import path5 from "node:path";
931
1039
 
932
1040
  // src/nucleo/confirmacion.ts
933
1041
  import { randomUUID } from "node:crypto";
@@ -1058,16 +1166,16 @@ function mostrarCobro(salida, cobro) {
1058
1166
  }
1059
1167
 
1060
1168
  // src/nucleo/documento.ts
1061
- import fs3 from "node:fs";
1062
- import path3 from "node:path";
1169
+ import fs4 from "node:fs";
1170
+ import path4 from "node:path";
1063
1171
  var METODOS = ["get", "post", "put", "patch", "delete"];
1064
- var rutaCopiaDocumento = (carpeta) => path3.join(carpeta, "api-docs.json");
1065
- var rutaEtagDocumento = (carpeta) => path3.join(carpeta, "api-docs.etag");
1172
+ var rutaCopiaDocumento = (carpeta) => path4.join(carpeta, "api-docs.json");
1173
+ var rutaEtagDocumento = (carpeta) => path4.join(carpeta, "api-docs.etag");
1066
1174
  function leerEtiqueta(carpeta) {
1067
1175
  const ruta = rutaEtagDocumento(carpeta);
1068
- if (!fs3.existsSync(ruta) || !fs3.existsSync(rutaCopiaDocumento(carpeta))) return null;
1176
+ if (!fs4.existsSync(ruta) || !fs4.existsSync(rutaCopiaDocumento(carpeta))) return null;
1069
1177
  try {
1070
- const datos = JSON.parse(fs3.readFileSync(ruta, "utf8"));
1178
+ const datos = JSON.parse(fs4.readFileSync(ruta, "utf8"));
1071
1179
  return typeof datos.api === "string" ? { api: datos.api, etag: typeof datos.etag === "string" ? datos.etag : null } : null;
1072
1180
  } catch {
1073
1181
  return null;
@@ -1075,15 +1183,15 @@ function leerEtiqueta(carpeta) {
1075
1183
  }
1076
1184
  function leerCopia(carpeta) {
1077
1185
  try {
1078
- return JSON.parse(fs3.readFileSync(rutaCopiaDocumento(carpeta), "utf8"));
1186
+ return JSON.parse(fs4.readFileSync(rutaCopiaDocumento(carpeta), "utf8"));
1079
1187
  } catch {
1080
1188
  return null;
1081
1189
  }
1082
1190
  }
1083
1191
  function guardarCopia(carpeta, api, texto2, etag) {
1084
- fs3.mkdirSync(carpeta, { recursive: true, mode: 448 });
1085
- fs3.writeFileSync(rutaCopiaDocumento(carpeta), texto2);
1086
- fs3.writeFileSync(rutaEtagDocumento(carpeta), `${JSON.stringify({ api, etag })}
1192
+ fs4.mkdirSync(carpeta, { recursive: true, mode: 448 });
1193
+ fs4.writeFileSync(rutaCopiaDocumento(carpeta), texto2);
1194
+ fs4.writeFileSync(rutaEtagDocumento(carpeta), `${JSON.stringify({ api, etag })}
1087
1195
  `);
1088
1196
  }
1089
1197
  var fechaLegible = (fecha) => fecha.toLocaleString("es-CL", { dateStyle: "medium", timeStyle: "short" });
@@ -1093,7 +1201,7 @@ async function cargarDocumento(cliente, carpeta, salida) {
1093
1201
  const usarCopiaSinRevalidar = (motivo) => {
1094
1202
  const crudo2 = copiaDelMismoApi ? leerCopia(carpeta) : null;
1095
1203
  if (!crudo2) throw new ErrorCli(`${motivo} No tengo una copia del documento del API para seguir sin \xE9l.`, CODIGOS_DE_SALIDA.api5xx, { codigo: "DOCUMENTO_NO_DISPONIBLE" });
1096
- const fecha = fs3.statSync(rutaCopiaDocumento(carpeta)).mtime;
1204
+ const fecha = fs4.statSync(rutaCopiaDocumento(carpeta)).mtime;
1097
1205
  salida.aviso(`${motivo} Uso la copia del documento del API del ${fechaLegible(fecha)}: puede no traer las operaciones m\xE1s nuevas.`);
1098
1206
  return { ...indexar(crudo2), copiaSinRevalidar: fecha };
1099
1207
  };
@@ -1185,13 +1293,51 @@ function buscarOperacion(documento, operationId) {
1185
1293
  const sugerencia = parecidas.length ? ` \xBFQuisiste decir ${parecidas.map((o) => o.operationId).join(", ")}?` : " Corre \xABredcumbre api buscar <texto>\xBB para encontrarla.";
1186
1294
  throw new ErrorCli(`El API no tiene la operaci\xF3n \xAB${operationId}\xBB.${sugerencia}`, CODIGOS_DE_SALIDA.uso, { codigo: "OPERACION_DESCONOCIDA" });
1187
1295
  }
1296
+ var sinTildes = (s) => s.normalize("NFD").replace(new RegExp("\\p{Diacritic}", "gu"), "").toLowerCase();
1297
+ var PESO_CAMPO = { resumen: 10, operationId: 6, ruta: 6, etiquetas: 4, descripcion: 2 };
1298
+ var CALIDAD = { palabra: 1, raiz: 0.8, fragmento: 0.4 };
1299
+ var PESO_EXTRA = 0.1;
1300
+ var SUFIJOS = ["aciones", "acion", "adores", "ador", "amiento", "ables", "able", "ibles", "ible", "ados", "adas", "ado", "ada", "ando", "iendo", "ar", "er", "ir", "es", "s"];
1301
+ function raizDe(palabra) {
1302
+ for (const sufijo of SUFIJOS) if (palabra.endsWith(sufijo) && palabra.length - sufijo.length >= 4) return palabra.slice(0, -sufijo.length);
1303
+ return palabra;
1304
+ }
1305
+ function palabrasDe(texto2) {
1306
+ return sinTildes(texto2.replace(/([a-z\d])([A-Z])/g, "$1 $2")).split(/[^a-z\d]+/).filter(Boolean);
1307
+ }
1308
+ function calidadEn(termino, raizTermino, palabras, textoPlano) {
1309
+ let mejor = 0;
1310
+ for (const palabra of palabras) {
1311
+ if (palabra === termino) return CALIDAD.palabra;
1312
+ if (raizTermino.length >= 4 && raizDe(palabra).startsWith(raizTermino)) mejor = Math.max(mejor, CALIDAD.raiz);
1313
+ }
1314
+ if (mejor === 0 && termino.length >= 3 && textoPlano.includes(termino)) mejor = CALIDAD.fragmento;
1315
+ return mejor;
1316
+ }
1188
1317
  function buscarOperaciones(documento, consulta) {
1189
- const normalizar = (s) => s.normalize("NFD").replace(new RegExp("\\p{Diacritic}", "gu"), "").toLowerCase();
1190
- const palabras = normalizar(consulta).split(/\s+/).filter(Boolean);
1191
- return documento.operaciones.filter((op) => {
1192
- const pajar = normalizar([op.operationId, op.resumen ?? "", op.descripcion ?? "", ...op.etiquetas].join(" "));
1193
- return palabras.every((p) => pajar.includes(p));
1318
+ const terminos = sinTildes(consulta).split(/\s+/).filter(Boolean);
1319
+ if (terminos.length === 0) return [];
1320
+ const raices = terminos.map(raizDe);
1321
+ const puntuadas = [];
1322
+ documento.operaciones.forEach((op, orden) => {
1323
+ const campos = {
1324
+ resumen: op.resumen ?? "",
1325
+ operationId: op.operationId,
1326
+ ruta: op.ruta,
1327
+ etiquetas: op.etiquetas.join(" "),
1328
+ descripcion: op.descripcion ?? ""
1329
+ };
1330
+ const indice = Object.keys(campos).map((campo) => ({ campo, palabras: palabrasDe(campos[campo]), plano: sinTildes(campos[campo]) }));
1331
+ let puntaje = 0;
1332
+ for (const [i, termino] of terminos.entries()) {
1333
+ const aportes = indice.map(({ campo, palabras, plano }) => PESO_CAMPO[campo] * calidadEn(termino, raices[i], palabras, plano)).filter((a) => a > 0);
1334
+ if (aportes.length === 0) return;
1335
+ const mejor = Math.max(...aportes);
1336
+ puntaje += mejor + PESO_EXTRA * (aportes.reduce((a, b) => a + b, 0) - mejor);
1337
+ }
1338
+ puntuadas.push({ op, puntaje, orden });
1194
1339
  });
1340
+ return puntuadas.sort((a, b) => b.puntaje - a.puntaje || a.orden - b.orden).map((p) => p.op);
1195
1341
  }
1196
1342
 
1197
1343
  // src/nucleo/cuerpo-sin-credenciales.ts
@@ -1446,11 +1592,11 @@ function armarRuta(op, slug, params) {
1446
1592
  }
1447
1593
  function leerCuerpo(valor) {
1448
1594
  let texto2;
1449
- if (valor === "-") texto2 = fs4.readFileSync(0, "utf8");
1595
+ if (valor === "-") texto2 = fs5.readFileSync(0, "utf8");
1450
1596
  else if (valor.startsWith("@")) {
1451
1597
  const archivo = valor.slice(1);
1452
- if (!fs4.existsSync(archivo)) throw errorDeUso(`No encuentro el archivo del cuerpo: ${archivo}`);
1453
- texto2 = fs4.readFileSync(archivo, "utf8");
1598
+ if (!fs5.existsSync(archivo)) throw errorDeUso(`No encuentro el archivo del cuerpo: ${archivo}`);
1599
+ texto2 = fs5.readFileSync(archivo, "utf8");
1454
1600
  } else texto2 = valor;
1455
1601
  let cuerpo;
1456
1602
  try {
@@ -1489,8 +1635,8 @@ async function una(ctx, llave, op, ruta, query, cuerpo, salidaArchivo) {
1489
1635
  if (r.bytes === null) return r.json;
1490
1636
  const tipo = r.headers.get("content-type") ?? "application/octet-stream";
1491
1637
  const extension = tipo.includes("pdf") ? "pdf" : tipo.includes("xml") ? "xml" : tipo.includes("zip") ? "zip" : "bin";
1492
- const archivo = path4.resolve(ctx.cwd, salidaArchivo ?? `${op.operationId}.${extension}`);
1493
- fs4.writeFileSync(archivo, r.bytes);
1638
+ const archivo = path5.resolve(ctx.cwd, salidaArchivo ?? `${op.operationId}.${extension}`);
1639
+ fs5.writeFileSync(archivo, r.bytes);
1494
1640
  ctx.salida.linea(`\u2713 Guard\xE9 ${r.bytes.length} bytes en ${archivo}`);
1495
1641
  ctx.salida.resultado({ archivo, bytes: r.bytes.length, tipo });
1496
1642
  return void 0;
@@ -1537,114 +1683,6 @@ function recortar(valor, campos) {
1537
1683
  // src/comandos/doctor.ts
1538
1684
  import fs6 from "node:fs";
1539
1685
  import path6 from "node:path";
1540
-
1541
- // src/nucleo/aviso-version.ts
1542
- import fs5 from "node:fs";
1543
- import path5 from "node:path";
1544
- var PAQUETE_CLI = PAQUETE_DEL_CLI;
1545
- var REGISTRO_NPM = "https://registry.npmjs.org/";
1546
- var urlUltimaVersion = (registro = REGISTRO_NPM) => `${registro.replace(/\/+$/, "")}/${PAQUETE_CLI}/latest`;
1547
- var TIEMPO_MAXIMO_MS = 1500;
1548
- var UN_DIA_MS = 24 * 60 * 60 * 1e3;
1549
- var rutaMarcaVersion = (carpeta) => path5.join(carpeta, "aviso-version.json");
1550
- function leerMarca(carpeta) {
1551
- try {
1552
- const marca = JSON.parse(fs5.readFileSync(rutaMarcaVersion(carpeta), "utf8"));
1553
- return typeof marca.revisadoEn === "string" ? { revisadoEn: marca.revisadoEn, ultima: typeof marca.ultima === "string" ? marca.ultima : null } : null;
1554
- } catch {
1555
- return null;
1556
- }
1557
- }
1558
- function escribirMarca(carpeta, marca) {
1559
- try {
1560
- fs5.mkdirSync(carpeta, { recursive: true, mode: 448 });
1561
- fs5.writeFileSync(rutaMarcaVersion(carpeta), `${JSON.stringify(marca)}
1562
- `);
1563
- } catch {
1564
- }
1565
- }
1566
- function compararVersiones(a, b) {
1567
- const partes = (v) => v.replace(/^v/, "").split("-")[0].split(".").map((n) => Number.parseInt(n, 10));
1568
- const pa = partes(a);
1569
- const pb = partes(b);
1570
- if ([...pa, ...pb].some((n) => !Number.isFinite(n))) return 0;
1571
- for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
1572
- const d = (pa[i] ?? 0) - (pb[i] ?? 0);
1573
- if (d !== 0) return d > 0 ? 1 : -1;
1574
- }
1575
- return 0;
1576
- }
1577
- async function consultarRegistro(url, senal) {
1578
- const r = await fetch(url, { signal: senal, headers: { accept: "application/json" } });
1579
- if (!r.ok) return null;
1580
- const cuerpo = await r.json();
1581
- return typeof cuerpo.version === "string" ? cuerpo.version : null;
1582
- }
1583
- var COMANDO_ACTUALIZAR = "redcumbre actualizar";
1584
- var COMANDO_ACTUALIZAR_CONFIRMADO = `${COMANDO_ACTUALIZAR} --confirmar`;
1585
- async function ultimaVersionConocida(opciones) {
1586
- const marca = leerMarca(opciones.carpeta);
1587
- if (marca && opciones.ahora.getTime() - Date.parse(marca.revisadoEn) < UN_DIA_MS) return { ultima: marca.ultima, consultado: false };
1588
- let ultima = null;
1589
- try {
1590
- const senal = AbortSignal.timeout(TIEMPO_MAXIMO_MS);
1591
- ultima = opciones.consultar ? await opciones.consultar(senal) : await consultarRegistro(urlUltimaVersion(opciones.registro || void 0), senal);
1592
- } catch {
1593
- ultima = null;
1594
- }
1595
- escribirMarca(opciones.carpeta, { revisadoEn: opciones.ahora.toISOString(), ultima });
1596
- return { ultima, consultado: true };
1597
- }
1598
- async function avisarSiHayVersionNueva(opciones) {
1599
- const { ultima, consultado } = await ultimaVersionConocida(opciones);
1600
- if (consultado && ultima && compararVersiones(ultima, opciones.version) > 0) {
1601
- opciones.humano.write(`\u2139 Hay una versi\xF3n m\xE1s nueva del CLI: ${ultima} (tienes ${opciones.version}). Actual\xEDzala con \xAB${COMANDO_ACTUALIZAR}\xBB, que deja al d\xEDa el CLI y la skill.
1602
- `);
1603
- }
1604
- }
1605
- async function actualizacionDisponible(opciones) {
1606
- const { ultima } = await ultimaVersionConocida(opciones);
1607
- if (!ultima || compararVersiones(ultima, opciones.version) <= 0) return null;
1608
- return { instalada: opciones.version, disponible: ultima, comando: COMANDO_ACTUALIZAR_CONFIRMADO };
1609
- }
1610
- var avisoDeActualizacion = (a) => `Hay una versi\xF3n m\xE1s nueva del CLI: ${a.disponible} (tienes ${a.instalada}). D\xEDselo a la persona y prop\xF3nle actualizar; si acepta, corre \xAB${a.comando}\xBB.`;
1611
- var SITIO_DOCS = PRODUCCION.docs;
1612
- var ARCHIVO_VERSION_MINIMA = "cli-version-minima.txt";
1613
- var COMANDO_DE_ACTUALIZACION = COMANDO_DE_ACTUALIZACION_DEL_CLI;
1614
- var VERSION_VALIDA = /^\d+\.\d+\.\d+$/;
1615
- function urlVersionMinima(env = process.env) {
1616
- return `${origenDeDocs(env)}/${ARCHIVO_VERSION_MINIMA}`;
1617
- }
1618
- async function leerArchivoMinimo(url, senal) {
1619
- const r = await fetch(url, { signal: senal, headers: { accept: "text/plain" }, credentials: "omit" });
1620
- if (!r.ok) throw new Error(`HTTP ${r.status}`);
1621
- return r.text();
1622
- }
1623
- async function exigirVersionMinima(opciones) {
1624
- const depurar = opciones.depurar ?? (() => void 0);
1625
- const url = urlVersionMinima(opciones.env);
1626
- let minima;
1627
- try {
1628
- const texto2 = await (opciones.consultar ?? leerArchivoMinimo)(url, AbortSignal.timeout(TIEMPO_MAXIMO_MS));
1629
- minima = texto2.trim();
1630
- } catch (error) {
1631
- depurar(`no pude leer la versi\xF3n m\xEDnima en ${url} (${error instanceof Error ? error.message : String(error)}); sigo sin comprobarla`);
1632
- return;
1633
- }
1634
- if (!VERSION_VALIDA.test(minima)) {
1635
- depurar(`la versi\xF3n m\xEDnima de ${url} no es una versi\xF3n (${JSON.stringify(minima.slice(0, 40))}); sigo sin comprobarla`);
1636
- return;
1637
- }
1638
- if (compararVersiones(minima, opciones.version) > 0) {
1639
- throw new ErrorCli(
1640
- `Este CLI (${opciones.version}) est\xE1 por debajo de la versi\xF3n m\xEDnima que se puede usar (${minima}). Actual\xEDzalo con \xAB${COMANDO_DE_ACTUALIZACION}\xBB.`,
1641
- 1,
1642
- { codigo: CODIGO_CLI_DESACTUALIZADO, comando: COMANDO_DE_ACTUALIZACION, datos: { version: opciones.version, minima } }
1643
- );
1644
- }
1645
- }
1646
-
1647
- // src/comandos/doctor.ts
1648
1686
  async function doctor(ctx) {
1649
1687
  const { salida, proyecto } = ctx;
1650
1688
  const revisiones = [];
@@ -1738,8 +1776,8 @@ async function panel(ctx, opciones) {
1738
1776
  }
1739
1777
 
1740
1778
  // src/comandos/emisores.ts
1741
- import fs9 from "node:fs";
1742
- import path9 from "node:path";
1779
+ import fs10 from "node:fs";
1780
+ import path11 from "node:path";
1743
1781
 
1744
1782
  // src/comandos/emisores-operaciones.ts
1745
1783
  var RUT_FILTRO = { bandera: "--rut <rut>", obligatoria: false, tipo: "texto", destino: { en: "consulta", nombre: "rut" } };
@@ -2000,19 +2038,6 @@ var OPERACIONES_EMISORES = [
2000
2038
  },
2001
2039
  {
2002
2040
  // 21
2003
- comando: ["dte", "certificacion", "solicitar"],
2004
- operationId: "crearSolicitudCertificacionBoletasEmisorDte",
2005
- metodo: "POST",
2006
- ruta: "/{tenantSlug}/emisores/{id}/solicitar-certificacion",
2007
- argumentos: ["id"],
2008
- banderas: [TIPOS_DE_CERTIFICACION, CORREO_DE_CONTACTO, TELEFONO_DE_CONTACTO],
2009
- salida: "accion",
2010
- hecho: "Certificaci\xF3n solicitada.",
2011
- confirmacion: "escrita",
2012
- aviso: "Esto le pide al SII certificar al contribuyente, con el RUT de su representante legal."
2013
- },
2014
- {
2015
- // 22
2016
2041
  comando: ["dte", "certificacion", "certificar-tipos"],
2017
2042
  operationId: "crearSolicitudCertificacionTiposEmisorDte",
2018
2043
  metodo: "POST",
@@ -2025,7 +2050,7 @@ var OPERACIONES_EMISORES = [
2025
2050
  aviso: "Esto le pide al SII certificar al contribuyente, con el RUT de su representante legal."
2026
2051
  },
2027
2052
  {
2028
- // 23
2053
+ // 22
2029
2054
  comando: ["dte", "migrar"],
2030
2055
  operationId: "crearSolicitudMigracionEmisorDte",
2031
2056
  metodo: "POST",
@@ -2038,7 +2063,7 @@ var OPERACIONES_EMISORES = [
2038
2063
  aviso: "Esto le pide al SII migrar el sistema de facturaci\xF3n del contribuyente. Puede dejar sin uso los folios que tenga."
2039
2064
  },
2040
2065
  {
2041
- // 24
2066
+ // 23
2042
2067
  comando: ["dte", "certificacion", "desistir"],
2043
2068
  operationId: "cancelarCertificacionEmisorDte",
2044
2069
  metodo: "POST",
@@ -2051,7 +2076,7 @@ var OPERACIONES_EMISORES = [
2051
2076
  aviso: "Esto archiva el emisor y cierra sus solicitudes de certificaci\xF3n."
2052
2077
  },
2053
2078
  {
2054
- // 25
2079
+ // 24
2055
2080
  comando: ["dte", "mipyme", "habilitar"],
2056
2081
  operationId: "registrarEmisorDteEnPortalMipyme",
2057
2082
  metodo: "POST",
@@ -2064,7 +2089,7 @@ var OPERACIONES_EMISORES = [
2064
2089
  aviso: "Esto inscribe al contribuyente en el Portal MiPyme del SII. Puede dejar sin uso los folios de mercado que tenga."
2065
2090
  },
2066
2091
  {
2067
- // 26
2092
+ // 25
2068
2093
  comando: ["dte", "ambiente"],
2069
2094
  operationId: "cambiarAmbienteTipoEmisorDte",
2070
2095
  metodo: "PATCH",
@@ -2077,7 +2102,7 @@ var OPERACIONES_EMISORES = [
2077
2102
  aviso: "Esto cambia el ambiente del SII por el que sale ese tipo de documento."
2078
2103
  },
2079
2104
  {
2080
- // 27
2105
+ // 26
2081
2106
  comando: ["dte", "archivar"],
2082
2107
  operationId: "archivarEmisorDte",
2083
2108
  metodo: "DELETE",
@@ -2091,7 +2116,7 @@ var OPERACIONES_EMISORES = [
2091
2116
  aviso: "Esto saca al emisor de la operaci\xF3n y deja de cobrarse."
2092
2117
  },
2093
2118
  {
2094
- // 28
2119
+ // 27
2095
2120
  comando: ["tributarios", "archivar"],
2096
2121
  operationId: "archivarEmisorTributario",
2097
2122
  metodo: "DELETE",
@@ -2105,7 +2130,7 @@ var OPERACIONES_EMISORES = [
2105
2130
  aviso: "Esto saca al emisor de la operaci\xF3n y deja de cobrarse."
2106
2131
  },
2107
2132
  {
2108
- // 29
2133
+ // 28
2109
2134
  comando: ["tributarios", "listar"],
2110
2135
  operationId: "listarEmisoresTributarios",
2111
2136
  metodo: "GET",
@@ -2117,7 +2142,7 @@ var OPERACIONES_EMISORES = [
2117
2142
  confirmacion: "efecto"
2118
2143
  },
2119
2144
  {
2120
- // 30
2145
+ // 29
2121
2146
  comando: ["tributarios", "por-defecto"],
2122
2147
  operationId: "obtenerEmisorTributarioPorDefecto",
2123
2148
  metodo: "GET",
@@ -2128,7 +2153,7 @@ var OPERACIONES_EMISORES = [
2128
2153
  confirmacion: "efecto"
2129
2154
  },
2130
2155
  {
2131
- // 31
2156
+ // 30
2132
2157
  comando: ["tributarios", "existe"],
2133
2158
  operationId: "consultarRutEmisorTributario",
2134
2159
  metodo: "GET",
@@ -2139,7 +2164,7 @@ var OPERACIONES_EMISORES = [
2139
2164
  confirmacion: "efecto"
2140
2165
  },
2141
2166
  {
2142
- // 32
2167
+ // 31
2143
2168
  comando: ["tributarios", "ver"],
2144
2169
  operationId: "obtenerEmisorTributario",
2145
2170
  metodo: "GET",
@@ -2150,7 +2175,7 @@ var OPERACIONES_EMISORES = [
2150
2175
  confirmacion: "efecto"
2151
2176
  },
2152
2177
  {
2153
- // 33
2178
+ // 32
2154
2179
  comando: ["tributarios", "logo", "ver"],
2155
2180
  operationId: "obtenerLogoEmisorTributario",
2156
2181
  metodo: "GET",
@@ -2161,7 +2186,7 @@ var OPERACIONES_EMISORES = [
2161
2186
  confirmacion: "efecto"
2162
2187
  },
2163
2188
  {
2164
- // 34
2189
+ // 33
2165
2190
  comando: ["tributarios", "certificado"],
2166
2191
  operationId: "obtenerCertificadoEmisorTributario",
2167
2192
  metodo: "GET",
@@ -2172,7 +2197,7 @@ var OPERACIONES_EMISORES = [
2172
2197
  confirmacion: "efecto"
2173
2198
  },
2174
2199
  {
2175
- // 35
2200
+ // 34
2176
2201
  comando: ["tributarios", "editar"],
2177
2202
  operationId: "actualizarEmisorTributario",
2178
2203
  metodo: "PATCH",
@@ -2184,7 +2209,7 @@ var OPERACIONES_EMISORES = [
2184
2209
  confirmacion: "efecto"
2185
2210
  },
2186
2211
  {
2187
- // 36
2212
+ // 35
2188
2213
  comando: ["tributarios", "fijar-por-defecto"],
2189
2214
  operationId: "cambiarEmisorTributarioPorDefecto",
2190
2215
  metodo: "PATCH",
@@ -2196,7 +2221,7 @@ var OPERACIONES_EMISORES = [
2196
2221
  confirmacion: "efecto"
2197
2222
  },
2198
2223
  {
2199
- // 37
2224
+ // 36
2200
2225
  comando: ["tributarios", "reactivar"],
2201
2226
  operationId: "reactivarEmisorTributario",
2202
2227
  metodo: "PATCH",
@@ -2208,7 +2233,7 @@ var OPERACIONES_EMISORES = [
2208
2233
  confirmacion: "efecto"
2209
2234
  },
2210
2235
  {
2211
- // 38
2236
+ // 37
2212
2237
  comando: ["tributarios", "logo", "subir"],
2213
2238
  operationId: "actualizarLogoEmisorTributario",
2214
2239
  metodo: "POST",
@@ -2220,7 +2245,7 @@ var OPERACIONES_EMISORES = [
2220
2245
  confirmacion: "efecto"
2221
2246
  },
2222
2247
  {
2223
- // 39
2248
+ // 38
2224
2249
  comando: ["tributarios", "logo", "quitar"],
2225
2250
  operationId: "eliminarLogoEmisorTributario",
2226
2251
  metodo: "DELETE",
@@ -2232,7 +2257,7 @@ var OPERACIONES_EMISORES = [
2232
2257
  confirmacion: "efecto"
2233
2258
  },
2234
2259
  {
2235
- // 40
2260
+ // 39
2236
2261
  comando: ["sucursales", "listar"],
2237
2262
  operationId: "listarSucursalesEmisorDte",
2238
2263
  metodo: "GET",
@@ -2244,7 +2269,7 @@ var OPERACIONES_EMISORES = [
2244
2269
  confirmacion: "efecto"
2245
2270
  },
2246
2271
  {
2247
- // 41
2272
+ // 40
2248
2273
  comando: ["sucursales", "crear"],
2249
2274
  operationId: "crearSucursalEmisorDte",
2250
2275
  metodo: "POST",
@@ -2256,7 +2281,7 @@ var OPERACIONES_EMISORES = [
2256
2281
  confirmacion: "efecto"
2257
2282
  },
2258
2283
  {
2259
- // 42
2284
+ // 41
2260
2285
  comando: ["sucursales", "editar"],
2261
2286
  operationId: "actualizarSucursalEmisorDte",
2262
2287
  metodo: "PATCH",
@@ -2268,7 +2293,7 @@ var OPERACIONES_EMISORES = [
2268
2293
  confirmacion: "efecto"
2269
2294
  },
2270
2295
  {
2271
- // 43
2296
+ // 42
2272
2297
  comando: ["sucursales", "desactivar"],
2273
2298
  operationId: "desactivarSucursalEmisorDte",
2274
2299
  metodo: "DELETE",
@@ -2280,7 +2305,7 @@ var OPERACIONES_EMISORES = [
2280
2305
  confirmacion: "efecto"
2281
2306
  },
2282
2307
  {
2283
- // 44
2308
+ // 43
2284
2309
  comando: ["representantes", "listar"],
2285
2310
  operationId: "listarRepresentantesLegales",
2286
2311
  metodo: "GET",
@@ -2292,7 +2317,7 @@ var OPERACIONES_EMISORES = [
2292
2317
  confirmacion: "efecto"
2293
2318
  },
2294
2319
  {
2295
- // 45
2320
+ // 44
2296
2321
  comando: ["dte", "sincronizar"],
2297
2322
  operationId: "actualizarEmisorDteDesdeSii",
2298
2323
  metodo: "POST",
@@ -2303,7 +2328,7 @@ var OPERACIONES_EMISORES = [
2303
2328
  confirmacion: "efecto"
2304
2329
  },
2305
2330
  {
2306
- // 46
2331
+ // 45
2307
2332
  comando: ["dte", "credencial", "reintentar"],
2308
2333
  operationId: "reintentarCredencialPortalEmisorDte",
2309
2334
  metodo: "POST",
@@ -2314,7 +2339,7 @@ var OPERACIONES_EMISORES = [
2314
2339
  confirmacion: "efecto"
2315
2340
  },
2316
2341
  {
2317
- // 47
2342
+ // 46
2318
2343
  comando: ["tributarios", "credencial", "reintentar"],
2319
2344
  operationId: "reintentarCredencialEmisorTributario",
2320
2345
  metodo: "POST",
@@ -2325,7 +2350,7 @@ var OPERACIONES_EMISORES = [
2325
2350
  confirmacion: "efecto"
2326
2351
  },
2327
2352
  {
2328
- // 48
2353
+ // 47
2329
2354
  comando: ["revocar"],
2330
2355
  operationId: "revocarEmisorTokenizado",
2331
2356
  metodo: "POST",
@@ -2337,6 +2362,19 @@ var OPERACIONES_EMISORES = [
2337
2362
  hecho: "Emisor revocado.",
2338
2363
  confirmacion: "escrita",
2339
2364
  aviso: "Esto revoca la autorizaci\xF3n y elimina sus credenciales de inmediato."
2365
+ },
2366
+ {
2367
+ // 48
2368
+ comando: ["dte", "volver-a-mipyme"],
2369
+ operationId: "volverEmisorDteAlPortalMipyme",
2370
+ metodo: "POST",
2371
+ ruta: "/{tenantSlug}/emisores/{id}/volver-a-mipyme",
2372
+ argumentos: ["id"],
2373
+ banderas: [RUT_DE_CONFIRMACION],
2374
+ salida: "accion",
2375
+ hecho: "Emisor vuelto al Portal MiPyme.",
2376
+ confirmacion: "escrita",
2377
+ aviso: "Vuelves este RUT al Portal MiPyme en TODAS las empresas que lo usan: se inscribe ante el SII, sus emisores de facturaci\xF3n pasan a Portal MiPyme, se pierde la certificaci\xF3n propia de facturas (33, 34, 43, 46, 52, 56, 61) y se anulan sus folios de facturaci\xF3n de producci\xF3n. Volver a certificarlo puede tener costo. Las boletas no cambian."
2340
2378
  }
2341
2379
  ];
2342
2380
 
@@ -2870,27 +2908,106 @@ async function abrirCon(programa2, destino) {
2870
2908
  });
2871
2909
  }
2872
2910
 
2873
- // src/nucleo/skill.ts
2874
- import { createHash, randomBytes } from "node:crypto";
2911
+ // src/nucleo/instalacion-del-cli.ts
2912
+ import { spawnSync as spawnSync2 } from "node:child_process";
2875
2913
  import fs8 from "node:fs";
2876
2914
  import path8 from "node:path";
2877
2915
  import { fileURLToPath } from "node:url";
2916
+ var real = (ruta) => {
2917
+ try {
2918
+ return fs8.realpathSync(ruta);
2919
+ } catch {
2920
+ return null;
2921
+ }
2922
+ };
2923
+ var dentroDe = (ruta, carpeta) => ruta === carpeta || ruta.startsWith(carpeta + path8.sep);
2924
+ var correPorNpx = (bundle) => (real(bundle) ?? path8.resolve(bundle)).split(path8.sep).includes("_npx");
2925
+ function detectarInstalacion(bundle, raizGlobal) {
2926
+ const bundleReal = real(bundle) ?? path8.resolve(bundle);
2927
+ if (correPorNpx(bundleReal)) return { forma: "npx" };
2928
+ for (const [gestor, forma] of [["npm", "npm-global"], ["pnpm", "pnpm-global"]]) {
2929
+ const raiz = raizGlobal(gestor);
2930
+ const carpeta = raiz ? real(path8.join(raiz, ...PAQUETE_DEL_CLI.split("/"))) : null;
2931
+ if (carpeta && dentroDe(bundleReal, carpeta)) return { forma, carpetaDelPaquete: carpeta };
2932
+ }
2933
+ const marcaDeDependencia = ["node_modules", ...PAQUETE_DEL_CLI.split("/")].join(path8.sep);
2934
+ if (bundleReal.includes(`${path8.sep}${marcaDeDependencia}${path8.sep}`)) {
2935
+ return { forma: "no-reconocida", motivo: `el CLI est\xE1 instalado como dependencia de un proyecto (${bundleReal}): actual\xEDzalo con el gestor de ese proyecto, que es quien decide su versi\xF3n` };
2936
+ }
2937
+ return { forma: "no-reconocida", motivo: `el CLI que corre (${bundleReal}) no est\xE1 en la cach\xE9 de npx ni en la carpeta global de npm o de pnpm` };
2938
+ }
2939
+ function comandoDeActualizacion(forma, version, registro) {
2940
+ const paquete = `${PAQUETE_DEL_CLI}@${version}`;
2941
+ const conRegistro = registro ? [`--registry=${registro}`] : [];
2942
+ if (forma === "pnpm-global") return { comando: "pnpm", args: ["add", "--global", ...conRegistro, paquete] };
2943
+ return { comando: "npm", args: ["install", "--global", ...conRegistro, paquete] };
2944
+ }
2945
+ var legible = (c) => [c.comando, ...c.args].join(" ");
2946
+ var comandoInstalarPorNpx = (version, confirmado) => `npx ${PAQUETE_DEL_CLI}@${version} instalar${confirmado ? " --confirmar" : ""}`;
2947
+ var prefijoPorNpx = (version) => `npx ${PAQUETE_DEL_CLI}@${version}`;
2948
+ function ejecutarDeVerdad(comando2, args, opciones) {
2949
+ const r = spawnSync2(comando2, args, { cwd: opciones.cwd, env: opciones.env, encoding: "utf8", shell: process.platform === "win32", timeout: 10 * 6e4 });
2950
+ return { status: r.status, stdout: r.stdout ?? "", stderr: r.stderr ?? (r.error ? r.error.message : "") };
2951
+ }
2952
+ function entornoDeActualizacion(ctx) {
2953
+ const registro = ctx.env.REDCUMBRE_NPM_REGISTRY || void 0;
2954
+ return {
2955
+ bundle: fileURLToPath(import.meta.url),
2956
+ ejecutar: ejecutarDeVerdad,
2957
+ raizGlobal(gestor) {
2958
+ const r = ejecutarDeVerdad(gestor, ["root", "--global"], { cwd: ctx.cwd, env: ctx.env });
2959
+ const raiz = r.stdout.trim().split(/\r?\n/).pop() ?? "";
2960
+ return r.status === 0 && raiz ? raiz : null;
2961
+ },
2962
+ async consultarUltima() {
2963
+ const respuesta = await fetch(urlUltimaVersion(registro), { signal: AbortSignal.timeout(1e4), headers: { accept: "application/json" } });
2964
+ if (!respuesta.ok) throw new Error(`el registro respondi\xF3 ${respuesta.status}`);
2965
+ const cuerpo = await respuesta.json();
2966
+ return typeof cuerpo.version === "string" ? cuerpo.version : null;
2967
+ }
2968
+ };
2969
+ }
2970
+ var VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
2971
+ function entornoSinNpx(env) {
2972
+ const limpio = { ...env };
2973
+ for (const clave of Object.keys(limpio).filter((k) => k.toUpperCase() === "PATH")) {
2974
+ limpio[clave] = (limpio[clave] ?? "").split(path8.delimiter).filter((carpeta) => carpeta && !carpeta.split(/[\\/]/).includes("_npx")).join(path8.delimiter);
2975
+ }
2976
+ return limpio;
2977
+ }
2978
+ function versionEnElPath(entorno, opciones) {
2979
+ const r = entorno.ejecutar("redcumbre", ["--version"], { cwd: opciones.cwd, env: entornoSinNpx(opciones.env) });
2980
+ const version = r.stdout.trim().split(/\r?\n/).pop()?.trim() ?? "";
2981
+ return r.status === 0 && VERSION.test(version) ? version : null;
2982
+ }
2983
+ function carpetaDeEjecutablesDeNpm(entorno, opciones) {
2984
+ const r = entorno.ejecutar("npm", ["prefix", "--global"], opciones);
2985
+ const prefijo = r.stdout.trim().split(/\r?\n/).pop()?.trim() ?? "";
2986
+ if (r.status !== 0 || !prefijo) return null;
2987
+ return process.platform === "win32" ? prefijo : path8.join(prefijo, "bin");
2988
+ }
2989
+
2990
+ // src/nucleo/skill.ts
2991
+ import { createHash, randomBytes } from "node:crypto";
2992
+ import fs9 from "node:fs";
2993
+ import path9 from "node:path";
2994
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
2878
2995
  var NOMBRE_SKILL = "redcumbre";
2879
2996
  var MARCA_INICIO = "<!-- redcumbre:inicio -->";
2880
2997
  var MARCA_FIN = "<!-- redcumbre:fin -->";
2881
2998
  var sha256 = (texto2) => createHash("sha256").update(texto2).digest("hex");
2882
- function carpetaDeLaSkill(aqui = path8.dirname(fileURLToPath(import.meta.url))) {
2883
- const candidatas = [path8.join(aqui, "skill"), path8.join(aqui, "..", "skill"), path8.join(aqui, "..", "..", "skill")];
2999
+ function carpetaDeLaSkill(aqui = path9.dirname(fileURLToPath2(import.meta.url))) {
3000
+ const candidatas = [path9.join(aqui, "skill"), path9.join(aqui, "..", "skill"), path9.join(aqui, "..", "..", "skill")];
2884
3001
  for (const candidata of candidatas) {
2885
- if (fs8.existsSync(path8.join(candidata, NOMBRE_SKILL, "SKILL.md"))) return candidata;
3002
+ if (fs9.existsSync(path9.join(candidata, NOMBRE_SKILL, "SKILL.md"))) return candidata;
2886
3003
  }
2887
- throw new ErrorCli("El paquete del CLI est\xE1 incompleto: no encuentro la skill de REDCUMBRE. Reinstala el CLI con \xABnpx @redcumbrecl/cli@latest\xBB.", CODIGOS_DE_SALIDA.error, {
3004
+ throw new ErrorCli(`El paquete del CLI est\xE1 incompleto: no encuentro la skill de REDCUMBRE. Reinstala el CLI con \xAB${COMANDO_DE_ACTUALIZACION}\xBB.`, CODIGOS_DE_SALIDA.error, {
2888
3005
  codigo: "PAQUETE_INCOMPLETO"
2889
3006
  });
2890
3007
  }
2891
3008
  function contenidoEmpaquetado(fuente) {
2892
3009
  const carpeta = fuente ?? carpetaDeLaSkill();
2893
- return fs8.readFileSync(path8.join(carpeta, NOMBRE_SKILL, "SKILL.md"), "utf8");
3010
+ return fs9.readFileSync(path9.join(carpeta, NOMBRE_SKILL, "SKILL.md"), "utf8");
2894
3011
  }
2895
3012
  var LINEA_DE_VERSION = /^<!-- redcumbre-cli: (\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?) -->$/m;
2896
3013
  var FRONTMATTER = /^---\r?\n[\s\S]*?\r?\n---\r?\n/;
@@ -2898,7 +3015,7 @@ var lineaDeVersion = (version) => `<!-- redcumbre-cli: ${version} -->`;
2898
3015
  function contenidoParaInstalar(fuente, version) {
2899
3016
  const frontmatter = fuente.match(FRONTMATTER);
2900
3017
  if (!frontmatter) {
2901
- throw new ErrorCli("El paquete del CLI est\xE1 incompleto: la skill de REDCUMBRE no trae su frontmatter. Reinstala el CLI con \xABnpx @redcumbrecl/cli@latest\xBB.", CODIGOS_DE_SALIDA.error, {
3018
+ throw new ErrorCli(`El paquete del CLI est\xE1 incompleto: la skill de REDCUMBRE no trae su frontmatter. Reinstala el CLI con \xAB${COMANDO_DE_ACTUALIZACION}\xBB.`, CODIGOS_DE_SALIDA.error, {
2902
3019
  codigo: "PAQUETE_INCOMPLETO"
2903
3020
  });
2904
3021
  }
@@ -2934,13 +3051,13 @@ function conReintentoEnWindows(operacion, opciones = {}) {
2934
3051
  }
2935
3052
  }
2936
3053
  function escribirAtomico(ruta, contenido) {
2937
- fs8.mkdirSync(path8.dirname(ruta), { recursive: true });
3054
+ fs9.mkdirSync(path9.dirname(ruta), { recursive: true });
2938
3055
  const temporal = `${ruta}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
2939
3056
  try {
2940
- fs8.writeFileSync(temporal, contenido);
2941
- conReintentoEnWindows(() => fs8.renameSync(temporal, ruta));
3057
+ fs9.writeFileSync(temporal, contenido);
3058
+ conReintentoEnWindows(() => fs9.renameSync(temporal, ruta));
2942
3059
  } catch (error) {
2943
- fs8.rmSync(temporal, { force: true });
3060
+ fs9.rmSync(temporal, { force: true });
2944
3061
  throw error;
2945
3062
  }
2946
3063
  }
@@ -2956,13 +3073,13 @@ function bloqueDeAgents() {
2956
3073
  MARCA_FIN
2957
3074
  ].join("\n");
2958
3075
  }
2959
- var rutaRegistroUsuario = (d) => path8.join(d.carpetaConfiguracion, "skill.json");
2960
- var rutaEstadoDelProyecto = (proyecto) => path8.join(proyecto, ".redcumbre", "estado.json");
3076
+ var rutaRegistroUsuario = (d) => path9.join(d.carpetaConfiguracion, "skill.json");
3077
+ var rutaEstadoDelProyecto = (proyecto) => path9.join(proyecto, ".redcumbre", "estado.json");
2961
3078
  function leerJson(ruta) {
2962
- if (!fs8.existsSync(ruta)) return null;
3079
+ if (!fs9.existsSync(ruta)) return null;
2963
3080
  let texto2;
2964
3081
  try {
2965
- texto2 = conReintentoEnWindows(() => fs8.readFileSync(ruta, "utf8"));
3082
+ texto2 = conReintentoEnWindows(() => fs9.readFileSync(ruta, "utf8"));
2966
3083
  } catch (error) {
2967
3084
  if (esErrorTransitorioDeWindows(error)) throw error;
2968
3085
  return null;
@@ -2995,13 +3112,13 @@ function guardarRegistroProyecto(proyecto, registro) {
2995
3112
  }
2996
3113
  function objetivos(d) {
2997
3114
  const lista2 = [
2998
- { id: "claude-usuario", archivo: path8.join(d.home, ".claude", "skills", NOMBRE_SKILL, "SKILL.md"), legible: `~/.claude/skills/${NOMBRE_SKILL}/SKILL.md` },
2999
- { id: "agents-usuario", archivo: path8.join(d.home, ".agents", "skills", NOMBRE_SKILL, "SKILL.md"), legible: `~/.agents/skills/${NOMBRE_SKILL}/SKILL.md` }
3115
+ { id: "claude-usuario", archivo: path9.join(d.home, ".claude", "skills", NOMBRE_SKILL, "SKILL.md"), legible: `~/.claude/skills/${NOMBRE_SKILL}/SKILL.md` },
3116
+ { id: "agents-usuario", archivo: path9.join(d.home, ".agents", "skills", NOMBRE_SKILL, "SKILL.md"), legible: `~/.agents/skills/${NOMBRE_SKILL}/SKILL.md` }
3000
3117
  ];
3001
3118
  if (d.proyecto) {
3002
3119
  lista2.push(
3003
- { id: "claude-proyecto", archivo: path8.join(d.proyecto, ".claude", "skills", NOMBRE_SKILL, "SKILL.md"), legible: `.claude/skills/${NOMBRE_SKILL}/SKILL.md` },
3004
- { id: "agents-proyecto", archivo: path8.join(d.proyecto, ".agents", "skills", NOMBRE_SKILL, "SKILL.md"), legible: `.agents/skills/${NOMBRE_SKILL}/SKILL.md` }
3120
+ { id: "claude-proyecto", archivo: path9.join(d.proyecto, ".claude", "skills", NOMBRE_SKILL, "SKILL.md"), legible: `.claude/skills/${NOMBRE_SKILL}/SKILL.md` },
3121
+ { id: "agents-proyecto", archivo: path9.join(d.proyecto, ".agents", "skills", NOMBRE_SKILL, "SKILL.md"), legible: `.agents/skills/${NOMBRE_SKILL}/SKILL.md` }
3005
3122
  );
3006
3123
  }
3007
3124
  return lista2;
@@ -3017,13 +3134,13 @@ function resumir2(rutas, quitada) {
3017
3134
  }
3018
3135
  function reconciliar(archivo, nuevo, registrado) {
3019
3136
  const hashNuevo = sha256(nuevo);
3020
- const existe = fs8.existsSync(archivo);
3137
+ const existe = fs9.existsSync(archivo);
3021
3138
  if (!existe) {
3022
3139
  if (registrado) return { accion: "borrada", hash: null };
3023
3140
  escribirAtomico(archivo, nuevo);
3024
3141
  return { accion: "instalada", hash: hashNuevo };
3025
3142
  }
3026
- const hashActual = sha256(conReintentoEnWindows(() => fs8.readFileSync(archivo)));
3143
+ const hashActual = sha256(conReintentoEnWindows(() => fs9.readFileSync(archivo)));
3027
3144
  if (registrado === void 0) {
3028
3145
  if (hashActual === hashNuevo) return { accion: "sin-cambios", hash: hashNuevo };
3029
3146
  return { accion: "editada", hash: null };
@@ -3040,13 +3157,13 @@ function extraerBloque(texto2) {
3040
3157
  function reconciliarAgents(archivo, registro) {
3041
3158
  const bloque = bloqueDeAgents();
3042
3159
  const hashBloque = sha256(bloque);
3043
- if (!fs8.existsSync(archivo)) {
3160
+ if (!fs9.existsSync(archivo)) {
3044
3161
  if (registro) return { accion: "borrada", registro: null };
3045
3162
  escribirAtomico(archivo, `${bloque}
3046
3163
  `);
3047
3164
  return { accion: "instalada", registro: { sha256: hashBloque, creado: true } };
3048
3165
  }
3049
- const texto2 = conReintentoEnWindows(() => fs8.readFileSync(archivo, "utf8"));
3166
+ const texto2 = conReintentoEnWindows(() => fs9.readFileSync(archivo, "utf8"));
3050
3167
  const actual = extraerBloque(texto2);
3051
3168
  if (actual === null) {
3052
3169
  if (registro) return { accion: "borrada", registro: null };
@@ -3083,7 +3200,7 @@ function instalarSkill(opciones) {
3083
3200
  }
3084
3201
  }
3085
3202
  if (bloqueAgents && destinos.proyecto && proyecto && !usuario.quitada && !proyecto.quitada) {
3086
- const { accion, registro } = reconciliarAgents(path8.join(destinos.proyecto, "AGENTS.md"), proyecto.agents);
3203
+ const { accion, registro } = reconciliarAgents(path9.join(destinos.proyecto, "AGENTS.md"), proyecto.agents);
3087
3204
  rutas.push({ ruta: "AGENTS.md", accion });
3088
3205
  if (registro) proyecto.agents = registro;
3089
3206
  }
@@ -3092,11 +3209,11 @@ function instalarSkill(opciones) {
3092
3209
  return resumir2(rutas, rutas.length === 0 && Boolean(usuario.quitada || proyecto?.quitada));
3093
3210
  }
3094
3211
  function quitarArchivo(archivo, registrado) {
3095
- if (!fs8.existsSync(archivo)) return null;
3096
- if (registrado === void 0 || sha256(conReintentoEnWindows(() => fs8.readFileSync(archivo))) !== registrado) return "editada";
3097
- fs8.rmSync(archivo);
3098
- const carpeta = path8.dirname(archivo);
3099
- if (fs8.readdirSync(carpeta).length === 0) fs8.rmdirSync(carpeta);
3212
+ if (!fs9.existsSync(archivo)) return null;
3213
+ if (registrado === void 0 || sha256(conReintentoEnWindows(() => fs9.readFileSync(archivo))) !== registrado) return "editada";
3214
+ fs9.rmSync(archivo);
3215
+ const carpeta = path9.dirname(archivo);
3216
+ if (fs9.readdirSync(carpeta).length === 0) fs9.rmdirSync(carpeta);
3100
3217
  return "quitada";
3101
3218
  }
3102
3219
  function quitarSkill(opciones) {
@@ -3111,16 +3228,16 @@ function quitarSkill(opciones) {
3111
3228
  if (accion) rutas.push({ ruta: objetivo.legible, accion });
3112
3229
  }
3113
3230
  if (destinos.proyecto && proyecto) {
3114
- const archivo = path8.join(destinos.proyecto, "AGENTS.md");
3115
- if (fs8.existsSync(archivo)) {
3116
- const texto2 = conReintentoEnWindows(() => fs8.readFileSync(archivo, "utf8"));
3231
+ const archivo = path9.join(destinos.proyecto, "AGENTS.md");
3232
+ if (fs9.existsSync(archivo)) {
3233
+ const texto2 = conReintentoEnWindows(() => fs9.readFileSync(archivo, "utf8"));
3117
3234
  const bloque = extraerBloque(texto2);
3118
3235
  if (bloque !== null) {
3119
3236
  if (!proyecto.agents || sha256(bloque) !== proyecto.agents.sha256) {
3120
3237
  rutas.push({ ruta: "AGENTS.md", accion: "editada" });
3121
3238
  } else {
3122
3239
  const resto = texto2.replace(regexBloque(), "").replace(/\n{3,}/g, "\n\n");
3123
- if (proyecto.agents.creado && resto.trim() === "") fs8.rmSync(archivo);
3240
+ if (proyecto.agents.creado && resto.trim() === "") fs9.rmSync(archivo);
3124
3241
  else escribirAtomico(archivo, resto.replace(/^\n+/, "").replace(/\n*$/, "\n"));
3125
3242
  rutas.push({ ruta: "AGENTS.md", accion: "quitada" });
3126
3243
  }
@@ -3143,8 +3260,8 @@ function renovarSkill(opciones) {
3143
3260
  const deUsuario = esDeUsuario(objetivo.id);
3144
3261
  const registro = deUsuario ? usuario : proyecto;
3145
3262
  if (usuario.quitada || registro.quitada) continue;
3146
- if (!fs8.existsSync(objetivo.archivo)) continue;
3147
- const actual = conReintentoEnWindows(() => fs8.readFileSync(objetivo.archivo, "utf8"));
3263
+ if (!fs9.existsSync(objetivo.archivo)) continue;
3264
+ const actual = conReintentoEnWindows(() => fs9.readFileSync(objetivo.archivo, "utf8"));
3148
3265
  const instalada2 = versionDeLaSkill(actual);
3149
3266
  if (instalada2 !== null && compararVersiones(version, instalada2) < 0) {
3150
3267
  rutas.push({ ruta: objetivo.legible, accion: "mas-nueva", instalada: instalada2 });
@@ -3290,6 +3407,106 @@ function sinRespuesta() {
3290
3407
  return new ErrorCli("La entrada se cerr\xF3 antes de que respondieras. No se hizo nada.", CODIGOS_DE_SALIDA.confirmacion);
3291
3408
  }
3292
3409
 
3410
+ // src/comandos/instalar.ts
3411
+ import path10 from "node:path";
3412
+ function estadoDeInstalacion(ctx, entorno) {
3413
+ if (!correPorNpx(entorno.bundle)) return { forma: "instalado" };
3414
+ const enElPath = versionEnElPath(entorno, { cwd: ctx.cwd, env: ctx.env });
3415
+ if (enElPath && compararVersiones(enElPath, ctx.version) >= 0) return { forma: "npx", enElPath, instalado: true };
3416
+ return { forma: "npx", enElPath, instalado: false };
3417
+ }
3418
+ function avisoDeInstalacion(version, estado2) {
3419
+ if (estado2.forma !== "npx") return null;
3420
+ const prefijo = prefijoPorNpx(version);
3421
+ if (estado2.instalado) {
3422
+ return {
3423
+ anexo: { version, enElPath: estado2.enElPath, instalado: true, comando: "redcumbre", prefijo },
3424
+ texto: `El CLI ya est\xE1 instalado en este computador (redcumbre ${estado2.enElPath}): usa \xABredcumbre \u2026\xBB en vez de \xAB${prefijo} \u2026\xBB.`,
3425
+ paraPersona: `\u2139 Ya tienes el CLI instalado (redcumbre ${estado2.enElPath}): usa \xABredcumbre \u2026\xBB en vez de npx.`
3426
+ };
3427
+ }
3428
+ const comando2 = comandoInstalarPorNpx(version, true);
3429
+ return {
3430
+ anexo: { version, enElPath: estado2.enElPath, instalado: false, comando: comando2, prefijo },
3431
+ texto: `El CLI corre por npx y no est\xE1 instalado en este computador${estado2.enElPath ? ` (el \xABredcumbre\xBB del PATH es la ${estado2.enElPath})` : ""}. D\xEDselo a la persona y prop\xF3nle instalarlo; si acepta, corre \xAB${comando2}\xBB. Mientras no est\xE9 instalado, donde un mensaje diga \xABredcumbre \u2026\xBB corre \xAB${prefijo} \u2026\xBB, con esta misma versi\xF3n.`,
3432
+ paraPersona: `\u2139 Est\xE1s usando el CLI por npx. Para dejarlo instalado y usar \xABredcumbre \u2026\xBB directo: \xAB${comandoInstalarPorNpx(version, false)}\xBB.`
3433
+ };
3434
+ }
3435
+ function errorDeInstalacion(comando2, corrida) {
3436
+ const salidaNpm = (corrida.stderr || corrida.stdout).trim();
3437
+ const detalle = salidaNpm.split(/\r?\n/).slice(-5).join(" \xB7 ");
3438
+ const permisos = /EACCES|EPERM|permission denied/i.test(salidaNpm) ? " npm no tiene permiso para escribir en su carpeta global: no lo corras con sudo; instala Node con nvm o configura un prefijo propio de npm (https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally) y vuelve a intentarlo." : "";
3439
+ return new ErrorCli(`No pude instalar el CLI: \xAB${legible(comando2)}\xBB termin\xF3 con ${corrida.status ?? "una se\xF1al"}${detalle ? ` (${detalle})` : ""}.${permisos} No cambi\xE9 nada m\xE1s.`, CODIGOS_DE_SALIDA.error, {
3440
+ codigo: "INSTALACION_FALLIDA",
3441
+ datos: { comando: legible(comando2) }
3442
+ });
3443
+ }
3444
+ function instalarConfirmado(ctx, entorno) {
3445
+ const { salida } = ctx;
3446
+ const registro = ctx.env.REDCUMBRE_NPM_REGISTRY || void 0;
3447
+ const comando2 = comandoDeActualizacion("npm-global", ctx.version, registro);
3448
+ const opciones = { cwd: ctx.cwd, env: ctx.env };
3449
+ salida.linea(`Instalando: ${legible(comando2)}`);
3450
+ const corrida = entorno.ejecutar(comando2.comando, comando2.args, opciones);
3451
+ if (corrida.status !== 0) throw errorDeInstalacion(comando2, corrida);
3452
+ const raiz = entorno.raizGlobal("npm");
3453
+ const bundle = raiz ? path10.join(raiz, ...PAQUETE_DEL_CLI.split("/"), "dist", "redcumbre.js") : null;
3454
+ const comprobada = bundle ? entorno.ejecutar(process.execPath, [bundle, "--version"], opciones) : null;
3455
+ if (!bundle || !comprobada || comprobada.status !== 0 || comprobada.stdout.trim() !== ctx.version) {
3456
+ throw new ErrorCli(
3457
+ `\xAB${legible(comando2)}\xBB termin\xF3 bien, pero el CLI de la carpeta global de npm (${raiz ?? "npm root --global no respondi\xF3"}) responde \xAB${comprobada?.stdout.trim() || comprobada?.stderr.trim() || "nada"}\xBB y no ${ctx.version}.`,
3458
+ CODIGOS_DE_SALIDA.error,
3459
+ { codigo: "INSTALACION_INCOMPLETA", datos: { version: ctx.version } }
3460
+ );
3461
+ }
3462
+ const enElPath = versionEnElPath(entorno, opciones);
3463
+ const carpeta = carpetaDeEjecutablesDeNpm(entorno, opciones);
3464
+ if (enElPath === ctx.version) {
3465
+ salida.linea(`\u2713 El CLI qued\xF3 instalado en la versi\xF3n ${ctx.version}: desde ahora usa \xABredcumbre \u2026\xBB.`);
3466
+ } else {
3467
+ salida.aviso(
3468
+ `El CLI qued\xF3 instalado en la versi\xF3n ${ctx.version}${carpeta ? ` en ${carpeta}` : ""}, pero ${enElPath ? `el \xABredcumbre\xBB que encuentra el PATH es la ${enElPath}` : "esa carpeta no est\xE1 en el PATH"}. Agrega ${carpeta ?? "la carpeta de ejecutables globales de npm (\xABnpm prefix --global\xBB)"} al PATH, antes que cualquier otra que tenga \xABredcumbre\xBB, y abre una terminal nueva. Mientras tanto usa \xAB${prefijoPorNpx(ctx.version)} \u2026\xBB.`
3469
+ );
3470
+ }
3471
+ return { ok: true, instalado: true, version: ctx.version, comando: legible(comando2), enElPath, carpeta };
3472
+ }
3473
+ async function instalar(ctx, opciones, entorno = entornoDeActualizacion(ctx)) {
3474
+ const { salida } = ctx;
3475
+ const instalacion = detectarInstalacion(entorno.bundle, entorno.raizGlobal);
3476
+ if (instalacion.forma === "npm-global" || instalacion.forma === "pnpm-global") {
3477
+ salida.linea(`El CLI ya est\xE1 instalado (${ctx.version}). Para pasar a una versi\xF3n m\xE1s nueva: \xABredcumbre actualizar\xBB.`);
3478
+ salida.resultado({ ok: true, instalado: false, motivo: "ya-instalado", version: ctx.version, forma: instalacion.forma });
3479
+ return;
3480
+ }
3481
+ if (instalacion.forma === "no-reconocida") {
3482
+ throw new ErrorCli(
3483
+ `No instal\xE9 nada: ${instalacion.motivo}. Para instalarlo a mano: \xABnpm install --global ${PAQUETE_DEL_CLI}@${ctx.version}\xBB.`,
3484
+ CODIGOS_DE_SALIDA.error,
3485
+ { codigo: "INSTALACION_NO_RECONOCIDA", datos: { version: ctx.version } }
3486
+ );
3487
+ }
3488
+ const enElPath = versionEnElPath(entorno, { cwd: ctx.cwd, env: ctx.env });
3489
+ if (enElPath && compararVersiones(enElPath, ctx.version) >= 0) {
3490
+ salida.linea(`El CLI ya est\xE1 instalado en este computador (redcumbre ${enElPath}): usa \xABredcumbre \u2026\xBB en vez de npx.`);
3491
+ salida.resultado({ ok: true, instalado: false, motivo: "ya-instalado", version: enElPath, forma: "npx" });
3492
+ return;
3493
+ }
3494
+ const comando2 = comandoDeActualizacion("npm-global", ctx.version, ctx.env.REDCUMBRE_NPM_REGISTRY || void 0);
3495
+ const confirmado = comandoInstalarPorNpx(ctx.version, true);
3496
+ const reemplaza = enElPath ? ` (reemplaza el redcumbre ${enElPath} del PATH)` : "";
3497
+ if (ctx.terminal) {
3498
+ if (!await ctx.terminal.confirmar(`\xBFInstalo el CLI ${ctx.version} en este computador con \xAB${legible(comando2)}\xBB${reemplaza}?`)) {
3499
+ throw faltaConfirmacion(`No confirmaste: no instal\xE9 nada. Cuando quieras: \xAB${comandoInstalarPorNpx(ctx.version, false)}\xBB.`, confirmado);
3500
+ }
3501
+ } else if (!opciones.confirmar) {
3502
+ throw faltaConfirmacion(
3503
+ `Instalar el CLI ${ctx.version}${reemplaza} instala un paquete en este computador y lo decide la persona. D\xEDselo y, si acepta, corre \xAB${confirmado}\xBB. No instal\xE9 nada.`,
3504
+ confirmado
3505
+ );
3506
+ }
3507
+ salida.resultado(instalarConfirmado(ctx, entorno));
3508
+ }
3509
+
3293
3510
  // src/comandos/registro.ts
3294
3511
  async function correr(globales, accion, opciones = {}) {
3295
3512
  const json2 = Boolean(globales.json);
@@ -3297,7 +3514,7 @@ async function correr(globales, accion, opciones = {}) {
3297
3514
  const salida = crearSalida(agente);
3298
3515
  const terminal = agente ? null : crearTerminal(process.stdin, process.stdout);
3299
3516
  try {
3300
- const ctx = crearContexto({ salida, terminal, sinNavegador: Boolean(globales.sinNavegador), cwd: process.cwd(), env: process.env, version: "0.5.1" });
3517
+ const ctx = crearContexto({ salida, terminal, sinNavegador: Boolean(globales.sinNavegador), cwd: process.cwd(), env: process.env, version: "0.6.0" });
3301
3518
  await exigirVersionMinima({
3302
3519
  version: ctx.version,
3303
3520
  env: process.env,
@@ -3308,15 +3525,29 @@ async function correr(globales, accion, opciones = {}) {
3308
3525
  `) : void 0;
3309
3526
  if (!opciones.revisaPorSuCuenta) {
3310
3527
  const consulta = { carpeta: ctx.carpetaConfiguracion, version: ctx.version, ahora: ctx.ahora(), registro: process.env.REDCUMBRE_NPM_REGISTRY };
3528
+ const entornoDelCli = entornoDeActualizacion(ctx);
3529
+ const porNpx = correPorNpx(entornoDelCli.bundle);
3530
+ const comandoActualizar = porNpx ? `${prefijoPorNpx(ctx.version)} actualizar` : void 0;
3311
3531
  if (!agente) {
3312
- await avisarSiHayVersionNueva({ ...consulta, humano: process.stderr });
3532
+ await avisarSiHayVersionNueva({ ...consulta, humano: process.stderr, comando: comandoActualizar });
3313
3533
  } else {
3314
3534
  const actualizacion = await actualizacionDisponible(consulta);
3315
3535
  if (actualizacion) {
3536
+ if (comandoActualizar) actualizacion.comando = `${comandoActualizar} --confirmar`;
3316
3537
  salida.anexar("actualizacion", actualizacion);
3317
3538
  salida.aviso(avisoDeActualizacion(actualizacion));
3318
3539
  }
3319
3540
  }
3541
+ if (porNpx) {
3542
+ const aviso = avisoDeInstalacion(ctx.version, estadoDeInstalacion(ctx, entornoDelCli));
3543
+ if (aviso && agente) {
3544
+ salida.anexar("instalacion", aviso.anexo);
3545
+ salida.aviso(aviso.texto);
3546
+ } else if (aviso && !opciones.ofreceInstalar) {
3547
+ process.stderr.write(`${aviso.paraPersona}
3548
+ `);
3549
+ }
3550
+ }
3320
3551
  renovarSkillAlCorrer({
3321
3552
  destinos: { carpetaConfiguracion: ctx.carpetaConfiguracion, home: ctx.home, proyecto: tieneInstalacionDelCli(ctx.proyecto) ? ctx.proyecto : void 0 },
3322
3553
  version: ctx.version,
@@ -3429,12 +3660,12 @@ function entradasDe(ctx, fila, argumentos, opciones) {
3429
3660
  return { query, cuerpo, archivo };
3430
3661
  }
3431
3662
  function logoDe(ctx, ruta) {
3432
- const completa = path9.resolve(ctx.cwd, ruta);
3433
- const tipo = TIPOS_DE_LOGO[path9.extname(completa).toLowerCase()];
3434
- if (!tipo) throw errorDeUso(`El logo tiene que ser .jpg, .jpeg, .png, .gif o .webp; \xAB${path9.basename(completa)}\xBB no lo es. No llam\xE9 al API.`);
3435
- if (!fs9.existsSync(completa) || !fs9.statSync(completa).isFile()) throw errorDeUso(`No encuentro el archivo del logo: ${completa}`);
3436
- if (fs9.statSync(completa).size > MAXIMO_DEL_LOGO) throw errorDeUso(`El logo pesa m\xE1s de 2 MB: ${path9.basename(completa)}. Reduce la imagen y vuelve a intentarlo. No llam\xE9 al API.`);
3437
- return { ruta: completa, tipo, bytes: fs9.readFileSync(completa) };
3663
+ const completa = path11.resolve(ctx.cwd, ruta);
3664
+ const tipo = TIPOS_DE_LOGO[path11.extname(completa).toLowerCase()];
3665
+ if (!tipo) throw errorDeUso(`El logo tiene que ser .jpg, .jpeg, .png, .gif o .webp; \xAB${path11.basename(completa)}\xBB no lo es. No llam\xE9 al API.`);
3666
+ if (!fs10.existsSync(completa) || !fs10.statSync(completa).isFile()) throw errorDeUso(`No encuentro el archivo del logo: ${completa}`);
3667
+ if (fs10.statSync(completa).size > MAXIMO_DEL_LOGO) throw errorDeUso(`El logo pesa m\xE1s de 2 MB: ${path11.basename(completa)}. Reduce la imagen y vuelve a intentarlo. No llam\xE9 al API.`);
3668
+ return { ruta: completa, tipo, bytes: fs10.readFileSync(completa) };
3438
3669
  }
3439
3670
  var citar = (valor) => /^[\w.@:/=,+-]+$/.test(valor) ? valor : `'${valor.replace(/'/g, `'\\''`)}'`;
3440
3671
  function comandoDe2(fila, argumentos, opciones) {
@@ -3466,9 +3697,9 @@ async function correrOperacionDeEmisor(ctx, fila, argumentos, opciones) {
3466
3697
  ctx.salida.linea(`Ensayo: no llam\xE9 al API. Con la llave \xAB${llave.archivo.name}\xBB (${nombreDelModo(llave.entorno)}) de ${slug} har\xEDa:`);
3467
3698
  ctx.salida.linea(` ${op.metodo} ${ctx.cliente.url(ruta, query)}`);
3468
3699
  if (cuerpo !== void 0) ctx.salida.linea(` ${JSON.stringify(cuerpo)}`);
3469
- if (archivo) ctx.salida.linea(` multipart/form-data: logo=${path9.basename(archivo.ruta)} (${archivo.tipo}, ${archivo.bytes.length} bytes)`);
3700
+ if (archivo) ctx.salida.linea(` multipart/form-data: logo=${path11.basename(archivo.ruta)} (${archivo.tipo}, ${archivo.bytes.length} bytes)`);
3470
3701
  ctx.salida.resultado({
3471
- solicitud: { metodo: op.metodo, ruta, query, cuerpo: cuerpo ?? null, ...archivo ? { formulario: { logo: path9.basename(archivo.ruta) } } : {} },
3702
+ solicitud: { metodo: op.metodo, ruta, query, cuerpo: cuerpo ?? null, ...archivo ? { formulario: { logo: path11.basename(archivo.ruta) } } : {} },
3472
3703
  empresa: slug,
3473
3704
  llave: llave.archivo.name,
3474
3705
  modo: llave.entorno,
@@ -3499,7 +3730,7 @@ async function correrOperacionDeEmisor(ctx, fila, argumentos, opciones) {
3499
3730
  let formulario;
3500
3731
  if (archivo) {
3501
3732
  formulario = new FormData();
3502
- formulario.append("logo", new Blob([new Uint8Array(archivo.bytes)], { type: archivo.tipo }), path9.basename(archivo.ruta));
3733
+ formulario.append("logo", new Blob([new Uint8Array(archivo.bytes)], { type: archivo.tipo }), path11.basename(archivo.ruta));
3503
3734
  }
3504
3735
  respuesta = (await pedir2(ctx, llave, op, ruta, query, cuerpo, formulario)).json;
3505
3736
  }
@@ -3856,7 +4087,7 @@ async function canjear(ctx, o) {
3856
4087
  await canjearYMostrar(ctx, llave, llave.archivo.tenantSlug, op, codigo);
3857
4088
  }
3858
4089
  function declararTokenizar(programa2) {
3859
- const raiz = comando(programa2, "tokenizar", "inscribe un emisor: la persona autoriza el uso de sus credenciales del SII y el CLI canjea el c\xF3digo").option("--rut <rut>", "RUT del emisor (el API valida el d\xEDgito verificador)").option("--tipo <tipo>", "tributario o dte").option("--autenticacion <m\xE9todo>", "clave o certificado (obligatoria con --tipo tributario)").option("--correo <correo>", "correo de la persona que autoriza, para la sesi\xF3n que abres t\xFA").option("--invitar <correo>", "manda la invitaci\xF3n a ese correo y termina").option("--integracion <tipo>", "PORTAL_MIPYME o FULL_DTE (solo --tipo dte)").option("--boletas", "incluye el carril de boletas (solo --tipo dte)").option("--correo-empresa <correo>", "correo de la empresa (obligatoria con --tipo dte)").option("--contacto-correo <correo>", "correo de contacto para la certificaci\xF3n (solo --tipo dte)").option("--contacto-telefono <tel\xE9fono>", "tel\xE9fono de contacto para la certificaci\xF3n (solo --tipo dte)").option("--clave <clave>", "clave de idempotencia de la invitaci\xF3n, para reintentar sin duplicar (solo con --invitar)").option("--espera <minutos>", `minutos de espera de la autorizaci\xF3n, de 1 a 120 (${ESPERA_POR_OMISION_MIN} por omisi\xF3n)`).addOption(new Option2("--sin-navegador", "no abre el navegador: imprime la URL y pide pegar el c\xF3digo")).option("--produccion", "con la llave de producci\xF3n (pide confirmar lo que escribe)").option("--confirmar <slug>", "confirma en producci\xF3n sin preguntar, con el identificador de la empresa");
4090
+ const raiz = comando(programa2, "tokenizar", "inscribe un emisor: la persona autoriza el uso de sus credenciales del SII y el CLI canjea el c\xF3digo").option("--rut <rut>", "RUT del emisor (el API valida el d\xEDgito verificador)").option("--tipo <tipo>", "tributario o dte").option("--autenticacion <m\xE9todo>", "clave o certificado (obligatoria con --tipo tributario)").option("--correo <correo>", "correo de la persona que autoriza, para la sesi\xF3n que abres t\xFA").option("--invitar <correo>", "manda la invitaci\xF3n a ese correo y termina").option("--integracion <tipo>", "PORTAL_MIPYME o FULL_DTE (s\xF3lo --tipo dte). FULL_DTE, recomendado, emite y recibe DTE integrado. PORTAL_MIPYME es para bajo volumen y sin cargo fijo, y no emite boletas").option("--boletas", "crea adem\xE1s el emisor de boletas (SOLO_BOLETA), un carril aparte del de facturaci\xF3n (s\xF3lo --tipo dte)").option("--correo-empresa <correo>", "correo de la empresa (obligatoria con --tipo dte)").option("--contacto-correo <correo>", "correo de contacto para la certificaci\xF3n (solo --tipo dte)").option("--contacto-telefono <tel\xE9fono>", "tel\xE9fono de contacto para la certificaci\xF3n (solo --tipo dte)").option("--clave <clave>", "clave de idempotencia de la invitaci\xF3n, para reintentar sin duplicar (solo con --invitar)").option("--espera <minutos>", `minutos de espera de la autorizaci\xF3n, de 1 a 120 (${ESPERA_POR_OMISION_MIN} por omisi\xF3n)`).addOption(new Option2("--sin-navegador", "no abre el navegador: imprime la URL y pide pegar el c\xF3digo")).option("--produccion", "con la llave de producci\xF3n (pide confirmar lo que escribe)").option("--confirmar <slug>", "confirma en producci\xF3n sin preguntar, con el identificador de la empresa");
3860
4091
  raiz.action((_o, accion) => {
3861
4092
  const o = accion.optsWithGlobals();
3862
4093
  return correr(o, (ctx) => tokenizar(ctx, o));
@@ -3869,8 +4100,8 @@ function declararTokenizar(programa2) {
3869
4100
 
3870
4101
  // src/nucleo/guias.ts
3871
4102
  import { randomBytes as randomBytes2 } from "node:crypto";
3872
- import fs10 from "node:fs";
3873
- import path10 from "node:path";
4103
+ import fs11 from "node:fs";
4104
+ import path12 from "node:path";
3874
4105
  var CODIGO_GUIA_NO_DISPONIBLE = "GUIA_NO_DISPONIBLE";
3875
4106
  var TEMA_VALIDO = /^[a-z0-9][a-z0-9-]*$/;
3876
4107
  var COPIA_DEL_INDICE = "_indice";
@@ -3881,15 +4112,15 @@ var TIPOS_DE_FICHA = ["text/markdown", "text/plain", "application/octet-stream"]
3881
4112
  var PARECE_HTML = /^\s*<(?:!doctype\s+html|html[\s>])/i;
3882
4113
  var TIPOS_DEL_INDICE = ["application/json"];
3883
4114
  var TIPOS_DE_VERSION = ["text/plain"];
3884
- var carpetaDeGuias = (carpeta) => path10.join(carpeta, "guias");
3885
- var rutaTexto = (carpeta, nombre) => path10.join(carpetaDeGuias(carpeta), `${nombre}${nombre === COPIA_DEL_INDICE ? ".txt" : ".md"}`);
3886
- var rutaMarca = (carpeta, nombre) => path10.join(carpetaDeGuias(carpeta), `${nombre}.json`);
4115
+ var carpetaDeGuias = (carpeta) => path12.join(carpeta, "guias");
4116
+ var rutaTexto = (carpeta, nombre) => path12.join(carpetaDeGuias(carpeta), `${nombre}${nombre === COPIA_DEL_INDICE ? ".txt" : ".md"}`);
4117
+ var rutaMarca = (carpeta, nombre) => path12.join(carpetaDeGuias(carpeta), `${nombre}.json`);
3887
4118
  function leerCopia2(carpeta, nombre, origen2) {
3888
4119
  try {
3889
- const marca = JSON.parse(fs10.readFileSync(rutaMarca(carpeta, nombre), "utf8"));
4120
+ const marca = JSON.parse(fs11.readFileSync(rutaMarca(carpeta, nombre), "utf8"));
3890
4121
  if (!marca || marca.origen !== origen2 || typeof marca.version !== "string" || !marca.version) return null;
3891
4122
  const archivo = rutaTexto(carpeta, nombre);
3892
- return { texto: fs10.readFileSync(archivo, "utf8"), version: marca.version, fecha: fs10.statSync(archivo).mtime };
4123
+ return { texto: fs11.readFileSync(archivo, "utf8"), version: marca.version, fecha: fs11.statSync(archivo).mtime };
3893
4124
  } catch {
3894
4125
  return null;
3895
4126
  }
@@ -3897,22 +4128,22 @@ function leerCopia2(carpeta, nombre, origen2) {
3897
4128
  function escribirAtomico2(destino, contenido) {
3898
4129
  const temporal = `${destino}.${process.pid}.${randomBytes2(4).toString("hex")}.tmp`;
3899
4130
  try {
3900
- fs10.writeFileSync(temporal, contenido);
3901
- fs10.renameSync(temporal, destino);
4131
+ fs11.writeFileSync(temporal, contenido);
4132
+ fs11.renameSync(temporal, destino);
3902
4133
  } catch (error) {
3903
- fs10.rmSync(temporal, { force: true });
4134
+ fs11.rmSync(temporal, { force: true });
3904
4135
  throw error;
3905
4136
  }
3906
4137
  }
3907
4138
  function guardarCopia2(carpeta, nombre, origen2, version, texto2) {
3908
- fs10.mkdirSync(carpetaDeGuias(carpeta), { recursive: true, mode: 448 });
4139
+ fs11.mkdirSync(carpetaDeGuias(carpeta), { recursive: true, mode: 448 });
3909
4140
  escribirAtomico2(rutaTexto(carpeta, nombre), texto2);
3910
4141
  escribirAtomico2(rutaMarca(carpeta, nombre), `${JSON.stringify({ origen: origen2, version })}
3911
4142
  `);
3912
4143
  }
3913
4144
  function borrarCopia(carpeta, nombre) {
3914
- fs10.rmSync(rutaMarca(carpeta, nombre), { force: true });
3915
- fs10.rmSync(rutaTexto(carpeta, nombre), { force: true });
4145
+ fs11.rmSync(rutaMarca(carpeta, nombre), { force: true });
4146
+ fs11.rmSync(rutaTexto(carpeta, nombre), { force: true });
3916
4147
  }
3917
4148
  var fechaLegible2 = (fecha) => fecha.toLocaleString("es-CL", { dateStyle: "medium", timeStyle: "short" });
3918
4149
  var sinCopia = (que, motivo) => new ErrorCli(`${motivo} No tengo una copia local de ${que}: sin red no puedo entregarla. Vuelve a intentarlo con conexi\xF3n.`, CODIGOS_DE_SALIDA.api5xx, {
@@ -3991,8 +4222,8 @@ async function obtener(opciones, nombre, ruta, que, tipos, validar2 = () => void
3991
4222
  guardarCopia2(carpeta, nombre, cliente.api, version, r.texto);
3992
4223
  return { texto: r.texto, version, copiaSinRevalidar: null };
3993
4224
  }
3994
- var invalido = (que) => new ErrorCli(`${que} no tiene el formato esperado. Actualiza el CLI con \xABnpx @redcumbrecl/cli@latest\xBB y vuelve a intentarlo.`, CODIGOS_DE_SALIDA.api5xx, { codigo: "GUIA_INVALIDA" });
3995
- var respuestaInvalida = (motivo) => new ErrorCli(`${motivo} No es una gu\xEDa v\xE1lida y no guard\xE9 ninguna copia. Vuelve a intentarlo m\xE1s tarde o actualiza el CLI con \xABnpx @redcumbrecl/cli@latest\xBB.`, CODIGOS_DE_SALIDA.api5xx, {
4225
+ var invalido = (que) => new ErrorCli(`${que} no tiene el formato esperado. Actualiza el CLI con \xAB${COMANDO_DE_ACTUALIZACION}\xBB y vuelve a intentarlo.`, CODIGOS_DE_SALIDA.api5xx, { codigo: "GUIA_INVALIDA" });
4226
+ var respuestaInvalida = (motivo) => new ErrorCli(`${motivo} No es una gu\xEDa v\xE1lida y no guard\xE9 ninguna copia. Vuelve a intentarlo m\xE1s tarde o actualiza el CLI con \xAB${COMANDO_DE_ACTUALIZACION}\xBB.`, CODIGOS_DE_SALIDA.api5xx, {
3996
4227
  codigo: "GUIA_INVALIDA"
3997
4228
  });
3998
4229
  var esTexto = (valor) => typeof valor === "string" && valor.trim() !== "";
@@ -4110,7 +4341,7 @@ async function guia(ctx, tema) {
4110
4341
  }
4111
4342
 
4112
4343
  // src/comandos/init.ts
4113
- import path12 from "node:path";
4344
+ import path14 from "node:path";
4114
4345
 
4115
4346
  // src/comandos/instalar-llave.ts
4116
4347
  function negativaSinRol(ctx, proyecto, empresa2, entorno) {
@@ -4204,9 +4435,9 @@ function mostrarWhoami(salida, tenant, modo, encabezado) {
4204
4435
  }
4205
4436
 
4206
4437
  // src/comandos/mcp.ts
4207
- import fs11 from "node:fs";
4438
+ import fs12 from "node:fs";
4208
4439
  import os3 from "node:os";
4209
- import path11 from "node:path";
4440
+ import path13 from "node:path";
4210
4441
  var URL_MCP_REDCUMBRE = "https://mcp.redcumbre.cl";
4211
4442
  var NOMBRE_SERVIDOR_MCP = "redcumbre";
4212
4443
  var COMANDO_MCP_AGREGAR = "redcumbre mcp agregar";
@@ -4226,12 +4457,12 @@ var ASISTENTE_REGISTRY = {
4226
4457
  var ENTRADA = { type: "http", url: URL_MCP_REDCUMBRE };
4227
4458
  var esObjeto5 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
4228
4459
  var mismaEntrada = (v) => esObjeto5(v) && Object.keys(v).length === 2 && v.type === ENTRADA.type && v.url === ENTRADA.url;
4229
- var rutaConfigMcp = (asistente, home = os3.homedir()) => path11.join(home, ...ASISTENTE_REGISTRY[asistente].archivo);
4460
+ var rutaConfigMcp = (asistente, home = os3.homedir()) => path13.join(home, ...ASISTENTE_REGISTRY[asistente].archivo);
4230
4461
  function leerConfig(ruta) {
4231
- if (!fs11.existsSync(ruta)) return null;
4462
+ if (!fs12.existsSync(ruta)) return null;
4232
4463
  let actual;
4233
4464
  try {
4234
- actual = JSON.parse(fs11.readFileSync(ruta, "utf8"));
4465
+ actual = JSON.parse(fs12.readFileSync(ruta, "utf8"));
4235
4466
  } catch (error) {
4236
4467
  throw new ErrorCli(`${ruta} no tiene JSON v\xE1lido (${error.message}): no lo modifiqu\xE9. Corr\xEDgelo y vuelve a correr el comando.`, CODIGOS_DE_SALIDA.error, {
4237
4468
  codigo: "CONFIG_MCP_INVALIDA"
@@ -4265,8 +4496,8 @@ function planQuitar(asistente, home) {
4265
4496
  function escribir(planes) {
4266
4497
  for (const p of planes) {
4267
4498
  if (p.contenido === void 0) continue;
4268
- fs11.mkdirSync(path11.dirname(p.ruta), { recursive: true });
4269
- fs11.writeFileSync(p.ruta, p.contenido);
4499
+ fs12.mkdirSync(path13.dirname(p.ruta), { recursive: true });
4500
+ fs12.writeFileSync(p.ruta, p.contenido);
4270
4501
  }
4271
4502
  }
4272
4503
  function asistentesPedidos(asistente) {
@@ -4385,19 +4616,19 @@ async function pedirCampo(ctx, terminal, campo, previo) {
4385
4616
  }
4386
4617
 
4387
4618
  // src/comandos/init.ts
4388
- async function init(ctx, opciones) {
4619
+ async function init(ctx, opciones, entorno = entornoDeActualizacion(ctx)) {
4389
4620
  const { salida } = ctx;
4390
4621
  const terminal = salida.json ? null : ctx.terminal;
4391
4622
  if (opciones.entorno !== void 0) {
4392
4623
  throw errorDeUso(`--entorno ya no existe: init s\xF3lo conecta la llave de prueba. Para pasar a producci\xF3n corre \xAB${COMANDO_PASAR_A_PRODUCCION}\xBB.`);
4393
4624
  }
4394
- let proyecto = path12.resolve(ctx.cwd, opciones.carpeta ?? ".");
4625
+ let proyecto = path14.resolve(ctx.cwd, opciones.carpeta ?? ".");
4395
4626
  const sesion = await ctx.sesion();
4396
4627
  const perfil = await sesion.usar((token) => ctx.cliente.perfil(token));
4397
4628
  if (perfil.empresas.length === 0) {
4398
4629
  if (!terminal) {
4399
4630
  throw new ErrorCli(
4400
- `Tu cuenta todav\xEDa no pertenece a ninguna empresa en REDCUMBRE. No envi\xE9 ninguna solicitud: pide la cuenta en https://docs.redcumbre.cl/solicitar-cuenta/ o corre \xAB${COMANDO_SOLICITAR_CUENTA}\xBB en una terminal.`,
4631
+ `Tu cuenta todav\xEDa no pertenece a ninguna empresa en REDCUMBRE. No envi\xE9 ninguna solicitud: pide la cuenta en ${SOLICITUD_CUENTA_URL_FORMULARIO_SITIO} o corre \xAB${COMANDO_SOLICITAR_CUENTA}\xBB en una terminal.`,
4401
4632
  CODIGOS_DE_SALIDA.error,
4402
4633
  { codigo: "SIN_EMPRESAS", comando: COMANDO_SOLICITAR_CUENTA }
4403
4634
  );
@@ -4415,7 +4646,7 @@ async function init(ctx, opciones) {
4415
4646
  const empresa2 = await elegirEmpresa(ctx, perfil.empresas, opciones.empresa);
4416
4647
  if (terminal && opciones.carpeta === void 0 && !tieneInstalacionDelCli(proyecto)) {
4417
4648
  const respuesta = await terminal.preguntar("\xBFD\xF3nde instalo la llave? [.]: ");
4418
- proyecto = path12.resolve(ctx.cwd, respuesta || ".");
4649
+ proyecto = path14.resolve(ctx.cwd, respuesta || ".");
4419
4650
  }
4420
4651
  const anterior = empresaAnterior(proyecto, empresa2.slug);
4421
4652
  const llave = await instalarLlave(ctx, proyecto, empresa2, "prueba");
@@ -4450,6 +4681,24 @@ async function init(ctx, opciones) {
4450
4681
  );
4451
4682
  }
4452
4683
  salida.linea(`\u2713 La llave de prueba funciona: ${comprobacion.tenant.nombre} (${comprobacion.tenant.slug}), modo de prueba.`);
4684
+ let cli;
4685
+ const estado2 = terminal ? estadoDeInstalacion(ctx, entorno) : null;
4686
+ if (terminal && estado2?.forma === "npx" && !estado2.instalado) {
4687
+ salida.linea();
4688
+ const reemplaza = estado2.enElPath ? ` (reemplaza el redcumbre ${estado2.enElPath} del PATH)` : "";
4689
+ if (await terminal.confirmar(`El CLI corre por npx. \xBFLo dejo instalado en este computador (versi\xF3n ${ctx.version})${reemplaza} para que uses \xABredcumbre \u2026\xBB directo?`)) {
4690
+ try {
4691
+ cli = instalarConfirmado(ctx, entorno);
4692
+ } catch (error) {
4693
+ if (!(error instanceof ErrorCli)) throw error;
4694
+ salida.aviso(`${error.message} El proyecto qued\xF3 conectado igual; puedes reintentarlo con \xAB${comandoInstalarPorNpx(ctx.version, false)}\xBB.`);
4695
+ cli = { instalado: false, codigo: error.codigo };
4696
+ }
4697
+ } else {
4698
+ salida.linea(`Cuando quieras dejarlo instalado: ${comandoInstalarPorNpx(ctx.version, false)}`);
4699
+ cli = { instalado: false, motivo: "no-confirmado" };
4700
+ }
4701
+ }
4453
4702
  salida.linea();
4454
4703
  salida.linea(`Para que tu asistente (Claude Code o Cursor) trabaje con REDCUMBRE: ${COMANDO_MCP_AGREGAR}`);
4455
4704
  salida.resultado({
@@ -4460,7 +4709,8 @@ async function init(ctx, opciones) {
4460
4709
  llave,
4461
4710
  skill: { rutas: skill.rutas, estado: skill.estado },
4462
4711
  comprobacion: { sandbox: true, tenant: { slug: comprobacion.tenant.slug, nombre: comprobacion.tenant.nombre } },
4463
- mcp: { comando: COMANDO_MCP_AGREGAR }
4712
+ mcp: { comando: COMANDO_MCP_AGREGAR },
4713
+ ...cli ? { cli } : {}
4464
4714
  });
4465
4715
  }
4466
4716
  async function elegirEmpresa(ctx, empresas, pedida) {
@@ -4567,7 +4817,7 @@ async function llamadas(ctx, opciones) {
4567
4817
  }
4568
4818
 
4569
4819
  // src/comandos/credenciales-reseller.ts
4570
- import path13 from "node:path";
4820
+ import path15 from "node:path";
4571
4821
  function declararOpcionesCrearCredencial(comando2) {
4572
4822
  return comando2.requiredOption("--tipo <tipo>", `${TIPOS_CREDENCIAL_RESELLER.join(" o ")}`).requiredOption("--entorno <entorno>", `${ENTORNOS_LLAVE.join(" o ")}`).requiredOption("--nombre <nombre>", "nombre de la credencial (3 a 191 caracteres)").option("--vence <fecha>", "vencimiento opcional, ISO 8601 (2027-12-31)").option("--empresa <slug>", "la empresa reseller");
4573
4823
  }
@@ -4597,7 +4847,7 @@ async function crearCredencial(ctx, opciones) {
4597
4847
  const sesion = await ctx.sesion();
4598
4848
  const creada = await sesion.usar((token) => ctx.cliente.crearCredencialReseller(token, slug, { nombre: opciones.nombre, tipo, entorno, venceEn }));
4599
4849
  const relativa = `keys/reseller-${slug}-${tipo}-${entorno}.json`;
4600
- const archivo = path13.join(ctx.proyecto, relativa);
4850
+ const archivo = path15.join(ctx.proyecto, relativa);
4601
4851
  asegurarExclusiones(ctx.proyecto, estaVersionado(ctx.proyecto, ".env"));
4602
4852
  escribirArchivoLlave(archivo, {
4603
4853
  tenantSlug: slug,
@@ -4621,7 +4871,7 @@ async function revocarCredencial(ctx, id, opciones) {
4621
4871
  }
4622
4872
 
4623
4873
  // src/comandos/llave-validafirma.ts
4624
- import path14 from "node:path";
4874
+ import path16 from "node:path";
4625
4875
  function declararOpcionesLlaveValidaFirma(comando2) {
4626
4876
  return comando2.requiredOption("--empresa <slug>", "la empresa (tenantSlug) donde se crea la llave").requiredOption("--alcance <alcance>", "carpetas (carpetas y documentos) o cuenta (cuenta corporativa)").option("--modo <modo>", "prueba (por omisi\xF3n) o produccion").option("--confirmar <slug>", "con --modo produccion: el slug de la empresa; confirma la llave sin preguntar (obligatorio sin terminal o con --json)");
4627
4877
  }
@@ -4637,8 +4887,8 @@ async function llaveValidaFirma(ctx, opciones) {
4637
4887
  if (!esEntornoLlave(modoPedido)) throw errorDeUso(mensajeEntornoLlaveInvalido(modoPedido));
4638
4888
  const modo = modoPedido;
4639
4889
  const relativa = rutaRelativaLlaveValidaFirma(empresa2, alcance, modo);
4640
- const archivo = path14.resolve(ctx.proyecto, relativa);
4641
- if (path14.join(ctx.proyecto, "keys", path14.basename(relativa)) !== archivo || path14.basename(relativa) !== relativa.slice("keys/".length)) throw errorDeUso(`\xAB${empresa2}\xBB no es el identificador de una empresa (tenantSlug).`);
4890
+ const archivo = path16.resolve(ctx.proyecto, relativa);
4891
+ if (path16.join(ctx.proyecto, "keys", path16.basename(relativa)) !== archivo || path16.basename(relativa) !== relativa.slice("keys/".length)) throw errorDeUso(`\xAB${empresa2}\xBB no es el identificador de una empresa (tenantSlug).`);
4642
4892
  const comando2 = `redcumbre llaves validafirma --empresa ${empresa2} --alcance ${alcance} --modo ${modo}`;
4643
4893
  const comandoConfirmando = `${comando2} --confirmar ${empresa2}`;
4644
4894
  const modoEsperado = ENTORNO_LLAVE_REGISTRY[modo].isSandbox;
@@ -5541,63 +5791,15 @@ async function logout(ctx) {
5541
5791
  }
5542
5792
 
5543
5793
  // src/comandos/actualizar.ts
5544
- import { spawnSync as spawnSync2 } from "node:child_process";
5545
- import fs12 from "node:fs";
5546
- import path15 from "node:path";
5547
- import { fileURLToPath as fileURLToPath2 } from "node:url";
5548
- var real = (ruta) => {
5794
+ import fs13 from "node:fs";
5795
+ import path17 from "node:path";
5796
+ var real2 = (ruta) => {
5549
5797
  try {
5550
- return fs12.realpathSync(ruta);
5798
+ return fs13.realpathSync(ruta);
5551
5799
  } catch {
5552
5800
  return null;
5553
5801
  }
5554
5802
  };
5555
- var dentroDe = (ruta, carpeta) => ruta === carpeta || ruta.startsWith(carpeta + path15.sep);
5556
- function detectarInstalacion(bundle, raizGlobal) {
5557
- const bundleReal = real(bundle) ?? path15.resolve(bundle);
5558
- const segmentos = bundleReal.split(path15.sep);
5559
- if (segmentos.includes("_npx")) return { forma: "npx" };
5560
- for (const [gestor, forma] of [["npm", "npm-global"], ["pnpm", "pnpm-global"]]) {
5561
- const raiz = raizGlobal(gestor);
5562
- const carpeta = raiz ? real(path15.join(raiz, ...PAQUETE_DEL_CLI.split("/"))) : null;
5563
- if (carpeta && dentroDe(bundleReal, carpeta)) return { forma, carpetaDelPaquete: carpeta };
5564
- }
5565
- const marcaDeDependencia = ["node_modules", ...PAQUETE_DEL_CLI.split("/")].join(path15.sep);
5566
- if (bundleReal.includes(`${path15.sep}${marcaDeDependencia}${path15.sep}`)) {
5567
- return { forma: "no-reconocida", motivo: `el CLI est\xE1 instalado como dependencia de un proyecto (${bundleReal}): actual\xEDzalo con el gestor de ese proyecto, que es quien decide su versi\xF3n` };
5568
- }
5569
- return { forma: "no-reconocida", motivo: `el CLI que corre (${bundleReal}) no est\xE1 en la cach\xE9 de npx ni en la carpeta global de npm o de pnpm` };
5570
- }
5571
- function comandoDeActualizacion(forma, version, registro) {
5572
- const paquete = `${PAQUETE_DEL_CLI}@${version}`;
5573
- const conRegistro = registro ? [`--registry=${registro}`] : [];
5574
- if (forma === "npm-global") return { comando: "npm", args: ["install", "--global", ...conRegistro, paquete] };
5575
- if (forma === "pnpm-global") return { comando: "pnpm", args: ["add", "--global", ...conRegistro, paquete] };
5576
- return { comando: "npx", args: ["--yes", ...conRegistro, paquete, "skill", "renovar", "--json"] };
5577
- }
5578
- var legible = (c) => [c.comando, ...c.args].join(" ");
5579
- function ejecutarDeVerdad(comando2, args, opciones) {
5580
- const r = spawnSync2(comando2, args, { cwd: opciones.cwd, env: opciones.env, encoding: "utf8", shell: process.platform === "win32", timeout: 10 * 6e4 });
5581
- return { status: r.status, stdout: r.stdout ?? "", stderr: r.stderr ?? (r.error ? r.error.message : "") };
5582
- }
5583
- function entornoDeActualizacion(ctx) {
5584
- const registro = ctx.env.REDCUMBRE_NPM_REGISTRY || void 0;
5585
- return {
5586
- bundle: fileURLToPath2(import.meta.url),
5587
- ejecutar: ejecutarDeVerdad,
5588
- raizGlobal(gestor) {
5589
- const r = ejecutarDeVerdad(gestor, ["root", "--global"], { cwd: ctx.cwd, env: ctx.env });
5590
- const raiz = r.stdout.trim().split(/\r?\n/).pop() ?? "";
5591
- return r.status === 0 && raiz ? raiz : null;
5592
- },
5593
- async consultarUltima() {
5594
- const respuesta = await fetch(urlUltimaVersion(registro), { signal: AbortSignal.timeout(1e4), headers: { accept: "application/json" } });
5595
- if (!respuesta.ok) throw new Error(`el registro respondi\xF3 ${respuesta.status}`);
5596
- const cuerpo = await respuesta.json();
5597
- return typeof cuerpo.version === "string" ? cuerpo.version : null;
5598
- }
5599
- };
5600
- }
5601
5803
  function leerJson2(texto2) {
5602
5804
  try {
5603
5805
  const dato = JSON.parse(texto2);
@@ -5630,44 +5832,47 @@ async function actualizar(ctx, opciones, entorno = entornoDeActualizacion(ctx))
5630
5832
  const instalacion = detectarInstalacion(entorno.bundle, entorno.raizGlobal);
5631
5833
  if (instalacion.forma === "no-reconocida") {
5632
5834
  throw new ErrorCli(
5633
- `No actualic\xE9 nada: ${instalacion.motivo}. Para actualizarlo a mano: \xABnpm install --global ${PAQUETE_DEL_CLI}@${disponible}\xBB, \xABpnpm add --global ${PAQUETE_DEL_CLI}@${disponible}\xBB o, sin instalar, \xABnpx ${PAQUETE_DEL_CLI}@latest\xBB.`,
5835
+ `No actualic\xE9 nada: ${instalacion.motivo}. Para actualizarlo a mano: \xABnpm install --global ${PAQUETE_DEL_CLI}@${disponible}\xBB o \xABpnpm add --global ${PAQUETE_DEL_CLI}@${disponible}\xBB.`,
5634
5836
  CODIGOS_DE_SALIDA.error,
5635
5837
  { codigo: "INSTALACION_NO_RECONOCIDA", datos: { instalada: ctx.version, disponible } }
5636
5838
  );
5637
5839
  }
5638
5840
  const comando2 = comandoDeActualizacion(instalacion.forma, disponible, registro);
5841
+ const confirmado = instalacion.forma === "npx" ? `${prefijoPorNpx(ctx.version)} actualizar --confirmar` : COMANDO_ACTUALIZAR_CONFIRMADO;
5639
5842
  const pregunta = `\xBFActualizo el CLI de ${ctx.version} a ${disponible} con \xAB${legible(comando2)}\xBB? Tambi\xE9n renuevo la skill donde ya est\xE1.`;
5640
5843
  if (ctx.terminal) {
5641
- if (!await ctx.terminal.confirmar(pregunta)) throw faltaConfirmacion("No confirmaste: no actualic\xE9 nada.", COMANDO_ACTUALIZAR_CONFIRMADO);
5844
+ if (!await ctx.terminal.confirmar(pregunta)) throw faltaConfirmacion("No confirmaste: no actualic\xE9 nada.", confirmado);
5642
5845
  } else if (!opciones.confirmar) {
5643
5846
  throw faltaConfirmacion(
5644
- `Actualizar el CLI de ${ctx.version} a ${disponible} instala un paquete en este computador y lo decide la persona. D\xEDselo y, si acepta, corre \xAB${COMANDO_ACTUALIZAR_CONFIRMADO}\xBB. No actualic\xE9 nada.`,
5645
- COMANDO_ACTUALIZAR_CONFIRMADO
5847
+ `Actualizar el CLI de ${ctx.version} a ${disponible} instala un paquete en este computador y lo decide la persona. D\xEDselo y, si acepta, corre \xAB${confirmado}\xBB. No actualic\xE9 nada.`,
5848
+ confirmado
5646
5849
  );
5647
5850
  }
5648
5851
  salida.linea(`Actualizando: ${legible(comando2)}`);
5649
5852
  const corrida = entorno.ejecutar(comando2.comando, comando2.args, { cwd: ctx.cwd, env: ctx.env });
5650
- let skill = null;
5651
- if (instalacion.forma === "npx") {
5652
- if (corrida.status !== 0) throw errorDeActualizacion(comando2, corrida);
5653
- skill = leerJson2(corrida.stdout)?.skill ?? null;
5654
- } else {
5655
- if (corrida.status !== 0) throw errorDeActualizacion(comando2, corrida);
5656
- const bundleNuevo = path15.join(instalacion.carpetaDelPaquete, "dist", "redcumbre.js");
5657
- const version = entorno.ejecutar(process.execPath, [bundleNuevo, "--version"], { cwd: ctx.cwd, env: ctx.env });
5658
- if (version.status !== 0 || version.stdout.trim() !== disponible) {
5659
- throw new ErrorCli(
5660
- `\xAB${legible(comando2)}\xBB termin\xF3 bien, pero el CLI de ${instalacion.carpetaDelPaquete} responde \xAB${version.stdout.trim() || version.stderr.trim()}\xBB y no ${disponible}. Revisa con \xABredcumbre --version\xBB.`,
5661
- CODIGOS_DE_SALIDA.error,
5662
- { codigo: "ACTUALIZACION_INCOMPLETA", datos: { instalada: ctx.version, disponible } }
5663
- );
5664
- }
5665
- const renovacion = entorno.ejecutar(process.execPath, [bundleNuevo, "skill", "renovar", "--json"], { cwd: ctx.cwd, env: ctx.env });
5666
- skill = renovacion.status === 0 ? leerJson2(renovacion.stdout)?.skill ?? null : null;
5667
- if (skill === null) salida.aviso(`El CLI qued\xF3 en la versi\xF3n ${disponible}, pero no pude renovar la skill: corre \xABredcumbre skill renovar\xBB.`);
5853
+ if (corrida.status !== 0) throw errorDeActualizacion(comando2, corrida);
5854
+ const raizNpm = instalacion.forma === "npx" ? entorno.raizGlobal("npm") : null;
5855
+ const carpetaDelPaquete = instalacion.forma === "npx" ? raizNpm ? real2(path17.join(raizNpm, ...PAQUETE_DEL_CLI.split("/"))) : null : instalacion.carpetaDelPaquete;
5856
+ if (!carpetaDelPaquete) {
5857
+ throw new ErrorCli(
5858
+ `\xAB${legible(comando2)}\xBB termin\xF3 bien, pero no encuentro el CLI en la carpeta global de npm (${raizNpm ?? "npm root --global no respondi\xF3"}). Revisa con \xABredcumbre --version\xBB.`,
5859
+ CODIGOS_DE_SALIDA.error,
5860
+ { codigo: "ACTUALIZACION_INCOMPLETA", datos: { instalada: ctx.version, disponible } }
5861
+ );
5862
+ }
5863
+ const bundleNuevo = path17.join(carpetaDelPaquete, "dist", "redcumbre.js");
5864
+ const version = entorno.ejecutar(process.execPath, [bundleNuevo, "--version"], { cwd: ctx.cwd, env: ctx.env });
5865
+ if (version.status !== 0 || version.stdout.trim() !== disponible) {
5866
+ throw new ErrorCli(
5867
+ `\xAB${legible(comando2)}\xBB termin\xF3 bien, pero el CLI de ${carpetaDelPaquete} responde \xAB${version.stdout.trim() || version.stderr.trim()}\xBB y no ${disponible}. Revisa con \xABredcumbre --version\xBB.`,
5868
+ CODIGOS_DE_SALIDA.error,
5869
+ { codigo: "ACTUALIZACION_INCOMPLETA", datos: { instalada: ctx.version, disponible } }
5870
+ );
5668
5871
  }
5669
- if (instalacion.forma === "npx") salida.linea(`Listo: la skill qued\xF3 con la versi\xF3n ${disponible}. La pr\xF3xima vez corre \xABnpx ${PAQUETE_DEL_CLI}@latest\xBB para usar la \xFAltima.`);
5670
- else salida.linea(`\u2713 El CLI qued\xF3 en la versi\xF3n ${disponible}.`);
5872
+ const renovacion = entorno.ejecutar(process.execPath, [bundleNuevo, "skill", "renovar", "--json"], { cwd: ctx.cwd, env: ctx.env });
5873
+ const skill = renovacion.status === 0 ? leerJson2(renovacion.stdout)?.skill ?? null : null;
5874
+ if (skill === null) salida.aviso(`El CLI qued\xF3 en la versi\xF3n ${disponible}, pero no pude renovar la skill: corre \xABredcumbre skill renovar\xBB.`);
5875
+ salida.linea(instalacion.forma === "npx" ? `\u2713 El CLI qued\xF3 instalado en la versi\xF3n ${disponible}: desde ahora usa \xABredcumbre \u2026\xBB en vez de npx.` : `\u2713 El CLI qued\xF3 en la versi\xF3n ${disponible}.`);
5671
5876
  salida.resultado({ ok: true, actualizado: true, instalada: ctx.version, disponible, forma: instalacion.forma, comando: legible(comando2), skill });
5672
5877
  }
5673
5878
  function errorDeActualizacion(comando2, corrida) {
@@ -5742,7 +5947,7 @@ function errorDeUsoEnEspanol(mensaje) {
5742
5947
  }
5743
5948
  var TITULOS_AYUDA = { "Usage:": "Uso:", "Options:": "Opciones:", "Commands:": "Comandos:", "Arguments:": "Argumentos:" };
5744
5949
  var sumar = (valor, anteriores) => [...anteriores, valor];
5745
- var programa = new Command3().name("redcumbre").description("El CLI de REDCUMBRE: conecta tu proyecto en el modo de prueba, opera la API y pasa a producci\xF3n cuando est\xE9s listo.").version("0.5.1", "-v, --version", "muestra la versi\xF3n").helpOption("-h, --help", "muestra esta ayuda").helpCommand(false).usage("[opciones] [comando]").enablePositionalOptions().configureHelp({ styleTitle: (titulo) => TITULOS_AYUDA[titulo] ?? titulo, subcommandTerm: (comando2) => `${comando2.name()} ${comando2.usage()}`.trim() }).showHelpAfterError("(corre redcumbre --help para ver los comandos)").configureOutput({ outputError: (texto2, escribir2) => escribir2(`\u2717 ${errorDeUsoEnEspanol(texto2)}
5950
+ var programa = new Command3().name("redcumbre").description("El CLI de REDCUMBRE: conecta tu proyecto en el modo de prueba, opera la API y pasa a producci\xF3n cuando est\xE9s listo.").version("0.6.0", "-v, --version", "muestra la versi\xF3n").helpOption("-h, --help", "muestra esta ayuda").helpCommand(false).usage("[opciones] [comando]").enablePositionalOptions().configureHelp({ styleTitle: (titulo) => TITULOS_AYUDA[titulo] ?? titulo, subcommandTerm: (comando2) => `${comando2.name()} ${comando2.usage()}`.trim() }).showHelpAfterError("(corre redcumbre --help para ver los comandos)").configureOutput({ outputError: (texto2, escribir2) => escribir2(`\u2717 ${errorDeUsoEnEspanol(texto2)}
5746
5951
  `) }).exitOverride((error) => {
5747
5952
  if (error.code === "commander.helpDisplayed" || error.code === "commander.version" || error.code === "commander.help") process.exit(0);
5748
5953
  if (process.argv.includes("--json")) {
@@ -5753,7 +5958,7 @@ var programa = new Command3().name("redcumbre").description("El CLI de REDCUMBRE
5753
5958
  });
5754
5959
  var sinNavegador = () => new Option3("--sin-navegador", "no abre el navegador: imprime la URL");
5755
5960
  var empresa = () => new Option3("--empresa <slug>", "la empresa (tenantSlug); por omisi\xF3n, la del proyecto");
5756
- comando(programa, "init", "conecta el proyecto: llave de prueba, puntero en .env, skill del integrador y una comprobaci\xF3n con la llave (no escribe c\xF3digo)").addOption(empresa()).addOption(new Option3("--entorno <modo>", "retirada: para producci\xF3n usa pasar-a-produccion").hideHelp()).option("--carpeta <ruta>", "carpeta del proyecto (por omisi\xF3n, la actual)").addOption(sinNavegador()).action((o) => correr(o, (ctx) => init(ctx, o)));
5961
+ comando(programa, "init", "conecta el proyecto: llave de prueba, puntero en .env, skill del integrador y una comprobaci\xF3n con la llave (no escribe c\xF3digo)").addOption(empresa()).addOption(new Option3("--entorno <modo>", "retirada: para producci\xF3n usa pasar-a-produccion").hideHelp()).option("--carpeta <ruta>", "carpeta del proyecto (por omisi\xF3n, la actual)").addOption(sinNavegador()).action((o) => correr(o, (ctx) => init(ctx, o), { ofreceInstalar: true }));
5757
5962
  comando(programa, "pasar-a-produccion", "revisa que todo est\xE9 en orden y agrega la llave de producci\xF3n al proyecto (una persona escribe el slug; sin terminal, --confirmar <slug>)").addOption(empresa()).option("--servicios <lista>", "los servicios que activas en producci\xF3n, separados por coma").option("--confirmar <slug>", "confirma sin preguntar: el slug de la empresa (obligatorio sin terminal o con --json)").option("--instalar <comando>", "despu\xE9s de crear la llave, corre este comando con la llave s\xF3lo en REDCUMBRE_VALOR_LLAVE_PRODUCCION").option("--comprobar <comando>", "con --instalar: corre este comando sin la llave; tiene que imprimir el whoami de la empresa en producci\xF3n").addOption(sinNavegador()).action((o) => correr(o, (ctx) => pasarAProduccion(ctx, o)));
5758
5963
  comando(programa, "login", "inicia sesi\xF3n con tu cuenta de REDCUMBRE (sin terminal o sin navegador, entrega el enlace y el c\xF3digo para que la persona los apruebe)").option("--completar", "termina el login: espera hasta 90 segundos a que la persona apruebe el c\xF3digo y guarda la sesi\xF3n").addOption(sinNavegador()).action((o) => correr(o, (ctx) => login(ctx, o)));
5759
5964
  comando(programa, "logout", "cierra la sesi\xF3n: la revoca en el servidor de identidad y la borra de este computador").action((o) => correr(o, logout));
@@ -5787,6 +5992,7 @@ comando(programa, "consumo", "lo consumido del plan y los topes del d\xEDa").opt
5787
5992
  var comandoSkill = programa.command("skill").description("la skill del integrador que el CLI instala en tus carpetas de skills");
5788
5993
  comando(comandoSkill, "quitar", "quita la skill de tus carpetas y del proyecto, y no la vuelve a instalar").action((o) => correr(o, (ctx) => skillQuitar(ctx), { revisaPorSuCuenta: true }));
5789
5994
  comando(comandoSkill, "renovar", "renueva la skill donde ya est\xE1 con la de esta versi\xF3n del CLI (no toca lo que editaste)").option("--reemplazar-editada", "reemplaza tambi\xE9n la skill que editaste o copiaste a mano (pide confirmar)").option("--confirmar", "sin terminal, confirma el reemplazo de la skill editada").action((o) => correr(o, (ctx) => skillRenovar(ctx, o), { revisaPorSuCuenta: true }));
5995
+ comando(programa, "instalar", "deja instalado en este computador el CLI que corre por npx, en la misma versi\xF3n (pide confirmar)").option("--confirmar", "sin terminal, confirma la instalaci\xF3n: corre s\xF3lo despu\xE9s de que la persona acept\xF3").action((o) => correr(o, (ctx) => instalar(ctx, o), { revisaPorSuCuenta: true }));
5790
5996
  comando(programa, "actualizar", "actualiza el CLI a la \xFAltima versi\xF3n publicada y renueva la skill (pide confirmar)").option("--confirmar", "sin terminal, confirma la actualizaci\xF3n: corre s\xF3lo despu\xE9s de que la persona acept\xF3").action((o) => correr(o, (ctx) => actualizar(ctx, o), { revisaPorSuCuenta: true }));
5791
5997
  var comandoMcp = programa.command("mcp").description("el servidor MCP de REDCUMBRE en tu asistente de c\xF3digo");
5792
5998
  comando(comandoMcp, "agregar", "agrega el servidor MCP a la configuraci\xF3n de tu asistente (pide confirmar)").option("--asistente <asistente>", ASISTENTES_MCP.join(" o ")).action((o) => correr(o, (ctx) => mcpAgregar(ctx, o)));