nexakit 0.8.3 → 0.10.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 +16 -0
- package/assets/runtime/package-lock.json +2 -2
- package/bin/nexakit.js +16 -10
- package/package.json +1 -1
- package/src/ahorro-command.js +54 -5
- package/src/antigravity-agents.js +242 -0
- package/src/antigravity-barra.js +179 -0
- package/src/antigravity-command.js +226 -0
- package/src/antigravity-hook.js +159 -0
- package/src/antigravity-pre-tool.js +233 -0
- package/src/antigravity-recommendation.js +179 -0
- package/src/antigravity-session.js +291 -0
- package/src/antigravity-setup.js +175 -0
- 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 +228 -0
- package/src/codex-pre-tool.js +88 -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/review-instructions.js +1 -1
- package/src/toolkit-cli.js +6 -0
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
const LEVELS = ['nivel_ligero', 'nivel_normal', 'nivel_exigente', 'nivel_alto'];
|
|
2
|
+
const SPECIALISTS = [
|
|
3
|
+
['investigador', /\b(?:busca(?:r)?|investiga(?:r)?|consulta(?:r)?)\b.*\b(?:fuentes oficiales|documentacion|docs)\b/, 'nivel_normal'],
|
|
4
|
+
['revisor_de_calidad', /\b(?:revisa(?:r)?|audita(?:r)?)\b.*\bcalidad\b/, 'nivel_exigente'],
|
|
5
|
+
['subir_al_repo', /\b(?:sube|subir|subas)\s+(?:al\s+)?(?:repo|repositorio)\b/, 'nivel_normal'],
|
|
6
|
+
['cierre_de_memoria', /\b(?:cierra|cerrar)\s+(?:la\s+)?memoria\b/, 'nivel_normal'],
|
|
7
|
+
['sincronizador_docs', /\bsincroniza(?:r)?\s+(?:la\s+)?(?:docs|documentacion)\b/, 'nivel_normal'],
|
|
8
|
+
['cazador_de_flakes', /\b(?:fallo|falla|fallos|test|tests|ci)\b.*\b(?:intermitente|intermitentes|flaky|flakes)\b/, 'nivel_exigente'],
|
|
9
|
+
];
|
|
10
|
+
const ALLOWED = new Set([...LEVELS, ...SPECIALISTS.map(([name]) => name)]);
|
|
11
|
+
const SENSITIVE = new Set(['subir_al_repo', 'cierre_de_memoria']);
|
|
12
|
+
const GUIDANCE = [
|
|
13
|
+
'El principal entiende, decide e integra; delega tareas de más de 1–2 pasos con la herramienta nativa spawn disponible.',
|
|
14
|
+
'Acota cada encargo: objetivo, archivos y criterio de hecho; no repitas búsquedas ni suites ya comprobadas.',
|
|
15
|
+
'Respeta los límites y permisos del padre, verifica los resultados antes de integrar y no cambies automáticamente modelo ni effort.',
|
|
16
|
+
'No solicites revisión cruzada por otra IA sin petición expresa. El hook no ejecuta agentes ni crea autorización.',
|
|
17
|
+
'Usa el perfil solo si aparece en tus agentes/herramientas disponibles; los archivos instalados no prueban que esta sesión lo haya cargado.',
|
|
18
|
+
'Si no está disponible usa un nivel registrado o resuelve tú, sin inventar agent_type.',
|
|
19
|
+
].join(' ');
|
|
20
|
+
const AUTHORIZATION = 'Antes de subir al repo o cerrar memoria, el principal debe confirmar que el encargo contiene el pedido escrito de la persona y evidencia verificable; esta sugerencia no crea autorización.';
|
|
21
|
+
|
|
22
|
+
function silent() {
|
|
23
|
+
return { agent: null, context: '' };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function isDirectRequest(task, pattern) {
|
|
27
|
+
const match = pattern.exec(task);
|
|
28
|
+
return match && /^[¿\s]*(?:por favor[,\s]+)?(?:(?:puedes|podrias|quiero que|necesito que)\s+)?$/.test(task.slice(0, match.index));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Pure routing hint, never an authorization or a statement of runtime availability. */
|
|
32
|
+
export function routeCodexTask(text, options = {}) {
|
|
33
|
+
if (typeof text !== 'string' || text.length > 16384 || Buffer.byteLength(text, 'utf8') > 16384) {
|
|
34
|
+
return silent();
|
|
35
|
+
}
|
|
36
|
+
if (!options || typeof options !== 'object' || Array.isArray(options)) return silent();
|
|
37
|
+
const { installedNames = [] } = options;
|
|
38
|
+
if (!Array.isArray(installedNames)) return silent();
|
|
39
|
+
const installed = new Set(installedNames.filter((name) => typeof name === 'string' && ALLOWED.has(name)));
|
|
40
|
+
if (!installed.size) return silent();
|
|
41
|
+
|
|
42
|
+
// Quoted examples are data, not requests. An unmatched opening quote hides the remainder too.
|
|
43
|
+
const task = text
|
|
44
|
+
.replace(/```[\s\S]*?(?:```|$)|`[^`]*(?:`|$)|"[^"]*(?:"|$)|'[^']*(?:'|$)|“[^”]*(?:”|$)|«[^»]*(?:»|$)|‘[^’]*(?:’|$)/g, ' ')
|
|
45
|
+
.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().trim()
|
|
46
|
+
.replace(/^si\s*,\s*/, '');
|
|
47
|
+
if (!task || /^(?:(?:si|ok|vale|adelante|continua|hazlo|de acuerdo|perfecto|gracias|listo|dale|sigue|confirmo|por favor)[\s,.!]*)+$/.test(task)) {
|
|
48
|
+
return silent();
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const informational = /^(?:[¿?\s]*)(?:explica\b|que\b|como\b|cual\b|cuando\b|donde\b|por que\b|ya\b|has\b)/.test(task);
|
|
52
|
+
const restricted = informational || /\b(?:no|nunca|jamas|sin|evita|prohibido|si|ejemplo|dice|escribio|significa)\b/.test(task);
|
|
53
|
+
const generalAction = /\b(?:implementa(?:r)?|anade|agrega(?:r)?|crea(?:r)?|corrige|arregla(?:r)?|resuelve|renombra(?:r)?|refactoriza(?:r)?|optimiza(?:r)?)\b/.test(task);
|
|
54
|
+
|
|
55
|
+
let specialist;
|
|
56
|
+
let fallback;
|
|
57
|
+
const explicit = /^(?:por favor[,\s]+)?(?:usa|utiliza|delega a)\s+([a-z][a-z_-]*)\b(?:\s+para\s+([\s\S]+))?/.exec(task);
|
|
58
|
+
const requested = explicit?.[1].replace(/-/g, '_');
|
|
59
|
+
const profile = SPECIALISTS.find(([name]) => name === requested);
|
|
60
|
+
if (ALLOWED.has(requested) && !restricted &&
|
|
61
|
+
(!SENSITIVE.has(requested) || isDirectRequest(explicit[2] || '', profile[1]))) {
|
|
62
|
+
specialist = requested;
|
|
63
|
+
fallback = profile?.[2] || requested;
|
|
64
|
+
}
|
|
65
|
+
if (!specialist) {
|
|
66
|
+
for (const [name, pattern, level] of SPECIALISTS) {
|
|
67
|
+
// Sensitive profiles require a direct request, not a mention or a question about permission.
|
|
68
|
+
if (pattern.test(task) && !(SENSITIVE.has(name) && (restricted || !isDirectRequest(task, pattern)))) {
|
|
69
|
+
specialist = name;
|
|
70
|
+
fallback = level;
|
|
71
|
+
break;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (!specialist && (informational || restricted) && !generalAction) return silent();
|
|
76
|
+
if (!specialist && /^[¿?]/.test(task) && !generalAction) return silent();
|
|
77
|
+
|
|
78
|
+
const runTests = /\b(?:ejecuta(?:r)?|corre(?:r)?|lanza(?:r)?)\s+(?:(?:las|los)\s+)?(?:pruebas|tests?|suite)\b/.test(task) &&
|
|
79
|
+
!/\b(?:escrib[ei]|anade|agrega|implementa|crea|corrige|arregla|diagnostica)\w*\b/.test(task);
|
|
80
|
+
const level = /\b(?:dificil|complejo|sutil|concurrencia|seguridad)\b/.test(task) ? 'nivel_alto'
|
|
81
|
+
: runTests ? 'nivel_ligero'
|
|
82
|
+
: /\b(?:parser|tests?|pruebas|casos borde)\b/.test(task) ? 'nivel_exigente'
|
|
83
|
+
: /\b(?:mecanico|mecanica|mecanicamente|renombra|formatea)\b/.test(task) ? 'nivel_ligero'
|
|
84
|
+
: 'nivel_normal';
|
|
85
|
+
const agent = installed.has(specialist) ? specialist : (fallback || level);
|
|
86
|
+
if (!installed.has(agent)) return silent();
|
|
87
|
+
return {
|
|
88
|
+
agent,
|
|
89
|
+
context: `Perfil candidato: ${agent}. ${GUIDANCE} ${AUTHORIZATION}`,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
|
|
6
|
+
export function buildCodexHookCommand({ executable = process.execPath,
|
|
7
|
+
entrypoint = fileURLToPath(new URL('../bin/nexakit.js', import.meta.url)), platform = process.platform } = {}) {
|
|
8
|
+
const pathApi = platform === 'win32' ? path.win32 : path;
|
|
9
|
+
for (const value of [executable, entrypoint]) {
|
|
10
|
+
if (!pathApi.isAbsolute(value) || /[\0\r\n]/u.test(value)) throw new Error('El hook requiere rutas absolutas seguras.');
|
|
11
|
+
}
|
|
12
|
+
if (platform === 'win32') {
|
|
13
|
+
// cmd expands percent variables and delayed ! expansions even inside quotes.
|
|
14
|
+
if ([executable, entrypoint].some(value => /[%!"\r\n]/u.test(value))) throw new Error('Ruta incompatible con quoting seguro en Windows.');
|
|
15
|
+
// Return shell command text; the runner owns cmd.exe's outer /s /c quotes.
|
|
16
|
+
return `"${executable}" "${entrypoint}" codex hook`;
|
|
17
|
+
}
|
|
18
|
+
const quote = value => `'${value.replaceAll("'", "'\\''")}'`;
|
|
19
|
+
return `${quote(executable)} ${quote(entrypoint)} codex hook`;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async function assertNoSymlinkAncestors(destination) {
|
|
23
|
+
let current = destination;
|
|
24
|
+
while (true) {
|
|
25
|
+
try {
|
|
26
|
+
const stat = await fs.lstat(current);
|
|
27
|
+
if (stat.isSymbolicLink()) throw new Error('No se admiten enlaces simbólicos en el destino.');
|
|
28
|
+
if (current !== destination && !stat.isDirectory()) throw new Error('El padre no es una carpeta.');
|
|
29
|
+
} catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
30
|
+
const parent = path.dirname(current);
|
|
31
|
+
if (parent === current) break;
|
|
32
|
+
current = parent;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
const within = (root, destination) => {
|
|
36
|
+
const relative = path.relative(path.resolve(root), destination);
|
|
37
|
+
return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
export async function prepareCodex({ outputDirectory, apply = false, homeDirectory = os.homedir(),
|
|
41
|
+
codexHome, projectRoot = process.cwd(), environment = process.env } = {}) {
|
|
42
|
+
if (apply && !outputDirectory) throw new Error('--apply requiere --salida.');
|
|
43
|
+
const destination = outputDirectory ? path.resolve(outputDirectory) : null;
|
|
44
|
+
if (destination) {
|
|
45
|
+
const protectedRoots = [path.join(homeDirectory, '.codex'), path.join(projectRoot, '.codex'),
|
|
46
|
+
codexHome ?? environment.CODEX_HOME].filter(Boolean);
|
|
47
|
+
if (protectedRoots.some(root => within(root, destination))) throw new Error('El paquete debe quedar fuera de la configuración activa de Codex.');
|
|
48
|
+
await assertNoSymlinkAncestors(destination);
|
|
49
|
+
}
|
|
50
|
+
const command = buildCodexHookCommand();
|
|
51
|
+
const events = ['PostModelRequest', 'SessionStart', 'PreCompact', 'PostCompact', 'UserPromptSubmit', 'PreToolUse', 'PostToolUse', 'SubagentStart', 'SubagentStop'];
|
|
52
|
+
const statusLine = ['model-with-reasoning', 'context-remaining', 'five-hour-limit', 'weekly-limit',
|
|
53
|
+
'total-input-tokens', 'total-output-tokens', 'git-branch'];
|
|
54
|
+
const config = 'tool_output_token_limit = 4000\n\n[agents]\nmax_concurrent_threads_per_session = 2\n'
|
|
55
|
+
+ `\n[tui]\nstatus_line = ${JSON.stringify(statusLine)}\n`;
|
|
56
|
+
const hooks = { hooks: Object.fromEntries(events.map(event => [event, [{
|
|
57
|
+
...(['PreToolUse', 'PostToolUse'].includes(event) ? { matcher: '^Bash$' } : {}),
|
|
58
|
+
hooks: [{ type: 'command', command }],
|
|
59
|
+
}]])) };
|
|
60
|
+
const readme = `# Paquete Codex: activación manual\n\nVista previa de configuración; no se activa automáticamente.\nRevisa y fusiona config.toml y hooks.json manualmente en tu CODEX_HOME.\nVerifica primero que tu versión de Codex admite estos eventos y claves.\nConfía los hooks mediante /hooks; no omitas sus confirmaciones.\nNo se garantiza compatibilidad de todos los clientes ni se cambian modelos.\nLa barra nativa muestra modelo/esfuerzo, contexto, límites y tokens cuando están disponibles.\nUsa /statusline para ordenar campos; en terminales estrechas Codex recorta los últimos.\nUserPromptSubmit recomienda localmente según la tarea mediante avisos; no cambia el modelo.\nUsa /model para aplicar una recomendación y /status para verificar el estado activo.\nEl comando del hook usa rutas absolutas: regenera el paquete si mueves NexaKit o Node.\n\nCompara muestras JSON con task, quality: { passed: true } y measurements\n(normalizeMeasurement: id, agent, phase, model, source y contadores).\nSolo se calculan porcentajes con cobertura completa y procedencia comparable.\n`;
|
|
61
|
+
const liveHooks = '\n## Salidas y subagentes\n\nPreToolUse envuelve comandos simples POSIX de pruebas/build/lint con el wrapper de salida.\nNo interpreta comandos compuestos ni shell general, no eleva permisos y no ejecuta el comando desde el hook.\nPostToolUse mantiene cobertura adicional; su sustitución depende del cliente.\nSin estado explícito informa exit_code desconocido; no acredita éxito.\nNEXAKIT_SALIDA=completa evita la reescritura y el recorte. Los logs privados pueden contener datos sensibles.\nSubagentStart/Stop registran solo metadatos; consulta nexakit codex actividad.\nAl combinar una instalación existente, agrega solo los eventos que falten y conserva los demás.\nRevisa y confía los hooks nuevos con /hooks: el paquete no modifica la confianza.\n';
|
|
62
|
+
const files = { 'config.toml': config, 'hooks.json': JSON.stringify(hooks, null, 2) + '\n', 'README.md': readme + liveHooks };
|
|
63
|
+
if (apply) {
|
|
64
|
+
// mkdir is exclusive; no recursive creation and no overwrites of an existing destination.
|
|
65
|
+
await fs.mkdir(destination, { mode: 0o700 });
|
|
66
|
+
for (const [name, contents] of Object.entries(files)) {
|
|
67
|
+
await fs.writeFile(path.join(destination, name), contents, { flag: 'wx', mode: 0o600 });
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return { applied: apply, outputDirectory: destination, files,
|
|
71
|
+
limitations: ['Activación manual; comprueba compatibilidad con tu versión de Codex.'] };
|
|
72
|
+
}
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import fs from 'node:fs/promises';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { getStaticTOMLValue, parseTOML } from 'toml-eslint-parser';
|
|
7
|
+
import { agentModels } from './agent-models.js';
|
|
8
|
+
import { levelAgentPlan } from './level-agents.js';
|
|
9
|
+
|
|
10
|
+
const MAX_BYTES = 128 * 1024;
|
|
11
|
+
const MODEL = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,79}$/u;
|
|
12
|
+
const LEVEL_NAMES = ['nivel_ligero', 'nivel_normal', 'nivel_exigente', 'nivel_alto'];
|
|
13
|
+
const SPECIALISTS = {
|
|
14
|
+
investigador: {
|
|
15
|
+
steps: 25, description: 'Investiga dudas técnicas en fuentes oficiales y separa lo verificado de lo pendiente.',
|
|
16
|
+
instructions: `Solo lees y buscas; no edites archivos ni hagas commit, push o PR. Los temporales, solo en el scratchpad indicado en el encargo.
|
|
17
|
+
Empieza por documentación, changelogs y repositorios oficiales; blogs y foros son pistas, nunca pruebas.
|
|
18
|
+
Por cada afirmación indica dato, fuente (URL), fecha o versión y si lo leíste o ejecutaste. Marca lo no confirmado como «no verificado», sin suposiciones.
|
|
19
|
+
Busca palabras clave en páginas largas y no repitas búsquedas. Si se agota el presupuesto, entrega lo conseguido y qué falta comprobar.
|
|
20
|
+
Entrecomilla los separadores en shell. Informe en español de máximo 300 palabras: respuesta primero, evidencia y pendientes con enlaces; detalle adicional solo en el scratchpad autorizado.`
|
|
21
|
+
},
|
|
22
|
+
revisor_de_calidad: {
|
|
23
|
+
steps: 30, description: 'Revisa requisitos, diff y pruebas frescas con quality-gate, sin corregir el cambio.',
|
|
24
|
+
instructions: `Lee y aplica la skill quality-gate con profundidad proporcional al riesgo.
|
|
25
|
+
No edites archivos ni hagas commit, push o PR. Describe los fallos con archivo y línea; no los corrijas.
|
|
26
|
+
Inspecciona tú mismo git status y git diff: otro informe es una declaración, no evidencia. Ejecuta las pruebas relevantes y lee la salida real; si ya se ejecutaron sobre el mismo árbol, declara esa evidencia sin repetirlas.
|
|
27
|
+
Revisa cada requisito, secretos, rutas personales y archivos ajenos. Clasifica hallazgos como Alta, Media o Baja.
|
|
28
|
+
Informe en español de máximo 300 palabras: Aprobado, Aprobado con observaciones, Requiere cambios o Sin evidencia suficiente; después hallazgos ubicados, comprobaciones y lo no comprobado.`
|
|
29
|
+
},
|
|
30
|
+
cierre_de_memoria: {
|
|
31
|
+
steps: 40, description: 'Cierra la memoria únicamente cuando la persona lo haya pedido y el encargo lo documente.',
|
|
32
|
+
instructions: `Actúa solo si el encargo dice por escrito que la persona ha pedido cerrar la memoria; si falta, detente y explica el motivo.
|
|
33
|
+
Lee y aplica cerrar-memoria. Identifica proyecto y bóveda mediante el manifiesto, valida con doctor y comprueba rama, PR fusionado y evidencia del cierre real.
|
|
34
|
+
Edita solo las notas afectadas de la bóveda. No cambies código, repositorio fuente, .obsidian ni secretos.
|
|
35
|
+
Registra PR pendientes uno por uno con la herramienta: exige registro limpio entre ellos. Commit local de bóveda solo con autorización explícita en el encargo; sin ella registra el primero y comunica los pendientes. No hagas push.
|
|
36
|
+
Nunca sustituyas el registro por una fila manual; si la herramienta bloquea, deja lo preparado e indica el motivo exacto.
|
|
37
|
+
Informe en español de máximo 200 palabras: notas, PR registrados y pendientes, doctor y línea final «Memoria <proyecto>: <estado real>.»`
|
|
38
|
+
},
|
|
39
|
+
subir_al_repo: {
|
|
40
|
+
steps: 40, description: 'Sube y fusiona un cambio verificado solo con autorización literal «sube al repo» en el encargo.',
|
|
41
|
+
instructions: `Si el encargo no dice por escrito que la persona dijo literalmente «sube al repo», detente sin actuar y devuelve ese motivo.
|
|
42
|
+
Comprueba git status y que no estás en main. Añade solo los archivos nombrados en el encargo.
|
|
43
|
+
Exige evidencia de pruebas frescas sobre el árbol actual o ejecuta las pruebas del proyecto; detente si fallan.
|
|
44
|
+
Commit en español con Conventional Commits: tipo(alcance): descripción, minúsculas, sin punto final, máximo 72 caracteres, sin Co-Authored-By ni firmas de herramientas.
|
|
45
|
+
Push de la rama sin forzar ni usar --no-verify. Crea PR con gh pr create, título y cuerpo en español sin firmas.
|
|
46
|
+
Espera gh pr checks <n> --watch y consulta el estado final con gh pr checks <n>. Fusiona únicamente con todas las comprobaciones verdes.
|
|
47
|
+
Si falla CI, lee el fallo. Solo si es claramente ajeno y pasa la ejecución hermana del mismo PR, relanza una vez la ejecución fallida; si vuelve a fallar o no es ajeno, detente.
|
|
48
|
+
Fusiona con gh pr merge <n> --merge; cambia a main y ejecuta git pull --ff-only. Ante cualquier denegación, detente y explica, sin rodearla.
|
|
49
|
+
No borres ramas ni toques archivos ajenos u otros repositorios.
|
|
50
|
+
Informe en español de máximo 200 palabras: PR, SHA de fusión, CI, archivos del commit y pendientes. La sesión principal verificará git log, gh pr view y main frente al remoto.`
|
|
51
|
+
},
|
|
52
|
+
sincronizador_docs: {
|
|
53
|
+
steps: 30, description: 'Contrasta documentación y código después de un cambio y comunica discrepancias sin editar.',
|
|
54
|
+
instructions: `Solo lees; no edites archivos ni hagas commit, push o PR.
|
|
55
|
+
Parte del cambio real con git diff o gh pr diff y anota cambios observables: comandos, opciones, nombres, rutas, mensajes y cifras (plugins, versiones, pruebas).
|
|
56
|
+
Busca esos términos con rg en README, docs, guías y plantillas; evita leer archivos completos si basta buscar.
|
|
57
|
+
Por discrepancia indica archivo:línea, afirmación actual, comportamiento del código y corrección sugerida. Lo no confirmado es «no verificado».
|
|
58
|
+
Ignora estilo y redacción: cuenta solo lo falso o faltante.
|
|
59
|
+
Informe en español de máximo 300 palabras: discrepancias primero, seguido de lo comprobado que estaba bien.`
|
|
60
|
+
},
|
|
61
|
+
cazador_de_flakes: {
|
|
62
|
+
steps: 20, description: 'Diagnostica fallos intermitentes del CI mediante historial y evidencia, sin relanzar ejecuciones.',
|
|
63
|
+
instructions: `Solo lees. Usa gh run list y gh run view. No relances ni canceles ejecuciones, no edites archivos ni hagas commit, push o PR; decidir un relanzamiento corresponde al principal.
|
|
64
|
+
Identifica prueba exacta, sistema, commit o PR. Examina las últimas 30 ejecuciones de main y otros PR: fallos sobre total, sistemas y resultado de la ejecución hermana del mismo commit.
|
|
65
|
+
Lee únicamente la parte fallida del log con --log-failed, filtrada por la prueba; nunca vuelques logs enteros.
|
|
66
|
+
Veredicto: INTERMITENTE si falla y pasa con el mismo código; REGRESIÓN si falla siempre desde un commit; SIN DATOS si falta evidencia. Enlaza las ejecuciones e indica si sería razonable relanzar una vez.
|
|
67
|
+
Informe en español de máximo 200 palabras: veredicto primero, después cifras y evidencia.`
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
const NAMES = [...LEVEL_NAMES, ...Object.keys(SPECIALISTS)];
|
|
71
|
+
const plans = new WeakMap();
|
|
72
|
+
const fail = message => Object.assign(new Error(message), { code: 'codex-team' });
|
|
73
|
+
const digest = content => createHash('sha256').update(content).digest('hex');
|
|
74
|
+
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
75
|
+
const homeOf = (options = {}) => path.resolve(options.codexHome ?? options.environment?.CODEX_HOME ?? process.env.CODEX_HOME ?? path.join(options.homeDirectory ?? os.homedir(), '.codex'));
|
|
76
|
+
const filePath = (home, name) => path.join(home, 'agents', `${name}.toml`);
|
|
77
|
+
|
|
78
|
+
async function statOrNull(target) {
|
|
79
|
+
try { return await fs.lstat(target); }
|
|
80
|
+
catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
81
|
+
}
|
|
82
|
+
const identity = stat => ({ dev: stat.dev, ino: stat.ino });
|
|
83
|
+
|
|
84
|
+
// Never traverse a linked home or agents directory. Pin both directory identities
|
|
85
|
+
// across planning/writing; a newly created agents directory is allowed.
|
|
86
|
+
async function directories(home) {
|
|
87
|
+
const result = [];
|
|
88
|
+
for (const dir of [home, path.join(home, 'agents')]) {
|
|
89
|
+
const stat = await statOrNull(dir);
|
|
90
|
+
if (stat && !stat.isDirectory()) return null;
|
|
91
|
+
result.push(stat ? { ...identity(stat), real: await fs.realpath(dir) } : null);
|
|
92
|
+
}
|
|
93
|
+
return result;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async function inspect(target) {
|
|
97
|
+
const stat = await statOrNull(target);
|
|
98
|
+
if (!stat) return { snapshot: { type: 'missing' }, content: null };
|
|
99
|
+
const base = { ...identity(stat), size: stat.size, mtimeMs: stat.mtimeMs, ctimeMs: stat.ctimeMs, nlink: stat.nlink };
|
|
100
|
+
if (!stat.isFile() || stat.nlink !== 1 || stat.size > MAX_BYTES) {
|
|
101
|
+
return { snapshot: { type: stat.isSymbolicLink() ? 'symlink' : stat.isDirectory() ? 'directory' : 'blocked', ...base }, content: null };
|
|
102
|
+
}
|
|
103
|
+
let handle;
|
|
104
|
+
try {
|
|
105
|
+
handle = await fs.open(target, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
|
|
106
|
+
const opened = await handle.stat();
|
|
107
|
+
if (!opened.isFile() || opened.nlink !== 1 || opened.size > MAX_BYTES || !same(identity(opened), identity(stat))) throw fail('Archivo cambiado durante lectura de snapshot.');
|
|
108
|
+
const buffer = Buffer.alloc(MAX_BYTES + 1);
|
|
109
|
+
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
|
|
110
|
+
const end = await handle.stat();
|
|
111
|
+
if (bytesRead > MAX_BYTES || bytesRead !== end.size || !same(base, { ...identity(end), size: end.size, mtimeMs: end.mtimeMs, ctimeMs: end.ctimeMs, nlink: end.nlink })) throw fail('Archivo cambiado durante lectura de snapshot.');
|
|
112
|
+
const bytes = buffer.subarray(0, bytesRead);
|
|
113
|
+
return { snapshot: { type: 'file', ...base, hash: digest(bytes) }, content: bytes.toString('utf8'), bytes };
|
|
114
|
+
} finally { await handle?.close(); }
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function native(name, description, instructions, pick) {
|
|
118
|
+
return `# Generado por nexakit codex agentes\nname = ${JSON.stringify(name)}\ndescription = ${JSON.stringify(description)}\nmodel = ${JSON.stringify(pick.model)}\nmodel_reasoning_effort = ${JSON.stringify(pick.effort)}\ndeveloper_instructions = ${JSON.stringify(instructions)}\n`;
|
|
119
|
+
}
|
|
120
|
+
const permissions = 'Los permisos efectivos se heredan de la sesión principal/padre; estas instrucciones de solo lectura y presupuesto son orientativas, no restricciones técnicas. No amplíes permisos.';
|
|
121
|
+
const common = `${permissions}\nRespeta AGENTS.md y las skills del proyecto. Haz solo el encargo; el principal decide, verifica el informe e integra. No solicites automáticamente revisiones a otra IA.`;
|
|
122
|
+
|
|
123
|
+
export async function teamPlan(options = {}) {
|
|
124
|
+
const codexHome = homeOf(options);
|
|
125
|
+
const dirs = await directories(codexHome);
|
|
126
|
+
const observed = dirs ? await Promise.all(NAMES.map(name => inspect(filePath(codexHome, name)))) : NAMES.map(() => ({ snapshot: { type: 'blocked-directory' }, content: null }));
|
|
127
|
+
const { codex, levels } = await agentModels({ codexHome });
|
|
128
|
+
// The legacy formatter also reads its four targets. Only invoke it after
|
|
129
|
+
// checking that those reads are bounded regular files (or missing/link/dir).
|
|
130
|
+
const safeLegacy = dirs && observed.slice(0, 4).every(item => ['missing', 'file', 'symlink', 'directory'].includes(item.snapshot.type));
|
|
131
|
+
const legacy = safeLegacy ? await levelAgentPlan({ codexHome }) : null;
|
|
132
|
+
const limitations = [permissions, 'Los presupuestos de pasos y la longitud de informes son instrucciones orientativas. No se cambia shell, configuración, hooks ni barra.', 'Los snapshots detectan cambios conocidos; el sistema de archivos no ofrece compare-and-swap entre procesos externos para rutas.'];
|
|
133
|
+
if (dirs && !safeLegacy) limitations.push('Los niveles quedan bloqueados porque el generador compartido no admite lecturas acotadas de los perfiles existentes.');
|
|
134
|
+
const files = NAMES.map((name, i) => {
|
|
135
|
+
const role = SPECIALISTS[name];
|
|
136
|
+
const selected = role ? levels.find(entry => entry.level === (name === 'revisor_de_calidad' ? 'Exigente' : 'Normal'))?.codex : levels[i]?.codex;
|
|
137
|
+
const pick = selected?.model && MODEL.test(selected.model) ? selected : null;
|
|
138
|
+
let content = null;
|
|
139
|
+
if (pick && codex.available) {
|
|
140
|
+
if (role) content = native(name, role.description, `${common}\nPresupuesto orientativo: ${role.steps} pasos; entrega avances y pendientes si se agota.\n${role.instructions}`, pick);
|
|
141
|
+
else if (legacy?.files[i]?.content) {
|
|
142
|
+
const parsed = getStaticTOMLValue(parseTOML(legacy.files[i].content));
|
|
143
|
+
content = native(name, parsed.description, `${parsed.developer_instructions.trim()}\n${common}\nPresupuesto orientativo: ${[15, 25, 30, 40][i]} pasos. Informe de máximo 200 palabras.`, pick);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
const { snapshot, content: current } = observed[i];
|
|
147
|
+
const blocked = !['missing', 'file'].includes(snapshot.type) || (i < 4 && !safeLegacy);
|
|
148
|
+
const state = blocked ? 'bloqueado' : !codex.available ? 'sin-catalogo' : !pick ? 'sin-modelo' : current === null ? 'nuevo' : current === content ? 'igual' : 'distinto';
|
|
149
|
+
return { name, kind: role ? 'specialist' : 'level', path: filePath(codexHome, name), model: pick?.model ?? null, effort: pick?.effort ?? null, state, content, snapshot };
|
|
150
|
+
});
|
|
151
|
+
const plan = { codexHome, catalog: codex.available, files, limitations };
|
|
152
|
+
plans.set(plan, { serialized: JSON.stringify(plan), dirs });
|
|
153
|
+
return plan;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export async function installedTeam(options = {}) {
|
|
157
|
+
const codexHome = homeOf(options);
|
|
158
|
+
if (!await directories(codexHome)) return [];
|
|
159
|
+
const installed = [];
|
|
160
|
+
for (const name of NAMES) {
|
|
161
|
+
try {
|
|
162
|
+
const { snapshot, content } = await inspect(filePath(codexHome, name));
|
|
163
|
+
if (snapshot.type !== 'file') continue;
|
|
164
|
+
const value = getStaticTOMLValue(parseTOML(content));
|
|
165
|
+
if (value.name === name && typeof value.description === 'string' && value.description.trim() && typeof value.developer_instructions === 'string' && value.developer_instructions.trim()) installed.push(name);
|
|
166
|
+
} catch { /* Invalid, inaccessible, changed or oversized profiles are not installed. */ }
|
|
167
|
+
}
|
|
168
|
+
return installed;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async function checkDirectories(home, expected) {
|
|
172
|
+
const current = await directories(home);
|
|
173
|
+
if (!current || !expected || expected.some((dir, i) => dir && !same(dir, current[i]))) throw fail('Directorio cambiado: snapshot concurrente o enlace.');
|
|
174
|
+
return current;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export async function writeTeam(plan, { update = false } = {}) {
|
|
178
|
+
const trusted = plans.get(plan);
|
|
179
|
+
if (!trusted || trusted.serialized !== JSON.stringify(plan)) throw fail('Plan inválido o modificado; genera otra vista previa con teamPlan.');
|
|
180
|
+
const pending = plan.files.filter(file => file.state === 'nuevo' || (update && file.state === 'distinto'));
|
|
181
|
+
if (!pending.length) return plan;
|
|
182
|
+
let dirs = await checkDirectories(plan.codexHome, trusted.dirs);
|
|
183
|
+
// Preflight the entire known team before any mutation, including unchanged files.
|
|
184
|
+
for (const file of plan.files) {
|
|
185
|
+
if (file.path !== filePath(plan.codexHome, file.name) || !NAMES.includes(file.name)) throw fail('Ruta de plan inválida.');
|
|
186
|
+
const actual = await inspect(file.path);
|
|
187
|
+
if (!same(actual.snapshot, file.snapshot)) throw fail(`Snapshot cambiado: ${file.name}; genera otra vista previa.`);
|
|
188
|
+
}
|
|
189
|
+
await fs.mkdir(plan.codexHome, { recursive: true });
|
|
190
|
+
await checkDirectories(plan.codexHome, dirs);
|
|
191
|
+
await fs.mkdir(path.join(plan.codexHome, 'agents'), { recursive: true });
|
|
192
|
+
dirs = await checkDirectories(plan.codexHome, dirs);
|
|
193
|
+
for (const file of pending) {
|
|
194
|
+
await checkDirectories(plan.codexHome, dirs);
|
|
195
|
+
const before = await inspect(file.path);
|
|
196
|
+
if (!same(before.snapshot, file.snapshot)) throw fail(`Snapshot concurrente: ${file.name}.`);
|
|
197
|
+
const temporary = path.join(plan.codexHome, 'agents', `.equipo-${randomUUID()}.tmp`);
|
|
198
|
+
let backupPath;
|
|
199
|
+
let displaced;
|
|
200
|
+
let restored = false;
|
|
201
|
+
const isOriginal = snapshot => snapshot.type === 'file' && ['hash', 'ino', 'dev', 'size', 'mtimeMs', 'nlink'].every(key => snapshot[key] === before.snapshot[key]);
|
|
202
|
+
try {
|
|
203
|
+
await fs.writeFile(temporary, file.content, { flag: 'wx', mode: 0o644 });
|
|
204
|
+
await checkDirectories(plan.codexHome, dirs);
|
|
205
|
+
const latest = await inspect(file.path);
|
|
206
|
+
if (!same(latest.snapshot, file.snapshot)) throw fail(`Snapshot concurrente: ${file.name}.`);
|
|
207
|
+
if (file.state === 'distinto') {
|
|
208
|
+
backupPath = `${file.path}.anterior-${randomUUID()}`;
|
|
209
|
+
// Exclusive backup creation preserves bytes and never follows a target link.
|
|
210
|
+
await fs.writeFile(backupPath, before.bytes, { flag: 'wx', mode: 0o600 });
|
|
211
|
+
const last = await inspect(file.path);
|
|
212
|
+
if (!same(last.snapshot, file.snapshot)) throw fail(`Snapshot concurrente: ${file.name}.`);
|
|
213
|
+
// Move the original aside, then publish exclusively. Any new concurrent
|
|
214
|
+
// target survives: link() never replaces an existing entry.
|
|
215
|
+
const movedPath = `${file.path}.anterior-${randomUUID()}`;
|
|
216
|
+
await fs.rename(file.path, movedPath);
|
|
217
|
+
const moved = await inspect(movedPath);
|
|
218
|
+
if (!isOriginal(moved.snapshot)) {
|
|
219
|
+
await fs.link(movedPath, file.path).catch(() => {});
|
|
220
|
+
throw fail(`Snapshot concurrente: ${file.name}; original conservado en ${movedPath}.`);
|
|
221
|
+
}
|
|
222
|
+
displaced = movedPath;
|
|
223
|
+
}
|
|
224
|
+
try { await fs.link(temporary, file.path); }
|
|
225
|
+
catch (error) {
|
|
226
|
+
if (displaced) {
|
|
227
|
+
try {
|
|
228
|
+
await checkDirectories(plan.codexHome, dirs);
|
|
229
|
+
if (isOriginal((await inspect(displaced)).snapshot)) {
|
|
230
|
+
// Restore exclusively: a concurrent entry, including a link,
|
|
231
|
+
// must survive even if it appears during this recovery attempt.
|
|
232
|
+
await fs.link(displaced, file.path);
|
|
233
|
+
restored = true;
|
|
234
|
+
}
|
|
235
|
+
} catch { /* Preserve the publication error and the exact-byte backup. */ }
|
|
236
|
+
}
|
|
237
|
+
if (error.code === 'EEXIST') throw fail(`Archivo concurrente preservado: ${file.name}.`);
|
|
238
|
+
throw error;
|
|
239
|
+
}
|
|
240
|
+
} finally {
|
|
241
|
+
await fs.unlink(temporary).catch(() => {});
|
|
242
|
+
if (displaced) await fs.unlink(displaced).catch(() => {});
|
|
243
|
+
if (backupPath) file.backupPath = backupPath;
|
|
244
|
+
if (restored) {
|
|
245
|
+
try {
|
|
246
|
+
const recovered = await inspect(file.path);
|
|
247
|
+
if (isOriginal(recovered.snapshot)) file.snapshot = recovered.snapshot;
|
|
248
|
+
} catch { /* A concurrent change still requires a fresh preview. */ }
|
|
249
|
+
}
|
|
250
|
+
trusted.dirs = dirs;
|
|
251
|
+
trusted.serialized = JSON.stringify(plan);
|
|
252
|
+
}
|
|
253
|
+
const published = await inspect(file.path);
|
|
254
|
+
if (published.snapshot.type !== 'file' || published.snapshot.hash !== digest(file.content)) throw fail(`Archivo concurrente: ${file.name}.`);
|
|
255
|
+
file.state = 'igual';
|
|
256
|
+
file.snapshot = published.snapshot;
|
|
257
|
+
trusted.serialized = JSON.stringify(plan);
|
|
258
|
+
}
|
|
259
|
+
trusted.dirs = dirs;
|
|
260
|
+
trusted.serialized = JSON.stringify(plan);
|
|
261
|
+
return plan;
|
|
262
|
+
}
|
|
@@ -0,0 +1,181 @@
|
|
|
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
|
+
|
|
6
|
+
const COUNTERS = ['input_tokens', 'cached_input_tokens', 'output_tokens', 'total_tokens'];
|
|
7
|
+
const MAX_RECORD_BYTES = 16384;
|
|
8
|
+
const MAX_RECORDS = 10000;
|
|
9
|
+
const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
10
|
+
const count = (value) => Number.isSafeInteger(value) && value >= 0 ? value : null;
|
|
11
|
+
|
|
12
|
+
function metadata(value, required = false) {
|
|
13
|
+
if (value == null && !required) return null;
|
|
14
|
+
if (typeof value !== 'string' || !value.trim() || value.length > 1024 || /[\u0000-\u001f\u007f]/u.test(value)) {
|
|
15
|
+
throw new TypeError('Metadatos de consumo Codex inválidos.');
|
|
16
|
+
}
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function normalize(payload) {
|
|
21
|
+
if (!isObject(payload) || payload.hook_event_name !== 'PostModelRequest') {
|
|
22
|
+
throw new TypeError('Evento de consumo Codex inválido.');
|
|
23
|
+
}
|
|
24
|
+
const usage = isObject(payload.token_usage) ? payload.token_usage : {};
|
|
25
|
+
const input = count(usage.input_tokens);
|
|
26
|
+
const output = count(usage.output_tokens);
|
|
27
|
+
let total = count(usage.total_tokens);
|
|
28
|
+
let cached = count(usage.cached_input_tokens ?? usage.input_tokens_details?.cached_tokens);
|
|
29
|
+
if (input !== null && cached !== null && cached > input) cached = null;
|
|
30
|
+
// This schema treats total as input + output, with cached input included once.
|
|
31
|
+
// A client with another definition needs an explicit schema adapter. Preserve
|
|
32
|
+
// component counts but discard a contradictory total, never invent a repair.
|
|
33
|
+
if (input !== null && output !== null && total !== null && BigInt(total) !== BigInt(input) + BigInt(output)) total = null;
|
|
34
|
+
return {
|
|
35
|
+
hook_event_name: 'PostModelRequest',
|
|
36
|
+
session_id: metadata(payload.session_id, true),
|
|
37
|
+
turn_id: metadata(payload.turn_id),
|
|
38
|
+
agent_id: metadata(payload.agent_id),
|
|
39
|
+
agent_type: metadata(payload.agent_type),
|
|
40
|
+
model: metadata(payload.model),
|
|
41
|
+
status: metadata(payload.status),
|
|
42
|
+
token_usage: {
|
|
43
|
+
input_tokens: input,
|
|
44
|
+
cached_input_tokens: cached,
|
|
45
|
+
output_tokens: output,
|
|
46
|
+
total_tokens: total,
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// CODEX_HOME configures the client, not NexaKit's private log root. This module
|
|
52
|
+
// never reads or writes that directory (including a supplied options.codexHome).
|
|
53
|
+
function storageDirectory(options, create) {
|
|
54
|
+
const home = path.resolve(options.homeDirectory ?? os.homedir());
|
|
55
|
+
if (!fs.lstatSync(home).isDirectory()) throw new Error('Directorio de consumo Codex no seguro.');
|
|
56
|
+
let directory = home;
|
|
57
|
+
for (const component of ['.nexakit', 'codex', 'usage']) {
|
|
58
|
+
directory = path.join(directory, component);
|
|
59
|
+
if (create) {
|
|
60
|
+
try { fs.mkdirSync(directory, { mode: 0o700 }); }
|
|
61
|
+
catch (error) { if (error.code !== 'EEXIST') throw new Error('No se pudo crear el registro Codex.'); }
|
|
62
|
+
}
|
|
63
|
+
let stat;
|
|
64
|
+
try { stat = fs.lstatSync(directory); }
|
|
65
|
+
catch (error) {
|
|
66
|
+
if (!create && error.code === 'ENOENT') return null;
|
|
67
|
+
throw new Error('No se pudo acceder al registro Codex.');
|
|
68
|
+
}
|
|
69
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error('Directorio de consumo Codex no seguro.');
|
|
70
|
+
if (create) fs.chmodSync(directory, 0o700);
|
|
71
|
+
}
|
|
72
|
+
return directory;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** One exclusive JSONL file per received event; never append to shared files.
|
|
76
|
+
* No official request ID exists: repeated turn_id values are neither retries
|
|
77
|
+
* nor duplicates. Re-delivery may therefore count an event twice.
|
|
78
|
+
* Returns the stored, allowlisted record; throws on invalid input/storage errors.
|
|
79
|
+
*/
|
|
80
|
+
export function recordCodexUsage(payload, options = {}) {
|
|
81
|
+
const normalized = normalize(payload);
|
|
82
|
+
const instant = typeof options.now === 'function' ? options.now() : options.now;
|
|
83
|
+
const date = instant === undefined ? new Date() : new Date(instant);
|
|
84
|
+
if (!Number.isFinite(date.getTime())) throw new TypeError('Fecha de consumo Codex inválida.');
|
|
85
|
+
const record = { version: 1, recorded_at: date.toISOString(), ...normalized };
|
|
86
|
+
const line = `${JSON.stringify(record)}\n`;
|
|
87
|
+
if (Buffer.byteLength(line) > MAX_RECORD_BYTES) throw new RangeError('Registro de consumo Codex demasiado grande.');
|
|
88
|
+
const directory = storageDirectory(options, true);
|
|
89
|
+
let fd;
|
|
90
|
+
try {
|
|
91
|
+
fd = fs.openSync(path.join(directory, `${randomUUID()}.jsonl`), 'wx', 0o600);
|
|
92
|
+
fs.writeFileSync(fd, line, 'utf8');
|
|
93
|
+
} catch {
|
|
94
|
+
throw new Error('No se pudo guardar el consumo Codex.');
|
|
95
|
+
} finally {
|
|
96
|
+
if (fd !== undefined) fs.closeSync(fd);
|
|
97
|
+
}
|
|
98
|
+
return record;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Bounded local snapshot, not live telemetry. Invalid records are skipped.
|
|
102
|
+
* Refuses unsafe directory paths; returns [] if storage has not been created.
|
|
103
|
+
*/
|
|
104
|
+
export function readCodexUsage(options = {}) {
|
|
105
|
+
const directory = storageDirectory(options, false);
|
|
106
|
+
if (directory === null) return [];
|
|
107
|
+
const records = [];
|
|
108
|
+
let entries = 0;
|
|
109
|
+
const dir = fs.opendirSync(directory);
|
|
110
|
+
try {
|
|
111
|
+
let entry;
|
|
112
|
+
while ((entry = dir.readSync()) !== null) {
|
|
113
|
+
if (++entries > MAX_RECORDS) throw new RangeError('Registro Codex supera el límite de lectura de 10000 archivos.');
|
|
114
|
+
if (!entry.isFile() || !entry.name.endsWith('.jsonl')) continue;
|
|
115
|
+
let fd;
|
|
116
|
+
try {
|
|
117
|
+
fd = fs.openSync(path.join(directory, entry.name), fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | fs.constants.O_NONBLOCK);
|
|
118
|
+
const stat = fs.fstatSync(fd);
|
|
119
|
+
if (!stat.isFile() || stat.nlink !== 1 || stat.size > MAX_RECORD_BYTES) continue;
|
|
120
|
+
// Fixed-size read also bounds files that grow after fstat.
|
|
121
|
+
const buffer = Buffer.alloc(MAX_RECORD_BYTES + 1);
|
|
122
|
+
const size = fs.readSync(fd, buffer, 0, buffer.length, 0);
|
|
123
|
+
if (size > MAX_RECORD_BYTES) continue;
|
|
124
|
+
const raw = buffer.subarray(0, size).toString('utf8').trim();
|
|
125
|
+
if (raw.includes('\n')) continue;
|
|
126
|
+
const parsed = JSON.parse(raw);
|
|
127
|
+
if (parsed.version !== 1 || typeof parsed.recorded_at !== 'string' || !Number.isFinite(Date.parse(parsed.recorded_at))) continue;
|
|
128
|
+
records.push({ version: 1, recorded_at: parsed.recorded_at, ...normalize(parsed) });
|
|
129
|
+
} catch {
|
|
130
|
+
// Partial concurrent writes, malformed records and symlinks are ignored.
|
|
131
|
+
} finally {
|
|
132
|
+
if (fd !== undefined) fs.closeSync(fd);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
} finally {
|
|
136
|
+
dir.closeSync();
|
|
137
|
+
}
|
|
138
|
+
return records.sort((a, b) => a.recorded_at.localeCompare(b.recorded_at));
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function aggregate(records) {
|
|
142
|
+
const token_usage = {};
|
|
143
|
+
const known_counts = {};
|
|
144
|
+
for (const key of COUNTERS) {
|
|
145
|
+
const values = records.map((record) => record.token_usage[key]).filter((value) => value !== null);
|
|
146
|
+
const sum = values.reduce((total, value) => total + BigInt(value), 0n);
|
|
147
|
+
token_usage[key] = values.length && sum <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(sum) : null;
|
|
148
|
+
known_counts[key] = values.length;
|
|
149
|
+
}
|
|
150
|
+
return { requests: records.length, token_usage, known_counts };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Known sums have per-counter coverage; null means unavailable or overflow.
|
|
154
|
+
* Cached input is already included in input_tokens. No costs are estimated.
|
|
155
|
+
* Attribution is explicit: main type, agent metadata, or unknown; no guessing.
|
|
156
|
+
*/
|
|
157
|
+
export function summarizeCodexUsage(records) {
|
|
158
|
+
if (!Array.isArray(records) || records.length > MAX_RECORDS) throw new TypeError('Lista de consumo Codex inválida o demasiado grande.');
|
|
159
|
+
const normalized = records.map(normalize);
|
|
160
|
+
const main = [], agents = [], unknown = [];
|
|
161
|
+
const statuses = new Map();
|
|
162
|
+
const models = new Map();
|
|
163
|
+
for (const record of normalized) {
|
|
164
|
+
(record.agent_type === 'main' ? main : record.agent_id !== null || record.agent_type !== null ? agents : unknown).push(record);
|
|
165
|
+
const status = record.status ?? 'unknown';
|
|
166
|
+
const model = record.model ?? 'unknown';
|
|
167
|
+
statuses.set(status, (statuses.get(status) ?? 0) + 1);
|
|
168
|
+
models.set(model, (models.get(model) ?? 0) + 1);
|
|
169
|
+
}
|
|
170
|
+
return {
|
|
171
|
+
...aggregate(normalized),
|
|
172
|
+
main: aggregate(main), agents: aggregate(agents), unknown: aggregate(unknown),
|
|
173
|
+
statuses: Object.fromEntries(statuses), models: Object.fromEntries(models),
|
|
174
|
+
limitations: [
|
|
175
|
+
'Muestra local de eventos recibidos; no es telemetría viva ni cobertura garantizada de todas las solicitudes.',
|
|
176
|
+
'Sin request id oficial: turn_id no identifica solicitudes, duplicados ni reintentos; cada evento recibido cuenta una vez.',
|
|
177
|
+
'Las sumas incluyen solo contadores conocidos; cached_input_tokens es parte de input_tokens. No se estiman costes.',
|
|
178
|
+
'Si input_tokens y output_tokens son conocidos, un total_tokens incompatible con su suma se marca null; otras definiciones de total requieren un adaptador explícito.',
|
|
179
|
+
],
|
|
180
|
+
};
|
|
181
|
+
}
|
package/src/level-agents.js
CHANGED
|
@@ -4,7 +4,7 @@ import os from "node:os";
|
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import { agentModels } from "./agent-models.js";
|
|
6
6
|
|
|
7
|
-
// Codex
|
|
7
|
+
// Codex level agents use local TOML files; Claude's come from the `niveles` plugin.
|
|
8
8
|
// The top level is "alto"; xhigh is asked per spawn, only after high failed.
|
|
9
9
|
const LEVELS = [["Ligero", "ligero"], ["Normal", "normal"], ["Exigente", "exigente"], ["Alto", "alto"]];
|
|
10
10
|
const USES = { ligero: "comandos, búsquedas, lecturas y cambios mecánicos", normal: "implementar con un diseño claro", exigente: "pruebas, casos borde o un fallo acotado", alto: "un fallo sutil, seguridad o lo que exigente no resolvió" };
|
|
@@ -15,7 +15,7 @@ o plan ya aprobado. Antes de un PR, quality-gate. Modo tutor (la persona
|
|
|
15
15
|
escribe el código, un paso verificable cada vez) solo si lo pide.
|
|
16
16
|
|
|
17
17
|
Orquesta: tú entiendes, planificas, decides e integras; delega la ejecución en
|
|
18
|
-
subagentes de nivel (Claude: niveles:nivel-<nivel>; Codex: nivel_<nivel>):
|
|
18
|
+
subagentes de nivel (Claude: niveles:nivel-<nivel>; Codex: nivel_<nivel>; Antigravity: nivel-<nivel>):
|
|
19
19
|
ligero para comandos, búsquedas y cambios mecánicos; normal para implementar
|
|
20
20
|
con diseño claro; exigente para pruebas, casos borde o un fallo acotado; alto
|
|
21
21
|
para un fallo sutil, seguridad o lo que exigente no resolvió. Trabaja tú solo
|