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,218 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
5
|
+
import { parseTOML, getStaticTOMLValue } from 'toml-eslint-parser';
|
|
6
|
+
|
|
7
|
+
const MAX_FILE = 256 * 1024;
|
|
8
|
+
const MAX_METADATA = 8192;
|
|
9
|
+
const MAX_ENTRIES = 512;
|
|
10
|
+
const inside = (root, file) => {
|
|
11
|
+
const relative = path.relative(root, file);
|
|
12
|
+
return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
|
|
13
|
+
};
|
|
14
|
+
const countTables = value => value && typeof value === 'object' && !Array.isArray(value) ? Object.keys(value).length : 0;
|
|
15
|
+
|
|
16
|
+
function selectSettings(config) {
|
|
17
|
+
const settings = {};
|
|
18
|
+
// Only short, conventional model identifiers and known enum values are exposed.
|
|
19
|
+
if (typeof config.model === 'string' && /^(?:gpt-|o[1-9]|codex-)[a-z0-9.-]{1,70}$/.test(config.model)) settings.model = config.model;
|
|
20
|
+
if (['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'].includes(config.model_reasoning_effort)) settings.model_reasoning_effort = config.model_reasoning_effort;
|
|
21
|
+
if (['fast', 'flex', 'standard', 'default', 'auto'].includes(config.service_tier)) settings.service_tier = config.service_tier;
|
|
22
|
+
const integer = value => Number.isSafeInteger(value) && value >= 0;
|
|
23
|
+
if (integer(config.tool_output_token_limit)) settings.tool_output_token_limit = config.tool_output_token_limit;
|
|
24
|
+
if (integer(config.skills?.max_context_tokens)) settings.skills = { max_context_tokens: config.skills.max_context_tokens };
|
|
25
|
+
if (integer(config.agents?.max_concurrent_threads_per_session)) settings.agents = { max_concurrent_threads_per_session: config.agents.max_concurrent_threads_per_session };
|
|
26
|
+
return settings;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Bounded local audit: only whitelisted settings and validated relative locators are exposed. */
|
|
30
|
+
export function auditCodex({ projectRoot = process.cwd(), codexHome, homeDirectory = os.homedir() } = {}) {
|
|
31
|
+
codexHome = path.resolve(codexHome ?? process.env.CODEX_HOME ?? path.join(homeDirectory, '.codex'));
|
|
32
|
+
projectRoot = path.resolve(projectRoot);
|
|
33
|
+
homeDirectory = path.resolve(homeDirectory);
|
|
34
|
+
const report = {
|
|
35
|
+
findings: [],
|
|
36
|
+
coverage: {
|
|
37
|
+
partial: true,
|
|
38
|
+
inspected: ['codex-home-config', 'skill-catalog-metadata', 'user-project-instructions'],
|
|
39
|
+
notInspected: ['remote-plugins', 'profiles', 'project-config', 'ancestor-instructions'],
|
|
40
|
+
message: 'Auditoría parcial: no se inspeccionan plugins remotos, perfiles, configuración del proyecto ni instrucciones de ancestros; los enlaces externos se omiten.',
|
|
41
|
+
},
|
|
42
|
+
summary: { skills: 0, skillBytes: 0, metadataBytes: 0, instructionFiles: 0, instructionBytes: 0, mcpServers: 0, plugins: 0, omitted: 0 },
|
|
43
|
+
recommendations: [
|
|
44
|
+
{ code: 'CATALOG_BUDGET', setting: 'skills.max_context_tokens', message: 'Usar el presupuesto nativo del catálogo de skills; antes de reducirlo, comprobar advertencias, descripciones y omisiones.' },
|
|
45
|
+
{ code: 'OUTPUT_BUDGET', setting: 'tool_output_token_limit', proposedValue: 4000, officialDefault: false, message: 'Propuesta local: evaluar 4000 tokens por salida y recuperar el log completo cuando haga falta; no es un valor predeterminado oficial.' },
|
|
46
|
+
{ code: 'EFFORT', message: 'Elegir esfuerzo proporcional a la tarea y comprobar calidad antes de reducirlo; no se modifica la configuración.' },
|
|
47
|
+
{ code: 'DELEGATION', message: 'Delegar tareas independientes con encargos breves y limitar la concurrencia según la tarea; no se modifica la configuración.' },
|
|
48
|
+
{ code: 'MCP', message: 'Revisar los MCP y plugins habilitados y habilitar solo los necesarios para la tarea; no se cambia ninguno.' },
|
|
49
|
+
],
|
|
50
|
+
settings: {},
|
|
51
|
+
};
|
|
52
|
+
const finding = (code, message, fields = {}) => report.findings.push({ code, severity: code.endsWith('MISSING') ? 'info' : 'warning', message, ...fields });
|
|
53
|
+
const omit = scope => { report.summary.omitted++; finding('PATH_OMITTED', 'Ruta o enlace omitido por estar fuera del ámbito autorizado.', { scope }); };
|
|
54
|
+
const issue = (error, scope) => {
|
|
55
|
+
if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') finding('READ_FAILED', 'No se pudo inspeccionar un archivo local.', { scope });
|
|
56
|
+
};
|
|
57
|
+
const realBase = base => { try { return fs.realpathSync(base); } catch { return path.resolve(base); } };
|
|
58
|
+
|
|
59
|
+
// A caller-selected base is authorized; symlinks below it must stay inside it.
|
|
60
|
+
function safeFile(file, roots, scope, allowSymlink = false) {
|
|
61
|
+
try {
|
|
62
|
+
if (!allowSymlink && fs.lstatSync(file).isSymbolicLink()) { omit(scope); return null; }
|
|
63
|
+
const real = fs.realpathSync(file);
|
|
64
|
+
if (!roots.some(root => inside(root, real))) { omit(scope); return null; }
|
|
65
|
+
const descriptor = fs.openSync(real, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
|
|
66
|
+
const stat = fs.fstatSync(descriptor);
|
|
67
|
+
if (!stat.isFile()) { fs.closeSync(descriptor); omit(scope); return null; }
|
|
68
|
+
return { descriptor, stat, real };
|
|
69
|
+
} catch (error) { issue(error, scope); return null; }
|
|
70
|
+
}
|
|
71
|
+
function readSmall(file, root, scope) {
|
|
72
|
+
const opened = safeFile(file, [realBase(root)], scope);
|
|
73
|
+
if (!opened) return null;
|
|
74
|
+
try {
|
|
75
|
+
if (opened.stat.size > MAX_FILE) { finding('READ_LIMIT', 'Archivo omitido por superar el límite de lectura.', { scope, limitBytes: MAX_FILE }); return null; }
|
|
76
|
+
// Fixed buffer also bounds reads if the file grows after fstat.
|
|
77
|
+
const buffer = Buffer.alloc(MAX_FILE + 1);
|
|
78
|
+
const length = fs.readSync(opened.descriptor, buffer, 0, buffer.length, 0);
|
|
79
|
+
if (length > MAX_FILE) { finding('READ_LIMIT', 'Archivo omitido por superar el límite de lectura.', { scope, limitBytes: MAX_FILE }); return null; }
|
|
80
|
+
return buffer.subarray(0, length);
|
|
81
|
+
} finally { fs.closeSync(opened.descriptor); }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const configText = readSmall(path.join(codexHome, 'config.toml'), codexHome, 'config');
|
|
85
|
+
if (configText) {
|
|
86
|
+
try {
|
|
87
|
+
const config = getStaticTOMLValue(parseTOML(configText.toString('utf8')));
|
|
88
|
+
report.settings = selectSettings(config);
|
|
89
|
+
report.summary.mcpServers = countTables(config.mcp_servers);
|
|
90
|
+
report.summary.plugins = countTables(config.plugins);
|
|
91
|
+
} catch { finding('CONFIG_INVALID', 'TOML inválido; se omiten los valores de configuración.'); }
|
|
92
|
+
} else {
|
|
93
|
+
try { fs.lstatSync(path.join(codexHome, 'config.toml')); }
|
|
94
|
+
catch (error) { if (error.code === 'ENOENT') finding('CONFIG_MISSING', 'No hay configuración de Codex en este ámbito.'); }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const catalogs = [
|
|
98
|
+
{ scope: 'user-skills', base: homeDirectory, root: path.join(homeDirectory, '.agents/skills') },
|
|
99
|
+
{ scope: 'codex-skills', base: codexHome, root: path.join(codexHome, 'skills') },
|
|
100
|
+
{ scope: 'project-skills', base: projectRoot, root: path.join(projectRoot, '.agents/skills') },
|
|
101
|
+
];
|
|
102
|
+
const roots = [];
|
|
103
|
+
for (const catalog of catalogs) {
|
|
104
|
+
try {
|
|
105
|
+
let component = catalog.base;
|
|
106
|
+
let linked = false;
|
|
107
|
+
for (const part of path.relative(catalog.base, catalog.root).split(path.sep)) {
|
|
108
|
+
component = path.join(component, part);
|
|
109
|
+
if (fs.lstatSync(component).isSymbolicLink()) { linked = true; break; }
|
|
110
|
+
}
|
|
111
|
+
if (linked) { omit(catalog.scope); continue; }
|
|
112
|
+
const real = fs.realpathSync(catalog.root);
|
|
113
|
+
if (!inside(realBase(catalog.base), real)) { omit(catalog.scope); continue; }
|
|
114
|
+
roots.push({ ...catalog, real });
|
|
115
|
+
} catch (error) { issue(error, catalog.scope); }
|
|
116
|
+
}
|
|
117
|
+
const allowedRoots = roots.map(root => root.real);
|
|
118
|
+
const seenFiles = new Set();
|
|
119
|
+
const names = new Map();
|
|
120
|
+
let entries = 0;
|
|
121
|
+
let limited = false;
|
|
122
|
+
|
|
123
|
+
function metadata(file, scope, directory) {
|
|
124
|
+
const opened = safeFile(file, allowedRoots, scope, true);
|
|
125
|
+
if (!opened) return;
|
|
126
|
+
try {
|
|
127
|
+
if (seenFiles.has(opened.real)) return;
|
|
128
|
+
seenFiles.add(opened.real);
|
|
129
|
+
report.summary.skills++;
|
|
130
|
+
report.summary.skillBytes += opened.stat.size;
|
|
131
|
+
// Stop exactly at the frontmatter closing line, without reading the body.
|
|
132
|
+
const bytes = Buffer.alloc(MAX_METADATA);
|
|
133
|
+
let used = 0;
|
|
134
|
+
let lineStart = 0;
|
|
135
|
+
let closed = false;
|
|
136
|
+
while (used < bytes.length) {
|
|
137
|
+
if (!fs.readSync(opened.descriptor, bytes, used, 1, null)) {
|
|
138
|
+
if (lineStart > 0 && bytes.subarray(lineStart, used).toString('utf8').trim() === '---') closed = true;
|
|
139
|
+
break;
|
|
140
|
+
}
|
|
141
|
+
used++;
|
|
142
|
+
if (bytes[used - 1] !== 10) continue;
|
|
143
|
+
const line = bytes.subarray(lineStart, used).toString('utf8').trim();
|
|
144
|
+
if (lineStart === 0 && line !== '---') break;
|
|
145
|
+
if (lineStart > 0 && line === '---') { closed = true; break; }
|
|
146
|
+
lineStart = used;
|
|
147
|
+
}
|
|
148
|
+
report.summary.metadataBytes += used;
|
|
149
|
+
if (!closed) {
|
|
150
|
+
finding(used === MAX_METADATA ? 'READ_LIMIT' : 'SKILL_METADATA_INVALID', 'Metadatos omitidos por ser incompletos o superar el límite.', { scope, limitBytes: MAX_METADATA });
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
const lines = bytes.subarray(0, used).toString('utf8').split(/\r?\n/);
|
|
154
|
+
const scalar = key => {
|
|
155
|
+
const index = lines.findIndex(line => line.startsWith(`${key}:`));
|
|
156
|
+
if (index < 0) return '';
|
|
157
|
+
let value = lines[index].slice(key.length + 1).trim();
|
|
158
|
+
if (/^[>|][-+]?$/.test(value)) {
|
|
159
|
+
value = '';
|
|
160
|
+
for (let i = index + 1; i < lines.length && /^\s/.test(lines[i]); i++) value += ` ${lines[i].trim()}`;
|
|
161
|
+
}
|
|
162
|
+
return value.replace(/^(['"])(.*)\1$/, '$2').trim();
|
|
163
|
+
};
|
|
164
|
+
const name = scalar('name');
|
|
165
|
+
const description = scalar('description');
|
|
166
|
+
const location = {
|
|
167
|
+
scope,
|
|
168
|
+
directory: directory.length <= 220 && directory.split('/').every(part => part === '.system' || /^[a-z0-9][a-z0-9._-]{0,99}$/.test(part)) ? directory : 'omitido',
|
|
169
|
+
};
|
|
170
|
+
const locator = { skillName: /^[a-z0-9-]{1,100}$/.test(name) ? name : 'omitido', locations: [location] };
|
|
171
|
+
if (!name || !description) finding('SKILL_METADATA_INVALID', 'La skill no tiene nombre o descripción utilizable.', { scope });
|
|
172
|
+
if (name) names.set(name, [...(names.get(name) ?? []), location]);
|
|
173
|
+
if (description.length > 1024) finding('SKILL_DESCRIPTION_LONG', 'Descripción extensa; conviene delimitar cuándo usar la skill.', { ...locator, characters: description.length });
|
|
174
|
+
if (/\b(everything|anything|all tasks|any task|siempre|todo|cualquier tarea)\b/i.test(description)) finding('SKILL_DESCRIPTION_BROAD', 'Descripción amplia; conviene acotar sus condiciones de activación.', locator);
|
|
175
|
+
} finally { fs.closeSync(opened.descriptor); }
|
|
176
|
+
}
|
|
177
|
+
function scan(directory, scope, depth = 0, prefix = '') {
|
|
178
|
+
let handle;
|
|
179
|
+
try {
|
|
180
|
+
handle = fs.opendirSync(directory);
|
|
181
|
+
for (let entry; (entry = handle.readSync());) {
|
|
182
|
+
if (entries >= MAX_ENTRIES) { limited = true; break; }
|
|
183
|
+
entries++;
|
|
184
|
+
if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
|
|
185
|
+
try {
|
|
186
|
+
const child = path.join(directory, entry.name);
|
|
187
|
+
const real = fs.realpathSync(child);
|
|
188
|
+
if (!allowedRoots.some(root => inside(root, real))) { omit(scope); continue; }
|
|
189
|
+
const relativeDirectory = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
190
|
+
if (entry.name === '.system' && depth === 0) scan(real, scope, 1, relativeDirectory);
|
|
191
|
+
else metadata(path.join(real, 'SKILL.md'), scope, relativeDirectory);
|
|
192
|
+
} catch (error) {
|
|
193
|
+
if (entry.isSymbolicLink()) omit(scope);
|
|
194
|
+
else issue(error, scope);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
} catch (error) { issue(error, scope); }
|
|
198
|
+
finally { handle?.closeSync(); }
|
|
199
|
+
}
|
|
200
|
+
for (const root of roots) scan(root.real, root.scope);
|
|
201
|
+
if (limited) finding('CATALOG_LIMIT', 'Catálogo parcial: se alcanzó el límite global de entradas.', { limit: MAX_ENTRIES });
|
|
202
|
+
for (const [name, locations] of names) if (locations.length > 1) finding('SKILL_DUPLICATE_NAME', 'Varias skills comparten el mismo nombre.', {
|
|
203
|
+
skillName: /^[a-z0-9-]{1,100}$/.test(name) ? name : 'omitido', locations, count: locations.length,
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
const hashes = new Map();
|
|
207
|
+
for (const [base, scope] of [[codexHome, 'user-instructions'], [projectRoot, 'project-instructions']]) {
|
|
208
|
+
const text = readSmall(path.join(base, 'AGENTS.md'), base, scope);
|
|
209
|
+
if (!text) continue;
|
|
210
|
+
report.summary.instructionFiles++;
|
|
211
|
+
report.summary.instructionBytes += text.length;
|
|
212
|
+
if (!text.toString('utf8').trim()) continue;
|
|
213
|
+
const hash = createHash('sha256').update(text).digest('hex');
|
|
214
|
+
hashes.set(hash, (hashes.get(hash) ?? 0) + 1);
|
|
215
|
+
}
|
|
216
|
+
for (const count of hashes.values()) if (count > 1) finding('INSTRUCTIONS_DUPLICATE', 'Las instrucciones de usuario y proyecto son idénticas.', { count });
|
|
217
|
+
return report;
|
|
218
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
import { compactarSalida } from '../plugins/nexakit-ahorro/hooks/compactar.js';
|
|
6
|
+
|
|
7
|
+
const MAX_BYTES = 1024 * 1024;
|
|
8
|
+
const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
9
|
+
const blocked = value => ['session_id', 'signal', 'backgroundTaskId'].some(key => key in value)
|
|
10
|
+
|| Boolean(value.isError || value.is_error || value.interrupted);
|
|
11
|
+
const FAILURE = /(error|fail|falla|✖|✗|not ok|exception|traceback|panic|assert|warn|denied|refused|cannot|no se pudo)/iu;
|
|
12
|
+
|
|
13
|
+
function responseText(response) {
|
|
14
|
+
if (typeof response === 'string') {
|
|
15
|
+
if (Buffer.byteLength(response, 'utf8') > MAX_BYTES) return null;
|
|
16
|
+
const match = /^(?:(?:Chunk ID: [^\r\n]+|Wall time: [^\r\n]+)\r?\n)*Process exited with code 0\r?\n(?:(?:Wall time: [^\r\n]+|Total output lines: \d+)\r?\n)*Final output:\r?\n([\s\S]*)$/u.exec(response);
|
|
17
|
+
if (match) return { text: match[1], original: response, json: false, exit: 0 };
|
|
18
|
+
// Native Codex can deliver just the model-facing text, without exit status.
|
|
19
|
+
// Never infer success; preserve error-like text and ambiguous/live envelopes.
|
|
20
|
+
if (FAILURE.test(response) || /^(?:Chunk ID:|Wall time:|Process exited|Process running)/u.test(response)) return null;
|
|
21
|
+
return { text: response, original: response, json: false, exit: null };
|
|
22
|
+
}
|
|
23
|
+
if (!object(response) || blocked(response) || response.exit_code !== 0) return null;
|
|
24
|
+
let text;
|
|
25
|
+
if (typeof response.output === 'string' && !('stdout' in response) && !('stderr' in response)) {
|
|
26
|
+
text = response.output;
|
|
27
|
+
} else if (!('output' in response) && typeof response.stdout === 'string' && typeof response.stderr === 'string') {
|
|
28
|
+
text = response.stdout + (response.stderr ? `\n${response.stderr}` : '');
|
|
29
|
+
} else return null;
|
|
30
|
+
return { text, original: JSON.stringify(response), json: true, exit: 0 };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function privateFolder(homeDirectory) {
|
|
34
|
+
const home = path.resolve(homeDirectory);
|
|
35
|
+
const target = path.join(home, '.nexakit', 'codex', 'salidas');
|
|
36
|
+
let current = path.parse(target).root;
|
|
37
|
+
for (const part of target.slice(current.length).split(path.sep).filter(Boolean)) {
|
|
38
|
+
current = path.join(current, part);
|
|
39
|
+
try {
|
|
40
|
+
const stat = fs.lstatSync(current);
|
|
41
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error('Unsafe directory');
|
|
42
|
+
} catch (error) {
|
|
43
|
+
if (error.code !== 'ENOENT') throw error;
|
|
44
|
+
fs.mkdirSync(current, { mode: 0o700 });
|
|
45
|
+
}
|
|
46
|
+
if (current === path.join(home, '.nexakit') || current === path.join(home, '.nexakit/codex') || current === target) {
|
|
47
|
+
fs.chmodSync(current, 0o700);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return target;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Returns hook JSON only; never executes the command, writes to stdout/stderr,
|
|
54
|
+
* or changes a process exit status. Unsupported inputs and storage errors fail open.
|
|
55
|
+
*/
|
|
56
|
+
export async function compactCodexToolOutput(payload, options = {}) {
|
|
57
|
+
try {
|
|
58
|
+
if (!object(payload) || payload.hook_event_name !== 'PostToolUse' || payload.tool_name !== 'Bash'
|
|
59
|
+
|| payload.isError || payload.is_error || payload.interrupted) return {};
|
|
60
|
+
if ((options.environment ?? process.env).NEXAKIT_SALIDA === 'completa') return {};
|
|
61
|
+
const command = payload.tool_input?.command;
|
|
62
|
+
if (typeof command === 'string' && /^\s*NEXAKIT_SALIDA=completa(?:\s|$)/u.test(command)) return {};
|
|
63
|
+
const response = responseText(payload.tool_response);
|
|
64
|
+
if (!response || Buffer.byteLength(response.original, 'utf8') > MAX_BYTES) return {};
|
|
65
|
+
if (!compactarSalida(response.text).omitidas) return {};
|
|
66
|
+
const home = options.homeDirectory ?? os.homedir();
|
|
67
|
+
const file = path.join(path.resolve(home), '.nexakit', 'codex', 'salidas', `${randomUUID()}.${response.json ? 'json' : 'log'}`);
|
|
68
|
+
const { texto } = compactarSalida(response.text, { ruta: file });
|
|
69
|
+
const status = response.exit === null ? 'desconocido (el hook no recibió el estado; este resumen no acredita éxito)' : '0';
|
|
70
|
+
const result = { continue: false, stopReason: `exit_code: ${status}\n${texto}\nOriginal completo (${response.json ? 'JSON de tool_response' : 'texto exacto de tool_response'}): ${file}` };
|
|
71
|
+
if (Buffer.byteLength(JSON.stringify(result), 'utf8') >= Buffer.byteLength(response.original, 'utf8')) return {};
|
|
72
|
+
privateFolder(home);
|
|
73
|
+
const fd = fs.openSync(file, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | (fs.constants.O_NOFOLLOW ?? 0), 0o600);
|
|
74
|
+
try {
|
|
75
|
+
const stat = fs.fstatSync(fd);
|
|
76
|
+
if (!stat.isFile() || stat.nlink !== 1) throw new Error('Unsafe output file');
|
|
77
|
+
fs.fchmodSync(fd, 0o600);
|
|
78
|
+
fs.writeFileSync(fd, response.original, 'utf8');
|
|
79
|
+
} catch (error) {
|
|
80
|
+
// Do not claim an original was saved if writing it failed.
|
|
81
|
+
try { fs.unlinkSync(file); } catch { /* best effort cleanup */ }
|
|
82
|
+
throw error;
|
|
83
|
+
} finally {
|
|
84
|
+
fs.closeSync(fd);
|
|
85
|
+
}
|
|
86
|
+
return result;
|
|
87
|
+
} catch {
|
|
88
|
+
return {};
|
|
89
|
+
}
|
|
90
|
+
}
|
|
@@ -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
|
+
}
|