nexakit 0.13.1 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +3 -3
- package/README.md +9 -8
- package/assets/runtime/package-lock.json +2 -2
- package/dist/fabrica/cli.js +69 -6
- package/dist/fabrica/conectores/codex.js +68 -1
- package/dist/fabrica/cuotas.js +299 -0
- package/dist/fabrica/decision.js +1 -3
- package/dist/fabrica/ejecutor.js +3 -0
- package/dist/fabrica/encargo/ejecutar.js +19 -6
- package/dist/fabrica/enrutador.js +77 -34
- package/dist/fabrica/mcp.js +2 -2
- package/dist/fabrica/rastro.js +2 -2
- package/dist/fabrica/sesion.js +5 -5
- package/dist/fabrica/tabla-modelos.json +4 -4
- package/package.json +1 -1
- package/plugins/huellas.json +8 -8
- package/plugins/nexakit-ahorro/.claude-plugin/plugin.json +2 -2
- package/plugins/nexakit-ahorro/README.md +9 -3
- package/plugins/nexakit-ahorro/hooks/register.js +17 -0
- package/plugins/nexakit-ahorro/tests/register.test.ts +40 -6
- package/plugins/nexakit-modelo/.claude-plugin/plugin.json +2 -2
- package/plugins/nexakit-modelo/hooks/barra.js +4 -27
- package/plugins/nexakit-modelo/hooks/decidir.js +15 -46
- package/plugins/nexakit-modelo/hooks/recomendar.js +8 -13
- package/plugins/nexakit-modelo/hooks/register.js +13 -134
- package/plugins/nexakit-modelo/tests/register.test.ts +31 -230
- package/plugins/nexakit-sesion/.claude-plugin/plugin.json +1 -1
- package/plugins/nexakit-sesion/hooks/aviso.js +5 -6
- package/plugins/nexakit-sesion/hooks/register.js +1 -1
- package/plugins/niveles/.claude-plugin/plugin.json +2 -2
- package/plugins/niveles/agents/cazador-de-flakes.md +2 -5
- package/plugins/niveles/agents/cierre-de-memoria.md +2 -4
- package/plugins/niveles/agents/investigador.md +6 -9
- package/plugins/niveles/agents/nivel-alto.md +6 -7
- package/plugins/niveles/agents/nivel-exigente.md +6 -7
- package/plugins/niveles/agents/nivel-ligero.md +7 -8
- package/plugins/niveles/agents/nivel-normal.md +6 -7
- package/plugins/niveles/agents/revisor-de-calidad.md +2 -4
- package/plugins/niveles/agents/sincronizador-docs.md +2 -4
- package/plugins/niveles/agents/subir-al-repo.md +2 -4
- package/skills/elegir-modelo/SKILL.md +13 -14
- package/skills/elegir-modelo/modelos.mjs +1 -0
- package/skills/fabrica/SKILL.md +6 -7
- package/src/agent-models.js +21 -7
- package/src/ahorro-command.js +26 -4
- package/src/antigravity-agents.js +10 -8
- package/src/antigravity-barra.js +89 -24
- package/src/antigravity-command.js +11 -3
- package/src/antigravity-hook.js +1 -1
- package/src/antigravity-pre-tool.js +3 -1
- package/src/antigravity-recommendation.js +49 -51
- package/src/codex-audit.js +2 -2
- package/src/codex-auto-output.js +3 -0
- package/src/codex-hook.js +1 -1
- package/src/codex-output.js +6 -1
- package/src/codex-pre-tool.js +7 -0
- package/src/codex-recommendation.js +6 -10
- package/src/codex-routing.js +1 -1
- package/src/codex-setup.js +4 -3
- package/src/codex-team.js +20 -19
- package/src/fabrica/cli.ts +63 -6
- package/src/fabrica/conectores/codex.ts +65 -2
- package/src/fabrica/conectores/tipos.ts +2 -0
- package/src/fabrica/cuotas.ts +294 -0
- package/src/fabrica/decision.ts +1 -3
- package/src/fabrica/ejecutor.ts +2 -0
- package/src/fabrica/encargo/ejecutar.ts +17 -6
- package/src/fabrica/enrutador.ts +67 -31
- package/src/fabrica/mcp.ts +2 -2
- package/src/fabrica/rastro.ts +2 -2
- package/src/fabrica/sesion.ts +6 -6
- package/src/fabrica/tabla-modelos.json +4 -4
- package/src/gemini-tools.js +1 -1
- package/src/level-agents.js +9 -7
- package/src/model-command.js +16 -7
- package/src/mods.js +2 -2
- package/src/preferencias-globales.js +80 -0
- package/src/review-instructions.js +27 -37
- package/src/toolkit-cli.js +5 -4
- package/src/regla-ordenes-simples.d.ts +0 -2
- package/src/regla-ordenes-simples.js +0 -4
|
@@ -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
|
-
|
|
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<
|
|
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>;
|
|
@@ -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
|
+
}
|
package/src/fabrica/decision.ts
CHANGED
|
@@ -59,14 +59,12 @@ export function riesgoDe(categorias: ReadonlySet<Categoria>, estacion: NombreEst
|
|
|
59
59
|
// Orden de coste sin datos medidos
|
|
60
60
|
// ---------------------------------------------------------------------------------------------------------------
|
|
61
61
|
|
|
62
|
-
/** Sin rango de coste en las listas por nivel, Neon usa el mismo rango que una familia desconocida. */
|
|
63
62
|
const FAMILIA_DESCONOCIDA = 99;
|
|
64
63
|
const FAMILIAS: ReadonlyArray<readonly [RegExp, number]> = [
|
|
65
64
|
[/\b(luna|flash|haiku)\b/u, 0],
|
|
66
65
|
[/\b(hydrogen|terra|sonnet)\b/u, 1],
|
|
67
|
-
[/\b(sol|argon|opus)\b/u, 2],
|
|
66
|
+
[/\b(neon|sol|argon|opus)\b/u, 2],
|
|
68
67
|
[/\b(astra|carbon|fable)\b/u, 3],
|
|
69
|
-
[/\bneon\b/u, FAMILIA_DESCONOCIDA],
|
|
70
68
|
];
|
|
71
69
|
|
|
72
70
|
const ESFUERZOS = ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'] as const;
|
package/src/fabrica/ejecutor.ts
CHANGED
|
@@ -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);
|
|
@@ -3,9 +3,9 @@ import { chmod, lstat, mkdir, readFile, rm } from 'node:fs/promises';
|
|
|
3
3
|
import os from 'node:os';
|
|
4
4
|
import path from 'node:path';
|
|
5
5
|
import { inspectModels, recommendAntigravity } from '../../../src/model-command.js';
|
|
6
|
-
import { REGLA_ORDENES_SIMPLES } from '../../../src/regla-ordenes-simples.js';
|
|
7
6
|
import { crearConectorAntigravity, esComponenteProtegido, ORDENES_ACTIVAS } from '../conectores/antigravity.js';
|
|
8
7
|
import { crearConectorCodex } from '../conectores/codex.js';
|
|
8
|
+
import { bloqueoVigente, estadoCuota, leerCuotas, pocaCuota, registrarFalloDeCuota, sinCuota, UMBRAL_CUOTA_BAJA } from '../cuotas.js';
|
|
9
9
|
import type { AlProgreso, Conector, Denegacion, Encargo, ResultadoEstacion } from '../conectores/tipos.js';
|
|
10
10
|
import { clasificarCambios, instantanea } from '../disco.js';
|
|
11
11
|
import { descarte, type Catalogos } from '../enrutador.js';
|
|
@@ -206,9 +206,8 @@ function instruccionesDelEncargo(texto: string, lecciones: readonly Leccion[], r
|
|
|
206
206
|
];
|
|
207
207
|
const lecc = bloqueLecciones(lecciones);
|
|
208
208
|
if (lecc !== '') partes.push('', lecc);
|
|
209
|
-
partes.push('', 'Reglas de trabajo:',
|
|
210
|
-
partes.push(
|
|
211
|
-
partes.push('', 'Al terminar, responde con un resumen breve en texto (qué cambiaste y qué queda pendiente), sin pegar el diff.');
|
|
209
|
+
partes.push('', 'Reglas de trabajo:', reglaOrdenes);
|
|
210
|
+
partes.push('', 'Al terminar, responde con un resumen en texto (qué cambiaste, qué comprobaste y qué queda pendiente), sin pegar el diff.');
|
|
212
211
|
return `${partes.join('\n')}\n`;
|
|
213
212
|
}
|
|
214
213
|
|
|
@@ -535,6 +534,10 @@ export async function ejecutarEncargo(opciones: OpcionesEncargo): Promise<Inform
|
|
|
535
534
|
else b.avisos.push(`No se usa el modelo normal de ${quien}: ${texto}`);
|
|
536
535
|
}
|
|
537
536
|
const { ia: iaElegida, conector, modelo, esfuerzo } = elegida;
|
|
537
|
+
const { porcentajeUsado, reinicio } = estadoCuota(leerCuotas(home)[iaElegida]);
|
|
538
|
+
if (porcentajeUsado !== undefined && porcentajeUsado >= UMBRAL_CUOTA_BAJA) {
|
|
539
|
+
b.avisos.push(pocaCuota(iaElegida, porcentajeUsado, reinicio));
|
|
540
|
+
}
|
|
538
541
|
b.ia = iaElegida;
|
|
539
542
|
b.modelo = modelo;
|
|
540
543
|
b.esfuerzo = esfuerzo;
|
|
@@ -642,6 +645,7 @@ export async function ejecutarEncargo(opciones: OpcionesEncargo): Promise<Inform
|
|
|
642
645
|
} else if (resultado.estado === 'fallida') {
|
|
643
646
|
b.estado = 'fallido';
|
|
644
647
|
b.motivo = limpiar(resultado.motivo ?? 'la IA no completó el encargo');
|
|
648
|
+
await registrarFalloDeCuota(home, elegida.ia, resultado.motivo);
|
|
645
649
|
} else {
|
|
646
650
|
b.estado = 'ok';
|
|
647
651
|
}
|
|
@@ -769,15 +773,22 @@ export async function ejecutarEncargo(opciones: OpcionesEncargo): Promise<Inform
|
|
|
769
773
|
motivo?: string;
|
|
770
774
|
}> {
|
|
771
775
|
const sinModelo = (motivo: string) => ({ candidatos: [], motivo });
|
|
776
|
+
const previa = leerCuotas(home)[quien];
|
|
777
|
+
const agotada = estadoCuota(previa);
|
|
778
|
+
const aviso = agotada.agotadaHasta === undefined ? undefined : sinCuota(quien, agotada.agotadaHasta, agotada.ventanaAgotada);
|
|
779
|
+
if (aviso !== undefined && (quien !== 'codex' || bloqueoVigente(previa) === undefined)) return sinModelo(aviso);
|
|
772
780
|
const fabrica = fabricas[quien];
|
|
773
|
-
if (fabrica === undefined) return sinModelo(`${quien} no está disponible`);
|
|
781
|
+
if (fabrica === undefined) return sinModelo(aviso ?? `${quien} no está disponible`);
|
|
774
782
|
let conector: Conector;
|
|
775
783
|
try {
|
|
776
784
|
conector = await fabrica({ raiz: w.dir, ordenesPermitidas: ordenes, ...(tmpCreado ? { tmp } : {}) });
|
|
777
785
|
} catch (error) {
|
|
778
|
-
return sinModelo(`${quien} no está disponible: ${datosDe(error)}`);
|
|
786
|
+
return sinModelo(aviso ?? `${quien} no está disponible: ${datosDe(error)}`);
|
|
779
787
|
}
|
|
780
788
|
abiertos[quien] = conector;
|
|
789
|
+
await conector.consultarCuota?.().catch(() => undefined);
|
|
790
|
+
const { agotadaHasta, ventanaAgotada } = estadoCuota(leerCuotas(home)[quien]);
|
|
791
|
+
if (agotadaHasta !== undefined) return sinModelo(sinCuota(quien, agotadaHasta, ventanaAgotada));
|
|
781
792
|
let catalogo: Awaited<ReturnType<Conector['catalogo']>> | typeof AGOTADO;
|
|
782
793
|
try {
|
|
783
794
|
catalogo = await conTope(Promise.resolve().then(() => conector.catalogo()), topeCatalogoMs);
|