nexakit 0.13.0 → 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.
@@ -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':
@@ -25,6 +25,10 @@
25
25
  // y, si es una orden, coincide exactamente con `ordenesPermitidas` y no está encadenada. El resto se rechaza y se
26
26
  // anota. Las reglas persistentes de la persona (`permissions.allow`) no se aplican gracias a `--gemini-dir`; las del
27
27
  // repo (`.gemini/`) se rechazan por la lista blanca de personalizaciones, que sigue vigente en este modo.
28
+ // Peticiones de edición reales (agy 1.5.16, capturadas con `NEXAKIT_DEPURAR_ACP`): `kind: edit` con `name: write_file`
29
+ // (`rawInput` = { Path, Content, Overwrite? }) y `name: edit_file` (`rawInput` = { Path, Target, Replacement }); la entrada
30
+ // se repite en `args`, `locations` y en un `content` de tipo diff. `Target` es texto (el fragmento que se reemplaza), no
31
+ // una ruta. El título lleva una ruta relativa larga con `..` que no se usa. Solo se admiten las claves observadas.
28
32
  // Órdenes en modo escritura: DESACTIVADAS por defecto en todas las plataformas (`ORDENES_ACTIVAS`, `comprobarOrdenes`).
29
33
  // Antigravity escribe solo dentro de la copia y no ejecuta órdenes; las pruebas las ejecuta el orquestador. Motivos,
30
34
  // comprobados con sesiones reales contra agy 1.5.14 y 1.5.16 en macOS (`gemini-3.8-flash-low`, unos 11 000 tokens cada
@@ -47,7 +51,7 @@
47
51
  // (`true` fuerza órdenes aprobables; `'verificar'` aplica la plataforma y la versión), para pruebas y para reactivarla.
48
52
  import { execFile, spawn } from 'node:child_process';
49
53
  import type { ChildProcess } from 'node:child_process';
50
- import { lstatSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, rmSync, statSync } from 'node:fs';
54
+ import { closeSync, fchmodSync, lstatSync, mkdirSync, mkdtempSync, openSync, readdirSync, realpathSync, rmSync, statSync, writeSync } from 'node:fs';
51
55
  import { readFile } from 'node:fs/promises';
52
56
  import { tmpdir } from 'node:os';
53
57
  import path from 'node:path';
