@redcumbrecl/cli 0.6.6 → 0.6.8

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
@@ -883,12 +883,19 @@ var PAQUETE_CLI = PAQUETE_DEL_CLI;
883
883
  var REGISTRO_NPM = "https://registry.npmjs.org/";
884
884
  var urlUltimaVersion = (registro = REGISTRO_NPM) => `${registro.replace(/\/+$/, "")}/${PAQUETE_CLI}/latest`;
885
885
  var TIEMPO_MAXIMO_MS = 1500;
886
- var UN_DIA_MS = 24 * 60 * 60 * 1e3;
886
+ var VIGENCIA_DE_LA_MARCA_MS = 6e4;
887
+ var ESPERA_ENTRE_INTENTOS_MS = 24 * 60 * 60 * 1e3;
887
888
  var rutaMarcaVersion = (carpeta) => path3.join(carpeta, "aviso-version.json");
888
889
  function leerMarca(carpeta) {
889
890
  try {
890
891
  const marca = JSON.parse(fs3.readFileSync(rutaMarcaVersion(carpeta), "utf8"));
891
- return typeof marca.revisadoEn === "string" ? { revisadoEn: marca.revisadoEn, ultima: typeof marca.ultima === "string" ? marca.ultima : null } : null;
892
+ if (typeof marca.revisadoEn !== "string") return null;
893
+ const intento = marca.intento;
894
+ return {
895
+ revisadoEn: marca.revisadoEn,
896
+ ultima: typeof marca.ultima === "string" ? marca.ultima : null,
897
+ ...intento && typeof intento.version === "string" && typeof intento.en === "string" ? { intento: { version: intento.version, en: intento.en } } : {}
898
+ };
892
899
  } catch {
893
900
  return null;
894
901
  }
@@ -901,6 +908,15 @@ function escribirMarca(carpeta, marca) {
901
908
  } catch {
902
909
  }
903
910
  }
