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.
@@ -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,228 @@
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 tempAgent = env.NEXAKIT_ANTIGRAVITY_TEMP_OUTPUT === '1'
136
+ ? 'antigravity'
137
+ : env.NEXAKIT_CODEX_TEMP_OUTPUT === '1'
138
+ ? 'codex'
139
+ : null;
140
+ const root = tempAgent
141
+ ? privateDirectory(path.join(directory(fs.realpathSync(options.tempDirectory ?? os.tmpdir())), `nexakit-${tempAgent}-${process.getuid?.() ?? 'user'}`))
142
+ : directory(options.homeDirectory ?? os.homedir());
143
+ home = privateDirectory(path.join(root, '.nexakit'));
144
+ const folder = privateDirectory(path.join(home, 'salidas'));
145
+ ruta = path.join(folder, `${Date.now()}-${randomUUID()}.log`);
146
+ fd = fs.openSync(ruta, fs.constants.O_RDWR | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600);
147
+ } catch {
148
+ fallback = true;
149
+ emit(err, 'nexakit: no se pudo guardar la salida; se muestra completa.\n');
150
+ }
151
+ function capture(index, chunk) {
152
+ if (!fallback) {
153
+ try { writeAll(fd, chunk); saved += chunk.length; }
154
+ catch {
155
+ fallback = true;
156
+ emit(err, 'nexakit: no se pudo guardar la salida; se reproduce el prefijo combinado y se muestra completa.\n');
157
+ if (!bypass) {
158
+ const buffer = Buffer.alloc(65536);
159
+ const decoder = new StringDecoder('utf8');
160
+ try {
161
+ for (let offset = 0; offset < saved;) {
162
+ const size = fs.readSync(fd, buffer, 0, Math.min(buffer.length, saved - offset), offset);
163
+ if (!size) break;
164
+ emit(out, decoder.write(buffer.subarray(0, size))); offset += size;
165
+ }
166
+ emit(out, decoder.end());
167
+ } catch {
168
+ emit(err, 'nexakit: no se pudo recuperar el prefijo guardado; se muestra la muestra retenida.\n');
169
+ for (const [sampleIndex, sample] of samples.entries()) emit(sinks[sampleIndex], sample.finish(ruta).text);
170
+ }
171
+ }
172
+ }
173
+ }
174
+ if (fallback || bypass) emit(sinks[index], liveDecoders[index].write(chunk));
175
+ else samples[index].push(chunk);
176
+ }
177
+ let exitCode;
178
+ try {
179
+ exitCode = await new Promise(resolve => {
180
+ let child;
181
+ try {
182
+ child = spawn(argv[0], argv.slice(1), {
183
+ shell: false, cwd: options.projectRoot ?? process.cwd(), env,
184
+ stdio: [input == null ? 'inherit' : 'pipe', 'pipe', 'pipe'],
185
+ });
186
+ } catch (error) {
187
+ emit(err, `nexakit: ${error.code ?? 'spawn error'}\n`); resolve(error.code === 'ENOENT' ? 127 : 1); return;
188
+ }
189
+ let spawnError;
190
+ child.stdout.on('data', chunk => capture(0, chunk));
191
+ child.stderr.on('data', chunk => capture(1, chunk));
192
+ child.on('error', error => {
193
+ spawnError = error.code === 'ENOENT' ? 127 : 1;
194
+ emit(err, `nexakit: ${error.code ?? 'spawn error'}\n`);
195
+ });
196
+ if (input != null) {
197
+ child.stdin.on('error', error => { if (error.code !== 'EPIPE') emit(err, 'nexakit: fallo de stdin\n'); });
198
+ if (typeof input.pipe === 'function') {
199
+ input.pipe(child.stdin);
200
+ child.once('close', () => input.unpipe(child.stdin));
201
+ } else child.stdin.end(input);
202
+ }
203
+ child.on('close', (code, signal) => resolve(spawnError ?? code ?? (128 + (os.constants.signals[signal] ?? 0))));
204
+ });
205
+ } finally {
206
+ if (fd !== undefined) {
207
+ try { fs.closeSync(fd); }
208
+ catch { emit(err, 'nexakit: no se pudo cerrar la copia de salida.\n'); }
209
+ }
210
+ }
211
+ if (fallback || bypass) {
212
+ for (const [index, decoder] of liveDecoders.entries()) emit(sinks[index], decoder.end());
213
+ }
214
+ if (!fallback && !bypass) {
215
+ const results = samples.map(sample => sample.finish(ruta));
216
+ for (const [index, result] of results.entries()) emit(sinks[index], result.text);
217
+ const before = results.reduce((sum, result) => sum + result.chars, 0);
218
+ const after = results.reduce((sum, result) => sum + result.text.length, 0);
219
+ const linesBefore = results.reduce((sum, result) => sum + result.lines, 0);
220
+ const linesAfter = results.reduce((sum, result) => sum + (result.text ? result.text.split('\n').length : 0), 0);
221
+ if (results.some(result => result.trimmed) && before > after && linesBefore >= linesAfter) {
222
+ try {
223
+ record(home, { fecha: Date.now(), antes: before, despues: after, lineasAntes: linesBefore, lineasDespues: linesAfter, agent: options.agent ?? 'codex' });
224
+ } catch { emit(err, 'nexakit: no se pudo guardar el registro de ahorro.\n'); }
225
+ }
226
+ }
227
+ return exitCode;
228
+ }
@@ -0,0 +1,88 @@
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
+ export const quoteShell = token => `'${token.replaceAll("'", "'\"'\"'")}'`;
17
+ export const safeAbsolutePath = 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
+ export function approvedOutputCommand(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
+ export function buildOutputWrapperCommand(command, {
51
+ executable = process.execPath,
52
+ entrypoint = ENTRYPOINT,
53
+ agent = 'codex',
54
+ tempEnv = 'NEXAKIT_CODEX_TEMP_OUTPUT=1',
55
+ platform = process.platform,
56
+ environment = process.env,
57
+ } = {}) {
58
+ if (platform === 'win32' || environment.NEXAKIT_SALIDA === 'completa') return null;
59
+ if (typeof command !== 'string' || command.length > 16 * 1024 ||
60
+ !/^[A-Za-z0-9_./:@%+=, -]+$/u.test(command)) return null;
61
+ const argv = command.trim().split(/ +/u);
62
+ if (!approvedOutputCommand(argv)) return null;
63
+ if (!safeAbsolutePath(executable) || !safeAbsolutePath(entrypoint)) return null;
64
+ return `${tempEnv} ${[executable, entrypoint, agent, 'ejecutar', '--', ...argv].map(quoteShell).join(' ')}`;
65
+ }
66
+
67
+ /** Pure, synchronous PreToolUse rewrite. Unknown inputs always retain their original route. */
68
+ export function rewriteCodexToolInput(payload, options = {}) {
69
+ if (!isRecord(payload) || payload.hook_event_name !== 'PreToolUse' || payload.tool_name !== 'Bash' ||
70
+ !isRecord(payload.tool_input)) return {};
71
+ const input = payload.tool_input;
72
+ if (('sandbox_permissions' in input && input.sandbox_permissions !== 'use_default') ||
73
+ ['tty', 'interactive', 'background', 'run_in_background'].some(key => input[key])) return {};
74
+ const wrapper = buildOutputWrapperCommand(input.command, {
75
+ executable: options.executable,
76
+ entrypoint: options.entrypoint,
77
+ agent: 'codex',
78
+ tempEnv: 'NEXAKIT_CODEX_TEMP_OUTPUT=1',
79
+ platform: options.platform ?? process.platform,
80
+ environment: options.environment ?? process.env,
81
+ });
82
+ if (!wrapper) return {};
83
+ return { hookSpecificOutput: {
84
+ hookEventName: 'PreToolUse',
85
+ permissionDecision: 'allow',
86
+ updatedInput: { ...input, command: wrapper },
87
+ } };
88
+ }
@@ -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
+ }