nexakit 0.8.2 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -0
- package/assets/runtime/package-lock.json +2 -2
- package/package.json +1 -1
- package/skills/elegir-modelo/SKILL.md +12 -3
- package/skills/elegir-modelo/modelos.mjs +3 -1
- package/src/ahorro-command.js +52 -5
- package/src/codex-audit.js +218 -0
- package/src/codex-auto-output.js +90 -0
- package/src/codex-command.js +173 -0
- package/src/codex-compare.js +67 -0
- package/src/codex-events.js +122 -0
- package/src/codex-hook.js +69 -0
- package/src/codex-output.js +223 -0
- package/src/codex-pre-tool.js +75 -0
- package/src/codex-recommendation.js +92 -0
- package/src/codex-routing.js +91 -0
- package/src/codex-setup.js +72 -0
- package/src/codex-team.js +262 -0
- package/src/codex-usage.js +181 -0
- package/src/level-agents.js +1 -1
- package/src/model-command.js +25 -9
- package/src/toolkit-cli.js +3 -0
package/README.md
CHANGED
|
@@ -40,6 +40,10 @@ npx nexakit setup --reponer <skill> --apply # Devolver una skill global que qui
|
|
|
40
40
|
~/.nexakit/nexakit revision --disponibles --principal <ia> # Ver IA revisoras certificadas
|
|
41
41
|
~/.nexakit/nexakit modelo # Ver catálogo real de modelos y esfuerzos
|
|
42
42
|
~/.nexakit/nexakit ahorro # Cuánta salida de comandos recortó nexakit-ahorro
|
|
43
|
+
~/.nexakit/nexakit codex auditar # Revisar contexto y recomendaciones de Codex
|
|
44
|
+
~/.nexakit/nexakit codex agentes # Ver los cuatro niveles y seis especialistas de Codex
|
|
45
|
+
~/.nexakit/nexakit codex consumo # Contadores registrados por los hooks de Codex
|
|
46
|
+
~/.nexakit/nexakit codex recomendar --tarea "Escribe pruebas para el parser" # Modelo y esfuerzo sugeridos
|
|
43
47
|
~/.nexakit/nexakit lecciones # Correcciones, lecciones guardadas y pendientes
|
|
44
48
|
npx nexakit memoria allow-dir <bóveda> --apply # Permitir a Claude Code abrir la memoria desde el proyecto
|
|
45
49
|
```
|
|
@@ -65,6 +69,16 @@ El catálogo incluido contiene **10 skills** con revisión de origen y hashes SH
|
|
|
65
69
|
|
|
66
70
|
## Más herramientas
|
|
67
71
|
|
|
72
|
+
**Codex:** `nexakit codex` audita contexto, prepara la barra nativa y los hooks de
|
|
73
|
+
medición y recomendaciones visibles, recorta salidas con un ejecutor explícito
|
|
74
|
+
y compara muestras de consumo. La preparación
|
|
75
|
+
muestra una vista previa; la activación se revisa por separado y respeta tu
|
|
76
|
+
configuración. [Guía de ahorro y consumo](docs/guias/codex-ahorro.md).
|
|
77
|
+
|
|
78
|
+
`nexakit codex agentes` prepara el equipo nativo: cuatro niveles y seis
|
|
79
|
+
especialistas con modelos del catálogo local, vista previa y actualización
|
|
80
|
+
con respaldos. [Equipo y delegación en Codex](docs/guias/codex-agentes.md).
|
|
81
|
+
|
|
68
82
|
Los mods de Claude Code se instalan *dentro* de Claude Code: `/plugin marketplace add Jcabr3ra1/nexakit` y luego `/plugin install <nombre>@agent-toolkit` para `niveles`, `nexakit-modelo`, `nexakit-sesion`, `nexakit-ahorro`, `nexakit-lecciones` y `nexakit-guardarrailes` ([paso 7 de la guía](docs/guias/guia-de-comandos.md#7-instala-los-plugins-y-mods-solo-claude-code)).
|
|
69
83
|
|
|
70
84
|
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nexakit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "nexakit",
|
|
9
|
-
"version": "0.
|
|
9
|
+
"version": "0.9.0",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@modelcontextprotocol/client": "^2.4.0",
|
package/package.json
CHANGED
|
@@ -31,13 +31,22 @@ La elección se hace por **papel**, no por nombres fijos que caducan:
|
|
|
31
31
|
| Papel | Cuándo usarlo | Cómo reconocerlo en `modelos.mjs` | Ejemplo con fecha (a 2026-11: usar solo lo que devuelva el script) |
|
|
32
32
|
| --- | --- | --- | --- |
|
|
33
33
|
| **ligero** | Solo comandos y cambios mecánicos, ediciones precisas o preguntas sobre código ya en contexto | `papel: ligero`, descripción *fast and affordable / lightweight / easier tasks* o familias `haiku`, `luna`, `flash` | a 2026-11: Claude `haiku`, Codex `gpt-6-luna`, Antigravity `gemini-3.8-flash-*` |
|
|
34
|
-
| **uso diario** | Implementar con un diseño claro, el trabajo habitual de programación | `papel: uso diario`, descripción *workhorse / everyday / balanced* o familias `sonnet`, `sol`, `terra` | a 2026-11: Claude `sonnet`, Codex `gpt-6.1-sol` o `gpt-6.1-terra` |
|
|
35
|
-
| **el más capaz** | Diseño, bugs sutiles y ambigüedad, dominios nuevos o arquitectura | `papel: el más capaz`, descripción *frontier / most demanding* o familias `opus`, `astra`, `argon` | a 2026-11: Claude `opus` (o `opusplan`), Codex `gpt-6-astra`, Antigravity `gemini-4-argon-*` |
|
|
34
|
+
| **uso diario** | Implementar con un diseño claro, el trabajo habitual de programación | `papel: uso diario`, descripción *workhorse / everyday / balanced* o familias `sonnet`, `sol`, `terra`, `hydrogen` | a 2026-11: Claude `sonnet`, Codex `gpt-6.1-sol` o `gpt-6.1-terra`, Antigravity `gemini-4-hydrogen-*` |
|
|
35
|
+
| **el más capaz** | Diseño, bugs sutiles y ambigüedad, dominios nuevos o arquitectura | `papel: el más capaz`, descripción *frontier / most demanding* o familias `opus`, `astra`, `argon`, `carbon` | a 2026-11: Claude `opus` (o `opusplan`), Codex `gpt-6-astra`, Antigravity `gemini-4-argon-*` o `gemini-4-carbon-*` |
|
|
36
36
|
|
|
37
37
|
- **Modelos nuevos y clasificación por familia:** entran modelos nuevos con frecuencia (por ejemplo, `gpt-6.1-terra`, que llega sin descripción útil). Si un modelo no tiene una descripción que indique su papel, `modelos.mjs` lo clasifica por su familia (`luna`, `terra`, `sol`, `astra`, `flash`, `argon`, `haiku`, `sonnet`, `opus`…) usando la descripción de la generación anterior de esa misma familia. Si no hay generación anterior ni familia conocida, queda marcado como `sin clasificar`: en ese caso, **pregunta al usuario en vez de adivinar**.
|
|
38
38
|
- **Generaciones pasadas:** los modelos marcados con `papel: anterior` (*older* / *previous generation*) no se recomiendan salvo que el usuario los pida expresamente.
|
|
39
39
|
- **Límites y cuota:** un aviso de límite o de cuota nunca baja el modelo sin decírselo al usuario. Si una cuenta se acerca al límite o agota cuota, informa al usuario y espera su decisión antes de pasar a otro modelo o a otra IA.
|
|
40
40
|
|
|
41
|
+
### Elegir Gemini en Antigravity
|
|
42
|
+
|
|
43
|
+
- **Flash 3.8** con `low` para consultas breves o cambios mecánicos y con `medium` para trabajo rutinario si la cuenta ofrece esa variante. [Gemini 3.8 Flash](https://antigravity.google/blog/gemini-3-8-flash-in-google-antigravity/)
|
|
44
|
+
- **Hydrogen** con `low` para iterar rápido, `medium` para implementar con un diseño claro y `high` (el predeterminado del modelo) para depurar, escribir pruebas o verificar cambios. Reserva `xhigh` para una tarea de implementación exigente que requiera más razonamiento dentro de la misma familia. [Gemini 4 Hydrogen](https://antigravity.google/blog/gemini-4-hydrogen-in-google-antigravity)
|
|
45
|
+
- **Argon** con `medium` para investigación o análisis con alcance definido y `high` para arquitectura, migraciones o depuración con dependencias difíciles. [Gemini 4 Argon](https://antigravity.google/blog/gemini-4-argon-in-google-antigravity)
|
|
46
|
+
- **Carbon** para auditorías críticas, problemas abiertos y trabajo largo de alto riesgo. Usa `high` para una verificación profunda y `medium` si la parte a resolver ya está acotada. Comprueba las variantes de la cuenta antes de recomendarlo. [Gemini 4 Carbon](https://antigravity.google/blog/gemini-4-carbon-in-google-antigravity)
|
|
47
|
+
|
|
48
|
+
Estas son pautas de uso. `agy models` determina qué pares de modelo y esfuerzo están disponibles. [Esfuerzo en Antigravity CLI](https://antigravity.google/docs/cli/commands/effort/)
|
|
49
|
+
|
|
41
50
|
## 4. Cambiar a mitad de sesión cuesta caché
|
|
42
51
|
|
|
43
52
|
Cada modelo tiene su propia caché: tras un `/model`, el turno siguiente relee todo el historial sin ella. Ese turno puede costar más de lo que se ahorra con el cambio, y más cuanto más contexto haya. Cambiar el esfuerzo **no** rompe la caché en Claude 5.x con suscripción o clave de API; en Bedrock, Google Cloud o una pasarela, sí la rompe.
|
|
@@ -86,7 +95,7 @@ Debajo, una línea por IA con cómo cambiarlo y comprobarlo:
|
|
|
86
95
|
|
|
87
96
|
- **Claude:** `/model <alias>` y `/effort <nivel>`; se comprueba con `/effort status`. Si el script avisa de `CLAUDE_CODE_EFFORT_LEVEL`, esa variable manda.
|
|
88
97
|
- **Codex:** `/model` (modelo y esfuerzo); se comprueba con `/status`.
|
|
89
|
-
- **Antigravity:** `/model`
|
|
98
|
+
- **Antigravity:** selecciona con `/model` y `/effort`, o ejecuta `agy --model <id>` con la variante elegida. Comprueba la variante activa en el selector de la sesión.
|
|
90
99
|
|
|
91
100
|
Si lo guardado ya coincide, dilo en una línea y no pidas cambios. Lo que el script lee de archivos es lo guardado, no la sesión abierta: no lo presentes como comprobado.
|
|
92
101
|
|
|
@@ -20,8 +20,10 @@ const FAMILY_ROLES = Object.freeze({
|
|
|
20
20
|
terra: 'uso diario',
|
|
21
21
|
sol: 'uso diario',
|
|
22
22
|
sonnet: 'uso diario',
|
|
23
|
+
hydrogen: 'uso diario',
|
|
23
24
|
astra: 'el más capaz',
|
|
24
25
|
argon: 'el más capaz',
|
|
26
|
+
carbon: 'el más capaz',
|
|
25
27
|
opus: 'el más capaz'
|
|
26
28
|
});
|
|
27
29
|
const roleFromDescription = (description = '') => {
|
|
@@ -102,7 +104,7 @@ if (missing) {
|
|
|
102
104
|
out(`- ${id.trim()} · ${label.trim()} · papel: ${role}`);
|
|
103
105
|
}
|
|
104
106
|
}
|
|
105
|
-
out('El esfuerzo
|
|
107
|
+
out('El id indica el esfuerzo cuando el modelo ofrece variantes: -low, -medium, -high, -xhigh o -max. Comprueba el modelo y el esfuerzo activos con /model y /effort dentro de agy.');
|
|
106
108
|
}
|
|
107
109
|
|
|
108
110
|
process.stdout.write(lines.join('\n') + '\n');
|
package/src/ahorro-command.js
CHANGED
|
@@ -1,8 +1,52 @@
|
|
|
1
1
|
import fs from 'node:fs/promises';
|
|
2
|
+
import { constants } from 'node:fs';
|
|
2
3
|
import os from 'node:os';
|
|
3
4
|
import path from 'node:path';
|
|
4
5
|
|
|
5
6
|
const DIA_MS = 24 * 60 * 60 * 1000;
|
|
7
|
+
const MAX_REGISTRO_BYTES = 1024 * 1024;
|
|
8
|
+
|
|
9
|
+
async function directorioSeguro(target) {
|
|
10
|
+
const absolute = path.resolve(target);
|
|
11
|
+
let current = path.parse(absolute).root;
|
|
12
|
+
for (const part of absolute.slice(current.length).split(path.sep).filter(Boolean)) {
|
|
13
|
+
current = path.join(current, part);
|
|
14
|
+
const stat = await fs.lstat(current);
|
|
15
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error('Directorio inseguro');
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async function leerFuente(target) {
|
|
20
|
+
let handle;
|
|
21
|
+
try {
|
|
22
|
+
await directorioSeguro(path.dirname(target));
|
|
23
|
+
const before = await fs.lstat(target);
|
|
24
|
+
if (!before.isFile() || before.nlink !== 1 || before.size > MAX_REGISTRO_BYTES) return [];
|
|
25
|
+
handle = await fs.open(target, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
|
|
26
|
+
const opened = await handle.stat();
|
|
27
|
+
if (!opened.isFile() || opened.nlink !== 1 || opened.size > MAX_REGISTRO_BYTES ||
|
|
28
|
+
opened.dev !== before.dev || opened.ino !== before.ino) return [];
|
|
29
|
+
// Un byte adicional detecta crecimiento sin una lectura sin límite.
|
|
30
|
+
const buffer = Buffer.alloc(MAX_REGISTRO_BYTES + 1);
|
|
31
|
+
let size = 0;
|
|
32
|
+
while (size < buffer.length) {
|
|
33
|
+
const { bytesRead } = await handle.read(buffer, size, buffer.length - size, size);
|
|
34
|
+
if (!bytesRead) break;
|
|
35
|
+
size += bytesRead;
|
|
36
|
+
}
|
|
37
|
+
const after = await handle.stat();
|
|
38
|
+
await directorioSeguro(path.dirname(target));
|
|
39
|
+
const final = await fs.lstat(target);
|
|
40
|
+
if (size > MAX_REGISTRO_BYTES || after.nlink !== 1 || !final.isFile() || final.nlink !== 1 ||
|
|
41
|
+
final.dev !== opened.dev || final.ino !== opened.ino) return [];
|
|
42
|
+
return leerRegistros(buffer.subarray(0, size).toString('utf8'));
|
|
43
|
+
} catch {
|
|
44
|
+
// Una fuente ausente o insegura no impide consultar la otra.
|
|
45
|
+
return [];
|
|
46
|
+
} finally {
|
|
47
|
+
await handle?.close();
|
|
48
|
+
}
|
|
49
|
+
}
|
|
6
50
|
|
|
7
51
|
function resumir(registros) {
|
|
8
52
|
const caracteres = registros.reduce((suma, r) => suma + (r.antes - r.despues), 0);
|
|
@@ -35,13 +79,16 @@ export async function runAhorroCommand(argv, { out, err }, options = {}) {
|
|
|
35
79
|
}
|
|
36
80
|
const home = options.homeDirectory ?? os.homedir();
|
|
37
81
|
const ahora = options.now ?? Date.now();
|
|
38
|
-
|
|
82
|
+
const fuentes = new Set([path.resolve(home, '.nexakit', 'ahorro.jsonl')]);
|
|
39
83
|
try {
|
|
40
|
-
|
|
84
|
+
// El temporal del sistema puede ser un alias (por ejemplo /var en macOS).
|
|
85
|
+
const temporal = await fs.realpath(options.tempDirectory ?? os.tmpdir());
|
|
86
|
+
fuentes.add(path.join(temporal, `nexakit-codex-${process.getuid?.() ?? 'user'}`, '.nexakit', 'ahorro.jsonl'));
|
|
41
87
|
} catch {
|
|
42
|
-
|
|
88
|
+
// No se crean directorios al consultar métricas.
|
|
43
89
|
}
|
|
44
|
-
const registros =
|
|
90
|
+
const registros = [];
|
|
91
|
+
for (const fuente of fuentes) registros.push(...await leerFuente(fuente));
|
|
45
92
|
const resumen = {
|
|
46
93
|
ultimos7Dias: resumir(registros.filter((r) => r.fecha >= ahora - 7 * DIA_MS)),
|
|
47
94
|
total: resumir(registros),
|
|
@@ -52,7 +99,7 @@ export async function runAhorroCommand(argv, { out, err }, options = {}) {
|
|
|
52
99
|
}
|
|
53
100
|
if (registros.length === 0) {
|
|
54
101
|
await out(
|
|
55
|
-
'Aún no hay recortes registrados.
|
|
102
|
+
'Aún no hay recortes registrados. Los escriben el mod nexakit-ahorro de Claude y nexakit codex ejecutar al recortar salidas largas.\n',
|
|
56
103
|
);
|
|
57
104
|
return 0;
|
|
58
105
|
}
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
5
|
+
import { parseTOML, getStaticTOMLValue } from 'toml-eslint-parser';
|
|
6
|
+
|
|
7
|
+
const MAX_FILE = 256 * 1024;
|
|
8
|
+
const MAX_METADATA = 8192;
|
|
9
|
+
const MAX_ENTRIES = 512;
|
|
10
|
+
const inside = (root, file) => {
|
|
11
|
+
const relative = path.relative(root, file);
|
|
12
|
+
return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
|
|
13
|
+
};
|
|
14
|
+
const countTables = value => value && typeof value === 'object' && !Array.isArray(value) ? Object.keys(value).length : 0;
|
|
15
|
+
|
|
16
|
+
function selectSettings(config) {
|
|
17
|
+
const settings = {};
|
|
18
|
+
// Only short, conventional model identifiers and known enum values are exposed.
|
|
19
|
+
if (typeof config.model === 'string' && /^(?:gpt-|o[1-9]|codex-)[a-z0-9.-]{1,70}$/.test(config.model)) settings.model = config.model;
|
|
20
|
+
if (['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'].includes(config.model_reasoning_effort)) settings.model_reasoning_effort = config.model_reasoning_effort;
|
|
21
|
+
if (['fast', 'flex', 'standard', 'default', 'auto'].includes(config.service_tier)) settings.service_tier = config.service_tier;
|
|
22
|
+
const integer = value => Number.isSafeInteger(value) && value >= 0;
|
|
23
|
+
if (integer(config.tool_output_token_limit)) settings.tool_output_token_limit = config.tool_output_token_limit;
|
|
24
|
+
if (integer(config.skills?.max_context_tokens)) settings.skills = { max_context_tokens: config.skills.max_context_tokens };
|
|
25
|
+
if (integer(config.agents?.max_concurrent_threads_per_session)) settings.agents = { max_concurrent_threads_per_session: config.agents.max_concurrent_threads_per_session };
|
|
26
|
+
return settings;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Bounded local audit: only whitelisted settings and validated relative locators are exposed. */
|
|
30
|
+
export function auditCodex({ projectRoot = process.cwd(), codexHome, homeDirectory = os.homedir() } = {}) {
|
|
31
|
+
codexHome = path.resolve(codexHome ?? process.env.CODEX_HOME ?? path.join(homeDirectory, '.codex'));
|
|
32
|
+
projectRoot = path.resolve(projectRoot);
|
|
33
|
+
homeDirectory = path.resolve(homeDirectory);
|
|
34
|
+
const report = {
|
|
35
|
+
findings: [],
|
|
36
|
+
coverage: {
|
|
37
|
+
partial: true,
|
|
38
|
+
inspected: ['codex-home-config', 'skill-catalog-metadata', 'user-project-instructions'],
|
|
39
|
+
notInspected: ['remote-plugins', 'profiles', 'project-config', 'ancestor-instructions'],
|
|
40
|
+
message: 'Auditoría parcial: no se inspeccionan plugins remotos, perfiles, configuración del proyecto ni instrucciones de ancestros; los enlaces externos se omiten.',
|
|
41
|
+
},
|
|
42
|
+
summary: { skills: 0, skillBytes: 0, metadataBytes: 0, instructionFiles: 0, instructionBytes: 0, mcpServers: 0, plugins: 0, omitted: 0 },
|
|
43
|
+
recommendations: [
|
|
44
|
+
{ code: 'CATALOG_BUDGET', setting: 'skills.max_context_tokens', message: 'Usar el presupuesto nativo del catálogo de skills; antes de reducirlo, comprobar advertencias, descripciones y omisiones.' },
|
|
45
|
+
{ code: 'OUTPUT_BUDGET', setting: 'tool_output_token_limit', proposedValue: 4000, officialDefault: false, message: 'Propuesta local: evaluar 4000 tokens por salida y recuperar el log completo cuando haga falta; no es un valor predeterminado oficial.' },
|
|
46
|
+
{ code: 'EFFORT', message: 'Elegir esfuerzo proporcional a la tarea y comprobar calidad antes de reducirlo; no se modifica la configuración.' },
|
|
47
|
+
{ code: 'DELEGATION', message: 'Delegar tareas independientes con encargos breves y limitar la concurrencia según la tarea; no se modifica la configuración.' },
|
|
48
|
+
{ code: 'MCP', message: 'Revisar los MCP y plugins habilitados y habilitar solo los necesarios para la tarea; no se cambia ninguno.' },
|
|
49
|
+
],
|
|
50
|
+
settings: {},
|
|
51
|
+
};
|
|
52
|
+
const finding = (code, message, fields = {}) => report.findings.push({ code, severity: code.endsWith('MISSING') ? 'info' : 'warning', message, ...fields });
|
|
53
|
+
const omit = scope => { report.summary.omitted++; finding('PATH_OMITTED', 'Ruta o enlace omitido por estar fuera del ámbito autorizado.', { scope }); };
|
|
54
|
+
const issue = (error, scope) => {
|
|
55
|
+
if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') finding('READ_FAILED', 'No se pudo inspeccionar un archivo local.', { scope });
|
|
56
|
+
};
|
|
57
|
+
const realBase = base => { try { return fs.realpathSync(base); } catch { return path.resolve(base); } };
|
|
58
|
+
|
|
59
|
+
// A caller-selected base is authorized; symlinks below it must stay inside it.
|
|
60
|
+
function safeFile(file, roots, scope, allowSymlink = false) {
|
|
61
|
+
try {
|
|
62
|
+
if (!allowSymlink && fs.lstatSync(file).isSymbolicLink()) { omit(scope); return null; }
|
|
63
|
+
const real = fs.realpathSync(file);
|
|
64
|
+
if (!roots.some(root => inside(root, real))) { omit(scope); return null; }
|
|
65
|
+
const descriptor = fs.openSync(real, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
|
|
66
|
+
const stat = fs.fstatSync(descriptor);
|
|
67
|
+
if (!stat.isFile()) { fs.closeSync(descriptor); omit(scope); return null; }
|
|
68
|
+
return { descriptor, stat, real };
|
|
69
|
+
} catch (error) { issue(error, scope); return null; }
|
|
70
|
+
}
|
|
71
|
+
function readSmall(file, root, scope) {
|
|
72
|
+
const opened = safeFile(file, [realBase(root)], scope);
|
|
73
|
+
if (!opened) return null;
|
|
74
|
+
try {
|
|
75
|
+
if (opened.stat.size > MAX_FILE) { finding('READ_LIMIT', 'Archivo omitido por superar el límite de lectura.', { scope, limitBytes: MAX_FILE }); return null; }
|
|
76
|
+
// Fixed buffer also bounds reads if the file grows after fstat.
|
|
77
|
+
const buffer = Buffer.alloc(MAX_FILE + 1);
|
|
78
|
+
const length = fs.readSync(opened.descriptor, buffer, 0, buffer.length, 0);
|
|
79
|
+
if (length > MAX_FILE) { finding('READ_LIMIT', 'Archivo omitido por superar el límite de lectura.', { scope, limitBytes: MAX_FILE }); return null; }
|
|
80
|
+
return buffer.subarray(0, length);
|
|
81
|
+
} finally { fs.closeSync(opened.descriptor); }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const configText = readSmall(path.join(codexHome, 'config.toml'), codexHome, 'config');
|
|
85
|
+
if (configText) {
|
|
86
|
+
try {
|
|
87
|
+
const config = getStaticTOMLValue(parseTOML(configText.toString('utf8')));
|
|
88
|
+
report.settings = selectSettings(config);
|
|
89
|
+
report.summary.mcpServers = countTables(config.mcp_servers);
|
|
90
|
+
report.summary.plugins = countTables(config.plugins);
|
|
91
|
+
} catch { finding('CONFIG_INVALID', 'TOML inválido; se omiten los valores de configuración.'); }
|
|
92
|
+
} else {
|
|
93
|
+
try { fs.lstatSync(path.join(codexHome, 'config.toml')); }
|
|
94
|
+
catch (error) { if (error.code === 'ENOENT') finding('CONFIG_MISSING', 'No hay configuración de Codex en este ámbito.'); }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const catalogs = [
|
|
98
|
+
{ scope: 'user-skills', base: homeDirectory, root: path.join(homeDirectory, '.agents/skills') },
|
|
99
|
+
{ scope: 'codex-skills', base: codexHome, root: path.join(codexHome, 'skills') },
|
|
100
|
+
{ scope: 'project-skills', base: projectRoot, root: path.join(projectRoot, '.agents/skills') },
|
|
101
|
+
];
|
|
102
|
+
const roots = [];
|
|
103
|
+
for (const catalog of catalogs) {
|
|
104
|
+
try {
|
|
105
|
+
let component = catalog.base;
|
|
106
|
+
let linked = false;
|
|
107
|
+
for (const part of path.relative(catalog.base, catalog.root).split(path.sep)) {
|
|
108
|
+
component = path.join(component, part);
|
|
109
|
+
if (fs.lstatSync(component).isSymbolicLink()) { linked = true; break; }
|
|
110
|
+
}
|
|
111
|
+
if (linked) { omit(catalog.scope); continue; }
|
|
112
|
+
const real = fs.realpathSync(catalog.root);
|
|
113
|
+
if (!inside(realBase(catalog.base), real)) { omit(catalog.scope); continue; }
|
|
114
|
+
roots.push({ ...catalog, real });
|
|
115
|
+
} catch (error) { issue(error, catalog.scope); }
|
|
116
|
+
}
|
|
117
|
+
const allowedRoots = roots.map(root => root.real);
|
|
118
|
+
const seenFiles = new Set();
|
|
119
|
+
const names = new Map();
|
|
120
|
+
let entries = 0;
|
|
121
|
+
let limited = false;
|
|
122
|
+
|
|
123
|
+
function metadata(file, scope, directory) {
|
|
124
|
+
const opened = safeFile(file, allowedRoots, scope, true);
|
|
125
|
+
if (!opened) return;
|
|
126
|
+
try {
|
|
127
|
+
if (seenFiles.has(opened.real)) return;
|
|
128
|
+
seenFiles.add(opened.real);
|
|
129
|
+
report.summary.skills++;
|
|
130
|
+
report.summary.skillBytes += opened.stat.size;
|
|
131
|
+
// Stop exactly at the frontmatter closing line, without reading the body.
|
|
132
|
+
const bytes = Buffer.alloc(MAX_METADATA);
|
|
133
|
+
let used = 0;
|
|
134
|
+
let lineStart = 0;
|
|
135
|
+
let closed = false;
|
|
136
|
+
while (used < bytes.length) {
|
|
137
|
+
if (!fs.readSync(opened.descriptor, bytes, used, 1, null)) {
|
|
138
|
+
if (lineStart > 0 && bytes.subarray(lineStart, used).toString('utf8').trim() === '---') closed = true;
|
|
139
|
+
break;
|
|
140
|
+
}
|
|
141
|
+
used++;
|
|
142
|
+
if (bytes[used - 1] !== 10) continue;
|
|
143
|
+
const line = bytes.subarray(lineStart, used).toString('utf8').trim();
|
|
144
|
+
if (lineStart === 0 && line !== '---') break;
|
|
145
|
+
if (lineStart > 0 && line === '---') { closed = true; break; }
|
|
146
|
+
lineStart = used;
|
|
147
|
+
}
|
|
148
|
+
report.summary.metadataBytes += used;
|
|
149
|
+
if (!closed) {
|
|
150
|
+
finding(used === MAX_METADATA ? 'READ_LIMIT' : 'SKILL_METADATA_INVALID', 'Metadatos omitidos por ser incompletos o superar el límite.', { scope, limitBytes: MAX_METADATA });
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
const lines = bytes.subarray(0, used).toString('utf8').split(/\r?\n/);
|
|
154
|
+
const scalar = key => {
|
|
155
|
+
const index = lines.findIndex(line => line.startsWith(`${key}:`));
|
|
156
|
+
if (index < 0) return '';
|
|
157
|
+
let value = lines[index].slice(key.length + 1).trim();
|
|
158
|
+
if (/^[>|][-+]?$/.test(value)) {
|
|
159
|
+
value = '';
|
|
160
|
+
for (let i = index + 1; i < lines.length && /^\s/.test(lines[i]); i++) value += ` ${lines[i].trim()}`;
|
|
161
|
+
}
|
|
162
|
+
return value.replace(/^(['"])(.*)\1$/, '$2').trim();
|
|
163
|
+
};
|
|
164
|
+
const name = scalar('name');
|
|
165
|
+
const description = scalar('description');
|
|
166
|
+
const location = {
|
|
167
|
+
scope,
|
|
168
|
+
directory: directory.length <= 220 && directory.split('/').every(part => part === '.system' || /^[a-z0-9][a-z0-9._-]{0,99}$/.test(part)) ? directory : 'omitido',
|
|
169
|
+
};
|
|
170
|
+
const locator = { skillName: /^[a-z0-9-]{1,100}$/.test(name) ? name : 'omitido', locations: [location] };
|
|
171
|
+
if (!name || !description) finding('SKILL_METADATA_INVALID', 'La skill no tiene nombre o descripción utilizable.', { scope });
|
|
172
|
+
if (name) names.set(name, [...(names.get(name) ?? []), location]);
|
|
173
|
+
if (description.length > 1024) finding('SKILL_DESCRIPTION_LONG', 'Descripción extensa; conviene delimitar cuándo usar la skill.', { ...locator, characters: description.length });
|
|
174
|
+
if (/\b(everything|anything|all tasks|any task|siempre|todo|cualquier tarea)\b/i.test(description)) finding('SKILL_DESCRIPTION_BROAD', 'Descripción amplia; conviene acotar sus condiciones de activación.', locator);
|
|
175
|
+
} finally { fs.closeSync(opened.descriptor); }
|
|
176
|
+
}
|
|
177
|
+
function scan(directory, scope, depth = 0, prefix = '') {
|
|
178
|
+
let handle;
|
|
179
|
+
try {
|
|
180
|
+
handle = fs.opendirSync(directory);
|
|
181
|
+
for (let entry; (entry = handle.readSync());) {
|
|
182
|
+
if (entries >= MAX_ENTRIES) { limited = true; break; }
|
|
183
|
+
entries++;
|
|
184
|
+
if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
|
|
185
|
+
try {
|
|
186
|
+
const child = path.join(directory, entry.name);
|
|
187
|
+
const real = fs.realpathSync(child);
|
|
188
|
+
if (!allowedRoots.some(root => inside(root, real))) { omit(scope); continue; }
|
|
189
|
+
const relativeDirectory = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
190
|
+
if (entry.name === '.system' && depth === 0) scan(real, scope, 1, relativeDirectory);
|
|
191
|
+
else metadata(path.join(real, 'SKILL.md'), scope, relativeDirectory);
|
|
192
|
+
} catch (error) {
|
|
193
|
+
if (entry.isSymbolicLink()) omit(scope);
|
|
194
|
+
else issue(error, scope);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
} catch (error) { issue(error, scope); }
|
|
198
|
+
finally { handle?.closeSync(); }
|
|
199
|
+
}
|
|
200
|
+
for (const root of roots) scan(root.real, root.scope);
|
|
201
|
+
if (limited) finding('CATALOG_LIMIT', 'Catálogo parcial: se alcanzó el límite global de entradas.', { limit: MAX_ENTRIES });
|
|
202
|
+
for (const [name, locations] of names) if (locations.length > 1) finding('SKILL_DUPLICATE_NAME', 'Varias skills comparten el mismo nombre.', {
|
|
203
|
+
skillName: /^[a-z0-9-]{1,100}$/.test(name) ? name : 'omitido', locations, count: locations.length,
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
const hashes = new Map();
|
|
207
|
+
for (const [base, scope] of [[codexHome, 'user-instructions'], [projectRoot, 'project-instructions']]) {
|
|
208
|
+
const text = readSmall(path.join(base, 'AGENTS.md'), base, scope);
|
|
209
|
+
if (!text) continue;
|
|
210
|
+
report.summary.instructionFiles++;
|
|
211
|
+
report.summary.instructionBytes += text.length;
|
|
212
|
+
if (!text.toString('utf8').trim()) continue;
|
|
213
|
+
const hash = createHash('sha256').update(text).digest('hex');
|
|
214
|
+
hashes.set(hash, (hashes.get(hash) ?? 0) + 1);
|
|
215
|
+
}
|
|
216
|
+
for (const count of hashes.values()) if (count > 1) finding('INSTRUCTIONS_DUPLICATE', 'Las instrucciones de usuario y proyecto son idénticas.', { count });
|
|
217
|
+
return report;
|
|
218
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
import { compactarSalida } from '../plugins/nexakit-ahorro/hooks/compactar.js';
|
|
6
|
+
|
|
7
|
+
const MAX_BYTES = 1024 * 1024;
|
|
8
|
+
const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
9
|
+
const blocked = value => ['session_id', 'signal', 'backgroundTaskId'].some(key => key in value)
|
|
10
|
+
|| Boolean(value.isError || value.is_error || value.interrupted);
|
|
11
|
+
const FAILURE = /(error|fail|falla|✖|✗|not ok|exception|traceback|panic|assert|warn|denied|refused|cannot|no se pudo)/iu;
|
|
12
|
+
|
|
13
|
+
function responseText(response) {
|
|
14
|
+
if (typeof response === 'string') {
|
|
15
|
+
if (Buffer.byteLength(response, 'utf8') > MAX_BYTES) return null;
|
|
16
|
+
const match = /^(?:(?:Chunk ID: [^\r\n]+|Wall time: [^\r\n]+)\r?\n)*Process exited with code 0\r?\n(?:(?:Wall time: [^\r\n]+|Total output lines: \d+)\r?\n)*Final output:\r?\n([\s\S]*)$/u.exec(response);
|
|
17
|
+
if (match) return { text: match[1], original: response, json: false, exit: 0 };
|
|
18
|
+
// Native Codex can deliver just the model-facing text, without exit status.
|
|
19
|
+
// Never infer success; preserve error-like text and ambiguous/live envelopes.
|
|
20
|
+
if (FAILURE.test(response) || /^(?:Chunk ID:|Wall time:|Process exited|Process running)/u.test(response)) return null;
|
|
21
|
+
return { text: response, original: response, json: false, exit: null };
|
|
22
|
+
}
|
|
23
|
+
if (!object(response) || blocked(response) || response.exit_code !== 0) return null;
|
|
24
|
+
let text;
|
|
25
|
+
if (typeof response.output === 'string' && !('stdout' in response) && !('stderr' in response)) {
|
|
26
|
+
text = response.output;
|
|
27
|
+
} else if (!('output' in response) && typeof response.stdout === 'string' && typeof response.stderr === 'string') {
|
|
28
|
+
text = response.stdout + (response.stderr ? `\n${response.stderr}` : '');
|
|
29
|
+
} else return null;
|
|
30
|
+
return { text, original: JSON.stringify(response), json: true, exit: 0 };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function privateFolder(homeDirectory) {
|
|
34
|
+
const home = path.resolve(homeDirectory);
|
|
35
|
+
const target = path.join(home, '.nexakit', 'codex', 'salidas');
|
|
36
|
+
let current = path.parse(target).root;
|
|
37
|
+
for (const part of target.slice(current.length).split(path.sep).filter(Boolean)) {
|
|
38
|
+
current = path.join(current, part);
|
|
39
|
+
try {
|
|
40
|
+
const stat = fs.lstatSync(current);
|
|
41
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error('Unsafe directory');
|
|
42
|
+
} catch (error) {
|
|
43
|
+
if (error.code !== 'ENOENT') throw error;
|
|
44
|
+
fs.mkdirSync(current, { mode: 0o700 });
|
|
45
|
+
}
|
|
46
|
+
if (current === path.join(home, '.nexakit') || current === path.join(home, '.nexakit/codex') || current === target) {
|
|
47
|
+
fs.chmodSync(current, 0o700);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return target;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Returns hook JSON only; never executes the command, writes to stdout/stderr,
|
|
54
|
+
* or changes a process exit status. Unsupported inputs and storage errors fail open.
|
|
55
|
+
*/
|
|
56
|
+
export async function compactCodexToolOutput(payload, options = {}) {
|
|
57
|
+
try {
|
|
58
|
+
if (!object(payload) || payload.hook_event_name !== 'PostToolUse' || payload.tool_name !== 'Bash'
|
|
59
|
+
|| payload.isError || payload.is_error || payload.interrupted) return {};
|
|
60
|
+
if ((options.environment ?? process.env).NEXAKIT_SALIDA === 'completa') return {};
|
|
61
|
+
const command = payload.tool_input?.command;
|
|
62
|
+
if (typeof command === 'string' && /^\s*NEXAKIT_SALIDA=completa(?:\s|$)/u.test(command)) return {};
|
|
63
|
+
const response = responseText(payload.tool_response);
|
|
64
|
+
if (!response || Buffer.byteLength(response.original, 'utf8') > MAX_BYTES) return {};
|
|
65
|
+
if (!compactarSalida(response.text).omitidas) return {};
|
|
66
|
+
const home = options.homeDirectory ?? os.homedir();
|
|
67
|
+
const file = path.join(path.resolve(home), '.nexakit', 'codex', 'salidas', `${randomUUID()}.${response.json ? 'json' : 'log'}`);
|
|
68
|
+
const { texto } = compactarSalida(response.text, { ruta: file });
|
|
69
|
+
const status = response.exit === null ? 'desconocido (el hook no recibió el estado; este resumen no acredita éxito)' : '0';
|
|
70
|
+
const result = { continue: false, stopReason: `exit_code: ${status}\n${texto}\nOriginal completo (${response.json ? 'JSON de tool_response' : 'texto exacto de tool_response'}): ${file}` };
|
|
71
|
+
if (Buffer.byteLength(JSON.stringify(result), 'utf8') >= Buffer.byteLength(response.original, 'utf8')) return {};
|
|
72
|
+
privateFolder(home);
|
|
73
|
+
const fd = fs.openSync(file, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | (fs.constants.O_NOFOLLOW ?? 0), 0o600);
|
|
74
|
+
try {
|
|
75
|
+
const stat = fs.fstatSync(fd);
|
|
76
|
+
if (!stat.isFile() || stat.nlink !== 1) throw new Error('Unsafe output file');
|
|
77
|
+
fs.fchmodSync(fd, 0o600);
|
|
78
|
+
fs.writeFileSync(fd, response.original, 'utf8');
|
|
79
|
+
} catch (error) {
|
|
80
|
+
// Do not claim an original was saved if writing it failed.
|
|
81
|
+
try { fs.unlinkSync(file); } catch { /* best effort cleanup */ }
|
|
82
|
+
throw error;
|
|
83
|
+
} finally {
|
|
84
|
+
fs.closeSync(fd);
|
|
85
|
+
}
|
|
86
|
+
return result;
|
|
87
|
+
} catch {
|
|
88
|
+
return {};
|
|
89
|
+
}
|
|
90
|
+
}
|