nexakit 0.13.1 → 0.13.2

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.
@@ -1,6 +1,7 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import os from 'node:os';
3
3
  import { cargarConfig } from './config.js';
4
+ import { estadoCuota, leerCuotas, nombreCuota, pocaCuota, sinCuota, UMBRAL_CUOTA_BAJA } from './cuotas.js';
4
5
  import { elegir, riesgoDe, UMBRALES } from './decision.js';
5
6
  import { clasificar, leerDiff } from './diff.js';
6
7
  import { ErrorFabrica } from './errores.js';
@@ -186,6 +187,17 @@ export async function proponer(entrada) {
186
187
  leerPreferencias(home),
187
188
  ]);
188
189
  const avisosEstaciones = [];
190
+ const cuotas = leerCuotas(home);
191
+ const agotadas = new Map();
192
+ const instante = ahora.getTime();
193
+ for (const ia of IAExterna.options) {
194
+ const { agotadaHasta, ventanaAgotada, porcentajeUsado, reinicio } = estadoCuota(cuotas[ia], instante);
195
+ if (agotadaHasta !== undefined)
196
+ agotadas.set(ia, sinCuota(ia, agotadaHasta, ventanaAgotada, instante));
197
+ else if (porcentajeUsado !== undefined && porcentajeUsado >= UMBRAL_CUOTA_BAJA) {
198
+ avisosEstaciones.push(pocaCuota(ia, porcentajeUsado, reinicio, instante));
199
+ }
200
+ }
189
201
  let usoEvidencia = false;
