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.
@@ -0,0 +1,294 @@
1
+ import { constants, closeSync, fstatSync, lstatSync, openSync, readFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { setTimeout as esperar } from 'node:timers/promises';
4
+ import { z } from 'zod';
5
+ import { ErrorCandadoOcupado, tomarCandadoArchivo } from './encargo/candado.js';
6
+ import { escribirReemplazando, prepararBase } from './rastro.js';
7
+ import { IAExterna } from './esquemas.js';
8
+
9
+ const HORA_MS = 60 * 60 * 1000;
10
+ const CADUCIDAD_BARRA_MS = 6 * HORA_MS;
11
+ const ARCHIVO = 'cuotas.json';
12
+ const CADUCIDAD_CANDADO_MS = 10_000;
13
+ const ESPERA_CANDADO_MS = 2_000;
14
+ const UMBRAL_AGOTADA = 95;
15
+ export const UMBRAL_CUOTA_BAJA = 80;
16
+ export const TOPE_CUOTA_MS = 5_000;
17
+ const fecha = z.iso.datetime();
18
+ const porcentaje = z.number().min(0).max(100);
19
+ const Ventana = z.object({ porcentajeUsado: porcentaje, reinicio: fecha.optional(), fecha: fecha.optional() });
20
+ const Ventanas = z.object({ cincoHoras: Ventana.optional(), semanal: Ventana.optional() });
21
+ const Bloqueo = z.object({ hasta: fecha, motivo: z.string(), fecha });
22
+ const Estado = Ventana.partial().extend({
23
+ ventanas: Ventanas.optional(),
24
+ porcentajeMinimoUsado: porcentaje.optional(),
25
+ bloqueo: Bloqueo.optional(),
26
+ fuente: z.enum(['consulta', 'notificación', 'barra']).optional(),
27
+ });
28
+ const EstadoEnDisco = Estado.extend({
29
+ agotadaHasta: fecha.optional(),
30
+ fuente: z.enum(['consulta', 'notificación', 'barra', 'error']).optional(),
31
+ });
32
+ type Ventanas = z.infer<typeof Ventanas>;
33
+ type Estado = z.infer<typeof Estado>;
34
+ type Cuotas = Partial<Record<IAExterna, Estado>>;
35
+ type ClaveVentana = keyof Ventanas;
36
+ export const NOMBRES_VENTANA = { cincoHoras: '5 h', semanal: 'semanal' } satisfies Record<ClaveVentana, string>;
37
+ export const CLAVES_VENTANA = ['cincoHoras', 'semanal'] as const;
38
+
39
+ export function leerCuotas(home: string): Cuotas {
40
+ try {
41
+ const nexakit = path.join(home, '.nexakit');
42
+ const base = path.join(nexakit, 'fabrica');
43
+ if (![nexakit, base].every((ruta) => lstatSync(ruta, { throwIfNoEntry: false })?.isDirectory())) return {};
44
+ const ruta = path.join(base, ARCHIVO);
45
+ if (!lstatSync(ruta, { throwIfNoEntry: false })?.isFile()) return {};
46
+ const fd = openSync(ruta, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
47
+ try {
48
+ const info = fstatSync(fd);
49
+ if (!info.isFile() || info.size > 16_384) return {};
50
+ const valor: unknown = JSON.parse(readFileSync(fd, 'utf8'));
51
+ const cuotas = z.object({ codex: z.unknown().optional(), antigravity: z.unknown().optional() }).safeParse(valor);
52
+ if (!cuotas.success) return {};
53
+ const datos: Cuotas = {};
54
+ for (const ia of IAExterna.options) {
55
+ const guardado = EstadoEnDisco.safeParse(cuotas.data[ia]);
56
+ if (!guardado.success) continue;
57
+ const { agotadaHasta, fuente, fecha: medida, ...estado } = guardado.data;
58
+ const tieneMedicion = estado.ventanas !== undefined || estado.porcentajeUsado !== undefined;
59
+ const fuentePredeterminada = ia === 'codex' ? 'consulta' : 'barra';
60
+ const fuenteMedicion = fuente === 'error' ? (tieneMedicion ? fuentePredeterminada : undefined) : fuente;
61
+ const bloqueo = estado.bloqueo ?? (agotadaHasta === undefined ? undefined : {
62
+ hasta: agotadaHasta, motivo: 'Límite informado por el proveedor', fecha: medida ?? agotadaHasta,
63
+ });
64
+ datos[ia] = {
65
+ ...estado,
66
+ ...(fuenteMedicion === undefined ? {} : { fuente: fuenteMedicion }),
67
+ ...(medida === undefined || fuenteMedicion === undefined ? {} : { fecha: medida }),
68
+ ...(bloqueo === undefined ? {} : { bloqueo }),
69
+ };
70
+ }
71
+ return datos;
72
+ } finally {
73
+ closeSync(fd);
74
+ }
75
+ } catch {
76
+ return {};
77
+ }
78
+ }
79
+
80
+ /** Las consultas de la CLI y las notificaciones de otros procesos pueden coincidir. */
81
+ async function actualizar(home: string, ia: IAExterna, cambiar: (anterior: Estado | undefined) => Estado): Promise<void> {
82
+ try {
83
+ const base = await prepararBase(home);
84
+ const ruta = path.join(base, ARCHIVO);
85
+ const candado = `${ruta}.candado`;
86
+ const limite = performance.now() + ESPERA_CANDADO_MS;
87
+ for (;;) {
88
+ try {
89
+ const propio = await tomarCandadoArchivo(candado, { caducidadMs: CADUCIDAD_CANDADO_MS });
90
+ try {
91
+ const cuotas = leerCuotas(home);
92
+ cuotas[ia] = cambiar(cuotas[ia]);
93
+ await escribirReemplazando(ruta, `${JSON.stringify(cuotas, null, 2)}\n`, () => {
94
+ if (!propio.vigente()) throw new ErrorCandadoOcupado('El candado de cuotas caducó');
95
+ });
96
+ } finally {
97
+ await propio.liberar();
98
+ }
99
+ return;
100
+ } catch (error) {
101
+ if (!(error instanceof ErrorCandadoOcupado)) throw error;
102
+ const restante = limite - performance.now();
103
+ if (restante <= 0) return;
104
+ await esperar(Math.min(20, restante));
105
+ }
106
+ }
107
+ } catch {
108
+ // La cuota es informativa si el estado local no se puede guardar.
109
+ }
110
+ }
111
+
112
+ export async function guardarVentanasCodex(home: string, ventanas: Ventanas, fuente: 'consulta' | 'notificación'): Promise<void> {
113
+ if (!CLAVES_VENTANA.some((clave) => ventanas[clave] !== undefined)) return;
114
+ const ahora = Date.now();
115
+ await actualizar(home, 'codex', (anterior) => {
116
+ const fusionadas: Ventanas = { ...ventanas };
117
+ if (fuente === 'notificación') {
118
+ for (const clave of CLAVES_VENTANA) {
119
+ const previa = anterior?.ventanas?.[clave];
120
+ if (fusionadas[clave] === undefined && previa !== undefined) {
121
+ // Si no hay reinicio conocido, la vigencia depende de cuándo se recibió esta ventana.
122
+ fusionadas[clave] = previa.reinicio === undefined ? { ...previa, fecha: previa.fecha ?? anterior?.fecha } : previa;
123
+ }
124
+ }
125
+ }
126
+ const medidas = Object.values(fusionadas).filter((v) => v !== undefined);
127
+ const mayor = medidas.sort((a, b) => b.porcentajeUsado - a.porcentajeUsado)[0];
128
+ const bloqueo = medidas.some((v) => v.porcentajeUsado >= UMBRAL_AGOTADA) ? bloqueoVigente(anterior, ahora) : undefined;
129
+ return {
130
+ porcentajeUsado: mayor?.porcentajeUsado,
131
+ reinicio: mayor?.reinicio,
132
+ ventanas: fusionadas,
133
+ fuente,
134
+ fecha: new Date(ahora).toISOString(),
135
+ bloqueo,
136
+ };
137
+ });
138
+ }
139
+
140
+ export async function guardarCuotaAntigravity(
141
+ home: string,
142
+ cuota: { porcentajeUsado: number; porcentajeMinimoUsado?: number; reinicio?: string | null },
143
+ ahora = Date.now(),
144
+ ): Promise<void> {
145
+ if (!Number.isFinite(cuota.porcentajeUsado)) return;
146
+ const porcentajeUsado = Math.min(100, Math.max(0, Math.round(cuota.porcentajeUsado)));
147
+ const minimo = cuota.porcentajeMinimoUsado;
148
+ const porcentajeMinimoUsado = minimo !== undefined && Number.isFinite(minimo)
149
+ ? Math.min(Math.max(0, cuota.porcentajeUsado), Math.max(0, minimo), 100)
150
+ : undefined;
151
+ const reinicioMs = typeof cuota.reinicio === 'string' ? Date.parse(cuota.reinicio) : Number.NaN;
152
+ const reinicio = Number.isFinite(reinicioMs) ? new Date(reinicioMs).toISOString() : undefined;
153
+ await actualizar(home, 'antigravity', (anterior) => ({
154
+ porcentajeUsado,
155
+ porcentajeMinimoUsado,
156
+ reinicio,
157
+ fuente: 'barra',
158
+ fecha: new Date(ahora).toISOString(),
159
+ bloqueo: bloqueoVigente(anterior, ahora),
160
+ }));
161
+ }
162
+
163
+ const vigente = (hasta: string | undefined, ahora: number): boolean => Date.parse(hasta ?? '') > ahora;
164
+ const enUnaHora = (ahora: number): string => new Date(ahora + HORA_MS).toISOString();
165
+
166
+ export function bloqueoVigente(estado: Estado | undefined, ahora = Date.now()): Estado['bloqueo'] {
167
+ return vigente(estado?.bloqueo?.hasta, ahora) ? estado?.bloqueo : undefined;
168
+ }
169
+
170
+ function limiteMedicion(estado: Estado, ventana: Partial<z.infer<typeof Ventana>>, ahora: number): string | undefined {
171
+ const medida = Date.parse(ventana.fecha ?? estado.fecha ?? '');
172
+ if (!Number.isFinite(medida) || ventana.porcentajeUsado === undefined) return undefined;
173
+ const duracion = estado.fuente === 'barra' ? CADUCIDAD_BARRA_MS : HORA_MS;
174
+ if (estado.fuente === 'barra' && ahora - medida >= duracion) return undefined;
175
+ const hasta = ventana.reinicio ?? new Date(medida + duracion).toISOString();
176
+ return vigente(hasta, ahora) ? hasta : undefined;
177
+ }
178
+
179
+ export function ventanasCuota(estado: Estado | undefined, ahora: number):
180
+ Partial<Record<ClaveVentana, z.infer<typeof Ventana> & { vigente: boolean }>> | undefined {
181
+ const ventanas = estado?.ventanas;
182
+ if (estado === undefined || ventanas === undefined) return undefined;
183
+ const resultado: NonNullable<ReturnType<typeof ventanasCuota>> = {};
184
+ for (const clave of CLAVES_VENTANA) {
185
+ const ventana = ventanas[clave];
186
+ if (ventana !== undefined) resultado[clave] = { ...ventana, vigente: limiteMedicion(estado, ventana, ahora) !== undefined };
187
+ }
188
+ return resultado;
189
+ }
190
+
191
+ /** Devuelve el límite de uso efectivo de las ventanas que todavía siguen abiertas. */
192
+ export function estadoCuota(estado: Estado | undefined, ahora = Date.now()): {
193
+ porcentajeUsado?: number; reinicio?: string; agotadaHasta?: string; ventanaAgotada?: ClaveVentana;
194
+ } {
195
+ if (estado === undefined) return {};
196
+ const ventanas = estado.ventanas === undefined
197
+ ? [[undefined, estado]] as const
198
+ : CLAVES_VENTANA.map((clave) => [clave, estado.ventanas?.[clave]] as const);
199
+ const efectivo: ReturnType<typeof estadoCuota> = {};
200
+ const bloqueo = bloqueoVigente(estado, ahora);
201
+ if (bloqueo !== undefined) efectivo.agotadaHasta = bloqueo.hasta;
202
+ for (const [clave, ventana] of ventanas) {
203
+ if (ventana?.porcentajeUsado === undefined) continue;
204
+ const hasta = limiteMedicion(estado, ventana, ahora);
205
+ if (hasta === undefined) continue;
206
+ if (efectivo.porcentajeUsado === undefined || ventana.porcentajeUsado > efectivo.porcentajeUsado) {
207
+ efectivo.porcentajeUsado = ventana.porcentajeUsado;
208
+ if (ventana.reinicio === undefined) delete efectivo.reinicio;
209
+ else efectivo.reinicio = ventana.reinicio;
210
+ }
211
+ const umbral = estado.fuente === 'barra' ? estado.porcentajeMinimoUsado : ventana.porcentajeUsado;
212
+ if (umbral !== undefined && umbral >= UMBRAL_AGOTADA &&
213
+ (efectivo.agotadaHasta === undefined || Date.parse(hasta) >= Date.parse(efectivo.agotadaHasta))) {
214
+ efectivo.agotadaHasta = hasta;
215
+ if (clave !== undefined) efectivo.ventanaAgotada = clave;
216
+ }
217
+ }
218
+ return efectivo;
219
+ }
220
+
221
+ export function fechaCuota(fecha: string, ahora = Date.now()): string {
222
+ const dia = new Date(fecha);
223
+ const hoy = new Date(ahora);
224
+ const mañana = new Date(ahora);
225
+ mañana.setDate(mañana.getDate() + 1);
226
+ const etiqueta = dia.toDateString() === hoy.toDateString() ? 'hoy'
227
+ : dia.toDateString() === mañana.toDateString() ? 'mañana' : `${dia.getDate()}/${dia.getMonth() + 1}`;
228
+ return `${etiqueta} ${dia.toLocaleTimeString('es', { hour: '2-digit', minute: '2-digit', hourCycle: 'h23' })}`;
229
+ }
230
+
231
+ export const nombreCuota = (ia: IAExterna): string => ia === 'codex' ? 'Codex' : 'Antigravity';
232
+ export const sinCuota = (ia: IAExterna, hasta: string, ventana?: ClaveVentana, ahora?: number): string =>
233
+ `${nombreCuota(ia)} sin cuota hasta ${fechaCuota(hasta, ahora)}${ventana === undefined ? '' : ` (ventana ${NOMBRES_VENTANA[ventana]})`}`;
234
+ export const pocaCuota = (ia: IAExterna, porcentaje: number, reinicio?: string, ahora?: number): string =>
235
+ `${nombreCuota(ia)} tiene poca cuota (${porcentaje} % usado${reinicio === undefined ? '' : `, reinicio ${fechaCuota(reinicio, ahora)}`})`;
236
+
237
+ // Solo se examina el motivo del fallo, con los prefijos que agregan los conectores y el ejecutor.
238
+ const PREFIJO = /^(?:(?:el conector falló|(?:Codex|Antigravity) (?:falló|no completó la revisión|interrumpió la revisión)|salida de error|(?:api )?error(?: \d{3})?):\s*|\[?429\]?(?:\s*:\s*|\s+))/iu;
239
+ const LIMITE = /^(?:(?:you(?:['’]ve| have) )?hit (?:your |the )?usage limit|usage[_ ]limit[_ ](?:exceeded|reached)|(?:api )?rate[- ]limit(?:ed|s? (?:exceeded|reached|hit))|(?:you(?:['’]ve| have)? )?exceeded (?:your |the )?(?:current )?quota|(?:your |the )?(?:api |usage |model )?quota (?:has been |is )?(?:exceeded|exhausted|reached)|insufficient_quota|resource[ _-]exhausted|too many requests)\b/iu;
240
+ const LIMITE_BREVE = /^(?:(?:api )?rate[- ]limit|usage limit|quota)(?:[.:,;!]?(?:\s*try again\b|\s*$))/iu;
241
+ const TRANSITORIO = /^(?:(?:api )?rate[- ]limit|too many requests)/iu;
242
+ const REINTENTO = /\btry again at\s+(?:(?<mes>[a-z]+)\.?\s+(?<dia>\d{1,2})(?:st|nd|rd|th)?,?\s+(?:(?<año>\d{4}),?\s+)?)?(?<hora>\d{1,2}):(?<minuto>\d{2})(?:\s*(?<periodo>[ap]m)\b)?(?![\w:])/iu;
243
+ const MESES = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'];
244
+
245
+ function fechaReintento(linea: string, ahora: number): string | undefined {
246
+ const grupos = REINTENTO.exec(linea)?.groups;
247
+ if (grupos === undefined) return undefined;
248
+ const { mes, dia, año, hora, minuto, periodo } = grupos;
249
+ const h = Number(hora);
250
+ const m = Number(minuto);
251
+ if (m >= 60 || (periodo === undefined ? h >= 24 : h < 1 || h > 12)) return undefined;
252
+ const reinicio = new Date(ahora);
253
+ reinicio.setHours(periodo === undefined ? h : h % 12 + (periodo.toLowerCase() === 'pm' ? 12 : 0), m, 0, 0);
254
+ if (mes === undefined) {
255
+ if (reinicio.getTime() <= ahora) reinicio.setDate(reinicio.getDate() + 1);
256
+ return reinicio.toISOString();
257
+ }
258
+ const nombre = mes.toLowerCase();
259
+ const indice = MESES.findIndex((mes) => mes === nombre || mes.slice(0, 3) === nombre);
260
+ if (indice === -1) return undefined;
261
+ const diaDelMes = Number(dia);
262
+ reinicio.setFullYear(año === undefined ? reinicio.getFullYear() : Number(año), indice, diaDelMes);
263
+ if (año === undefined && reinicio.getTime() <= ahora) {
264
+ reinicio.setFullYear(reinicio.getFullYear() + 1, indice, diaDelMes);
265
+ }
266
+ return reinicio.getMonth() === indice && reinicio.getDate() === diaDelMes && reinicio.getTime() > ahora
267
+ ? reinicio.toISOString() : undefined;
268
+ }
269
+
270
+ /** Interpreta la hora local del proveedor. Una hora anterior se refiere al día siguiente. */
271
+ export function detectarAgotamiento(motivo: string, ahora = Date.now()): string | undefined {
272
+ const lineas = motivo.slice(-8192).split(/\r?\n|(?<=\. )(?=Salida de error:)/iu);
273
+ for (let linea of lineas) {
274
+ linea = linea.trim();
275
+ while (PREFIJO.test(linea)) linea = linea.replace(PREFIJO, '');
276
+ if (!LIMITE.test(linea) && !LIMITE_BREVE.test(linea)) continue;
277
+ return fechaReintento(linea, ahora) ??
278
+ (TRANSITORIO.test(linea) ? new Date(ahora + 10 * 60_000).toISOString() : enUnaHora(ahora));
279
+ }
280
+ return undefined;
281
+ }
282
+
283
+ export async function registrarFalloDeCuota(home: string, ia: IAExterna, motivo: string | undefined): Promise<void> {
284
+ const ahora = Date.now();
285
+ if (motivo === undefined) return;
286
+ const hasta = detectarAgotamiento(motivo, ahora);
287
+ if (hasta === undefined) return;
288
+ await actualizar(home, ia, (anterior) => ({
289
+ ...anterior,
290
+ bloqueo: bloqueoVigente(anterior, Date.parse(hasta)) ?? {
291
+ hasta, motivo: motivo.trim().slice(-1024), fecha: new Date(ahora).toISOString(),
292
+ },
293
+ }));
294
+ }
@@ -1,6 +1,7 @@
1
1
  import { createHash, randomBytes } from 'node:crypto';
2
2
  import os from 'node:os';
3
3
  import type { AlProgreso, Conector, Encargo, ResultadoEstacion } from './conectores/tipos.js';
4
+ import { registrarFalloDeCuota } from './cuotas.js';
4
5
  import { leerDiff } from './diff.js';
5
6
  import { clasificarCambios, instantanea, type Instantanea } from './disco.js';
6
7
  import { calcularCoste, comprobarHuella, descarte, type EstacionRecorrido, type Recorrido } from './enrutador.js';
@@ -450,6 +451,7 @@ async function correrConPlaza(ej: Ejecucion, trabajo: Lanzable, timeoutMs: numbe
450
451
  else if (agotado) final = { ...resultado, estado: 'fallida', motivo: TIEMPO_AGOTADO };
451
452
  else if (ej.cancelado) final = { ...resultado, estado: 'cancelada', motivo: CANCELADA };
452
453
  else final = resultado;
454
+ if (final.estado === 'fallida' && trabajo.ia !== 'claude') await registrarFalloDeCuota(ej.home, trabajo.ia, final.motivo);
453
455
  // Primero el archivo de la estación, para que un estado terminado siempre tenga su resultado.
454
456
  try {
455
457
  await rastro.guardarEstacion(ej.estado.dir, trabajo.fila.estacion, trabajo.encargoRastro, final, trabajo.fila.revisionDe);
@@ -6,6 +6,7 @@ import { inspectModels, recommendAntigravity } from '../../../src/model-command.
6
6
  import { REGLA_ORDENES_SIMPLES } from '../../../src/regla-ordenes-simples.js';
7
7
  import { crearConectorAntigravity, esComponenteProtegido, ORDENES_ACTIVAS } from '../conectores/antigravity.js';
8
8
  import { crearConectorCodex } from '../conectores/codex.js';
9
+ import { bloqueoVigente, estadoCuota, leerCuotas, pocaCuota, registrarFalloDeCuota, sinCuota, UMBRAL_CUOTA_BAJA } from '../cuotas.js';
9
10
  import type { AlProgreso, Conector, Denegacion, Encargo, ResultadoEstacion } from '../conectores/tipos.js';
10
11
  import { clasificarCambios, instantanea } from '../disco.js';
11
12
  import { descarte, type Catalogos } from '../enrutador.js';
@@ -535,6 +536,10 @@ export async function ejecutarEncargo(opciones: OpcionesEncargo): Promise<Inform
535
536
  else b.avisos.push(`No se usa el modelo normal de ${quien}: ${texto}`);
536
537
  }
537
538
  const { ia: iaElegida, conector, modelo, esfuerzo } = elegida;
539
+ const { porcentajeUsado, reinicio } = estadoCuota(leerCuotas(home)[iaElegida]);
540
+ if (porcentajeUsado !== undefined && porcentajeUsado >= UMBRAL_CUOTA_BAJA) {
541
+ b.avisos.push(pocaCuota(iaElegida, porcentajeUsado, reinicio));
542
+ }
538
543
  b.ia = iaElegida;
539
544
  b.modelo = modelo;
540
545
  b.esfuerzo = esfuerzo;
@@ -642,6 +647,7 @@ export async function ejecutarEncargo(opciones: OpcionesEncargo): Promise<Inform
642
647
  } else if (resultado.estado === 'fallida') {
643
648
  b.estado = 'fallido';
644
649
  b.motivo = limpiar(resultado.motivo ?? 'la IA no completó el encargo');
650
+ await registrarFalloDeCuota(home, elegida.ia, resultado.motivo);
645
651
  } else {
646
652
  b.estado = 'ok';
647
653
  }
@@ -769,15 +775,22 @@ export async function ejecutarEncargo(opciones: OpcionesEncargo): Promise<Inform
769
775
  motivo?: string;
770
776
  }> {
771
777
  const sinModelo = (motivo: string) => ({ candidatos: [], motivo });
778
+ const previa = leerCuotas(home)[quien];
779
+ const agotada = estadoCuota(previa);
780
+ const aviso = agotada.agotadaHasta === undefined ? undefined : sinCuota(quien, agotada.agotadaHasta, agotada.ventanaAgotada);
781
+ if (aviso !== undefined && (quien !== 'codex' || bloqueoVigente(previa) === undefined)) return sinModelo(aviso);
772
782
  const fabrica = fabricas[quien];
773
- if (fabrica === undefined) return sinModelo(`${quien} no está disponible`);
783
+ if (fabrica === undefined) return sinModelo(aviso ?? `${quien} no está disponible`);
774
784
  let conector: Conector;
775
785
  try {
776
786
  conector = await fabrica({ raiz: w.dir, ordenesPermitidas: ordenes, ...(tmpCreado ? { tmp } : {}) });
777
787
  } catch (error) {
778
- return sinModelo(`${quien} no está disponible: ${datosDe(error)}`);
788
+ return sinModelo(aviso ?? `${quien} no está disponible: ${datosDe(error)}`);
779
789
  }
780
790
  abiertos[quien] = conector;
791
+ await conector.consultarCuota?.().catch(() => undefined);
792
+ const { agotadaHasta, ventanaAgotada } = estadoCuota(leerCuotas(home)[quien]);
793
+ if (agotadaHasta !== undefined) return sinModelo(sinCuota(quien, agotadaHasta, ventanaAgotada));
781
794
  let catalogo: Awaited<ReturnType<Conector['catalogo']>> | typeof AGOTADO;
782
795
  try {
783
796
  catalogo = await conTope(Promise.resolve().then(() => conector.catalogo()), topeCatalogoMs);
@@ -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, type Candidato } from './decision.js';
5
6
  import { clasificar, leerDiff, type Categoria } from './diff.js';
6
7
  import { ErrorFabrica } from './errores.js';
@@ -258,6 +259,16 @@ export async function proponer(entrada: {
258
259
  ]);
259
260
 
260
261
  const avisosEstaciones: string[] = [];
262
+ const cuotas = leerCuotas(home);
263
+ const agotadas = new Map<IA, string>();
264
+ const instante = ahora.getTime();
265
+ for (const ia of IAExterna.options) {
266
+ const { agotadaHasta, ventanaAgotada, porcentajeUsado, reinicio } = estadoCuota(cuotas[ia], instante);
267
+ if (agotadaHasta !== undefined) agotadas.set(ia, sinCuota(ia, agotadaHasta, ventanaAgotada, instante));
268
+ else if (porcentajeUsado !== undefined && porcentajeUsado >= UMBRAL_CUOTA_BAJA) {
269
+ avisosEstaciones.push(pocaCuota(ia, porcentajeUsado, reinicio, instante));
270
+ }
271
+ }
261
272
  let usoEvidencia = false;
262
273
 
263
274
  function proponerEstacion(estacion: NombreEstacion, revisionDe?: IAExterna): EstacionRecorrido {
@@ -282,33 +293,54 @@ export async function proponer(entrada: {
282
293
  const motivo = revisionDe !== undefined ? 'revisión cruzada de código' : porDiff ? regla.motivo : 'activada en la configuración';
283
294
 
284
295
  const descartes: string[] = [];
296
+ const descartesCuota = new Set<string>();
297
+ function descartar(c: Candidato): string | null {
298
+ const agotada = agotadas.get(c.ia);
299
+ if (agotada === undefined) return descarte(c, catalogos);
300
+ descartesCuota.add(agotada);
301
+ return agotada;
302
+ }
285
303
  const manual = candidatosDe(estacion, revisionDe === undefined ? cfg : undefined, descartes, revisionDe);
286
- const propuesta = (c: Candidato, explicacion: string, calidad: number | null): EstacionRecorrido => ({
287
- estacion,
288
- ...(revisionDe === undefined ? {} : { revisionDe }),
289
- ia: c.ia,
290
- modelo: c.modelo,
291
- // Antigravity lleva el esfuerzo dentro del id del modelo.
292
- esfuerzo: c.ia === 'antigravity' ? null : c.esfuerzo,
293
- motivo,
294
- descartes,
295
- explicacion,
296
- calidad,
297
- ordenesPermitidas: ordenesDe(estacion, c.ia, cfg),
298
- estado: 'propuesta',
299
- });
300
- const sinModelo = (): EstacionRecorrido => ({
301
- ...omitida(motivo),
302
- descartes,
303
- explicacion: 'ningún candidato está disponible en el catálogo',
304
- estado: 'sin-modelo',
305
- });
304
+ const propuesta = (c: Candidato, explicacion: string, calidad: number | null): EstacionRecorrido => {
305
+ for (const aviso of descartesCuota) avisosEstaciones.push(`${aviso}. En ${nombre} se usa ${c.ia} (${nombreDe(c)})`);
306
+ return {
307
+ estacion,
308
+ ...(revisionDe === undefined ? {} : { revisionDe }),
309
+ ia: c.ia,
310
+ modelo: c.modelo,
311
+ // Antigravity lleva el esfuerzo dentro del id del modelo.
312
+ esfuerzo: c.ia === 'antigravity' ? null : c.esfuerzo,
313
+ motivo,
314
+ descartes,
315
+ explicacion,
316
+ calidad,
317
+ ordenesPermitidas: ordenesDe(estacion, c.ia, cfg),
318
+ estado: 'propuesta',
319
+ };
320
+ };
321
+ const sinModelo = (): EstacionRecorrido => {
322
+ for (const aviso of descartesCuota) avisosEstaciones.push(`${aviso}. En ${nombre} no hay otro candidato disponible`);
323
+ return { ...omitida(motivo), descartes, explicacion: 'ningún candidato está disponible en el catálogo', estado: 'sin-modelo' };
324
+ };
325
+ function delCatalogo(): Candidato[] {
326
+ const candidatos: Candidato[] = [];
327
+ for (const ia of revisionDe === undefined ? IAExterna.options : [revisionDe]) {
328
+ if (agotadas.has(ia)) continue;
329
+ for (const { modelo, esfuerzos } of catalogos[ia] ?? []) {
330
+ if (ia === 'antigravity') candidatos.push({ ia, modelo, esfuerzo: null });
331
+ else for (const esfuerzo of esfuerzos) {
332
+ if (cfg?.esfuerzo === undefined || esfuerzo === cfg.esfuerzo) candidatos.push({ ia, modelo, esfuerzo });
333
+ }
334
+ }
335
+ }
336
+ return candidatos;
337
+ }
306
338
 
307
339
  const fijada = cfg?.ia !== undefined || cfg?.modelo !== undefined;
308
340
  if (revisionDe === undefined && (fijada || manual[0]?.ia === 'claude')) {
309
341
  // Lo fijado en la configuración y las estaciones de Claude no se deciden por evidencia: manda la tabla.
310
342
  for (const c of manual) {
311
- const razon = descarte(c, catalogos);
343
+ const razon = descartar(c);
312
344
  if (razon !== null) {
313
345
  descartes.push(razon);
314
346
  continue;
@@ -317,24 +349,23 @@ export async function proponer(entrada: {
317
349
  const cumple = (cfg?.ia === undefined || c.ia === cfg.ia) && (cfg?.modelo === undefined || c.modelo === cfg.modelo);
318
350
  return propuesta(c, cumple ? NOTA_FIJADA : `${NOTA_FIJADA} no está disponible; se usa ${nombreDe(c)} de la tabla`, null);
319
351
  }
352
+ if (descartesCuota.size > 0) {
353
+ const alternativa = delCatalogo()[0];
354
+ if (alternativa !== undefined) return propuesta(alternativa, 'se usa el orden del catálogo por falta de cuota', null);
355
+ }
320
356
  return sinModelo();
321
357
  }
322
358
 
323
359
  const disponibles: Candidato[] = [];
324
360
  for (const c of candidatosConEvidencia(estacion, manual, revisionDe === undefined ? cfg : undefined, catalogos, evidencia)) {
325
361
  if (revisionDe !== undefined && c.ia !== revisionDe) continue;
326
- const razon = descarte(c, catalogos);
362
+ const razon = descartar(c);
327
363
  if (razon === null) disponibles.push(c);
328
364
  else descartes.push(razon);
329
365
  }
330
- // Si la tabla y la evidencia no ofrecen ningún par vivo, usa el orden del catálogo.
331
- const porCatalogo = revisionDe !== undefined && disponibles.length === 0;
332
- if (porCatalogo) {
333
- for (const { modelo, esfuerzos } of catalogos[revisionDe] ?? []) {
334
- if (revisionDe === 'antigravity') disponibles.push({ ia: revisionDe, modelo, esfuerzo: null });
335
- else for (const esfuerzo of esfuerzos) disponibles.push({ ia: revisionDe, modelo, esfuerzo });
336
- }
337
- }
366
+ // Una revisión cruzada o una estación que perdió sus candidatos por cuota puede recurrir al catálogo.
367
+ const porCatalogo = disponibles.length === 0 && (revisionDe !== undefined || descartesCuota.size > 0);
368
+ if (porCatalogo) disponibles.push(...delCatalogo());
338
369
  if (disponibles.length === 0) return sinModelo();
339
370
 
340
371
  usoEvidencia = true;
@@ -359,9 +390,14 @@ export async function proponer(entrada: {
359
390
  if (estacion !== 'codigo' || principal.estado === 'omitida' || !revisionCruzada) continue;
360
391
  for (const ia of IAExterna.options) {
361
392
  if (principal.ia === ia) continue;
393
+ const agotada = agotadas.get(ia);
394
+ if (agotada !== undefined) {
395
+ avisosEstaciones.push(`Se omite la revisión cruzada de código: ${agotada}`);
396
+ continue;
397
+ }
362
398
  const revision = proponerEstacion(estacion, ia);
363
399
  if (revision.estado === 'propuesta') estaciones.push(revision);
364
- else avisosEstaciones.push(`Se omite la revisión cruzada de código con ${ia}: no hay modelos disponibles`);
400
+ else avisosEstaciones.push(`Se omite la revisión cruzada de código con ${nombreCuota(ia)}: no hay modelos disponibles`);
365
401
  }
366
402
  }
367
403
 
@@ -97,9 +97,9 @@ export async function escribirReemplazando(ruta: string, texto: string | Uint8Ar
97
97
  const json = (valor: unknown): string => `${JSON.stringify(valor, null, 2)}\n`;
98
98
 
99
99
  /** Deja lista `~/.nexakit/fabrica/` y devuelve su ruta. */
100
- async function prepararBase(home: string): Promise<string> {
100
+ export async function prepararBase(home: string): Promise<string> {
101
101
  const nexakit = path.join(home, '.nexakit');
102
- await mkdir(nexakit, { recursive: true, mode: 0o700 });
102
+ await carpetaPropia(nexakit);
103
103
  const base = path.join(nexakit, 'fabrica');
104
104
  await carpetaPropia(base);
105
105
  return base;
@@ -95,14 +95,14 @@ export function opcionesDeEntorno(entorno: NodeJS.ProcessEnv, variable: string):
95
95
  * `NEXAKIT_FABRICA_CODEX` y `NEXAKIT_FABRICA_AGY`. Si uno no se puede crear, no entra en el resultado y se avisa.
96
96
  */
97
97
  export async function crearConectoresDesdeEntorno(
98
- opciones: { ias?: readonly IA[]; entorno?: NodeJS.ProcessEnv; avisar?: Avisar } = {},
98
+ opciones: { ias?: readonly IA[]; entorno?: NodeJS.ProcessEnv; avisar?: Avisar; home?: string } = {},
99
99
  ): Promise<Conectores> {
100
- const { ias = ['codex', 'antigravity'], entorno = process.env, avisar = sinAvisos } = opciones;
100
+ const { ias = ['codex', 'antigravity'], entorno = process.env, avisar = sinAvisos, home } = opciones;
101
101
  const conectores: Conectores = {};
102
102
  for (const ia of ias) {
103
103
  try {
104
104
  if (ia === 'codex') {
105
- conectores.codex = await crearConectorCodex(opcionesDeEntorno(entorno, 'NEXAKIT_FABRICA_CODEX'));
105
+ conectores.codex = await crearConectorCodex({ ...opcionesDeEntorno(entorno, 'NEXAKIT_FABRICA_CODEX'), ...(home === undefined ? {} : { home }) });
106
106
  } else if (ia === 'antigravity') {
107
107
  conectores.antigravity = await crearConectorAntigravity(opcionesDeEntorno(entorno, 'NEXAKIT_FABRICA_AGY'));
108
108
  }
@@ -209,10 +209,10 @@ export async function proponerEnRaiz(entrada: {
209
209
  avisar?: Avisar;
210
210
  }): Promise<Recorrido> {
211
211
  const { raiz, base, foco, home, entorno = process.env, avisar = sinAvisos } = entrada;
212
- const conectores = await crearConectoresDesdeEntorno({ entorno, avisar });
212
+ const conectores = await crearConectoresDesdeEntorno({ entorno, avisar, home });
213
213
  let catalogos: Catalogos;
214
214
  try {
215
- catalogos = await consultarCatalogos(conectores, avisar);
215
+ [catalogos] = await Promise.all([consultarCatalogos(conectores, avisar), conectores.codex?.consultarCuota?.()]);
216
216
  } finally {
217
217
  await cerrarConectores(conectores);
218
218
  }
@@ -261,7 +261,7 @@ export async function lanzarAprobado(entrada: {
261
261
  for (const e of recorrido.estaciones) {
262
262
  if (e.estado === 'propuesta' && e.ia !== null && e.ia !== 'claude') externas.add(e.ia);
263
263
  }
264
- const conectores = await crearConectoresDesdeEntorno({ ias: [...externas], entorno, avisar });
264
+ const conectores = await crearConectoresDesdeEntorno({ ias: [...externas], entorno, avisar, home });
265
265
  let id: string;
266
266
  try {
267
267
  ({ id } = await ejecutor.lanzar(recorrido, { raiz, conectores, paralelismo: config.paralelismo, ...(config.paralelismoPorIa === undefined ? {} : { paralelismoPorIa: config.paralelismoPorIa }), home }));
@@ -42,6 +42,7 @@ const HELP = `Uso: npx nexakit [--project <ruta>] [--si]
42
42
  nexakit codex auditar|preparar|agentes|actividad|consumo|recomendar|hook|ejecutar|comparar [opciones]
43
43
  nexakit antigravity barra|preparar|agentes|recomendar|hook|ejecutar [opciones]
44
44
  nexakit fabrica proponer|lanzar|estado|resultado|cancelar|banco|preferencias [opciones]
45
+ nexakit cuotas [--json]
45
46
  nexakit encargar --ia codex|antigravity|auto --encargo <archivo.md> [--modelo <m>] [--esfuerzo <e>] [--ordenes <archivo.json>] [--tiempo <min>] [--json]
46
47
  nexakit encargar valorar --id <id> --resultado aplicado|corregido|descartado
47
48
  nexakit ahorro [--json]
@@ -109,11 +110,11 @@ export async function runToolkitCli(
109
110
  if (command === 'modelo') return runModelCommand(rest, { out, err }, options);
110
111
  if (command === 'codex') return runCodexCommand(rest, { out, err, input, output }, options);
111
112
  if (command === 'antigravity') return runAntigravityCommand(rest, { out, err, input, output }, options);
112
- if (command === 'fabrica' || command === 'encargar') {
113
+ if (command === 'fabrica' || command === 'encargar' || command === 'cuotas') {
113
114
  let aviso = '';
114
115
  const cli = await loadWithDependencyCheck(() => import('../dist/fabrica/cli.js'), { write: text => { aviso += text; } });
115
116
  if (!cli) { await err(aviso); return 1; }
116
- return cli.ejecutarCli(command === 'encargar' ? ['encargar', ...rest] : rest, { out, err }, options);
117
+ return cli.ejecutarCli(command === 'fabrica' ? rest : [command, ...rest], { out, err }, options);
117
118
  }
118
119
  if (command === 'ahorro') return runAhorroCommand(rest, { out, err }, options);
119
120
  if (command === 'lecciones') return runLeccionesCommand(rest, { out, err }, options);