@redcumbrecl/cli 0.6.7 → 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
@@ -1831,128 +1831,606 @@ function recortar(valor, campos) {
1831
1831
  }
1832
1832
 
1833
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";
1834
1839
  import fs6 from "node:fs";
1835
1840
  import path6 from "node:path";
1836
- async function doctor(ctx) {
1837
- const { salida, proyecto } = ctx;
1838
- const revisiones = [];
1839
- const anotar = (r) => {
1840
- revisiones.push(r);
1841
- salida.linea(`${r.ok ? "\u2713" : r.opcional ? "\xB7" : "\u2717"} ${r.detalle}${!r.ok && r.comando ? ` \u2192 ${r.comando}` : ""}`);
1842
- };
1843
- const haySesion = await ctx.haySesion();
1844
- anotar(
1845
- 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" }
1846
- );
1847
- const estado2 = leerEstado(proyecto);
1848
- let slug = null;
1849
- if (estado2) {
1850
- slug = estado2.tenantSlug;
1851
- anotar({ revision: "empresa", ok: true, detalle: `El proyecto ${proyecto} apunta a la empresa ${slug}.` });
1852
- } else {
1853
- 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;
1854
1850
  }
1855
- for (const entorno of ENTORNOS_LLAVE) {
1856
- 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
+ });
1857
1867
  }
1858
- const gitignore = path6.join(proyecto, ".gitignore");
1859
- const lineas = new Set((fs6.existsSync(gitignore) ? fs6.readFileSync(gitignore, "utf8") : "").split(/\r?\n/).map((l) => l.trim()));
1860
- const faltanExclusiones = ["keys/", ".redcumbre/"].filter((l) => !lineas.has(l) && !lineas.has(`/${l}`));
1861
- const versionadas = ENTORNOS_LLAVE.map((e) => path6.relative(proyecto, rutaDeLaLlave(proyecto, e, ctx.env))).filter(
1862
- (relativa) => fs6.existsSync(path6.join(proyecto, relativa)) && estaVersionado(proyecto, relativa)
1863
- );
1864
- if (versionadas.length > 0) {
1865
- anotar({
1866
- revision: "exclusiones",
1867
- ok: false,
1868
- 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"
1869
1889
  });
1870
- } else if (faltanExclusiones.length > 0) {
1871
- anotar({ revision: "exclusiones", ok: false, detalle: `Al .gitignore le falta ${faltanExclusiones.join(" y ")}.`, comando: COMANDO_INIT });
1872
- } else {
1873
- anotar({ revision: "exclusiones", ok: true, detalle: "keys/ y .redcumbre/ est\xE1n fuera del control de versiones." });
1874
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`;
1875
1925
  try {
1876
- const documento = await cargarDocumento(ctx.cliente, ctx.carpetaConfiguracion, salida);
1877
- anotar({
1878
- revision: "documento",
1879
- ok: true,
1880
- 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).`
1881
- });
1926
+ fs6.writeFileSync(temporal, contenido);
1927
+ conReintentoEnWindows(() => fs6.renameSync(temporal, ruta));
1882
1928
  } catch (error) {
1883
- 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;
1884
1931
  }
1885
- 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;
1886
- const version = { instalada: ctx.version, disponible };
1887
- if (disponible === null) salida.linea("\xB7 No pude consultar la \xFAltima versi\xF3n del CLI.");
1888
- 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.`);
1889
- else salida.linea(`\u2713 El CLI est\xE1 en la \xFAltima versi\xF3n (${ctx.version}).`);
1890
- const faltantes = revisiones.filter((r) => !r.ok && !r.opcional).map((r) => ({ revision: r.revision, detalle: r.detalle, ...r.comando ? { comando: r.comando } : {} }));
1891
- if (faltantes.length > 0) {
1892
- throw new ErrorCli(`Hay ${faltantes.length === 1 ? "una cosa que arreglar" : `${faltantes.length} cosas que arreglar`} en el proyecto.`, CODIGOS_DE_SALIDA.error, {
1893
- codigo: "DOCTOR_CON_FALTANTES",
1894
- datos: { revisiones, faltantes, version }
1895
- });
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;
1957
+ }
1958
+ try {
1959
+ const dato = JSON.parse(texto2);
1960
+ return dato && typeof dato === "object" && !Array.isArray(dato) ? dato : null;
1961
+ } catch {
1962
+ return null;
1896
1963
  }
1897
- salida.linea("Todo en orden.");
1898
- salida.resultado({ ok: true, proyecto, revisiones, faltantes: [], version });
1899
1964
  }
1900
- async function revisarLlave(ctx, entorno, slug) {
1901
- const revision = `llave-${entorno}`;
1902
- const nombre = etiquetaLlave(entorno);
1903
- const ruta = path6.relative(ctx.proyecto, rutaDeLaLlave(ctx.proyecto, entorno, ctx.env)) || rutaDeLaLlave(ctx.proyecto, entorno, ctx.env);
1904
- const archivo = llaveDelEntorno(ctx.proyecto, entorno, ctx.env);
1905
- if (!archivo) {
1906
- 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 };
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
+ }
1907
2026
  }
1908
- if (slug && archivo.tenantSlug !== slug) {
1909
- return { revision, ok: false, detalle: `La ${nombre} es de ${archivo.tenantSlug}, pero el proyecto apunta a ${slug}.`, comando: COMANDO_INIT };
2027
+ throw new Error(`ya hay demasiadas copias de ${archivo} con la misma hora`);
2028
+ }
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 };
2037
+ }
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);
1910
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;
1911
2050
  try {
1912
- const r = await ctx.cliente.whoami(archivo.token, archivo.tenantSlug);
1913
- 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 };
1914
- if (r.sandbox !== (entorno === "prueba")) {
1915
- 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 };
1916
- }
1917
- return { revision, ok: true, detalle: `La ${nombre} funciona (${r.tenant.nombre}).` };
2051
+ copia = guardarCopiaDeLoEditado(archivo, ahora);
1918
2052
  } catch (error) {
1919
- 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) };
1920
2054
  }
2055
+ escribirAtomico(archivo, nuevo);
2056
+ return { accion: "reemplazada-editada", hash: hashNuevo, copia };
1921
2057
  }
1922
- async function panel(ctx, opciones) {
1923
- const slug = empresaDelProyecto(ctx, opciones.empresa);
1924
- const url = `${ctx.servidores.web}${rutaDeEmpresa(slug, "/dashboard")}`;
1925
- const abierto = opciones.sinNavegador ? false : await ctx.abrir(url);
1926
- ctx.salida.linea(abierto ? `Abr\xED el panel de ${slug} en el navegador: ${url}` : `El panel de ${slug}: ${url}`);
1927
- 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;
1928
2061
  }
1929
-
1930
- // src/comandos/emisores.ts
1931
- import fs11 from "node:fs";
1932
- import path12 from "node:path";
1933
-
1934
- // src/comandos/emisores-operaciones.ts
1935
- var RUT_FILTRO = { bandera: "--rut <rut>", obligatoria: false, tipo: "texto", destino: { en: "consulta", nombre: "rut" } };
1936
- var ESTADO_FILTRO = { bandera: "--estado <estado>", obligatoria: false, tipo: "texto", destino: { en: "consulta", nombre: "estado" } };
1937
- var INTEGRACION_FILTRO = { bandera: "--integracion <tipo>", obligatoria: false, tipo: "texto", destino: { en: "consulta", nombre: "tipoIntegracion" } };
1938
- var CREDENCIAL_FILTRO = { bandera: "--credencial <estado>", obligatoria: false, tipo: "texto", destino: { en: "consulta", nombre: "credencialEstado" } };
1939
- var ACTIVO_FILTRO = { bandera: "--activo <true|false>", obligatoria: false, tipo: "booleano", destino: { en: "consulta", nombre: "activo" }, valores: ["true", "false"] };
1940
- var TRIBUTARIA_FILTRO = { bandera: "--tributaria <true|false>", obligatoria: false, tipo: "booleano", destino: { en: "consulta", nombre: "esTributaria" }, valores: ["true", "false"] };
1941
- var LIMITE = { bandera: "--limite <n>", obligatoria: false, tipo: "entero", destino: { en: "consulta", nombre: "limit" } };
1942
- var DESDE = { bandera: "--desde <n>", obligatoria: false, tipo: "entero", destino: { en: "consulta", nombre: "offset" } };
1943
- var TODAS = { bandera: "--todas", obligatoria: false, tipo: "interruptor", destino: { en: "ninguno" } };
1944
- var INCLUIR_ARCHIVADOS = { bandera: "--incluir-archivados", obligatoria: false, tipo: "interruptor", destino: { en: "consulta", nombre: "includeInactive", valorFijo: "true" } };
1945
- var CUERPO_OBLIGATORIO = { bandera: "--cuerpo <json|@archivo|->", obligatoria: true, tipo: "cuerpo", destino: { en: "cuerpo-completo" } };
1946
- var CUERPO_OPCIONAL = { bandera: "--cuerpo <json|@archivo|->", obligatoria: false, tipo: "cuerpo", destino: { en: "cuerpo-completo" } };
1947
- var ARCHIVO_LOGO = { bandera: "--archivo <ruta>", obligatoria: true, tipo: "archivo", destino: { en: "formulario", nombre: "logo" } };
1948
- var TIPOS_DE_CERTIFICACION = { bandera: "--tipos <lista>", obligatoria: true, tipo: "lista-de-enteros", destino: { en: "cuerpo", nombre: "tiposDte" } };
1949
- var CORREO_DE_CONTACTO = { bandera: "--correo <correo>", obligatoria: true, tipo: "texto", destino: { en: "cuerpo", nombre: "emailContacto" } };
1950
- var TELEFONO_DE_CONTACTO = { bandera: "--telefono <tel\xE9fono>", obligatoria: true, tipo: "texto", destino: { en: "cuerpo", nombre: "telefonoContacto" } };
1951
- var RUT_DE_CONFIRMACION = { bandera: "--rut <rut>", obligatoria: true, tipo: "texto", destino: { en: "cuerpo", nombre: "confirmacionRut" } };
1952
- var MOTIVO_OPCIONAL = { bandera: "--motivo <motivo>", obligatoria: false, tipo: "texto", destino: { en: "cuerpo", nombre: "motivo" } };
1953
- var TIPO_DTE_DEL_AMBIENTE = { bandera: "--tipo-dte <n>", obligatoria: true, tipo: "entero", destino: { en: "cuerpo", nombre: "tipoDte" } };
1954
- var AMBIENTE_DEL_TIPO = { bandera: "--ambiente <CERTIFICACION|PRODUCCION>", obligatoria: true, tipo: "ambiente", destino: { en: "cuerpo", nombre: "ambiente" }, valores: ["CERTIFICACION", "PRODUCCION"] };
1955
- var TIPO_DE_EMISOR_A_REVOCAR = { bandera: "--tipo <tributario|dte>", obligatoria: true, tipo: "texto", destino: { en: "cuerpo", nombre: "tipoEmisor" }, valores: ["tributario", "dte"] };
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 } };
2070
+ }
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 } };
2079
+ }
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 };
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 } };
2089
+ }
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
+ }
2107
+ }
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));
2116
+ }
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";
2124
+ }
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 });
2135
+ }
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
+ }
2152
+ }
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 };
2156
+ }
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 });
2178
+ }
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) {
2202
+ try {
2203
+ copia = guardarCopiaDeLoEditado(objetivo.archivo, ahora);
2204
+ } catch (error) {
2205
+ rutas.push({ ruta: objetivo.legible, accion: "desactualizada", instalada: instalada2, error: motivoDe(error) });
2206
+ continue;
2207
+ }
2208
+ }
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 };
2222
+ }
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";
2228
+ }
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}`;
2233
+ }
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;
2245
+ }
2246
+ function renovarSkillAlCorrer(opciones) {
2247
+ try {
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`);
2259
+ }
2260
+ }
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 };
2292
+ }
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.`
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." });
2333
+ }
2334
+ anotar(revisarSkill(ctx));
2335
+ try {
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)}` });
2344
+ }
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
+ });
2356
+ }
2357
+ salida.linea("Todo en orden.");
2358
+ salida.resultado({ ok: true, proyecto, revisiones, faltantes: [], version });
2359
+ }
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 };
2367
+ }
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 };
2370
+ }
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 };
2376
+ }
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)}` };
2380
+ }
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." };
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 };
2405
+ }
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"] };
1956
2434
  var MOTIVO_DE_REVOCACION = { bandera: "--motivo <motivo>", obligatoria: false, tipo: "texto", destino: { en: "cuerpo", nombre: "motivoRevocacion" } };