190
202
  function proponerEstacion(estacion, revisionDe) {
191
203
  const cfg = config.estaciones?.[estacion];
@@ -210,32 +222,60 @@ export async function proponer(entrada) {
210
222
  return omitida(regla.sinActivar);
211
223
  const motivo = revisionDe !== undefined ? 'revisión cruzada de código' : porDiff ? regla.motivo : 'activada en la configuración';
212
224
  const descartes = [];
225
+ const descartesCuota = new Set();
226
+ function descartar(c) {
227
+ const agotada = agotadas.get(c.ia);
228
+ if (agotada === undefined)
229
+ return descarte(c, catalogos);
230
+ descartesCuota.add(agotada);
231
+ return agotada;
232
+ }
213
233
  const manual = candidatosDe(estacion, revisionDe === undefined ? cfg : undefined, descartes, revisionDe);
214
- const propuesta = (c, explicacion, calidad) => ({
215
- estacion,
216
- ...(revisionDe === undefined ? {} : { revisionDe }),
217
- ia: c.ia,
218
- modelo: c.modelo,
219
- // Antigravity lleva el esfuerzo dentro del id del modelo.
220
- esfuerzo: c.ia === 'antigravity' ? null : c.esfuerzo,
221
- motivo,
222
- descartes,
223
- explicacion,
224
- calidad,
225
- ordenesPermitidas: ordenesDe(estacion, c.ia, cfg),
226
- estado: 'propuesta',
227
- });
228
- const sinModelo = () => ({
229
- ...omitida(motivo),
230
- descartes,
231
- explicacion: 'ningún candidato está disponible en el catálogo',
232
- estado: 'sin-modelo',
233
- });
234
+ const propuesta = (c, explicacion, calidad) => {
235
+ for (const aviso of descartesCuota)
236
+ avisosEstaciones.push(`${aviso}. En ${nombre} se usa ${c.ia} (${nombreDe(c)})`);
237
+ return {
238
+ estacion,
239
+ ...(revisionDe === undefined ? {} : { revisionDe }),
240
+ ia: c.ia,
241
+ modelo: c.modelo,
242
+ // Antigravity lleva el esfuerzo dentro del id del modelo.
243
+ esfuerzo: c.ia === 'antigravity' ? null : c.esfuerzo,
244
+ motivo,
245
+ descartes,
246
+ explicacion,
247
+ calidad,
248
+ ordenesPermitidas: ordenesDe(estacion, c.ia, cfg),
249
+ estado: 'propuesta',
250
+ };
251
+ };
252
+ const sinModelo = () => {
253
+ for (const aviso of descartesCuota)
254
+ avisosEstaciones.push(`${aviso}. En ${nombre} no hay otro candidato disponible`);
255
+ return { ...omitida(motivo), descartes, explicacion: 'ningún candidato está disponible en el catálogo', estado: 'sin-modelo' };
256
+ };
257
+ function delCatalogo() {
258
+ const candidatos = [];
259
+ for (const ia of revisionDe === undefined ? IAExterna.options : [revisionDe]) {
260
+ if (agotadas.has(ia))
261
+ continue;
262
+ for (const { modelo, esfuerzos } of catalogos[ia] ?? []) {
263
+ if (ia === 'antigravity')
264
+ candidatos.push({ ia, modelo, esfuerzo: null });
265
+ else
266
+ for (const esfuerzo of esfuerzos) {
267
+ if (cfg?.esfuerzo === undefined || esfuerzo === cfg.esfuerzo)
268
+ candidatos.push({ ia, modelo, esfuerzo });
269
+ }
270
+ }
271
+ }
272
+ return candidatos;
273
+ }
234
274
  const fijada = cfg?.ia !== undefined || cfg?.modelo !== undefined;
235
275
  if (revisionDe === undefined && (fijada || manual[0]?.ia === 'claude')) {
236
276
  // Lo fijado en la configuración y las estaciones de Claude no se deciden por evidencia: manda la tabla.
237
277
  for (const c of manual) {
238
- const razon = descarte(c, catalogos);
278
+ const razon = descartar(c);
239
279
  if (razon !== null) {
240
280
  descartes.push(razon);
241
281
  continue;
@@ -245,29 +285,27 @@ export async function proponer(entrada) {
245
285
  const cumple = (cfg?.ia === undefined || c.ia === cfg.ia) && (cfg?.modelo === undefined || c.modelo === cfg.modelo);
246
286
  return propuesta(c, cumple ? NOTA_FIJADA : `${NOTA_FIJADA} no está disponible; se usa ${nombreDe(c)} de la tabla`, null);
247
287
  }
288
+ if (descartesCuota.size > 0) {
289
+ const alternativa = delCatalogo()[0];
290
+ if (alternativa !== undefined)
291
+ return propuesta(alternativa, 'se usa el orden del catálogo por falta de cuota', null);
292
+ }
248
293
  return sinModelo();
249
294
  }
250
295
  const disponibles = [];
251
296
  for (const c of candidatosConEvidencia(estacion, manual, revisionDe === undefined ? cfg : undefined, catalogos, evidencia)) {
252
297
  if (revisionDe !== undefined && c.ia !== revisionDe)
253
298
  continue;
254
- const razon = descarte(c, catalogos);
299
+ const razon = descartar(c);
255
300
  if (razon === null)
256
301
  disponibles.push(c);
257
302
  else
258
303
  descartes.push(razon);
259
304
  }
260
- // Si la tabla y la evidencia no ofrecen ningún par vivo, usa el orden del catálogo.
261
- const porCatalogo = revisionDe !== undefined && disponibles.length === 0;
262
- if (porCatalogo) {
263
- for (const { modelo, esfuerzos } of catalogos[revisionDe] ?? []) {
264
- if (revisionDe === 'antigravity')
265
- disponibles.push({ ia: revisionDe, modelo, esfuerzo: null });
266
- else
267
- for (const esfuerzo of esfuerzos)
268
- disponibles.push({ ia: revisionDe, modelo, esfuerzo });
269
- }
270
- }
305
+ // Una revisión cruzada o una estación que perdió sus candidatos por cuota puede recurrir al catálogo.
306
+ const porCatalogo = disponibles.length === 0 && (revisionDe !== undefined || descartesCuota.size > 0);
307
+ if (porCatalogo)
308
+ disponibles.push(...delCatalogo());
271
309
  if (disponibles.length === 0)
272
310
  return sinModelo();
273
311
  usoEvidencia = true;
@@ -292,11 +330,16 @@ export async function proponer(entrada) {
292
330
  for (const ia of IAExterna.options) {
293
331
  if (principal.ia === ia)
294
332
  continue;
333
+ const agotada = agotadas.get(ia);
334
+ if (agotada !== undefined) {
335
+ avisosEstaciones.push(`Se omite la revisión cruzada de código: ${agotada}`);
336
+ continue;
337
+ }
295
338
  const revision = proponerEstacion(estacion, ia);
296
339
  if (revision.estado === 'propuesta')
297
340
  estaciones.push(revision);
298
341
  else
299
- avisosEstaciones.push(`Se omite la revisión cruzada de código con ${ia}: no hay modelos disponibles`);
342
+ avisosEstaciones.push(`Se omite la revisión cruzada de código con ${nombreCuota(ia)}: no hay modelos disponibles`);
300
343
  }
301
344
  }
302
345
  const avisos = [];
@@ -87,9 +87,9 @@ export async function escribirReemplazando(ruta, texto, antesDeRenombrar) {
87
87
  }
88
88
  const json = (valor) => `${JSON.stringify(valor, null, 2)}\n`;
89
89
  /** Deja lista `~/.nexakit/fabrica/` y devuelve su ruta. */
90
- async function prepararBase(home) {
90
+ export async function prepararBase(home) {
91
91
  const nexakit = path.join(home, '.nexakit');
92
- await mkdir(nexakit, { recursive: true, mode: 0o700 });
92
+ await carpetaPropia(nexakit);
93
93
  const base = path.join(nexakit, 'fabrica');
94
94
  await carpetaPropia(base);
95
95
  return base;
@@ -83,12 +83,12 @@ export function opcionesDeEntorno(entorno, variable) {
83
83
  * `NEXAKIT_FABRICA_CODEX` y `NEXAKIT_FABRICA_AGY`. Si uno no se puede crear, no entra en el resultado y se avisa.
84
84
  */
85
85
  export async function crearConectoresDesdeEntorno(opciones = {}) {
86
- const { ias = ['codex', 'antigravity'], entorno = process.env, avisar = sinAvisos } = opciones;
86
+ const { ias = ['codex', 'antigravity'], entorno = process.env, avisar = sinAvisos, home } = opciones;
87
87
  const conectores = {};
88
88
  for (const ia of ias) {
89
89
  try {
90
90
  if (ia === 'codex') {
91
- conectores.codex = await crearConectorCodex(opcionesDeEntorno(entorno, 'NEXAKIT_FABRICA_CODEX'));
91
+ conectores.codex = await crearConectorCodex({ ...opcionesDeEntorno(entorno, 'NEXAKIT_FABRICA_CODEX'), ...(home === undefined ? {} : { home }) });
92
92
  }
93
93
  else if (ia === 'antigravity') {
94
94
  conectores.antigravity = await crearConectorAntigravity(opcionesDeEntorno(entorno, 'NEXAKIT_FABRICA_AGY'));
@@ -178,10 +178,10 @@ function cargarPropuesta(home, repo) {
178
178
  /** Calcula el recorrido propuesto para el diff contra `base` y lo guarda como la propuesta del repo. */
179
179
  export async function proponerEnRaiz(entrada) {
180
180
  const { raiz, base, foco, home, entorno = process.env, avisar = sinAvisos } = entrada;
181
- const conectores = await crearConectoresDesdeEntorno({ entorno, avisar });
181
+ const conectores = await crearConectoresDesdeEntorno({ entorno, avisar, home });
182
182
  let catalogos;
183
183
  try {
184
- catalogos = await consultarCatalogos(conectores, avisar);
184
+ [catalogos] = await Promise.all([consultarCatalogos(conectores, avisar), conectores.codex?.consultarCuota?.()]);
185
185
  }
186
186
  finally {
187
187
  await cerrarConectores(conectores);
@@ -213,7 +213,7 @@ export async function lanzarAprobado(entrada) {
213
213
  if (e.estado === 'propuesta' && e.ia !== null && e.ia !== 'claude')
214
214
  externas.add(e.ia);
215
215
  }
216
- const conectores = await crearConectoresDesdeEntorno({ ias: [...externas], entorno, avisar });
216
+ const conectores = await crearConectoresDesdeEntorno({ ias: [...externas], entorno, avisar, home });
217
217
  let id;
218
218
  try {
219
219
  ({ id } = await ejecutor.lanzar(recorrido, { raiz, conectores, paralelismo: config.paralelismo, ...(config.paralelismoPorIa === undefined ? {} : { paralelismoPorIa: config.paralelismoPorIa }), home }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nexakit",
3
- "version": "0.13.1",
3
+ "version": "0.13.2",
4
4
  "description": "Asistente por pasos de skills verificadas por SHA-256, coordinación entre agentes y memoria por proyecto para Claude Code y Codex.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -33,14 +33,16 @@ const isNum = (v) => typeof v === 'number' && Number.isFinite(v);
33
33
  const clampPercent = (v) => Math.min(100, Math.max(0, v));
34
34
  const fitText = (text, width) => (text.length > width ? `${text.slice(0, width - 1)}…` : text.padEnd(width));
35
35
 
36
- /** Extract highest active quota bucket usage percentage and ISO reset timestamp. */
36
+ /** Extract the usage range across active quota buckets and the reset of the fullest bucket. */
37
37
  export function extractQuotaSummary(quota, now = Date.now()) {
38
38
  if (!quota || typeof quota !== 'object' || Array.isArray(quota)) return null;
39
39
  let best = null;
40
+ let minPercentUsed = 100;
40
41
  for (const bucket of Object.values(quota)) {
41
42
  if (!bucket || typeof bucket !== 'object' || bucket.disabled === true) continue;
42
43
  if (!isNum(bucket.remaining_fraction)) continue;
43
- const percentUsed = clampPercent((1 - bucket.remaining_fraction) * 100);
44
+ const percentUsed = clampPercent(100 - bucket.remaining_fraction * 100);
45
+ minPercentUsed = Math.min(minPercentUsed, percentUsed);
44
46
  let resetsAt = null;
45
47
  if (typeof bucket.reset_time === 'string') {
46
48
  resetsAt = bucket.reset_time;
@@ -49,7 +51,7 @@ export function extractQuotaSummary(quota, now = Date.now()) {
49
51
  }
50
52
  if (!best || percentUsed > best.percentUsed) best = { percentUsed, resetsAt };
51
53
  }
52
- return best;
54
+ return best === null ? null : { ...best, minPercentUsed };
53
55
  }
54
56
 
55
57
  /** Extract cache hit percentage only when current_usage reports explicit cache read tokens. */
@@ -174,8 +176,81 @@ export function leerActivoDeFabrica(home = os.homedir()) {
174
176
  }
175
177
  }
176
178
 
179
+ const INTERVALO_ESCRITURA_MS = 60_000;
180
+ let promesaCuotas;
181
+ let ultimaEscrituraCuota = Promise.resolve();
182
+
183
+ function cargarCuotas() {
184
+ promesaCuotas ??= import('../dist/fabrica/cuotas.js').catch(() => null);
185
+ return promesaCuotas;
186
+ }
187
+
188
+ function mismoReinicio(anterior, actual) {
189
+ if (!anterior && !actual) return true;
190
+ if (!anterior || !actual) return false;
191
+ const a = Date.parse(anterior);
192
+ const b = Date.parse(actual);
193
+ return Number.isFinite(a) && Number.isFinite(b) && Math.abs(a - b) <= INTERVALO_ESCRITURA_MS;
194
+ }
195
+
196
+ function leerCuotaDeBarra(home) {
197
+ try {
198
+ const nexakit = path.join(home, '.nexakit');
199
+ const base = path.join(nexakit, 'fabrica');
200
+ if (![nexakit, base].every((ruta) => lstatSync(ruta, { throwIfNoEntry: false })?.isDirectory())) return;
201
+ const ruta = path.join(base, 'cuotas.json');
202
+ if (!lstatSync(ruta, { throwIfNoEntry: false })?.isFile()) return;
203
+ const fd = openSync(ruta, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
204
+ try {
205
+ const info = fstatSync(fd);
206
+ const { size } = info;
207
+ if (size > 16_384 || !info.isFile()) return;
208
+ const buffer = Buffer.alloc(size);
209
+ const leidos = readSync(fd, buffer, 0, size, 0);
210
+ return JSON.parse(buffer.toString('utf8', 0, leidos))?.antigravity;
211
+ } finally {
212
+ closeSync(fd);
213
+ }
214
+ } catch {
215
+ return undefined;
216
+ }
217
+ }
218
+
219
+ /** Guarda la cuota de Antigravity si cambió o pasaron más de 60 s desde la última escritura. */
220
+ async function guardarCuota(quota, home, now) {
221
+ try {
222
+ if (!quota || typeof quota.percentUsed !== 'number' || !Number.isFinite(quota.percentUsed)) return;
223
+ const porcentajeUsado = Math.min(100, Math.max(0, Math.round(quota.percentUsed)));
224
+ const porcentajeMinimoUsado = quota.minPercentUsed;
225
+ const reinicioMs = typeof quota.resetsAt === 'string' ? Date.parse(quota.resetsAt) : Number.NaN;
226
+ const reinicio = Number.isFinite(reinicioMs) ? new Date(reinicioMs).toISOString() : undefined;
227
+ const anterior = leerCuotaDeBarra(home);
228
+ const ultimaEscritura = anterior?.fuente === 'barra' ? Date.parse(anterior.fecha) : Number.NaN;
229
+ const sinCambios =
230
+ anterior?.fuente === 'barra' &&
231
+ anterior.porcentajeUsado === porcentajeUsado &&
232
+ anterior.porcentajeMinimoUsado === porcentajeMinimoUsado &&
233
+ mismoReinicio(anterior.reinicio, reinicio);
234
+ if (sinCambios && now >= ultimaEscritura && now - ultimaEscritura < INTERVALO_ESCRITURA_MS) {
235
+ return;
236
+ }
237
+ const mod = await cargarCuotas();
238
+ await mod?.guardarCuotaAntigravity(home, { porcentajeUsado: quota.percentUsed, porcentajeMinimoUsado, reinicio }, now);
239
+ } catch {
240
+ // La barra nunca debe fallar ni avisar si no se puede guardar la cuota.
241
+ }
242
+ }
243
+
244
+ export function guardarCuotaDeBarra(quota, { home = os.homedir(), now = Date.now() } = {}) {
245
+ ultimaEscrituraCuota = ultimaEscrituraCuota.then(() => guardarCuota(quota, home, now));
246
+ return ultimaEscrituraCuota;
247
+ }
248
+
249
+ /** Espera a que termine la última escritura en segundo plano de la cuota de la barra. */
250
+ export const esperarCuotaDeBarra = () => ultimaEscrituraCuota;
251
+
177
252
  /** Build structured bar segments and subagent rows from an Antigravity statusLine payload. */
178
- export function buildAntigravityStatusSegments(payload, { recommendation = null, now = Date.now(), fabrica = null } = {}) {
253
+ export function buildAntigravityStatusSegments(payload, { recommendation = null, now = Date.now(), fabrica = null, home = os.homedir() } = {}) {
179
254
  const safe = payload && typeof payload === 'object' && !Array.isArray(payload) ? payload : {};
180
255
  const model = parseAntigravityModel(safe.model);
181
256
  const segments = [
@@ -184,6 +259,9 @@ export function buildAntigravityStatusSegments(payload, { recommendation = null,
184
259
  ];
185
260
 
186
261
  const quota = extractQuotaSummary(safe.quota, now);
262
+ if (quota !== null) {
263
+ void guardarCuotaDeBarra(quota, { home, now });
264
+ }
187
265
  const advice = recommendationSegment(recommendation, model, quota?.percentUsed);
188
266
  if (advice) segments.push(advice);
189
267
 
@@ -224,8 +302,8 @@ function renderSegment(segment, color) {
224
302
  }
225
303
 
226
304
  /** Render Antigravity statusLine payload as ANSI or plain text lines. */
227
- export function formatAntigravityStatusLine(payload, { recommendation = null, now = Date.now(), color = true, fabrica = null } = {}) {
228
- const { segments, subagents } = buildAntigravityStatusSegments(payload, { recommendation, now, fabrica });
305
+ export function formatAntigravityStatusLine(payload, { recommendation = null, now = Date.now(), color = true, fabrica = null, home = os.homedir() } = {}) {
306
+ const { segments, subagents } = buildAntigravityStatusSegments(payload, { recommendation, now, fabrica, home });
229
307
  const renderRow = (row) => row.map((segment) => renderSegment(segment, color)).join('');
230
308
  return [renderRow(segments), ...subagents.map(renderRow)].join('\n');
231
309
  }
@@ -5,11 +5,16 @@ import {
5
5
  extractContextPercent,
6
6
  extractQuotaSummary,
7
7
  formatAntigravityStatusLine,
8
+ esperarCuotaDeBarra,
8
9
  } from './antigravity-barra.js';
9
10
  import { syncAndReadAntigravityBarraSession } from './antigravity-session.js';
10
11
 
11
12
  const MAX_STDIN_BYTES = 1024 * 1024;
12
13
 
14
+ /** Deja terminar el guardado de la cuota de la barra (como mucho 1 s) antes de salir, para no cortarlo a medias. */
15
+ const esperarCuotaGuardada = () =>
16
+ Promise.race([esperarCuotaDeBarra(), new Promise((resolve) => setTimeout(resolve, 1000).unref())]);
17
+
13
18
  const HELP = `Uso: nexakit antigravity barra [--sin-color] [--json]
14
19
  nexakit antigravity preparar [--salida carpeta] [--apply] [--json]
15
20
  nexakit antigravity agentes [--proyecto] [--salida carpeta] [--apply] [--actualizar] [--json]
@@ -83,14 +88,17 @@ async function handleBarra(flags, io, options) {
83
88
  options,
84
89
  );
85
90
 
86
- const fabrica = leerActivoDeFabrica(options.environment?.HOME || undefined);
91
+ const home = options.homeDirectory || options.environment?.HOME || undefined;
92
+ const fabrica = leerActivoDeFabrica(home);
87
93
  if (flags['--json']) {
88
- await io.out(JSON.stringify(buildAntigravityStatusSegments(payload, { recommendation, now, fabrica })) + '\n');
94
+ await io.out(JSON.stringify(buildAntigravityStatusSegments(payload, { recommendation, now, fabrica, home })) + '\n');
95
+ await esperarCuotaGuardada();
89
96
  return 0;
90
97
  }
91
98
  const color = !flags['--sin-color'] && !(options.environment?.NO_COLOR || process.env.NO_COLOR);
92
- const line = formatAntigravityStatusLine(payload, { recommendation, now, color, fabrica });
99
+ const line = formatAntigravityStatusLine(payload, { recommendation, now, color, fabrica, home });
93
100
  if (line) await io.out(`${line}\n`);
101
+ await esperarCuotaGuardada();
94
102
  return 0;
95
103
  }
96
104
 
@@ -4,6 +4,7 @@ import path from 'node:path';
4
4
  import { parseArgs, type ParseArgsOptionsConfig } from 'node:util';
5
5
  import { z } from 'zod';
6
6
  import { escaparMarkdown, escribirConsolidado, type HallazgoConsolidado, hallazgosDe, hallazgosGuardados } from './consolidar.js';
7
+ import { CLAVES_VENTANA, estadoCuota, fechaCuota, leerCuotas, nombreCuota, NOMBRES_VENTANA, sinCuota, UMBRAL_CUOTA_BAJA, ventanasCuota } from './cuotas.js';
7
8
  import * as ejecutor from './ejecutor.js';
8
9
  import type { CambioRecorrido, Recorrido } from './enrutador.js';
9
10
  import { describirPlan, ejecutarBanco, planificarBanco, verificarPlanAprobado, type EjecucionMedida, type ResultadoBanco } from './banco/ejecutar.js';
@@ -11,7 +12,7 @@ import { ResultadoValoracion } from './encargo/evidencia.js';
11
12
  import { type FabricasConectores, type InformeEncargo, type OpcionesEncargo, ejecutarEncargo, RE_ID_ENCARGO, valorarEncargo } from './encargo/ejecutar.js';
12
13
  import { ErrorEntorno, ErrorFabrica } from './errores.js';
13
14
  import { cargar } from './evidencia.js';
14
- import { claveEstacion } from './esquemas.js';
15
+ import { claveEstacion, IAExterna } from './esquemas.js';
15
16
  import { esCriterio, guardarPreferencias, leerPreferencias } from './preferencias.js';
16
17
  import { consumirPlanBanco, guardarPlanBanco, nombreRepo } from './rastro.js';
17
18
  import {
@@ -54,6 +55,7 @@ const AYUDA = `Uso: nexakit fabrica proponer --base <rama> [--foco <texto>] [--j
54
55
  nexakit fabrica resultado --id <id> [--veredictos <archivo.json>] [--json]
55
56
  nexakit fabrica cancelar --id <id>
56
57
  nexakit fabrica preferencias [--criterio calidad|barato] [--revision-cruzada sí|no] [--json]
58
+ nexakit cuotas [--json]
57
59
  nexakit encargar --ia codex|antigravity|auto --encargo <archivo.md> [--modelo <modelo>] [--esfuerzo <esfuerzo>]
58
60
  [--ordenes <archivo.json>] [--tiempo <min>] [--json]
59
61
  nexakit encargar valorar --id <id> --resultado aplicado|corregido|descartado
@@ -65,6 +67,7 @@ recorrido de revisión: estaciones, IA, modelo, esfuerzo, órdenes permitidas y
65
67
  modelo externo se elige con la evidencia medida, el umbral del riesgo y el criterio global;
66
68
  sin datos manda la tabla manual y se avisa de que conviene medir.
67
69
  preferencias muestra o guarda el criterio global y la revisión cruzada (por defecto, barato y sí).
70
+ cuotas consulta a Codex sin iniciar turnos y muestra también la cuota guardada por la barra de Antigravity.
68
71
  lanzar ejecuta ese recorrido en primer plano si la huella coincide con la propuesta y el
69
72
  diff sigue siendo el mismo; muestra el progreso y, al terminar, la ruta de consolidado.md.
70
73
  --cambios es un JSON con una lista de { "estacion", "quitar"?, "ia"?, "modelo"?, "esfuerzo"? }.
@@ -102,6 +105,7 @@ const USOS: Record<string, string> = {
102
105
  resultado: 'Uso: nexakit fabrica resultado --id <id> [--veredictos <archivo.json>] [--json]',
103
106
  cancelar: 'Uso: nexakit fabrica cancelar --id <id>',
104
107
  preferencias: 'Uso: nexakit fabrica preferencias [--criterio calidad|barato] [--revision-cruzada sí|no] [--json]',
108
+ cuotas: 'Uso: nexakit cuotas [--json]',
105
109
  encargar: 'Uso: nexakit encargar --ia codex|antigravity|auto --encargo <archivo.md> [--modelo <modelo>] [--esfuerzo <esfuerzo>] [--ordenes <archivo.json>] [--tiempo <min>] [--json]',
106
110
  'encargar valorar': 'Uso: nexakit encargar valorar --id <id> --resultado aplicado|corregido|descartado',
107
111
  'banco planificar': 'Uso: nexakit fabrica banco planificar [--fase 1|2] [--estacion <estacion>] [--ia codex|antigravity] [--json]',
@@ -657,6 +661,7 @@ async function ordenPreferencias(ctx: Contexto, valor: unknown, revision: unknow
657
661
  }
658
662
 
659
663
  const OPCIONES: Record<string, ParseArgsOptionsConfig> = {
664
+ cuotas: { json: { type: 'boolean' } },
660
665
  preferencias: { criterio: { type: 'string' }, 'revision-cruzada': { type: 'string' }, json: { type: 'boolean' } },
661
666
  proponer: { base: { type: 'string' }, foco: { type: 'string' }, json: { type: 'boolean' } },
662
667
  lanzar: { huella: { type: 'string' }, cambios: { type: 'string' }, json: { type: 'boolean' } },
@@ -687,10 +692,60 @@ function exigir(valor: string | undefined, bandera: string): string {
687
692
  return valor;
688
693
  }
689
694
 
690
- /**
691
- * Ejecuta `nexakit fabrica`. Devuelve el código de salida: 0 bien, 1 fallo de estación o escritura
692
- * detectada, 2 argumentos inválidos.
693
- */
695
+ async function ordenCuotas(ctx: Contexto, json: boolean): Promise<number> {
696
+ try {
697
+ const conectores = await crearConectoresDesdeEntorno({ ias: ['codex'], entorno: ctx.entorno, home: ctx.home });
698
+ try {
699
+ await conectores.codex?.consultarCuota?.();
700
+ } finally {
701
+ await cerrarConectores(conectores);
702
+ }
703
+ } catch {
704
+ // La consulta es de cortesía: también se puede ver el estado guardado sin Codex.
705
+ }
706
+ const cuotas = leerCuotas(ctx.home);
707
+ const ahora = Date.now();
708
+ const datos = IAExterna.options.map((ia) => {
709
+ const estado = cuotas[ia];
710
+ const efectivo = estadoCuota(estado, ahora);
711
+ const ventanas = ventanasCuota(estado, ahora);
712
+ const vigente = efectivo.porcentajeUsado !== undefined;
713
+ return { ia, estado, efectivo, ventanas, vigente };
714
+ });
715
+ if (json) {
716
+ const salidaJson = Object.fromEntries(datos.map(({ ia, estado, efectivo, ventanas, vigente }) => [
717
+ ia, { ...estado, ventanas, vigente, agotadaHasta: efectivo.agotadaHasta ?? null, agotada: efectivo.agotadaHasta !== undefined },
718
+ ]));
719
+ await salida(ctx, JSON.stringify(salidaJson, null, 2));
720
+ return 0;
721
+ }
722
+ const formatoReinicio = (fecha: string | undefined): string =>
723
+ fecha === undefined ? 'reinicio desconocido' : `reinicio ${fechaCuota(fecha, ahora)}`;
724
+ for (const { ia, estado, efectivo, ventanas, vigente } of datos) {
725
+ const { agotadaHasta, ventanaAgotada, porcentajeUsado } = efectivo;
726
+ const nombre = nombreCuota(ia);
727
+ let situacion = `${nombre}: sin datos de cuota vigentes`;
728
+ if (agotadaHasta !== undefined) situacion = sinCuota(ia, agotadaHasta, ventanaAgotada, ahora);
729
+ else if (porcentajeUsado !== undefined) situacion = `${nombre}: cuota ${porcentajeUsado >= UMBRAL_CUOTA_BAJA ? 'baja' : 'disponible'}`;
730
+ await salida(ctx, situacion);
731
+ for (const clave of CLAVES_VENTANA) {
732
+ const ventana = ventanas?.[clave];
733
+ if (ventana === undefined) continue;
734
+ const etiqueta = NOMBRES_VENTANA[clave];
735
+ const caducada = ventana.vigente ? '' : ' (caducada)';
736
+ await salida(ctx, ` ${etiqueta}${caducada}: ${ventana.porcentajeUsado} % usado, ${formatoReinicio(ventana.reinicio)}`);
737
+ }
738
+ if (ventanas === undefined && estado?.porcentajeUsado !== undefined) {
739
+ const lectura = `${estado.porcentajeUsado} % usado, ${formatoReinicio(estado.reinicio)}`;
740
+ if (vigente) await salida(ctx, ` ${lectura}`);
741
+ else if (estado.fecha !== undefined) await salida(ctx, ` Última lectura caducada (${fechaCuota(estado.fecha, ahora)}): ${lectura}`);
742
+ }
743
+ if (ia === 'antigravity' && !vigente) await salida(ctx, ' La cuota se actualiza al usar la barra de agy.');
744
+ }
745
+ return 0;
746
+ }
747
+
748
+ /** Ejecuta las órdenes de la fábrica y devuelve su código de salida. */
694
749
  export async function ejecutarCli(argv: string[], io: IoCli, opciones: OpcionesCli = {}): Promise<number> {
695
750
  const ctx: Contexto = {
696
751
  io,
@@ -732,10 +787,12 @@ export async function ejecutarCli(argv: string[], io: IoCli, opciones: OpcionesC
732
787
  if (analizado.positionals.length > 0) throw new ErrorUso('Sobran argumentos');
733
788
  valores = analizado.values;
734
789
  } catch (error) {
735
- throw error instanceof ErrorUso ? error : new ErrorUso(`Argumentos no válidos para «${primera === 'encargar' ? '' : 'fabrica '}${orden}»`);
790
+ throw error instanceof ErrorUso ? error : new ErrorUso(`Argumentos no válidos para «${primera === 'encargar' || primera === 'cuotas' ? '' : 'fabrica '}${orden}»`);
736
791
  }
737
792
  const json = valores['json'] === true;
738
793
  switch (orden) {
794
+ case 'cuotas':
795
+ return await ordenCuotas(ctx, json);
739
796
  case 'preferencias':
740
797
  return await ordenPreferencias(ctx, valores['criterio'], valores['revision-cruzada'], json);
741
798
  case 'proponer':
@@ -27,6 +27,7 @@ import { promisify } from 'node:util';
27
27
  import { resolveCliInvocation } from '../../../src/cli-executable.js';
28
28
  import { hallazgosJsonSchema, InformeEstacion } from '../esquemas.js';
29
29
  import { ClienteJsonRpc, ErrorProceso } from '../jsonrpc.js';
30
+ import { guardarVentanasCodex, TOPE_CUOTA_MS } from '../cuotas.js';
30
31
  import { nombreSeguro, type AlProgreso, type Conector, type Denegacion, type Encargo, type ResultadoEstacion } from './tipos.js';
31
32
  import type { ApplyPatchApprovalResponse } from '../protocolos/codex/ApplyPatchApprovalResponse.js';
32
33
  import type { ExecCommandApprovalParams } from '../protocolos/codex/ExecCommandApprovalParams.js';
@@ -109,6 +110,32 @@ export interface OpcionesConectorCodex {
109
110
  home?: string;
110
111
  }
111
112
 
113
+ /** Campos de RateLimitSnapshot usados por la fábrica. `resetsAt` viene en segundos Unix. */
114
+ function ventanasDeCuota(respuesta: unknown): Parameters<typeof guardarVentanasCodex>[1] {
115
+ if (!esObjeto(respuesta)) return {};
116
+ const porId = respuesta['rateLimitsByLimitId'];
117
+ const limites = (esObjeto(porId) ? porId['codex'] : undefined) ?? respuesta['rateLimits'];
118
+ if (!esObjeto(limites)) return {};
119
+ const id = limites['limitId'];
120
+ if (id !== undefined && id !== null && id !== 'codex') return {};
121
+ const ventanas: Parameters<typeof guardarVentanasCodex>[1] = {};
122
+ for (const [campo, duracion] of [['primary', 300], ['secondary', 10_080]] as const) {
123
+ const ventana = limites[campo];
124
+ if (!esObjeto(ventana)) continue;
125
+ const minutos = ventana['windowDurationMins'] ?? duracion;
126
+ const clave = minutos === 300 ? 'cincoHoras' : minutos === 10_080 ? 'semanal' : undefined;
127
+ const usado = ventana['usedPercent'];
128
+ if (clave === undefined || typeof usado !== 'number' || !Number.isFinite(usado) || usado < 0) continue;
129
+ const segundos = ventana['resetsAt'];
130
+ const reinicio = typeof segundos === 'number' ? new Date(segundos * 1000) : null;
131
+ ventanas[clave] = {
132
+ porcentajeUsado: Math.min(usado, 100),
133
+ ...(reinicio !== null && Number.isFinite(reinicio.getTime()) ? { reinicio: reinicio.toISOString() } : {}),
134
+ };
135
+ }
136
+ return ventanas;
137
+ }
138
+
112
139
  export interface VersionTiposCodex {
113
140
  /** Versión con la que se generaron los tipos vendorizados. */
114
141
  tipos: string;
@@ -530,6 +557,7 @@ function esperarAborto(señal: AbortSignal): { promesa: Promise<Desenlace>; quit
530
557
  }
531
558
 
532
559
  class ConectorCodex implements Conector {
560
+ private guardadoCuota: Promise<void> = Promise.resolve();
533
561
  readonly ia = 'codex' as const;
534
562
  private readonly opciones: OpcionesConectorCodex;
535
563
  private proceso: Proceso | undefined;
@@ -602,6 +630,33 @@ class ConectorCodex implements Conector {
602
630
  return modelos;
603
631
  }
604
632
 
633
+ async consultarCuota(topeMs = TOPE_CUOTA_MS): Promise<ReturnType<typeof ventanasDeCuota> | undefined> {
634
+ const limite = performance.now() + topeMs;
635
+ let reloj: NodeJS.Timeout | undefined;
636
+ const consulta = async () => {
637
+ const cliente = await this.asegurarCliente();
638
+ const restante = limite - performance.now();
639
+ if (restante <= 0) return undefined;
640
+ const respuesta = await cliente.solicitar('account/rateLimits/read', undefined, { timeoutMs: restante });
641
+ const ventanas = ventanasDeCuota(respuesta);
642
+ await this.guardarCuota(ventanas, 'consulta');
643
+ return ventanas;
644
+ };
645
+ try {
646
+ return await Promise.race([
647
+ consulta().catch(() => undefined),
648
+ new Promise<undefined>((resolver) => { reloj = setTimeout(() => resolver(undefined), topeMs); }),
649
+ ]);
650
+ } finally {
651
+ clearTimeout(reloj);
652
+ }
653
+ }
654
+
655
+ private guardarCuota(ventanas: ReturnType<typeof ventanasDeCuota>, fuente: 'consulta' | 'notificación'): Promise<void> {
656
+ this.guardadoCuota = this.guardadoCuota.then(() => guardarVentanasCodex(this.opciones.home ?? os.homedir(), ventanas, fuente));
657
+ return this.guardadoCuota;
658
+ }
659
+
605
660
  async ejecutar(encargo: Encargo, señal: AbortSignal, alProgreso?: AlProgreso): Promise<ResultadoEstacion> {
606
661
  const resultado: ResultadoEstacion = { estado: 'fallida', crudo: '', modeloInformado: null, tokens: null, denegaciones: [] };
607
662
  const cancelada = (): ResultadoEstacion => ({ ...resultado, estado: 'cancelada', motivo: CANCELADA });
@@ -693,7 +748,9 @@ class ConectorCodex implements Conector {
693
748
  return cancelada();
694
749
  }
695
750
  if (desenlace.tipo === 'muerto') {
696
- return { ...resultado, motivo: `El proceso de Codex terminó antes de acabar la revisión: ${desenlace.motivo}` };
751
+ const stderr = cliente.salidaError.trim();
752
+ const detalle = stderr ? `${desenlace.motivo}. Salida de error: ${stderr}` : desenlace.motivo;
753
+ return { ...resultado, motivo: `El proceso de Codex terminó antes de acabar la revisión: ${detalle}` };
697
754
  }
698
755
  return this.cerrarTurno(resultado, desenlace.fin, señal);
699
756
  } catch (error) {
@@ -707,6 +764,7 @@ class ConectorCodex implements Conector {
707
764
  } finally {
708
765
  aborto.quitar();
709
766
  if (threadId !== null) this.hilos.delete(threadId);
767
+ await this.guardadoCuota;
710
768
  }
711
769
  }
712
770
 
@@ -718,6 +776,7 @@ class ConectorCodex implements Conector {
718
776
  if (proceso) await proceso.cliente.cerrar();
719
777
  } finally {
720
778
  await this.borrarHomeAislado();
779
+ await this.guardadoCuota;
721
780
  }
722
781
  }
723
782
 
@@ -881,6 +940,10 @@ class ConectorCodex implements Conector {
881
940
 
882
941
  private alNotificar(metodo: string, params: unknown): void {
883
942
  if (!esObjeto(params)) return;
943
+ if (metodo === 'account/rateLimits/updated') {
944
+ void this.guardarCuota(ventanasDeCuota(params), 'notificación');
945
+ return;
946
+ }
884
947
  const enCurso = this.enCursoDe(params);
885
948
  if (!enCurso) return;
886
949
  if (metodo === 'item/completed') {
@@ -984,7 +1047,7 @@ function validarRaizEscritura(raiz: string, que = 'La raíz de escritura'): stri
984
1047
  }
985
1048
  }
986
1049
 
987
- export async function crearConectorCodex(opciones: OpcionesConectorCodex = {}): Promise<Conector> {
1050
+ export async function crearConectorCodex(opciones: OpcionesConectorCodex = {}): Promise<ConectorCodex> {
988
1051
  const raiz = opciones.escritura === undefined ? undefined : validarRaizEscritura(opciones.escritura.raiz);
989
1052
  const tmp = opciones.escritura?.tmp === undefined ? undefined : validarRaizEscritura(opciones.escritura.tmp, 'La carpeta temporal del encargo');
990
1053
  return new ConectorCodex(opciones, raiz, tmp);