911
+ function yaSeIntento(carpeta, version, ahora) {
912
+ const intento = leerMarca(carpeta)?.intento;
913
+ if (!intento || intento.version !== version) return false;
914
+ return ahora.getTime() - Date.parse(intento.en) < ESPERA_ENTRE_INTENTOS_MS;
915
+ }
916
+ function marcarIntento(carpeta, version, ahora) {
917
+ const marca = leerMarca(carpeta) ?? { revisadoEn: ahora.toISOString(), ultima: version };
918
+ escribirMarca(carpeta, { ...marca, intento: { version, en: ahora.toISOString() } });
919
+ }
904
920
  function compararVersiones(a, b) {
905
921
  const partes = (v) => v.replace(/^v/, "").split("-")[0].split(".").map((n) => Number.parseInt(n, 10));
906
922
  const pa = partes(a);
@@ -919,10 +935,9 @@ async function consultarRegistro(url, senal) {
919
935
  return typeof cuerpo.version === "string" ? cuerpo.version : null;
920
936
  }
921
937
  var COMANDO_ACTUALIZAR = "redcumbre actualizar";
922
- var COMANDO_ACTUALIZAR_CONFIRMADO = `${COMANDO_ACTUALIZAR} --confirmar`;
923
938
  async function ultimaVersionConocida(opciones) {
924
939
  const marca = leerMarca(opciones.carpeta);
925
- if (marca && opciones.ahora.getTime() - Date.parse(marca.revisadoEn) < UN_DIA_MS) return { ultima: marca.ultima, consultado: false };
940
+ if (!opciones.sinMarca && marca && opciones.ahora.getTime() - Date.parse(marca.revisadoEn) < VIGENCIA_DE_LA_MARCA_MS) return { ultima: marca.ultima, consultado: false };
926
941
  let ultima = null;
927
942
  try {
928
943
  const senal = AbortSignal.timeout(TIEMPO_MAXIMO_MS);
@@ -930,22 +945,10 @@ async function ultimaVersionConocida(opciones) {
930
945
  } catch {
931
946
  ultima = null;
932
947
  }
933
- escribirMarca(opciones.carpeta, { revisadoEn: opciones.ahora.toISOString(), ultima });
948
+ escribirMarca(opciones.carpeta, { revisadoEn: opciones.ahora.toISOString(), ultima, ...marca?.intento ? { intento: marca.intento } : {} });
934
949
  return { ultima, consultado: true };
935
950
  }
936
- async function avisarSiHayVersionNueva(opciones) {
937
- const { ultima, consultado } = await ultimaVersionConocida(opciones);
938
- if (consultado && ultima && compararVersiones(ultima, opciones.version) > 0) {
939
- 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.
940
- `);
941
- }
942
- }
943
- async function actualizacionDisponible(opciones) {
944
- const { ultima } = await ultimaVersionConocida(opciones);
945
- if (!ultima || compararVersiones(ultima, opciones.version) <= 0) return null;
946
- return { instalada: opciones.version, disponible: ultima, comando: COMANDO_ACTUALIZAR_CONFIRMADO };
947
- }
948
- var avisoDeActualizacion = (a) => `Hay una versi\xF3n m\xE1s nueva del CLI: ${a.disponible} (tienes ${a.instalada}). Empieza tu respuesta, antes de lo que te pidieron, pregunt\xE1ndole a la persona si lo actualizas: \xABHay una versi\xF3n m\xE1s nueva del CLI de REDCUMBRE (${a.disponible}; tienes ${a.instalada}). \xBFLo actualizo?\xBB. Con su s\xED, c\xF3rrelo t\xFA: \xAB${a.comando}\xBB. Si ya se lo preguntaste en esta conversaci\xF3n y dijo que no, no vuelvas a preguntar.`;
951
+ var avisoDeActualizacion = (a, motivo) => `Hay una versi\xF3n m\xE1s nueva del CLI: ${a.disponible} (tienes ${a.instalada}), y no pudo actualizarse solo${motivo ? ` (${motivo})` : ""}. Corre \xAB${a.comando}\xBB ahora, sin preguntarle a la persona: deja al d\xEDa el CLI y la skill. Si vuelve a fallar, dile qu\xE9 pas\xF3.`;
949
952
  var SITIO_DOCS = PRODUCCION.docs;
950
953
  var ARCHIVO_VERSION_MINIMA = "cli-version-minima.txt";
951
954
  var COMANDO_DE_ACTUALIZACION = COMANDO_DE_ACTUALIZACION_DEL_CLI;
@@ -1828,1238 +1831,1273 @@ function recortar(valor, campos) {
1828
1831
  }
1829
1832
 
1830
1833
  // src/comandos/doctor.ts
1834
+ import fs7 from "node:fs";
1835
+ import path7 from "node:path";
1836
+
1837
+ // src/nucleo/skill.ts
1838
+ import { createHash, randomBytes } from "node:crypto";
1831
1839
  import fs6 from "node:fs";
1832
1840
  import path6 from "node:path";
1833
- async function doctor(ctx) {
1834
- const { salida, proyecto } = ctx;
1835
- const revisiones = [];
1836
- const anotar = (r) => {
1837
- revisiones.push(r);
1838
- salida.linea(`${r.ok ? "\u2713" : r.opcional ? "\xB7" : "\u2717"} ${r.detalle}${!r.ok && r.comando ? ` \u2192 ${r.comando}` : ""}`);
1839
- };
1840
- const haySesion = await ctx.haySesion();
1841
- anotar(
1842
- haySesion ? { revision: "sesion", ok: true, detalle: "Hay una sesi\xF3n iniciada en este computador." } : { revision: "sesion", ok: false, detalle: "No hay una sesi\xF3n iniciada en este computador.", comando: "redcumbre login" }
1843
- );
1844
- const estado2 = leerEstado(proyecto);
1845
- let slug = null;
1846
- if (estado2) {
1847
- slug = estado2.tenantSlug;
1848
- anotar({ revision: "empresa", ok: true, detalle: `El proyecto ${proyecto} apunta a la empresa ${slug}.` });
1849
- } else {
1850
- anotar({ revision: "empresa", ok: false, detalle: `La carpeta ${proyecto} no est\xE1 conectada con REDCUMBRE (falta .redcumbre/estado.json).`, comando: COMANDO_INIT });
1841
+ import { fileURLToPath } from "node:url";
1842
+ var NOMBRE_SKILL = "redcumbre";
1843
+ var MARCA_INICIO = "<!-- redcumbre:inicio -->";
1844
+ var MARCA_FIN = "<!-- redcumbre:fin -->";
1845
+ var sha256 = (texto2) => createHash("sha256").update(texto2).digest("hex");
1846
+ function carpetaDeLaSkill(aqui = path6.dirname(fileURLToPath(import.meta.url))) {
1847
+ const candidatas = [path6.join(aqui, "skill"), path6.join(aqui, "..", "skill"), path6.join(aqui, "..", "..", "skill")];
1848
+ for (const candidata of candidatas) {
1849
+ if (fs6.existsSync(path6.join(candidata, NOMBRE_SKILL, "SKILL.md"))) return candidata;
1851
1850
  }
1852
- for (const entorno of ENTORNOS_LLAVE) {
1853
- anotar(await revisarLlave(ctx, entorno, slug));
1851
+ 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, {
1852
+ codigo: "PAQUETE_INCOMPLETO"
1853
+ });
1854
+ }
1855
+ var ARCHIVO_FUENTE = {
1856
+ skill: [NOMBRE_SKILL, "SKILL.md"],
1857
+ tarifas: ["commands", "tarifas.md"],
1858
+ issue: ["commands", "issue.md"]
1859
+ };
1860
+ function contenidoEmpaquetado(fuenteDeRuta, fuente) {
1861
+ const carpeta = fuente ?? carpetaDeLaSkill();
1862
+ const archivo = path6.join(carpeta, ...ARCHIVO_FUENTE[fuenteDeRuta]);
1863
+ if (!fs6.existsSync(archivo)) {
1864
+ throw new ErrorCli(`El paquete del CLI est\xE1 incompleto: falta ${ARCHIVO_FUENTE[fuenteDeRuta].join("/")}. Reinstala el CLI con \xAB${COMANDO_DE_ACTUALIZACION}\xBB.`, CODIGOS_DE_SALIDA.error, {
1865
+ codigo: "PAQUETE_INCOMPLETO"
1866
+ });
1854
1867
  }
1855
- const gitignore = path6.join(proyecto, ".gitignore");
1856
- const lineas = new Set((fs6.existsSync(gitignore) ? fs6.readFileSync(gitignore, "utf8") : "").split(/\r?\n/).map((l) => l.trim()));
1857
- const faltanExclusiones = ["keys/", ".redcumbre/"].filter((l) => !lineas.has(l) && !lineas.has(`/${l}`));
1858
- const versionadas = ENTORNOS_LLAVE.map((e) => path6.relative(proyecto, rutaDeLaLlave(proyecto, e, ctx.env))).filter(
1859
- (relativa) => fs6.existsSync(path6.join(proyecto, relativa)) && estaVersionado(proyecto, relativa)
1860
- );
1861
- if (versionadas.length > 0) {
1862
- anotar({
1863
- revision: "exclusiones",
1864
- ok: false,
1865
- detalle: `La llave est\xE1 en el control de versiones (${versionadas.join(", ")}): s\xE1cala con \xABgit rm --cached ${versionadas.join(" ")}\xBB y rev\xF3cala en la web, porque qued\xF3 en el historial.`
1868
+ return fs6.readFileSync(archivo, "utf8");
1869
+ }
1870
+ function contenidoPorFuente(version, fuente) {
1871
+ const cache = /* @__PURE__ */ new Map();
1872
+ return (f) => {
1873
+ let texto2 = cache.get(f);
1874
+ if (texto2 === void 0) {
1875
+ texto2 = contenidoParaInstalar(contenidoEmpaquetado(f, fuente), version);
1876
+ cache.set(f, texto2);
1877
+ }
1878
+ return texto2;
1879
+ };
1880
+ }
1881
+ var LINEA_DE_VERSION = /^<!-- redcumbre-cli: (\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?) -->$/m;
1882
+ var FRONTMATTER = /^---\r?\n[\s\S]*?\r?\n---\r?\n/;
1883
+ var lineaDeVersion = (version) => `<!-- redcumbre-cli: ${version} -->`;
1884
+ function contenidoParaInstalar(fuente, version) {
1885
+ const frontmatter = fuente.match(FRONTMATTER);
1886
+ if (!frontmatter) {
1887
+ 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, {
1888
+ codigo: "PAQUETE_INCOMPLETO"
1866
1889
  });
1867
- } else if (faltanExclusiones.length > 0) {
1868
- anotar({ revision: "exclusiones", ok: false, detalle: `Al .gitignore le falta ${faltanExclusiones.join(" y ")}.`, comando: COMANDO_INIT });
1869
- } else {
1870
- anotar({ revision: "exclusiones", ok: true, detalle: "keys/ y .redcumbre/ est\xE1n fuera del control de versiones." });
1871
1890
  }
1891
+ const sinLinea = fuente.slice(frontmatter[0].length).replace(/^<!-- redcumbre-cli: [^\n]* -->\r?\n/, "");
1892
+ return `${frontmatter[0]}${lineaDeVersion(version)}
1893
+ ${sinLinea}`;
1894
+ }
1895
+ function versionDeLaSkill(texto2) {
1896
+ return texto2.match(LINEA_DE_VERSION)?.[1] ?? null;
1897
+ }
1898
+ var CODIGOS_TRANSITORIOS_WINDOWS = /* @__PURE__ */ new Set(["EPERM", "EACCES", "EBUSY"]);
1899
+ function esperarSincrono(ms) {
1900
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
1901
+ }
1902
+ function esErrorTransitorioDeWindows(error) {
1903
+ const codigo = error?.code;
1904
+ return typeof codigo === "string" && CODIGOS_TRANSITORIOS_WINDOWS.has(codigo);
1905
+ }
1906
+ function conReintentoEnWindows(operacion, opciones = {}) {
1907
+ const { plataforma = process.platform, esperar = esperarSincrono, presupuestoMs = 2500 } = opciones;
1908
+ let espera = 10;
1909
+ let gastado = 0;
1910
+ for (; ; ) {
1911
+ try {
1912
+ return operacion();
1913
+ } catch (error) {
1914
+ if (plataforma !== "win32" || !esErrorTransitorioDeWindows(error) || gastado >= presupuestoMs) throw error;
1915
+ const ms = Math.min(espera, presupuestoMs - gastado);
1916
+ esperar(ms);
1917
+ gastado += ms;
1918
+ espera = Math.min(espera * 2, 100);
1919
+ }
1920
+ }
1921
+ }
1922
+ function escribirAtomico(ruta, contenido) {
1923
+ fs6.mkdirSync(path6.dirname(ruta), { recursive: true });
1924
+ const temporal = `${ruta}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
1872
1925
  try {
1873
- const documento = await cargarDocumento(ctx.cliente, ctx.carpetaConfiguracion, salida);
1874
- anotar({
1875
- revision: "documento",
1876
- ok: true,
1877
- detalle: documento.copiaSinRevalidar ? `Uso la copia del documento del API sin revalidar (${documento.operaciones.length} operaciones).` : `El documento del API est\xE1 al d\xEDa (${documento.operaciones.length} operaciones).`
1878
- });
1926
+ fs6.writeFileSync(temporal, contenido);
1927
+ conReintentoEnWindows(() => fs6.renameSync(temporal, ruta));
1879
1928
  } catch (error) {
1880
- anotar({ revision: "documento", ok: false, detalle: `No pude leer el documento del API: ${error instanceof Error ? error.message : String(error)}` });
1929
+ fs6.rmSync(temporal, { force: true });
1930
+ throw error;
1931
+ }
1932
+ }
1933
+ function bloqueDeAgents() {
1934
+ return [
1935
+ MARCA_INICIO,
1936
+ "## REDCUMBRE",
1937
+ "",
1938
+ "Este proyecto se integra con la API de REDCUMBRE por medio del CLI `redcumbre`. Antes de tocar la integraci\xF3n lee la",
1939
+ "skill `redcumbre` (`.agents/skills/redcumbre/SKILL.md`). En resumen: busca la operaci\xF3n (`redcumbre buscar`), lee su",
1940
+ "contrato (`redcumbre api describir`), pru\xE9bala con `--ensayo`, consulta las fichas (`redcumbre guia`) y verifica el",
1941
+ "sitio (`redcumbre prueba verificar`). No leas ni imprimas `keys/`. Pasar a producci\xF3n lo confirma una persona.",
1942
+ "Si la persona escribe `redcumbre:tarifas` o `redcumbre:issue`, sigue las secciones 9 y 8 de la skill.",
1943
+ "H\xE1blale a la persona en espa\xF1ol, salvo que ella te escriba en otro idioma.",
1944
+ MARCA_FIN
1945
+ ].join("\n");
1946
+ }
1947
+ var rutaRegistroUsuario = (d) => path6.join(d.carpetaConfiguracion, "skill.json");
1948
+ var rutaEstadoDelProyecto = (proyecto) => path6.join(proyecto, ".redcumbre", "estado.json");
1949
+ function leerJson(ruta) {
1950
+ if (!fs6.existsSync(ruta)) return null;
1951
+ let texto2;
1952
+ try {
1953
+ texto2 = conReintentoEnWindows(() => fs6.readFileSync(ruta, "utf8"));
1954
+ } catch (error) {
1955
+ if (esErrorTransitorioDeWindows(error)) throw error;
1956
+ return null;
1881
1957
  }
1882
- if (!salida.json && ctx.terminal) {
1883
- await avisarSiHayVersionNueva({ carpeta: ctx.carpetaConfiguracion, version: ctx.version, ahora: ctx.ahora(), humano: process.stderr, registro: ctx.env.REDCUMBRE_NPM_REGISTRY });
1958
+ try {
1959
+ const dato = JSON.parse(texto2);
1960
+ return dato && typeof dato === "object" && !Array.isArray(dato) ? dato : null;
1961
+ } catch {
1962
+ return null;
1884
1963
  }
1885
- const faltantes = revisiones.filter((r) => !r.ok && !r.opcional).map((r) => ({ revision: r.revision, detalle: r.detalle, ...r.comando ? { comando: r.comando } : {} }));
1886
- if (faltantes.length > 0) {
1887
- throw new ErrorCli(`Hay ${faltantes.length === 1 ? "una cosa que arreglar" : `${faltantes.length} cosas que arreglar`} en el proyecto.`, CODIGOS_DE_SALIDA.error, {
1888
- codigo: "DOCTOR_CON_FALTANTES",
1889
- datos: { revisiones, faltantes }
1890
- });
1964
+ }
1965
+ function escribirJson(ruta, dato) {
1966
+ escribirAtomico(ruta, `${JSON.stringify(dato, null, 2)}
1967
+ `);
1968
+ }
1969
+ function leerRegistroUsuario(d) {
1970
+ return leerJson(rutaRegistroUsuario(d)) ?? {};
1971
+ }
1972
+ function guardarRegistroUsuario(d, registro) {
1973
+ escribirJson(rutaRegistroUsuario(d), registro);
1974
+ }
1975
+ function leerRegistroProyecto(proyecto) {
1976
+ const estado2 = leerJson(rutaEstadoDelProyecto(proyecto));
1977
+ return estado2?.skill ?? {};
1978
+ }
1979
+ function guardarRegistroProyecto(proyecto, registro) {
1980
+ const ruta = rutaEstadoDelProyecto(proyecto);
1981
+ const estado2 = leerJson(ruta) ?? {};
1982
+ escribirJson(ruta, { ...estado2, skill: registro });
1983
+ }
1984
+ var COMANDOS = ["tarifas", "issue"];
1985
+ var esComando = (o) => o.fuente !== "skill";
1986
+ var skillDeClaudeDe = (o) => esDeUsuario(o.id) ? "claude-usuario" : "claude-proyecto";
1987
+ function objetivos(d) {
1988
+ const deAmbito = (raiz, ambito, prefijo) => [
1989
+ { id: `claude-${ambito}`, archivo: path6.join(raiz, ".claude", "skills", NOMBRE_SKILL, "SKILL.md"), legible: `${prefijo}.claude/skills/${NOMBRE_SKILL}/SKILL.md`, fuente: "skill" },
1990
+ { id: `agents-${ambito}`, archivo: path6.join(raiz, ".agents", "skills", NOMBRE_SKILL, "SKILL.md"), legible: `${prefijo}.agents/skills/${NOMBRE_SKILL}/SKILL.md`, fuente: "skill" },
1991
+ ...COMANDOS.map(
1992
+ (comando2) => ({
1993
+ id: `claude-${ambito}-${comando2}`,
1994
+ archivo: path6.join(raiz, ".claude", "commands", NOMBRE_SKILL, `${comando2}.md`),
1995
+ legible: `${prefijo}.claude/commands/${NOMBRE_SKILL}/${comando2}.md`,
1996
+ fuente: comando2
1997
+ })
1998
+ )
1999
+ ];
2000
+ const lista2 = deAmbito(d.home, "usuario", "~/");
2001
+ if (d.proyecto) lista2.push(...deAmbito(d.proyecto, "proyecto", ""));
2002
+ return lista2;
2003
+ }
2004
+ var esDeUsuario = (id) => id.includes("-usuario");
2005
+ function resumir2(rutas, quitada) {
2006
+ let estado2 = "sin-cambios";
2007
+ if (quitada) estado2 = "quitada";
2008
+ else if (rutas.some((r) => r.accion === "editada")) estado2 = "editada";
2009
+ else if (rutas.some((r) => r.accion === "reemplazada-editada")) estado2 = "reemplazada-editada";
2010
+ else if (rutas.some((r) => r.accion === "instalada")) estado2 = "instalada";
2011
+ else if (rutas.some((r) => r.accion === "actualizada")) estado2 = "actualizada";
2012
+ return { estado: estado2, rutas };
2013
+ }
2014
+ var marcaDeTiempoDeLaCopia = (ahora) => ahora.toISOString().slice(0, 19).replace(/[-:]/g, "").replace("T", "-");
2015
+ function guardarCopiaDeLoEditado(archivo, ahora) {
2016
+ const base = `${archivo}.editada-${marcaDeTiempoDeLaCopia(ahora)}`;
2017
+ for (let n = 1; n < 100; n++) {
2018
+ const destino = n === 1 ? base : `${base}-${n}`;
2019
+ try {
2020
+ conReintentoEnWindows(() => fs6.copyFileSync(archivo, destino, fs6.constants.COPYFILE_EXCL));
2021
+ return path6.resolve(destino);
2022
+ } catch (error) {
2023
+ if (error.code === "EEXIST") continue;
2024
+ throw error;
2025
+ }
1891
2026
  }
1892
- salida.linea("Todo en orden.");
1893
- salida.resultado({ ok: true, proyecto, revisiones, faltantes: [] });
2027
+ throw new Error(`ya hay demasiadas copias de ${archivo} con la misma hora`);
1894
2028
  }
1895
- async function revisarLlave(ctx, entorno, slug) {
1896
- const revision = `llave-${entorno}`;
1897
- const nombre = etiquetaLlave(entorno);
1898
- const ruta = path6.relative(ctx.proyecto, rutaDeLaLlave(ctx.proyecto, entorno, ctx.env)) || rutaDeLaLlave(ctx.proyecto, entorno, ctx.env);
1899
- const archivo = llaveDelEntorno(ctx.proyecto, entorno, ctx.env);
1900
- if (!archivo) {
1901
- return entorno === "prueba" ? { revision, ok: false, detalle: `Falta la ${nombre} (${ruta}).`, comando: COMANDO_INIT } : { revision, ok: false, opcional: true, detalle: `El proyecto todav\xEDa no tiene ${nombre}.`, comando: COMANDO_PASAR_A_PRODUCCION };
2029
+ var motivoDe = (error) => error instanceof Error ? error.message : String(error);
2030
+ function reconciliar(archivo, nuevo, registrado, ahora) {
2031
+ const hashNuevo = sha256(nuevo);
2032
+ const existe = fs6.existsSync(archivo);
2033
+ if (!existe) {
2034
+ if (registrado) return { accion: "borrada", hash: null };
2035
+ escribirAtomico(archivo, nuevo);
2036
+ return { accion: "instalada", hash: hashNuevo };
1902
2037
  }
1903
- if (slug && archivo.tenantSlug !== slug) {
1904
- return { revision, ok: false, detalle: `La ${nombre} es de ${archivo.tenantSlug}, pero el proyecto apunta a ${slug}.`, comando: COMANDO_INIT };
2038
+ const hashActual = sha256(conReintentoEnWindows(() => fs6.readFileSync(archivo)));
2039
+ if (registrado === void 0) {
2040
+ if (hashActual === hashNuevo) return { accion: "sin-cambios", hash: hashNuevo };
2041
+ return reemplazarConCopia(archivo, nuevo, hashNuevo, ahora);
1905
2042
  }
2043
+ if (hashActual !== registrado) return hashActual === hashNuevo ? { accion: "sin-cambios", hash: hashNuevo } : reemplazarConCopia(archivo, nuevo, hashNuevo, ahora);
2044
+ if (hashActual === hashNuevo) return { accion: "sin-cambios", hash: hashNuevo };
2045
+ escribirAtomico(archivo, nuevo);
2046
+ return { accion: "actualizada", hash: hashNuevo };
2047
+ }
2048
+ function reemplazarConCopia(archivo, nuevo, hashNuevo, ahora) {
2049
+ let copia;
1906
2050
  try {
1907
- const r = await ctx.cliente.whoami(archivo.token, archivo.tenantSlug);
1908
- if (r.estado === "rechazada") return { revision, ok: false, detalle: `La API rechaza la ${nombre} (${ruta}): fue revocada o venci\xF3.`, comando: entorno === "prueba" ? COMANDO_INIT : COMANDO_PASAR_A_PRODUCCION };
1909
- if (r.sandbox !== (entorno === "prueba")) {
1910
- return { revision, ok: false, detalle: `El archivo ${ruta} no trae una ${nombre}: seg\xFAn la API es de otro modo.`, comando: entorno === "prueba" ? COMANDO_INIT : COMANDO_PASAR_A_PRODUCCION };
1911
- }
1912
- return { revision, ok: true, detalle: `La ${nombre} funciona (${r.tenant.nombre}).` };
2051
+ copia = guardarCopiaDeLoEditado(archivo, ahora);
1913
2052
  } catch (error) {
1914
- return { revision, ok: false, detalle: `No pude comprobar la ${nombre}: ${error instanceof Error ? error.message : String(error)}` };
2053
+ return { accion: "editada", hash: null, error: motivoDe(error) };
1915
2054
  }
2055
+ escribirAtomico(archivo, nuevo);
2056
+ return { accion: "reemplazada-editada", hash: hashNuevo, copia };
1916
2057
  }
1917
- async function panel(ctx, opciones) {
1918
- const slug = empresaDelProyecto(ctx, opciones.empresa);
1919
- const url = `${ctx.servidores.web}${rutaDeEmpresa(slug, "/dashboard")}`;
1920
- const abierto = opciones.sinNavegador ? false : await ctx.abrir(url);
1921
- ctx.salida.linea(abierto ? `Abr\xED el panel de ${slug} en el navegador: ${url}` : `El panel de ${slug}: ${url}`);
1922
- ctx.salida.resultado({ ok: true, empresa: slug, url, abierto });
2058
+ var regexBloque = () => new RegExp(`${MARCA_INICIO.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[\\s\\S]*?${MARCA_FIN.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`);
2059
+ function extraerBloque(texto2) {
2060
+ return texto2.match(regexBloque())?.[0] ?? null;
1923
2061
  }
1924
-
1925
- // src/comandos/emisores.ts
1926
- import fs10 from "node:fs";
1927
- import path11 from "node:path";
1928
-
1929
- // src/comandos/emisores-operaciones.ts
1930
- var RUT_FILTRO = { bandera: "--rut <rut>", obligatoria: false, tipo: "texto", destino: { en: "consulta", nombre: "rut" } };
1931
- var ESTADO_FILTRO = { bandera: "--estado <estado>", obligatoria: false, tipo: "texto", destino: { en: "consulta", nombre: "estado" } };
1932
- var INTEGRACION_FILTRO = { bandera: "--integracion <tipo>", obligatoria: false, tipo: "texto", destino: { en: "consulta", nombre: "tipoIntegracion" } };
1933
- var CREDENCIAL_FILTRO = { bandera: "--credencial <estado>", obligatoria: false, tipo: "texto", destino: { en: "consulta", nombre: "credencialEstado" } };
1934
- var ACTIVO_FILTRO = { bandera: "--activo <true|false>", obligatoria: false, tipo: "booleano", destino: { en: "consulta", nombre: "activo" }, valores: ["true", "false"] };
1935
- var TRIBUTARIA_FILTRO = { bandera: "--tributaria <true|false>", obligatoria: false, tipo: "booleano", destino: { en: "consulta", nombre: "esTributaria" }, valores: ["true", "false"] };
1936
- var LIMITE = { bandera: "--limite <n>", obligatoria: false, tipo: "entero", destino: { en: "consulta", nombre: "limit" } };
1937
- var DESDE = { bandera: "--desde <n>", obligatoria: false, tipo: "entero", destino: { en: "consulta", nombre: "offset" } };
1938
- var TODAS = { bandera: "--todas", obligatoria: false, tipo: "interruptor", destino: { en: "ninguno" } };
1939
- var INCLUIR_ARCHIVADOS = { bandera: "--incluir-archivados", obligatoria: false, tipo: "interruptor", destino: { en: "consulta", nombre: "includeInactive", valorFijo: "true" } };
1940
- var CUERPO_OBLIGATORIO = { bandera: "--cuerpo <json|@archivo|->", obligatoria: true, tipo: "cuerpo", destino: { en: "cuerpo-completo" } };
1941
- var CUERPO_OPCIONAL = { bandera: "--cuerpo <json|@archivo|->", obligatoria: false, tipo: "cuerpo", destino: { en: "cuerpo-completo" } };
1942
- var ARCHIVO_LOGO = { bandera: "--archivo <ruta>", obligatoria: true, tipo: "archivo", destino: { en: "formulario", nombre: "logo" } };
1943
- var TIPOS_DE_CERTIFICACION = { bandera: "--tipos <lista>", obligatoria: true, tipo: "lista-de-enteros", destino: { en: "cuerpo", nombre: "tiposDte" } };
1944
- var CORREO_DE_CONTACTO = { bandera: "--correo <correo>", obligatoria: true, tipo: "texto", destino: { en: "cuerpo", nombre: "emailContacto" } };
1945
- var TELEFONO_DE_CONTACTO = { bandera: "--telefono <tel\xE9fono>", obligatoria: true, tipo: "texto", destino: { en: "cuerpo", nombre: "telefonoContacto" } };
1946
- var RUT_DE_CONFIRMACION = { bandera: "--rut <rut>", obligatoria: true, tipo: "texto", destino: { en: "cuerpo", nombre: "confirmacionRut" } };
1947
- var MOTIVO_OPCIONAL = { bandera: "--motivo <motivo>", obligatoria: false, tipo: "texto", destino: { en: "cuerpo", nombre: "motivo" } };
1948
- var TIPO_DTE_DEL_AMBIENTE = { bandera: "--tipo-dte <n>", obligatoria: true, tipo: "entero", destino: { en: "cuerpo", nombre: "tipoDte" } };
1949
- var AMBIENTE_DEL_TIPO = { bandera: "--ambiente <CERTIFICACION|PRODUCCION>", obligatoria: true, tipo: "ambiente", destino: { en: "cuerpo", nombre: "ambiente" }, valores: ["CERTIFICACION", "PRODUCCION"] };
1950
- var TIPO_DE_EMISOR_A_REVOCAR = { bandera: "--tipo <tributario|dte>", obligatoria: true, tipo: "texto", destino: { en: "cuerpo", nombre: "tipoEmisor" }, valores: ["tributario", "dte"] };
1951
- var MOTIVO_DE_REVOCACION = { bandera: "--motivo <motivo>", obligatoria: false, tipo: "texto", destino: { en: "cuerpo", nombre: "motivoRevocacion" } };
1952
- var OPERACIONES_EMISORES = [
1953
- {
1954
- // 1
1955
- comando: ["dte", "listar"],
1956
- operationId: "listarEmisoresDte",
1957
- metodo: "GET",
1958
- ruta: "/{tenantSlug}/emisores",
1959
- argumentos: [],
1960
- banderas: [RUT_FILTRO, ESTADO_FILTRO, INTEGRACION_FILTRO, LIMITE, DESDE, TODAS],
1961
- salida: "tabla",
1962
- columnas: ["emisorId", "rut", "razonSocial", "tipoIntegracion", "estado"],
1963
- confirmacion: "efecto"
1964
- },
1965
- {
1966
- // 2
1967
- comando: ["dte", "por-defecto"],
1968
- operationId: "listarEmisoresDtePorDefecto",
1969
- metodo: "GET",
1970
- ruta: "/{tenantSlug}/emisores/default",
1971
- argumentos: [],
1972
- banderas: [],
1973
- salida: "tabla",
1974
- columnas: ["emisorId", "rut", "razonSocial", "tipoIntegracion"],
1975
- confirmacion: "efecto"
1976
- },
1977
- {
1978
- // 3
1979
- comando: ["dte", "existe"],
1980
- operationId: "verificarRutEmisorDte",
1981
- metodo: "GET",
1982
- ruta: "/{tenantSlug}/emisores/check-rut/{rut}",
1983
- argumentos: ["rut"],
1984
- banderas: [],
1985
- salida: "ficha",
1986
- confirmacion: "efecto"
1987
- },
1988
- {
1989
- // 4
1990
- comando: ["dte", "ver"],
1991
- operationId: "obtenerEmisorDte",
1992
- metodo: "GET",
1993
- ruta: "/{tenantSlug}/emisores/{id}",
1994
- argumentos: ["id"],
1995
- banderas: [INCLUIR_ARCHIVADOS],
1996
- salida: "ficha",
1997
- confirmacion: "efecto"
1998
- },
1999
- {
2000
- // 5
2001
- comando: ["dte", "certificacion", "verificar"],
2002
- operationId: "verificarCertificacionTipoEmisorDte",
2003
- metodo: "GET",
2004
- ruta: "/{tenantSlug}/emisores/{id}/verificar-certificacion/{tipoDte}",
2005
- argumentos: ["id", "tipoDte"],
2006
- banderas: [],
2007
- salida: "ficha",
2008
- confirmacion: "efecto"
2009
- },
2010
- {
2011
- // 6
2012
- comando: ["dte", "certificacion", "tipos"],
2013
- operationId: "listarTiposCertificablesEmisorDte",
2014
- metodo: "GET",
2015
- ruta: "/{tenantSlug}/emisores/{id}/tipos-dte-certificables",
2016
- argumentos: ["id"],
2017
- banderas: [],
2018
- salida: "ficha",
2019
- confirmacion: "efecto"
2020
- },
2021
- {
2022
- // 7
2023
- comando: ["dte", "certificacion", "estado"],
2024
- operationId: "consultarEstadoCertificacionRutEmisorDte",
2025
- metodo: "GET",
2026
- ruta: "/{tenantSlug}/emisores/{id}/estado-certificacion-rut",
2027
- argumentos: ["id"],
2028
- banderas: [],
2029
- salida: "ficha",
2030
- confirmacion: "efecto"
2031
- },
2032
- {
2033
- // 8
2034
- comando: ["dte", "mipyme", "estado"],
2035
- operationId: "consultarEstadoMipymeEmisorDte",
2036
- metodo: "GET",
2037
- ruta: "/{tenantSlug}/emisores/{id}/mipyme/estado",
2038
- argumentos: ["id"],
2039
- banderas: [],
2040
- salida: "ficha",
2041
- confirmacion: "efecto"
2042
- },
2043
- {
2044
- // 9
2045
- comando: ["dte", "solicitudes"],
2046
- operationId: "listarSolicitudesCertificacionEmisorDte",
2047
- metodo: "GET",
2048
- ruta: "/{tenantSlug}/emisores/{id}/solicitudes",
2049
- argumentos: ["id"],
2050
- banderas: [],
2051
- salida: "tabla",
2052
- columnas: ["solicitudId", "tipoSolicitud", "estado", "solicitadoEn"],
2053
- confirmacion: "efecto"
2054
- },
2055
- {
2056
- // 10
2057
- comando: ["dte", "logo", "ver"],
2058
- operationId: "obtenerLogoEmisorDte",
2059
- metodo: "GET",
2060
- ruta: "/{tenantSlug}/emisores/{id}/logo",
2061
- argumentos: ["id"],
2062
- banderas: [],
2063
- salida: "ficha",
2064
- confirmacion: "efecto"
2065
- },
2066
- {
2067
- // 11
2068
- comando: ["dte", "editar"],
2069
- operationId: "actualizarEmisorDte",
2070
- metodo: "PATCH",
2071
- ruta: "/{tenantSlug}/emisores/{id}",
2072
- argumentos: ["id"],
2073
- banderas: [CUERPO_OBLIGATORIO],
2074
- salida: "accion",
2075
- hecho: "Emisor actualizado.",
2076
- confirmacion: "efecto"
2077
- },
2078
- {
2079
- // 12
2080
- comando: ["dte", "fijar-por-defecto"],
2081
- operationId: "asignarEmisorDtePorDefecto",
2082
- metodo: "PATCH",
2083
- ruta: "/{tenantSlug}/emisores/{id}/set-default",
2084
- argumentos: ["id"],
2085
- banderas: [],
2086
- salida: "accion",
2087
- hecho: "Emisor fijado por defecto.",
2088
- confirmacion: "efecto"
2089
- },
2090
- {
2091
- // 13
2092
- comando: ["dte", "reactivar"],
2093
- operationId: "reactivarEmisorDte",
2094
- metodo: "PATCH",
2095
- ruta: "/{tenantSlug}/emisores/{id}/reactivate",
2096
- argumentos: ["id"],
2097
- banderas: [CUERPO_OPCIONAL],
2098
- salida: "accion",
2099
- hecho: "Emisor reactivado.",
2100
- confirmacion: "efecto"
2101
- },
2102
- {
2103
- // 14
2104
- comando: ["dte", "tipos-integracion", "crear"],
2105
- operationId: "crearTipoIntegracionEmisorDte",
2106
- metodo: "POST",
2107
- ruta: "/{tenantSlug}/emisores/{id}/tipos-integracion",
2108
- argumentos: ["id"],
2109
- banderas: [CUERPO_OBLIGATORIO],
2110
- salida: "accion",
2111
- hecho: "Tipo de integraci\xF3n creado.",
2112
- confirmacion: "efecto"
2113
- },
2114
- {
2115
- // 15
2116
- comando: ["dte", "tipos-integracion", "editar"],
2117
- operationId: "actualizarTipoIntegracionEmisorDte",
2118
- metodo: "PATCH",
2119
- ruta: "/{tenantSlug}/emisores/{id}/tipos-integracion/{tiId}",
2120
- argumentos: ["id", "tiId"],
2121
- banderas: [CUERPO_OBLIGATORIO],
2122
- salida: "accion",
2123
- hecho: "Tipo de integraci\xF3n actualizado.",
2124
- confirmacion: "efecto"
2125
- },
2126
- {
2127
- // 16
2128
- comando: ["dte", "logo", "subir"],
2129
- operationId: "actualizarLogoEmisorDte",
2130
- metodo: "POST",
2131
- ruta: "/{tenantSlug}/emisores/{id}/logo",
2132
- argumentos: ["id"],
2133
- banderas: [ARCHIVO_LOGO],
2134
- salida: "accion",
2135
- hecho: "Logo actualizado.",
2136
- confirmacion: "efecto"
2137
- },
2138
- {
2139
- // 17
2140
- comando: ["dte", "logo", "quitar"],
2141
- operationId: "eliminarLogoEmisorDte",
2142
- metodo: "DELETE",
2143
- ruta: "/{tenantSlug}/emisores/{id}/logo",
2144
- argumentos: ["id"],
2145
- banderas: [],
2146
- salida: "accion",
2147
- hecho: "Logo eliminado.",
2148
- confirmacion: "efecto"
2149
- },
2150
- {
2151
- // 18
2152
- comando: ["dte", "info-pago", "guardar"],
2153
- operationId: "actualizarInfoPagoEmisorDte",
2154
- metodo: "PUT",
2155
- ruta: "/{tenantSlug}/emisores/{id}/info-pago",
2156
- argumentos: ["id"],
2157
- banderas: [CUERPO_OBLIGATORIO],
2158
- salida: "accion",
2159
- hecho: "Informaci\xF3n de pago guardada.",
2160
- confirmacion: "efecto"
2161
- },
2162
- {
2163
- // 19
2164
- comando: ["dte", "info-pago", "quitar"],
2165
- operationId: "eliminarInfoPagoEmisorDte",
2166
- metodo: "DELETE",
2167
- ruta: "/{tenantSlug}/emisores/{id}/info-pago",
2168
- argumentos: ["id"],
2169
- banderas: [],
2170
- salida: "accion",
2171
- hecho: "Informaci\xF3n de pago eliminada.",
2172
- confirmacion: "efecto"
2173
- },
2174
- {
2175
- // 20
2176
- comando: ["dte", "resolver-conflictos"],
2177
- operationId: "resolverConflictosEmisorDte",
2178
- metodo: "POST",
2179
- ruta: "/{tenantSlug}/emisores/{id}/resolver-conflictos",
2180
- argumentos: ["id"],
2181
- banderas: [CUERPO_OBLIGATORIO],
2182
- salida: "accion",
2183
- hecho: "Conflictos resueltos.",
2184
- confirmacion: "efecto"
2185
- },
2186
- {
2187
- // 21
2188
- comando: ["dte", "certificacion", "certificar-tipos"],
2189
- operationId: "crearSolicitudCertificacionTiposEmisorDte",
2190
- metodo: "POST",
2191
- ruta: "/{tenantSlug}/emisores/{id}/certificar-tipos",
2192
- argumentos: ["id"],
2193
- banderas: [TIPOS_DE_CERTIFICACION, CORREO_DE_CONTACTO, TELEFONO_DE_CONTACTO],
2194
- salida: "accion",
2195
- hecho: "Certificaci\xF3n de tipos solicitada.",
2196
- confirmacion: "escrita",
2197
- aviso: "Esto le pide al SII certificar al contribuyente, con el RUT de su representante legal."
2198
- },
2199
- {
2200
- // 22
2201
- comando: ["dte", "migrar"],
2202
- operationId: "crearSolicitudMigracionEmisorDte",
2203
- metodo: "POST",
2204
- ruta: "/{tenantSlug}/emisores/{id}/migrar",
2205
- argumentos: ["id"],
2206
- banderas: [TIPOS_DE_CERTIFICACION, CORREO_DE_CONTACTO, TELEFONO_DE_CONTACTO],
2207
- salida: "accion",
2208
- hecho: "Migraci\xF3n solicitada.",
2209
- confirmacion: "escrita",
2210
- aviso: "Esto le pide al SII migrar el sistema de facturaci\xF3n del contribuyente. Puede dejar sin uso los folios que tenga."
2211
- },
2212
- {
2213
- // 23
2214
- comando: ["dte", "certificacion", "desistir"],
2215
- operationId: "cancelarCertificacionEmisorDte",
2216
- metodo: "POST",
2217
- ruta: "/{tenantSlug}/emisores/{id}/desistir-certificacion",
2218
- argumentos: ["id"],
2219
- banderas: [RUT_DE_CONFIRMACION, MOTIVO_OPCIONAL],
2220
- salida: "accion",
2221
- hecho: "Desististe de la certificaci\xF3n.",
2222
- confirmacion: "escrita",
2223
- aviso: "Esto archiva el emisor y cierra sus solicitudes de certificaci\xF3n."
2224
- },
2225
- {
2226
- // 24
2227
- comando: ["dte", "mipyme", "habilitar"],
2228
- operationId: "registrarEmisorDteEnPortalMipyme",
2229
- metodo: "POST",
2230
- ruta: "/{tenantSlug}/emisores/{id}/mipyme/habilitar",
2231
- argumentos: ["id"],
2232
- banderas: [],
2233
- salida: "accion",
2234
- hecho: "Portal MiPyme habilitado.",
2235
- confirmacion: "escrita",
2236
- aviso: "Esto inscribe al contribuyente en el Portal MiPyme del SII. Puede dejar sin uso los folios de mercado que tenga."
2237
- },
2238
- {
2239
- // 25
2240
- comando: ["dte", "ambiente"],
2241
- operationId: "cambiarAmbienteTipoEmisorDte",
2242
- metodo: "PATCH",
2243
- ruta: "/{tenantSlug}/emisores/{id}/ambiente",
2244
- argumentos: ["id"],
2245
- banderas: [TIPO_DTE_DEL_AMBIENTE, AMBIENTE_DEL_TIPO],
2246
- salida: "accion",
2247
- hecho: "Ambiente cambiado.",
2248
- confirmacion: "escrita",
2249
- aviso: "Esto cambia el ambiente del SII por el que sale ese tipo de documento."
2250
- },
2251
- {
2252
- // 26
2253
- comando: ["dte", "archivar"],
2254
- operationId: "archivarEmisorDte",
2255
- metodo: "DELETE",
2256
- ruta: "/{tenantSlug}/emisores/{id}",
2257
- argumentos: ["id"],
2258
- banderas: [RUT_DE_CONFIRMACION],
2259
- salida: "accion",
2260
- hecho: "Emisor archivado.",
2261
- archiva: true,
2262
- confirmacion: "escrita",
2263
- aviso: "Esto saca al emisor de la operaci\xF3n y deja de cobrarse."
2264
- },
2265
- {
2266
- // 27
2267
- comando: ["tributarios", "archivar"],
2268
- operationId: "archivarEmisorTributario",
2269
- metodo: "DELETE",
2270
- ruta: "/{tenantSlug}/emisores-tributarios/{id}",
2271
- argumentos: ["id"],
2272
- banderas: [],
2273
- salida: "accion",
2274
- hecho: "Emisor archivado.",
2275
- archiva: true,
2276
- confirmacion: "escrita",
2277
- aviso: "Esto saca al emisor de la operaci\xF3n y deja de cobrarse."
2278
- },
2279
- {
2280
- // 28
2281
- comando: ["tributarios", "listar"],
2282
- operationId: "listarEmisoresTributarios",
2283
- metodo: "GET",
2284
- ruta: "/{tenantSlug}/emisores-tributarios",
2285
- argumentos: [],
2286
- banderas: [RUT_FILTRO, ESTADO_FILTRO, CREDENCIAL_FILTRO, LIMITE, DESDE, TODAS],
2287
- salida: "tabla",
2288
- columnas: ["emisorId", "rut", "razonSocial", "estado", "credencialEstado"],
2289
- confirmacion: "efecto"
2290
- },
2291
- {
2292
- // 29
2293
- comando: ["tributarios", "por-defecto"],
2294
- operationId: "obtenerEmisorTributarioPorDefecto",
2295
- metodo: "GET",
2296
- ruta: "/{tenantSlug}/emisores-tributarios/default",
2297
- argumentos: [],
2298
- banderas: [],
2299
- salida: "ficha",
2300
- confirmacion: "efecto"
2301
- },
2302
- {
2303
- // 30
2304
- comando: ["tributarios", "existe"],
2305
- operationId: "consultarRutEmisorTributario",
2306
- metodo: "GET",
2307
- ruta: "/{tenantSlug}/emisores-tributarios/check-rut/{rut}",
2308
- argumentos: ["rut"],
2309
- banderas: [],
2310
- salida: "ficha",
2311
- confirmacion: "efecto"
2312
- },
2313
- {
2314
- // 31
2315
- comando: ["tributarios", "ver"],
2316
- operationId: "obtenerEmisorTributario",
2317
- metodo: "GET",
2318
- ruta: "/{tenantSlug}/emisores-tributarios/{id}",
2319
- argumentos: ["id"],
2320
- banderas: [INCLUIR_ARCHIVADOS],
2321
- salida: "ficha",
2322
- confirmacion: "efecto"
2323
- },
2324
- {
2325
- // 32
2326
- comando: ["tributarios", "logo", "ver"],
2327
- operationId: "obtenerLogoEmisorTributario",
2328
- metodo: "GET",
2329
- ruta: "/{tenantSlug}/emisores-tributarios/{id}/logo",
2330
- argumentos: ["id"],
2331
- banderas: [],
2332
- salida: "ficha",
2333
- confirmacion: "efecto"
2334
- },
2335
- {
2336
- // 33
2337
- comando: ["tributarios", "certificado"],
2338
- operationId: "obtenerCertificadoEmisorTributario",
2339
- metodo: "GET",
2340
- ruta: "/{tenantSlug}/emisores-tributarios/{id}/certificado",
2341
- argumentos: ["id"],
2342
- banderas: [],
2343
- salida: "ficha",
2344
- confirmacion: "efecto"
2345
- },
2346
- {
2347
- // 34
2348
- comando: ["tributarios", "editar"],
2349
- operationId: "actualizarEmisorTributario",
2350
- metodo: "PATCH",
2351
- ruta: "/{tenantSlug}/emisores-tributarios/{id}",
2352
- argumentos: ["id"],
2353
- banderas: [CUERPO_OBLIGATORIO],
2354
- salida: "accion",
2355
- hecho: "Emisor actualizado.",
2356
- confirmacion: "efecto"
2357
- },
2358
- {
2359
- // 35
2360
- comando: ["tributarios", "fijar-por-defecto"],
2361
- operationId: "cambiarEmisorTributarioPorDefecto",
2362
- metodo: "PATCH",
2363
- ruta: "/{tenantSlug}/emisores-tributarios/{id}/set-default",
2364
- argumentos: ["id"],
2365
- banderas: [],
2366
- salida: "accion",
2367
- hecho: "Emisor fijado por defecto.",
2368
- confirmacion: "efecto"
2369
- },
2370
- {
2371
- // 36
2372
- comando: ["tributarios", "reactivar"],
2373
- operationId: "reactivarEmisorTributario",
2374
- metodo: "PATCH",
2375
- ruta: "/{tenantSlug}/emisores-tributarios/{id}/reactivate",
2376
- argumentos: ["id"],
2377
- banderas: [CUERPO_OPCIONAL],
2378
- salida: "accion",
2379
- hecho: "Emisor reactivado.",
2380
- confirmacion: "efecto"
2381
- },
2382
- {
2383
- // 37
2384
- comando: ["tributarios", "logo", "subir"],
2385
- operationId: "actualizarLogoEmisorTributario",
2386
- metodo: "POST",
2387
- ruta: "/{tenantSlug}/emisores-tributarios/{id}/logo",
2388
- argumentos: ["id"],
2389
- banderas: [ARCHIVO_LOGO],
2390
- salida: "accion",
2391
- hecho: "Logo actualizado.",
2392
- confirmacion: "efecto"
2393
- },
2394
- {
2395
- // 38
2396
- comando: ["tributarios", "logo", "quitar"],
2397
- operationId: "eliminarLogoEmisorTributario",
2398
- metodo: "DELETE",
2399
- ruta: "/{tenantSlug}/emisores-tributarios/{id}/logo",
2400
- argumentos: ["id"],
2401
- banderas: [],
2402
- salida: "accion",
2403
- hecho: "Logo eliminado.",
2404
- confirmacion: "efecto"
2405
- },
2406
- {
2407
- // 39
2408
- comando: ["sucursales", "listar"],
2409
- operationId: "listarSucursalesEmisorDte",
2410
- metodo: "GET",
2411
- ruta: "/{tenantSlug}/dte/emisores/{emisorId}/sucursales",
2412
- argumentos: ["emisorId"],
2413
- banderas: [ACTIVO_FILTRO, TRIBUTARIA_FILTRO, LIMITE, DESDE, TODAS],
2414
- salida: "tabla",
2415
- columnas: ["sucursalId", "nombre", "direccion", "comuna", "ciudad"],
2416
- confirmacion: "efecto"
2417
- },
2418
- {
2419
- // 40
2420
- comando: ["sucursales", "crear"],
2421
- operationId: "crearSucursalEmisorDte",
2422
- metodo: "POST",
2423
- ruta: "/{tenantSlug}/dte/emisores/{emisorId}/sucursales",
2424
- argumentos: ["emisorId"],
2425
- banderas: [CUERPO_OBLIGATORIO],
2426
- salida: "accion",
2427
- hecho: "Sucursal creada.",
2428
- confirmacion: "efecto"
2429
- },
2430
- {
2431
- // 41
2432
- comando: ["sucursales", "editar"],
2433
- operationId: "actualizarSucursalEmisorDte",
2434
- metodo: "PATCH",
2435
- ruta: "/{tenantSlug}/dte/sucursales/{sucursalId}",
2436
- argumentos: ["sucursalId"],
2437
- banderas: [CUERPO_OBLIGATORIO],
2438
- salida: "accion",
2439
- hecho: "Sucursal actualizada.",
2440
- confirmacion: "efecto"
2441
- },
2442
- {
2443
- // 42
2444
- comando: ["sucursales", "desactivar"],
2445
- operationId: "desactivarSucursalEmisorDte",
2446
- metodo: "DELETE",
2447
- ruta: "/{tenantSlug}/dte/sucursales/{sucursalId}",
2448
- argumentos: ["sucursalId"],
2449
- banderas: [],
2450
- salida: "accion",
2451
- hecho: "Sucursal desactivada.",
2452
- confirmacion: "efecto"
2453
- },
2454
- {
2455
- // 43
2456
- comando: ["representantes", "listar"],
2457
- operationId: "listarRepresentantesLegales",
2458
- metodo: "GET",
2459
- ruta: "/{tenantSlug}/representantes-legales",
2460
- argumentos: [],
2461
- banderas: [RUT_FILTRO, LIMITE, DESDE, TODAS],
2462
- salida: "tabla",
2463
- columnas: ["rut", "nombre", "certVigente", "certValidoHasta", "emisoresCount"],
2464
- confirmacion: "efecto"
2465
- },
2466
- {
2467
- // 44
2468
- comando: ["dte", "sincronizar"],
2469
- operationId: "actualizarEmisorDteDesdeSii",
2470
- metodo: "POST",
2471
- ruta: "/{tenantSlug}/emisores/{id}/sincronizar",
2472
- argumentos: ["id"],
2473
- banderas: [],
2474
- salida: "ficha",
2475
- confirmacion: "efecto"
2476
- },
2477
- {
2478
- // 45
2479
- comando: ["dte", "credencial", "reintentar"],
2480
- operationId: "reintentarCredencialPortalEmisorDte",
2481
- metodo: "POST",
2482
- ruta: "/{tenantSlug}/emisores/{id}/credencial-portal/reintentar",
2483
- argumentos: ["id"],
2484
- banderas: [],
2485
- salida: "ficha",
2486
- confirmacion: "efecto"
2487
- },
2488
- {
2489
- // 46
2490
- comando: ["tributarios", "credencial", "reintentar"],
2491
- operationId: "reintentarCredencialEmisorTributario",
2492
- metodo: "POST",
2493
- ruta: "/{tenantSlug}/emisores-tributarios/{id}/credencial/reintentar",
2494
- argumentos: ["id"],
2495
- banderas: [],
2496
- salida: "ficha",
2497
- confirmacion: "efecto"
2498
- },
2499
- {
2500
- // 47
2501
- comando: ["revocar"],
2502
- operationId: "revocarEmisorTokenizado",
2503
- metodo: "POST",
2504
- ruta: "/{tenantSlug}/tokenizacion/revoke",
2505
- argumentos: ["id"],
2506
- argumentoACuerpo: "emisorId",
2507
- banderas: [TIPO_DE_EMISOR_A_REVOCAR, MOTIVO_DE_REVOCACION],
2508
- salida: "accion",
2509
- hecho: "Emisor revocado.",
2510
- confirmacion: "escrita",
2511
- aviso: "Esto revoca la autorizaci\xF3n y elimina sus credenciales de inmediato."
2512
- },
2513
- {
2514
- // 48
2515
- comando: ["dte", "volver-a-mipyme"],
2516
- operationId: "volverEmisorDteAlPortalMipyme",
2517
- metodo: "POST",
2518
- ruta: "/{tenantSlug}/emisores/{id}/volver-a-mipyme",
2519
- argumentos: ["id"],
2520
- banderas: [RUT_DE_CONFIRMACION],
2521
- salida: "accion",
2522
- hecho: "Emisor vuelto al Portal MiPyme.",
2523
- confirmacion: "escrita",
2524
- 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."
2525
- }
2526
- ];
2527
-
2528
- // src/comandos/registro.ts
2529
- import { Option } from "commander";
2530
-
2531
- // src/nucleo/contexto.ts
2532
- import os2 from "node:os";
2533
-
2534
- // src/nucleo/sesion.ts
2535
- import { spawn } from "node:child_process";
2536
- import fs7 from "node:fs";
2537
- import os from "node:os";
2538
- import path7 from "node:path";
2539
- import { setTimeout as setTimeoutAbortable } from "node:timers/promises";
2540
- import * as oidc from "openid-client";
2541
-
2542
- // src/nucleo/retorno-local.ts
2543
- import http from "node:http";
2544
- function paginaListo(titulo, texto2) {
2545
- return `<!doctype html><html lang="es"><head><meta charset="utf-8"><title>REDCUMBRE</title>
2546
- <meta name="viewport" content="width=device-width, initial-scale=1">
2547
- <style>body{font-family:system-ui,sans-serif;display:flex;min-height:100vh;align-items:center;justify-content:center;margin:0;background:Canvas;color:CanvasText}
2548
- main{max-width:28rem;padding:1.5rem;text-align:center}h1{font-size:1.25rem;margin:0 0 .5rem}p{margin:0;opacity:.8}</style></head>
2549
- <body><main><h1>${titulo}</h1><p>${texto2}</p></main></body></html>`;
2550
- }
2551
- async function abrirRetornoLocal(opciones) {
2552
- let resolver;
2553
- let rechazar;
2554
- const recibido = new Promise((ok, falla) => {
2555
- resolver = ok;
2556
- rechazar = falla;
2557
- });
2558
- recibido.catch(() => void 0);
2559
- const servidor = http.createServer((req, res) => {
2560
- const url = new URL(req.url ?? "/", "http://127.0.0.1");
2561
- if (url.pathname !== "/callback") {
2562
- res.writeHead(404).end();
2563
- return;
2564
- }
2565
- if (opciones.aceptar && !opciones.aceptar(url)) {
2566
- res.writeHead(400).end();
2567
- return;
2568
- }
2569
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }).end(opciones.pagina);
2570
- resolver(url);
2571
- });
2572
- await new Promise((ok) => servidor.listen(0, "127.0.0.1", ok));
2573
- const { port } = servidor.address();
2574
- let espera;
2575
- const cerrar = () => {
2576
- clearTimeout(espera);
2577
- servidor.close();
2578
- };
2579
- espera = setTimeout(() => {
2580
- cerrar();
2581
- rechazar(new ErrorCli(opciones.mensajeDeEspera));
2582
- }, opciones.esperaMs);
2583
- return { puerto: port, recibido, cerrar };
2584
- }
2585
-
2586
- // src/nucleo/sesion.ts
2587
- function carpetaDeConfiguracion(env = process.env, plataforma = process.platform) {
2588
- if (plataforma === "win32") {
2589
- if (!env.APPDATA) throw new ErrorCli("No encuentro %APPDATA%: no tengo d\xF3nde guardar la sesi\xF3n.");
2590
- return path7.join(env.APPDATA, "redcumbre");
2591
- }
2592
- const base = env.XDG_CONFIG_HOME || path7.join(os.homedir(), ".config");
2593
- return path7.join(base, "redcumbre");
2594
- }
2595
- function estaDentro(base, ruta) {
2596
- const relativa = path7.relative(path7.resolve(base), path7.resolve(ruta));
2597
- return !relativa.startsWith("..") && !path7.isAbsolute(relativa);
2598
- }
2599
- function exigirFueraDelProyecto(carpeta, proyecto, personal = os.homedir()) {
2600
- if (!estaDentro(proyecto, carpeta)) return;
2601
- if (estaDentro(proyecto, personal) && !tieneInstalacionDelCli(proyecto)) return;
2602
- throw new ErrorCli(
2603
- `La carpeta de configuraci\xF3n (${carpeta}) est\xE1 dentro del proyecto: ah\xED no guardo tu sesi\xF3n. Corre el comando con XDG_CONFIG_HOME fuera del proyecto.`
2604
- );
2605
- }
2606
- var AlmacenArchivo = class {
2607
- ruta;
2608
- descripcion;
2609
- /** `proyecto`: la carpeta donde corre el CLI; la sesión nunca puede quedar debajo de ella. */
2610
- constructor(carpeta, proyecto) {
2611
- this.ruta = path7.join(carpeta, "sesion.json");
2612
- exigirFueraDelProyecto(carpeta, proyecto);
2613
- this.descripcion = `el archivo ${this.ruta} (permisos 0600)`;
2614
- }
2615
- leer() {
2616
- if (!fs7.existsSync(this.ruta)) return null;
2617
- return JSON.parse(fs7.readFileSync(this.ruta, "utf8"));
2618
- }
2619
- guardar(par) {
2620
- fs7.mkdirSync(path7.dirname(this.ruta), { recursive: true, mode: 448 });
2621
- fs7.writeFileSync(this.ruta, JSON.stringify(par), { mode: 384 });
2622
- fs7.chmodSync(this.ruta, 384);
2623
- }
2624
- borrar() {
2625
- fs7.rmSync(this.ruta, { force: true });
2626
- }
2627
- };
2628
- var AlmacenLlavero = class {
2629
- constructor(entrada) {
2630
- this.entrada = entrada;
2631
- }
2632
- descripcion = `el llavero del sistema (servicio ${SERVICIO_LLAVERO})`;
2633
- leer() {
2634
- const valor = this.entrada.getPassword();
2635
- return valor ? JSON.parse(valor) : null;
2636
- }
2637
- guardar(par) {
2638
- this.entrada.setPassword(JSON.stringify(par));
2062
+ function reconciliarAgents(archivo, registro) {
2063
+ const bloque = bloqueDeAgents();
2064
+ const hashBloque = sha256(bloque);
2065
+ if (!fs6.existsSync(archivo)) {
2066
+ if (registro) return { accion: "borrada", registro: null };
2067
+ escribirAtomico(archivo, `${bloque}
2068
+ `);
2069
+ return { accion: "instalada", registro: { sha256: hashBloque, creado: true } };
2639
2070
  }
2640
- borrar() {
2641
- this.entrada.deletePassword();
2071
+ const texto2 = conReintentoEnWindows(() => fs6.readFileSync(archivo, "utf8"));
2072
+ const actual = extraerBloque(texto2);
2073
+ if (actual === null) {
2074
+ if (registro) return { accion: "borrada", registro: null };
2075
+ const separador = texto2.length === 0 ? "" : texto2.endsWith("\n\n") ? "" : texto2.endsWith("\n") ? "\n" : "\n\n";
2076
+ escribirAtomico(archivo, `${texto2}${separador}${bloque}
2077
+ `);
2078
+ return { accion: "instalada", registro: { sha256: hashBloque, creado: false } };
2642
2079
  }
2643
- };
2644
- async function elegirAlmacen(proyecto, env = process.env) {
2645
- if (env.REDCUMBRE_SESION_EN_ARCHIVO === "1") return new AlmacenArchivo(carpetaDeConfiguracion(env), proyecto);
2646
- try {
2647
- const { Entry } = await import("@napi-rs/keyring");
2648
- const entrada = new Entry(SERVICIO_LLAVERO, "sesion");
2649
- entrada.getPassword();
2650
- return new AlmacenLlavero(entrada);
2651
- } catch {
2652
- return new AlmacenArchivo(carpetaDeConfiguracion(env), proyecto);
2080
+ const hashActual = sha256(actual);
2081
+ if (!registro) {
2082
+ if (hashActual === hashBloque) return { accion: "sin-cambios", registro: { sha256: hashBloque, creado: false } };
2083
+ return { accion: "editada", registro: null };
2653
2084
  }
2085
+ if (hashActual !== registro.sha256) return { accion: "editada", registro: null };
2086
+ if (hashActual === hashBloque) return { accion: "sin-cambios", registro: { ...registro, sha256: hashBloque } };
2087
+ escribirAtomico(archivo, texto2.replace(regexBloque(), () => bloque));
2088
+ return { accion: "actualizada", registro: { ...registro, sha256: hashBloque } };
2654
2089
  }
2655
- var ErrorRefreshInvalido = class extends Error {
2656
- constructor() {
2657
- super("La sesi\xF3n guardada ya no es v\xE1lida.");
2658
- this.name = "ErrorRefreshInvalido";
2090
+ function instalarSkill(opciones) {
2091
+ const { destinos, bloqueAgents } = opciones;
2092
+ const ahora = opciones.ahora ?? /* @__PURE__ */ new Date();
2093
+ const contenido = contenidoPorFuente(opciones.version, opciones.fuente);
2094
+ const usuario = leerRegistroUsuario(destinos);
2095
+ const proyecto = destinos.proyecto ? leerRegistroProyecto(destinos.proyecto) : null;
2096
+ const rutas = [];
2097
+ for (const objetivo of objetivos(destinos)) {
2098
+ const deUsuario = esDeUsuario(objetivo.id);
2099
+ const registro = deUsuario ? usuario : proyecto;
2100
+ if (usuario.quitada || registro.quitada) continue;
2101
+ const previo = registro.rutas?.[objetivo.id]?.sha256;
2102
+ const { accion, hash, copia, error } = reconciliar(objetivo.archivo, contenido(objetivo.fuente), previo, ahora);
2103
+ rutas.push({ ruta: objetivo.legible, accion, ...copia ? { copia } : {}, ...error ? { error } : {} });
2104
+ if (hash) {
2105
+ registro.rutas = { ...registro.rutas ?? {}, [objetivo.id]: { sha256: hash } };
2106
+ }
2659
2107
  }
2660
- };
2661
- var DEVICE_CODE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
2662
- function esperarAbortable(ms, signal) {
2663
- return setTimeoutAbortable(ms, void 0, { signal });
2664
- }
2665
- function comoPar(respuesta) {
2666
- if (!respuesta.refresh_token) throw new ErrorCli("El servidor de identidad no devolvi\xF3 un refresh token.");
2667
- const segundos = respuesta.expiresIn();
2668
- if (segundos === void 0) throw new ErrorCli("El servidor de identidad no dijo cu\xE1ndo vence el token.");
2669
- return {
2670
- access_token: respuesta.access_token,
2671
- refresh_token: respuesta.refresh_token,
2672
- expira: new Date(Date.now() + segundos * 1e3).toISOString()
2673
- };
2674
- }
2675
- function refreshInvalido(codigo, descripcion) {
2676
- return codigo === "invalid_grant" || codigo === "invalid_request" && /RefreshToken/i.test(descripcion ?? "");
2677
- }
2678
- function esRefreshInvalido(error) {
2679
- return error instanceof oidc.ResponseBodyError && refreshInvalido(error.error, error.error_description);
2108
+ if (bloqueAgents && destinos.proyecto && proyecto && !usuario.quitada && !proyecto.quitada) {
2109
+ const { accion, registro } = reconciliarAgents(path6.join(destinos.proyecto, "AGENTS.md"), proyecto.agents);
2110
+ rutas.push({ ruta: "AGENTS.md", accion });
2111
+ if (registro) proyecto.agents = registro;
2112
+ }
2113
+ if (!usuario.quitada && rutas.some((r) => r.ruta.startsWith("~"))) guardarRegistroUsuario(destinos, usuario);
2114
+ if (destinos.proyecto && proyecto && !proyecto.quitada && rutas.some((r) => !r.ruta.startsWith("~"))) guardarRegistroProyecto(destinos.proyecto, proyecto);
2115
+ return resumir2(rutas, rutas.length === 0 && Boolean(usuario.quitada || proyecto?.quitada));
2680
2116
  }
2681
- function sinRespuestaDelIdp(error) {
2682
- if (error instanceof ErrorCli) return false;
2683
- if (error instanceof oidc.ResponseBodyError) return error.status >= 500;
2684
- if (error instanceof oidc.AuthorizationResponseError || error instanceof oidc.WWWAuthenticateChallengeError) return false;
2685
- return true;
2117
+ function quitarArchivo(archivo, registrado) {
2118
+ if (!fs6.existsSync(archivo)) return null;
2119
+ if (registrado === void 0 || sha256(conReintentoEnWindows(() => fs6.readFileSync(archivo))) !== registrado) return "editada";
2120
+ fs6.rmSync(archivo);
2121
+ const carpeta = path6.dirname(archivo);
2122
+ if (fs6.readdirSync(carpeta).length === 0) fs6.rmdirSync(carpeta);
2123
+ return "quitada";
2686
2124
  }
2687
- function errorDeIdentidad(error) {
2688
- if (error instanceof ErrorCli) return error;
2689
- if (sinRespuestaDelIdp(error)) {
2690
- const detalle = error instanceof Error ? error.cause instanceof Error ? error.cause.message : error.message : String(error);
2691
- return identidadSinRespuesta(`No pude hablar con ${CLIENTE_OIDC.issuer} (${detalle}). Revisa tu conexi\xF3n y vuelve a intentarlo: lo que ten\xEDas guardado sigue igual.`);
2125
+ function quitarSkill(opciones) {
2126
+ const { destinos } = opciones;
2127
+ const usuario = leerRegistroUsuario(destinos);
2128
+ const proyecto = destinos.proyecto ? leerRegistroProyecto(destinos.proyecto) : null;
2129
+ const rutas = [];
2130
+ for (const objetivo of objetivos(destinos)) {
2131
+ const registro = esDeUsuario(objetivo.id) ? usuario : proyecto;
2132
+ const previo = registro.rutas?.[objetivo.id]?.sha256;
2133
+ const accion = quitarArchivo(objetivo.archivo, previo);
2134
+ if (accion) rutas.push({ ruta: objetivo.legible, accion });
2692
2135
  }
2693
- if (error instanceof oidc.ResponseBodyError) {
2694
- return new ErrorCli(`El servidor de identidad rechaz\xF3 la operaci\xF3n: ${error.error}${error.error_description ? ` (${error.error_description})` : ""}.`);
2136
+ if (destinos.proyecto && proyecto) {
2137
+ const archivo = path6.join(destinos.proyecto, "AGENTS.md");
2138
+ if (fs6.existsSync(archivo)) {
2139
+ const texto2 = conReintentoEnWindows(() => fs6.readFileSync(archivo, "utf8"));
2140
+ const bloque = extraerBloque(texto2);
2141
+ if (bloque !== null) {
2142
+ if (!proyecto.agents || sha256(bloque) !== proyecto.agents.sha256) {
2143
+ rutas.push({ ruta: "AGENTS.md", accion: "editada" });
2144
+ } else {
2145
+ const resto = texto2.replace(regexBloque(), "").replace(/\n{3,}/g, "\n\n");
2146
+ if (proyecto.agents.creado && resto.trim() === "") fs6.rmSync(archivo);
2147
+ else escribirAtomico(archivo, resto.replace(/^\n+/, "").replace(/\n*$/, "\n"));
2148
+ rutas.push({ ruta: "AGENTS.md", accion: "quitada" });
2149
+ }
2150
+ }
2151
+ }
2695
2152
  }
2696
- return new ErrorCli(`El servidor de identidad rechaz\xF3 la operaci\xF3n: ${error instanceof Error ? error.message : String(error)}.`);
2153
+ guardarRegistroUsuario(destinos, { quitada: true, rutas: {} });
2154
+ if (destinos.proyecto && proyecto) guardarRegistroProyecto(destinos.proyecto, { quitada: true, rutas: {}, agents: void 0 });
2155
+ return { estado: "quitada", rutas };
2697
2156
  }
2698
- function identidadOidc(cliente = CLIENTE_OIDC) {
2699
- let configuracion = null;
2700
- let senalDeEspera;
2701
- const config = () => {
2702
- const emisor = new URL(cliente.issuer);
2703
- const opciones = emisor.protocol === "http:" && emisor.hostname === "127.0.0.1" ? { execute: [oidc.allowInsecureRequests] } : void 0;
2704
- configuracion ??= oidc.discovery(emisor, cliente.clientId, void 0, oidc.None(), opciones).then((c) => {
2705
- c[oidc.customFetch] = (url, init2) => fetch(url, senalDeEspera ? { ...init2, signal: init2.signal ? AbortSignal.any([init2.signal, senalDeEspera]) : senalDeEspera } : init2);
2706
- return c;
2707
- }).catch((error) => {
2708
- configuracion = null;
2709
- throw errorDeIdentidad(error);
2710
- });
2711
- return configuracion;
2712
- };
2713
- return {
2714
- async urlDeAutorizacion(redirectUri, pkce) {
2715
- return oidc.buildAuthorizationUrl(await config(), {
2716
- redirect_uri: redirectUri,
2717
- scope: SCOPE,
2718
- code_challenge: pkce.desafio,
2719
- code_challenge_method: "S256",
2720
- state: pkce.estado
2721
- }).toString();
2722
- },
2723
- async canjear(retorno, pkce) {
2724
- try {
2725
- return comoPar(await oidc.authorizationCodeGrant(await config(), retorno, { pkceCodeVerifier: pkce.verificador, expectedState: pkce.estado }));
2726
- } catch (error) {
2727
- if (error instanceof ErrorCli) throw error;
2728
- throw errorDeIdentidad(error);
2729
- }
2730
- },
2731
- async renovar(refreshToken) {
2732
- try {
2733
- return comoPar(await oidc.refreshTokenGrant(await config(), refreshToken));
2734
- } catch (error) {
2735
- if (esRefreshInvalido(error)) throw new ErrorRefreshInvalido();
2736
- if (error instanceof ErrorCli) throw error;
2737
- throw errorDeIdentidad(error);
2738
- }
2739
- },
2740
- async revocar(refreshToken) {
2741
- try {
2742
- await oidc.tokenRevocation(await config(), refreshToken, { token_type_hint: "refresh_token" });
2743
- } catch (error) {
2744
- throw errorDeIdentidad(error);
2745
- }
2746
- },
2747
- async exigeIss() {
2748
- return (await config()).serverMetadata().authorization_response_iss_parameter_supported === true;
2749
- },
2750
- async iniciarDispositivo() {
2751
- try {
2752
- const respuesta = await oidc.initiateDeviceAuthorization(await config(), { scope: SCOPE });
2753
- if (!respuesta.verification_uri_complete) throw new ErrorCli("El servidor de identidad no devolvi\xF3 la direcci\xF3n completa para aprobar el acceso.");
2754
- return {
2755
- deviceCode: respuesta.device_code,
2756
- userCode: respuesta.user_code,
2757
- url: respuesta.verification_uri_complete,
2758
- intervalo: respuesta.interval ?? 5,
2759
- venceEnSegundos: respuesta.expires_in
2760
- };
2761
- } catch (error) {
2762
- throw errorDeIdentidad(error);
2157
+ function renovarSkill(opciones) {
2158
+ const { destinos, version } = opciones;
2159
+ const ahora = opciones.ahora ?? /* @__PURE__ */ new Date();
2160
+ const usuario = leerRegistroUsuario(destinos);
2161
+ const proyecto = destinos.proyecto ? leerRegistroProyecto(destinos.proyecto) : null;
2162
+ const rutas = [];
2163
+ const cambiosUsuario = {};
2164
+ const cambiosProyecto = {};
2165
+ const contenido = contenidoPorFuente(version, opciones.fuente);
2166
+ for (const objetivo of objetivos(destinos)) {
2167
+ const deUsuario = esDeUsuario(objetivo.id);
2168
+ const registro = deUsuario ? usuario : proyecto;
2169
+ if (usuario.quitada || registro.quitada) continue;
2170
+ const registrado = (registro.rutas ?? {})[objetivo.id]?.sha256;
2171
+ if (!fs6.existsSync(objetivo.archivo)) {
2172
+ const skillDeClaude = objetivos(destinos).find((o) => o.id === skillDeClaudeDe(objetivo));
2173
+ if (esComando(objetivo) && registrado === void 0 && skillDeClaude && fs6.existsSync(skillDeClaude.archivo)) {
2174
+ const texto2 = contenido(objetivo.fuente);
2175
+ escribirAtomico(objetivo.archivo, texto2);
2176
+ (deUsuario ? cambiosUsuario : cambiosProyecto)[objetivo.id] = sha256(texto2);
2177
+ rutas.push({ ruta: objetivo.legible, accion: "instalada", instalada: version });
2763
2178
  }
2764
- },
2765
- async esperarDispositivo(pendiente, esperaMs) {
2766
- const techo = AbortSignal.timeout(esperaMs);
2767
- const venceEn = new Date(pendiente.venceEn).getTime();
2768
- let intervalo = pendiente.intervalo;
2769
- senalDeEspera = techo;
2179
+ continue;
2180
+ }
2181
+ const actual = conReintentoEnWindows(() => fs6.readFileSync(objetivo.archivo, "utf8"));
2182
+ const instalada2 = versionDeLaSkill(actual);
2183
+ if (instalada2 !== null && compararVersiones(version, instalada2) < 0) {
2184
+ rutas.push({ ruta: objetivo.legible, accion: "mas-nueva", instalada: instalada2 });
2185
+ continue;
2186
+ }
2187
+ const nuevo = contenido(objetivo.fuente);
2188
+ const hashNuevo = sha256(nuevo);
2189
+ const hashActual = sha256(actual);
2190
+ if (hashActual === hashNuevo) {
2191
+ if (registrado !== hashNuevo) (deUsuario ? cambiosUsuario : cambiosProyecto)[objetivo.id] = hashNuevo;
2192
+ rutas.push({ ruta: objetivo.legible, accion: "al-dia", instalada: version });
2193
+ continue;
2194
+ }
2195
+ const editada = registrado === void 0 || hashActual !== registrado;
2196
+ if (instalada2 !== null && compararVersiones(version, instalada2) === 0 && !editada) {
2197
+ rutas.push({ ruta: objetivo.legible, accion: "al-dia", instalada: instalada2 });
2198
+ continue;
2199
+ }
2200
+ let copia;
2201
+ if (editada) {
2770
2202
  try {
2771
- for (; ; ) {
2772
- try {
2773
- await esperarAbortable(intervalo * 1e3, techo);
2774
- } catch (error) {
2775
- if (techo.aborted) return { estado: "pendiente" };
2776
- throw error;
2777
- }
2778
- if (Date.now() >= venceEn) return { estado: "vencido" };
2779
- try {
2780
- const respuesta = await oidc.genericGrantRequest(await config(), DEVICE_CODE_GRANT, { device_code: pendiente.deviceCode });
2781
- return { estado: "aprobado", par: comoPar(respuesta) };
2782
- } catch (error) {
2783
- if (techo.aborted) return { estado: "pendiente" };
2784
- if (error instanceof oidc.ResponseBodyError) {
2785
- if (error.error === "authorization_pending") continue;
2786
- if (error.error === "slow_down") {
2787
- intervalo += 5;
2788
- continue;
2789
- }
2790
- if (error.error === "expired_token") return { estado: "vencido" };
2791
- if (error.error === "access_denied") return { estado: "rechazado" };
2792
- }
2793
- throw errorDeIdentidad(error);
2794
- }
2795
- }
2796
- } finally {
2797
- senalDeEspera = void 0;
2203
+ copia = guardarCopiaDeLoEditado(objetivo.archivo, ahora);
2204
+ } catch (error) {
2205
+ rutas.push({ ruta: objetivo.legible, accion: "desactualizada", instalada: instalada2, error: motivoDe(error) });
2206
+ continue;
2798
2207
  }
2799
2208
  }
2800
- };
2209
+ escribirAtomico(objetivo.archivo, nuevo);
2210
+ (deUsuario ? cambiosUsuario : cambiosProyecto)[objetivo.id] = hashNuevo;
2211
+ rutas.push(copia ? { ruta: objetivo.legible, accion: "reemplazada-editada", instalada: instalada2, copia } : { ruta: objetivo.legible, accion: "renovada", instalada: instalada2 });
2212
+ }
2213
+ if (Object.keys(cambiosUsuario).length > 0) {
2214
+ const vigente = leerRegistroUsuario(destinos);
2215
+ if (!vigente.quitada) guardarRegistroUsuario(destinos, { ...vigente, rutas: { ...vigente.rutas ?? {}, ...aRutas(cambiosUsuario) } });
2216
+ }
2217
+ if (Object.keys(cambiosProyecto).length > 0 && destinos.proyecto) {
2218
+ const vigente = leerRegistroProyecto(destinos.proyecto);
2219
+ if (!vigente.quitada) guardarRegistroProyecto(destinos.proyecto, { ...vigente, rutas: { ...vigente.rutas ?? {}, ...aRutas(cambiosProyecto) } });
2220
+ }
2221
+ return { version, rutas };
2801
2222
  }
2802
- async function crearPkce() {
2803
- const verificador = oidc.randomPKCECodeVerifier();
2804
- return { verificador, desafio: await oidc.calculatePKCECodeChallenge(verificador), estado: oidc.randomState() };
2223
+ var aRutas = (cambios) => Object.fromEntries(Object.entries(cambios).map(([id, sha]) => [id, { sha256: sha }]));
2224
+ var COMANDO_SKILL_RENOVAR = "redcumbre skill renovar";
2225
+ function nombreDeLoInstalado(ruta) {
2226
+ const comando2 = ruta.match(/\.claude\/commands\/redcumbre\/([^/]+)\.md$/)?.[1];
2227
+ return comando2 ? `el comando /${NOMBRE_SKILL}:${comando2}` : "la skill de REDCUMBRE";
2805
2228
  }
2806
- function hayQueIrSinNavegador(pedido, env = process.env, plataforma = process.platform) {
2807
- if (pedido) return true;
2808
- if (env.SSH_CONNECTION || env.SSH_TTY) return true;
2809
- return plataforma === "linux" && !env.DISPLAY && !env.WAYLAND_DISPLAY;
2229
+ function deLaVersion(ruta, prep, version) {
2230
+ const comando2 = nombreDeLoInstalado(ruta).startsWith("el comando");
2231
+ const que = prep === "a" ? comando2 ? "al" : "a la" : comando2 ? "por el" : "por la";
2232
+ return `${que} de la versi\xF3n ${version}`;
2810
2233
  }
2811
- async function abrirNavegadorDelSistema(url) {
2812
- const [comando2, argumentos] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", '""', url.replace(/&/g, "^&")]] : ["xdg-open", [url]];
2813
- return new Promise((resolver) => {
2814
- const hijo = spawn(comando2, argumentos, { stdio: "ignore", detached: true });
2815
- hijo.once("error", () => resolver(false));
2816
- hijo.once("spawn", () => {
2817
- hijo.unref();
2818
- resolver(true);
2819
- });
2820
- });
2234
+ function avisoDeRenovacion(r, version) {
2235
+ const que = nombreDeLoInstalado(r.ruta);
2236
+ const suyo = que.startsWith("el comando") ? "Tu versi\xF3n editada del comando" : "Tu versi\xF3n editada de la skill";
2237
+ if (r.accion === "instalada") return `Instal\xE9 ${que} en ${r.ruta}.`;
2238
+ if (r.accion === "renovada") return `Renov\xE9 ${que} en ${r.ruta} ${deLaVersion(r.ruta, "a", version)}.`;
2239
+ if (r.accion === "reemplazada-editada") return `Reemplac\xE9 ${que} en ${r.ruta} ${deLaVersion(r.ruta, "por", version)}. ${suyo} qued\xF3 en ${r.copia}.`;
2240
+ if (r.accion === "desactualizada") {
2241
+ const la = que.startsWith("el comando") ? "lo" : "la";
2242
+ return `${que[0].toUpperCase()}${que.slice(1)} en ${r.ruta} tiene cambios tuyos (o no ${la} instal\xF3 el CLI) y no pude guardar su copia (${r.error}): no ${la} toqu\xE9. Corre \xAB${COMANDO_SKILL_RENOVAR}\xBB cuando se pueda escribir en esa carpeta.`;
2243
+ }
2244
+ return null;
2821
2245
  }
2822
- var PAGINA_LISTO = paginaListo("Listo, ya iniciaste sesi\xF3n", "Ya puedes cerrar esta ventana y volver a la terminal.");
2823
- async function loginConLoopback(identidad, salida, opciones) {
2824
- const pkce = await crearPkce();
2825
- const local = await abrirRetornoLocal({
2826
- pagina: PAGINA_LISTO,
2827
- esperaMs: opciones.esperaMs ?? 3e5,
2828
- mensajeDeEspera: "No lleg\xF3 la autorizaci\xF3n del navegador en 5 minutos. Vuelve a correr el comando."
2829
- });
2830
- const redirectUri = `http://127.0.0.1:${local.puerto}/callback`;
2246
+ function renovarSkillAlCorrer(opciones) {
2831
2247
  try {
2832
- const url = await identidad.urlDeAutorizacion(redirectUri, pkce);
2833
- const abierto = await (opciones.abrirNavegador ?? abrirNavegadorDelSistema)(url);
2834
- salida.linea(abierto ? "Abr\xED tu navegador para que inicies sesi\xF3n. Si no se abri\xF3, abre esta URL:" : "Abre esta URL en tu navegador para iniciar sesi\xF3n:");
2835
- salida.linea(url);
2836
- const vuelta = await local.recibido;
2837
- const recibida = new URL(`${redirectUri}${vuelta.search}`);
2838
- const error = recibida.searchParams.get("error");
2839
- if (error) throw new ErrorCli(`El inicio de sesi\xF3n no se complet\xF3: ${error}.`);
2840
- return await identidad.canjear(recibida, pkce);
2841
- } finally {
2842
- local.cerrar();
2248
+ const informe = renovarSkill({ destinos: opciones.destinos, version: opciones.version, ahora: opciones.ahora });
2249
+ for (const r of informe.rutas.filter((x) => x.accion === "instalada" || x.accion === "renovada" || x.accion === "reemplazada-editada")) opciones.avisar(avisoDeRenovacion(r, informe.version));
2250
+ const desactualizadas = informe.rutas.filter((x) => x.accion === "desactualizada");
2251
+ if (desactualizadas.length === 0) return;
2252
+ const hoy = opciones.ahora.toISOString().slice(0, 10);
2253
+ const usuario = leerRegistroUsuario(opciones.destinos);
2254
+ if (usuario.avisoDesactualizadaEn === hoy) return;
2255
+ for (const r of desactualizadas) opciones.avisar(avisoDeRenovacion(r, informe.version));
2256
+ guardarRegistroUsuario(opciones.destinos, { ...usuario, avisoDesactualizadaEn: hoy });
2257
+ } catch (error) {
2258
+ opciones.depurar?.(`no pude revisar la skill instalada (${error instanceof Error ? error.message : String(error)}); el comando sigue`);
2843
2259
  }
2844
2260
  }
2845
- var AVISO_DE_APROBACION = "Este acceso es para el CLI de REDCUMBRE. Apru\xE9balo solo si t\xFA lo pediste: no apruebes un c\xF3digo que no pediste.";
2846
- async function iniciarSesion(identidad, salida, opciones) {
2847
- return opciones.sinNavegador ? loginDeDispositivoEnLinea(identidad, salida) : loginConLoopback(identidad, salida, opciones);
2848
- }
2849
- async function loginDeDispositivoEnLinea(identidad, salida) {
2850
- const solicitud = await identidad.iniciarDispositivo();
2851
- salida.linea("Abre esta direcci\xF3n en un navegador y aprueba el acceso:");
2852
- salida.linea(solicitud.url);
2853
- salida.linea(`El c\xF3digo que tiene que mostrar es ${solicitud.userCode}.`);
2854
- salida.linea(AVISO_DE_APROBACION);
2855
- const venceEn = new Date(Date.now() + solicitud.venceEnSegundos * 1e3).toISOString();
2856
- const desenlace = await identidad.esperarDispositivo({ deviceCode: solicitud.deviceCode, intervalo: solicitud.intervalo, venceEn }, solicitud.venceEnSegundos * 1e3);
2857
- if (desenlace.estado === "aprobado") return desenlace.par;
2858
- throw errorDelDesenlace(desenlace.estado);
2261
+ function revisarSkillInstalada(opciones) {
2262
+ const { destinos, version } = opciones;
2263
+ const usuario = leerRegistroUsuario(destinos);
2264
+ const proyecto = destinos.proyecto ? leerRegistroProyecto(destinos.proyecto) : null;
2265
+ if (usuario.quitada || proyecto?.quitada) return { quitada: true, rutas: [] };
2266
+ const contenido = contenidoPorFuente(version, opciones.fuente);
2267
+ const rutas = [];
2268
+ for (const objetivo of objetivos(destinos).filter((o) => o.id.startsWith("claude-"))) {
2269
+ const deUsuario = esDeUsuario(objetivo.id);
2270
+ const registro = deUsuario ? usuario : proyecto;
2271
+ const registrado = (registro.rutas ?? {})[objetivo.id]?.sha256;
2272
+ const informar = (estado2) => rutas.push({ id: objetivo.id, ruta: objetivo.legible, ambito: deUsuario ? "usuario" : "proyecto", estado: estado2 });
2273
+ if (!fs6.existsSync(objetivo.archivo)) {
2274
+ if (registrado === void 0) informar("falta");
2275
+ continue;
2276
+ }
2277
+ const actual = conReintentoEnWindows(() => fs6.readFileSync(objetivo.archivo, "utf8"));
2278
+ const instalada2 = versionDeLaSkill(actual);
2279
+ if (instalada2 !== null && compararVersiones(version, instalada2) < 0) {
2280
+ informar("mas-nueva");
2281
+ continue;
2282
+ }
2283
+ if (sha256(actual) === sha256(contenido(objetivo.fuente))) {
2284
+ informar("al-dia");
2285
+ continue;
2286
+ }
2287
+ const editada = registrado === void 0 || sha256(actual) !== registrado;
2288
+ if (editada) informar("editada");
2289
+ else informar(instalada2 !== null && compararVersiones(version, instalada2) === 0 ? "al-dia" : "desactualizada");
2290
+ }
2291
+ return { quitada: false, rutas };
2859
2292
  }
2860
- var ESPERA_DE_COMPLETAR_MS = 9e4;
2861
- var rutaLoginPendiente = (carpeta) => path7.join(carpeta, "login-pendiente.json");
2862
- var volverAEmpezar = (motivo, codigo) => new ErrorCli(`${motivo} Vuelve a empezar con \xABredcumbre login\xBB.`, CODIGOS_DE_SALIDA.sesion, { codigo, comando: "redcumbre login" });
2863
- function errorDelDesenlace(estado2) {
2864
- if (estado2 === "pendiente") {
2865
- return new ErrorCli("Nadie aprob\xF3 el acceso todav\xEDa. Cuando la persona lo apruebe, repite \xABredcumbre login --completar\xBB: sigue siendo el mismo c\xF3digo.", CODIGOS_DE_SALIDA.sesion, {
2866
- codigo: "LOGIN_PENDIENTE",
2867
- comando: "redcumbre login --completar"
2293
+
2294
+ // src/comandos/doctor.ts
2295
+ async function doctor(ctx) {
2296
+ const { salida, proyecto } = ctx;
2297
+ const revisiones = [];
2298
+ const anotar = (r) => {
2299
+ revisiones.push(r);
2300
+ salida.linea(`${r.ok ? "\u2713" : r.opcional ? "\xB7" : "\u2717"} ${r.detalle}${!r.ok && r.comando ? ` \u2192 ${r.comando}` : ""}`);
2301
+ };
2302
+ const haySesion = await ctx.haySesion();
2303
+ anotar(
2304
+ haySesion ? { revision: "sesion", ok: true, detalle: "Hay una sesi\xF3n iniciada en este computador." } : { revision: "sesion", ok: false, detalle: "No hay una sesi\xF3n iniciada en este computador.", comando: "redcumbre login" }
2305
+ );
2306
+ const estado2 = leerEstado(proyecto);
2307
+ let slug = null;
2308
+ if (estado2) {
2309
+ slug = estado2.tenantSlug;
2310
+ anotar({ revision: "empresa", ok: true, detalle: `El proyecto ${proyecto} apunta a la empresa ${slug}.` });
2311
+ } else {
2312
+ anotar({ revision: "empresa", ok: false, detalle: `La carpeta ${proyecto} no est\xE1 conectada con REDCUMBRE (falta .redcumbre/estado.json).`, comando: COMANDO_INIT });
2313
+ }
2314
+ for (const entorno of ENTORNOS_LLAVE) {
2315
+ anotar(await revisarLlave(ctx, entorno, slug));
2316
+ }
2317
+ const gitignore = path7.join(proyecto, ".gitignore");
2318
+ const lineas = new Set((fs7.existsSync(gitignore) ? fs7.readFileSync(gitignore, "utf8") : "").split(/\r?\n/).map((l) => l.trim()));
2319
+ const faltanExclusiones = ["keys/", ".redcumbre/"].filter((l) => !lineas.has(l) && !lineas.has(`/${l}`));
2320
+ const versionadas = ENTORNOS_LLAVE.map((e) => path7.relative(proyecto, rutaDeLaLlave(proyecto, e, ctx.env))).filter(
2321
+ (relativa) => fs7.existsSync(path7.join(proyecto, relativa)) && estaVersionado(proyecto, relativa)
2322
+ );
2323
+ if (versionadas.length > 0) {
2324
+ anotar({
2325
+ revision: "exclusiones",
2326
+ ok: false,
2327
+ detalle: `La llave est\xE1 en el control de versiones (${versionadas.join(", ")}): s\xE1cala con \xABgit rm --cached ${versionadas.join(" ")}\xBB y rev\xF3cala en la web, porque qued\xF3 en el historial.`
2868
2328
  });
2329
+ } else if (faltanExclusiones.length > 0) {
2330
+ anotar({ revision: "exclusiones", ok: false, detalle: `Al .gitignore le falta ${faltanExclusiones.join(" y ")}.`, comando: COMANDO_INIT });
2331
+ } else {
2332
+ anotar({ revision: "exclusiones", ok: true, detalle: "keys/ y .redcumbre/ est\xE1n fuera del control de versiones." });
2869
2333
  }
2870
- if (estado2 === "vencido") return volverAEmpezar("El c\xF3digo venci\xF3 antes de que lo aprobaran.", "LOGIN_PENDIENTE_VENCIDO");
2871
- return volverAEmpezar("La persona rechaz\xF3 el acceso.", "LOGIN_RECHAZADO");
2872
- }
2873
- function leerLoginPendiente(carpeta) {
2874
- const ruta = rutaLoginPendiente(carpeta);
2875
- if (!fs7.existsSync(ruta)) return null;
2334
+ anotar(revisarSkill(ctx));
2876
2335
  try {
2877
- const d = JSON.parse(fs7.readFileSync(ruta, "utf8"));
2878
- const textos = ["deviceCode", "userCode", "url", "venceEn", "clientId"];
2879
- if (!textos.every((k) => typeof d[k] === "string") || typeof d.intervalo !== "number") return null;
2880
- if (d.clientId !== CLIENTE_OIDC.clientId || Number.isNaN(new Date(d.venceEn).getTime())) return null;
2881
- return d;
2882
- } catch {
2883
- return null;
2884
- }
2885
- }
2886
- function guardarLoginPendiente(carpeta, pendiente) {
2887
- const ruta = rutaLoginPendiente(carpeta);
2888
- fs7.mkdirSync(carpeta, { recursive: true, mode: 448 });
2889
- fs7.writeFileSync(ruta, JSON.stringify(pendiente), { mode: 384 });
2890
- fs7.chmodSync(ruta, 384);
2891
- }
2892
- function borrarLoginPendiente(carpeta) {
2893
- const ruta = rutaLoginPendiente(carpeta);
2894
- const habia = fs7.existsSync(ruta);
2895
- fs7.rmSync(ruta, { force: true });
2896
- return habia;
2897
- }
2898
- async function iniciarLoginDeDispositivo(identidad, carpeta, proyecto, ahora = /* @__PURE__ */ new Date()) {
2899
- exigirFueraDelProyecto(carpeta, proyecto);
2900
- const vigente = leerLoginPendiente(carpeta);
2901
- if (vigente && new Date(vigente.venceEn).getTime() > ahora.getTime()) return { url: vigente.url, codigo: vigente.userCode, vence: vigente.venceEn };
2902
- borrarLoginPendiente(carpeta);
2903
- const solicitud = await identidad.iniciarDispositivo();
2904
- const venceEn = new Date(ahora.getTime() + solicitud.venceEnSegundos * 1e3).toISOString();
2905
- guardarLoginPendiente(carpeta, {
2906
- deviceCode: solicitud.deviceCode,
2907
- userCode: solicitud.userCode,
2908
- url: solicitud.url,
2909
- intervalo: solicitud.intervalo,
2910
- venceEn,
2911
- clientId: CLIENTE_OIDC.clientId
2912
- });
2913
- return { url: solicitud.url, codigo: solicitud.userCode, vence: venceEn };
2914
- }
2915
- async function completarLogin(identidad, almacen, carpeta, proyecto, ahora = /* @__PURE__ */ new Date(), esperaMs = ESPERA_DE_COMPLETAR_MS) {
2916
- exigirFueraDelProyecto(carpeta, proyecto);
2917
- if (almacen.leer() !== null) return "ya-habia-sesion";
2918
- const pendiente = leerLoginPendiente(carpeta);
2919
- if (!pendiente) throw volverAEmpezar("No hay un inicio de sesi\xF3n pendiente.", "SIN_SESION");
2920
- if (new Date(pendiente.venceEn).getTime() <= ahora.getTime()) {
2921
- borrarLoginPendiente(carpeta);
2922
- throw errorDelDesenlace("vencido");
2336
+ const documento = await cargarDocumento(ctx.cliente, ctx.carpetaConfiguracion, salida);
2337
+ anotar({
2338
+ revision: "documento",
2339
+ ok: true,
2340
+ detalle: documento.copiaSinRevalidar ? `Uso la copia del documento del API sin revalidar (${documento.operaciones.length} operaciones).` : `El documento del API est\xE1 al d\xEDa (${documento.operaciones.length} operaciones).`
2341
+ });
2342
+ } catch (error) {
2343
+ anotar({ revision: "documento", ok: false, detalle: `No pude leer el documento del API: ${error instanceof Error ? error.message : String(error)}` });
2923
2344
  }
2924
- const desenlace = await identidad.esperarDispositivo({ deviceCode: pendiente.deviceCode, intervalo: pendiente.intervalo, venceEn: pendiente.venceEn }, esperaMs);
2925
- if (desenlace.estado === "aprobado") {
2926
- almacen.guardar(desenlace.par);
2927
- borrarLoginPendiente(carpeta);
2928
- return "iniciada";
2345
+ const disponible = ctx.versionDelRegistro ? ctx.versionDelRegistro.ultima : (await ultimaVersionConocida({ carpeta: ctx.carpetaConfiguracion, version: ctx.version, ahora: ctx.ahora(), registro: ctx.env.REDCUMBRE_NPM_REGISTRY, sinMarca: true })).ultima;
2346
+ const version = { instalada: ctx.version, disponible };
2347
+ if (disponible === null) salida.linea("\xB7 No pude consultar la \xFAltima versi\xF3n del CLI.");
2348
+ else if (compararVersiones(disponible, ctx.version) > 0) salida.linea(`\xB7 Hay una versi\xF3n m\xE1s nueva del CLI: ${disponible} (tienes ${ctx.version}). Actual\xEDzala con \xAB${COMANDO_ACTUALIZAR}\xBB.`);
2349
+ else salida.linea(`\u2713 El CLI est\xE1 en la \xFAltima versi\xF3n (${ctx.version}).`);
2350
+ const faltantes = revisiones.filter((r) => !r.ok && !r.opcional).map((r) => ({ revision: r.revision, detalle: r.detalle, ...r.comando ? { comando: r.comando } : {} }));
2351
+ if (faltantes.length > 0) {
2352
+ throw new ErrorCli(`Hay ${faltantes.length === 1 ? "una cosa que arreglar" : `${faltantes.length} cosas que arreglar`} en el proyecto.`, CODIGOS_DE_SALIDA.error, {
2353
+ codigo: "DOCTOR_CON_FALTANTES",
2354
+ datos: { revisiones, faltantes, version }
2355
+ });
2929
2356
  }
2930
- if (desenlace.estado !== "pendiente") borrarLoginPendiente(carpeta);
2931
- throw errorDelDesenlace(desenlace.estado);
2357
+ salida.linea("Todo en orden.");
2358
+ salida.resultado({ ok: true, proyecto, revisiones, faltantes: [], version });
2932
2359
  }
2933
- var Sesion = class {
2934
- constructor(almacen, identidad, salida, login2) {
2935
- this.almacen = almacen;
2936
- this.identidad = identidad;
2937
- this.salida = salida;
2938
- this.login = login2;
2360
+ async function revisarLlave(ctx, entorno, slug) {
2361
+ const revision = `llave-${entorno}`;
2362
+ const nombre = etiquetaLlave(entorno);
2363
+ const ruta = path7.relative(ctx.proyecto, rutaDeLaLlave(ctx.proyecto, entorno, ctx.env)) || rutaDeLaLlave(ctx.proyecto, entorno, ctx.env);
2364
+ const archivo = llaveDelEntorno(ctx.proyecto, entorno, ctx.env);
2365
+ if (!archivo) {
2366
+ return entorno === "prueba" ? { revision, ok: false, detalle: `Falta la ${nombre} (${ruta}).`, comando: COMANDO_INIT } : { revision, ok: false, opcional: true, detalle: `El proyecto todav\xEDa no tiene ${nombre}.`, comando: COMANDO_PASAR_A_PRODUCCION };
2939
2367
  }
2940
- actual = null;
2941
- async entrar() {
2942
- const par = await this.login();
2943
- this.almacen.guardar(par);
2944
- this.salida.linea(`Sesi\xF3n iniciada. Qued\xF3 guardada en ${this.almacen.descripcion}.`);
2945
- return par;
2368
+ if (slug && archivo.tenantSlug !== slug) {
2369
+ return { revision, ok: false, detalle: `La ${nombre} es de ${archivo.tenantSlug}, pero el proyecto apunta a ${slug}.`, comando: COMANDO_INIT };
2946
2370
  }
2947
- /** El access token de esta corrida: renueva siempre la sesión guardada y guarda el par rotado. */
2948
- async token() {
2949
- if (this.actual) return this.actual.access_token;
2950
- const guardada = this.almacen.leer();
2951
- if (!guardada) {
2952
- this.actual = await this.entrar();
2953
- return this.actual.access_token;
2954
- }
2955
- try {
2956
- this.actual = await this.identidad.renovar(guardada.refresh_token);
2957
- this.almacen.guardar(this.actual);
2958
- } catch (error) {
2959
- if (!(error instanceof ErrorRefreshInvalido)) throw error;
2960
- this.almacen.borrar();
2961
- this.salida.linea("Tu sesi\xF3n anterior venci\xF3 o se cerr\xF3. Inicia sesi\xF3n de nuevo.");
2962
- this.actual = await this.entrar();
2371
+ try {
2372
+ const r = await ctx.cliente.whoami(archivo.token, archivo.tenantSlug);
2373
+ if (r.estado === "rechazada") return { revision, ok: false, detalle: `La API rechaza la ${nombre} (${ruta}): fue revocada o venci\xF3.`, comando: entorno === "prueba" ? COMANDO_INIT : COMANDO_PASAR_A_PRODUCCION };
2374
+ if (r.sandbox !== (entorno === "prueba")) {
2375
+ return { revision, ok: false, detalle: `El archivo ${ruta} no trae una ${nombre}: seg\xFAn la API es de otro modo.`, comando: entorno === "prueba" ? COMANDO_INIT : COMANDO_PASAR_A_PRODUCCION };
2963
2376
  }
2964
- return this.actual.access_token;
2377
+ return { revision, ok: true, detalle: `La ${nombre} funciona (${r.tenant.nombre}).` };
2378
+ } catch (error) {
2379
+ return { revision, ok: false, detalle: `No pude comprobar la ${nombre}: ${error instanceof Error ? error.message : String(error)}` };
2965
2380
  }
2966
- /**
2967
- * Corre `operacion` con el token de la sesión. Si el API responde 401, borra la sesión, pide login y
2968
- * la repite UNA vez con el token nuevo; nunca reintenta con el mismo (`CA-33`).
2969
- */
2970
- async usar(operacion) {
2971
- try {
2972
- return await operacion(await this.token());
2973
- } catch (error) {
2974
- if (!(error instanceof ErrorSesionRechazada)) throw error;
2975
- this.almacen.borrar();
2976
- this.actual = null;
2977
- this.salida.linea("La plataforma rechaz\xF3 tu sesi\xF3n (por ejemplo, porque cambiaste tu contrase\xF1a). Inicia sesi\xF3n de nuevo.");
2978
- this.actual = await this.entrar();
2979
- try {
2980
- return await operacion(this.actual.access_token);
2981
- } catch (otra) {
2982
- if (otra instanceof ErrorSesionRechazada) throw new ErrorCli("La plataforma volvi\xF3 a rechazar la sesi\xF3n reci\xE9n iniciada. Escr\xEDbenos a soporte con la hora del intento.");
2983
- throw otra;
2984
- }
2381
+ }
2382
+ async function panel(ctx, opciones) {
2383
+ const slug = empresaDelProyecto(ctx, opciones.empresa);
2384
+ const url = `${ctx.servidores.web}${rutaDeEmpresa(slug, "/dashboard")}`;
2385
+ const abierto = opciones.sinNavegador ? false : await ctx.abrir(url);
2386
+ ctx.salida.linea(abierto ? `Abr\xED el panel de ${slug} en el navegador: ${url}` : `El panel de ${slug}: ${url}`);
2387
+ ctx.salida.resultado({ ok: true, empresa: slug, url, abierto });
2388
+ }
2389
+ function revisarSkill(ctx) {
2390
+ const destinos = { carpetaConfiguracion: ctx.carpetaConfiguracion, home: ctx.home, proyecto: tieneInstalacionDelCli(ctx.proyecto) ? ctx.proyecto : void 0 };
2391
+ try {
2392
+ const informe = revisarSkillInstalada({ destinos, version: ctx.version });
2393
+ if (informe.quitada) {
2394
+ return { revision: "skill", ok: true, detalle: "Quitaste la skill de REDCUMBRE con \xABredcumbre skill quitar\xBB: no se instala ni se renueva." };
2395
+ }
2396
+ const pendientes = informe.rutas.filter((r) => r.estado !== "al-dia" && r.estado !== "mas-nueva");
2397
+ if (pendientes.length === 0) {
2398
+ return { revision: "skill", ok: true, detalle: "La skill de REDCUMBRE y los comandos /redcumbre:tarifas y /redcumbre:issue est\xE1n al d\xEDa." };
2985
2399
  }
2400
+ const detalle = pendientes.map((r) => `${r.ruta} (${r.estado === "falta" ? "falta" : r.estado === "editada" ? "tiene cambios tuyos" : "de una versi\xF3n anterior"})`).join(", ");
2401
+ const faltaLaDelProyecto = pendientes.some((r) => r.id === "claude-proyecto" && r.estado === "falta");
2402
+ return { revision: "skill", ok: false, opcional: true, detalle: `Hay que renovar la skill o los comandos de Claude Code: ${detalle}.`, comando: faltaLaDelProyecto ? COMANDO_INIT : COMANDO_SKILL_RENOVAR };
2403
+ } catch (error) {
2404
+ return { revision: "skill", ok: false, opcional: true, detalle: `No pude revisar la skill de REDCUMBRE: ${error instanceof Error ? error.message : String(error)}`, comando: COMANDO_SKILL_RENOVAR };
2986
2405
  }
2987
- /** `logout`: revoca el refresh token (RFC 7009) y borra lo local. */
2988
- async cerrar() {
2989
- const guardada = this.almacen.leer();
2990
- if (!guardada) return false;
2991
- await this.identidad.revocar(guardada.refresh_token);
2992
- this.almacen.borrar();
2993
- return true;
2406
+ }
2407
+
2408
+ // src/comandos/emisores.ts
2409
+ import fs11 from "node:fs";
2410
+ import path12 from "node:path";
2411
+
2412
+ // src/comandos/emisores-operaciones.ts
2413
+ var RUT_FILTRO = { bandera: "--rut <rut>", obligatoria: false, tipo: "texto", destino: { en: "consulta", nombre: "rut" } };
2414
+ var ESTADO_FILTRO = { bandera: "--estado <estado>", obligatoria: false, tipo: "texto", destino: { en: "consulta", nombre: "estado" } };
2415
+ var INTEGRACION_FILTRO = { bandera: "--integracion <tipo>", obligatoria: false, tipo: "texto", destino: { en: "consulta", nombre: "tipoIntegracion" } };
2416
+ var CREDENCIAL_FILTRO = { bandera: "--credencial <estado>", obligatoria: false, tipo: "texto", destino: { en: "consulta", nombre: "credencialEstado" } };
2417
+ var ACTIVO_FILTRO = { bandera: "--activo <true|false>", obligatoria: false, tipo: "booleano", destino: { en: "consulta", nombre: "activo" }, valores: ["true", "false"] };
2418
+ var TRIBUTARIA_FILTRO = { bandera: "--tributaria <true|false>", obligatoria: false, tipo: "booleano", destino: { en: "consulta", nombre: "esTributaria" }, valores: ["true", "false"] };
2419
+ var LIMITE = { bandera: "--limite <n>", obligatoria: false, tipo: "entero", destino: { en: "consulta", nombre: "limit" } };
2420
+ var DESDE = { bandera: "--desde <n>", obligatoria: false, tipo: "entero", destino: { en: "consulta", nombre: "offset" } };
2421
+ var TODAS = { bandera: "--todas", obligatoria: false, tipo: "interruptor", destino: { en: "ninguno" } };
2422
+ var INCLUIR_ARCHIVADOS = { bandera: "--incluir-archivados", obligatoria: false, tipo: "interruptor", destino: { en: "consulta", nombre: "includeInactive", valorFijo: "true" } };
2423
+ var CUERPO_OBLIGATORIO = { bandera: "--cuerpo <json|@archivo|->", obligatoria: true, tipo: "cuerpo", destino: { en: "cuerpo-completo" } };
2424
+ var CUERPO_OPCIONAL = { bandera: "--cuerpo <json|@archivo|->", obligatoria: false, tipo: "cuerpo", destino: { en: "cuerpo-completo" } };
2425
+ var ARCHIVO_LOGO = { bandera: "--archivo <ruta>", obligatoria: true, tipo: "archivo", destino: { en: "formulario", nombre: "logo" } };
2426
+ var TIPOS_DE_CERTIFICACION = { bandera: "--tipos <lista>", obligatoria: true, tipo: "lista-de-enteros", destino: { en: "cuerpo", nombre: "tiposDte" } };
2427
+ var CORREO_DE_CONTACTO = { bandera: "--correo <correo>", obligatoria: true, tipo: "texto", destino: { en: "cuerpo", nombre: "emailContacto" } };
2428
+ var TELEFONO_DE_CONTACTO = { bandera: "--telefono <tel\xE9fono>", obligatoria: true, tipo: "texto", destino: { en: "cuerpo", nombre: "telefonoContacto" } };
2429
+ var RUT_DE_CONFIRMACION = { bandera: "--rut <rut>", obligatoria: true, tipo: "texto", destino: { en: "cuerpo", nombre: "confirmacionRut" } };
2430
+ var MOTIVO_OPCIONAL = { bandera: "--motivo <motivo>", obligatoria: false, tipo: "texto", destino: { en: "cuerpo", nombre: "motivo" } };
2431
+ var TIPO_DTE_DEL_AMBIENTE = { bandera: "--tipo-dte <n>", obligatoria: true, tipo: "entero", destino: { en: "cuerpo", nombre: "tipoDte" } };
2432
+ var AMBIENTE_DEL_TIPO = { bandera: "--ambiente <CERTIFICACION|PRODUCCION>", obligatoria: true, tipo: "ambiente", destino: { en: "cuerpo", nombre: "ambiente" }, valores: ["CERTIFICACION", "PRODUCCION"] };
2433
+ var TIPO_DE_EMISOR_A_REVOCAR = { bandera: "--tipo <tributario|dte>", obligatoria: true, tipo: "texto", destino: { en: "cuerpo", nombre: "tipoEmisor" }, valores: ["tributario", "dte"] };
2434
+ var MOTIVO_DE_REVOCACION = { bandera: "--motivo <motivo>", obligatoria: false, tipo: "texto", destino: { en: "cuerpo", nombre: "motivoRevocacion" } };
2435
+ var OPERACIONES_EMISORES = [
2436
+ {
2437
+ // 1
2438
+ comando: ["dte", "listar"],
2439
+ operationId: "listarEmisoresDte",
2440
+ metodo: "GET",
2441
+ ruta: "/{tenantSlug}/emisores",
2442
+ argumentos: [],
2443
+ banderas: [RUT_FILTRO, ESTADO_FILTRO, INTEGRACION_FILTRO, LIMITE, DESDE, TODAS],
2444
+ salida: "tabla",
2445
+ columnas: ["emisorId", "rut", "razonSocial", "tipoIntegracion", "estado"],
2446
+ confirmacion: "efecto"
2447
+ },
2448
+ {
2449
+ // 2
2450
+ comando: ["dte", "por-defecto"],
2451
+ operationId: "listarEmisoresDtePorDefecto",
2452
+ metodo: "GET",
2453
+ ruta: "/{tenantSlug}/emisores/default",
2454
+ argumentos: [],
2455
+ banderas: [],
2456
+ salida: "tabla",
2457
+ columnas: ["emisorId", "rut", "razonSocial", "tipoIntegracion"],
2458
+ confirmacion: "efecto"
2459
+ },
2460
+ {
2461
+ // 3
2462
+ comando: ["dte", "existe"],
2463
+ operationId: "verificarRutEmisorDte",
2464
+ metodo: "GET",
2465
+ ruta: "/{tenantSlug}/emisores/check-rut/{rut}",
2466
+ argumentos: ["rut"],
2467
+ banderas: [],
2468
+ salida: "ficha",
2469
+ confirmacion: "efecto"
2470
+ },
2471
+ {
2472
+ // 4
2473
+ comando: ["dte", "ver"],
2474
+ operationId: "obtenerEmisorDte",
2475
+ metodo: "GET",
2476
+ ruta: "/{tenantSlug}/emisores/{id}",
2477
+ argumentos: ["id"],
2478
+ banderas: [INCLUIR_ARCHIVADOS],
2479
+ salida: "ficha",
2480
+ confirmacion: "efecto"
2481
+ },
2482
+ {
2483
+ // 5
2484
+ comando: ["dte", "certificacion", "verificar"],
2485
+ operationId: "verificarCertificacionTipoEmisorDte",
2486
+ metodo: "GET",
2487
+ ruta: "/{tenantSlug}/emisores/{id}/verificar-certificacion/{tipoDte}",
2488
+ argumentos: ["id", "tipoDte"],
2489
+ banderas: [],
2490
+ salida: "ficha",
2491
+ confirmacion: "efecto"
2492
+ },
2493
+ {
2494
+ // 6
2495
+ comando: ["dte", "certificacion", "tipos"],
2496
+ operationId: "listarTiposCertificablesEmisorDte",
2497
+ metodo: "GET",
2498
+ ruta: "/{tenantSlug}/emisores/{id}/tipos-dte-certificables",
2499
+ argumentos: ["id"],
2500
+ banderas: [],
2501
+ salida: "ficha",
2502
+ confirmacion: "efecto"
2503
+ },
2504
+ {
2505
+ // 7
2506
+ comando: ["dte", "certificacion", "estado"],
2507
+ operationId: "consultarEstadoCertificacionRutEmisorDte",
2508
+ metodo: "GET",
2509
+ ruta: "/{tenantSlug}/emisores/{id}/estado-certificacion-rut",
2510
+ argumentos: ["id"],
2511
+ banderas: [],
2512
+ salida: "ficha",
2513
+ confirmacion: "efecto"
2514
+ },
2515
+ {
2516
+ // 8
2517
+ comando: ["dte", "mipyme", "estado"],
2518
+ operationId: "consultarEstadoMipymeEmisorDte",
2519
+ metodo: "GET",
2520
+ ruta: "/{tenantSlug}/emisores/{id}/mipyme/estado",
2521
+ argumentos: ["id"],
2522
+ banderas: [],
2523
+ salida: "ficha",
2524
+ confirmacion: "efecto"
2525
+ },
2526
+ {
2527
+ // 9
2528
+ comando: ["dte", "solicitudes"],
2529
+ operationId: "listarSolicitudesCertificacionEmisorDte",
2530
+ metodo: "GET",
2531
+ ruta: "/{tenantSlug}/emisores/{id}/solicitudes",
2532
+ argumentos: ["id"],
2533
+ banderas: [],
2534
+ salida: "tabla",
2535
+ columnas: ["solicitudId", "tipoSolicitud", "estado", "solicitadoEn"],
2536
+ confirmacion: "efecto"
2537
+ },
2538
+ {
2539
+ // 10
2540
+ comando: ["dte", "logo", "ver"],
2541
+ operationId: "obtenerLogoEmisorDte",
2542
+ metodo: "GET",
2543
+ ruta: "/{tenantSlug}/emisores/{id}/logo",
2544
+ argumentos: ["id"],
2545
+ banderas: [],
2546
+ salida: "ficha",
2547
+ confirmacion: "efecto"
2548
+ },
2549
+ {
2550
+ // 11
2551
+ comando: ["dte", "editar"],
2552
+ operationId: "actualizarEmisorDte",
2553
+ metodo: "PATCH",
2554
+ ruta: "/{tenantSlug}/emisores/{id}",
2555
+ argumentos: ["id"],
2556
+ banderas: [CUERPO_OBLIGATORIO],
2557
+ salida: "accion",
2558
+ hecho: "Emisor actualizado.",
2559
+ confirmacion: "efecto"
2560
+ },
2561
+ {
2562
+ // 12
2563
+ comando: ["dte", "fijar-por-defecto"],
2564
+ operationId: "asignarEmisorDtePorDefecto",
2565
+ metodo: "PATCH",
2566
+ ruta: "/{tenantSlug}/emisores/{id}/set-default",
2567
+ argumentos: ["id"],
2568
+ banderas: [],
2569
+ salida: "accion",
2570
+ hecho: "Emisor fijado por defecto.",
2571
+ confirmacion: "efecto"
2572
+ },
2573
+ {
2574
+ // 13
2575
+ comando: ["dte", "reactivar"],
2576
+ operationId: "reactivarEmisorDte",
2577
+ metodo: "PATCH",
2578
+ ruta: "/{tenantSlug}/emisores/{id}/reactivate",
2579
+ argumentos: ["id"],
2580
+ banderas: [CUERPO_OPCIONAL],
2581
+ salida: "accion",
2582
+ hecho: "Emisor reactivado.",
2583
+ confirmacion: "efecto"
2584
+ },
2585
+ {
2586
+ // 14
2587
+ comando: ["dte", "tipos-integracion", "crear"],
2588
+ operationId: "crearTipoIntegracionEmisorDte",
2589
+ metodo: "POST",
2590
+ ruta: "/{tenantSlug}/emisores/{id}/tipos-integracion",
2591
+ argumentos: ["id"],
2592
+ banderas: [CUERPO_OBLIGATORIO],
2593
+ salida: "accion",
2594
+ hecho: "Tipo de integraci\xF3n creado.",
2595
+ confirmacion: "efecto"
2596
+ },
2597
+ {
2598
+ // 15
2599
+ comando: ["dte", "tipos-integracion", "editar"],
2600
+ operationId: "actualizarTipoIntegracionEmisorDte",
2601
+ metodo: "PATCH",
2602
+ ruta: "/{tenantSlug}/emisores/{id}/tipos-integracion/{tiId}",
2603
+ argumentos: ["id", "tiId"],
2604
+ banderas: [CUERPO_OBLIGATORIO],
2605
+ salida: "accion",
2606
+ hecho: "Tipo de integraci\xF3n actualizado.",
2607
+ confirmacion: "efecto"
2608
+ },
2609
+ {
2610
+ // 16
2611
+ comando: ["dte", "logo", "subir"],
2612
+ operationId: "actualizarLogoEmisorDte",
2613
+ metodo: "POST",
2614
+ ruta: "/{tenantSlug}/emisores/{id}/logo",
2615
+ argumentos: ["id"],
2616
+ banderas: [ARCHIVO_LOGO],
2617
+ salida: "accion",
2618
+ hecho: "Logo actualizado.",
2619
+ confirmacion: "efecto"
2620
+ },
2621
+ {
2622
+ // 17
2623
+ comando: ["dte", "logo", "quitar"],
2624
+ operationId: "eliminarLogoEmisorDte",
2625
+ metodo: "DELETE",
2626
+ ruta: "/{tenantSlug}/emisores/{id}/logo",
2627
+ argumentos: ["id"],
2628
+ banderas: [],
2629
+ salida: "accion",
2630
+ hecho: "Logo eliminado.",
2631
+ confirmacion: "efecto"
2632
+ },
2633
+ {
2634
+ // 18
2635
+ comando: ["dte", "info-pago", "guardar"],
2636
+ operationId: "actualizarInfoPagoEmisorDte",
2637
+ metodo: "PUT",
2638
+ ruta: "/{tenantSlug}/emisores/{id}/info-pago",
2639
+ argumentos: ["id"],
2640
+ banderas: [CUERPO_OBLIGATORIO],
2641
+ salida: "accion",
2642
+ hecho: "Informaci\xF3n de pago guardada.",
2643
+ confirmacion: "efecto"
2644
+ },
2645
+ {
2646
+ // 19
2647
+ comando: ["dte", "info-pago", "quitar"],
2648
+ operationId: "eliminarInfoPagoEmisorDte",
2649
+ metodo: "DELETE",
2650
+ ruta: "/{tenantSlug}/emisores/{id}/info-pago",
2651
+ argumentos: ["id"],
2652
+ banderas: [],
2653
+ salida: "accion",
2654
+ hecho: "Informaci\xF3n de pago eliminada.",
2655
+ confirmacion: "efecto"
2656
+ },
2657
+ {
2658
+ // 20
2659
+ comando: ["dte", "resolver-conflictos"],
2660
+ operationId: "resolverConflictosEmisorDte",
2661
+ metodo: "POST",
2662
+ ruta: "/{tenantSlug}/emisores/{id}/resolver-conflictos",
2663
+ argumentos: ["id"],
2664
+ banderas: [CUERPO_OBLIGATORIO],
2665
+ salida: "accion",
2666
+ hecho: "Conflictos resueltos.",
2667
+ confirmacion: "efecto"
2668
+ },
2669
+ {
2670
+ // 21
2671
+ comando: ["dte", "certificacion", "certificar-tipos"],
2672
+ operationId: "crearSolicitudCertificacionTiposEmisorDte",
2673
+ metodo: "POST",
2674
+ ruta: "/{tenantSlug}/emisores/{id}/certificar-tipos",
2675
+ argumentos: ["id"],
2676
+ banderas: [TIPOS_DE_CERTIFICACION, CORREO_DE_CONTACTO, TELEFONO_DE_CONTACTO],
2677
+ salida: "accion",
2678
+ hecho: "Certificaci\xF3n de tipos solicitada.",
2679
+ confirmacion: "escrita",
2680
+ aviso: "Esto le pide al SII certificar al contribuyente, con el RUT de su representante legal."
2681
+ },
2682
+ {
2683
+ // 22
2684
+ comando: ["dte", "migrar"],
2685
+ operationId: "crearSolicitudMigracionEmisorDte",
2686
+ metodo: "POST",
2687
+ ruta: "/{tenantSlug}/emisores/{id}/migrar",
2688
+ argumentos: ["id"],
2689
+ banderas: [TIPOS_DE_CERTIFICACION, CORREO_DE_CONTACTO, TELEFONO_DE_CONTACTO],
2690
+ salida: "accion",
2691
+ hecho: "Migraci\xF3n solicitada.",
2692
+ confirmacion: "escrita",
2693
+ aviso: "Esto le pide al SII migrar el sistema de facturaci\xF3n del contribuyente. Puede dejar sin uso los folios que tenga."
2694
+ },
2695
+ {
2696
+ // 23
2697
+ comando: ["dte", "certificacion", "desistir"],
2698
+ operationId: "cancelarCertificacionEmisorDte",
2699
+ metodo: "POST",
2700
+ ruta: "/{tenantSlug}/emisores/{id}/desistir-certificacion",
2701
+ argumentos: ["id"],
2702
+ banderas: [RUT_DE_CONFIRMACION, MOTIVO_OPCIONAL],
2703
+ salida: "accion",
2704
+ hecho: "Desististe de la certificaci\xF3n.",
2705
+ confirmacion: "escrita",
2706
+ aviso: "Esto archiva el emisor y cierra sus solicitudes de certificaci\xF3n."
2707
+ },
2708
+ {
2709
+ // 24
2710
+ comando: ["dte", "mipyme", "habilitar"],
2711
+ operationId: "registrarEmisorDteEnPortalMipyme",
2712
+ metodo: "POST",
2713
+ ruta: "/{tenantSlug}/emisores/{id}/mipyme/habilitar",
2714
+ argumentos: ["id"],
2715
+ banderas: [],
2716
+ salida: "accion",
2717
+ hecho: "Portal MiPyme habilitado.",
2718
+ confirmacion: "escrita",
2719
+ aviso: "Esto inscribe al contribuyente en el Portal MiPyme del SII. Puede dejar sin uso los folios de mercado que tenga."
2720
+ },
2721
+ {
2722
+ // 25
2723
+ comando: ["dte", "ambiente"],
2724
+ operationId: "cambiarAmbienteTipoEmisorDte",
2725
+ metodo: "PATCH",
2726
+ ruta: "/{tenantSlug}/emisores/{id}/ambiente",
2727
+ argumentos: ["id"],
2728
+ banderas: [TIPO_DTE_DEL_AMBIENTE, AMBIENTE_DEL_TIPO],
2729
+ salida: "accion",
2730
+ hecho: "Ambiente cambiado.",
2731
+ confirmacion: "escrita",
2732
+ aviso: "Esto cambia el ambiente del SII por el que sale ese tipo de documento."
2733
+ },
2734
+ {
2735
+ // 26
2736
+ comando: ["dte", "archivar"],
2737
+ operationId: "archivarEmisorDte",
2738
+ metodo: "DELETE",
2739
+ ruta: "/{tenantSlug}/emisores/{id}",
2740
+ argumentos: ["id"],
2741
+ banderas: [RUT_DE_CONFIRMACION],
2742
+ salida: "accion",
2743
+ hecho: "Emisor archivado.",
2744
+ archiva: true,
2745
+ confirmacion: "escrita",
2746
+ aviso: "Esto saca al emisor de la operaci\xF3n y deja de cobrarse."
2747
+ },
2748
+ {
2749
+ // 27
2750
+ comando: ["tributarios", "archivar"],
2751
+ operationId: "archivarEmisorTributario",
2752
+ metodo: "DELETE",
2753
+ ruta: "/{tenantSlug}/emisores-tributarios/{id}",
2754
+ argumentos: ["id"],
2755
+ banderas: [],
2756
+ salida: "accion",
2757
+ hecho: "Emisor archivado.",
2758
+ archiva: true,
2759
+ confirmacion: "escrita",
2760
+ aviso: "Esto saca al emisor de la operaci\xF3n y deja de cobrarse."
2761
+ },
2762
+ {
2763
+ // 28
2764
+ comando: ["tributarios", "listar"],
2765
+ operationId: "listarEmisoresTributarios",
2766
+ metodo: "GET",
2767
+ ruta: "/{tenantSlug}/emisores-tributarios",
2768
+ argumentos: [],
2769
+ banderas: [RUT_FILTRO, ESTADO_FILTRO, CREDENCIAL_FILTRO, LIMITE, DESDE, TODAS],
2770
+ salida: "tabla",
2771
+ columnas: ["emisorId", "rut", "razonSocial", "estado", "credencialEstado"],
2772
+ confirmacion: "efecto"
2773
+ },
2774
+ {
2775
+ // 29
2776
+ comando: ["tributarios", "por-defecto"],
2777
+ operationId: "obtenerEmisorTributarioPorDefecto",
2778
+ metodo: "GET",
2779
+ ruta: "/{tenantSlug}/emisores-tributarios/default",
2780
+ argumentos: [],
2781
+ banderas: [],
2782
+ salida: "ficha",
2783
+ confirmacion: "efecto"
2784
+ },
2785
+ {
2786
+ // 30
2787
+ comando: ["tributarios", "existe"],
2788
+ operationId: "consultarRutEmisorTributario",
2789
+ metodo: "GET",
2790
+ ruta: "/{tenantSlug}/emisores-tributarios/check-rut/{rut}",
2791
+ argumentos: ["rut"],
2792
+ banderas: [],
2793
+ salida: "ficha",
2794
+ confirmacion: "efecto"
2795
+ },
2796
+ {
2797
+ // 31
2798
+ comando: ["tributarios", "ver"],
2799
+ operationId: "obtenerEmisorTributario",
2800
+ metodo: "GET",
2801
+ ruta: "/{tenantSlug}/emisores-tributarios/{id}",
2802
+ argumentos: ["id"],
2803
+ banderas: [INCLUIR_ARCHIVADOS],
2804
+ salida: "ficha",
2805
+ confirmacion: "efecto"
2806
+ },
2807
+ {
2808
+ // 32
2809
+ comando: ["tributarios", "logo", "ver"],
2810
+ operationId: "obtenerLogoEmisorTributario",
2811
+ metodo: "GET",
2812
+ ruta: "/{tenantSlug}/emisores-tributarios/{id}/logo",
2813
+ argumentos: ["id"],
2814
+ banderas: [],
2815
+ salida: "ficha",
2816
+ confirmacion: "efecto"
2817
+ },
2818
+ {
2819
+ // 33
2820
+ comando: ["tributarios", "certificado"],
2821
+ operationId: "obtenerCertificadoEmisorTributario",
2822
+ metodo: "GET",
2823
+ ruta: "/{tenantSlug}/emisores-tributarios/{id}/certificado",
2824
+ argumentos: ["id"],
2825
+ banderas: [],
2826
+ salida: "ficha",
2827
+ confirmacion: "efecto"
2828
+ },
2829
+ {
2830
+ // 34
2831
+ comando: ["tributarios", "editar"],
2832
+ operationId: "actualizarEmisorTributario",
2833
+ metodo: "PATCH",
2834
+ ruta: "/{tenantSlug}/emisores-tributarios/{id}",
2835
+ argumentos: ["id"],
2836
+ banderas: [CUERPO_OBLIGATORIO],
2837
+ salida: "accion",
2838
+ hecho: "Emisor actualizado.",
2839
+ confirmacion: "efecto"
2840
+ },
2841
+ {
2842
+ // 35
2843
+ comando: ["tributarios", "fijar-por-defecto"],
2844
+ operationId: "cambiarEmisorTributarioPorDefecto",
2845
+ metodo: "PATCH",
2846
+ ruta: "/{tenantSlug}/emisores-tributarios/{id}/set-default",
2847
+ argumentos: ["id"],
2848
+ banderas: [],
2849
+ salida: "accion",
2850
+ hecho: "Emisor fijado por defecto.",
2851
+ confirmacion: "efecto"
2852
+ },
2853
+ {
2854
+ // 36
2855
+ comando: ["tributarios", "reactivar"],
2856
+ operationId: "reactivarEmisorTributario",
2857
+ metodo: "PATCH",
2858
+ ruta: "/{tenantSlug}/emisores-tributarios/{id}/reactivate",
2859
+ argumentos: ["id"],
2860
+ banderas: [CUERPO_OPCIONAL],
2861
+ salida: "accion",
2862
+ hecho: "Emisor reactivado.",
2863
+ confirmacion: "efecto"
2864
+ },
2865
+ {
2866
+ // 37
2867
+ comando: ["tributarios", "logo", "subir"],
2868
+ operationId: "actualizarLogoEmisorTributario",
2869
+ metodo: "POST",
2870
+ ruta: "/{tenantSlug}/emisores-tributarios/{id}/logo",
2871
+ argumentos: ["id"],
2872
+ banderas: [ARCHIVO_LOGO],
2873
+ salida: "accion",
2874
+ hecho: "Logo actualizado.",
2875
+ confirmacion: "efecto"
2876
+ },
2877
+ {
2878
+ // 38
2879
+ comando: ["tributarios", "logo", "quitar"],
2880
+ operationId: "eliminarLogoEmisorTributario",
2881
+ metodo: "DELETE",
2882
+ ruta: "/{tenantSlug}/emisores-tributarios/{id}/logo",
2883
+ argumentos: ["id"],
2884
+ banderas: [],
2885
+ salida: "accion",
2886
+ hecho: "Logo eliminado.",
2887
+ confirmacion: "efecto"
2888
+ },
2889
+ {
2890
+ // 39
2891
+ comando: ["sucursales", "listar"],
2892
+ operationId: "listarSucursalesEmisorDte",
2893
+ metodo: "GET",
2894
+ ruta: "/{tenantSlug}/dte/emisores/{emisorId}/sucursales",
2895
+ argumentos: ["emisorId"],
2896
+ banderas: [ACTIVO_FILTRO, TRIBUTARIA_FILTRO, LIMITE, DESDE, TODAS],
2897
+ salida: "tabla",
2898
+ columnas: ["sucursalId", "nombre", "direccion", "comuna", "ciudad"],
2899
+ confirmacion: "efecto"
2900
+ },
2901
+ {
2902
+ // 40
2903
+ comando: ["sucursales", "crear"],
2904
+ operationId: "crearSucursalEmisorDte",
2905
+ metodo: "POST",
2906
+ ruta: "/{tenantSlug}/dte/emisores/{emisorId}/sucursales",
2907
+ argumentos: ["emisorId"],
2908
+ banderas: [CUERPO_OBLIGATORIO],
2909
+ salida: "accion",
2910
+ hecho: "Sucursal creada.",
2911
+ confirmacion: "efecto"
2912
+ },
2913
+ {
2914
+ // 41
2915
+ comando: ["sucursales", "editar"],
2916
+ operationId: "actualizarSucursalEmisorDte",
2917
+ metodo: "PATCH",
2918
+ ruta: "/{tenantSlug}/dte/sucursales/{sucursalId}",
2919
+ argumentos: ["sucursalId"],
2920
+ banderas: [CUERPO_OBLIGATORIO],
2921
+ salida: "accion",
2922
+ hecho: "Sucursal actualizada.",
2923
+ confirmacion: "efecto"
2924
+ },
2925
+ {
2926
+ // 42
2927
+ comando: ["sucursales", "desactivar"],
2928
+ operationId: "desactivarSucursalEmisorDte",
2929
+ metodo: "DELETE",
2930
+ ruta: "/{tenantSlug}/dte/sucursales/{sucursalId}",
2931
+ argumentos: ["sucursalId"],
2932
+ banderas: [],
2933
+ salida: "accion",
2934
+ hecho: "Sucursal desactivada.",
2935
+ confirmacion: "efecto"
2936
+ },
2937
+ {
2938
+ // 43
2939
+ comando: ["representantes", "listar"],
2940
+ operationId: "listarRepresentantesLegales",
2941
+ metodo: "GET",
2942
+ ruta: "/{tenantSlug}/representantes-legales",
2943
+ argumentos: [],
2944
+ banderas: [RUT_FILTRO, LIMITE, DESDE, TODAS],
2945
+ salida: "tabla",
2946
+ columnas: ["rut", "nombre", "certVigente", "certValidoHasta", "emisoresCount"],
2947
+ confirmacion: "efecto"
2948
+ },
2949
+ {
2950
+ // 44
2951
+ comando: ["dte", "sincronizar"],
2952
+ operationId: "actualizarEmisorDteDesdeSii",
2953
+ metodo: "POST",
2954
+ ruta: "/{tenantSlug}/emisores/{id}/sincronizar",
2955
+ argumentos: ["id"],
2956
+ banderas: [],
2957
+ salida: "ficha",
2958
+ confirmacion: "efecto"
2959
+ },
2960
+ {
2961
+ // 45
2962
+ comando: ["dte", "credencial", "reintentar"],
2963
+ operationId: "reintentarCredencialPortalEmisorDte",
2964
+ metodo: "POST",
2965
+ ruta: "/{tenantSlug}/emisores/{id}/credencial-portal/reintentar",
2966
+ argumentos: ["id"],
2967
+ banderas: [],
2968
+ salida: "ficha",
2969
+ confirmacion: "efecto"
2970
+ },
2971
+ {
2972
+ // 46
2973
+ comando: ["tributarios", "credencial", "reintentar"],
2974
+ operationId: "reintentarCredencialEmisorTributario",
2975
+ metodo: "POST",
2976
+ ruta: "/{tenantSlug}/emisores-tributarios/{id}/credencial/reintentar",
2977
+ argumentos: ["id"],
2978
+ banderas: [],
2979
+ salida: "ficha",
2980
+ confirmacion: "efecto"
2981
+ },
2982
+ {
2983
+ // 47
2984
+ comando: ["revocar"],
2985
+ operationId: "revocarEmisorTokenizado",
2986
+ metodo: "POST",
2987
+ ruta: "/{tenantSlug}/tokenizacion/revoke",
2988
+ argumentos: ["id"],
2989
+ argumentoACuerpo: "emisorId",
2990
+ banderas: [TIPO_DE_EMISOR_A_REVOCAR, MOTIVO_DE_REVOCACION],
2991
+ salida: "accion",
2992
+ hecho: "Emisor revocado.",
2993
+ confirmacion: "escrita",
2994
+ aviso: "Esto revoca la autorizaci\xF3n y elimina sus credenciales de inmediato."
2995
+ },
2996
+ {
2997
+ // 48
2998
+ comando: ["dte", "volver-a-mipyme"],
2999
+ operationId: "volverEmisorDteAlPortalMipyme",
3000
+ metodo: "POST",
3001
+ ruta: "/{tenantSlug}/emisores/{id}/volver-a-mipyme",
3002
+ argumentos: ["id"],
3003
+ banderas: [RUT_DE_CONFIRMACION],
3004
+ salida: "accion",
3005
+ hecho: "Emisor vuelto al Portal MiPyme.",
3006
+ confirmacion: "escrita",
3007
+ 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."
2994
3008
  }
2995
- };
3009
+ ];
2996
3010
 
2997
- // src/nucleo/contexto.ts
2998
- var sinSesionEnModoAgente = () => new ErrorCli(
2999
- "No hay una sesi\xF3n iniciada y en modo agente no puedo esperar a que la persona inicie sesi\xF3n. Corre \xABredcumbre login\xBB, p\xEDdele a la persona que apruebe el acceso en la direcci\xF3n que responde y termina con \xABredcumbre login --completar\xBB.",
3000
- CODIGOS_DE_SALIDA.sesion,
3001
- { codigo: "SIN_SESION", comando: "redcumbre login" }
3011
+ // src/comandos/registro.ts
3012
+ import { Option } from "commander";
3013
+
3014
+ // src/nucleo/actualizacion-del-cli.ts
3015
+ import fs9 from "node:fs";
3016
+ import path9 from "node:path";
3017
+
3018
+ // src/nucleo/bienvenida.ts
3019
+ var TITULO_DE_BIENVENIDA = "BIENVENIDO A REDCUMBRE";
3020
+ var ETIQUETA_DEL_AVISO = "AVISO IMPORTANTE";
3021
+ var AVISO_DE_COBROS = "En modo de prueba nada se cobra, en modo de producci\xF3n las acciones se cobran de acuerdo a tu plan. Siempre puedes consultar con redcumbre:tarifas los precios de todas tus operaciones o en el panel web en la secci\xF3n Mi suscripci\xF3n.";
3022
+ var ANCHO_PLANO = 80;
3023
+ var ANCHO_DEL_RECUADRO = 76;
3024
+ var RELLENO = 2;
3025
+ var LETRAS = {
3026
+ R: [" ____ ", "| _ \\ ", "| |_) |", "| _ < ", "|_| \\_\\"],
3027
+ E: [" _____ ", "| ____|", "| _| ", "| |___ ", "|_____|"],
3028
+ D: [" ____ ", "| _ \\ ", "| | | |", "| |_| |", "|____/ "],
3029
+ C: [" ____ ", " / ___|", "| | ", "| |___ ", " \\____|"],
3030
+ U: [" _ _ ", "| | | |", "| | | |", "| |_| |", " \\___/ "],
3031
+ M: [" __ __ ", "| \\/ |", "| |\\/| |", "| | | |", "|_| |_|"],
3032
+ B: [" ____ ", "| __ ) ", "| _ \\ ", "| |_) |", "|____/ "]
3033
+ };
3034
+ var LOGO = [0, 1, 2, 3, 4].map(
3035
+ (fila) => [..."REDCUMBRE"].map((letra) => LETRAS[letra][fila]).join(" ").replace(/\s+$/, "")
3002
3036
  );
3003
- function crearContexto(opciones) {
3004
- const { salida, terminal, env } = opciones;
3005
- const destinos = servidores(env);
3006
- const proyecto = raizDelProyecto(opciones.cwd);
3007
- const carpeta = carpetaDeConfiguracion(env);
3008
- const identidad = identidadOidc();
3009
- let almacen = null;
3010
- let sesion = null;
3011
- const elAlmacen = () => almacen ??= elegirAlmacen(proyecto, env);
3012
- const abrir = async (destino) => {
3013
- const propio = env.REDCUMBRE_ABRIR;
3014
- if (propio) return abrirCon(propio, destino);
3015
- return abrirNavegadorDelSistema(destino);
3016
- };
3017
- return {
3018
- salida,
3019
- terminal,
3020
- cliente: new ClienteApi(destinos.api),
3021
- servidores: destinos,
3022
- carpetaConfiguracion: carpeta,
3023
- home: os2.homedir(),
3024
- cwd: opciones.cwd,
3025
- proyecto,
3026
- env,
3027
- version: opciones.version,
3028
- identidad,
3029
- ahora: () => /* @__PURE__ */ new Date(),
3030
- abrir,
3031
- almacen: elAlmacen,
3032
- async haySesion() {
3033
- return (await elAlmacen()).leer() !== null;
3034
- },
3035
- sesion() {
3036
- sesion ??= elAlmacen().then(
3037
- (a) => new Sesion(a, identidad, salida, async () => {
3038
- if (!terminal) throw sinSesionEnModoAgente();
3039
- return iniciarSesion(identidad, salida, {
3040
- sinNavegador: hayQueIrSinNavegador(opciones.sinNavegador, env),
3041
- abrirNavegador: abrir
3042
- });
3043
- })
3044
- );
3045
- return sesion;
3037
+ var ANSI = {
3038
+ reset: "\x1B[0m",
3039
+ negrita: "\x1B[1m",
3040
+ rojoBrillante: "\x1B[91m",
3041
+ amarilloBrillante: "\x1B[93m",
3042
+ etiqueta: "\x1B[1;97;41m"
3043
+ };
3044
+ function envolver(texto2, ancho) {
3045
+ const lineas = [];
3046
+ let actual = "";
3047
+ for (const palabra of texto2.split(/\s+/).filter(Boolean)) {
3048
+ if (actual && actual.length + 1 + palabra.length > ancho) {
3049
+ lineas.push(actual);
3050
+ actual = palabra;
3051
+ } else {
3052
+ actual = actual ? `${actual} ${palabra}` : palabra;
3046
3053
  }
3047
- };
3054
+ }
3055
+ if (actual) lineas.push(actual);
3056
+ return lineas;
3048
3057
  }
3049
- async function abrirCon(programa2, destino) {
3050
- const { spawn: spawn4 } = await import("node:child_process");
3051
- return new Promise((resolver) => {
3052
- const hijo = spawn4(programa2, [destino], { stdio: "ignore" });
3053
- hijo.once("error", () => resolver(false));
3054
- hijo.once("exit", (codigo) => resolver(codigo === 0));
3055
- });
3058
+ var tituloConVersion = (version) => `${TITULO_DE_BIENVENIDA} \xB7 CLI ${version}`;
3059
+ var AVISO_EN_TEXTO = `${ETIQUETA_DEL_AVISO}: ${AVISO_DE_COBROS}`;
3060
+ function textoPlanoDeBienvenida(version) {
3061
+ return [...envolver(tituloConVersion(version), ANCHO_PLANO), ...envolver(AVISO_EN_TEXTO, ANCHO_PLANO)].join("\n");
3062
+ }
3063
+ var ANCHO_INTERIOR = ANCHO_DEL_RECUADRO - 2 - 2 * RELLENO;
3064
+ var ANCHO_DE_LA_PANTALLA = Math.max(ANCHO_DEL_RECUADRO, ...LOGO.map((l) => l.length));
3065
+ function pantallaDeBienvenida(version, { color }) {
3066
+ const pintar = (codigo, texto2) => color ? `${codigo}${texto2}${ANSI.reset}` : texto2;
3067
+ const relleno = " ".repeat(RELLENO);
3068
+ const borde = (texto2) => pintar(ANSI.amarilloBrillante, texto2);
3069
+ const interior = (texto2, visible = texto2) => `${borde("\u2551")}${relleno}${texto2}${" ".repeat(ANCHO_INTERIOR - visible.length)}${relleno}${borde("\u2551")}`;
3070
+ const lineas = [];
3071
+ for (const fila of LOGO) lineas.push(pintar(ANSI.rojoBrillante, fila));
3072
+ lineas.push("");
3073
+ lineas.push(pintar(ANSI.negrita, tituloConVersion(version)));
3074
+ lineas.push("");
3075
+ lineas.push(borde(`\u2554${"\u2550".repeat(ANCHO_DEL_RECUADRO - 2)}\u2557`));
3076
+ lineas.push(interior(pintar(ANSI.etiqueta, ` ${ETIQUETA_DEL_AVISO} `), ` ${ETIQUETA_DEL_AVISO} `));
3077
+ for (const linea of envolver(AVISO_DE_COBROS, ANCHO_INTERIOR)) lineas.push(interior(linea));
3078
+ lineas.push(borde(`\u255A${"\u2550".repeat(ANCHO_DEL_RECUADRO - 2)}\u255D`));
3079
+ return lineas.join("\n");
3080
+ }
3081
+ function mostrarBienvenida(salida, version, entorno) {
3082
+ const plano = textoPlanoDeBienvenida(version);
3083
+ if (salida.json) {
3084
+ salida.anexar("bienvenida", { titulo: TITULO_DE_BIENVENIDA, aviso: AVISO_EN_TEXTO, version, texto: plano });
3085
+ salida.linea();
3086
+ salida.linea(plano);
3087
+ return;
3088
+ }
3089
+ const sinColor = (entorno.env.NO_COLOR ?? "") !== "" || entorno.env.TERM === "dumb";
3090
+ const angosta = entorno.columnas !== void 0 && entorno.columnas < ANCHO_DE_LA_PANTALLA;
3091
+ salida.linea();
3092
+ salida.linea(sinColor || angosta ? plano : pantallaDeBienvenida(version, { color: true }));
3093
+ salida.linea();
3056
3094
  }
3057
3095
 
3058
3096
  // src/nucleo/instalacion-del-cli.ts
3059
3097
  import { spawnSync as spawnSync2 } from "node:child_process";
3060
3098
  import fs8 from "node:fs";
3061
3099
  import path8 from "node:path";
3062
- import { fileURLToPath } from "node:url";
3100
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
3063
3101
  var real = (ruta) => {
3064
3102
  try {
3065
3103
  return fs8.realpathSync(ruta);
@@ -3090,7 +3128,7 @@ function comandoDeActualizacion(forma, version, registro) {
3090
3128
  return { comando: "npm", args: ["install", "--global", ...conRegistro, paquete] };
3091
3129
  }
3092
3130
  var legible = (c) => [c.comando, ...c.args].join(" ");
3093
- var comandoInstalarPorNpx = (version, confirmado) => `npx ${PAQUETE_DEL_CLI}@${version} instalar${confirmado ? " --confirmar" : ""}`;
3131
+ var comandoInstalarPorNpx = (version) => `npx ${PAQUETE_DEL_CLI}@${version} instalar`;
3094
3132
  var prefijoPorNpx = (version) => `npx ${PAQUETE_DEL_CLI}@${version}`;
3095
3133
  function ejecutarDeVerdad(comando2, args, opciones) {
3096
3134
  const r = spawnSync2(comando2, args, { cwd: opciones.cwd, env: opciones.env, encoding: "utf8", shell: process.platform === "win32", timeout: 10 * 6e4 });
@@ -3099,7 +3137,7 @@ function ejecutarDeVerdad(comando2, args, opciones) {
3099
3137
  function entornoDeActualizacion(ctx) {
3100
3138
  const registro = ctx.env.REDCUMBRE_NPM_REGISTRY || void 0;
3101
3139
  return {
3102
- bundle: fileURLToPath(import.meta.url),
3140
+ bundle: fileURLToPath2(import.meta.url),
3103
3141
  ejecutar: ejecutarDeVerdad,
3104
3142
  raizGlobal(gestor) {
3105
3143
  const r = ejecutarDeVerdad(gestor, ["root", "--global"], { cwd: ctx.cwd, env: ctx.env });
@@ -3134,343 +3172,675 @@ function carpetaDeEjecutablesDeNpm(entorno, opciones) {
3134
3172
  return process.platform === "win32" ? prefijo : path8.join(prefijo, "bin");
3135
3173
  }
3136
3174
 
3137
- // src/nucleo/skill.ts
3138
- import { createHash, randomBytes } from "node:crypto";
3139
- import fs9 from "node:fs";
3140
- import path9 from "node:path";
3141
- import { fileURLToPath as fileURLToPath2 } from "node:url";
3142
- var NOMBRE_SKILL = "redcumbre";
3143
- var MARCA_INICIO = "<!-- redcumbre:inicio -->";
3144
- var MARCA_FIN = "<!-- redcumbre:fin -->";
3145
- var sha256 = (texto2) => createHash("sha256").update(texto2).digest("hex");
3146
- function carpetaDeLaSkill(aqui = path9.dirname(fileURLToPath2(import.meta.url))) {
3147
- const candidatas = [path9.join(aqui, "skill"), path9.join(aqui, "..", "skill"), path9.join(aqui, "..", "..", "skill")];
3148
- for (const candidata of candidatas) {
3149
- if (fs9.existsSync(path9.join(candidata, NOMBRE_SKILL, "SKILL.md"))) return candidata;
3175
+ // src/nucleo/actualizacion-del-cli.ts
3176
+ var real2 = (ruta) => {
3177
+ try {
3178
+ return fs9.realpathSync(ruta);
3179
+ } catch {
3180
+ return null;
3181
+ }
3182
+ };
3183
+ function leerJson2(texto2) {
3184
+ try {
3185
+ const dato = JSON.parse(texto2);
3186
+ return dato && typeof dato === "object" && !Array.isArray(dato) ? dato : null;
3187
+ } catch {
3188
+ return null;
3189
+ }
3190
+ }
3191
+ function errorDeActualizacion(comando2, corrida) {
3192
+ const detalle = (corrida.stderr || corrida.stdout).trim().split(/\r?\n/).slice(-5).join(" \xB7 ");
3193
+ return new ErrorCli(`No pude actualizar el CLI: \xAB${legible(comando2)}\xBB termin\xF3 con ${corrida.status ?? "una se\xF1al"}${detalle ? ` (${detalle})` : ""}. No cambi\xE9 nada m\xE1s.`, CODIGOS_DE_SALIDA.error, {
3194
+ codigo: "ACTUALIZACION_FALLIDA",
3195
+ datos: { comando: legible(comando2) }
3196
+ });
3197
+ }
3198
+ function actualizarElCli(ctx, entorno, disponible, informar) {
3199
+ const registro = ctx.env.REDCUMBRE_NPM_REGISTRY || void 0;
3200
+ const instalacion = detectarInstalacion(entorno.bundle, entorno.raizGlobal);
3201
+ if (instalacion.forma === "no-reconocida") {
3202
+ throw new ErrorCli(
3203
+ `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.`,
3204
+ CODIGOS_DE_SALIDA.error,
3205
+ { codigo: "INSTALACION_NO_RECONOCIDA", datos: { instalada: ctx.version, disponible } }
3206
+ );
3207
+ }
3208
+ const comando2 = comandoDeActualizacion(instalacion.forma, disponible, registro);
3209
+ informar(`Actualizando: ${legible(comando2)}`);
3210
+ const corrida = entorno.ejecutar(comando2.comando, comando2.args, { cwd: ctx.cwd, env: ctx.env });
3211
+ if (corrida.status !== 0) throw errorDeActualizacion(comando2, corrida);
3212
+ const raizNpm = instalacion.forma === "npx" ? entorno.raizGlobal("npm") : null;
3213
+ const carpetaDelPaquete = instalacion.forma === "npx" ? raizNpm ? real2(path9.join(raizNpm, ...PAQUETE_DEL_CLI.split("/"))) : null : instalacion.carpetaDelPaquete;
3214
+ if (!carpetaDelPaquete) {
3215
+ throw new ErrorCli(
3216
+ `\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.`,
3217
+ CODIGOS_DE_SALIDA.error,
3218
+ { codigo: "ACTUALIZACION_INCOMPLETA", datos: { instalada: ctx.version, disponible } }
3219
+ );
3220
+ }
3221
+ const bundleNuevo = path9.join(carpetaDelPaquete, "dist", "redcumbre.js");
3222
+ const version = entorno.ejecutar(process.execPath, [bundleNuevo, "--version"], { cwd: ctx.cwd, env: ctx.env });
3223
+ if (version.status !== 0 || version.stdout.trim() !== disponible) {
3224
+ throw new ErrorCli(
3225
+ `\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.`,
3226
+ CODIGOS_DE_SALIDA.error,
3227
+ { codigo: "ACTUALIZACION_INCOMPLETA", datos: { instalada: ctx.version, disponible } }
3228
+ );
3229
+ }
3230
+ const renovacion = entorno.ejecutar(process.execPath, [bundleNuevo, "skill", "renovar", "--json"], { cwd: ctx.cwd, env: ctx.env });
3231
+ const skill = renovacion.status === 0 ? leerJson2(renovacion.stdout)?.skill ?? null : null;
3232
+ return { forma: instalacion.forma, comando: legible(comando2), skill };
3233
+ }
3234
+ function resumirLaSkill(skill) {
3235
+ const rutas = Array.isArray(skill?.rutas) ? skill.rutas : [];
3236
+ const copias = rutas.flatMap((r) => r.accion === "reemplazada-editada" && typeof r.copia === "string" ? [r.copia] : []);
3237
+ return { renovadas: rutas.filter((r) => r.accion === "renovada" || r.accion === "instalada" || r.accion === "reemplazada-editada").length, copias };
3238
+ }
3239
+ function textoDeLaSkillRenovada(resumen) {
3240
+ if (resumen.copias.length > 0) return `reemplac\xE9 la skill; tu versi\xF3n editada de la skill qued\xF3 en ${resumen.copias.join(" y ")}`;
3241
+ if (resumen.renovadas > 0) return "renov\xE9 la skill";
3242
+ return "no hab\xEDa una skill instalada por el CLI que renovar";
3243
+ }
3244
+ var motivoDe2 = (error) => error instanceof Error ? error.message : String(error);
3245
+ async function autoactualizarElCli(ctx, opciones) {
3246
+ const { entorno, salida, agente } = opciones;
3247
+ const depurar = opciones.depurar ?? (() => void 0);
3248
+ const err = opciones.stderr ?? process.stderr;
3249
+ let actualizacion;
3250
+ try {
3251
+ const { ultima } = await ultimaVersionConocida({
3252
+ carpeta: ctx.carpetaConfiguracion,
3253
+ version: ctx.version,
3254
+ ahora: ctx.ahora(),
3255
+ registro: ctx.env.REDCUMBRE_NPM_REGISTRY,
3256
+ consultar: opciones.consultar,
3257
+ sinMarca: opciones.consultaSinMarca
3258
+ });
3259
+ if (opciones.consultaSinMarca) ctx.versionDelRegistro = { ultima };
3260
+ actualizacion = ultima && compararVersiones(ultima, ctx.version) > 0 ? { instalada: ctx.version, disponible: ultima, comando: COMANDO_ACTUALIZAR } : null;
3261
+ } catch (error) {
3262
+ depurar(`no pude leer la marca de versi\xF3n: ${motivoDe2(error)}`);
3263
+ return false;
3264
+ }
3265
+ if (!actualizacion) return false;
3266
+ const instalacion = detectarInstalacion(entorno.bundle, entorno.raizGlobal);
3267
+ if (instalacion.forma === "no-reconocida") {
3268
+ depurar(`hay una versi\xF3n m\xE1s nueva del CLI (${actualizacion.disponible}), pero no la instalo: ${instalacion.motivo}`);
3269
+ return false;
3270
+ }
3271
+ const porNpx = instalacion.forma === "npx";
3272
+ const comandoManual = porNpx ? `${prefijoPorNpx(ctx.version)} actualizar` : COMANDO_ACTUALIZAR;
3273
+ const { instalada: instalada2, disponible } = actualizacion;
3274
+ actualizacion.comando = comandoManual;
3275
+ const fallo2 = (error, avisarEnTerminal) => {
3276
+ if (agente) {
3277
+ salida.anexar("actualizacion", { instalada: instalada2, disponible, actualizado: false, comando: comandoManual, ...error ? { error } : {} });
3278
+ salida.avisoAlAgente(avisoDeActualizacion(actualizacion, error?.mensaje));
3279
+ } else if (avisarEnTerminal) {
3280
+ err.write(`\u26A0 No pude actualizar el CLI solo${error ? ` (${error.mensaje})` : ""}. Actual\xEDzalo con \xAB${comandoManual}\xBB.
3281
+ `);
3282
+ }
3283
+ };
3284
+ if (yaSeIntento(ctx.carpetaConfiguracion, disponible, ctx.ahora())) {
3285
+ depurar(`ya intent\xE9 actualizar el CLI a ${disponible} en las \xFAltimas 24 h; no lo reintento`);
3286
+ fallo2(null, false);
3287
+ return false;
3288
+ }
3289
+ marcarIntento(ctx.carpetaConfiguracion, disponible, ctx.ahora());
3290
+ try {
3291
+ const r = actualizarElCli(ctx, entorno, disponible, (texto2) => {
3292
+ if (!agente) err.write(`${texto2}
3293
+ `);
3294
+ });
3295
+ const resumen = resumirLaSkill(r.skill);
3296
+ if (agente) {
3297
+ salida.anexar("actualizacion", { instalada: instalada2, disponible, actualizado: true, forma: r.forma, comando: r.comando, skill: r.skill });
3298
+ salida.avisoAlAgente(
3299
+ r.skill === null ? `Actualic\xE9 el CLI de ${instalada2} a ${disponible}, sin preguntarle a nadie, pero no pude renovar la skill: corre \xABredcumbre skill renovar\xBB. Este comando corri\xF3 con la ${instalada2}; los siguientes usan la ${disponible}.` : `Actualic\xE9 el CLI de ${instalada2} a ${disponible} y ${textoDeLaSkillRenovada(resumen)}, sin preguntarle a nadie. Este comando corri\xF3 con la ${instalada2}; los siguientes usan la ${disponible}.${resumen.renovadas > 0 ? " Vuelve a leer la skill \xABredcumbre\xBB si la tienes cargada." : ""}`
3300
+ );
3301
+ } else {
3302
+ if (r.skill === null) err.write(`\u26A0 El CLI qued\xF3 en la versi\xF3n ${disponible}, pero no pude renovar la skill: corre \xABredcumbre skill renovar\xBB.
3303
+ `);
3304
+ err.write(`\u2713 Actualic\xE9 el CLI de ${instalada2} a ${disponible}${r.skill === null ? "" : ` y ${textoDeLaSkillRenovada(resumen)}`}.
3305
+ `);
3306
+ for (const copia of resumen.copias) err.write(`\u2139 Tu versi\xF3n editada de la skill qued\xF3 en ${copia}.
3307
+ `);
3308
+ mostrarBienvenida(salida, disponible, { env: ctx.env, columnas: salida.humano.columns });
3309
+ }
3310
+ return true;
3311
+ } catch (error) {
3312
+ const codigo = error instanceof ErrorCli && error.codigo ? error.codigo : "ACTUALIZACION_FALLIDA";
3313
+ depurar(`la auto-actualizaci\xF3n a ${disponible} fall\xF3 (${codigo}): ${motivoDe2(error)}`);
3314
+ fallo2({ codigo, mensaje: motivoDe2(error) }, true);
3315
+ return false;
3316
+ }
3317
+ }
3318
+
3319
+ // src/nucleo/contexto.ts
3320
+ import os2 from "node:os";
3321
+
3322
+ // src/nucleo/sesion.ts
3323
+ import { spawn } from "node:child_process";
3324
+ import fs10 from "node:fs";
3325
+ import os from "node:os";
3326
+ import path10 from "node:path";
3327
+ import { setTimeout as setTimeoutAbortable } from "node:timers/promises";
3328
+ import * as oidc from "openid-client";
3329
+
3330
+ // src/nucleo/retorno-local.ts
3331
+ import http from "node:http";
3332
+ function paginaListo(titulo, texto2) {
3333
+ return `<!doctype html><html lang="es"><head><meta charset="utf-8"><title>REDCUMBRE</title>
3334
+ <meta name="viewport" content="width=device-width, initial-scale=1">
3335
+ <style>body{font-family:system-ui,sans-serif;display:flex;min-height:100vh;align-items:center;justify-content:center;margin:0;background:Canvas;color:CanvasText}
3336
+ main{max-width:28rem;padding:1.5rem;text-align:center}h1{font-size:1.25rem;margin:0 0 .5rem}p{margin:0;opacity:.8}</style></head>
3337
+ <body><main><h1>${titulo}</h1><p>${texto2}</p></main></body></html>`;
3338
+ }
3339
+ async function abrirRetornoLocal(opciones) {
3340
+ let resolver;
3341
+ let rechazar;
3342
+ const recibido = new Promise((ok, falla) => {
3343
+ resolver = ok;
3344
+ rechazar = falla;
3345
+ });
3346
+ recibido.catch(() => void 0);
3347
+ const servidor = http.createServer((req, res) => {
3348
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
3349
+ if (url.pathname !== "/callback") {
3350
+ res.writeHead(404).end();
3351
+ return;
3352
+ }
3353
+ if (opciones.aceptar && !opciones.aceptar(url)) {
3354
+ res.writeHead(400).end();
3355
+ return;
3356
+ }
3357
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }).end(opciones.pagina);
3358
+ resolver(url);
3359
+ });
3360
+ await new Promise((ok) => servidor.listen(0, "127.0.0.1", ok));
3361
+ const { port } = servidor.address();
3362
+ let espera;
3363
+ const cerrar = () => {
3364
+ clearTimeout(espera);
3365
+ servidor.close();
3366
+ };
3367
+ espera = setTimeout(() => {
3368
+ cerrar();
3369
+ rechazar(new ErrorCli(opciones.mensajeDeEspera));
3370
+ }, opciones.esperaMs);
3371
+ return { puerto: port, recibido, cerrar };
3372
+ }
3373
+
3374
+ // src/nucleo/sesion.ts
3375
+ function carpetaDeConfiguracion(env = process.env, plataforma = process.platform) {
3376
+ if (plataforma === "win32") {
3377
+ if (!env.APPDATA) throw new ErrorCli("No encuentro %APPDATA%: no tengo d\xF3nde guardar la sesi\xF3n.");
3378
+ return path10.join(env.APPDATA, "redcumbre");
3379
+ }
3380
+ const base = env.XDG_CONFIG_HOME || path10.join(os.homedir(), ".config");
3381
+ return path10.join(base, "redcumbre");
3382
+ }
3383
+ function estaDentro(base, ruta) {
3384
+ const relativa = path10.relative(path10.resolve(base), path10.resolve(ruta));
3385
+ return !relativa.startsWith("..") && !path10.isAbsolute(relativa);
3386
+ }
3387
+ function exigirFueraDelProyecto(carpeta, proyecto, personal = os.homedir()) {
3388
+ if (!estaDentro(proyecto, carpeta)) return;
3389
+ if (estaDentro(proyecto, personal) && !tieneInstalacionDelCli(proyecto)) return;
3390
+ throw new ErrorCli(
3391
+ `La carpeta de configuraci\xF3n (${carpeta}) est\xE1 dentro del proyecto: ah\xED no guardo tu sesi\xF3n. Corre el comando con XDG_CONFIG_HOME fuera del proyecto.`
3392
+ );
3393
+ }
3394
+ var AlmacenArchivo = class {
3395
+ ruta;
3396
+ descripcion;
3397
+ /** `proyecto`: la carpeta donde corre el CLI; la sesión nunca puede quedar debajo de ella. */
3398
+ constructor(carpeta, proyecto) {
3399
+ this.ruta = path10.join(carpeta, "sesion.json");
3400
+ exigirFueraDelProyecto(carpeta, proyecto);
3401
+ this.descripcion = `el archivo ${this.ruta} (permisos 0600)`;
3402
+ }
3403
+ leer() {
3404
+ if (!fs10.existsSync(this.ruta)) return null;
3405
+ return JSON.parse(fs10.readFileSync(this.ruta, "utf8"));
3406
+ }
3407
+ guardar(par) {
3408
+ fs10.mkdirSync(path10.dirname(this.ruta), { recursive: true, mode: 448 });
3409
+ fs10.writeFileSync(this.ruta, JSON.stringify(par), { mode: 384 });
3410
+ fs10.chmodSync(this.ruta, 384);
3411
+ }
3412
+ borrar() {
3413
+ fs10.rmSync(this.ruta, { force: true });
3414
+ }
3415
+ };
3416
+ var AlmacenLlavero = class {
3417
+ constructor(entrada) {
3418
+ this.entrada = entrada;
3419
+ }
3420
+ descripcion = `el llavero del sistema (servicio ${SERVICIO_LLAVERO})`;
3421
+ leer() {
3422
+ const valor = this.entrada.getPassword();
3423
+ return valor ? JSON.parse(valor) : null;
3424
+ }
3425
+ guardar(par) {
3426
+ this.entrada.setPassword(JSON.stringify(par));
3427
+ }
3428
+ borrar() {
3429
+ this.entrada.deletePassword();
3430
+ }
3431
+ };
3432
+ async function elegirAlmacen(proyecto, env = process.env) {
3433
+ if (env.REDCUMBRE_SESION_EN_ARCHIVO === "1") return new AlmacenArchivo(carpetaDeConfiguracion(env), proyecto);
3434
+ try {
3435
+ const { Entry } = await import("@napi-rs/keyring");
3436
+ const entrada = new Entry(SERVICIO_LLAVERO, "sesion");
3437
+ entrada.getPassword();
3438
+ return new AlmacenLlavero(entrada);
3439
+ } catch {
3440
+ return new AlmacenArchivo(carpetaDeConfiguracion(env), proyecto);
3150
3441
  }
3151
- 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, {
3152
- codigo: "PAQUETE_INCOMPLETO"
3153
- });
3154
- }
3155
- function contenidoEmpaquetado(fuente) {
3156
- const carpeta = fuente ?? carpetaDeLaSkill();
3157
- return fs9.readFileSync(path9.join(carpeta, NOMBRE_SKILL, "SKILL.md"), "utf8");
3158
3442
  }
3159
- var LINEA_DE_VERSION = /^<!-- redcumbre-cli: (\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?) -->$/m;
3160
- var FRONTMATTER = /^---\r?\n[\s\S]*?\r?\n---\r?\n/;
3161
- var lineaDeVersion = (version) => `<!-- redcumbre-cli: ${version} -->`;
3162
- function contenidoParaInstalar(fuente, version) {
3163
- const frontmatter = fuente.match(FRONTMATTER);
3164
- if (!frontmatter) {
3165
- 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, {
3166
- codigo: "PAQUETE_INCOMPLETO"
3167
- });
3443
+ var ErrorRefreshInvalido = class extends Error {
3444
+ constructor() {
3445
+ super("La sesi\xF3n guardada ya no es v\xE1lida.");
3446
+ this.name = "ErrorRefreshInvalido";
3168
3447
  }
3169
- const sinLinea = fuente.slice(frontmatter[0].length).replace(/^<!-- redcumbre-cli: [^\n]* -->\r?\n/, "");
3170
- return `${frontmatter[0]}${lineaDeVersion(version)}
3171
- ${sinLinea}`;
3448
+ };
3449
+ var DEVICE_CODE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
3450
+ function esperarAbortable(ms, signal) {
3451
+ return setTimeoutAbortable(ms, void 0, { signal });
3172
3452
  }
3173
- function versionDeLaSkill(texto2) {
3174
- return texto2.match(LINEA_DE_VERSION)?.[1] ?? null;
3453
+ function comoPar(respuesta) {
3454
+ if (!respuesta.refresh_token) throw new ErrorCli("El servidor de identidad no devolvi\xF3 un refresh token.");
3455
+ const segundos = respuesta.expiresIn();
3456
+ if (segundos === void 0) throw new ErrorCli("El servidor de identidad no dijo cu\xE1ndo vence el token.");
3457
+ return {
3458
+ access_token: respuesta.access_token,
3459
+ refresh_token: respuesta.refresh_token,
3460
+ expira: new Date(Date.now() + segundos * 1e3).toISOString()
3461
+ };
3175
3462
  }
3176
- var CODIGOS_TRANSITORIOS_WINDOWS = /* @__PURE__ */ new Set(["EPERM", "EACCES", "EBUSY"]);
3177
- function esperarSincrono(ms) {
3178
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
3463
+ function refreshInvalido(codigo, descripcion) {
3464
+ return codigo === "invalid_grant" || codigo === "invalid_request" && /RefreshToken/i.test(descripcion ?? "");
3179
3465
  }
3180
- function esErrorTransitorioDeWindows(error) {
3181
- const codigo = error?.code;
3182
- return typeof codigo === "string" && CODIGOS_TRANSITORIOS_WINDOWS.has(codigo);
3466
+ function esRefreshInvalido(error) {
3467
+ return error instanceof oidc.ResponseBodyError && refreshInvalido(error.error, error.error_description);
3183
3468
  }
3184
- function conReintentoEnWindows(operacion, opciones = {}) {
3185
- const { plataforma = process.platform, esperar = esperarSincrono, presupuestoMs = 2500 } = opciones;
3186
- let espera = 10;
3187
- let gastado = 0;
3188
- for (; ; ) {
3189
- try {
3190
- return operacion();
3191
- } catch (error) {
3192
- if (plataforma !== "win32" || !esErrorTransitorioDeWindows(error) || gastado >= presupuestoMs) throw error;
3193
- const ms = Math.min(espera, presupuestoMs - gastado);
3194
- esperar(ms);
3195
- gastado += ms;
3196
- espera = Math.min(espera * 2, 100);
3197
- }
3198
- }
3469
+ function sinRespuestaDelIdp(error) {
3470
+ if (error instanceof ErrorCli) return false;
3471
+ if (error instanceof oidc.ResponseBodyError) return error.status >= 500;
3472
+ if (error instanceof oidc.AuthorizationResponseError || error instanceof oidc.WWWAuthenticateChallengeError) return false;
3473
+ return true;
3199
3474
  }
3200
- function escribirAtomico(ruta, contenido) {
3201
- fs9.mkdirSync(path9.dirname(ruta), { recursive: true });
3202
- const temporal = `${ruta}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
3203
- try {
3204
- fs9.writeFileSync(temporal, contenido);
3205
- conReintentoEnWindows(() => fs9.renameSync(temporal, ruta));
3206
- } catch (error) {
3207
- fs9.rmSync(temporal, { force: true });
3208
- throw error;
3475
+ function errorDeIdentidad(error) {
3476
+ if (error instanceof ErrorCli) return error;
3477
+ if (sinRespuestaDelIdp(error)) {
3478
+ const detalle = error instanceof Error ? error.cause instanceof Error ? error.cause.message : error.message : String(error);
3479
+ return identidadSinRespuesta(`No pude hablar con ${CLIENTE_OIDC.issuer} (${detalle}). Revisa tu conexi\xF3n y vuelve a intentarlo: lo que ten\xEDas guardado sigue igual.`);
3209
3480
  }
3481
+ if (error instanceof oidc.ResponseBodyError) {
3482
+ return new ErrorCli(`El servidor de identidad rechaz\xF3 la operaci\xF3n: ${error.error}${error.error_description ? ` (${error.error_description})` : ""}.`);
3483
+ }
3484
+ return new ErrorCli(`El servidor de identidad rechaz\xF3 la operaci\xF3n: ${error instanceof Error ? error.message : String(error)}.`);
3210
3485
  }
3211
- function bloqueDeAgents() {
3212
- return [
3213
- MARCA_INICIO,
3214
- "## REDCUMBRE",
3215
- "",
3216
- "Este proyecto se integra con la API de REDCUMBRE por medio del CLI `redcumbre`. Antes de tocar la integraci\xF3n lee la",
3217
- "skill `redcumbre` (`.agents/skills/redcumbre/SKILL.md`). En resumen: busca la operaci\xF3n (`redcumbre buscar`), lee su",
3218
- "contrato (`redcumbre api describir`), pru\xE9bala con `--ensayo`, consulta las fichas (`redcumbre guia`) y verifica el",
3219
- "sitio (`redcumbre prueba verificar`). No leas ni imprimas `keys/`. Pasar a producci\xF3n lo confirma una persona.",
3220
- "H\xE1blale a la persona en espa\xF1ol, salvo que ella te escriba en otro idioma.",
3221
- MARCA_FIN
3222
- ].join("\n");
3486
+ function identidadOidc(cliente = CLIENTE_OIDC) {
3487
+ let configuracion = null;
3488
+ let senalDeEspera;
3489
+ const config = () => {
3490
+ const emisor = new URL(cliente.issuer);
3491
+ const opciones = emisor.protocol === "http:" && emisor.hostname === "127.0.0.1" ? { execute: [oidc.allowInsecureRequests] } : void 0;
3492
+ configuracion ??= oidc.discovery(emisor, cliente.clientId, void 0, oidc.None(), opciones).then((c) => {
3493
+ c[oidc.customFetch] = (url, init2) => fetch(url, senalDeEspera ? { ...init2, signal: init2.signal ? AbortSignal.any([init2.signal, senalDeEspera]) : senalDeEspera } : init2);
3494
+ return c;
3495
+ }).catch((error) => {
3496
+ configuracion = null;
3497
+ throw errorDeIdentidad(error);
3498
+ });
3499
+ return configuracion;
3500
+ };
3501
+ return {
3502
+ async urlDeAutorizacion(redirectUri, pkce) {
3503
+ return oidc.buildAuthorizationUrl(await config(), {
3504
+ redirect_uri: redirectUri,
3505
+ scope: SCOPE,
3506
+ code_challenge: pkce.desafio,
3507
+ code_challenge_method: "S256",
3508
+ state: pkce.estado
3509
+ }).toString();
3510
+ },
3511
+ async canjear(retorno, pkce) {
3512
+ try {
3513
+ return comoPar(await oidc.authorizationCodeGrant(await config(), retorno, { pkceCodeVerifier: pkce.verificador, expectedState: pkce.estado }));
3514
+ } catch (error) {
3515
+ if (error instanceof ErrorCli) throw error;
3516
+ throw errorDeIdentidad(error);
3517
+ }
3518
+ },
3519
+ async renovar(refreshToken) {
3520
+ try {
3521
+ return comoPar(await oidc.refreshTokenGrant(await config(), refreshToken));
3522
+ } catch (error) {
3523
+ if (esRefreshInvalido(error)) throw new ErrorRefreshInvalido();
3524
+ if (error instanceof ErrorCli) throw error;
3525
+ throw errorDeIdentidad(error);
3526
+ }
3527
+ },
3528
+ async revocar(refreshToken) {
3529
+ try {
3530
+ await oidc.tokenRevocation(await config(), refreshToken, { token_type_hint: "refresh_token" });
3531
+ } catch (error) {
3532
+ throw errorDeIdentidad(error);
3533
+ }
3534
+ },
3535
+ async exigeIss() {
3536
+ return (await config()).serverMetadata().authorization_response_iss_parameter_supported === true;
3537
+ },
3538
+ async iniciarDispositivo() {
3539
+ try {
3540
+ const respuesta = await oidc.initiateDeviceAuthorization(await config(), { scope: SCOPE });
3541
+ if (!respuesta.verification_uri_complete) throw new ErrorCli("El servidor de identidad no devolvi\xF3 la direcci\xF3n completa para aprobar el acceso.");
3542
+ return {
3543
+ deviceCode: respuesta.device_code,
3544
+ userCode: respuesta.user_code,
3545
+ url: respuesta.verification_uri_complete,
3546
+ intervalo: respuesta.interval ?? 5,
3547
+ venceEnSegundos: respuesta.expires_in
3548
+ };
3549
+ } catch (error) {
3550
+ throw errorDeIdentidad(error);
3551
+ }
3552
+ },
3553
+ async esperarDispositivo(pendiente, esperaMs) {
3554
+ const techo = AbortSignal.timeout(esperaMs);
3555
+ const venceEn = new Date(pendiente.venceEn).getTime();
3556
+ let intervalo = pendiente.intervalo;
3557
+ senalDeEspera = techo;
3558
+ try {
3559
+ for (; ; ) {
3560
+ try {
3561
+ await esperarAbortable(intervalo * 1e3, techo);
3562
+ } catch (error) {
3563
+ if (techo.aborted) return { estado: "pendiente" };
3564
+ throw error;
3565
+ }
3566
+ if (Date.now() >= venceEn) return { estado: "vencido" };
3567
+ try {
3568
+ const respuesta = await oidc.genericGrantRequest(await config(), DEVICE_CODE_GRANT, { device_code: pendiente.deviceCode });
3569
+ return { estado: "aprobado", par: comoPar(respuesta) };
3570
+ } catch (error) {
3571
+ if (techo.aborted) return { estado: "pendiente" };
3572
+ if (error instanceof oidc.ResponseBodyError) {
3573
+ if (error.error === "authorization_pending") continue;
3574
+ if (error.error === "slow_down") {
3575
+ intervalo += 5;
3576
+ continue;
3577
+ }
3578
+ if (error.error === "expired_token") return { estado: "vencido" };
3579
+ if (error.error === "access_denied") return { estado: "rechazado" };
3580
+ }
3581
+ throw errorDeIdentidad(error);
3582
+ }
3583
+ }
3584
+ } finally {
3585
+ senalDeEspera = void 0;
3586
+ }
3587
+ }
3588
+ };
3223
3589
  }
3224
- var rutaRegistroUsuario = (d) => path9.join(d.carpetaConfiguracion, "skill.json");
3225
- var rutaEstadoDelProyecto = (proyecto) => path9.join(proyecto, ".redcumbre", "estado.json");
3226
- function leerJson(ruta) {
3227
- if (!fs9.existsSync(ruta)) return null;
3228
- let texto2;
3229
- try {
3230
- texto2 = conReintentoEnWindows(() => fs9.readFileSync(ruta, "utf8"));
3231
- } catch (error) {
3232
- if (esErrorTransitorioDeWindows(error)) throw error;
3233
- return null;
3234
- }
3235
- try {
3236
- const dato = JSON.parse(texto2);
3237
- return dato && typeof dato === "object" && !Array.isArray(dato) ? dato : null;
3238
- } catch {
3239
- return null;
3240
- }
3590
+ async function crearPkce() {
3591
+ const verificador = oidc.randomPKCECodeVerifier();
3592
+ return { verificador, desafio: await oidc.calculatePKCECodeChallenge(verificador), estado: oidc.randomState() };
3241
3593
  }
3242
- function escribirJson(ruta, dato) {
3243
- escribirAtomico(ruta, `${JSON.stringify(dato, null, 2)}
3244
- `);
3594
+ function hayQueIrSinNavegador(pedido, env = process.env, plataforma = process.platform) {
3595
+ if (pedido) return true;
3596
+ if (env.SSH_CONNECTION || env.SSH_TTY) return true;
3597
+ return plataforma === "linux" && !env.DISPLAY && !env.WAYLAND_DISPLAY;
3245
3598
  }
3246
- function leerRegistroUsuario(d) {
3247
- return leerJson(rutaRegistroUsuario(d)) ?? {};
3599
+ async function abrirNavegadorDelSistema(url) {
3600
+ const [comando2, argumentos] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", '""', url.replace(/&/g, "^&")]] : ["xdg-open", [url]];
3601
+ return new Promise((resolver) => {
3602
+ const hijo = spawn(comando2, argumentos, { stdio: "ignore", detached: true });
3603
+ hijo.once("error", () => resolver(false));
3604
+ hijo.once("spawn", () => {
3605
+ hijo.unref();
3606
+ resolver(true);
3607
+ });
3608
+ });
3248
3609
  }
3249
- function guardarRegistroUsuario(d, registro) {
3250
- escribirJson(rutaRegistroUsuario(d), registro);
3610
+ var PAGINA_LISTO = paginaListo("Listo, ya iniciaste sesi\xF3n", "Ya puedes cerrar esta ventana y volver a la terminal.");
3611
+ async function loginConLoopback(identidad, salida, opciones) {
3612
+ const pkce = await crearPkce();
3613
+ const local = await abrirRetornoLocal({
3614
+ pagina: PAGINA_LISTO,
3615
+ esperaMs: opciones.esperaMs ?? 3e5,
3616
+ mensajeDeEspera: "No lleg\xF3 la autorizaci\xF3n del navegador en 5 minutos. Vuelve a correr el comando."
3617
+ });
3618
+ const redirectUri = `http://127.0.0.1:${local.puerto}/callback`;
3619
+ try {
3620
+ const url = await identidad.urlDeAutorizacion(redirectUri, pkce);
3621
+ const abierto = await (opciones.abrirNavegador ?? abrirNavegadorDelSistema)(url);
3622
+ salida.linea(abierto ? "Abr\xED tu navegador para que inicies sesi\xF3n. Si no se abri\xF3, abre esta URL:" : "Abre esta URL en tu navegador para iniciar sesi\xF3n:");
3623
+ salida.linea(url);
3624
+ const vuelta = await local.recibido;
3625
+ const recibida = new URL(`${redirectUri}${vuelta.search}`);
3626
+ const error = recibida.searchParams.get("error");
3627
+ if (error) throw new ErrorCli(`El inicio de sesi\xF3n no se complet\xF3: ${error}.`);
3628
+ return await identidad.canjear(recibida, pkce);
3629
+ } finally {
3630
+ local.cerrar();
3631
+ }
3251
3632
  }
3252
- function leerRegistroProyecto(proyecto) {
3253
- const estado2 = leerJson(rutaEstadoDelProyecto(proyecto));
3254
- return estado2?.skill ?? {};
3633
+ var AVISO_DE_APROBACION = "Este acceso es para el CLI de REDCUMBRE. Apru\xE9balo solo si t\xFA lo pediste: no apruebes un c\xF3digo que no pediste.";
3634
+ async function iniciarSesion(identidad, salida, opciones) {
3635
+ return opciones.sinNavegador ? loginDeDispositivoEnLinea(identidad, salida) : loginConLoopback(identidad, salida, opciones);
3255
3636
  }
3256
- function guardarRegistroProyecto(proyecto, registro) {
3257
- const ruta = rutaEstadoDelProyecto(proyecto);
3258
- const estado2 = leerJson(ruta) ?? {};
3259
- escribirJson(ruta, { ...estado2, skill: registro });
3637
+ async function loginDeDispositivoEnLinea(identidad, salida) {
3638
+ const solicitud = await identidad.iniciarDispositivo();
3639
+ salida.linea("Abre esta direcci\xF3n en un navegador y aprueba el acceso:");
3640
+ salida.linea(solicitud.url);
3641
+ salida.linea(`El c\xF3digo que tiene que mostrar es ${solicitud.userCode}.`);
3642
+ salida.linea(AVISO_DE_APROBACION);
3643
+ const venceEn = new Date(Date.now() + solicitud.venceEnSegundos * 1e3).toISOString();
3644
+ const desenlace = await identidad.esperarDispositivo({ deviceCode: solicitud.deviceCode, intervalo: solicitud.intervalo, venceEn }, solicitud.venceEnSegundos * 1e3);
3645
+ if (desenlace.estado === "aprobado") return desenlace.par;
3646
+ throw errorDelDesenlace(desenlace.estado);
3260
3647
  }
3261
- function objetivos(d) {
3262
- const lista2 = [
3263
- { id: "claude-usuario", archivo: path9.join(d.home, ".claude", "skills", NOMBRE_SKILL, "SKILL.md"), legible: `~/.claude/skills/${NOMBRE_SKILL}/SKILL.md` },
3264
- { id: "agents-usuario", archivo: path9.join(d.home, ".agents", "skills", NOMBRE_SKILL, "SKILL.md"), legible: `~/.agents/skills/${NOMBRE_SKILL}/SKILL.md` }
3265
- ];
3266
- if (d.proyecto) {
3267
- lista2.push(
3268
- { id: "claude-proyecto", archivo: path9.join(d.proyecto, ".claude", "skills", NOMBRE_SKILL, "SKILL.md"), legible: `.claude/skills/${NOMBRE_SKILL}/SKILL.md` },
3269
- { id: "agents-proyecto", archivo: path9.join(d.proyecto, ".agents", "skills", NOMBRE_SKILL, "SKILL.md"), legible: `.agents/skills/${NOMBRE_SKILL}/SKILL.md` }
3270
- );
3648
+ var ESPERA_DE_COMPLETAR_MS = 9e4;
3649
+ var rutaLoginPendiente = (carpeta) => path10.join(carpeta, "login-pendiente.json");
3650
+ var volverAEmpezar = (motivo, codigo) => new ErrorCli(`${motivo} Vuelve a empezar con \xABredcumbre login\xBB.`, CODIGOS_DE_SALIDA.sesion, { codigo, comando: "redcumbre login" });
3651
+ function errorDelDesenlace(estado2) {
3652
+ if (estado2 === "pendiente") {
3653
+ return new ErrorCli("Nadie aprob\xF3 el acceso todav\xEDa. Cuando la persona lo apruebe, repite \xABredcumbre login --completar\xBB: sigue siendo el mismo c\xF3digo.", CODIGOS_DE_SALIDA.sesion, {
3654
+ codigo: "LOGIN_PENDIENTE",
3655
+ comando: "redcumbre login --completar"
3656
+ });
3271
3657
  }
3272
- return lista2;
3273
- }
3274
- var esDeUsuario = (id) => id.endsWith("-usuario");
3275
- function resumir2(rutas, quitada) {
3276
- let estado2 = "sin-cambios";
3277
- if (quitada) estado2 = "quitada";
3278
- else if (rutas.some((r) => r.accion === "editada")) estado2 = "editada";
3279
- else if (rutas.some((r) => r.accion === "instalada")) estado2 = "instalada";
3280
- else if (rutas.some((r) => r.accion === "actualizada")) estado2 = "actualizada";
3281
- return { estado: estado2, rutas };
3658
+ if (estado2 === "vencido") return volverAEmpezar("El c\xF3digo venci\xF3 antes de que lo aprobaran.", "LOGIN_PENDIENTE_VENCIDO");
3659
+ return volverAEmpezar("La persona rechaz\xF3 el acceso.", "LOGIN_RECHAZADO");
3282
3660
  }
3283
- function reconciliar(archivo, nuevo, registrado) {
3284
- const hashNuevo = sha256(nuevo);
3285
- const existe = fs9.existsSync(archivo);
3286
- if (!existe) {
3287
- if (registrado) return { accion: "borrada", hash: null };
3288
- escribirAtomico(archivo, nuevo);
3289
- return { accion: "instalada", hash: hashNuevo };
3290
- }
3291
- const hashActual = sha256(conReintentoEnWindows(() => fs9.readFileSync(archivo)));
3292
- if (registrado === void 0) {
3293
- if (hashActual === hashNuevo) return { accion: "sin-cambios", hash: hashNuevo };
3294
- return { accion: "editada", hash: null };
3661
+ function leerLoginPendiente(carpeta) {
3662
+ const ruta = rutaLoginPendiente(carpeta);
3663
+ if (!fs10.existsSync(ruta)) return null;
3664
+ try {
3665
+ const d = JSON.parse(fs10.readFileSync(ruta, "utf8"));
3666
+ const textos = ["deviceCode", "userCode", "url", "venceEn", "clientId"];
3667
+ if (!textos.every((k) => typeof d[k] === "string") || typeof d.intervalo !== "number") return null;
3668
+ if (d.clientId !== CLIENTE_OIDC.clientId || Number.isNaN(new Date(d.venceEn).getTime())) return null;
3669
+ return d;
3670
+ } catch {
3671
+ return null;
3295
3672
  }
3296
- if (hashActual !== registrado) return { accion: "editada", hash: null };
3297
- if (hashActual === hashNuevo) return { accion: "sin-cambios", hash: hashNuevo };
3298
- escribirAtomico(archivo, nuevo);
3299
- return { accion: "actualizada", hash: hashNuevo };
3300
3673
  }
3301
- var regexBloque = () => new RegExp(`${MARCA_INICIO.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[\\s\\S]*?${MARCA_FIN.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`);
3302
- function extraerBloque(texto2) {
3303
- return texto2.match(regexBloque())?.[0] ?? null;
3674
+ function guardarLoginPendiente(carpeta, pendiente) {
3675
+ const ruta = rutaLoginPendiente(carpeta);
3676
+ fs10.mkdirSync(carpeta, { recursive: true, mode: 448 });
3677
+ fs10.writeFileSync(ruta, JSON.stringify(pendiente), { mode: 384 });
3678
+ fs10.chmodSync(ruta, 384);
3304
3679
  }
3305
- function reconciliarAgents(archivo, registro) {
3306
- const bloque = bloqueDeAgents();
3307
- const hashBloque = sha256(bloque);
3308
- if (!fs9.existsSync(archivo)) {
3309
- if (registro) return { accion: "borrada", registro: null };
3310
- escribirAtomico(archivo, `${bloque}
3311
- `);
3312
- return { accion: "instalada", registro: { sha256: hashBloque, creado: true } };
3313
- }
3314
- const texto2 = conReintentoEnWindows(() => fs9.readFileSync(archivo, "utf8"));
3315
- const actual = extraerBloque(texto2);
3316
- if (actual === null) {
3317
- if (registro) return { accion: "borrada", registro: null };
3318
- const separador = texto2.length === 0 ? "" : texto2.endsWith("\n\n") ? "" : texto2.endsWith("\n") ? "\n" : "\n\n";
3319
- escribirAtomico(archivo, `${texto2}${separador}${bloque}
3320
- `);
3321
- return { accion: "instalada", registro: { sha256: hashBloque, creado: false } };
3322
- }
3323
- const hashActual = sha256(actual);
3324
- if (!registro) {
3325
- if (hashActual === hashBloque) return { accion: "sin-cambios", registro: { sha256: hashBloque, creado: false } };
3326
- return { accion: "editada", registro: null };
3327
- }
3328
- if (hashActual !== registro.sha256) return { accion: "editada", registro: null };
3329
- if (hashActual === hashBloque) return { accion: "sin-cambios", registro: { ...registro, sha256: hashBloque } };
3330
- escribirAtomico(archivo, texto2.replace(regexBloque(), () => bloque));
3331
- return { accion: "actualizada", registro: { ...registro, sha256: hashBloque } };
3680
+ function borrarLoginPendiente(carpeta) {
3681
+ const ruta = rutaLoginPendiente(carpeta);
3682
+ const habia = fs10.existsSync(ruta);
3683
+ fs10.rmSync(ruta, { force: true });
3684
+ return habia;
3332
3685
  }
3333
- function instalarSkill(opciones) {
3334
- const { destinos, bloqueAgents } = opciones;
3335
- const nuevo = contenidoParaInstalar(contenidoEmpaquetado(opciones.fuente), opciones.version);
3336
- const usuario = leerRegistroUsuario(destinos);
3337
- const proyecto = destinos.proyecto ? leerRegistroProyecto(destinos.proyecto) : null;
3338
- const rutas = [];
3339
- for (const objetivo of objetivos(destinos)) {
3340
- const deUsuario = esDeUsuario(objetivo.id);
3341
- const registro = deUsuario ? usuario : proyecto;
3342
- if (usuario.quitada || registro.quitada) continue;
3343
- const previo = registro.rutas?.[objetivo.id]?.sha256;
3344
- const { accion, hash } = reconciliar(objetivo.archivo, nuevo, previo);
3345
- rutas.push({ ruta: objetivo.legible, accion });
3346
- if (hash) {
3347
- registro.rutas = { ...registro.rutas ?? {}, [objetivo.id]: { sha256: hash } };
3348
- }
3686
+ async function iniciarLoginDeDispositivo(identidad, carpeta, proyecto, ahora = /* @__PURE__ */ new Date()) {
3687
+ exigirFueraDelProyecto(carpeta, proyecto);
3688
+ const vigente = leerLoginPendiente(carpeta);
3689
+ if (vigente && new Date(vigente.venceEn).getTime() > ahora.getTime()) return { url: vigente.url, codigo: vigente.userCode, vence: vigente.venceEn };
3690
+ borrarLoginPendiente(carpeta);
3691
+ const solicitud = await identidad.iniciarDispositivo();
3692
+ const venceEn = new Date(ahora.getTime() + solicitud.venceEnSegundos * 1e3).toISOString();
3693
+ guardarLoginPendiente(carpeta, {
3694
+ deviceCode: solicitud.deviceCode,
3695
+ userCode: solicitud.userCode,
3696
+ url: solicitud.url,
3697
+ intervalo: solicitud.intervalo,
3698
+ venceEn,
3699
+ clientId: CLIENTE_OIDC.clientId
3700
+ });
3701
+ return { url: solicitud.url, codigo: solicitud.userCode, vence: venceEn };
3702
+ }
3703
+ async function completarLogin(identidad, almacen, carpeta, proyecto, ahora = /* @__PURE__ */ new Date(), esperaMs = ESPERA_DE_COMPLETAR_MS) {
3704
+ exigirFueraDelProyecto(carpeta, proyecto);
3705
+ if (almacen.leer() !== null) return "ya-habia-sesion";
3706
+ const pendiente = leerLoginPendiente(carpeta);
3707
+ if (!pendiente) throw volverAEmpezar("No hay un inicio de sesi\xF3n pendiente.", "SIN_SESION");
3708
+ if (new Date(pendiente.venceEn).getTime() <= ahora.getTime()) {
3709
+ borrarLoginPendiente(carpeta);
3710
+ throw errorDelDesenlace("vencido");
3349
3711
  }
3350
- if (bloqueAgents && destinos.proyecto && proyecto && !usuario.quitada && !proyecto.quitada) {
3351
- const { accion, registro } = reconciliarAgents(path9.join(destinos.proyecto, "AGENTS.md"), proyecto.agents);
3352
- rutas.push({ ruta: "AGENTS.md", accion });
3353
- if (registro) proyecto.agents = registro;
3712
+ const desenlace = await identidad.esperarDispositivo({ deviceCode: pendiente.deviceCode, intervalo: pendiente.intervalo, venceEn: pendiente.venceEn }, esperaMs);
3713
+ if (desenlace.estado === "aprobado") {
3714
+ almacen.guardar(desenlace.par);
3715
+ borrarLoginPendiente(carpeta);
3716
+ return "iniciada";
3354
3717
  }
3355
- if (!usuario.quitada && rutas.some((r) => r.ruta.startsWith("~"))) guardarRegistroUsuario(destinos, usuario);
3356
- if (destinos.proyecto && proyecto && !proyecto.quitada && rutas.some((r) => !r.ruta.startsWith("~"))) guardarRegistroProyecto(destinos.proyecto, proyecto);
3357
- return resumir2(rutas, rutas.length === 0 && Boolean(usuario.quitada || proyecto?.quitada));
3358
- }
3359
- function quitarArchivo(archivo, registrado) {
3360
- if (!fs9.existsSync(archivo)) return null;
3361
- if (registrado === void 0 || sha256(conReintentoEnWindows(() => fs9.readFileSync(archivo))) !== registrado) return "editada";
3362
- fs9.rmSync(archivo);
3363
- const carpeta = path9.dirname(archivo);
3364
- if (fs9.readdirSync(carpeta).length === 0) fs9.rmdirSync(carpeta);
3365
- return "quitada";
3718
+ if (desenlace.estado !== "pendiente") borrarLoginPendiente(carpeta);
3719
+ throw errorDelDesenlace(desenlace.estado);
3366
3720
  }
3367
- function quitarSkill(opciones) {
3368
- const { destinos } = opciones;
3369
- const usuario = leerRegistroUsuario(destinos);
3370
- const proyecto = destinos.proyecto ? leerRegistroProyecto(destinos.proyecto) : null;
3371
- const rutas = [];
3372
- for (const objetivo of objetivos(destinos)) {
3373
- const registro = esDeUsuario(objetivo.id) ? usuario : proyecto;
3374
- const previo = registro.rutas?.[objetivo.id]?.sha256;
3375
- const accion = quitarArchivo(objetivo.archivo, previo);
3376
- if (accion) rutas.push({ ruta: objetivo.legible, accion });
3721
+ var Sesion = class {
3722
+ constructor(almacen, identidad, salida, login2) {
3723
+ this.almacen = almacen;
3724
+ this.identidad = identidad;
3725
+ this.salida = salida;
3726
+ this.login = login2;
3377
3727
  }
3378
- if (destinos.proyecto && proyecto) {
3379
- const archivo = path9.join(destinos.proyecto, "AGENTS.md");
3380
- if (fs9.existsSync(archivo)) {
3381
- const texto2 = conReintentoEnWindows(() => fs9.readFileSync(archivo, "utf8"));
3382
- const bloque = extraerBloque(texto2);
3383
- if (bloque !== null) {
3384
- if (!proyecto.agents || sha256(bloque) !== proyecto.agents.sha256) {
3385
- rutas.push({ ruta: "AGENTS.md", accion: "editada" });
3386
- } else {
3387
- const resto = texto2.replace(regexBloque(), "").replace(/\n{3,}/g, "\n\n");
3388
- if (proyecto.agents.creado && resto.trim() === "") fs9.rmSync(archivo);
3389
- else escribirAtomico(archivo, resto.replace(/^\n+/, "").replace(/\n*$/, "\n"));
3390
- rutas.push({ ruta: "AGENTS.md", accion: "quitada" });
3391
- }
3392
- }
3393
- }
3728
+ actual = null;
3729
+ async entrar() {
3730
+ const par = await this.login();
3731
+ this.almacen.guardar(par);
3732
+ this.salida.linea(`Sesi\xF3n iniciada. Qued\xF3 guardada en ${this.almacen.descripcion}.`);
3733
+ return par;
3394
3734
  }
3395
- guardarRegistroUsuario(destinos, { quitada: true, rutas: {} });
3396
- if (destinos.proyecto && proyecto) guardarRegistroProyecto(destinos.proyecto, { quitada: true, rutas: {}, agents: void 0 });
3397
- return { estado: "quitada", rutas };
3398
- }
3399
- function renovarSkill(opciones) {
3400
- const { destinos, version } = opciones;
3401
- const usuario = leerRegistroUsuario(destinos);
3402
- const proyecto = destinos.proyecto ? leerRegistroProyecto(destinos.proyecto) : null;
3403
- const rutas = [];
3404
- const cambiosUsuario = {};
3405
- const cambiosProyecto = {};
3406
- let nuevo = null;
3407
- for (const objetivo of objetivos(destinos)) {
3408
- const deUsuario = esDeUsuario(objetivo.id);
3409
- const registro = deUsuario ? usuario : proyecto;
3410
- if (usuario.quitada || registro.quitada) continue;
3411
- if (!fs9.existsSync(objetivo.archivo)) continue;
3412
- const actual = conReintentoEnWindows(() => fs9.readFileSync(objetivo.archivo, "utf8"));
3413
- const instalada2 = versionDeLaSkill(actual);
3414
- if (instalada2 !== null && compararVersiones(version, instalada2) < 0) {
3415
- rutas.push({ ruta: objetivo.legible, accion: "mas-nueva", instalada: instalada2 });
3416
- continue;
3417
- }
3418
- nuevo ??= contenidoParaInstalar(contenidoEmpaquetado(opciones.fuente), version);
3419
- const hashNuevo = sha256(nuevo);
3420
- const hashActual = sha256(actual);
3421
- const registrado = (registro.rutas ?? {})[objetivo.id]?.sha256;
3422
- if (hashActual === hashNuevo) {
3423
- if (registrado !== hashNuevo) (deUsuario ? cambiosUsuario : cambiosProyecto)[objetivo.id] = hashNuevo;
3424
- rutas.push({ ruta: objetivo.legible, accion: "al-dia", instalada: version });
3425
- continue;
3426
- }
3427
- if (instalada2 !== null && compararVersiones(version, instalada2) === 0 && !opciones.reemplazarEditada) {
3428
- rutas.push({ ruta: objetivo.legible, accion: "al-dia", instalada: instalada2 });
3429
- continue;
3735
+ /** El access token de esta corrida: renueva siempre la sesión guardada y guarda el par rotado. */
3736
+ async token() {
3737
+ if (this.actual) return this.actual.access_token;
3738
+ const guardada = this.almacen.leer();
3739
+ if (!guardada) {
3740
+ this.actual = await this.entrar();
3741
+ return this.actual.access_token;
3430
3742
  }
3431
- if (registrado !== void 0 && hashActual === registrado || opciones.reemplazarEditada) {
3432
- escribirAtomico(objetivo.archivo, nuevo);
3433
- (deUsuario ? cambiosUsuario : cambiosProyecto)[objetivo.id] = hashNuevo;
3434
- rutas.push({ ruta: objetivo.legible, accion: "renovada", instalada: instalada2 });
3435
- continue;
3743
+ try {
3744
+ this.actual = await this.identidad.renovar(guardada.refresh_token);
3745
+ this.almacen.guardar(this.actual);
3746
+ } catch (error) {
3747
+ if (!(error instanceof ErrorRefreshInvalido)) throw error;
3748
+ this.almacen.borrar();
3749
+ this.salida.linea("Tu sesi\xF3n anterior venci\xF3 o se cerr\xF3. Inicia sesi\xF3n de nuevo.");
3750
+ this.actual = await this.entrar();
3436
3751
  }
3437
- rutas.push({ ruta: objetivo.legible, accion: "desactualizada", instalada: instalada2 });
3438
- }
3439
- if (Object.keys(cambiosUsuario).length > 0) {
3440
- const vigente = leerRegistroUsuario(destinos);
3441
- if (!vigente.quitada) guardarRegistroUsuario(destinos, { ...vigente, rutas: { ...vigente.rutas ?? {}, ...aRutas(cambiosUsuario) } });
3752
+ return this.actual.access_token;
3442
3753
  }
3443
- if (Object.keys(cambiosProyecto).length > 0 && destinos.proyecto) {
3444
- const vigente = leerRegistroProyecto(destinos.proyecto);
3445
- if (!vigente.quitada) guardarRegistroProyecto(destinos.proyecto, { ...vigente, rutas: { ...vigente.rutas ?? {}, ...aRutas(cambiosProyecto) } });
3754
+ /**
3755
+ * Corre `operacion` con el token de la sesión. Si el API responde 401, borra la sesión, pide login y
3756
+ * la repite UNA vez con el token nuevo; nunca reintenta con el mismo (`CA-33`).
3757
+ */
3758
+ async usar(operacion) {
3759
+ try {
3760
+ return await operacion(await this.token());
3761
+ } catch (error) {
3762
+ if (!(error instanceof ErrorSesionRechazada)) throw error;
3763
+ this.almacen.borrar();
3764
+ this.actual = null;
3765
+ this.salida.linea("La plataforma rechaz\xF3 tu sesi\xF3n (por ejemplo, porque cambiaste tu contrase\xF1a). Inicia sesi\xF3n de nuevo.");
3766
+ this.actual = await this.entrar();
3767
+ try {
3768
+ return await operacion(this.actual.access_token);
3769
+ } catch (otra) {
3770
+ if (otra instanceof ErrorSesionRechazada) throw new ErrorCli("La plataforma volvi\xF3 a rechazar la sesi\xF3n reci\xE9n iniciada. Escr\xEDbenos a soporte con la hora del intento.");
3771
+ throw otra;
3772
+ }
3773
+ }
3446
3774
  }
3447
- return { version, rutas };
3448
- }
3449
- var aRutas = (cambios) => Object.fromEntries(Object.entries(cambios).map(([id, sha]) => [id, { sha256: sha }]));
3450
- var COMANDO_SKILL_RENOVAR = "redcumbre skill renovar";
3451
- var COMANDO_SKILL_RENOVAR_EDITADA = `${COMANDO_SKILL_RENOVAR} --reemplazar-editada`;
3452
- function avisoDeRenovacion(r, version) {
3453
- if (r.accion === "renovada") return `Renov\xE9 la skill de REDCUMBRE en ${r.ruta} a la de la versi\xF3n ${version}.`;
3454
- if (r.accion === "desactualizada") {
3455
- const de = r.instalada ? `es de la versi\xF3n ${r.instalada}` : "es de una versi\xF3n anterior";
3456
- return `La skill de REDCUMBRE en ${r.ruta} ${de} y tiene cambios tuyos (o no la instal\xF3 el CLI): no la toqu\xE9. Para reemplazarla por la de la versi\xF3n ${version}, corre \xAB${COMANDO_SKILL_RENOVAR_EDITADA}\xBB.`;
3775
+ /** `logout`: revoca el refresh token (RFC 7009) y borra lo local. */
3776
+ async cerrar() {
3777
+ const guardada = this.almacen.leer();
3778
+ if (!guardada) return false;
3779
+ await this.identidad.revocar(guardada.refresh_token);
3780
+ this.almacen.borrar();
3781
+ return true;
3457
3782
  }
3458
- return null;
3783
+ };
3784
+
3785
+ // src/nucleo/contexto.ts
3786
+ var sinSesionEnModoAgente = () => new ErrorCli(
3787
+ "No hay una sesi\xF3n iniciada y en modo agente no puedo esperar a que la persona inicie sesi\xF3n. Corre \xABredcumbre login\xBB, p\xEDdele a la persona que apruebe el acceso en la direcci\xF3n que responde y termina con \xABredcumbre login --completar\xBB.",
3788
+ CODIGOS_DE_SALIDA.sesion,
3789
+ { codigo: "SIN_SESION", comando: "redcumbre login" }
3790
+ );
3791
+ function crearContexto(opciones) {
3792
+ const { salida, terminal, env } = opciones;
3793
+ const destinos = servidores(env);
3794
+ const proyecto = raizDelProyecto(opciones.cwd);
3795
+ const carpeta = carpetaDeConfiguracion(env);
3796
+ const identidad = identidadOidc();
3797
+ let almacen = null;
3798
+ let sesion = null;
3799
+ const elAlmacen = () => almacen ??= elegirAlmacen(proyecto, env);
3800
+ const abrir = async (destino) => {
3801
+ const propio = env.REDCUMBRE_ABRIR;
3802
+ if (propio) return abrirCon(propio, destino);
3803
+ return abrirNavegadorDelSistema(destino);
3804
+ };
3805
+ return {
3806
+ salida,
3807
+ terminal,
3808
+ cliente: new ClienteApi(destinos.api),
3809
+ servidores: destinos,
3810
+ carpetaConfiguracion: carpeta,
3811
+ home: os2.homedir(),
3812
+ cwd: opciones.cwd,
3813
+ proyecto,
3814
+ env,
3815
+ version: opciones.version,
3816
+ identidad,
3817
+ ahora: () => /* @__PURE__ */ new Date(),
3818
+ abrir,
3819
+ almacen: elAlmacen,
3820
+ async haySesion() {
3821
+ return (await elAlmacen()).leer() !== null;
3822
+ },
3823
+ sesion() {
3824
+ sesion ??= elAlmacen().then(
3825
+ (a) => new Sesion(a, identidad, salida, async () => {
3826
+ if (!terminal) throw sinSesionEnModoAgente();
3827
+ return iniciarSesion(identidad, salida, {
3828
+ sinNavegador: hayQueIrSinNavegador(opciones.sinNavegador, env),
3829
+ abrirNavegador: abrir
3830
+ });
3831
+ })
3832
+ );
3833
+ return sesion;
3834
+ }
3835
+ };
3459
3836
  }
3460
- function renovarSkillAlCorrer(opciones) {
3461
- try {
3462
- const informe = renovarSkill({ destinos: opciones.destinos, version: opciones.version });
3463
- for (const r of informe.rutas.filter((x) => x.accion === "renovada")) opciones.avisar(avisoDeRenovacion(r, informe.version));
3464
- const desactualizadas = informe.rutas.filter((x) => x.accion === "desactualizada");
3465
- if (desactualizadas.length === 0) return;
3466
- const hoy = opciones.ahora.toISOString().slice(0, 10);
3467
- const usuario = leerRegistroUsuario(opciones.destinos);
3468
- if (usuario.avisoDesactualizadaEn === hoy) return;
3469
- for (const r of desactualizadas) opciones.avisar(avisoDeRenovacion(r, informe.version));
3470
- guardarRegistroUsuario(opciones.destinos, { ...usuario, avisoDesactualizadaEn: hoy });
3471
- } catch (error) {
3472
- opciones.depurar?.(`no pude revisar la skill instalada (${error instanceof Error ? error.message : String(error)}); el comando sigue`);
3473
- }
3837
+ async function abrirCon(programa2, destino) {
3838
+ const { spawn: spawn4 } = await import("node:child_process");
3839
+ return new Promise((resolver) => {
3840
+ const hijo = spawn4(programa2, [destino], { stdio: "ignore" });
3841
+ hijo.once("error", () => resolver(false));
3842
+ hijo.once("exit", (codigo) => resolver(codigo === 0));
3843
+ });
3474
3844
  }
3475
3845
 
3476
3846
  // src/nucleo/terminal.ts
@@ -3557,7 +3927,7 @@ function sinRespuesta() {
3557
3927
  }
3558
3928
 
3559
3929
  // src/comandos/instalar.ts
3560
- import path10 from "node:path";
3930
+ import path11 from "node:path";
3561
3931
  function estadoDeInstalacion(ctx, entorno) {
3562
3932
  if (!correPorNpx(entorno.bundle)) return { forma: "instalado" };
3563
3933
  const enElPath = versionEnElPath(entorno, { cwd: ctx.cwd, env: ctx.env });
@@ -3574,13 +3944,13 @@ function avisoDeInstalacion(version, estado2) {
3574
3944
  paraPersona: `\u2139 Ya tienes el CLI instalado (redcumbre ${estado2.enElPath}): usa \xABredcumbre \u2026\xBB en vez de npx.`
3575
3945
  };
3576
3946
  }
3577
- const comando2 = comandoInstalarPorNpx(version, true);
3947
+ const comando2 = comandoInstalarPorNpx(version);
3578
3948
  const delPath = estado2.enElPath ? ` (el \xABredcumbre\xBB del PATH es la ${estado2.enElPath})` : "";
3579
3949
  return {
3580
3950
  anexo: { version, enElPath: estado2.enElPath, instalado: false, comando: comando2, prefijo },
3581
3951
  // Corto a propósito: viaja en cada respuesta mientras el CLI corra por npx (2026-11-10, «dice muchas cosas que ensucian»).
3582
- texto: `El CLI corre por npx y no est\xE1 instalado${delPath}. Empieza tu respuesta pregunt\xE1ndole a la persona \xABEl CLI de REDCUMBRE no est\xE1 instalado en este computador. \xBFLo instalo?\xBB y, con su s\xED, c\xF3rrelo t\xFA: \xAB${comando2}\xBB; si ya dijo que no, no insistas. Mientras tanto, cada comando que corras o le muestres va con \xAB${prefijo}\xBB en lugar de \xABredcumbre\xBB.`,
3583
- paraPersona: `\u2139 Est\xE1s usando el CLI por npx. Para dejarlo instalado y usar \xABredcumbre \u2026\xBB directo: \xAB${comandoInstalarPorNpx(version, false)}\xBB.`
3952
+ texto: `El CLI corre por npx y no est\xE1 instalado${delPath}. Inst\xE1lalo ahora, sin preguntarle a la persona: c\xF3rrelo t\xFA, \xAB${comando2}\xBB, y desde ah\xED usa \xABredcumbre \u2026\xBB. Si la instalaci\xF3n falla, dile qu\xE9 pas\xF3 y, mientras tanto, cada comando que corras o le muestres va con \xAB${prefijo}\xBB en lugar de \xABredcumbre\xBB.`,
3953
+ paraPersona: `\u2139 Est\xE1s usando el CLI por npx. Para dejarlo instalado y usar \xABredcumbre \u2026\xBB directo: \xAB${comandoInstalarPorNpx(version)}\xBB.`
3584
3954
  };
3585
3955
  }
3586
3956
  function errorDeInstalacion(comando2, corrida) {
@@ -3601,7 +3971,7 @@ function instalarConfirmado(ctx, entorno) {
3601
3971
  const corrida = entorno.ejecutar(comando2.comando, comando2.args, opciones);
3602
3972
  if (corrida.status !== 0) throw errorDeInstalacion(comando2, corrida);
3603
3973
  const raiz = entorno.raizGlobal("npm");
3604
- const bundle = raiz ? path10.join(raiz, ...PAQUETE_DEL_CLI.split("/"), "dist", "redcumbre.js") : null;
3974
+ const bundle = raiz ? path11.join(raiz, ...PAQUETE_DEL_CLI.split("/"), "dist", "redcumbre.js") : null;
3605
3975
  const comprobada = bundle ? entorno.ejecutar(process.execPath, [bundle, "--version"], opciones) : null;
3606
3976
  if (!bundle || !comprobada || comprobada.status !== 0 || comprobada.stdout.trim() !== ctx.version) {
3607
3977
  throw new ErrorCli(
@@ -3625,11 +3995,14 @@ function renovarLaSkill(ctx) {
3625
3995
  const { salida } = ctx;
3626
3996
  const proyecto = tieneInstalacionDelCli(ctx.proyecto) ? ctx.proyecto : void 0;
3627
3997
  try {
3628
- const informe = renovarSkill({ destinos: { carpetaConfiguracion: ctx.carpetaConfiguracion, home: ctx.home, proyecto }, version: ctx.version });
3998
+ const informe = renovarSkill({ destinos: { carpetaConfiguracion: ctx.carpetaConfiguracion, home: ctx.home, proyecto }, version: ctx.version, ahora: ctx.ahora() });
3629
3999
  for (const r of informe.rutas) {
3630
4000
  const aviso = avisoDeRenovacion(r, informe.version);
3631
- if (r.accion === "renovada") salida.linea(`\u2713 ${aviso}`);
3632
- else if (aviso) salida.aviso(aviso);
4001
+ if (r.accion === "renovada" || r.accion === "instalada") salida.linea(`\u2713 ${aviso}`);
4002
+ else if (r.accion === "reemplazada-editada") {
4003
+ salida.linea(`\u2713 Reemplac\xE9 ${nombreDeLoInstalado(r.ruta)} en ${r.ruta} ${deLaVersion(r.ruta, "por", informe.version)}.`);
4004
+ salida.aviso(`${r.ruta.includes("/commands/") ? "Tu versi\xF3n editada del comando" : "Tu versi\xF3n editada de la skill"} qued\xF3 en ${r.copia}.`);
4005
+ } else if (aviso) salida.aviso(aviso);
3633
4006
  }
3634
4007
  return { version: informe.version, rutas: informe.rutas };
3635
4008
  } catch (error) {
@@ -3637,7 +4010,7 @@ function renovarLaSkill(ctx) {
3637
4010
  return null;
3638
4011
  }
3639
4012
  }
3640
- async function instalar(ctx, opciones, entorno = entornoDeActualizacion(ctx)) {
4013
+ async function instalar(ctx, _opciones, entorno = entornoDeActualizacion(ctx)) {
3641
4014
  const { salida } = ctx;
3642
4015
  const instalacion = detectarInstalacion(entorno.bundle, entorno.raizGlobal);
3643
4016
  if (instalacion.forma === "npm-global" || instalacion.forma === "pnpm-global") {
@@ -3658,19 +4031,6 @@ async function instalar(ctx, opciones, entorno = entornoDeActualizacion(ctx)) {
3658
4031
  salida.resultado({ ok: true, instalado: false, motivo: "ya-instalado", version: enElPath, forma: "npx", skill: renovarLaSkill(ctx) });
3659
4032
  return;
3660
4033
  }
3661
- const comando2 = comandoDeActualizacion("npm-global", ctx.version, ctx.env.REDCUMBRE_NPM_REGISTRY || void 0);
3662
- const confirmado = comandoInstalarPorNpx(ctx.version, true);
3663
- const reemplaza = enElPath ? ` (reemplaza el redcumbre ${enElPath} del PATH)` : "";
3664
- if (ctx.terminal) {
3665
- if (!await ctx.terminal.confirmar(`\xBFInstalo el CLI ${ctx.version} en este computador con \xAB${legible(comando2)}\xBB${reemplaza}?`)) {
3666
- throw faltaConfirmacion(`No confirmaste: no instal\xE9 nada. Cuando quieras: \xAB${comandoInstalarPorNpx(ctx.version, false)}\xBB.`, confirmado);
3667
- }
3668
- } else if (!opciones.confirmar) {
3669
- throw faltaConfirmacion(
3670
- `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.`,
3671
- confirmado
3672
- );
3673
- }
3674
4034
  const instalado = instalarConfirmado(ctx, entorno);
3675
4035
  salida.resultado({ ...instalado, skill: renovarLaSkill(ctx) });
3676
4036
  }
@@ -3683,7 +4043,7 @@ async function correr(globales, accion, opciones = {}) {
3683
4043
  const salida = crearSalida(agente);
3684
4044
  const terminal = agente ? null : crearTerminal(process.stdin, process.stdout);
3685
4045
  try {
3686
- const ctx = crearContexto({ salida, terminal, sinNavegador: Boolean(globales.sinNavegador), cwd: process.cwd(), env: process.env, version: "0.6.6" });
4046
+ const ctx = crearContexto({ salida, terminal, sinNavegador: Boolean(globales.sinNavegador), cwd: process.cwd(), env: process.env, version: "0.6.8" });
3687
4047
  await exigirVersionMinima({
3688
4048
  version: ctx.version,
3689
4049
  env: process.env,
@@ -3694,21 +4054,15 @@ async function correr(globales, accion, opciones = {}) {
3694
4054
  const depurar = process.env.REDCUMBRE_DEBUG ? (mensaje) => process.stderr.write(`debug: ${mensaje}
3695
4055
  `) : void 0;
3696
4056
  if (!opciones.revisaPorSuCuenta) {
3697
- const consulta = { carpeta: ctx.carpetaConfiguracion, version: ctx.version, ahora: ctx.ahora(), registro: process.env.REDCUMBRE_NPM_REGISTRY };
3698
4057
  const entornoDelCli = entornoDeActualizacion(ctx);
3699
4058
  const porNpx = correPorNpx(entornoDelCli.bundle);
3700
- const comandoActualizar = porNpx ? `${prefijoPorNpx(ctx.version)} actualizar` : void 0;
3701
- if (!agente) {
3702
- await avisarSiHayVersionNueva({ ...consulta, humano: process.stderr, comando: comandoActualizar });
3703
- } else {
3704
- const actualizacion = await actualizacionDisponible(consulta);
3705
- if (actualizacion) {
3706
- if (comandoActualizar) actualizacion.comando = `${comandoActualizar} --confirmar`;
3707
- salida.anexar("actualizacion", actualizacion);
3708
- salida.avisoAlAgente(avisoDeActualizacion(actualizacion));
3709
- }
4059
+ let actualizado = false;
4060
+ try {
4061
+ actualizado = await autoactualizarElCli(ctx, { entorno: entornoDelCli, salida, agente, depurar, consultaSinMarca: opciones.consultaSinMarca });
4062
+ } catch (error) {
4063
+ depurar?.(`la auto-actualizaci\xF3n fall\xF3 antes de empezar: ${error instanceof Error ? error.message : String(error)}`);
3710
4064
  }
3711
- if (porNpx && !opciones.instalaPorSuCuenta) {
4065
+ if (porNpx && !actualizado && !opciones.instalaPorSuCuenta) {
3712
4066
  const aviso = avisoDeInstalacion(ctx.version, estadoDeInstalacion(ctx, entornoDelCli));
3713
4067
  if (aviso && agente) {
3714
4068
  salida.anexar("instalacion", aviso.anexo);
@@ -3830,12 +4184,12 @@ function entradasDe(ctx, fila, argumentos, opciones) {
3830
4184
  return { query, cuerpo, archivo };
3831
4185
  }
3832
4186
  function logoDe(ctx, ruta) {
3833
- const completa = path11.resolve(ctx.cwd, ruta);
3834
- const tipo = TIPOS_DE_LOGO[path11.extname(completa).toLowerCase()];
3835
- 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.`);
3836
- if (!fs10.existsSync(completa) || !fs10.statSync(completa).isFile()) throw errorDeUso(`No encuentro el archivo del logo: ${completa}`);
3837
- 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.`);
3838
- return { ruta: completa, tipo, bytes: fs10.readFileSync(completa) };
4187
+ const completa = path12.resolve(ctx.cwd, ruta);
4188
+ const tipo = TIPOS_DE_LOGO[path12.extname(completa).toLowerCase()];
4189
+ if (!tipo) throw errorDeUso(`El logo tiene que ser .jpg, .jpeg, .png, .gif o .webp; \xAB${path12.basename(completa)}\xBB no lo es. No llam\xE9 al API.`);
4190
+ if (!fs11.existsSync(completa) || !fs11.statSync(completa).isFile()) throw errorDeUso(`No encuentro el archivo del logo: ${completa}`);
4191
+ if (fs11.statSync(completa).size > MAXIMO_DEL_LOGO) throw errorDeUso(`El logo pesa m\xE1s de 2 MB: ${path12.basename(completa)}. Reduce la imagen y vuelve a intentarlo. No llam\xE9 al API.`);
4192
+ return { ruta: completa, tipo, bytes: fs11.readFileSync(completa) };
3839
4193
  }
3840
4194
  var citar = (valor) => /^[\w.@:/=,+-]+$/.test(valor) ? valor : `'${valor.replace(/'/g, `'\\''`)}'`;
3841
4195
  function comandoDe2(fila, argumentos, opciones) {
@@ -3867,9 +4221,9 @@ async function correrOperacionDeEmisor(ctx, fila, argumentos, opciones) {
3867
4221
  ctx.salida.linea(`Ensayo: no llam\xE9 al API. Con la llave \xAB${llave.archivo.name}\xBB (${nombreDelModo(llave.entorno)}) de ${slug} har\xEDa:`);
3868
4222
  ctx.salida.linea(` ${op.metodo} ${ctx.cliente.url(ruta, query)}`);
3869
4223
  if (cuerpo !== void 0) ctx.salida.linea(` ${JSON.stringify(cuerpo)}`);
3870
- if (archivo) ctx.salida.linea(` multipart/form-data: logo=${path11.basename(archivo.ruta)} (${archivo.tipo}, ${archivo.bytes.length} bytes)`);
4224
+ if (archivo) ctx.salida.linea(` multipart/form-data: logo=${path12.basename(archivo.ruta)} (${archivo.tipo}, ${archivo.bytes.length} bytes)`);
3871
4225
  ctx.salida.resultado({
3872
- solicitud: { metodo: op.metodo, ruta, query, cuerpo: cuerpo ?? null, ...archivo ? { formulario: { logo: path11.basename(archivo.ruta) } } : {} },
4226
+ solicitud: { metodo: op.metodo, ruta, query, cuerpo: cuerpo ?? null, ...archivo ? { formulario: { logo: path12.basename(archivo.ruta) } } : {} },
3873
4227
  empresa: slug,
3874
4228
  llave: llave.archivo.name,
3875
4229
  modo: llave.entorno,
@@ -3900,7 +4254,7 @@ async function correrOperacionDeEmisor(ctx, fila, argumentos, opciones) {
3900
4254
  let formulario;
3901
4255
  if (archivo) {
3902
4256
  formulario = new FormData();
3903
- formulario.append("logo", new Blob([new Uint8Array(archivo.bytes)], { type: archivo.tipo }), path11.basename(archivo.ruta));
4257
+ formulario.append("logo", new Blob([new Uint8Array(archivo.bytes)], { type: archivo.tipo }), path12.basename(archivo.ruta));
3904
4258
  }
3905
4259
  respuesta = (await pedir2(ctx, llave, op, ruta, query, cuerpo, formulario)).json;
3906
4260
  }
@@ -4270,8 +4624,8 @@ function declararTokenizar(programa2) {
4270
4624
 
4271
4625
  // src/nucleo/guias.ts
4272
4626
  import { randomBytes as randomBytes2 } from "node:crypto";
4273
- import fs11 from "node:fs";
4274
- import path12 from "node:path";
4627
+ import fs12 from "node:fs";
4628
+ import path13 from "node:path";
4275
4629
  var CODIGO_GUIA_NO_DISPONIBLE = "GUIA_NO_DISPONIBLE";
4276
4630
  var TEMA_VALIDO = /^[a-z0-9][a-z0-9-]*$/;
4277
4631
  var COPIA_DEL_INDICE = "_indice";
@@ -4282,15 +4636,15 @@ var TIPOS_DE_FICHA = ["text/markdown", "text/plain", "application/octet-stream"]
4282
4636
  var PARECE_HTML = /^\s*<(?:!doctype\s+html|html[\s>])/i;
4283
4637
  var TIPOS_DEL_INDICE = ["application/json"];
4284
4638
  var TIPOS_DE_VERSION = ["text/plain"];
4285
- var carpetaDeGuias = (carpeta) => path12.join(carpeta, "guias");
4286
- var rutaTexto = (carpeta, nombre) => path12.join(carpetaDeGuias(carpeta), `${nombre}${nombre === COPIA_DEL_INDICE ? ".txt" : ".md"}`);
4287
- var rutaMarca = (carpeta, nombre) => path12.join(carpetaDeGuias(carpeta), `${nombre}.json`);
4639
+ var carpetaDeGuias = (carpeta) => path13.join(carpeta, "guias");
4640
+ var rutaTexto = (carpeta, nombre) => path13.join(carpetaDeGuias(carpeta), `${nombre}${nombre === COPIA_DEL_INDICE ? ".txt" : ".md"}`);
4641
+ var rutaMarca = (carpeta, nombre) => path13.join(carpetaDeGuias(carpeta), `${nombre}.json`);
4288
4642
  function leerCopia2(carpeta, nombre, origen2) {
4289
4643
  try {
4290
- const marca = JSON.parse(fs11.readFileSync(rutaMarca(carpeta, nombre), "utf8"));
4644
+ const marca = JSON.parse(fs12.readFileSync(rutaMarca(carpeta, nombre), "utf8"));
4291
4645
  if (!marca || marca.origen !== origen2 || typeof marca.version !== "string" || !marca.version) return null;
4292
4646
  const archivo = rutaTexto(carpeta, nombre);
4293
- return { texto: fs11.readFileSync(archivo, "utf8"), version: marca.version, fecha: fs11.statSync(archivo).mtime };
4647
+ return { texto: fs12.readFileSync(archivo, "utf8"), version: marca.version, fecha: fs12.statSync(archivo).mtime };
4294
4648
  } catch {
4295
4649
  return null;
4296
4650
  }
@@ -4298,22 +4652,22 @@ function leerCopia2(carpeta, nombre, origen2) {
4298
4652
  function escribirAtomico2(destino, contenido) {
4299
4653
  const temporal = `${destino}.${process.pid}.${randomBytes2(4).toString("hex")}.tmp`;
4300
4654
  try {
4301
- fs11.writeFileSync(temporal, contenido);
4302
- fs11.renameSync(temporal, destino);
4655
+ fs12.writeFileSync(temporal, contenido);
4656
+ fs12.renameSync(temporal, destino);
4303
4657
  } catch (error) {
4304
- fs11.rmSync(temporal, { force: true });
4658
+ fs12.rmSync(temporal, { force: true });
4305
4659
  throw error;
4306
4660
  }
4307
4661
  }
4308
4662
  function guardarCopia2(carpeta, nombre, origen2, version, texto2) {
4309
- fs11.mkdirSync(carpetaDeGuias(carpeta), { recursive: true, mode: 448 });
4663
+ fs12.mkdirSync(carpetaDeGuias(carpeta), { recursive: true, mode: 448 });
4310
4664
  escribirAtomico2(rutaTexto(carpeta, nombre), texto2);
4311
4665
  escribirAtomico2(rutaMarca(carpeta, nombre), `${JSON.stringify({ origen: origen2, version })}
4312
4666
  `);
4313
4667
  }
4314
4668
  function borrarCopia(carpeta, nombre) {
4315
- fs11.rmSync(rutaMarca(carpeta, nombre), { force: true });
4316
- fs11.rmSync(rutaTexto(carpeta, nombre), { force: true });
4669
+ fs12.rmSync(rutaMarca(carpeta, nombre), { force: true });
4670
+ fs12.rmSync(rutaTexto(carpeta, nombre), { force: true });
4317
4671
  }
4318
4672
  var fechaLegible2 = (fecha) => fecha.toLocaleString("es-CL", { dateStyle: "medium", timeStyle: "short" });
4319
4673
  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, {
@@ -4510,86 +4864,8 @@ async function guia(ctx, tema) {
4510
4864
  ctx.salida.linea(sanearParaTerminal(ficha.texto).replace(/\n+$/, ""));
4511
4865
  }
4512
4866
 
4513
- // src/nucleo/bienvenida.ts
4514
- var TITULO_DE_BIENVENIDA = "BIENVENIDO A REDCUMBRE";
4515
- var ETIQUETA_DEL_AVISO = "AVISO IMPORTANTE";
4516
- var AVISO_DE_COBROS = "En modo de prueba nada se cobra, en modo de producci\xF3n las acciones se cobran de acuerdo a tu plan. Siempre puedes consultar con redcumbre:tarifas los precios de todas tus operaciones o en el panel web en la secci\xF3n Mi suscripci\xF3n.";
4517
- var ANCHO_PLANO = 80;
4518
- var ANCHO_DEL_RECUADRO = 76;
4519
- var RELLENO = 2;
4520
- var LETRAS = {
4521
- R: [" ____ ", "| _ \\ ", "| |_) |", "| _ < ", "|_| \\_\\"],
4522
- E: [" _____ ", "| ____|", "| _| ", "| |___ ", "|_____|"],
4523
- D: [" ____ ", "| _ \\ ", "| | | |", "| |_| |", "|____/ "],
4524
- C: [" ____ ", " / ___|", "| | ", "| |___ ", " \\____|"],
4525
- U: [" _ _ ", "| | | |", "| | | |", "| |_| |", " \\___/ "],
4526
- M: [" __ __ ", "| \\/ |", "| |\\/| |", "| | | |", "|_| |_|"],
4527
- B: [" ____ ", "| __ ) ", "| _ \\ ", "| |_) |", "|____/ "]
4528
- };
4529
- var LOGO = [0, 1, 2, 3, 4].map(
4530
- (fila) => [..."REDCUMBRE"].map((letra) => LETRAS[letra][fila]).join(" ").replace(/\s+$/, "")
4531
- );
4532
- var ANSI = {
4533
- reset: "\x1B[0m",
4534
- negrita: "\x1B[1m",
4535
- rojoBrillante: "\x1B[91m",
4536
- amarilloBrillante: "\x1B[93m",
4537
- etiqueta: "\x1B[1;97;41m"
4538
- };
4539
- function envolver(texto2, ancho) {
4540
- const lineas = [];
4541
- let actual = "";
4542
- for (const palabra of texto2.split(/\s+/).filter(Boolean)) {
4543
- if (actual && actual.length + 1 + palabra.length > ancho) {
4544
- lineas.push(actual);
4545
- actual = palabra;
4546
- } else {
4547
- actual = actual ? `${actual} ${palabra}` : palabra;
4548
- }
4549
- }
4550
- if (actual) lineas.push(actual);
4551
- return lineas;
4552
- }
4553
- var tituloConVersion = (version) => `${TITULO_DE_BIENVENIDA} \xB7 CLI ${version}`;
4554
- var AVISO_EN_TEXTO = `${ETIQUETA_DEL_AVISO}: ${AVISO_DE_COBROS}`;
4555
- function textoPlanoDeBienvenida(version) {
4556
- return [...envolver(tituloConVersion(version), ANCHO_PLANO), ...envolver(AVISO_EN_TEXTO, ANCHO_PLANO)].join("\n");
4557
- }
4558
- var ANCHO_INTERIOR = ANCHO_DEL_RECUADRO - 2 - 2 * RELLENO;
4559
- var ANCHO_DE_LA_PANTALLA = Math.max(ANCHO_DEL_RECUADRO, ...LOGO.map((l) => l.length));
4560
- function pantallaDeBienvenida(version, { color }) {
4561
- const pintar = (codigo, texto2) => color ? `${codigo}${texto2}${ANSI.reset}` : texto2;
4562
- const relleno = " ".repeat(RELLENO);
4563
- const borde = (texto2) => pintar(ANSI.amarilloBrillante, texto2);
4564
- const interior = (texto2, visible = texto2) => `${borde("\u2551")}${relleno}${texto2}${" ".repeat(ANCHO_INTERIOR - visible.length)}${relleno}${borde("\u2551")}`;
4565
- const lineas = [];
4566
- for (const fila of LOGO) lineas.push(pintar(ANSI.rojoBrillante, fila));
4567
- lineas.push("");
4568
- lineas.push(pintar(ANSI.negrita, tituloConVersion(version)));
4569
- lineas.push("");
4570
- lineas.push(borde(`\u2554${"\u2550".repeat(ANCHO_DEL_RECUADRO - 2)}\u2557`));
4571
- lineas.push(interior(pintar(ANSI.etiqueta, ` ${ETIQUETA_DEL_AVISO} `), ` ${ETIQUETA_DEL_AVISO} `));
4572
- for (const linea of envolver(AVISO_DE_COBROS, ANCHO_INTERIOR)) lineas.push(interior(linea));
4573
- lineas.push(borde(`\u255A${"\u2550".repeat(ANCHO_DEL_RECUADRO - 2)}\u255D`));
4574
- return lineas.join("\n");
4575
- }
4576
- function mostrarBienvenida(salida, version, entorno) {
4577
- const plano = textoPlanoDeBienvenida(version);
4578
- if (salida.json) {
4579
- salida.anexar("bienvenida", { titulo: TITULO_DE_BIENVENIDA, aviso: AVISO_EN_TEXTO, version, texto: plano });
4580
- salida.linea();
4581
- salida.linea(plano);
4582
- return;
4583
- }
4584
- const sinColor = (entorno.env.NO_COLOR ?? "") !== "" || entorno.env.TERM === "dumb";
4585
- const angosta = entorno.columnas !== void 0 && entorno.columnas < ANCHO_DE_LA_PANTALLA;
4586
- salida.linea();
4587
- salida.linea(sinColor || angosta ? plano : pantallaDeBienvenida(version, { color: true }));
4588
- salida.linea();
4589
- }
4590
-
4591
4867
  // src/comandos/init.ts
4592
- import path14 from "node:path";
4868
+ import path15 from "node:path";
4593
4869
 
4594
4870
  // src/comandos/instalar-llave.ts
4595
4871
  function negativaSinRol(ctx, proyecto, empresa2, entorno) {
@@ -4683,9 +4959,9 @@ function mostrarWhoami(salida, tenant, modo, encabezado) {
4683
4959
  }
4684
4960
 
4685
4961
  // src/comandos/mcp.ts
4686
- import fs12 from "node:fs";
4962
+ import fs13 from "node:fs";
4687
4963
  import os3 from "node:os";
4688
- import path13 from "node:path";
4964
+ import path14 from "node:path";
4689
4965
  var URL_MCP_REDCUMBRE = "https://mcp.redcumbre.cl";
4690
4966
  var NOMBRE_SERVIDOR_MCP = "redcumbre";
4691
4967
  var COMANDO_MCP_AGREGAR = "redcumbre mcp agregar";
@@ -4705,12 +4981,12 @@ var ASISTENTE_REGISTRY = {
4705
4981
  var ENTRADA = { type: "http", url: URL_MCP_REDCUMBRE };
4706
4982
  var esObjeto6 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
4707
4983
  var mismaEntrada = (v) => esObjeto6(v) && Object.keys(v).length === 2 && v.type === ENTRADA.type && v.url === ENTRADA.url;
4708
- var rutaConfigMcp = (asistente, home = os3.homedir()) => path13.join(home, ...ASISTENTE_REGISTRY[asistente].archivo);
4984
+ var rutaConfigMcp = (asistente, home = os3.homedir()) => path14.join(home, ...ASISTENTE_REGISTRY[asistente].archivo);
4709
4985
  function leerConfig(ruta) {
4710
- if (!fs12.existsSync(ruta)) return null;
4986
+ if (!fs13.existsSync(ruta)) return null;
4711
4987
  let actual;
4712
4988
  try {
4713
- actual = JSON.parse(fs12.readFileSync(ruta, "utf8"));
4989
+ actual = JSON.parse(fs13.readFileSync(ruta, "utf8"));
4714
4990
  } catch (error) {
4715
4991
  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, {
4716
4992
  codigo: "CONFIG_MCP_INVALIDA"
@@ -4744,8 +5020,8 @@ function planQuitar(asistente, home) {
4744
5020
  function escribir(planes) {
4745
5021
  for (const p of planes) {
4746
5022
  if (p.contenido === void 0) continue;
4747
- fs12.mkdirSync(path13.dirname(p.ruta), { recursive: true });
4748
- fs12.writeFileSync(p.ruta, p.contenido);
5023
+ fs13.mkdirSync(path14.dirname(p.ruta), { recursive: true });
5024
+ fs13.writeFileSync(p.ruta, p.contenido);
4749
5025
  }
4750
5026
  }
4751
5027
  function asistentesPedidos(asistente) {
@@ -4870,7 +5146,7 @@ async function init(ctx, opciones, entorno = entornoDeActualizacion(ctx)) {
4870
5146
  if (opciones.entorno !== void 0) {
4871
5147
  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.`);
4872
5148
  }
4873
- let proyecto = path14.resolve(ctx.cwd, opciones.carpeta ?? ".");
5149
+ const proyecto = path15.resolve(ctx.cwd, opciones.carpeta ?? ".");
4874
5150
  instalarAlEmpezar(ctx, entorno);
4875
5151
  const sesion = await ctx.sesion();
4876
5152
  const perfil = await sesion.usar((token) => ctx.cliente.perfil(token));
@@ -4883,20 +5159,14 @@ async function init(ctx, opciones, entorno = entornoDeActualizacion(ctx)) {
4883
5159
  );
4884
5160
  }
4885
5161
  salida.linea("Tu cuenta todav\xEDa no pertenece a ninguna empresa en REDCUMBRE.");
4886
- if (await terminal.confirmar("\xBFQuieres enviar una solicitud de cuenta?")) {
4887
- const enviada = await solicitarCuenta(ctx, { nombre: perfil.persona.nombre, email: perfil.persona.correo });
4888
- salida.resultado({ ok: true, solicitud: enviada ? "enviada" : "no-enviada" });
4889
- } else {
4890
- salida.linea(`Cuando quieras pedirla: ${COMANDO_SOLICITAR_CUENTA}`);
4891
- salida.resultado({ ok: true, solicitud: "no-enviada" });
4892
- }
5162
+ salida.linea("Te voy a pedir unos datos para solicitar la cuenta.");
5163
+ const enviada = await solicitarCuenta(ctx, { nombre: perfil.persona.nombre, email: perfil.persona.correo });
5164
+ if (!enviada) salida.linea(`Cuando quieras pedirla: ${COMANDO_SOLICITAR_CUENTA}`);
5165
+ salida.resultado({ ok: true, solicitud: enviada ? "enviada" : "no-enviada" });
4893
5166
  return;
4894
5167
  }
4895
5168
  const empresa2 = await elegirEmpresa(ctx, perfil.empresas, opciones.empresa);
4896
- if (terminal && opciones.carpeta === void 0 && !tieneInstalacionDelCli(proyecto)) {
4897
- const respuesta = await terminal.preguntar("\xBFD\xF3nde instalo la llave? [.]: ");
4898
- proyecto = path14.resolve(ctx.cwd, respuesta || ".");
4899
- }
5169
+ if (terminal) salida.linea(`Instalo la llave en ${proyecto}.`);
4900
5170
  const anterior = empresaAnterior(proyecto, empresa2.slug);
4901
5171
  const llave = await instalarLlave(ctx, proyecto, empresa2, "prueba");
4902
5172
  if (anterior) {
@@ -4906,7 +5176,7 @@ async function init(ctx, opciones, entorno = entornoDeActualizacion(ctx)) {
4906
5176
  }
4907
5177
  let skill;
4908
5178
  try {
4909
- skill = instalarSkill({ destinos: { carpetaConfiguracion: ctx.carpetaConfiguracion, home: ctx.home, proyecto }, bloqueAgents: true, version: ctx.version });
5179
+ skill = instalarSkill({ destinos: { carpetaConfiguracion: ctx.carpetaConfiguracion, home: ctx.home, proyecto }, bloqueAgents: true, version: ctx.version, ahora: ctx.ahora() });
4910
5180
  } catch (error) {
4911
5181
  if (error instanceof ErrorCli) throw error;
4912
5182
  throw new ErrorCli(`La llave de prueba qued\xF3 instalada, pero no pude instalar la skill: ${error.message}`, CODIGOS_DE_SALIDA.error, {
@@ -4915,7 +5185,15 @@ async function init(ctx, opciones, entorno = entornoDeActualizacion(ctx)) {
4915
5185
  });
4916
5186
  }
4917
5187
  for (const r of skill.rutas) {
4918
- if (r.accion === "editada") salida.aviso(`${r.ruta} tiene cambios tuyos: no lo toqu\xE9. Para volver a la versi\xF3n del CLI b\xF3rralo y corre init otra vez.`);
5188
+ if (r.accion === "reemplazada-editada") {
5189
+ salida.linea(`\u2713 Reemplac\xE9 ${nombreDeLoInstalado(r.ruta)} en ${r.ruta} ${deLaVersion(r.ruta, "por", ctx.version)}.`);
5190
+ salida.aviso(`Tu versi\xF3n editada ${r.ruta.includes("/commands/") ? "del comando" : "de la skill"} qued\xF3 en ${r.copia}.`);
5191
+ }
5192
+ if (r.accion === "editada") {
5193
+ salida.aviso(
5194
+ r.error ? `${r.ruta} tiene cambios tuyos y no pude guardar su copia (${r.error}): no lo toqu\xE9.` : `${r.ruta} tiene cambios tuyos: no lo toqu\xE9. Para volver a la versi\xF3n del CLI b\xF3rralo y corre init otra vez.`
5195
+ );
5196
+ }
4919
5197
  }
4920
5198
  const instalada2 = leerLlave(proyecto, "prueba");
4921
5199
  if (!instalada2) {
@@ -4964,7 +5242,7 @@ function instalarAlEmpezar(ctx, entorno) {
4964
5242
  if (!(error instanceof ErrorCli)) throw error;
4965
5243
  salida.aviso(`${error.message} Sigo por npx: cada comando va con \xAB${prefijo}\xBB en lugar de \xABredcumbre\xBB.`);
4966
5244
  salida.anexar("cli", { instalado: false, codigo: error.codigo });
4967
- salida.anexar("instalacion", { version: ctx.version, enElPath: estado2.enElPath, instalado: false, comando: comandoInstalarPorNpx(ctx.version, true), prefijo });
5245
+ salida.anexar("instalacion", { version: ctx.version, enElPath: estado2.enElPath, instalado: false, comando: comandoInstalarPorNpx(ctx.version), prefijo });
4968
5246
  }
4969
5247
  }
4970
5248
  function informarInstalado(ctx, enElPath) {
@@ -5089,7 +5367,7 @@ async function llamadas(ctx, opciones) {
5089
5367
  }
5090
5368
 
5091
5369
  // src/comandos/credenciales-reseller.ts
5092
- import path15 from "node:path";
5370
+ import path16 from "node:path";
5093
5371
  function declararOpcionesCrearCredencial(comando2) {
5094
5372
  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");
5095
5373
  }
@@ -5119,7 +5397,7 @@ async function crearCredencial(ctx, opciones) {
5119
5397
  const sesion = await ctx.sesion();
5120
5398
  const creada = await sesion.usar((token) => ctx.cliente.crearCredencialReseller(token, slug, { nombre: opciones.nombre, tipo, entorno, venceEn }));
5121
5399
  const relativa = `keys/reseller-${slug}-${tipo}-${entorno}.json`;
5122
- const archivo = path15.join(ctx.proyecto, relativa);
5400
+ const archivo = path16.join(ctx.proyecto, relativa);
5123
5401
  asegurarExclusiones(ctx.proyecto, estaVersionado(ctx.proyecto, ".env"));
5124
5402
  escribirArchivoLlave(archivo, {
5125
5403
  tenantSlug: slug,
@@ -5143,7 +5421,7 @@ async function revocarCredencial(ctx, id, opciones) {
5143
5421
  }
5144
5422
 
5145
5423
  // src/comandos/llave-validafirma.ts
5146
- import path16 from "node:path";
5424
+ import path17 from "node:path";
5147
5425
  function declararOpcionesLlaveValidaFirma(comando2) {
5148
5426
  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)");
5149
5427
  }
@@ -5159,8 +5437,8 @@ async function llaveValidaFirma(ctx, opciones) {
5159
5437
  if (!esEntornoLlave(modoPedido)) throw errorDeUso(mensajeEntornoLlaveInvalido(modoPedido));
5160
5438
  const modo = modoPedido;
5161
5439
  const relativa = rutaRelativaLlaveValidaFirma(empresa2, alcance, modo);
5162
- const archivo = path16.resolve(ctx.proyecto, relativa);
5163
- 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).`);
5440
+ const archivo = path17.resolve(ctx.proyecto, relativa);
5441
+ if (path17.join(ctx.proyecto, "keys", path17.basename(relativa)) !== archivo || path17.basename(relativa) !== relativa.slice("keys/".length)) throw errorDeUso(`\xAB${empresa2}\xBB no es el identificador de una empresa (tenantSlug).`);
5164
5442
  const comando2 = `redcumbre llaves validafirma --empresa ${empresa2} --alcance ${alcance} --modo ${modo}`;
5165
5443
  const comandoConfirmando = `${comando2} --confirmar ${empresa2}`;
5166
5444
  const modoEsperado = ENTORNO_LLAVE_REGISTRY[modo].isSandbox;
@@ -5945,7 +6223,7 @@ async function pasarAProduccion(ctx, opciones) {
5945
6223
  } else if (!pedidos && terminal && revision.servicios.some((s) => s.deducido)) {
5946
6224
  salida.linea("Por las llamadas de la llave de prueba, el proyecto usa:");
5947
6225
  for (const s of revision.servicios) salida.linea(` \xB7 ${s.nombre} (${s.codigo})`);
5948
- if (!await terminal.confirmar("\xBFSon esos los servicios del proyecto?")) revision = await revisar2(await elegirServicios(terminal, "\xBFQu\xE9 servicios usa este proyecto?"));
6226
+ salida.linea(`Si no son esos, vuelve a correrlo con --servicios <${CODIGOS_SERVICIO_DE_PASO_A_PRODUCCION.join(",")}>.`);
5949
6227
  }
5950
6228
  const servicios = revision.servicios.map((s) => s.codigo);
5951
6229
  mostrarRevision(ctx, revision);
@@ -6113,10 +6391,14 @@ async function mostrarEmpresas(ctx) {
6113
6391
  }
6114
6392
  function instalarSkillDeUsuario(ctx) {
6115
6393
  try {
6116
- const informe = instalarSkill({ destinos: { carpetaConfiguracion: ctx.carpetaConfiguracion, home: ctx.home }, bloqueAgents: false, version: ctx.version });
6394
+ const informe = instalarSkill({ destinos: { carpetaConfiguracion: ctx.carpetaConfiguracion, home: ctx.home }, bloqueAgents: false, version: ctx.version, ahora: ctx.ahora() });
6117
6395
  for (const r of informe.rutas) {
6118
- if (r.accion === "instalada") ctx.salida.linea(`\u2713 Instal\xE9 la skill de REDCUMBRE en ${r.ruta}.`);
6119
- if (r.accion === "editada") ctx.salida.aviso(`${r.ruta} tiene cambios tuyos: no lo toqu\xE9.`);
6396
+ if (r.accion === "instalada") ctx.salida.linea(`\u2713 Instal\xE9 ${nombreDeLoInstalado(r.ruta)} en ${r.ruta}.`);
6397
+ if (r.accion === "reemplazada-editada") {
6398
+ ctx.salida.linea(`\u2713 Reemplac\xE9 ${nombreDeLoInstalado(r.ruta)} en ${r.ruta} ${deLaVersion(r.ruta, "por", ctx.version)}.`);
6399
+ ctx.salida.aviso(`Tu versi\xF3n editada ${r.ruta.includes("/commands/") ? "del comando" : "de la skill"} qued\xF3 en ${r.copia}.`);
6400
+ }
6401
+ if (r.accion === "editada") ctx.salida.aviso(`${r.ruta} tiene cambios tuyos y no pude guardar su copia (${r.error ?? "es parte de tu AGENTS.md"}): no lo toqu\xE9.`);
6120
6402
  }
6121
6403
  return { rutas: informe.rutas, estado: informe.estado };
6122
6404
  } catch (error) {
@@ -6134,24 +6416,7 @@ async function logout(ctx) {
6134
6416
  }
6135
6417
 
6136
6418
  // src/comandos/actualizar.ts
6137
- import fs13 from "node:fs";
6138
- import path17 from "node:path";
6139
- var real2 = (ruta) => {
6140
- try {
6141
- return fs13.realpathSync(ruta);
6142
- } catch {
6143
- return null;
6144
- }
6145
- };
6146
- function leerJson2(texto2) {
6147
- try {
6148
- const dato = JSON.parse(texto2);
6149
- return dato && typeof dato === "object" && !Array.isArray(dato) ? dato : null;
6150
- } catch {
6151
- return null;
6152
- }
6153
- }
6154
- async function actualizar(ctx, opciones, entorno = entornoDeActualizacion(ctx)) {
6419
+ async function actualizar(ctx, _opciones, entorno = entornoDeActualizacion(ctx)) {
6155
6420
  const { salida } = ctx;
6156
6421
  const registro = ctx.env.REDCUMBRE_NPM_REGISTRY || void 0;
6157
6422
  let disponible;
@@ -6172,59 +6437,12 @@ async function actualizar(ctx, opciones, entorno = entornoDeActualizacion(ctx))
6172
6437
  salida.resultado({ ok: true, actualizado: false, instalada: ctx.version, disponible });
6173
6438
  return;
6174
6439
  }
6175
- const instalacion = detectarInstalacion(entorno.bundle, entorno.raizGlobal);
6176
- if (instalacion.forma === "no-reconocida") {
6177
- throw new ErrorCli(
6178
- `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.`,
6179
- CODIGOS_DE_SALIDA.error,
6180
- { codigo: "INSTALACION_NO_RECONOCIDA", datos: { instalada: ctx.version, disponible } }
6181
- );
6182
- }
6183
- const comando2 = comandoDeActualizacion(instalacion.forma, disponible, registro);
6184
- const confirmado = instalacion.forma === "npx" ? `${prefijoPorNpx(ctx.version)} actualizar --confirmar` : COMANDO_ACTUALIZAR_CONFIRMADO;
6185
- const pregunta = `\xBFActualizo el CLI de ${ctx.version} a ${disponible} con \xAB${legible(comando2)}\xBB? Tambi\xE9n renuevo la skill donde ya est\xE1.`;
6186
- if (ctx.terminal) {
6187
- if (!await ctx.terminal.confirmar(pregunta)) throw faltaConfirmacion("No confirmaste: no actualic\xE9 nada.", confirmado);
6188
- } else if (!opciones.confirmar) {
6189
- throw faltaConfirmacion(
6190
- `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.`,
6191
- confirmado
6192
- );
6193
- }
6194
- salida.linea(`Actualizando: ${legible(comando2)}`);
6195
- const corrida = entorno.ejecutar(comando2.comando, comando2.args, { cwd: ctx.cwd, env: ctx.env });
6196
- if (corrida.status !== 0) throw errorDeActualizacion(comando2, corrida);
6197
- const raizNpm = instalacion.forma === "npx" ? entorno.raizGlobal("npm") : null;
6198
- const carpetaDelPaquete = instalacion.forma === "npx" ? raizNpm ? real2(path17.join(raizNpm, ...PAQUETE_DEL_CLI.split("/"))) : null : instalacion.carpetaDelPaquete;
6199
- if (!carpetaDelPaquete) {
6200
- throw new ErrorCli(
6201
- `\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.`,
6202
- CODIGOS_DE_SALIDA.error,
6203
- { codigo: "ACTUALIZACION_INCOMPLETA", datos: { instalada: ctx.version, disponible } }
6204
- );
6205
- }
6206
- const bundleNuevo = path17.join(carpetaDelPaquete, "dist", "redcumbre.js");
6207
- const version = entorno.ejecutar(process.execPath, [bundleNuevo, "--version"], { cwd: ctx.cwd, env: ctx.env });
6208
- if (version.status !== 0 || version.stdout.trim() !== disponible) {
6209
- throw new ErrorCli(
6210
- `\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.`,
6211
- CODIGOS_DE_SALIDA.error,
6212
- { codigo: "ACTUALIZACION_INCOMPLETA", datos: { instalada: ctx.version, disponible } }
6213
- );
6214
- }
6215
- const renovacion = entorno.ejecutar(process.execPath, [bundleNuevo, "skill", "renovar", "--json"], { cwd: ctx.cwd, env: ctx.env });
6216
- const skill = renovacion.status === 0 ? leerJson2(renovacion.stdout)?.skill ?? null : null;
6440
+ const { forma, comando: comando2, skill } = actualizarElCli(ctx, entorno, disponible, (texto2) => salida.linea(texto2));
6217
6441
  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.`);
6218
- 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}.`);
6442
+ for (const copia of resumirLaSkill(skill).copias) salida.aviso(`Tu versi\xF3n editada de la skill qued\xF3 en ${copia}.`);
6443
+ salida.linea(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}.`);
6219
6444
  mostrarBienvenida(salida, disponible, { env: ctx.env, columnas: salida.humano.columns });
6220
- salida.resultado({ ok: true, actualizado: true, instalada: ctx.version, disponible, forma: instalacion.forma, comando: legible(comando2), skill });
6221
- }
6222
- function errorDeActualizacion(comando2, corrida) {
6223
- const detalle = (corrida.stderr || corrida.stdout).trim().split(/\r?\n/).slice(-5).join(" \xB7 ");
6224
- return new ErrorCli(`No pude actualizar el CLI: \xAB${legible(comando2)}\xBB termin\xF3 con ${corrida.status ?? "una se\xF1al"}${detalle ? ` (${detalle})` : ""}. No cambi\xE9 nada m\xE1s.`, CODIGOS_DE_SALIDA.error, {
6225
- codigo: "ACTUALIZACION_FALLIDA",
6226
- datos: { comando: legible(comando2) }
6227
- });
6445
+ salida.resultado({ ok: true, actualizado: true, instalada: ctx.version, disponible, forma, comando: comando2, skill });
6228
6446
  }
6229
6447
 
6230
6448
  // src/comandos/skill.ts
@@ -6240,32 +6458,18 @@ async function skillQuitar(ctx) {
6240
6458
  salida.linea("La skill qued\xF3 quitada: \xABlogin\xBB e \xABinit\xBB no la vuelven a instalar.");
6241
6459
  salida.resultado({ ok: true, skill: { rutas: informe.rutas, estado: informe.estado } });
6242
6460
  }
6243
- async function skillRenovar(ctx, opciones) {
6461
+ async function skillRenovar(ctx, _opciones) {
6244
6462
  const { salida } = ctx;
6245
6463
  const proyecto = tieneInstalacionDelCli(ctx.proyecto) ? ctx.proyecto : void 0;
6246
6464
  const destinos = { carpetaConfiguracion: ctx.carpetaConfiguracion, home: ctx.home, proyecto };
6247
- if (opciones.reemplazarEditada) {
6248
- const previa = renovarSkill({ destinos, version: ctx.version, fuente: void 0, reemplazarEditada: false });
6249
- const editadas = previa.rutas.filter((r) => r.accion === "desactualizada");
6250
- if (editadas.length > 0) {
6251
- const lista2 = editadas.map((r) => r.ruta).join(", ");
6252
- if (ctx.terminal) {
6253
- if (!await ctx.terminal.confirmar(`\xBFReemplazo la skill que editaste en ${lista2} por la de la versi\xF3n ${ctx.version}? Tus cambios se pierden.`)) {
6254
- throw faltaConfirmacion("No confirmaste: no reemplac\xE9 la skill editada.", `${COMANDO_SKILL_RENOVAR_EDITADA} --confirmar`);
6255
- }
6256
- } else if (!opciones.confirmar) {
6257
- throw faltaConfirmacion(
6258
- `Reemplazar la skill que editaste en ${lista2} borra tus cambios y necesita confirmaci\xF3n. No reemplac\xE9 nada de lo editado.`,
6259
- `${COMANDO_SKILL_RENOVAR_EDITADA} --confirmar`
6260
- );
6261
- }
6262
- }
6263
- }
6264
- const informe = renovarSkill({ destinos, version: ctx.version, reemplazarEditada: Boolean(opciones.reemplazarEditada) });
6465
+ const informe = renovarSkill({ destinos, version: ctx.version, ahora: ctx.ahora() });
6265
6466
  for (const r of informe.rutas) {
6266
6467
  const aviso = avisoDeRenovacion(r, informe.version);
6267
- if (r.accion === "renovada") salida.linea(`\u2713 ${aviso}`);
6268
- else if (aviso) salida.aviso(aviso);
6468
+ if (r.accion === "renovada" || r.accion === "instalada") salida.linea(`\u2713 ${aviso}`);
6469
+ else if (r.accion === "reemplazada-editada") {
6470
+ salida.linea(`\u2713 Reemplac\xE9 ${nombreDeLoInstalado(r.ruta)} en ${r.ruta} ${deLaVersion(r.ruta, "por", informe.version)}.`);
6471
+ salida.aviso(`${r.ruta.includes("/commands/") ? "Tu versi\xF3n editada del comando" : "Tu versi\xF3n editada de la skill"} qued\xF3 en ${r.copia}.`);
6472
+ } else if (aviso) salida.aviso(aviso);
6269
6473
  }
6270
6474
  if (informe.rutas.length === 0) salida.linea("No hay una skill instalada por el CLI que renovar (o la quitaste con \xABredcumbre skill quitar\xBB).");
6271
6475
  else if (informe.rutas.every((r) => r.accion === "al-dia" || r.accion === "mas-nueva")) salida.linea(`La skill ya est\xE1 al d\xEDa con la versi\xF3n ${informe.version}.`);
@@ -6291,7 +6495,7 @@ function errorDeUsoEnEspanol(mensaje) {
6291
6495
  }
6292
6496
  var TITULOS_AYUDA = { "Usage:": "Uso:", "Options:": "Opciones:", "Commands:": "Comandos:", "Arguments:": "Argumentos:" };
6293
6497
  var sumar = (valor, anteriores) => [...anteriores, valor];
6294
- 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.6", "-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)}
6498
+ 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.8", "-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)}
6295
6499
  `) }).exitOverride((error) => {
6296
6500
  if (error.code === "commander.helpDisplayed" || error.code === "commander.version" || error.code === "commander.help") process.exit(0);
6297
6501
  if (process.argv.includes("--json")) {
@@ -6336,9 +6540,9 @@ comando(programa, "tarifas", "el precio de cada operaci\xF3n en tu plan: lo incl
6336
6540
  comando(programa, "consumo", "lo consumido del plan y los topes del d\xEDa").option("--produccion", "el de la llave de producci\xF3n").action((o) => correr(o, (ctx) => consumo(ctx, o)));
6337
6541
  var comandoSkill = programa.command("skill").description("la skill del integrador que el CLI instala en tus carpetas de skills");
6338
6542
  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 }));
6339
- 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 }));
6340
- comando(programa, "instalar", "deja instalado en este computador el CLI que corre por npx, en la misma versi\xF3n, y renueva la skill (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 }));
6341
- 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 }));
6543
+ comando(comandoSkill, "renovar", "renueva la skill donde ya est\xE1 con la de esta versi\xF3n del CLI (si la editaste, guarda tu copia al lado)").option("--reemplazar-editada", "se acepta por compatibilidad; ya no hace falta").option("--confirmar", "se acepta por compatibilidad; ya no hace falta").action((o) => correr(o, (ctx) => skillRenovar(ctx, o), { revisaPorSuCuenta: true }));
6544
+ comando(programa, "instalar", "deja instalado en este computador el CLI que corre por npx, en la misma versi\xF3n, y renueva la skill").option("--confirmar", "se acepta por compatibilidad; ya no hace falta").action((o) => correr(o, (ctx) => instalar(ctx, o), { revisaPorSuCuenta: true }));
6545
+ comando(programa, "actualizar", "actualiza el CLI a la \xFAltima versi\xF3n publicada y renueva la skill").option("--confirmar", "se acepta por compatibilidad; ya no hace falta").action((o) => correr(o, (ctx) => actualizar(ctx, o), { revisaPorSuCuenta: true }));
6342
6546
  var comandoMcp = programa.command("mcp").description("el servidor MCP de REDCUMBRE en tu asistente de c\xF3digo");
6343
6547
  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)));
6344
6548
  comando(comandoMcp, "quitar", "quita el servidor MCP de la configuraci\xF3n de tu asistente").option("--asistente <asistente>", ASISTENTES_MCP.join(" o ")).action((o) => correr(o, (ctx) => mcpQuitar(ctx, o)));
@@ -6347,7 +6551,7 @@ comando(programa, "solicitar-cuenta", "pide una cuenta en REDCUMBRE para tu empr
6347
6551
  await solicitarCuenta(ctx);
6348
6552
  })
6349
6553
  );
6350
- comando(programa, "doctor", "revisa la sesi\xF3n, la empresa, las llaves, las exclusiones de git y el documento del API").action((o) => correr(o, doctor));
6554
+ comando(programa, "doctor", "revisa la sesi\xF3n, la empresa, las llaves, las exclusiones de git y el documento del API").action((o) => correr(o, doctor, { consultaSinMarca: true }));
6351
6555
  comando(programa, "panel", "abre el panel de la empresa del proyecto en el navegador").addOption(empresa()).addOption(sinNavegador()).action((o) => correr(o, (ctx) => panel(ctx, { empresa: o.empresa, sinNavegador: hayQueIrSinNavegador(Boolean(o.sinNavegador), process.env) })));
6352
6556
  var traducirUso = (c) => {
6353
6557
  c.usage(c.usage().replace("[options]", "[opciones]").replace("[command]", "[comando]"));