1957
2435
  var OPERACIONES_EMISORES = [
1958
2436
  {
@@ -2534,8 +3012,8 @@ var OPERACIONES_EMISORES = [
2534
3012
  import { Option } from "commander";
2535
3013
 
2536
3014
  // src/nucleo/actualizacion-del-cli.ts
2537
- import fs8 from "node:fs";
2538
- import path8 from "node:path";
3015
+ import fs9 from "node:fs";
3016
+ import path9 from "node:path";
2539
3017
 
2540
3018
  // src/nucleo/bienvenida.ts
2541
3019
  var TITULO_DE_BIENVENIDA = "BIENVENIDO A REDCUMBRE";
@@ -2617,28 +3095,28 @@ function mostrarBienvenida(salida, version, entorno) {
2617
3095
 
2618
3096
  // src/nucleo/instalacion-del-cli.ts
2619
3097
  import { spawnSync as spawnSync2 } from "node:child_process";
2620
- import fs7 from "node:fs";
2621
- import path7 from "node:path";
2622
- import { fileURLToPath } from "node:url";
3098
+ import fs8 from "node:fs";
3099
+ import path8 from "node:path";
3100
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
2623
3101
  var real = (ruta) => {
2624
3102
  try {
2625
- return fs7.realpathSync(ruta);
3103
+ return fs8.realpathSync(ruta);
2626
3104
  } catch {
2627
3105
  return null;
2628
3106
  }
2629
3107
  };
2630
- var dentroDe = (ruta, carpeta) => ruta === carpeta || ruta.startsWith(carpeta + path7.sep);
2631
- var correPorNpx = (bundle) => (real(bundle) ?? path7.resolve(bundle)).split(path7.sep).includes("_npx");
3108
+ var dentroDe = (ruta, carpeta) => ruta === carpeta || ruta.startsWith(carpeta + path8.sep);
3109
+ var correPorNpx = (bundle) => (real(bundle) ?? path8.resolve(bundle)).split(path8.sep).includes("_npx");
2632
3110
  function detectarInstalacion(bundle, raizGlobal) {
2633
- const bundleReal = real(bundle) ?? path7.resolve(bundle);
3111
+ const bundleReal = real(bundle) ?? path8.resolve(bundle);
2634
3112
  if (correPorNpx(bundleReal)) return { forma: "npx" };
2635
3113
  for (const [gestor, forma] of [["npm", "npm-global"], ["pnpm", "pnpm-global"]]) {
2636
3114
  const raiz = raizGlobal(gestor);
2637
- const carpeta = raiz ? real(path7.join(raiz, ...PAQUETE_DEL_CLI.split("/"))) : null;
3115
+ const carpeta = raiz ? real(path8.join(raiz, ...PAQUETE_DEL_CLI.split("/"))) : null;
2638
3116
  if (carpeta && dentroDe(bundleReal, carpeta)) return { forma, carpetaDelPaquete: carpeta };
2639
3117
  }
2640
- const marcaDeDependencia = ["node_modules", ...PAQUETE_DEL_CLI.split("/")].join(path7.sep);
2641
- if (bundleReal.includes(`${path7.sep}${marcaDeDependencia}${path7.sep}`)) {
3118
+ const marcaDeDependencia = ["node_modules", ...PAQUETE_DEL_CLI.split("/")].join(path8.sep);
3119
+ if (bundleReal.includes(`${path8.sep}${marcaDeDependencia}${path8.sep}`)) {
2642
3120
  return { forma: "no-reconocida", motivo: `el CLI est\xE1 instalado como dependencia de un proyecto (${bundleReal}): actual\xEDzalo con el gestor de ese proyecto, que es quien decide su versi\xF3n` };
2643
3121
  }
2644
3122
  return { forma: "no-reconocida", motivo: `el CLI que corre (${bundleReal}) no est\xE1 en la cach\xE9 de npx ni en la carpeta global de npm o de pnpm` };
@@ -2659,7 +3137,7 @@ function ejecutarDeVerdad(comando2, args, opciones) {
2659
3137
  function entornoDeActualizacion(ctx) {
2660
3138
  const registro = ctx.env.REDCUMBRE_NPM_REGISTRY || void 0;
2661
3139
  return {
2662
- bundle: fileURLToPath(import.meta.url),
3140
+ bundle: fileURLToPath2(import.meta.url),
2663
3141
  ejecutar: ejecutarDeVerdad,
2664
3142
  raizGlobal(gestor) {
2665
3143
  const r = ejecutarDeVerdad(gestor, ["root", "--global"], { cwd: ctx.cwd, env: ctx.env });
@@ -2678,7 +3156,7 @@ var VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
2678
3156
  function entornoSinNpx(env) {
2679
3157
  const limpio = { ...env };
2680
3158
  for (const clave of Object.keys(limpio).filter((k) => k.toUpperCase() === "PATH")) {
2681
- limpio[clave] = (limpio[clave] ?? "").split(path7.delimiter).filter((carpeta) => carpeta && !carpeta.split(/[\\/]/).includes("_npx")).join(path7.delimiter);
3159
+ limpio[clave] = (limpio[clave] ?? "").split(path8.delimiter).filter((carpeta) => carpeta && !carpeta.split(/[\\/]/).includes("_npx")).join(path8.delimiter);
2682
3160
  }
2683
3161
  return limpio;
2684
3162
  }
@@ -2691,18 +3169,18 @@ function carpetaDeEjecutablesDeNpm(entorno, opciones) {
2691
3169
  const r = entorno.ejecutar("npm", ["prefix", "--global"], opciones);
2692
3170
  const prefijo = r.stdout.trim().split(/\r?\n/).pop()?.trim() ?? "";
2693
3171
  if (r.status !== 0 || !prefijo) return null;
2694
- return process.platform === "win32" ? prefijo : path7.join(prefijo, "bin");
3172
+ return process.platform === "win32" ? prefijo : path8.join(prefijo, "bin");
2695
3173
  }
2696
3174
 
2697
3175
  // src/nucleo/actualizacion-del-cli.ts
2698
3176
  var real2 = (ruta) => {
2699
3177
  try {
2700
- return fs8.realpathSync(ruta);
3178
+ return fs9.realpathSync(ruta);
2701
3179
  } catch {
2702
3180
  return null;
2703
3181
  }
2704
3182
  };
2705
- function leerJson(texto2) {
3183
+ function leerJson2(texto2) {
2706
3184
  try {
2707
3185
  const dato = JSON.parse(texto2);
2708
3186
  return dato && typeof dato === "object" && !Array.isArray(dato) ? dato : null;
@@ -2732,7 +3210,7 @@ function actualizarElCli(ctx, entorno, disponible, informar) {
2732
3210
  const corrida = entorno.ejecutar(comando2.comando, comando2.args, { cwd: ctx.cwd, env: ctx.env });
2733
3211
  if (corrida.status !== 0) throw errorDeActualizacion(comando2, corrida);
2734
3212
  const raizNpm = instalacion.forma === "npx" ? entorno.raizGlobal("npm") : null;
2735
- const carpetaDelPaquete = instalacion.forma === "npx" ? raizNpm ? real2(path8.join(raizNpm, ...PAQUETE_DEL_CLI.split("/"))) : null : instalacion.carpetaDelPaquete;
3213
+ const carpetaDelPaquete = instalacion.forma === "npx" ? raizNpm ? real2(path9.join(raizNpm, ...PAQUETE_DEL_CLI.split("/"))) : null : instalacion.carpetaDelPaquete;
2736
3214
  if (!carpetaDelPaquete) {
2737
3215
  throw new ErrorCli(
2738
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.`,
@@ -2740,7 +3218,7 @@ function actualizarElCli(ctx, entorno, disponible, informar) {
2740
3218
  { codigo: "ACTUALIZACION_INCOMPLETA", datos: { instalada: ctx.version, disponible } }
2741
3219
  );
2742
3220
  }
2743
- const bundleNuevo = path8.join(carpetaDelPaquete, "dist", "redcumbre.js");
3221
+ const bundleNuevo = path9.join(carpetaDelPaquete, "dist", "redcumbre.js");
2744
3222
  const version = entorno.ejecutar(process.execPath, [bundleNuevo, "--version"], { cwd: ctx.cwd, env: ctx.env });
2745
3223
  if (version.status !== 0 || version.stdout.trim() !== disponible) {
2746
3224
  throw new ErrorCli(
@@ -2750,20 +3228,20 @@ function actualizarElCli(ctx, entorno, disponible, informar) {
2750
3228
  );
2751
3229
  }
2752
3230
  const renovacion = entorno.ejecutar(process.execPath, [bundleNuevo, "skill", "renovar", "--json"], { cwd: ctx.cwd, env: ctx.env });
2753
- const skill = renovacion.status === 0 ? leerJson(renovacion.stdout)?.skill ?? null : null;
3231
+ const skill = renovacion.status === 0 ? leerJson2(renovacion.stdout)?.skill ?? null : null;
2754
3232
  return { forma: instalacion.forma, comando: legible(comando2), skill };
2755
3233
  }
2756
3234
  function resumirLaSkill(skill) {
2757
3235
  const rutas = Array.isArray(skill?.rutas) ? skill.rutas : [];
2758
3236
  const copias = rutas.flatMap((r) => r.accion === "reemplazada-editada" && typeof r.copia === "string" ? [r.copia] : []);
2759
- return { renovadas: rutas.filter((r) => r.accion === "renovada" || r.accion === "reemplazada-editada").length, copias };
3237
+ return { renovadas: rutas.filter((r) => r.accion === "renovada" || r.accion === "instalada" || r.accion === "reemplazada-editada").length, copias };
2760
3238
  }
2761
3239
  function textoDeLaSkillRenovada(resumen) {
2762
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 ")}`;
2763
3241
  if (resumen.renovadas > 0) return "renov\xE9 la skill";
2764
3242
  return "no hab\xEDa una skill instalada por el CLI que renovar";
2765
3243
  }
2766
- var motivoDe = (error) => error instanceof Error ? error.message : String(error);
3244
+ var motivoDe2 = (error) => error instanceof Error ? error.message : String(error);
2767
3245
  async function autoactualizarElCli(ctx, opciones) {
2768
3246
  const { entorno, salida, agente } = opciones;
2769
3247
  const depurar = opciones.depurar ?? (() => void 0);
@@ -2781,7 +3259,7 @@ async function autoactualizarElCli(ctx, opciones) {
2781
3259
  if (opciones.consultaSinMarca) ctx.versionDelRegistro = { ultima };
2782
3260
  actualizacion = ultima && compararVersiones(ultima, ctx.version) > 0 ? { instalada: ctx.version, disponible: ultima, comando: COMANDO_ACTUALIZAR } : null;
2783
3261
  } catch (error) {
2784
- depurar(`no pude leer la marca de versi\xF3n: ${motivoDe(error)}`);
3262
+ depurar(`no pude leer la marca de versi\xF3n: ${motivoDe2(error)}`);
2785
3263
  return false;
2786
3264
  }
2787
3265
  if (!actualizacion) return false;
@@ -2832,8 +3310,8 @@ async function autoactualizarElCli(ctx, opciones) {
2832
3310
  return true;
2833
3311
  } catch (error) {
2834
3312
  const codigo = error instanceof ErrorCli && error.codigo ? error.codigo : "ACTUALIZACION_FALLIDA";
2835
- depurar(`la auto-actualizaci\xF3n a ${disponible} fall\xF3 (${codigo}): ${motivoDe(error)}`);
2836
- fallo2({ codigo, mensaje: motivoDe(error) }, true);
3313
+ depurar(`la auto-actualizaci\xF3n a ${disponible} fall\xF3 (${codigo}): ${motivoDe2(error)}`);
3314
+ fallo2({ codigo, mensaje: motivoDe2(error) }, true);
2837
3315
  return false;
2838
3316
  }
2839
3317
  }
@@ -2843,9 +3321,9 @@ import os2 from "node:os";
2843
3321
 
2844
3322
  // src/nucleo/sesion.ts
2845
3323
  import { spawn } from "node:child_process";
2846
- import fs9 from "node:fs";
3324
+ import fs10 from "node:fs";
2847
3325
  import os from "node:os";
2848
- import path9 from "node:path";
3326
+ import path10 from "node:path";
2849
3327
  import { setTimeout as setTimeoutAbortable } from "node:timers/promises";
2850
3328
  import * as oidc from "openid-client";
2851
3329
 
@@ -2897,14 +3375,14 @@ async function abrirRetornoLocal(opciones) {
2897
3375
  function carpetaDeConfiguracion(env = process.env, plataforma = process.platform) {
2898
3376
  if (plataforma === "win32") {
2899
3377
  if (!env.APPDATA) throw new ErrorCli("No encuentro %APPDATA%: no tengo d\xF3nde guardar la sesi\xF3n.");
2900
- return path9.join(env.APPDATA, "redcumbre");
3378
+ return path10.join(env.APPDATA, "redcumbre");
2901
3379
  }
2902
- const base = env.XDG_CONFIG_HOME || path9.join(os.homedir(), ".config");
2903
- return path9.join(base, "redcumbre");
3380
+ const base = env.XDG_CONFIG_HOME || path10.join(os.homedir(), ".config");
3381
+ return path10.join(base, "redcumbre");
2904
3382
  }
2905
3383
  function estaDentro(base, ruta) {
2906
- const relativa = path9.relative(path9.resolve(base), path9.resolve(ruta));
2907
- return !relativa.startsWith("..") && !path9.isAbsolute(relativa);
3384
+ const relativa = path10.relative(path10.resolve(base), path10.resolve(ruta));
3385
+ return !relativa.startsWith("..") && !path10.isAbsolute(relativa);
2908
3386
  }
2909
3387
  function exigirFueraDelProyecto(carpeta, proyecto, personal = os.homedir()) {
2910
3388
  if (!estaDentro(proyecto, carpeta)) return;
@@ -2918,21 +3396,21 @@ var AlmacenArchivo = class {
2918
3396
  descripcion;
2919
3397
  /** `proyecto`: la carpeta donde corre el CLI; la sesión nunca puede quedar debajo de ella. */
2920
3398
  constructor(carpeta, proyecto) {
2921
- this.ruta = path9.join(carpeta, "sesion.json");
3399
+ this.ruta = path10.join(carpeta, "sesion.json");
2922
3400
  exigirFueraDelProyecto(carpeta, proyecto);
2923
3401
  this.descripcion = `el archivo ${this.ruta} (permisos 0600)`;
2924
3402
  }
2925
3403
  leer() {
2926
- if (!fs9.existsSync(this.ruta)) return null;
2927
- return JSON.parse(fs9.readFileSync(this.ruta, "utf8"));
3404
+ if (!fs10.existsSync(this.ruta)) return null;
3405
+ return JSON.parse(fs10.readFileSync(this.ruta, "utf8"));
2928
3406
  }
2929
3407
  guardar(par) {
2930
- fs9.mkdirSync(path9.dirname(this.ruta), { recursive: true, mode: 448 });
2931
- fs9.writeFileSync(this.ruta, JSON.stringify(par), { mode: 384 });
2932
- fs9.chmodSync(this.ruta, 384);
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);
2933
3411
  }
2934
3412
  borrar() {
2935
- fs9.rmSync(this.ruta, { force: true });
3413
+ fs10.rmSync(this.ruta, { force: true });
2936
3414
  }
2937
3415
  };
2938
3416
  var AlmacenLlavero = class {
@@ -3118,624 +3596,251 @@ function hayQueIrSinNavegador(pedido, env = process.env, plataforma = process.pl
3118
3596
  if (env.SSH_CONNECTION || env.SSH_TTY) return true;
3119
3597
  return plataforma === "linux" && !env.DISPLAY && !env.WAYLAND_DISPLAY;
3120
3598
  }
3121
- async function abrirNavegadorDelSistema(url) {
3122
- const [comando2, argumentos] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", '""', url.replace(/&/g, "^&")]] : ["xdg-open", [url]];
3123
- return new Promise((resolver) => {
3124
- const hijo = spawn(comando2, argumentos, { stdio: "ignore", detached: true });
3125
- hijo.once("error", () => resolver(false));
3126
- hijo.once("spawn", () => {
3127
- hijo.unref();
3128
- resolver(true);
3129
- });
3130
- });
3131
- }
3132
- var PAGINA_LISTO = paginaListo("Listo, ya iniciaste sesi\xF3n", "Ya puedes cerrar esta ventana y volver a la terminal.");
3133
- async function loginConLoopback(identidad, salida, opciones) {
3134
- const pkce = await crearPkce();
3135
- const local = await abrirRetornoLocal({
3136
- pagina: PAGINA_LISTO,
3137
- esperaMs: opciones.esperaMs ?? 3e5,
3138
- mensajeDeEspera: "No lleg\xF3 la autorizaci\xF3n del navegador en 5 minutos. Vuelve a correr el comando."
3139
- });
3140
- const redirectUri = `http://127.0.0.1:${local.puerto}/callback`;
3141
- try {
3142
- const url = await identidad.urlDeAutorizacion(redirectUri, pkce);
3143
- const abierto = await (opciones.abrirNavegador ?? abrirNavegadorDelSistema)(url);
3144
- 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:");
3145
- salida.linea(url);
3146
- const vuelta = await local.recibido;
3147
- const recibida = new URL(`${redirectUri}${vuelta.search}`);
3148
- const error = recibida.searchParams.get("error");
3149
- if (error) throw new ErrorCli(`El inicio de sesi\xF3n no se complet\xF3: ${error}.`);
3150
- return await identidad.canjear(recibida, pkce);
3151
- } finally {
3152
- local.cerrar();
3153
- }
3154
- }
3155
- 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.";
3156
- async function iniciarSesion(identidad, salida, opciones) {
3157
- return opciones.sinNavegador ? loginDeDispositivoEnLinea(identidad, salida) : loginConLoopback(identidad, salida, opciones);
3158
- }
3159
- async function loginDeDispositivoEnLinea(identidad, salida) {
3160
- const solicitud = await identidad.iniciarDispositivo();
3161
- salida.linea("Abre esta direcci\xF3n en un navegador y aprueba el acceso:");
3162
- salida.linea(solicitud.url);
3163
- salida.linea(`El c\xF3digo que tiene que mostrar es ${solicitud.userCode}.`);
3164
- salida.linea(AVISO_DE_APROBACION);
3165
- const venceEn = new Date(Date.now() + solicitud.venceEnSegundos * 1e3).toISOString();
3166
- const desenlace = await identidad.esperarDispositivo({ deviceCode: solicitud.deviceCode, intervalo: solicitud.intervalo, venceEn }, solicitud.venceEnSegundos * 1e3);
3167
- if (desenlace.estado === "aprobado") return desenlace.par;
3168
- throw errorDelDesenlace(desenlace.estado);
3169
- }
3170
- var ESPERA_DE_COMPLETAR_MS = 9e4;
3171
- var rutaLoginPendiente = (carpeta) => path9.join(carpeta, "login-pendiente.json");
3172
- var volverAEmpezar = (motivo, codigo) => new ErrorCli(`${motivo} Vuelve a empezar con \xABredcumbre login\xBB.`, CODIGOS_DE_SALIDA.sesion, { codigo, comando: "redcumbre login" });
3173
- function errorDelDesenlace(estado2) {
3174
- if (estado2 === "pendiente") {
3175
- 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, {
3176
- codigo: "LOGIN_PENDIENTE",
3177
- comando: "redcumbre login --completar"
3178
- });
3179
- }
3180
- if (estado2 === "vencido") return volverAEmpezar("El c\xF3digo venci\xF3 antes de que lo aprobaran.", "LOGIN_PENDIENTE_VENCIDO");
3181
- return volverAEmpezar("La persona rechaz\xF3 el acceso.", "LOGIN_RECHAZADO");
3182
- }
3183
- function leerLoginPendiente(carpeta) {
3184
- const ruta = rutaLoginPendiente(carpeta);
3185
- if (!fs9.existsSync(ruta)) return null;
3186
- try {
3187
- const d = JSON.parse(fs9.readFileSync(ruta, "utf8"));
3188
- const textos = ["deviceCode", "userCode", "url", "venceEn", "clientId"];
3189
- if (!textos.every((k) => typeof d[k] === "string") || typeof d.intervalo !== "number") return null;
3190
- if (d.clientId !== CLIENTE_OIDC.clientId || Number.isNaN(new Date(d.venceEn).getTime())) return null;
3191
- return d;
3192
- } catch {
3193
- return null;
3194
- }
3195
- }
3196
- function guardarLoginPendiente(carpeta, pendiente) {
3197
- const ruta = rutaLoginPendiente(carpeta);
3198
- fs9.mkdirSync(carpeta, { recursive: true, mode: 448 });
3199
- fs9.writeFileSync(ruta, JSON.stringify(pendiente), { mode: 384 });
3200
- fs9.chmodSync(ruta, 384);
3201
- }
3202
- function borrarLoginPendiente(carpeta) {
3203
- const ruta = rutaLoginPendiente(carpeta);
3204
- const habia = fs9.existsSync(ruta);
3205
- fs9.rmSync(ruta, { force: true });
3206
- return habia;
3207
- }
3208
- async function iniciarLoginDeDispositivo(identidad, carpeta, proyecto, ahora = /* @__PURE__ */ new Date()) {
3209
- exigirFueraDelProyecto(carpeta, proyecto);
3210
- const vigente = leerLoginPendiente(carpeta);
3211
- if (vigente && new Date(vigente.venceEn).getTime() > ahora.getTime()) return { url: vigente.url, codigo: vigente.userCode, vence: vigente.venceEn };
3212
- borrarLoginPendiente(carpeta);
3213
- const solicitud = await identidad.iniciarDispositivo();
3214
- const venceEn = new Date(ahora.getTime() + solicitud.venceEnSegundos * 1e3).toISOString();
3215
- guardarLoginPendiente(carpeta, {
3216
- deviceCode: solicitud.deviceCode,
3217
- userCode: solicitud.userCode,
3218
- url: solicitud.url,
3219
- intervalo: solicitud.intervalo,
3220
- venceEn,
3221
- clientId: CLIENTE_OIDC.clientId
3222
- });
3223
- return { url: solicitud.url, codigo: solicitud.userCode, vence: venceEn };
3224
- }
3225
- async function completarLogin(identidad, almacen, carpeta, proyecto, ahora = /* @__PURE__ */ new Date(), esperaMs = ESPERA_DE_COMPLETAR_MS) {
3226
- exigirFueraDelProyecto(carpeta, proyecto);
3227
- if (almacen.leer() !== null) return "ya-habia-sesion";
3228
- const pendiente = leerLoginPendiente(carpeta);
3229
- if (!pendiente) throw volverAEmpezar("No hay un inicio de sesi\xF3n pendiente.", "SIN_SESION");
3230
- if (new Date(pendiente.venceEn).getTime() <= ahora.getTime()) {
3231
- borrarLoginPendiente(carpeta);
3232
- throw errorDelDesenlace("vencido");
3233
- }
3234
- const desenlace = await identidad.esperarDispositivo({ deviceCode: pendiente.deviceCode, intervalo: pendiente.intervalo, venceEn: pendiente.venceEn }, esperaMs);
3235
- if (desenlace.estado === "aprobado") {
3236
- almacen.guardar(desenlace.par);
3237
- borrarLoginPendiente(carpeta);
3238
- return "iniciada";
3239
- }
3240
- if (desenlace.estado !== "pendiente") borrarLoginPendiente(carpeta);
3241
- throw errorDelDesenlace(desenlace.estado);
3242
- }
3243
- var Sesion = class {
3244
- constructor(almacen, identidad, salida, login2) {
3245
- this.almacen = almacen;
3246
- this.identidad = identidad;
3247
- this.salida = salida;
3248
- this.login = login2;
3249
- }
3250
- actual = null;
3251
- async entrar() {
3252
- const par = await this.login();
3253
- this.almacen.guardar(par);
3254
- this.salida.linea(`Sesi\xF3n iniciada. Qued\xF3 guardada en ${this.almacen.descripcion}.`);
3255
- return par;
3256
- }
3257
- /** El access token de esta corrida: renueva siempre la sesión guardada y guarda el par rotado. */
3258
- async token() {
3259
- if (this.actual) return this.actual.access_token;
3260
- const guardada = this.almacen.leer();
3261
- if (!guardada) {
3262
- this.actual = await this.entrar();
3263
- return this.actual.access_token;
3264
- }
3265
- try {
3266
- this.actual = await this.identidad.renovar(guardada.refresh_token);
3267
- this.almacen.guardar(this.actual);
3268
- } catch (error) {
3269
- if (!(error instanceof ErrorRefreshInvalido)) throw error;
3270
- this.almacen.borrar();
3271
- this.salida.linea("Tu sesi\xF3n anterior venci\xF3 o se cerr\xF3. Inicia sesi\xF3n de nuevo.");
3272
- this.actual = await this.entrar();
3273
- }
3274
- return this.actual.access_token;
3275
- }
3276
- /**
3277
- * Corre `operacion` con el token de la sesión. Si el API responde 401, borra la sesión, pide login y
3278
- * la repite UNA vez con el token nuevo; nunca reintenta con el mismo (`CA-33`).
3279
- */
3280
- async usar(operacion) {
3281
- try {
3282
- return await operacion(await this.token());
3283
- } catch (error) {
3284
- if (!(error instanceof ErrorSesionRechazada)) throw error;
3285
- this.almacen.borrar();
3286
- this.actual = null;
3287
- this.salida.linea("La plataforma rechaz\xF3 tu sesi\xF3n (por ejemplo, porque cambiaste tu contrase\xF1a). Inicia sesi\xF3n de nuevo.");
3288
- this.actual = await this.entrar();
3289
- try {
3290
- return await operacion(this.actual.access_token);
3291
- } catch (otra) {
3292
- 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.");
3293
- throw otra;
3294
- }
3295
- }
3296
- }
3297
- /** `logout`: revoca el refresh token (RFC 7009) y borra lo local. */
3298
- async cerrar() {
3299
- const guardada = this.almacen.leer();
3300
- if (!guardada) return false;
3301
- await this.identidad.revocar(guardada.refresh_token);
3302
- this.almacen.borrar();
3303
- return true;
3304
- }
3305
- };
3306
-
3307
- // src/nucleo/contexto.ts
3308
- var sinSesionEnModoAgente = () => new ErrorCli(
3309
- "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.",
3310
- CODIGOS_DE_SALIDA.sesion,
3311
- { codigo: "SIN_SESION", comando: "redcumbre login" }
3312
- );
3313
- function crearContexto(opciones) {
3314
- const { salida, terminal, env } = opciones;
3315
- const destinos = servidores(env);
3316
- const proyecto = raizDelProyecto(opciones.cwd);
3317
- const carpeta = carpetaDeConfiguracion(env);
3318
- const identidad = identidadOidc();
3319
- let almacen = null;
3320
- let sesion = null;
3321
- const elAlmacen = () => almacen ??= elegirAlmacen(proyecto, env);
3322
- const abrir = async (destino) => {
3323
- const propio = env.REDCUMBRE_ABRIR;
3324
- if (propio) return abrirCon(propio, destino);
3325
- return abrirNavegadorDelSistema(destino);
3326
- };
3327
- return {
3328
- salida,
3329
- terminal,
3330
- cliente: new ClienteApi(destinos.api),
3331
- servidores: destinos,
3332
- carpetaConfiguracion: carpeta,
3333
- home: os2.homedir(),
3334
- cwd: opciones.cwd,
3335
- proyecto,
3336
- env,
3337
- version: opciones.version,
3338
- identidad,
3339
- ahora: () => /* @__PURE__ */ new Date(),
3340
- abrir,
3341
- almacen: elAlmacen,
3342
- async haySesion() {
3343
- return (await elAlmacen()).leer() !== null;
3344
- },
3345
- sesion() {
3346
- sesion ??= elAlmacen().then(
3347
- (a) => new Sesion(a, identidad, salida, async () => {
3348
- if (!terminal) throw sinSesionEnModoAgente();
3349
- return iniciarSesion(identidad, salida, {
3350
- sinNavegador: hayQueIrSinNavegador(opciones.sinNavegador, env),
3351
- abrirNavegador: abrir
3352
- });
3353
- })
3354
- );
3355
- return sesion;
3356
- }
3357
- };
3358
- }
3359
- async function abrirCon(programa2, destino) {
3360
- const { spawn: spawn4 } = await import("node:child_process");
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]];
3361
3601
  return new Promise((resolver) => {
3362
- const hijo = spawn4(programa2, [destino], { stdio: "ignore" });
3602
+ const hijo = spawn(comando2, argumentos, { stdio: "ignore", detached: true });
3363
3603
  hijo.once("error", () => resolver(false));
3364
- hijo.once("exit", (codigo) => resolver(codigo === 0));
3604
+ hijo.once("spawn", () => {
3605
+ hijo.unref();
3606
+ resolver(true);
3607
+ });
3365
3608
  });
3366
3609
  }
3367
-
3368
- // src/nucleo/skill.ts
3369
- import { createHash, randomBytes } from "node:crypto";
3370
- import fs10 from "node:fs";
3371
- import path10 from "node:path";
3372
- import { fileURLToPath as fileURLToPath2 } from "node:url";
3373
- var NOMBRE_SKILL = "redcumbre";
3374
- var MARCA_INICIO = "<!-- redcumbre:inicio -->";
3375
- var MARCA_FIN = "<!-- redcumbre:fin -->";
3376
- var sha256 = (texto2) => createHash("sha256").update(texto2).digest("hex");
3377
- function carpetaDeLaSkill(aqui = path10.dirname(fileURLToPath2(import.meta.url))) {
3378
- const candidatas = [path10.join(aqui, "skill"), path10.join(aqui, "..", "skill"), path10.join(aqui, "..", "..", "skill")];
3379
- for (const candidata of candidatas) {
3380
- if (fs10.existsSync(path10.join(candidata, NOMBRE_SKILL, "SKILL.md"))) return candidata;
3381
- }
3382
- 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, {
3383
- codigo: "PAQUETE_INCOMPLETO"
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."
3384
3617
  });
3385
- }
3386
- function contenidoEmpaquetado(fuente) {
3387
- const carpeta = fuente ?? carpetaDeLaSkill();
3388
- return fs10.readFileSync(path10.join(carpeta, NOMBRE_SKILL, "SKILL.md"), "utf8");
3389
- }
3390
- var LINEA_DE_VERSION = /^<!-- redcumbre-cli: (\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?) -->$/m;
3391
- var FRONTMATTER = /^---\r?\n[\s\S]*?\r?\n---\r?\n/;
3392
- var lineaDeVersion = (version) => `<!-- redcumbre-cli: ${version} -->`;
3393
- function contenidoParaInstalar(fuente, version) {
3394
- const frontmatter = fuente.match(FRONTMATTER);
3395
- if (!frontmatter) {
3396
- 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, {
3397
- codigo: "PAQUETE_INCOMPLETO"
3398
- });
3399
- }
3400
- const sinLinea = fuente.slice(frontmatter[0].length).replace(/^<!-- redcumbre-cli: [^\n]* -->\r?\n/, "");
3401
- return `${frontmatter[0]}${lineaDeVersion(version)}
3402
- ${sinLinea}`;
3403
- }
3404
- function versionDeLaSkill(texto2) {
3405
- return texto2.match(LINEA_DE_VERSION)?.[1] ?? null;
3406
- }
3407
- var CODIGOS_TRANSITORIOS_WINDOWS = /* @__PURE__ */ new Set(["EPERM", "EACCES", "EBUSY"]);
3408
- function esperarSincrono(ms) {
3409
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
3410
- }
3411
- function esErrorTransitorioDeWindows(error) {
3412
- const codigo = error?.code;
3413
- return typeof codigo === "string" && CODIGOS_TRANSITORIOS_WINDOWS.has(codigo);
3414
- }
3415
- function conReintentoEnWindows(operacion, opciones = {}) {
3416
- const { plataforma = process.platform, esperar = esperarSincrono, presupuestoMs = 2500 } = opciones;
3417
- let espera = 10;
3418
- let gastado = 0;
3419
- for (; ; ) {
3420
- try {
3421
- return operacion();
3422
- } catch (error) {
3423
- if (plataforma !== "win32" || !esErrorTransitorioDeWindows(error) || gastado >= presupuestoMs) throw error;
3424
- const ms = Math.min(espera, presupuestoMs - gastado);
3425
- esperar(ms);
3426
- gastado += ms;
3427
- espera = Math.min(espera * 2, 100);
3428
- }
3429
- }
3430
- }
3431
- function escribirAtomico(ruta, contenido) {
3432
- fs10.mkdirSync(path10.dirname(ruta), { recursive: true });
3433
- const temporal = `${ruta}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
3434
- try {
3435
- fs10.writeFileSync(temporal, contenido);
3436
- conReintentoEnWindows(() => fs10.renameSync(temporal, ruta));
3437
- } catch (error) {
3438
- fs10.rmSync(temporal, { force: true });
3439
- throw error;
3440
- }
3441
- }
3442
- function bloqueDeAgents() {
3443
- return [
3444
- MARCA_INICIO,
3445
- "## REDCUMBRE",
3446
- "",
3447
- "Este proyecto se integra con la API de REDCUMBRE por medio del CLI `redcumbre`. Antes de tocar la integraci\xF3n lee la",
3448
- "skill `redcumbre` (`.agents/skills/redcumbre/SKILL.md`). En resumen: busca la operaci\xF3n (`redcumbre buscar`), lee su",
3449
- "contrato (`redcumbre api describir`), pru\xE9bala con `--ensayo`, consulta las fichas (`redcumbre guia`) y verifica el",
3450
- "sitio (`redcumbre prueba verificar`). No leas ni imprimas `keys/`. Pasar a producci\xF3n lo confirma una persona.",
3451
- "H\xE1blale a la persona en espa\xF1ol, salvo que ella te escriba en otro idioma.",
3452
- MARCA_FIN
3453
- ].join("\n");
3454
- }
3455
- var rutaRegistroUsuario = (d) => path10.join(d.carpetaConfiguracion, "skill.json");
3456
- var rutaEstadoDelProyecto = (proyecto) => path10.join(proyecto, ".redcumbre", "estado.json");
3457
- function leerJson2(ruta) {
3458
- if (!fs10.existsSync(ruta)) return null;
3459
- let texto2;
3460
- try {
3461
- texto2 = conReintentoEnWindows(() => fs10.readFileSync(ruta, "utf8"));
3462
- } catch (error) {
3463
- if (esErrorTransitorioDeWindows(error)) throw error;
3464
- return null;
3465
- }
3618
+ const redirectUri = `http://127.0.0.1:${local.puerto}/callback`;
3466
3619
  try {
3467
- const dato = JSON.parse(texto2);
3468
- return dato && typeof dato === "object" && !Array.isArray(dato) ? dato : null;
3469
- } catch {
3470
- return null;
3471
- }
3472
- }
3473
- function escribirJson(ruta, dato) {
3474
- escribirAtomico(ruta, `${JSON.stringify(dato, null, 2)}
3475
- `);
3476
- }
3477
- function leerRegistroUsuario(d) {
3478
- return leerJson2(rutaRegistroUsuario(d)) ?? {};
3479
- }
3480
- function guardarRegistroUsuario(d, registro) {
3481
- escribirJson(rutaRegistroUsuario(d), registro);
3482
- }
3483
- function leerRegistroProyecto(proyecto) {
3484
- const estado2 = leerJson2(rutaEstadoDelProyecto(proyecto));
3485
- return estado2?.skill ?? {};
3486
- }
3487
- function guardarRegistroProyecto(proyecto, registro) {
3488
- const ruta = rutaEstadoDelProyecto(proyecto);
3489
- const estado2 = leerJson2(ruta) ?? {};
3490
- escribirJson(ruta, { ...estado2, skill: registro });
3491
- }
3492
- function objetivos(d) {
3493
- const lista2 = [
3494
- { id: "claude-usuario", archivo: path10.join(d.home, ".claude", "skills", NOMBRE_SKILL, "SKILL.md"), legible: `~/.claude/skills/${NOMBRE_SKILL}/SKILL.md` },
3495
- { id: "agents-usuario", archivo: path10.join(d.home, ".agents", "skills", NOMBRE_SKILL, "SKILL.md"), legible: `~/.agents/skills/${NOMBRE_SKILL}/SKILL.md` }
3496
- ];
3497
- if (d.proyecto) {
3498
- lista2.push(
3499
- { id: "claude-proyecto", archivo: path10.join(d.proyecto, ".claude", "skills", NOMBRE_SKILL, "SKILL.md"), legible: `.claude/skills/${NOMBRE_SKILL}/SKILL.md` },
3500
- { id: "agents-proyecto", archivo: path10.join(d.proyecto, ".agents", "skills", NOMBRE_SKILL, "SKILL.md"), legible: `.agents/skills/${NOMBRE_SKILL}/SKILL.md` }
3501
- );
3502
- }
3503
- return lista2;
3504
- }
3505
- var esDeUsuario = (id) => id.endsWith("-usuario");
3506
- function resumir2(rutas, quitada) {
3507
- let estado2 = "sin-cambios";
3508
- if (quitada) estado2 = "quitada";
3509
- else if (rutas.some((r) => r.accion === "editada")) estado2 = "editada";
3510
- else if (rutas.some((r) => r.accion === "reemplazada-editada")) estado2 = "reemplazada-editada";
3511
- else if (rutas.some((r) => r.accion === "instalada")) estado2 = "instalada";
3512
- else if (rutas.some((r) => r.accion === "actualizada")) estado2 = "actualizada";
3513
- return { estado: estado2, rutas };
3514
- }
3515
- var marcaDeTiempoDeLaCopia = (ahora) => ahora.toISOString().slice(0, 19).replace(/[-:]/g, "").replace("T", "-");
3516
- function guardarCopiaDeLoEditado(archivo, ahora) {
3517
- const base = `${archivo}.editada-${marcaDeTiempoDeLaCopia(ahora)}`;
3518
- for (let n = 1; n < 100; n++) {
3519
- const destino = n === 1 ? base : `${base}-${n}`;
3520
- try {
3521
- conReintentoEnWindows(() => fs10.copyFileSync(archivo, destino, fs10.constants.COPYFILE_EXCL));
3522
- return path10.resolve(destino);
3523
- } catch (error) {
3524
- if (error.code === "EEXIST") continue;
3525
- throw error;
3526
- }
3527
- }
3528
- throw new Error(`ya hay demasiadas copias de ${archivo} con la misma hora`);
3529
- }
3530
- var motivoDe2 = (error) => error instanceof Error ? error.message : String(error);
3531
- function reconciliar(archivo, nuevo, registrado, ahora) {
3532
- const hashNuevo = sha256(nuevo);
3533
- const existe = fs10.existsSync(archivo);
3534
- if (!existe) {
3535
- if (registrado) return { accion: "borrada", hash: null };
3536
- escribirAtomico(archivo, nuevo);
3537
- return { accion: "instalada", hash: hashNuevo };
3538
- }
3539
- const hashActual = sha256(conReintentoEnWindows(() => fs10.readFileSync(archivo)));
3540
- if (registrado === void 0) {
3541
- if (hashActual === hashNuevo) return { accion: "sin-cambios", hash: hashNuevo };
3542
- return reemplazarConCopia(archivo, nuevo, hashNuevo, ahora);
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();
3543
3631
  }
3544
- if (hashActual !== registrado) return hashActual === hashNuevo ? { accion: "sin-cambios", hash: hashNuevo } : reemplazarConCopia(archivo, nuevo, hashNuevo, ahora);
3545
- if (hashActual === hashNuevo) return { accion: "sin-cambios", hash: hashNuevo };
3546
- escribirAtomico(archivo, nuevo);
3547
- return { accion: "actualizada", hash: hashNuevo };
3548
3632
  }
3549
- function reemplazarConCopia(archivo, nuevo, hashNuevo, ahora) {
3550
- let copia;
3551
- try {
3552
- copia = guardarCopiaDeLoEditado(archivo, ahora);
3553
- } catch (error) {
3554
- return { accion: "editada", hash: null, error: motivoDe2(error) };
3555
- }
3556
- escribirAtomico(archivo, nuevo);
3557
- return { accion: "reemplazada-editada", hash: hashNuevo, copia };
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);
3558
3636
  }
3559
- var regexBloque = () => new RegExp(`${MARCA_INICIO.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[\\s\\S]*?${MARCA_FIN.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`);
3560
- function extraerBloque(texto2) {
3561
- return texto2.match(regexBloque())?.[0] ?? null;
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);
3562
3647
  }
3563
- function reconciliarAgents(archivo, registro) {
3564
- const bloque = bloqueDeAgents();
3565
- const hashBloque = sha256(bloque);
3566
- if (!fs10.existsSync(archivo)) {
3567
- if (registro) return { accion: "borrada", registro: null };
3568
- escribirAtomico(archivo, `${bloque}
3569
- `);
3570
- return { accion: "instalada", registro: { sha256: hashBloque, creado: true } };
3571
- }
3572
- const texto2 = conReintentoEnWindows(() => fs10.readFileSync(archivo, "utf8"));
3573
- const actual = extraerBloque(texto2);
3574
- if (actual === null) {
3575
- if (registro) return { accion: "borrada", registro: null };
3576
- const separador = texto2.length === 0 ? "" : texto2.endsWith("\n\n") ? "" : texto2.endsWith("\n") ? "\n" : "\n\n";
3577
- escribirAtomico(archivo, `${texto2}${separador}${bloque}
3578
- `);
3579
- return { accion: "instalada", registro: { sha256: hashBloque, creado: false } };
3580
- }
3581
- const hashActual = sha256(actual);
3582
- if (!registro) {
3583
- if (hashActual === hashBloque) return { accion: "sin-cambios", registro: { sha256: hashBloque, creado: false } };
3584
- return { accion: "editada", registro: null };
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
+ });
3585
3657
  }
3586
- if (hashActual !== registro.sha256) return { accion: "editada", registro: null };
3587
- if (hashActual === hashBloque) return { accion: "sin-cambios", registro: { ...registro, sha256: hashBloque } };
3588
- escribirAtomico(archivo, texto2.replace(regexBloque(), () => bloque));
3589
- return { accion: "actualizada", registro: { ...registro, sha256: hashBloque } };
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");
3590
3660
  }
3591
- function instalarSkill(opciones) {
3592
- const { destinos, bloqueAgents } = opciones;
3593
- const ahora = opciones.ahora ?? /* @__PURE__ */ new Date();
3594
- const nuevo = contenidoParaInstalar(contenidoEmpaquetado(opciones.fuente), opciones.version);
3595
- const usuario = leerRegistroUsuario(destinos);
3596
- const proyecto = destinos.proyecto ? leerRegistroProyecto(destinos.proyecto) : null;
3597
- const rutas = [];
3598
- for (const objetivo of objetivos(destinos)) {
3599
- const deUsuario = esDeUsuario(objetivo.id);
3600
- const registro = deUsuario ? usuario : proyecto;
3601
- if (usuario.quitada || registro.quitada) continue;
3602
- const previo = registro.rutas?.[objetivo.id]?.sha256;
3603
- const { accion, hash, copia, error } = reconciliar(objetivo.archivo, nuevo, previo, ahora);
3604
- rutas.push({ ruta: objetivo.legible, accion, ...copia ? { copia } : {}, ...error ? { error } : {} });
3605
- if (hash) {
3606
- registro.rutas = { ...registro.rutas ?? {}, [objetivo.id]: { sha256: hash } };
3607
- }
3608
- }
3609
- if (bloqueAgents && destinos.proyecto && proyecto && !usuario.quitada && !proyecto.quitada) {
3610
- const { accion, registro } = reconciliarAgents(path10.join(destinos.proyecto, "AGENTS.md"), proyecto.agents);
3611
- rutas.push({ ruta: "AGENTS.md", accion });
3612
- if (registro) proyecto.agents = registro;
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;
3613
3672
  }
3614
- if (!usuario.quitada && rutas.some((r) => r.ruta.startsWith("~"))) guardarRegistroUsuario(destinos, usuario);
3615
- if (destinos.proyecto && proyecto && !proyecto.quitada && rutas.some((r) => !r.ruta.startsWith("~"))) guardarRegistroProyecto(destinos.proyecto, proyecto);
3616
- return resumir2(rutas, rutas.length === 0 && Boolean(usuario.quitada || proyecto?.quitada));
3617
3673
  }
3618
- function quitarArchivo(archivo, registrado) {
3619
- if (!fs10.existsSync(archivo)) return null;
3620
- if (registrado === void 0 || sha256(conReintentoEnWindows(() => fs10.readFileSync(archivo))) !== registrado) return "editada";
3621
- fs10.rmSync(archivo);
3622
- const carpeta = path10.dirname(archivo);
3623
- if (fs10.readdirSync(carpeta).length === 0) fs10.rmdirSync(carpeta);
3624
- return "quitada";
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);
3625
3679
  }
3626
- function quitarSkill(opciones) {
3627
- const { destinos } = opciones;
3628
- const usuario = leerRegistroUsuario(destinos);
3629
- const proyecto = destinos.proyecto ? leerRegistroProyecto(destinos.proyecto) : null;
3630
- const rutas = [];
3631
- for (const objetivo of objetivos(destinos)) {
3632
- const registro = esDeUsuario(objetivo.id) ? usuario : proyecto;
3633
- const previo = registro.rutas?.[objetivo.id]?.sha256;
3634
- const accion = quitarArchivo(objetivo.archivo, previo);
3635
- if (accion) rutas.push({ ruta: objetivo.legible, accion });
3680
+ function borrarLoginPendiente(carpeta) {
3681
+ const ruta = rutaLoginPendiente(carpeta);
3682
+ const habia = fs10.existsSync(ruta);
3683
+ fs10.rmSync(ruta, { force: true });
3684
+ return habia;
3685
+ }
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");
3636
3711
  }
3637
- if (destinos.proyecto && proyecto) {
3638
- const archivo = path10.join(destinos.proyecto, "AGENTS.md");
3639
- if (fs10.existsSync(archivo)) {
3640
- const texto2 = conReintentoEnWindows(() => fs10.readFileSync(archivo, "utf8"));
3641
- const bloque = extraerBloque(texto2);
3642
- if (bloque !== null) {
3643
- if (!proyecto.agents || sha256(bloque) !== proyecto.agents.sha256) {
3644
- rutas.push({ ruta: "AGENTS.md", accion: "editada" });
3645
- } else {
3646
- const resto = texto2.replace(regexBloque(), "").replace(/\n{3,}/g, "\n\n");
3647
- if (proyecto.agents.creado && resto.trim() === "") fs10.rmSync(archivo);
3648
- else escribirAtomico(archivo, resto.replace(/^\n+/, "").replace(/\n*$/, "\n"));
3649
- rutas.push({ ruta: "AGENTS.md", accion: "quitada" });
3650
- }
3651
- }
3652
- }
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";
3653
3717
  }
3654
- guardarRegistroUsuario(destinos, { quitada: true, rutas: {} });
3655
- if (destinos.proyecto && proyecto) guardarRegistroProyecto(destinos.proyecto, { quitada: true, rutas: {}, agents: void 0 });
3656
- return { estado: "quitada", rutas };
3718
+ if (desenlace.estado !== "pendiente") borrarLoginPendiente(carpeta);
3719
+ throw errorDelDesenlace(desenlace.estado);
3657
3720
  }
3658
- function renovarSkill(opciones) {
3659
- const { destinos, version } = opciones;
3660
- const ahora = opciones.ahora ?? /* @__PURE__ */ new Date();
3661
- const usuario = leerRegistroUsuario(destinos);
3662
- const proyecto = destinos.proyecto ? leerRegistroProyecto(destinos.proyecto) : null;
3663
- const rutas = [];
3664
- const cambiosUsuario = {};
3665
- const cambiosProyecto = {};
3666
- let nuevo = null;
3667
- for (const objetivo of objetivos(destinos)) {
3668
- const deUsuario = esDeUsuario(objetivo.id);
3669
- const registro = deUsuario ? usuario : proyecto;
3670
- if (usuario.quitada || registro.quitada) continue;
3671
- if (!fs10.existsSync(objetivo.archivo)) continue;
3672
- const actual = conReintentoEnWindows(() => fs10.readFileSync(objetivo.archivo, "utf8"));
3673
- const instalada2 = versionDeLaSkill(actual);
3674
- if (instalada2 !== null && compararVersiones(version, instalada2) < 0) {
3675
- rutas.push({ ruta: objetivo.legible, accion: "mas-nueva", instalada: instalada2 });
3676
- continue;
3677
- }
3678
- nuevo ??= contenidoParaInstalar(contenidoEmpaquetado(opciones.fuente), version);
3679
- const hashNuevo = sha256(nuevo);
3680
- const hashActual = sha256(actual);
3681
- const registrado = (registro.rutas ?? {})[objetivo.id]?.sha256;
3682
- if (hashActual === hashNuevo) {
3683
- if (registrado !== hashNuevo) (deUsuario ? cambiosUsuario : cambiosProyecto)[objetivo.id] = hashNuevo;
3684
- rutas.push({ ruta: objetivo.legible, accion: "al-dia", instalada: version });
3685
- continue;
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;
3727
+ }
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;
3734
+ }
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;
3686
3742
  }
3687
- const editada = registrado === void 0 || hashActual !== registrado;
3688
- if (instalada2 !== null && compararVersiones(version, instalada2) === 0 && !editada) {
3689
- rutas.push({ ruta: objetivo.legible, accion: "al-dia", instalada: instalada2 });
3690
- 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();
3691
3751
  }
3692
- let copia;
3693
- if (editada) {
3752
+ return this.actual.access_token;
3753
+ }
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();
3694
3767
  try {
3695
- copia = guardarCopiaDeLoEditado(objetivo.archivo, ahora);
3696
- } catch (error) {
3697
- rutas.push({ ruta: objetivo.legible, accion: "desactualizada", instalada: instalada2, error: motivoDe2(error) });
3698
- continue;
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;
3699
3772
  }
3700
3773
  }
3701
- escribirAtomico(objetivo.archivo, nuevo);
3702
- (deUsuario ? cambiosUsuario : cambiosProyecto)[objetivo.id] = hashNuevo;
3703
- rutas.push(copia ? { ruta: objetivo.legible, accion: "reemplazada-editada", instalada: instalada2, copia } : { ruta: objetivo.legible, accion: "renovada", instalada: instalada2 });
3704
- }
3705
- if (Object.keys(cambiosUsuario).length > 0) {
3706
- const vigente = leerRegistroUsuario(destinos);
3707
- if (!vigente.quitada) guardarRegistroUsuario(destinos, { ...vigente, rutas: { ...vigente.rutas ?? {}, ...aRutas(cambiosUsuario) } });
3708
- }
3709
- if (Object.keys(cambiosProyecto).length > 0 && destinos.proyecto) {
3710
- const vigente = leerRegistroProyecto(destinos.proyecto);
3711
- if (!vigente.quitada) guardarRegistroProyecto(destinos.proyecto, { ...vigente, rutas: { ...vigente.rutas ?? {}, ...aRutas(cambiosProyecto) } });
3712
3774
  }
3713
- return { version, rutas };
3714
- }
3715
- var aRutas = (cambios) => Object.fromEntries(Object.entries(cambios).map(([id, sha]) => [id, { sha256: sha }]));
3716
- var COMANDO_SKILL_RENOVAR = "redcumbre skill renovar";
3717
- function avisoDeRenovacion(r, version) {
3718
- if (r.accion === "renovada") return `Renov\xE9 la skill de REDCUMBRE en ${r.ruta} a la de la versi\xF3n ${version}.`;
3719
- if (r.accion === "reemplazada-editada") return `Reemplac\xE9 la skill de REDCUMBRE en ${r.ruta} por la de la versi\xF3n ${version}. Tu versi\xF3n editada de la skill qued\xF3 en ${r.copia}.`;
3720
- if (r.accion === "desactualizada") {
3721
- return `La skill de REDCUMBRE 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.`;
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;
3722
3782
  }
3723
- 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
+ };
3724
3836
  }
3725
- function renovarSkillAlCorrer(opciones) {
3726
- try {
3727
- const informe = renovarSkill({ destinos: opciones.destinos, version: opciones.version, ahora: opciones.ahora });
3728
- for (const r of informe.rutas.filter((x) => x.accion === "renovada" || x.accion === "reemplazada-editada")) opciones.avisar(avisoDeRenovacion(r, informe.version));
3729
- const desactualizadas = informe.rutas.filter((x) => x.accion === "desactualizada");
3730
- if (desactualizadas.length === 0) return;
3731
- const hoy = opciones.ahora.toISOString().slice(0, 10);
3732
- const usuario = leerRegistroUsuario(opciones.destinos);
3733
- if (usuario.avisoDesactualizadaEn === hoy) return;
3734
- for (const r of desactualizadas) opciones.avisar(avisoDeRenovacion(r, informe.version));
3735
- guardarRegistroUsuario(opciones.destinos, { ...usuario, avisoDesactualizadaEn: hoy });
3736
- } catch (error) {
3737
- opciones.depurar?.(`no pude revisar la skill instalada (${error instanceof Error ? error.message : String(error)}); el comando sigue`);
3738
- }
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
+ });
3739
3844
  }
3740
3845
 
3741
3846
  // src/nucleo/terminal.ts
@@ -3893,10 +3998,10 @@ function renovarLaSkill(ctx) {
3893
3998
  const informe = renovarSkill({ destinos: { carpetaConfiguracion: ctx.carpetaConfiguracion, home: ctx.home, proyecto }, version: ctx.version, ahora: ctx.ahora() });
3894
3999
  for (const r of informe.rutas) {
3895
4000
  const aviso = avisoDeRenovacion(r, informe.version);
3896
- if (r.accion === "renovada") salida.linea(`\u2713 ${aviso}`);
4001
+ if (r.accion === "renovada" || r.accion === "instalada") salida.linea(`\u2713 ${aviso}`);
3897
4002
  else if (r.accion === "reemplazada-editada") {
3898
- salida.linea(`\u2713 Reemplac\xE9 la skill de REDCUMBRE en ${r.ruta} por la de la versi\xF3n ${informe.version}.`);
3899
- salida.aviso(`Tu versi\xF3n editada de la skill qued\xF3 en ${r.copia}.`);
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}.`);
3900
4005
  } else if (aviso) salida.aviso(aviso);
3901
4006
  }
3902
4007
  return { version: informe.version, rutas: informe.rutas };
@@ -3938,7 +4043,7 @@ async function correr(globales, accion, opciones = {}) {
3938
4043
  const salida = crearSalida(agente);
3939
4044
  const terminal = agente ? null : crearTerminal(process.stdin, process.stdout);
3940
4045
  try {
3941
- const ctx = crearContexto({ salida, terminal, sinNavegador: Boolean(globales.sinNavegador), cwd: process.cwd(), env: process.env, version: "0.6.7" });
4046
+ const ctx = crearContexto({ salida, terminal, sinNavegador: Boolean(globales.sinNavegador), cwd: process.cwd(), env: process.env, version: "0.6.8" });
3942
4047
  await exigirVersionMinima({
3943
4048
  version: ctx.version,
3944
4049
  env: process.env,
@@ -5081,8 +5186,8 @@ async function init(ctx, opciones, entorno = entornoDeActualizacion(ctx)) {
5081
5186
  }
5082
5187
  for (const r of skill.rutas) {
5083
5188
  if (r.accion === "reemplazada-editada") {
5084
- salida.linea(`\u2713 Reemplac\xE9 la skill de REDCUMBRE en ${r.ruta} por la de la versi\xF3n ${ctx.version}.`);
5085
- salida.aviso(`Tu versi\xF3n editada de la skill qued\xF3 en ${r.copia}.`);
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}.`);
5086
5191
  }
5087
5192
  if (r.accion === "editada") {
5088
5193
  salida.aviso(
@@ -6288,10 +6393,10 @@ function instalarSkillDeUsuario(ctx) {
6288
6393
  try {
6289
6394
  const informe = instalarSkill({ destinos: { carpetaConfiguracion: ctx.carpetaConfiguracion, home: ctx.home }, bloqueAgents: false, version: ctx.version, ahora: ctx.ahora() });
6290
6395
  for (const r of informe.rutas) {
6291
- if (r.accion === "instalada") ctx.salida.linea(`\u2713 Instal\xE9 la skill de REDCUMBRE en ${r.ruta}.`);
6396
+ if (r.accion === "instalada") ctx.salida.linea(`\u2713 Instal\xE9 ${nombreDeLoInstalado(r.ruta)} en ${r.ruta}.`);
6292
6397
  if (r.accion === "reemplazada-editada") {
6293
- ctx.salida.linea(`\u2713 Reemplac\xE9 la skill de REDCUMBRE en ${r.ruta} por la de la versi\xF3n ${ctx.version}.`);
6294
- ctx.salida.aviso(`Tu versi\xF3n editada de la skill qued\xF3 en ${r.copia}.`);
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}.`);
6295
6400
  }
6296
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.`);
6297
6402
  }
@@ -6360,10 +6465,10 @@ async function skillRenovar(ctx, _opciones) {
6360
6465
  const informe = renovarSkill({ destinos, version: ctx.version, ahora: ctx.ahora() });
6361
6466
  for (const r of informe.rutas) {
6362
6467
  const aviso = avisoDeRenovacion(r, informe.version);
6363
- if (r.accion === "renovada") salida.linea(`\u2713 ${aviso}`);
6468
+ if (r.accion === "renovada" || r.accion === "instalada") salida.linea(`\u2713 ${aviso}`);
6364
6469
  else if (r.accion === "reemplazada-editada") {
6365
- salida.linea(`\u2713 Reemplac\xE9 la skill de REDCUMBRE en ${r.ruta} por la de la versi\xF3n ${informe.version}.`);
6366
- salida.aviso(`Tu versi\xF3n editada de la skill qued\xF3 en ${r.copia}.`);
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}.`);
6367
6472
  } else if (aviso) salida.aviso(aviso);
6368
6473
  }
6369
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).");
@@ -6390,7 +6495,7 @@ function errorDeUsoEnEspanol(mensaje) {
6390
6495
  }
6391
6496
  var TITULOS_AYUDA = { "Usage:": "Uso:", "Options:": "Opciones:", "Commands:": "Comandos:", "Arguments:": "Argumentos:" };
6392
6497
  var sumar = (valor, anteriores) => [...anteriores, valor];
6393
- 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.7", "-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)}
6394
6499
  `) }).exitOverride((error) => {
6395
6500
  if (error.code === "commander.helpDisplayed" || error.code === "commander.version" || error.code === "commander.help") process.exit(0);
6396
6501
  if (process.argv.includes("--json")) {