@@ -163,12 +167,17 @@ export function esComponenteProtegido(parte: string): boolean {
163
167
 
164
168
  /** Claves de `rawInput` que contienen una ruta (nombres normalizados: minúsculas y sin `_` ni `-`). */
165
169
  const CLAVES_RUTA = new Set(['path', 'filepath', 'absolutepath', 'targetfile', 'file', 'directory', 'directorypath', 'dir', 'searchpath', 'oldpath', 'newpath', 'from', 'to', 'source', 'destination', 'dest']);
166
- const CLAVES_TEXTO = ['content', 'contents', 'text', 'newtext', 'oldtext', 'newstring', 'oldstring', 'replacement', 'description', 'instruction'];
170
+ // Claves de texto observadas en agy 1.5.16: `write_file` manda `Path`, `Content` y `Overwrite`; `edit_file` manda `Path`,
171
+ // `Target` (el fragmento que se reemplaza, NO una ruta) y `Replacement`.
172
+ const CLAVES_TEXTO = new Set(['content', 'contents', 'text', 'newtext', 'oldtext', 'newstring', 'oldstring', 'replacement', 'target', 'description', 'instruction']);
173
+ const CLAVES_SOLO_EDIT_FILE = new Set(['target', 'replacement']);
174
+ /** Claves booleanas admitidas (`write_file` manda `Overwrite`). */
175
+ const CLAVES_BOOLEANAS = new Set(['overwrite']);
167
176
  const CLAVES_LECTURA = ['offset', 'limit', 'line', 'startline', 'endline'];
168
177
  const CLAVES_BUSQUEDA = ['query', 'pattern', 'glob', 'include', 'exclude', 'regex', 'casesensitive'];
169
178
  /** Lista cerrada de claves de `rawInput` admitidas por tipo de petición; cualquier otra rechaza la petición. */
170
179
  const CLAVES_ADMITIDAS: Record<string, Set<string>> = {
171
- edit: new Set([...CLAVES_RUTA, ...CLAVES_TEXTO]),
180
+ edit: new Set([...CLAVES_RUTA, ...CLAVES_TEXTO, ...CLAVES_BOOLEANAS]),
172
181
  delete: new Set(CLAVES_RUTA),
173
182
  move: new Set(CLAVES_RUTA),
174
183
  read: new Set([...CLAVES_RUTA, ...CLAVES_LECTURA]),
@@ -298,6 +307,9 @@ function analizarPeticion(tipo: string, llamada: Record<string, unknown>): Petic
298
307
  if (vistas.has(normal)) return rechazo(`clave repetida con otra capitalización: ${recortar(clave)}`);
299
308
  vistas.add(normal);
300
309
  if (!admitidas.has(normal)) return rechazo(`campo no reconocido: ${recortar(clave)}`);
310
+ if (CLAVES_SOLO_EDIT_FILE.has(normal) && llamada['name'] !== undefined && llamada['name'] !== 'edit_file') {
311
+ return rechazo(`campo no reconocido: ${recortar(clave)}`);
312
+ }
301
313
  if (tipo === 'execute') {
302
314
  if (normal === 'bypasssandbox') {
303
315
  // Salir del sandbox nunca se aprueba: solo vale `false` explícito.
@@ -318,6 +330,10 @@ function analizarPeticion(tipo: string, llamada: Record<string, unknown>): Petic
318
330
  } else if (CLAVES_RUTA.has(normal)) {
319
331
  if (typeof valor !== 'string') return rechazo(`el campo ${clave} no es un texto`);
320
332
  resultado.rutas.push(valor);
333
+ } else if (CLAVES_BOOLEANAS.has(normal)) {
334
+ if (typeof valor !== 'boolean') return rechazo(`el campo ${clave} no es un booleano`);
335
+ } else if (CLAVES_TEXTO.has(normal)) {
336
+ if (typeof valor !== 'string') return rechazo(`el campo ${clave} no es un texto`);
321
337
  }
322
338
  }
323
339
  return resultado;
@@ -342,11 +358,12 @@ export function motivoPermisoRechazado(
342
358
  if (llamada['name'] !== undefined && llamada['name'] !== HERRAMIENTA_ORDENES) {
343
359
  return `la herramienta no es ${HERRAMIENTA_ORDENES}: ${recortar(String(llamada['name']))}`;
344
360
  }
345
- // agy repite la entrada de la orden en `args`: si dice otra cosa que `rawInput`, no se sabe cuál se ejecuta.
346
- if (llamada['args'] !== undefined) {
347
- if (!esObjeto(llamada['args'])) return 'la orden trae args que no son un objeto';
348
- if (canonico(llamada['args']) !== canonico(llamada['rawInput'])) return 'la orden trae args distintos de rawInput';
349
- }
361
+ }
362
+ // agy repite la entrada de la herramienta en `args` (órdenes, `write_file`, `edit_file`): si dice otra cosa que
363
+ // `rawInput`, no se sabe cuál se usa y la ruta validada podría no ser la que se escribe.
364
+ if ((TIPOS_ESCRITURA.has(tipo) || tipo === 'execute') && llamada['args'] !== undefined) {
365
+ if (!esObjeto(llamada['args'])) return 'la petición trae args que no son un objeto';
366
+ if (canonico(llamada['args']) !== canonico(llamada['rawInput'])) return 'la petición trae args distintos de rawInput';
350
367
  }
351
368
  const peticion = analizarPeticion(tipo, llamada);
352
369
  if (peticion.motivo !== null) return peticion.motivo;
@@ -376,6 +393,85 @@ export function motivoPermisoRechazado(
376
393
  return null;
377
394
  }
378
395
 
396
+ /** Variable de entorno de depuración: ruta absoluta de un archivo donde se anota el resumen de cada petición de permiso. */
397
+ export const VARIABLE_DEPURAR_ACP = 'NEXAKIT_DEPURAR_ACP';
398
+ const MAX_ELEMENTOS_DEPURACION = 20;
399
+ const MAX_PROFUNDIDAD_DEPURACION = 6;
400
+
401
+ function resumirValorSinTexto(valor: unknown, profundidad = 0): unknown {
402
+ if (typeof valor === 'string') return valor.length;
403
+ if (valor === null || typeof valor !== 'object') return valor;
404
+ if (profundidad >= MAX_PROFUNDIDAD_DEPURACION) return '…';
405
+ if (Array.isArray(valor)) return valor.slice(0, MAX_ELEMENTOS_DEPURACION).map((v) => resumirValorSinTexto(v, profundidad + 1));
406
+ return Object.fromEntries(Object.entries(valor).map(([k, v]) => [k, resumirValorSinTexto(v, profundidad + 1)]));
407
+ }
408
+
409
+ /**
410
+ * Resumen acotado de una petición de permiso para el registro de depuración: guarda solo `kind`, `name`, `rutas`
411
+ * y los nombres de las claves de `rawInput` con la longitud de cada texto, nunca el contenido de los textos.
412
+ */
413
+ export function resumirParaDepuracion(llamada: Record<string, unknown>): {
414
+ kind: string | null;
415
+ name: string | null;
416
+ rutas: string[];
417
+ claves: Record<string, unknown>;
418
+ } {
419
+ const rutas: string[] = [];
420
+ if (Array.isArray(llamada['locations'])) {
421
+ for (const l of llamada['locations']) {
422
+ if (esObjeto(l) && typeof l['path'] === 'string') rutas.push(l['path']);
423
+ }
424
+ }
425
+ if (Array.isArray(llamada['content'])) {
426
+ for (const c of llamada['content']) {
427
+ if (esObjeto(c) && c['type'] === 'diff' && typeof c['path'] === 'string') rutas.push(c['path']);
428
+ }
429
+ }
430
+ const crudo = llamada['rawInput'];
431
+ const claves: Record<string, unknown> = {};
432
+ if (esObjeto(crudo)) {
433
+ for (const [k, v] of Object.entries(crudo)) {
434
+ if (CLAVES_RUTA.has(normalizarClave(k)) && typeof v === 'string') rutas.push(v);
435
+ claves[k] = resumirValorSinTexto(v);
436
+ }
437
+ }
438
+ return {
439
+ kind: texto(llamada['kind']),
440
+ name: texto(llamada['name']),
441
+ rutas: [...new Set(rutas)],
442
+ claves,
443
+ };
444
+ }
445
+
446
+ /**
447
+ * Con `NEXAKIT_DEPURAR_ACP=<ruta absoluta>` anota (una línea JSON por petición, archivo 0o600, nunca en enlace
448
+ * simbólico) solo `kind`, `name`, `rutas`, las claves de `rawInput` con la longitud de cada texto (nunca su contenido)
449
+ * y la decisión definitiva con su motivo. Nunca lanza.
450
+ */
451
+ function depurarPermiso(llamada: Record<string, unknown>, motivo: string | null): void {
452
+ const destino = process.env[VARIABLE_DEPURAR_ACP];
453
+ if (destino === undefined || destino === '' || !path.isAbsolute(destino)) return;
454
+ try {
455
+ const info = lstatSync(destino, { throwIfNoEntry: false });
456
+ if (info?.isSymbolicLink()) return;
457
+ const linea = JSON.stringify({
458
+ momento: new Date().toISOString(),
459
+ decision: motivo === null ? 'aprobada' : 'rechazada',
460
+ motivo,
461
+ toolCall: resumirParaDepuracion(llamada),
462
+ });
463
+ const fd = openSync(destino, 'a', 0o600);
464
+ try {
465
+ fchmodSync(fd, 0o600);
466
+ writeSync(fd, `${linea}\n`);
467
+ } finally {
468
+ closeSync(fd);
469
+ }
470
+ } catch {
471
+ // La depuración nunca debe romper el encargo.
472
+ }
473
+ }
474
+
379
475
  class ErrorNoInstalado extends Error {
380
476
  constructor() {
381
477
  super(NO_INSTALADO);
@@ -1002,11 +1098,13 @@ class ConectorAntigravity implements Conector {
1002
1098
  if (motivo === null) {
1003
1099
  const permitir = opciones.find((o) => o['kind'] === 'allow_once' && typeof o['optionId'] === 'string');
1004
1100
  if (permitir) {
1101
+ depurarPermiso(llamada, null);
1005
1102
  enCurso?.resultado.aprobaciones?.push({ tipo: 'session/request_permission', detalle: recortar(`Permiso aprobado: ${detalle}`) });
1006
1103
  return { outcome: { outcome: 'selected', optionId: permitir['optionId'] as string } };
1007
1104
  }
1008
1105
  motivo = 'no hay opción de permitir una vez';
1009
1106
  }
1107
+ depurarPermiso(llamada, motivo);
1010
1108
  }
1011
1109
  enCurso?.resultado.denegaciones.push({
1012
1110
  tipo: 'session/request_permission',
@@ -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);
@@ -38,6 +38,8 @@ export interface Conector {
38
38
  ia: IA;
39
39
  /** Solo Antigravity en modo escritura: si aprueba las órdenes de la lista (por defecto no: están desactivadas). */
40
40
  readonly ordenesActivas?: boolean;
41
+ /** Refresca la cuota de cuenta sin iniciar un turno, si el proveedor ofrece la consulta. */
42
+ consultarCuota?(): Promise<unknown>;
41
43
  catalogo(): Promise<Array<{ modelo: string; esfuerzos: string[] }>>;
42
44
  ejecutar(encargo: Encargo, señal: AbortSignal, alProgreso?: AlProgreso): Promise<ResultadoEstacion>;
43
45
  cerrar(): Promise<void>;