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
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { prepareCodex } from './codex-setup.js';
|
|
3
|
+
import { compareCodexSamples, readCodexSample } from './codex-compare.js';
|
|
4
|
+
|
|
5
|
+
const HELP = `Uso: nexakit codex auditar [--project ruta] [--json]
|
|
6
|
+
nexakit codex preparar [--salida carpeta] [--apply] [--json]
|
|
7
|
+
nexakit codex agentes [--apply] [--actualizar] [--json]
|
|
8
|
+
nexakit codex consumo [--json]
|
|
9
|
+
nexakit codex actividad [--json]
|
|
10
|
+
nexakit codex recomendar --tarea texto [--json]
|
|
11
|
+
nexakit codex hook
|
|
12
|
+
nexakit codex ejecutar -- programa argumentos
|
|
13
|
+
nexakit codex comparar --antes archivo --despues archivo [--json]\n`;
|
|
14
|
+
const FLAGS = { auditar: { '--project': 'value', '--json': 'bool' },
|
|
15
|
+
preparar: { '--salida': 'value', '--apply': 'bool', '--json': 'bool' },
|
|
16
|
+
agentes: { '--apply': 'bool', '--actualizar': 'bool', '--json': 'bool' },
|
|
17
|
+
consumo: { '--json': 'bool' }, actividad: { '--json': 'bool' }, recomendar: { '--tarea': 'value', '--json': 'bool' }, hook: {}, comparar: { '--antes': 'value', '--despues': 'value', '--json': 'bool' } };
|
|
18
|
+
function parse(command, argv) {
|
|
19
|
+
if (!Object.hasOwn(FLAGS, command)) throw new Error('Uso inválido.');
|
|
20
|
+
const result = {};
|
|
21
|
+
for (let i = 0; i < argv.length; i++) {
|
|
22
|
+
const flag = argv[i], kind = FLAGS[command][flag];
|
|
23
|
+
if (!Object.hasOwn(FLAGS[command], flag) || Object.hasOwn(result, flag)) throw new Error('Uso inválido.');
|
|
24
|
+
if (kind === 'bool') result[flag] = true;
|
|
25
|
+
else {
|
|
26
|
+
const value = argv[++i];
|
|
27
|
+
if (!value || value.startsWith('--')) throw new Error('Falta el valor.');
|
|
28
|
+
result[flag] = value;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
if (command === 'comparar' && (!result['--antes'] || !result['--despues'])) throw new Error('Faltan muestras.');
|
|
32
|
+
if (command === 'recomendar' && !result['--tarea']?.trim()) throw new Error('Falta la tarea.');
|
|
33
|
+
if (command === 'agentes' && result['--actualizar'] && !result['--apply']) throw new Error('Actualizar requiere apply.');
|
|
34
|
+
return result;
|
|
35
|
+
}
|
|
36
|
+
async function readHookInput(input) {
|
|
37
|
+
let size = 0;
|
|
38
|
+
const chunks = [];
|
|
39
|
+
for await (const chunk of input) {
|
|
40
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
41
|
+
size += buffer.length;
|
|
42
|
+
if (size > 1024 * 1024) throw new Error('Límite de entrada.');
|
|
43
|
+
chunks.push(buffer);
|
|
44
|
+
}
|
|
45
|
+
const payload = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
46
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload) || typeof payload.hook_event_name !== 'string') throw new Error('Payload inválido.');
|
|
47
|
+
return payload;
|
|
48
|
+
}
|
|
49
|
+
async function hook(io, options) {
|
|
50
|
+
let result = {};
|
|
51
|
+
try {
|
|
52
|
+
const payload = await readHookInput(io.input ?? process.stdin);
|
|
53
|
+
const { runCodexHook } = await import('./codex-hook.js');
|
|
54
|
+
result = await runCodexHook(payload, options) ?? {};
|
|
55
|
+
} catch {
|
|
56
|
+
await io.err('No se pudo procesar el hook de Codex; la sesión puede continuar.\n');
|
|
57
|
+
}
|
|
58
|
+
await io.out(JSON.stringify(result) + '\n');
|
|
59
|
+
return 0;
|
|
60
|
+
}
|
|
61
|
+
function formatComparison(report) {
|
|
62
|
+
return [`Tarea: ${report.task}`, `Comparabilidad: ${report.comparable ? 'sí' : 'no'}`,
|
|
63
|
+
...Object.entries(report.counters).map(([key, value]) => `${key}: ${value.saved ?? 'desconocido'} evitados; ${value.percent === null ? 'porcentaje no disponible' : `${value.percent.toFixed(2)}%`}; cobertura ${report.before.counters[key].known}/${report.before.calls} antes, ${report.after.counters[key].known}/${report.after.calls} después`),
|
|
64
|
+
...report.limitations, ''].join('\n');
|
|
65
|
+
}
|
|
66
|
+
function formatConsumption(report) {
|
|
67
|
+
const labels = { input_tokens: 'Entrada', cached_input_tokens: 'Entrada en caché (incluida en entrada)',
|
|
68
|
+
output_tokens: 'Salida', total_tokens: 'Total de tokens' };
|
|
69
|
+
const groups = [['Total', report], ['Principal', report.main], ['Subagentes', report.agents],
|
|
70
|
+
['Atribución desconocida', report.unknown]];
|
|
71
|
+
return ['Consumo Codex: cobertura de solicitudes registradas.',
|
|
72
|
+
...groups.flatMap(([label, group]) => [`${label}: ${group.requests} solicitudes`,
|
|
73
|
+
...Object.entries(labels).map(([key, name]) =>
|
|
74
|
+
` ${name}: ${group.token_usage[key] ?? 'desconocido'} (cobertura ${group.known_counts[key]}/${group.requests})`)]),
|
|
75
|
+
`Estados: ${Object.entries(report.statuses).map(([status, count]) => `${status}: ${count}`).join(', ') || 'sin datos'}`,
|
|
76
|
+
'Limitaciones:', ...report.limitations, ''].join('\n');
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Explicit allowlist: profile instructions and concurrency snapshots stay local.
|
|
80
|
+
function publicTeam(plan) {
|
|
81
|
+
return {
|
|
82
|
+
codexHome: plan.codexHome,
|
|
83
|
+
files: plan.files.map(({ name, kind, path, model, effort, state, backupPath }) => ({
|
|
84
|
+
name, kind, path, model, effort, state, ...(backupPath ? { backupPath } : {}),
|
|
85
|
+
})),
|
|
86
|
+
limitations: plan.limitations,
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
function formatTeam(report, apply) {
|
|
90
|
+
const rows = [['Nombre', 'Modelo', 'Esfuerzo', 'Estado'],
|
|
91
|
+
...report.files.map(file => [file.name, file.model ?? 'no disponible', file.effort ?? 'no disponible',
|
|
92
|
+
`${file.state}${['sin-modelo', 'sin-catalogo', 'bloqueado'].includes(file.state) ? ' (no instalado)' : ''}`])];
|
|
93
|
+
const widths = rows[0].map((_, index) => Math.max(...rows.map(row => row[index].length)));
|
|
94
|
+
return [apply ? 'Equipo de Codex: resultado de la aplicación.' : 'Vista previa: no se escribió ningún perfil.',
|
|
95
|
+
...rows.map(row => row.map((value, index) => value.padEnd(widths[index])).join(' ').trimEnd()),
|
|
96
|
+
...report.files.filter(file => file.backupPath).map(file => `Respaldo ${file.name}: ${file.backupPath}`),
|
|
97
|
+
'Limitaciones:', ...report.limitations, ''].join('\n');
|
|
98
|
+
}
|
|
99
|
+
async function teamCommand(flags, io, options) {
|
|
100
|
+
const { teamPlan, writeTeam } = await import('./codex-team.js');
|
|
101
|
+
let plan = await teamPlan(options);
|
|
102
|
+
if (flags['--apply']) plan = await writeTeam(plan, { update: Boolean(flags['--actualizar']) });
|
|
103
|
+
const report = publicTeam(plan);
|
|
104
|
+
await io.out(flags['--json'] ? JSON.stringify(report) + '\n' : formatTeam(report, Boolean(flags['--apply'])));
|
|
105
|
+
const blocked = plan.files.some(file => file.state === 'bloqueado');
|
|
106
|
+
const incomplete = plan.files.some(file => file.state !== 'igual');
|
|
107
|
+
return blocked || (flags['--apply'] && incomplete) ? 1 : 0;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function formatRecommendation(report) {
|
|
111
|
+
return [report.message,
|
|
112
|
+
report.recommendation ? `Recomendación: ${report.recommendation.model}; esfuerzo: ${report.recommendation.effort ?? 'no fijado'}.` : 'Recomendación no disponible.',
|
|
113
|
+
`Configuración guardada: ${report.stored ? `${report.stored.model}; esfuerzo: ${report.stored.effort ?? 'no fijado'}` : 'no comprobable'}. No acredita el estado activo; consulta /status.`,
|
|
114
|
+
`Razón: ${report.reason}`,
|
|
115
|
+
`Fuente: ${report.source}`,
|
|
116
|
+
`Acción: ${report.action ?? 'sin acción'}`,
|
|
117
|
+
...(report.delegate ? [`Subagente: ${report.delegate}`] : []),
|
|
118
|
+
...(report.command ? [`Comando: ${report.command}`] : []),
|
|
119
|
+
'Sin cambios automáticos.', ''].join('\n');
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export async function runCodexCommand(argv, io, options = {}) {
|
|
123
|
+
const [command, ...rest] = argv;
|
|
124
|
+
if (argv.length === 1 && ['--help', '-h'].includes(command)) { await io.out(HELP); return 0; }
|
|
125
|
+
if (command === 'ejecutar') {
|
|
126
|
+
if (rest[0] !== '--' || !rest[1]) { await io.err(HELP); return 2; }
|
|
127
|
+
try {
|
|
128
|
+
const { runCodexOutput } = await import('./codex-output.js');
|
|
129
|
+
return await runCodexOutput(rest.slice(1), io, options);
|
|
130
|
+
} catch { await io.err('No se pudo ejecutar el programa.\n'); return 1; }
|
|
131
|
+
}
|
|
132
|
+
let flags;
|
|
133
|
+
try { flags = parse(command, rest); }
|
|
134
|
+
catch { await io.err(HELP); return 2; }
|
|
135
|
+
if (command === 'hook') return hook(io, options);
|
|
136
|
+
try {
|
|
137
|
+
if (command === 'actividad') {
|
|
138
|
+
const { readCodexAgentEvents } = await import('./codex-events.js');
|
|
139
|
+
const events = await readCodexAgentEvents(options);
|
|
140
|
+
const limitations = ['Eventos locales recibidos; no acreditan cobertura completa, éxito de la tarea ni consumo del subagente.'];
|
|
141
|
+
const report = { events, limitations };
|
|
142
|
+
await io.out(flags['--json'] ? JSON.stringify(report) + '\n' : [
|
|
143
|
+
'Actividad local de subagentes (últimos 50 eventos):',
|
|
144
|
+
...events.slice(-50).map(event => `${event.recorded_at} ${event.hook_event_name} ${event.agent_type} id=${event.agent_id} modelo=${event.model ?? 'desconocido'}`),
|
|
145
|
+
...limitations, '',
|
|
146
|
+
].join('\n'));
|
|
147
|
+
return 0;
|
|
148
|
+
}
|
|
149
|
+
if (command === 'agentes') return await teamCommand(flags, io, options);
|
|
150
|
+
let report;
|
|
151
|
+
if (command === 'recomendar') {
|
|
152
|
+
const { recommendCodexTask } = await import('./codex-recommendation.js');
|
|
153
|
+
report = await recommendCodexTask(flags['--tarea'], { ...options, includeAntigravity: false });
|
|
154
|
+
} else if (command === 'preparar') report = await prepareCodex({ ...options, outputDirectory: flags['--salida'], apply: Boolean(flags['--apply']) });
|
|
155
|
+
else if (command === 'comparar') {
|
|
156
|
+
const before = await readCodexSample(flags['--antes']);
|
|
157
|
+
const after = await readCodexSample(flags['--despues']);
|
|
158
|
+
report = compareCodexSamples(before, after);
|
|
159
|
+
} else if (command === 'auditar') {
|
|
160
|
+
const { auditCodex } = await import('./codex-audit.js');
|
|
161
|
+
report = await auditCodex({ ...options, projectRoot: path.resolve(flags['--project'] ?? options.projectRoot ?? process.cwd()) });
|
|
162
|
+
} else {
|
|
163
|
+
const { readCodexUsage, summarizeCodexUsage } = await import('./codex-usage.js');
|
|
164
|
+
report = summarizeCodexUsage(await readCodexUsage(options));
|
|
165
|
+
}
|
|
166
|
+
await io.out(flags['--json'] ? JSON.stringify(report) + '\n' :
|
|
167
|
+
command === 'recomendar' ? formatRecommendation(report) : command === 'comparar' ? formatComparison(report) : command === 'consumo' ? formatConsumption(report) : JSON.stringify(report, null, 2) + '\n');
|
|
168
|
+
return 0;
|
|
169
|
+
} catch {
|
|
170
|
+
await io.err('No se pudo completar el comando Codex. Revisa formato, calidad, rutas y permisos.\n');
|
|
171
|
+
return 1;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { constants } from 'node:fs';
|
|
4
|
+
import { normalizeMeasurement, summarizeMeasurements, USAGE_COUNTERS } from './usage-metrics.js';
|
|
5
|
+
|
|
6
|
+
const MAX_SAMPLE_BYTES = 1024 * 1024;
|
|
7
|
+
function normalizeSample(sample) {
|
|
8
|
+
if (!sample || typeof sample.task !== 'string' || !sample.task.trim() || sample.task.length > 500 ||
|
|
9
|
+
sample.quality?.passed !== true || !Array.isArray(sample.measurements)) {
|
|
10
|
+
throw new Error('La muestra exige task, quality.passed=true y measurements.');
|
|
11
|
+
}
|
|
12
|
+
const measurements = sample.measurements.map(normalizeMeasurement);
|
|
13
|
+
if (new Set(measurements.map(item => item.id)).size !== measurements.length) {
|
|
14
|
+
throw new Error('Mediciones duplicadas.');
|
|
15
|
+
}
|
|
16
|
+
return { task: sample.task, measurements };
|
|
17
|
+
}
|
|
18
|
+
const provenance = records => [...new Set(records.map(({ agent, phase, model, source }) =>
|
|
19
|
+
JSON.stringify([agent, phase, model, source])))].sort();
|
|
20
|
+
|
|
21
|
+
export function compareCodexSamples(beforeSample, afterSample) {
|
|
22
|
+
const before = normalizeSample(beforeSample), after = normalizeSample(afterSample);
|
|
23
|
+
if (before.task !== after.task) throw new Error('Las muestras deben declarar la misma tarea.');
|
|
24
|
+
const comparable = before.measurements.length > 0 && after.measurements.length > 0 &&
|
|
25
|
+
JSON.stringify(provenance(before.measurements)) === JSON.stringify(provenance(after.measurements));
|
|
26
|
+
const beforeSummary = summarizeMeasurements(before.measurements);
|
|
27
|
+
const afterSummary = summarizeMeasurements(after.measurements);
|
|
28
|
+
const counters = Object.fromEntries(USAGE_COUNTERS.map(key => {
|
|
29
|
+
const a = beforeSummary.counters[key], b = afterSummary.counters[key];
|
|
30
|
+
const complete = comparable && a.complete && b.complete;
|
|
31
|
+
return [key, { saved: complete ? a.sum - b.sum : null,
|
|
32
|
+
percent: complete && a.sum > 0 ? (a.sum - b.sum) / a.sum * 100 : null }];
|
|
33
|
+
}));
|
|
34
|
+
return { task: before.task, comparable, before: beforeSummary, after: afterSummary, counters,
|
|
35
|
+
limitations: ['Muestras declaradas; cobertura limitada a llamadas registradas.',
|
|
36
|
+
'La caché es un subconjunto de entrada; no se suma al total.',
|
|
37
|
+
...(comparable ? [] : ['Procedencia distinta o muestras vacías: ahorro no comparable.'])] };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export async function readCodexSample(filename) {
|
|
41
|
+
filename = path.resolve(filename);
|
|
42
|
+
let ancestor = path.dirname(filename);
|
|
43
|
+
while (true) {
|
|
44
|
+
if ((await fs.lstat(ancestor)).isSymbolicLink()) throw new Error('No se admiten enlaces simbólicos en las muestras.');
|
|
45
|
+
const parent = path.dirname(ancestor);
|
|
46
|
+
if (parent === ancestor) break;
|
|
47
|
+
ancestor = parent;
|
|
48
|
+
}
|
|
49
|
+
const stat = await fs.lstat(filename);
|
|
50
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_SAMPLE_BYTES) throw new Error('Muestra inválida o demasiado grande.');
|
|
51
|
+
const handle = await fs.open(filename, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | constants.O_NONBLOCK);
|
|
52
|
+
try {
|
|
53
|
+
const current = await handle.stat();
|
|
54
|
+
if (!current.isFile() || current.size > MAX_SAMPLE_BYTES || current.ino !== stat.ino || current.dev !== stat.dev) {
|
|
55
|
+
throw new Error('La muestra cambió durante la lectura.');
|
|
56
|
+
}
|
|
57
|
+
const buffer = Buffer.alloc(MAX_SAMPLE_BYTES + 1);
|
|
58
|
+
let size = 0;
|
|
59
|
+
while (size < buffer.length) {
|
|
60
|
+
const { bytesRead } = await handle.read(buffer, size, buffer.length - size, null);
|
|
61
|
+
if (!bytesRead) break;
|
|
62
|
+
size += bytesRead;
|
|
63
|
+
}
|
|
64
|
+
if (size > MAX_SAMPLE_BYTES) throw new Error('Muestra demasiado grande.');
|
|
65
|
+
return JSON.parse(buffer.subarray(0, size).toString('utf8'));
|
|
66
|
+
} finally { await handle.close(); }
|
|
67
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
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 MAX_RECORD_BYTES = 16384;
|
|
7
|
+
const MAX_ENTRIES = 10000;
|
|
8
|
+
const invalidMetadata = () => new TypeError('Metadatos de agentes Codex inválidos.');
|
|
9
|
+
|
|
10
|
+
function metadata(value, required = false, model = false) {
|
|
11
|
+
if (value == null && !required) return null;
|
|
12
|
+
if (typeof value !== 'string' || !value.trim() || value.length > (model ? 100 : 200) ||
|
|
13
|
+
/[\u0000-\u001f\u007f-\u009f]/u.test(value) ||
|
|
14
|
+
(model && !/^[a-zA-Z0-9][a-zA-Z0-9._:/+-]*$/u.test(value))) {
|
|
15
|
+
throw invalidMetadata();
|
|
16
|
+
}
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function normalize(payload) {
|
|
21
|
+
if (payload === null || typeof payload !== 'object' || Array.isArray(payload) ||
|
|
22
|
+
!['SubagentStart', 'SubagentStop'].includes(payload.hook_event_name)) throw invalidMetadata();
|
|
23
|
+
return {
|
|
24
|
+
hook_event_name: payload.hook_event_name,
|
|
25
|
+
session_id: metadata(payload.session_id, true),
|
|
26
|
+
agent_id: metadata(payload.agent_id, true),
|
|
27
|
+
agent_type: metadata(payload.agent_type, true),
|
|
28
|
+
model: metadata(payload.model, false, true),
|
|
29
|
+
turn_id: metadata(payload.turn_id),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Check every ancestor, including the supplied home: resolving symlinks would
|
|
34
|
+
// silently authorize a different storage location. Only the private suffix is created.
|
|
35
|
+
function storageDirectory(options, create) {
|
|
36
|
+
const home = path.resolve(options.homeDirectory ?? os.homedir());
|
|
37
|
+
const root = path.parse(home).root;
|
|
38
|
+
const ancestors = home.slice(root.length).split(path.sep).filter(Boolean);
|
|
39
|
+
let directory = root;
|
|
40
|
+
for (const [index, component] of [...ancestors, '.nexakit', 'codex', 'agents'].entries()) {
|
|
41
|
+
directory = path.join(directory, component);
|
|
42
|
+
const privateDirectory = index >= ancestors.length;
|
|
43
|
+
try {
|
|
44
|
+
if (create && privateDirectory) {
|
|
45
|
+
try { fs.mkdirSync(directory, { mode: 0o700 }); }
|
|
46
|
+
catch (error) { if (error.code !== 'EEXIST') throw error; }
|
|
47
|
+
}
|
|
48
|
+
const stat = fs.lstatSync(directory);
|
|
49
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error();
|
|
50
|
+
if (create && privateDirectory) fs.chmodSync(directory, 0o700);
|
|
51
|
+
} catch (error) {
|
|
52
|
+
if (!create && error.code === 'ENOENT') return null;
|
|
53
|
+
throw new Error('Directorio de agentes Codex no seguro.');
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return directory;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** One private, exclusive JSONL file per event. No payload content is persisted. */
|
|
60
|
+
export function recordCodexAgentEvent(payload, options = {}) {
|
|
61
|
+
const normalized = normalize(payload);
|
|
62
|
+
const instant = typeof options.now === 'function' ? options.now() : options.now;
|
|
63
|
+
const date = instant === undefined ? new Date() : new Date(instant);
|
|
64
|
+
if (!Number.isFinite(date.getTime())) throw new TypeError('Fecha de agentes Codex inválida.');
|
|
65
|
+
const record = { version: 1, recorded_at: date.toISOString(), ...normalized };
|
|
66
|
+
const directory = storageDirectory(options, true);
|
|
67
|
+
let fd;
|
|
68
|
+
try {
|
|
69
|
+
fd = fs.openSync(path.join(directory, `${randomUUID()}.jsonl`), 'wx', 0o600);
|
|
70
|
+
fs.writeFileSync(fd, `${JSON.stringify(record)}\n`, 'utf8');
|
|
71
|
+
} catch {
|
|
72
|
+
throw new Error('No se pudo guardar el evento de agentes Codex.');
|
|
73
|
+
} finally {
|
|
74
|
+
if (fd !== undefined) fs.closeSync(fd);
|
|
75
|
+
}
|
|
76
|
+
return record;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Bounded snapshot: malformed/unsafe files are skipped; exceeded limits throw. */
|
|
80
|
+
export function readCodexAgentEvents(options = {}) {
|
|
81
|
+
const directory = storageDirectory(options, false);
|
|
82
|
+
if (directory === null) return [];
|
|
83
|
+
const records = [];
|
|
84
|
+
const dir = fs.opendirSync(directory);
|
|
85
|
+
let entries = 0;
|
|
86
|
+
try {
|
|
87
|
+
let entry;
|
|
88
|
+
while ((entry = dir.readSync()) !== null) {
|
|
89
|
+
if (++entries > MAX_ENTRIES) throw new RangeError('Registro de agentes Codex supera 10000 entradas.');
|
|
90
|
+
if (!entry.isFile() || !entry.name.endsWith('.jsonl')) continue;
|
|
91
|
+
let fd;
|
|
92
|
+
try {
|
|
93
|
+
const file = path.join(directory, entry.name);
|
|
94
|
+
const before = fs.lstatSync(file);
|
|
95
|
+
if (!before.isFile() || before.nlink !== 1) continue;
|
|
96
|
+
fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0));
|
|
97
|
+
const stat = fs.fstatSync(fd);
|
|
98
|
+
if (!stat.isFile() || stat.nlink !== 1 || before.dev !== stat.dev || before.ino !== stat.ino) continue;
|
|
99
|
+
if (stat.size > MAX_RECORD_BYTES) throw new RangeError('Registro de agentes Codex supera 16KiB.');
|
|
100
|
+
// One extra byte detects growth since fstat without unbounded allocation.
|
|
101
|
+
const buffer = Buffer.alloc(MAX_RECORD_BYTES + 1);
|
|
102
|
+
const size = fs.readSync(fd, buffer, 0, buffer.length, 0);
|
|
103
|
+
if (size > MAX_RECORD_BYTES) throw new RangeError('Registro de agentes Codex supera 16KiB.');
|
|
104
|
+
const after = fs.lstatSync(file);
|
|
105
|
+
if (!after.isFile() || after.nlink !== 1 || after.dev !== stat.dev || after.ino !== stat.ino) continue;
|
|
106
|
+
const raw = buffer.subarray(0, size).toString('utf8').trim();
|
|
107
|
+
if (raw.includes('\n')) continue;
|
|
108
|
+
const parsed = JSON.parse(raw);
|
|
109
|
+
if (parsed?.version !== 1 || typeof parsed.recorded_at !== 'string' || !Number.isFinite(Date.parse(parsed.recorded_at))) continue;
|
|
110
|
+
records.push({ version: 1, recorded_at: parsed.recorded_at, ...normalize(parsed) });
|
|
111
|
+
} catch (error) {
|
|
112
|
+
if (error instanceof RangeError) throw error;
|
|
113
|
+
// Partial concurrent writes, malformed records and unsafe files are ignored.
|
|
114
|
+
} finally {
|
|
115
|
+
if (fd !== undefined) fs.closeSync(fd);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
} finally {
|
|
119
|
+
dir.closeSync();
|
|
120
|
+
}
|
|
121
|
+
return records.sort((a, b) => Date.parse(a.recorded_at) - Date.parse(b.recorded_at));
|
|
122
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { recordCodexUsage } from './codex-usage.js';
|
|
2
|
+
|
|
3
|
+
const SESSION_GUIDANCE = 'Configura y ordena la barra nativa con /statusline; una terminal estrecha puede truncarla. Los avisos de recomendación local de NexaKit aparecen al enviar tareas, separados del pie y sin cambios automáticos: usa /model para elegir y /status para consultar la sesión. Consulta los hilos del equipo con /subagents. Los perfiles instalados se cargan al abrir sesión; usa solo los registrados en tus herramientas. El principal orquesta, decide e integra; resuelve tareas pequeñas directamente y delega las de más de 1–2 pasos con un encargo acotado y verifica el informe; no cambies modelo ni esfuerzo sin autorización. Para salidas voluminosas usa explícitamente nexakit codex ejecutar -- programa argumentos. Mantén breves las salidas y reutiliza el contexto ya disponible.';
|
|
4
|
+
const COMPACT_GUIDANCE = 'Retoma el trabajo ya autorizado; conserva rama, objetivo, restricciones, decisiones confirmadas, archivos modificados, pruebas y siguiente paso. No inicies tareas nuevas ni escribas memoria del proyecto sin autorización.';
|
|
5
|
+
|
|
6
|
+
/** Returns the JSON object the caller serializes to stdout. Never logs payloads
|
|
7
|
+
* or provider errors. Guidance uses the hooks systemMessage/additionalContext
|
|
8
|
+
* envelopes; client/version support must be verified when installing hooks.
|
|
9
|
+
*/
|
|
10
|
+
export async function runCodexHook(payload, options = {}) {
|
|
11
|
+
try {
|
|
12
|
+
if (payload === null || typeof payload !== 'object' || Array.isArray(payload) || typeof payload.hook_event_name !== 'string') {
|
|
13
|
+
throw new TypeError('Evento inválido.');
|
|
14
|
+
}
|
|
15
|
+
switch (payload.hook_event_name) {
|
|
16
|
+
case 'PreToolUse': {
|
|
17
|
+
const { rewriteCodexToolInput } = await import('./codex-pre-tool.js');
|
|
18
|
+
return rewriteCodexToolInput(payload, options);
|
|
19
|
+
}
|
|
20
|
+
case 'SubagentStart':
|
|
21
|
+
case 'SubagentStop': {
|
|
22
|
+
const { recordCodexAgentEvent } = await import('./codex-events.js');
|
|
23
|
+
await recordCodexAgentEvent(payload, options);
|
|
24
|
+
return {};
|
|
25
|
+
}
|
|
26
|
+
case 'PostToolUse': {
|
|
27
|
+
const { compactCodexToolOutput } = await import('./codex-auto-output.js');
|
|
28
|
+
return await compactCodexToolOutput(payload, options);
|
|
29
|
+
}
|
|
30
|
+
case 'PostModelRequest':
|
|
31
|
+
await recordCodexUsage(payload, options);
|
|
32
|
+
return {};
|
|
33
|
+
case 'SessionStart': {
|
|
34
|
+
let context = SESSION_GUIDANCE;
|
|
35
|
+
try {
|
|
36
|
+
const { installedTeam } = await import('./codex-team.js');
|
|
37
|
+
const names = await installedTeam(options);
|
|
38
|
+
if (names.length) context += ` Equipo instalado: ${names.join(', ')}.`;
|
|
39
|
+
} catch { /* Optional inspection must not suppress session guidance. */ }
|
|
40
|
+
return { hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: context } };
|
|
41
|
+
}
|
|
42
|
+
case 'PreCompact':
|
|
43
|
+
case 'PostCompact':
|
|
44
|
+
return { systemMessage: COMPACT_GUIDANCE };
|
|
45
|
+
// No official context occupancy counter is available in this contract.
|
|
46
|
+
// Accumulated request tokens cannot measure the current context window.
|
|
47
|
+
case 'UserPromptSubmit': {
|
|
48
|
+
const { recommendCodexTask } = await import('./codex-recommendation.js');
|
|
49
|
+
const result = await recommendCodexTask(payload.prompt ?? '', { ...options, includeAntigravity: false });
|
|
50
|
+
if (result.silent) return {};
|
|
51
|
+
const response = { systemMessage: result.message };
|
|
52
|
+
try {
|
|
53
|
+
const { installedTeam } = await import('./codex-team.js');
|
|
54
|
+
const { routeCodexTask } = await import('./codex-routing.js');
|
|
55
|
+
const { context } = routeCodexTask(payload.prompt, { installedNames: await installedTeam(options) });
|
|
56
|
+
if (context) response.hookSpecificOutput = { hookEventName: 'UserPromptSubmit', additionalContext: context };
|
|
57
|
+
} catch {
|
|
58
|
+
try { process.stderr.write('NexaKit: no se pudo orientar el equipo Codex.\n'); } catch { /* fail open */ }
|
|
59
|
+
}
|
|
60
|
+
return response;
|
|
61
|
+
}
|
|
62
|
+
default:
|
|
63
|
+
return {};
|
|
64
|
+
}
|
|
65
|
+
} catch {
|
|
66
|
+
try { process.stderr.write('NexaKit: no se pudo procesar el evento Codex.\n'); } catch { /* fail open */ }
|
|
67
|
+
return {};
|
|
68
|
+
}
|
|
69
|
+
}
|
|
@@ -0,0 +1,223 @@
|
|
|
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 { spawn } from 'node:child_process';
|
|
6
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
7
|
+
import { compactarSalida } from '../plugins/nexakit-ahorro/hooks/compactar.js';
|
|
8
|
+
|
|
9
|
+
const FAILURE = /(error|fail|falla|✖|✗|not ok|exception|traceback|panic|assert|warn|denied|refused|cannot|no se pudo)/iu;
|
|
10
|
+
const emit = (sink, text) => typeof sink === 'function' ? sink(text) : sink.write(text);
|
|
11
|
+
|
|
12
|
+
// No full-output array: at most 12k exact characters and bounded line samples.
|
|
13
|
+
function sampler() {
|
|
14
|
+
const decoder = new StringDecoder('utf8');
|
|
15
|
+
let exact = '', chars = 0, newlines = 0, start = '', end = '', window = '', failure = '', long = false;
|
|
16
|
+
const head = [], tail = [], failures = [];
|
|
17
|
+
function line() {
|
|
18
|
+
const value = long ? `${start.slice(0, 140)} … ${failure.slice(0, 140)} … ${end.slice(-100)}` : start;
|
|
19
|
+
if (head.length < 20) head.push(value);
|
|
20
|
+
else {
|
|
21
|
+
tail.push(value);
|
|
22
|
+
if (tail.length > 40) {
|
|
23
|
+
const middle = tail.shift();
|
|
24
|
+
if (FAILURE.test(middle) && failures.length < 40 && !failures.includes(middle)) failures.push(middle);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
start = ''; end = ''; window = ''; failure = ''; long = false;
|
|
28
|
+
}
|
|
29
|
+
function accept(text) {
|
|
30
|
+
chars += text.length;
|
|
31
|
+
if (exact !== null) exact = chars <= 12000 ? exact + text : null;
|
|
32
|
+
let offset = 0;
|
|
33
|
+
while (offset < text.length) {
|
|
34
|
+
const newline = text.indexOf('\n', offset);
|
|
35
|
+
const piece = text.slice(offset, newline < 0 ? text.length : newline);
|
|
36
|
+
if (start.length + piece.length > 400) long = true;
|
|
37
|
+
start = (start + piece).slice(0, 400);
|
|
38
|
+
end = (end + piece).slice(-180);
|
|
39
|
+
const search = window + piece;
|
|
40
|
+
const match = FAILURE.exec(search);
|
|
41
|
+
if (match && !failure) failure = search.slice(Math.max(0, match.index - 30), match.index + 200);
|
|
42
|
+
window = search.slice(-40);
|
|
43
|
+
if (newline < 0) break;
|
|
44
|
+
newlines++; line(); offset = newline + 1;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return {
|
|
48
|
+
push(chunk) { accept(decoder.write(chunk)); },
|
|
49
|
+
finish(ruta) {
|
|
50
|
+
accept(decoder.end()); line();
|
|
51
|
+
if (exact !== null) {
|
|
52
|
+
const result = compactarSalida(exact, { ruta });
|
|
53
|
+
return { text: result.texto, chars, lines: chars ? newlines + 1 : 0, trimmed: result.omitidas > 0 };
|
|
54
|
+
}
|
|
55
|
+
// Force the shared formatter to apply its bounded line policy. The filler
|
|
56
|
+
// represents omitted middle lines, never the full output in memory.
|
|
57
|
+
const selected = [...head, ...Array(121).fill(''), ...failures, ...tail];
|
|
58
|
+
const result = compactarSalida(selected.join('\n'), { ruta });
|
|
59
|
+
const kept = head.length + failures.length + tail.length;
|
|
60
|
+
const text = result.texto.replace(/\d+ líneas omitidas de \d+/u, `${Math.max(0, newlines + 1 - kept)} líneas omitidas de ${newlines + 1}`);
|
|
61
|
+
return { text, chars, lines: newlines + 1, trimmed: true };
|
|
62
|
+
},
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Reject symlinks in every existing component, including supplied home paths.
|
|
67
|
+
function directory(target, create = false) {
|
|
68
|
+
const absolute = path.resolve(target);
|
|
69
|
+
let current = path.parse(absolute).root;
|
|
70
|
+
for (const part of absolute.slice(current.length).split(path.sep).filter(Boolean)) {
|
|
71
|
+
current = path.join(current, part);
|
|
72
|
+
try {
|
|
73
|
+
const stat = fs.lstatSync(current);
|
|
74
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error('Directorio inseguro');
|
|
75
|
+
} catch (error) {
|
|
76
|
+
if (error.code !== 'ENOENT' || !create) throw error;
|
|
77
|
+
try { fs.mkdirSync(current, { mode: 0o700 }); }
|
|
78
|
+
catch (created) { if (created.code !== 'EEXIST') throw created; }
|
|
79
|
+
const stat = fs.lstatSync(current);
|
|
80
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error('Directorio inseguro');
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return absolute;
|
|
84
|
+
}
|
|
85
|
+
function privateDirectory(target) {
|
|
86
|
+
directory(target, true);
|
|
87
|
+
fs.chmodSync(target, 0o700);
|
|
88
|
+
return target;
|
|
89
|
+
}
|
|
90
|
+
function writeAll(fd, chunk) {
|
|
91
|
+
let offset = 0;
|
|
92
|
+
while (offset < chunk.length) {
|
|
93
|
+
const written = fs.writeSync(fd, chunk, offset, chunk.length - offset);
|
|
94
|
+
if (!written) throw new Error('Escritura incompleta');
|
|
95
|
+
offset += written;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
function record(home, row) {
|
|
99
|
+
directory(home);
|
|
100
|
+
const target = path.join(home, 'ahorro.jsonl');
|
|
101
|
+
try {
|
|
102
|
+
const stat = fs.lstatSync(target);
|
|
103
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1) throw new Error('Registro inseguro');
|
|
104
|
+
} catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
105
|
+
const fd = fs.openSync(target, fs.constants.O_WRONLY | fs.constants.O_APPEND | fs.constants.O_CREAT | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK, 0o600);
|
|
106
|
+
try {
|
|
107
|
+
const stat = fs.fstatSync(fd);
|
|
108
|
+
if (!stat.isFile() || stat.nlink !== 1) throw new Error('Registro inseguro');
|
|
109
|
+
fs.fchmodSync(fd, 0o600);
|
|
110
|
+
writeAll(fd, Buffer.from(JSON.stringify(row) + '\n'));
|
|
111
|
+
} finally { fs.closeSync(fd); }
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Execute literal argv once. If storage fails, replay the saved prefix (mixed
|
|
115
|
+
* channels on stdout), then pass both streams through without compacting.
|
|
116
|
+
* If replay also fails, show the bounded retained samples before live output.
|
|
117
|
+
* Full mode streams immediately; the disk copy still remains private.
|
|
118
|
+
* Windows .cmd/.bat files require an explicit interpreter in argv; for npm,
|
|
119
|
+
* pass node and npm-cli.js, preserving shell:false and literal arguments.
|
|
120
|
+
*/
|
|
121
|
+
export async function runCodexOutput(argv, { out, err, input }, options = {}) {
|
|
122
|
+
if (!Array.isArray(argv) || !argv.length || argv.some(arg => typeof arg !== 'string') || !argv[0]) {
|
|
123
|
+
emit(err, 'nexakit: falta programa o argumentos inválidos\n');
|
|
124
|
+
return 2;
|
|
125
|
+
}
|
|
126
|
+
const env = options.env ?? process.env;
|
|
127
|
+
const bypass = env.NEXAKIT_SALIDA === 'completa';
|
|
128
|
+
const samples = [sampler(), sampler()];
|
|
129
|
+
const sinks = [out, err];
|
|
130
|
+
const liveDecoders = [new StringDecoder('utf8'), new StringDecoder('utf8')];
|
|
131
|
+
let fd, ruta, home, saved = 0, fallback = false;
|
|
132
|
+
try {
|
|
133
|
+
// Automatic wrapping runs inside the tool sandbox. Its private temporary
|
|
134
|
+
// store requires no additional access to the real user home.
|
|
135
|
+
const root = env.NEXAKIT_CODEX_TEMP_OUTPUT === '1'
|
|
136
|
+
? privateDirectory(path.join(directory(fs.realpathSync(options.tempDirectory ?? os.tmpdir())), `nexakit-codex-${process.getuid?.() ?? 'user'}`))
|
|
137
|
+
: directory(options.homeDirectory ?? os.homedir());
|
|
138
|
+
home = privateDirectory(path.join(root, '.nexakit'));
|
|
139
|
+
const folder = privateDirectory(path.join(home, 'salidas'));
|
|
140
|
+
ruta = path.join(folder, `${Date.now()}-${randomUUID()}.log`);
|
|
141
|
+
fd = fs.openSync(ruta, fs.constants.O_RDWR | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600);
|
|
142
|
+
} catch {
|
|
143
|
+
fallback = true;
|
|
144
|
+
emit(err, 'nexakit: no se pudo guardar la salida; se muestra completa.\n');
|
|
145
|
+
}
|
|
146
|
+
function capture(index, chunk) {
|
|
147
|
+
if (!fallback) {
|
|
148
|
+
try { writeAll(fd, chunk); saved += chunk.length; }
|
|
149
|
+
catch {
|
|
150
|
+
fallback = true;
|
|
151
|
+
emit(err, 'nexakit: no se pudo guardar la salida; se reproduce el prefijo combinado y se muestra completa.\n');
|
|
152
|
+
if (!bypass) {
|
|
153
|
+
const buffer = Buffer.alloc(65536);
|
|
154
|
+
const decoder = new StringDecoder('utf8');
|
|
155
|
+
try {
|
|
156
|
+
for (let offset = 0; offset < saved;) {
|
|
157
|
+
const size = fs.readSync(fd, buffer, 0, Math.min(buffer.length, saved - offset), offset);
|
|
158
|
+
if (!size) break;
|
|
159
|
+
emit(out, decoder.write(buffer.subarray(0, size))); offset += size;
|
|
160
|
+
}
|
|
161
|
+
emit(out, decoder.end());
|
|
162
|
+
} catch {
|
|
163
|
+
emit(err, 'nexakit: no se pudo recuperar el prefijo guardado; se muestra la muestra retenida.\n');
|
|
164
|
+
for (const [sampleIndex, sample] of samples.entries()) emit(sinks[sampleIndex], sample.finish(ruta).text);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
if (fallback || bypass) emit(sinks[index], liveDecoders[index].write(chunk));
|
|
170
|
+
else samples[index].push(chunk);
|
|
171
|
+
}
|
|
172
|
+
let exitCode;
|
|
173
|
+
try {
|
|
174
|
+
exitCode = await new Promise(resolve => {
|
|
175
|
+
let child;
|
|
176
|
+
try {
|
|
177
|
+
child = spawn(argv[0], argv.slice(1), {
|
|
178
|
+
shell: false, cwd: options.projectRoot ?? process.cwd(), env,
|
|
179
|
+
stdio: [input == null ? 'inherit' : 'pipe', 'pipe', 'pipe'],
|
|
180
|
+
});
|
|
181
|
+
} catch (error) {
|
|
182
|
+
emit(err, `nexakit: ${error.code ?? 'spawn error'}\n`); resolve(error.code === 'ENOENT' ? 127 : 1); return;
|
|
183
|
+
}
|
|
184
|
+
let spawnError;
|
|
185
|
+
child.stdout.on('data', chunk => capture(0, chunk));
|
|
186
|
+
child.stderr.on('data', chunk => capture(1, chunk));
|
|
187
|
+
child.on('error', error => {
|
|
188
|
+
spawnError = error.code === 'ENOENT' ? 127 : 1;
|
|
189
|
+
emit(err, `nexakit: ${error.code ?? 'spawn error'}\n`);
|
|
190
|
+
});
|
|
191
|
+
if (input != null) {
|
|
192
|
+
child.stdin.on('error', error => { if (error.code !== 'EPIPE') emit(err, 'nexakit: fallo de stdin\n'); });
|
|
193
|
+
if (typeof input.pipe === 'function') {
|
|
194
|
+
input.pipe(child.stdin);
|
|
195
|
+
child.once('close', () => input.unpipe(child.stdin));
|
|
196
|
+
} else child.stdin.end(input);
|
|
197
|
+
}
|
|
198
|
+
child.on('close', (code, signal) => resolve(spawnError ?? code ?? (128 + (os.constants.signals[signal] ?? 0))));
|
|
199
|
+
});
|
|
200
|
+
} finally {
|
|
201
|
+
if (fd !== undefined) {
|
|
202
|
+
try { fs.closeSync(fd); }
|
|
203
|
+
catch { emit(err, 'nexakit: no se pudo cerrar la copia de salida.\n'); }
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
if (fallback || bypass) {
|
|
207
|
+
for (const [index, decoder] of liveDecoders.entries()) emit(sinks[index], decoder.end());
|
|
208
|
+
}
|
|
209
|
+
if (!fallback && !bypass) {
|
|
210
|
+
const results = samples.map(sample => sample.finish(ruta));
|
|
211
|
+
for (const [index, result] of results.entries()) emit(sinks[index], result.text);
|
|
212
|
+
const before = results.reduce((sum, result) => sum + result.chars, 0);
|
|
213
|
+
const after = results.reduce((sum, result) => sum + result.text.length, 0);
|
|
214
|
+
const linesBefore = results.reduce((sum, result) => sum + result.lines, 0);
|
|
215
|
+
const linesAfter = results.reduce((sum, result) => sum + (result.text ? result.text.split('\n').length : 0), 0);
|
|
216
|
+
if (results.some(result => result.trimmed) && before > after && linesBefore >= linesAfter) {
|
|
217
|
+
try {
|
|
218
|
+
record(home, { fecha: Date.now(), antes: before, despues: after, lineasAntes: linesBefore, lineasDespues: linesAfter, agent: 'codex' });
|
|
219
|
+
} catch { emit(err, 'nexakit: no se pudo guardar el registro de ahorro.\n'); }
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
return exitCode;
|
|
223
|
+
}
|