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.
@@ -0,0 +1,75 @@
1
+ import { posix } from 'node:path';
2
+ import { fileURLToPath } from 'node:url';
3
+
4
+ const ENTRYPOINT = fileURLToPath(new URL('../bin/nexakit.js', import.meta.url));
5
+ const TASKS = new Set(['test', 'build', 'lint', 'check']);
6
+ const MANAGERS = new Set(['npm', 'pnpm', 'yarn', 'bun']);
7
+ const NODE_SWITCHES = new Set(['--test-only', '--test-force-exit', '--test-coverage', '--experimental-test-coverage']);
8
+ const NODE_VALUES = new Map([
9
+ ['--test-reporter', /^(?:tap|spec|dot)$/u],
10
+ ['--test-concurrency', /^[1-9][0-9]*$/u],
11
+ ['--test-timeout', /^[1-9][0-9]*$/u],
12
+ ['--test-name-pattern', /^[A-Za-z0-9_./:@%+=,-]+$/u],
13
+ ['--test-skip-pattern', /^[A-Za-z0-9_./:@%+=,-]+$/u],
14
+ ]);
15
+ const isRecord = value => value !== null && typeof value === 'object' && !Array.isArray(value);
16
+ const quote = token => `'${token.replaceAll("'", "'\"'\"'")}'`;
17
+ const safeAbsolute = value => typeof value === 'string' && posix.isAbsolute(value) &&
18
+ value.length <= 4096 && !/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/u.test(value);
19
+
20
+ function nodeTests(argv) {
21
+ if (argv[1] !== '--test') return false;
22
+ let filesOnly = false;
23
+ for (let index = 2; index < argv.length; index++) {
24
+ const token = argv[index];
25
+ if (!filesOnly && token === '--') { filesOnly = true; continue; }
26
+ if (!filesOnly && token.startsWith('-')) {
27
+ if (NODE_SWITCHES.has(token)) continue;
28
+ const equals = token.indexOf('=');
29
+ const name = equals < 0 ? token : token.slice(0, equals);
30
+ const pattern = NODE_VALUES.get(name);
31
+ if (!pattern) return false;
32
+ const value = equals < 0 ? argv[++index] : token.slice(equals + 1);
33
+ if (typeof value !== 'string' || !pattern.test(value)) return false;
34
+ } else if (token.startsWith('-') || !/\.(?:js|cjs|mjs)$/u.test(token)) return false;
35
+ }
36
+ return true;
37
+ }
38
+
39
+ function approved(argv) {
40
+ // Conservative bypass: preserve interactive and structured-output commands intact.
41
+ if (argv.some(token => /watch|inspect|interactive|tty|background/iu.test(token) ||
42
+ /^(?:-w|-i|-t|-it|-ti|--ui|--open|--debug)(?:=|$)/u.test(token) ||
43
+ /(?:^|[-=,:])json(?:l)?(?:$|[-=,:])/iu.test(token))) return false;
44
+ if (argv[0] === 'node') return nodeTests(argv);
45
+ if (!MANAGERS.has(argv[0])) return false;
46
+ return argv[1] === 'test' || (argv[1] === 'run' && TASKS.has(argv[2])) ||
47
+ (argv[0] === 'yarn' && TASKS.has(argv[1]));
48
+ }
49
+
50
+ /** Pure, synchronous PreToolUse rewrite. Unknown inputs always retain their original route. */
51
+ export function rewriteCodexToolInput(payload, options = {}) {
52
+ if ((options.platform ?? process.platform) === 'win32' ||
53
+ (options.environment ?? process.env).NEXAKIT_SALIDA === 'completa' ||
54
+ !isRecord(payload) || payload.hook_event_name !== 'PreToolUse' || payload.tool_name !== 'Bash' ||
55
+ !isRecord(payload.tool_input)) return {};
56
+ const input = payload.tool_input;
57
+ if (('sandbox_permissions' in input && input.sandbox_permissions !== 'use_default') ||
58
+ ['tty', 'interactive', 'background', 'run_in_background'].some(key => input[key])) return {};
59
+ const command = input.command;
60
+ // ASCII-only grammar makes this length limit also a byte limit. Only literal spaces separate tokens.
61
+ if (typeof command !== 'string' || command.length > 16 * 1024 ||
62
+ !/^[A-Za-z0-9_./:@%+=, -]+$/u.test(command)) return {};
63
+ const argv = command.trim().split(/ +/u);
64
+ if (!approved(argv)) return {};
65
+ const executable = options.executable ?? process.execPath;
66
+ const entrypoint = options.entrypoint ?? ENTRYPOINT;
67
+ if (!safeAbsolute(executable) || !safeAbsolute(entrypoint)) return {};
68
+ const wrapper = 'NEXAKIT_CODEX_TEMP_OUTPUT=1 ' +
69
+ [executable, entrypoint, 'codex', 'ejecutar', '--', ...argv].map(quote).join(' ');
70
+ return { hookSpecificOutput: {
71
+ hookEventName: 'PreToolUse',
72
+ permissionDecision: 'allow',
73
+ updatedInput: { ...input, command: wrapper },
74
+ } };
75
+ }
@@ -0,0 +1,92 @@
1
+ import { inspectModels } from './model-command.js';
2
+ import { recomendarPorTexto } from '../plugins/nexakit-modelo/hooks/recomendar.js';
3
+
4
+ const ROLES = { haiku: 'ligero', sonnet: 'uso diario', opus: 'el más capaz' };
5
+ const CONFIRMATION = /^(?:¡?)(?:s[ií]|ok|okay|dale|listo|vale|perfecto|bien|contin[uú]a|sigue|hazlo|adelante|gracias|de una|claro|no)(?:[\s.!,¡]+(?:s[ií]|ok|okay|dale|listo|vale|perfecto|bien|contin[uú]a|sigue|hazlo|adelante|gracias|de una|claro|no))*[\s.!,]*$/iu;
6
+ const validModel = (value) => typeof value === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/u.test(value)
7
+ && !/(?:claude|haiku|sonnet|opus)/iu.test(value);
8
+ const validEffort = (value) => typeof value === 'string' && /^[a-z][a-z0-9_-]{0,23}$/u.test(value);
9
+
10
+ function emptyResult(reason, silent = false) {
11
+ return {
12
+ available: false, silent, recommendation: null, stored: null,
13
+ action: silent ? 'keep' : 'unavailable', delegate: null, command: null, reason,
14
+ message: silent ? '' : `NexaKit recomienda consultar /model: ${reason}.`,
15
+ source: 'local-catalog', automaticChange: false,
16
+ };
17
+ }
18
+
19
+ // Reads local catalog/config only. A saved preference never establishes the active session state.
20
+ export async function recommendCodexTask(text, options = {}) {
21
+ if (typeof text !== 'string' || Buffer.byteLength(text, 'utf8') > 16 * 1024) {
22
+ return emptyResult('texto no válido o superior al límite de 16 KiB');
23
+ }
24
+ const task = text.trim();
25
+ if (!task || CONFIRMATION.test(task)) return emptyResult('', true);
26
+
27
+ const classification = recomendarPorTexto(task);
28
+ const role = ROLES[classification.model];
29
+ let data;
30
+ try {
31
+ data = await inspectModels({ ...options, includeAntigravity: false });
32
+ } catch {
33
+ return emptyResult('catálogo local no disponible o inválido');
34
+ }
35
+ const saved = data.stored.codex;
36
+ const stored = saved && validModel(saved.model) && (saved.effort == null || validEffort(saved.effort))
37
+ ? { model: saved.model, effort: saved.effort ?? null } : null;
38
+ const candidates = data.catalogs.codex
39
+ .filter((item) => item.category === role && validModel(item.model))
40
+ .sort((a, b) => a.priority - b.priority);
41
+ // Routine and design use the model's actual default, not the classifier's effort.
42
+ const useDefault = classification.effort === 'medium';
43
+ let chosen, effort, fallback = '';
44
+ for (const candidate of candidates) {
45
+ const supports = (value) => validEffort(value) && candidate.efforts.includes(value);
46
+ const preferred = useDefault ? candidate.defaultEffort : classification.effort;
47
+ if (supports(preferred)) {
48
+ chosen = candidate;
49
+ effort = preferred;
50
+ break;
51
+ }
52
+ if (supports(candidate.defaultEffort)) {
53
+ chosen = candidate;
54
+ effort = candidate.defaultEffort;
55
+ fallback = `; ${classification.effort} no disponible: defecto soportado`;
56
+ break;
57
+ }
58
+ // Design can still use medium when that effort is explicitly offered.
59
+ if (useDefault && role === 'el más capaz' && supports('medium')) {
60
+ chosen = candidate;
61
+ effort = 'medium';
62
+ fallback = '; defecto no disponible: medium soportado';
63
+ break;
64
+ }
65
+ }
66
+ if (!chosen) {
67
+ return { ...emptyResult('sin modelo y esfuerzo soportados para esta tarea en el catálogo local'), stored };
68
+ }
69
+
70
+ const delegate = classification.delegar === 'nivel-ligero' ? 'nivel_ligero'
71
+ : classification.delegar === 'nivel-alto' ? 'nivel_alto' : null;
72
+ let reason = delegate === 'nivel_ligero' ? 'tarea mecánica'
73
+ : delegate === 'nivel_alto' ? 'fallo difícil o seguridad'
74
+ : role === 'el más capaz' ? 'diseño o ambigüedad'
75
+ : classification.effort === 'high' ? 'fallo o pruebas: verificar importa'
76
+ : classification.effort === 'low' ? 'pregunta breve'
77
+ : 'trabajo habitual: esfuerzo por defecto del catálogo';
78
+ reason += fallback;
79
+ const recommendation = { model: chosen.model, effort };
80
+ const command = `/model ${chosen.model} --reasoning=${effort}`;
81
+ const action = delegate ? 'delegate' : stored?.model !== chosen.model ? 'model'
82
+ : stored.effort !== effort ? 'effort' : 'keep';
83
+ const savedLabel = stored ? ` Guardado: ${stored.model} / ${stored.effort ?? 'sin esfuerzo'}.` : ' Guardado: no comprobable.';
84
+ const proposal = delegate
85
+ ? `delegar a ${delegate}; conserva el principal. Alternativa: ${command}`
86
+ : command;
87
+ return {
88
+ available: true, silent: false, recommendation, stored, action, delegate, command, reason,
89
+ message: `NexaKit recomienda ${proposal}. Razón: ${reason}.${savedLabel}`,
90
+ source: 'local-catalog', automaticChange: false,
91
+ };
92
+ }
@@ -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
+ }