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,181 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
|
|
6
|
+
const COUNTERS = ['input_tokens', 'cached_input_tokens', 'output_tokens', 'total_tokens'];
|
|
7
|
+
const MAX_RECORD_BYTES = 16384;
|
|
8
|
+
const MAX_RECORDS = 10000;
|
|
9
|
+
const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
10
|
+
const count = (value) => Number.isSafeInteger(value) && value >= 0 ? value : null;
|
|
11
|
+
|
|
12
|
+
function metadata(value, required = false) {
|
|
13
|
+
if (value == null && !required) return null;
|
|
14
|
+
if (typeof value !== 'string' || !value.trim() || value.length > 1024 || /[\u0000-\u001f\u007f]/u.test(value)) {
|
|
15
|
+
throw new TypeError('Metadatos de consumo Codex inválidos.');
|
|
16
|
+
}
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function normalize(payload) {
|
|
21
|
+
if (!isObject(payload) || payload.hook_event_name !== 'PostModelRequest') {
|
|
22
|
+
throw new TypeError('Evento de consumo Codex inválido.');
|
|
23
|
+
}
|
|
24
|
+
const usage = isObject(payload.token_usage) ? payload.token_usage : {};
|
|
25
|
+
const input = count(usage.input_tokens);
|
|
26
|
+
const output = count(usage.output_tokens);
|
|
27
|
+
let total = count(usage.total_tokens);
|
|
28
|
+
let cached = count(usage.cached_input_tokens ?? usage.input_tokens_details?.cached_tokens);
|
|
29
|
+
if (input !== null && cached !== null && cached > input) cached = null;
|
|
30
|
+
// This schema treats total as input + output, with cached input included once.
|
|
31
|
+
// A client with another definition needs an explicit schema adapter. Preserve
|
|
32
|
+
// component counts but discard a contradictory total, never invent a repair.
|
|
33
|
+
if (input !== null && output !== null && total !== null && BigInt(total) !== BigInt(input) + BigInt(output)) total = null;
|
|
34
|
+
return {
|
|
35
|
+
hook_event_name: 'PostModelRequest',
|
|
36
|
+
session_id: metadata(payload.session_id, true),
|
|
37
|
+
turn_id: metadata(payload.turn_id),
|
|
38
|
+
agent_id: metadata(payload.agent_id),
|
|
39
|
+
agent_type: metadata(payload.agent_type),
|
|
40
|
+
model: metadata(payload.model),
|
|
41
|
+
status: metadata(payload.status),
|
|
42
|
+
token_usage: {
|
|
43
|
+
input_tokens: input,
|
|
44
|
+
cached_input_tokens: cached,
|
|
45
|
+
output_tokens: output,
|
|
46
|
+
total_tokens: total,
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// CODEX_HOME configures the client, not NexaKit's private log root. This module
|
|
52
|
+
// never reads or writes that directory (including a supplied options.codexHome).
|
|
53
|
+
function storageDirectory(options, create) {
|
|
54
|
+
const home = path.resolve(options.homeDirectory ?? os.homedir());
|
|
55
|
+
if (!fs.lstatSync(home).isDirectory()) throw new Error('Directorio de consumo Codex no seguro.');
|
|
56
|
+
let directory = home;
|
|
57
|
+
for (const component of ['.nexakit', 'codex', 'usage']) {
|
|
58
|
+
directory = path.join(directory, component);
|
|
59
|
+
if (create) {
|
|
60
|
+
try { fs.mkdirSync(directory, { mode: 0o700 }); }
|
|
61
|
+
catch (error) { if (error.code !== 'EEXIST') throw new Error('No se pudo crear el registro Codex.'); }
|
|
62
|
+
}
|
|
63
|
+
let stat;
|
|
64
|
+
try { stat = fs.lstatSync(directory); }
|
|
65
|
+
catch (error) {
|
|
66
|
+
if (!create && error.code === 'ENOENT') return null;
|
|
67
|
+
throw new Error('No se pudo acceder al registro Codex.');
|
|
68
|
+
}
|
|
69
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error('Directorio de consumo Codex no seguro.');
|
|
70
|
+
if (create) fs.chmodSync(directory, 0o700);
|
|
71
|
+
}
|
|
72
|
+
return directory;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** One exclusive JSONL file per received event; never append to shared files.
|
|
76
|
+
* No official request ID exists: repeated turn_id values are neither retries
|
|
77
|
+
* nor duplicates. Re-delivery may therefore count an event twice.
|
|
78
|
+
* Returns the stored, allowlisted record; throws on invalid input/storage errors.
|
|
79
|
+
*/
|
|
80
|
+
export function recordCodexUsage(payload, options = {}) {
|
|
81
|
+
const normalized = normalize(payload);
|
|
82
|
+
const instant = typeof options.now === 'function' ? options.now() : options.now;
|
|
83
|
+
const date = instant === undefined ? new Date() : new Date(instant);
|
|
84
|
+
if (!Number.isFinite(date.getTime())) throw new TypeError('Fecha de consumo Codex inválida.');
|
|
85
|
+
const record = { version: 1, recorded_at: date.toISOString(), ...normalized };
|
|
86
|
+
const line = `${JSON.stringify(record)}\n`;
|
|
87
|
+
if (Buffer.byteLength(line) > MAX_RECORD_BYTES) throw new RangeError('Registro de consumo Codex demasiado grande.');
|
|
88
|
+
const directory = storageDirectory(options, true);
|
|
89
|
+
let fd;
|
|
90
|
+
try {
|
|
91
|
+
fd = fs.openSync(path.join(directory, `${randomUUID()}.jsonl`), 'wx', 0o600);
|
|
92
|
+
fs.writeFileSync(fd, line, 'utf8');
|
|
93
|
+
} catch {
|
|
94
|
+
throw new Error('No se pudo guardar el consumo Codex.');
|
|
95
|
+
} finally {
|
|
96
|
+
if (fd !== undefined) fs.closeSync(fd);
|
|
97
|
+
}
|
|
98
|
+
return record;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Bounded local snapshot, not live telemetry. Invalid records are skipped.
|
|
102
|
+
* Refuses unsafe directory paths; returns [] if storage has not been created.
|
|
103
|
+
*/
|
|
104
|
+
export function readCodexUsage(options = {}) {
|
|
105
|
+
const directory = storageDirectory(options, false);
|
|
106
|
+
if (directory === null) return [];
|
|
107
|
+
const records = [];
|
|
108
|
+
let entries = 0;
|
|
109
|
+
const dir = fs.opendirSync(directory);
|
|
110
|
+
try {
|
|
111
|
+
let entry;
|
|
112
|
+
while ((entry = dir.readSync()) !== null) {
|
|
113
|
+
if (++entries > MAX_RECORDS) throw new RangeError('Registro Codex supera el límite de lectura de 10000 archivos.');
|
|
114
|
+
if (!entry.isFile() || !entry.name.endsWith('.jsonl')) continue;
|
|
115
|
+
let fd;
|
|
116
|
+
try {
|
|
117
|
+
fd = fs.openSync(path.join(directory, entry.name), fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | fs.constants.O_NONBLOCK);
|
|
118
|
+
const stat = fs.fstatSync(fd);
|
|
119
|
+
if (!stat.isFile() || stat.nlink !== 1 || stat.size > MAX_RECORD_BYTES) continue;
|
|
120
|
+
// Fixed-size read also bounds files that grow after fstat.
|
|
121
|
+
const buffer = Buffer.alloc(MAX_RECORD_BYTES + 1);
|
|
122
|
+
const size = fs.readSync(fd, buffer, 0, buffer.length, 0);
|
|
123
|
+
if (size > MAX_RECORD_BYTES) continue;
|
|
124
|
+
const raw = buffer.subarray(0, size).toString('utf8').trim();
|
|
125
|
+
if (raw.includes('\n')) continue;
|
|
126
|
+
const parsed = JSON.parse(raw);
|
|
127
|
+
if (parsed.version !== 1 || typeof parsed.recorded_at !== 'string' || !Number.isFinite(Date.parse(parsed.recorded_at))) continue;
|
|
128
|
+
records.push({ version: 1, recorded_at: parsed.recorded_at, ...normalize(parsed) });
|
|
129
|
+
} catch {
|
|
130
|
+
// Partial concurrent writes, malformed records and symlinks are ignored.
|
|
131
|
+
} finally {
|
|
132
|
+
if (fd !== undefined) fs.closeSync(fd);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
} finally {
|
|
136
|
+
dir.closeSync();
|
|
137
|
+
}
|
|
138
|
+
return records.sort((a, b) => a.recorded_at.localeCompare(b.recorded_at));
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function aggregate(records) {
|
|
142
|
+
const token_usage = {};
|
|
143
|
+
const known_counts = {};
|
|
144
|
+
for (const key of COUNTERS) {
|
|
145
|
+
const values = records.map((record) => record.token_usage[key]).filter((value) => value !== null);
|
|
146
|
+
const sum = values.reduce((total, value) => total + BigInt(value), 0n);
|
|
147
|
+
token_usage[key] = values.length && sum <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(sum) : null;
|
|
148
|
+
known_counts[key] = values.length;
|
|
149
|
+
}
|
|
150
|
+
return { requests: records.length, token_usage, known_counts };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Known sums have per-counter coverage; null means unavailable or overflow.
|
|
154
|
+
* Cached input is already included in input_tokens. No costs are estimated.
|
|
155
|
+
* Attribution is explicit: main type, agent metadata, or unknown; no guessing.
|
|
156
|
+
*/
|
|
157
|
+
export function summarizeCodexUsage(records) {
|
|
158
|
+
if (!Array.isArray(records) || records.length > MAX_RECORDS) throw new TypeError('Lista de consumo Codex inválida o demasiado grande.');
|
|
159
|
+
const normalized = records.map(normalize);
|
|
160
|
+
const main = [], agents = [], unknown = [];
|
|
161
|
+
const statuses = new Map();
|
|
162
|
+
const models = new Map();
|
|
163
|
+
for (const record of normalized) {
|
|
164
|
+
(record.agent_type === 'main' ? main : record.agent_id !== null || record.agent_type !== null ? agents : unknown).push(record);
|
|
165
|
+
const status = record.status ?? 'unknown';
|
|
166
|
+
const model = record.model ?? 'unknown';
|
|
167
|
+
statuses.set(status, (statuses.get(status) ?? 0) + 1);
|
|
168
|
+
models.set(model, (models.get(model) ?? 0) + 1);
|
|
169
|
+
}
|
|
170
|
+
return {
|
|
171
|
+
...aggregate(normalized),
|
|
172
|
+
main: aggregate(main), agents: aggregate(agents), unknown: aggregate(unknown),
|
|
173
|
+
statuses: Object.fromEntries(statuses), models: Object.fromEntries(models),
|
|
174
|
+
limitations: [
|
|
175
|
+
'Muestra local de eventos recibidos; no es telemetría viva ni cobertura garantizada de todas las solicitudes.',
|
|
176
|
+
'Sin request id oficial: turn_id no identifica solicitudes, duplicados ni reintentos; cada evento recibido cuenta una vez.',
|
|
177
|
+
'Las sumas incluyen solo contadores conocidos; cached_input_tokens es parte de input_tokens. No se estiman costes.',
|
|
178
|
+
'Si input_tokens y output_tokens son conocidos, un total_tokens incompatible con su suma se marca null; otras definiciones de total requieren un adaptador explícito.',
|
|
179
|
+
],
|
|
180
|
+
};
|
|
181
|
+
}
|
package/src/level-agents.js
CHANGED
|
@@ -4,7 +4,7 @@ import os from "node:os";
|
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import { agentModels } from "./agent-models.js";
|
|
6
6
|
|
|
7
|
-
// Codex
|
|
7
|
+
// Codex level agents use local TOML files; Claude's come from the `niveles` plugin.
|
|
8
8
|
// The top level is "alto"; xhigh is asked per spawn, only after high failed.
|
|
9
9
|
const LEVELS = [["Ligero", "ligero"], ["Normal", "normal"], ["Exigente", "exigente"], ["Alto", "alto"]];
|
|
10
10
|
const USES = { ligero: "comandos, búsquedas, lecturas y cambios mecánicos", normal: "implementar con un diseño claro", exigente: "pruebas, casos borde o un fallo acotado", alto: "un fallo sutil, seguridad o lo que exigente no resolvió" };
|
package/src/model-command.js
CHANGED
|
@@ -2,11 +2,27 @@ import fs from 'node:fs/promises';
|
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import os from 'node:os';
|
|
4
4
|
import { getStaticTOMLValue, parseTOML } from 'toml-eslint-parser';
|
|
5
|
-
import { agentModels } from './agent-models.js';
|
|
5
|
+
import { agentModels, familyOfModel } from './agent-models.js';
|
|
6
6
|
import { resolveCliInvocation } from './cli-executable.js';
|
|
7
7
|
import { runRevisionProcess } from './revision-process.js';
|
|
8
8
|
import pkg from '../package.json' with { type: 'json' };
|
|
9
9
|
|
|
10
|
+
const ANTIGRAVITY_FAMILIES_BY_LEVEL = {
|
|
11
|
+
Ligero: ['flash', 'hydrogen'],
|
|
12
|
+
Normal: ['hydrogen', 'flash'],
|
|
13
|
+
Exigente: ['hydrogen', 'argon', 'flash'],
|
|
14
|
+
Alto: ['carbon', 'argon'],
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
function recommendAntigravity(models, { level, effort }) {
|
|
18
|
+
const variants = models.filter(({ model, efforts }) => model.startsWith('gemini-') && efforts.includes(effort));
|
|
19
|
+
for (const family of ANTIGRAVITY_FAMILIES_BY_LEVEL[level]) {
|
|
20
|
+
const match = variants.find(({ model }) => familyOfModel(model) === family);
|
|
21
|
+
if (match) return { model: match.model, effort };
|
|
22
|
+
}
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
|
|
10
26
|
export async function inspectModels({
|
|
11
27
|
homeDirectory = os.homedir(),
|
|
12
28
|
environment = process.env,
|
|
@@ -126,21 +142,21 @@ export async function runModelCommand(args, { out, err }, options = {}) {
|
|
|
126
142
|
if (level && !row) return 2;
|
|
127
143
|
for (const ia of client ? [client] : ['claude', 'codex', 'antigravity']) {
|
|
128
144
|
await out(`${ia}: ${data.sources[ia]}\n`);
|
|
129
|
-
for (const model of data.catalogs[ia])
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
145
|
+
for (const model of data.catalogs[ia]) {
|
|
146
|
+
const defaultEffort = ia === 'antigravity' ? '' : ` · defecto ${model.defaultEffort ?? 'no informado'}`;
|
|
147
|
+
await out(` ${model.model} · ${model.efforts.join(', ')}${defaultEffort}\n`);
|
|
148
|
+
}
|
|
133
149
|
const stored = data.stored[ia],
|
|
134
|
-
wanted = row
|
|
150
|
+
wanted = row && (ia === 'antigravity' ? recommendAntigravity(data.catalogs[ia], row) : row[ia]);
|
|
135
151
|
const mark =
|
|
136
152
|
!stored?.model || !stored?.effort || !wanted
|
|
137
153
|
? '?'
|
|
138
154
|
: stored.model === wanted.model && stored.effort === wanted.effort
|
|
139
155
|
? '✓'
|
|
140
156
|
: '→';
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
);
|
|
157
|
+
const recommendation = wanted ? ` · recomendado ${wanted.model} · ${wanted.effort}`
|
|
158
|
+
: row && ia === 'antigravity' ? ' · sin recomendación disponible' : '';
|
|
159
|
+
await out(`${mark} Guardado: ${stored?.model ?? 'no comprobable'} · ${stored?.effort ?? 'no informado'}${recommendation}\n`);
|
|
144
160
|
}
|
|
145
161
|
await out('Compara lo guardado; una sesión abierta puede diferir. Compruébalo en /model.\n');
|
|
146
162
|
return 0;
|
package/src/toolkit-cli.js
CHANGED
|
@@ -2,6 +2,7 @@ import os from 'node:os';
|
|
|
2
2
|
import { runCli } from './cli.js';
|
|
3
3
|
import { runModelCommand } from './model-command.js';
|
|
4
4
|
import { runAhorroCommand } from './ahorro-command.js';
|
|
5
|
+
import { runCodexCommand } from './codex-command.js';
|
|
5
6
|
import { runLeccionesCommand } from './lecciones-command.js';
|
|
6
7
|
import { runRevisionCommand } from './revision.js';
|
|
7
8
|
import path from 'node:path';
|
|
@@ -39,6 +40,7 @@ const HELP = `Uso: npx nexakit [--project <ruta>] [--si]
|
|
|
39
40
|
nexakit revision --disponibles [--principal claude|codex|antigravity]
|
|
40
41
|
nexakit revision --con <ia> --modelo <m> --esfuerzo <e> --encargo <archivo> [--base <rama>]
|
|
41
42
|
nexakit modelo [--nivel <nivel>] [--ia claude|codex|antigravity] [--perfil-codex <nombre>]
|
|
43
|
+
nexakit codex auditar|preparar|agentes|actividad|consumo|recomendar|hook|ejecutar|comparar [opciones]
|
|
42
44
|
nexakit ahorro [--json]
|
|
43
45
|
nexakit lecciones [--json | --descartar]
|
|
44
46
|
npx nexakit recommend [--project <ruta>] [--profile frontend|backend|mcp|security] [--client codex|claude] [--dry-run] [--json]
|
|
@@ -97,6 +99,7 @@ export async function runToolkitCli(
|
|
|
97
99
|
|
|
98
100
|
const [command, ...rest] = argv;
|
|
99
101
|
if (command === 'modelo') return runModelCommand(rest, { out, err }, options);
|
|
102
|
+
if (command === 'codex') return runCodexCommand(rest, { out, err, input, output }, options);
|
|
100
103
|
if (command === 'ahorro') return runAhorroCommand(rest, { out, err }, options);
|
|
101
104
|
if (command === 'lecciones') return runLeccionesCommand(rest, { out, err }, options);
|
|
102
105
|
if (command === 'revision') return runRevisionCommand(rest, { out, err }, { options });
|