nexakit 0.13.1 → 0.13.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- 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/ejecutor.js +3 -0
- package/dist/fabrica/encargo/ejecutar.js +17 -2
- package/dist/fabrica/enrutador.js +77 -34
- package/dist/fabrica/rastro.js +2 -2
- package/dist/fabrica/sesion.js +5 -5
- package/package.json +1 -1
- package/src/antigravity-barra.js +84 -6
- package/src/antigravity-command.js +11 -3
- 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/ejecutor.ts +2 -0
- package/src/fabrica/encargo/ejecutar.ts +15 -2
- package/src/fabrica/enrutador.ts +67 -31
- package/src/fabrica/rastro.ts +2 -2
- package/src/fabrica/sesion.ts +6 -6
- package/src/toolkit-cli.js +3 -2
package/README.md
CHANGED
|
@@ -39,6 +39,7 @@ npx nexakit memoria <subcomando> # Operaciones avanzadas de memori
|
|
|
39
39
|
npx nexakit setup --omitir <skill> --apply # Declarar quitada una skill global que ya no enlazas
|
|
40
40
|
npx nexakit setup --reponer <skill> --apply # Devolver una skill global que quitaste
|
|
41
41
|
~/.nexakit/nexakit fabrica proponer --base main # Proponer un recorrido de revisión (lo lanza después con la huella de la propuesta)
|
|
42
|
+
~/.nexakit/nexakit cuotas [--json] # Consultar ventanas de cuota y agotamientos registrados
|
|
42
43
|
~/.nexakit/nexakit encargar --ia codex|antigravity|auto --encargo <archivo.md> [--modelo m] [--esfuerzo e] [--ordenes <archivo.json>] [--tiempo <min>] # Delega en una copia aislada, imprime el id y devuelve un diff. Auto aprende de las valoraciones
|
|
43
44
|
~/.nexakit/nexakit encargar valorar --id <id> --resultado aplicado|corregido|descartado # Registra el resultado del encargo
|
|
44
45
|
~/.nexakit/nexakit fabrica preferencias --criterio calidad # Elegir modelos por calidad o por coste; revisión cruzada sí|no
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nexakit",
|
|
3
|
-
"version": "0.13.
|
|
3
|
+
"version": "0.13.2",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "nexakit",
|
|
9
|
-
"version": "0.13.
|
|
9
|
+
"version": "0.13.2",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@agentclientprotocol/sdk": "^2.7.0",
|
package/dist/fabrica/cli.js
CHANGED
|
@@ -4,13 +4,14 @@ import path from 'node:path';
|
|
|
4
4
|
import { parseArgs } from 'node:util';
|
|
5
5
|
import { z } from 'zod';
|
|
6
6
|
import { escaparMarkdown, escribirConsolidado, 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 { describirPlan, ejecutarBanco, planificarBanco, verificarPlanAprobado } from './banco/ejecutar.js';
|
|
9
10
|
import { ResultadoValoracion } from './encargo/evidencia.js';
|
|
10
11
|
import { ejecutarEncargo, RE_ID_ENCARGO, valorarEncargo } from './encargo/ejecutar.js';
|
|
11
12
|
import { ErrorEntorno, ErrorFabrica } from './errores.js';
|
|
12
13
|
import { cargar } from './evidencia.js';
|
|
13
|
-
import { claveEstacion } from './esquemas.js';
|
|
14
|
+
import { claveEstacion, IAExterna } from './esquemas.js';
|
|
14
15
|
import { esCriterio, guardarPreferencias, leerPreferencias } from './preferencias.js';
|
|
15
16
|
import { consumirPlanBanco, guardarPlanBanco, nombreRepo } from './rastro.js';
|
|
16
17
|
import { cerrarConectores, consultarCatalogos, crearConectoresDesdeEntorno, EsquemaCambios, limpiar, lanzarAprobado, leerSinEnlaces, mensajeDe, proponerEnRaiz, raizDelRepo, } from './sesion.js';
|
|
@@ -21,6 +22,7 @@ const AYUDA = `Uso: nexakit fabrica proponer --base <rama> [--foco <texto>] [--j
|
|
|
21
22
|
nexakit fabrica resultado --id <id> [--veredictos <archivo.json>] [--json]
|
|
22
23
|
nexakit fabrica cancelar --id <id>
|
|
23
24
|
nexakit fabrica preferencias [--criterio calidad|barato] [--revision-cruzada sí|no] [--json]
|
|
25
|
+
nexakit cuotas [--json]
|
|
24
26
|
nexakit encargar --ia codex|antigravity|auto --encargo <archivo.md> [--modelo <modelo>] [--esfuerzo <esfuerzo>]
|
|
25
27
|
[--ordenes <archivo.json>] [--tiempo <min>] [--json]
|
|
26
28
|
nexakit encargar valorar --id <id> --resultado aplicado|corregido|descartado
|
|
@@ -32,6 +34,7 @@ recorrido de revisión: estaciones, IA, modelo, esfuerzo, órdenes permitidas y
|
|
|
32
34
|
modelo externo se elige con la evidencia medida, el umbral del riesgo y el criterio global;
|
|
33
35
|
sin datos manda la tabla manual y se avisa de que conviene medir.
|
|
34
36
|
preferencias muestra o guarda el criterio global y la revisión cruzada (por defecto, barato y sí).
|
|
37
|
+
cuotas consulta a Codex sin iniciar turnos y muestra también la cuota guardada por la barra de Antigravity.
|
|
35
38
|
lanzar ejecuta ese recorrido en primer plano si la huella coincide con la propuesta y el
|
|
36
39
|
diff sigue siendo el mismo; muestra el progreso y, al terminar, la ruta de consolidado.md.
|
|
37
40
|
--cambios es un JSON con una lista de { "estacion", "quitar"?, "ia"?, "modelo"?, "esfuerzo"? }.
|
|
@@ -68,6 +71,7 @@ const USOS = {
|
|
|
68
71
|
resultado: 'Uso: nexakit fabrica resultado --id <id> [--veredictos <archivo.json>] [--json]',
|
|
69
72
|
cancelar: 'Uso: nexakit fabrica cancelar --id <id>',
|
|
70
73
|
preferencias: 'Uso: nexakit fabrica preferencias [--criterio calidad|barato] [--revision-cruzada sí|no] [--json]',
|
|
74
|
+
cuotas: 'Uso: nexakit cuotas [--json]',
|
|
71
75
|
encargar: 'Uso: nexakit encargar --ia codex|antigravity|auto --encargo <archivo.md> [--modelo <modelo>] [--esfuerzo <esfuerzo>] [--ordenes <archivo.json>] [--tiempo <min>] [--json]',
|
|
72
76
|
'encargar valorar': 'Uso: nexakit encargar valorar --id <id> --resultado aplicado|corregido|descartado',
|
|
73
77
|
'banco planificar': 'Uso: nexakit fabrica banco planificar [--fase 1|2] [--estacion <estacion>] [--ia codex|antigravity] [--json]',
|
|
@@ -607,6 +611,7 @@ async function ordenPreferencias(ctx, valor, revision, json) {
|
|
|
607
611
|
return 0;
|
|
608
612
|
}
|
|
609
613
|
const OPCIONES = {
|
|
614
|
+
cuotas: { json: { type: 'boolean' } },
|
|
610
615
|
preferencias: { criterio: { type: 'string' }, 'revision-cruzada': { type: 'string' }, json: { type: 'boolean' } },
|
|
611
616
|
proponer: { base: { type: 'string' }, foco: { type: 'string' }, json: { type: 'boolean' } },
|
|
612
617
|
lanzar: { huella: { type: 'string' }, cambios: { type: 'string' }, json: { type: 'boolean' } },
|
|
@@ -635,10 +640,66 @@ function exigir(valor, bandera) {
|
|
|
635
640
|
throw new ErrorUso(`Falta ${bandera}`);
|
|
636
641
|
return valor;
|
|
637
642
|
}
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
643
|
+
async function ordenCuotas(ctx, json) {
|
|
644
|
+
try {
|
|
645
|
+
const conectores = await crearConectoresDesdeEntorno({ ias: ['codex'], entorno: ctx.entorno, home: ctx.home });
|
|
646
|
+
try {
|
|
647
|
+
await conectores.codex?.consultarCuota?.();
|
|
648
|
+
}
|
|
649
|
+
finally {
|
|
650
|
+
await cerrarConectores(conectores);
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
catch {
|
|
654
|
+
// La consulta es de cortesía: también se puede ver el estado guardado sin Codex.
|
|
655
|
+
}
|
|
656
|
+
const cuotas = leerCuotas(ctx.home);
|
|
657
|
+
const ahora = Date.now();
|
|
658
|
+
const datos = IAExterna.options.map((ia) => {
|
|
659
|
+
const estado = cuotas[ia];
|
|
660
|
+
const efectivo = estadoCuota(estado, ahora);
|
|
661
|
+
const ventanas = ventanasCuota(estado, ahora);
|
|
662
|
+
const vigente = efectivo.porcentajeUsado !== undefined;
|
|
663
|
+
return { ia, estado, efectivo, ventanas, vigente };
|
|
664
|
+
});
|
|
665
|
+
if (json) {
|
|
666
|
+
const salidaJson = Object.fromEntries(datos.map(({ ia, estado, efectivo, ventanas, vigente }) => [
|
|
667
|
+
ia, { ...estado, ventanas, vigente, agotadaHasta: efectivo.agotadaHasta ?? null, agotada: efectivo.agotadaHasta !== undefined },
|
|
668
|
+
]));
|
|
669
|
+
await salida(ctx, JSON.stringify(salidaJson, null, 2));
|
|
670
|
+
return 0;
|
|
671
|
+
}
|
|
672
|
+
const formatoReinicio = (fecha) => fecha === undefined ? 'reinicio desconocido' : `reinicio ${fechaCuota(fecha, ahora)}`;
|
|
673
|
+
for (const { ia, estado, efectivo, ventanas, vigente } of datos) {
|
|
674
|
+
const { agotadaHasta, ventanaAgotada, porcentajeUsado } = efectivo;
|
|
675
|
+
const nombre = nombreCuota(ia);
|
|
676
|
+
let situacion = `${nombre}: sin datos de cuota vigentes`;
|
|
677
|
+
if (agotadaHasta !== undefined)
|
|
678
|
+
situacion = sinCuota(ia, agotadaHasta, ventanaAgotada, ahora);
|
|
679
|
+
else if (porcentajeUsado !== undefined)
|
|
680
|
+
situacion = `${nombre}: cuota ${porcentajeUsado >= UMBRAL_CUOTA_BAJA ? 'baja' : 'disponible'}`;
|
|
681
|
+
await salida(ctx, situacion);
|
|
682
|
+
for (const clave of CLAVES_VENTANA) {
|
|
683
|
+
const ventana = ventanas?.[clave];
|
|
684
|
+
if (ventana === undefined)
|
|
685
|
+
continue;
|
|
686
|
+
const etiqueta = NOMBRES_VENTANA[clave];
|
|
687
|
+
const caducada = ventana.vigente ? '' : ' (caducada)';
|
|
688
|
+
await salida(ctx, ` ${etiqueta}${caducada}: ${ventana.porcentajeUsado} % usado, ${formatoReinicio(ventana.reinicio)}`);
|
|
689
|
+
}
|
|
690
|
+
if (ventanas === undefined && estado?.porcentajeUsado !== undefined) {
|
|
691
|
+
const lectura = `${estado.porcentajeUsado} % usado, ${formatoReinicio(estado.reinicio)}`;
|
|
692
|
+
if (vigente)
|
|
693
|
+
await salida(ctx, ` ${lectura}`);
|
|
694
|
+
else if (estado.fecha !== undefined)
|
|
695
|
+
await salida(ctx, ` Última lectura caducada (${fechaCuota(estado.fecha, ahora)}): ${lectura}`);
|
|
696
|
+
}
|
|
697
|
+
if (ia === 'antigravity' && !vigente)
|
|
698
|
+
await salida(ctx, ' La cuota se actualiza al usar la barra de agy.');
|
|
699
|
+
}
|
|
700
|
+
return 0;
|
|
701
|
+
}
|
|
702
|
+
/** Ejecuta las órdenes de la fábrica y devuelve su código de salida. */
|
|
642
703
|
export async function ejecutarCli(argv, io, opciones = {}) {
|
|
643
704
|
const ctx = {
|
|
644
705
|
io,
|
|
@@ -683,10 +744,12 @@ export async function ejecutarCli(argv, io, opciones = {}) {
|
|
|
683
744
|
valores = analizado.values;
|
|
684
745
|
}
|
|
685
746
|
catch (error) {
|
|
686
|
-
throw error instanceof ErrorUso ? error : new ErrorUso(`Argumentos no válidos para «${primera === 'encargar' ? '' : 'fabrica '}${orden}»`);
|
|
747
|
+
throw error instanceof ErrorUso ? error : new ErrorUso(`Argumentos no válidos para «${primera === 'encargar' || primera === 'cuotas' ? '' : 'fabrica '}${orden}»`);
|
|
687
748
|
}
|
|
688
749
|
const json = valores['json'] === true;
|
|
689
750
|
switch (orden) {
|
|
751
|
+
case 'cuotas':
|
|
752
|
+
return await ordenCuotas(ctx, json);
|
|
690
753
|
case 'preferencias':
|
|
691
754
|
return await ordenPreferencias(ctx, valores['criterio'], valores['revision-cruzada'], json);
|
|
692
755
|
case 'proponer':
|
|
@@ -27,6 +27,7 @@ import { promisify } from 'node:util';
|
|
|
27
27
|
import { resolveCliInvocation } from '../../../src/cli-executable.js';
|
|
28
28
|
import { hallazgosJsonSchema, InformeEstacion } from '../esquemas.js';
|
|
29
29
|
import { ClienteJsonRpc, ErrorProceso } from '../jsonrpc.js';
|
|
30
|
+
import { guardarVentanasCodex, TOPE_CUOTA_MS } from '../cuotas.js';
|
|
30
31
|
import { nombreSeguro } from './tipos.js';
|
|
31
32
|
const NO_INSTALADO = 'Codex no está instalado';
|
|
32
33
|
/** En modo escritura el turno no pide hallazgos: pide solo un resumen breve de lo hecho. */
|
|
@@ -70,6 +71,36 @@ const FUNCIONES_DESACTIVADAS = [
|
|
|
70
71
|
'multi_agent',
|
|
71
72
|
'image_generation',
|
|
72
73
|
];
|
|
74
|
+
/** Campos de RateLimitSnapshot usados por la fábrica. `resetsAt` viene en segundos Unix. */
|
|
75
|
+
function ventanasDeCuota(respuesta) {
|
|
76
|
+
if (!esObjeto(respuesta))
|
|
77
|
+
return {};
|
|
78
|
+
const porId = respuesta['rateLimitsByLimitId'];
|
|
79
|
+
const limites = (esObjeto(porId) ? porId['codex'] : undefined) ?? respuesta['rateLimits'];
|
|
80
|
+
if (!esObjeto(limites))
|
|
81
|
+
return {};
|
|
82
|
+
const id = limites['limitId'];
|
|
83
|
+
if (id !== undefined && id !== null && id !== 'codex')
|
|
84
|
+
return {};
|
|
85
|
+
const ventanas = {};
|
|
86
|
+
for (const [campo, duracion] of [['primary', 300], ['secondary', 10_080]]) {
|
|
87
|
+
const ventana = limites[campo];
|
|
88
|
+
if (!esObjeto(ventana))
|
|
89
|
+
continue;
|
|
90
|
+
const minutos = ventana['windowDurationMins'] ?? duracion;
|
|
91
|
+
const clave = minutos === 300 ? 'cincoHoras' : minutos === 10_080 ? 'semanal' : undefined;
|
|
92
|
+
const usado = ventana['usedPercent'];
|
|
93
|
+
if (clave === undefined || typeof usado !== 'number' || !Number.isFinite(usado) || usado < 0)
|
|
94
|
+
continue;
|
|
95
|
+
const segundos = ventana['resetsAt'];
|
|
96
|
+
const reinicio = typeof segundos === 'number' ? new Date(segundos * 1000) : null;
|
|
97
|
+
ventanas[clave] = {
|
|
98
|
+
porcentajeUsado: Math.min(usado, 100),
|
|
99
|
+
...(reinicio !== null && Number.isFinite(reinicio.getTime()) ? { reinicio: reinicio.toISOString() } : {}),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
return ventanas;
|
|
103
|
+
}
|
|
73
104
|
class ErrorNoInstalado extends Error {
|
|
74
105
|
constructor() {
|
|
75
106
|
super(NO_INSTALADO);
|
|
@@ -460,6 +491,7 @@ function esperarAborto(señal) {
|
|
|
460
491
|
return { promesa, quitar };
|
|
461
492
|
}
|
|
462
493
|
class ConectorCodex {
|
|
494
|
+
guardadoCuota = Promise.resolve();
|
|
463
495
|
ia = 'codex';
|
|
464
496
|
opciones;
|
|
465
497
|
proceso;
|
|
@@ -531,6 +563,33 @@ class ConectorCodex {
|
|
|
531
563
|
}
|
|
532
564
|
return modelos;
|
|
533
565
|
}
|
|
566
|
+
async consultarCuota(topeMs = TOPE_CUOTA_MS) {
|
|
567
|
+
const limite = performance.now() + topeMs;
|
|
568
|
+
let reloj;
|
|
569
|
+
const consulta = async () => {
|
|
570
|
+
const cliente = await this.asegurarCliente();
|
|
571
|
+
const restante = limite - performance.now();
|
|
572
|
+
if (restante <= 0)
|
|
573
|
+
return undefined;
|
|
574
|
+
const respuesta = await cliente.solicitar('account/rateLimits/read', undefined, { timeoutMs: restante });
|
|
575
|
+
const ventanas = ventanasDeCuota(respuesta);
|
|
576
|
+
await this.guardarCuota(ventanas, 'consulta');
|
|
577
|
+
return ventanas;
|
|
578
|
+
};
|
|
579
|
+
try {
|
|
580
|
+
return await Promise.race([
|
|
581
|
+
consulta().catch(() => undefined),
|
|
582
|
+
new Promise((resolver) => { reloj = setTimeout(() => resolver(undefined), topeMs); }),
|
|
583
|
+
]);
|
|
584
|
+
}
|
|
585
|
+
finally {
|
|
586
|
+
clearTimeout(reloj);
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
guardarCuota(ventanas, fuente) {
|
|
590
|
+
this.guardadoCuota = this.guardadoCuota.then(() => guardarVentanasCodex(this.opciones.home ?? os.homedir(), ventanas, fuente));
|
|
591
|
+
return this.guardadoCuota;
|
|
592
|
+
}
|
|
534
593
|
async ejecutar(encargo, señal, alProgreso) {
|
|
535
594
|
const resultado = { estado: 'fallida', crudo: '', modeloInformado: null, tokens: null, denegaciones: [] };
|
|
536
595
|
const cancelada = () => ({ ...resultado, estado: 'cancelada', motivo: CANCELADA });
|
|
@@ -623,7 +682,9 @@ class ConectorCodex {
|
|
|
623
682
|
return cancelada();
|
|
624
683
|
}
|
|
625
684
|
if (desenlace.tipo === 'muerto') {
|
|
626
|
-
|
|
685
|
+
const stderr = cliente.salidaError.trim();
|
|
686
|
+
const detalle = stderr ? `${desenlace.motivo}. Salida de error: ${stderr}` : desenlace.motivo;
|
|
687
|
+
return { ...resultado, motivo: `El proceso de Codex terminó antes de acabar la revisión: ${detalle}` };
|
|
627
688
|
}
|
|
628
689
|
return this.cerrarTurno(resultado, desenlace.fin, señal);
|
|
629
690
|
}
|
|
@@ -643,6 +704,7 @@ class ConectorCodex {
|
|
|
643
704
|
aborto.quitar();
|
|
644
705
|
if (threadId !== null)
|
|
645
706
|
this.hilos.delete(threadId);
|
|
707
|
+
await this.guardadoCuota;
|
|
646
708
|
}
|
|
647
709
|
}
|
|
648
710
|
async cerrar() {
|
|
@@ -655,6 +717,7 @@ class ConectorCodex {
|
|
|
655
717
|
}
|
|
656
718
|
finally {
|
|
657
719
|
await this.borrarHomeAislado();
|
|
720
|
+
await this.guardadoCuota;
|
|
658
721
|
}
|
|
659
722
|
}
|
|
660
723
|
/** Los borrados se encadenan: quien llama espera también al que ya estaba en marcha. */
|
|
@@ -828,6 +891,10 @@ class ConectorCodex {
|
|
|
828
891
|
alNotificar(metodo, params) {
|
|
829
892
|
if (!esObjeto(params))
|
|
830
893
|
return;
|
|
894
|
+
if (metodo === 'account/rateLimits/updated') {
|
|
895
|
+
void this.guardarCuota(ventanasDeCuota(params), 'notificación');
|
|
896
|
+
return;
|
|
897
|
+
}
|
|
831
898
|
const enCurso = this.enCursoDe(params);
|
|
832
899
|
if (!enCurso)
|
|
833
900
|
return;
|
|
@@ -0,0 +1,299 @@
|
|
|
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
|
+
const HORA_MS = 60 * 60 * 1000;
|
|
9
|
+
const CADUCIDAD_BARRA_MS = 6 * HORA_MS;
|
|
10
|
+
const ARCHIVO = 'cuotas.json';
|
|
11
|
+
const CADUCIDAD_CANDADO_MS = 10_000;
|
|
12
|
+
const ESPERA_CANDADO_MS = 2_000;
|
|
13
|
+
const UMBRAL_AGOTADA = 95;
|
|
14
|
+
export const UMBRAL_CUOTA_BAJA = 80;
|
|
15
|
+
export const TOPE_CUOTA_MS = 5_000;
|
|
16
|
+
const fecha = z.iso.datetime();
|
|
17
|
+
const porcentaje = z.number().min(0).max(100);
|
|
18
|
+
const Ventana = z.object({ porcentajeUsado: porcentaje, reinicio: fecha.optional(), fecha: fecha.optional() });
|
|
19
|
+
const Ventanas = z.object({ cincoHoras: Ventana.optional(), semanal: Ventana.optional() });
|
|
20
|
+
const Bloqueo = z.object({ hasta: fecha, motivo: z.string(), fecha });
|
|
21
|
+
const Estado = Ventana.partial().extend({
|
|
22
|
+
ventanas: Ventanas.optional(),
|
|
23
|
+
porcentajeMinimoUsado: porcentaje.optional(),
|
|
24
|
+
bloqueo: Bloqueo.optional(),
|
|
25
|
+
fuente: z.enum(['consulta', 'notificación', 'barra']).optional(),
|
|
26
|
+
});
|
|
27
|
+
const EstadoEnDisco = Estado.extend({
|
|
28
|
+
agotadaHasta: fecha.optional(),
|
|
29
|
+
fuente: z.enum(['consulta', 'notificación', 'barra', 'error']).optional(),
|
|
30
|
+
});
|
|
31
|
+
export const NOMBRES_VENTANA = { cincoHoras: '5 h', semanal: 'semanal' };
|
|
32
|
+
export const CLAVES_VENTANA = ['cincoHoras', 'semanal'];
|
|
33
|
+
export function leerCuotas(home) {
|
|
34
|
+
try {
|
|
35
|
+
const nexakit = path.join(home, '.nexakit');
|
|
36
|
+
const base = path.join(nexakit, 'fabrica');
|
|
37
|
+
if (![nexakit, base].every((ruta) => lstatSync(ruta, { throwIfNoEntry: false })?.isDirectory()))
|
|
38
|
+
return {};
|
|
39
|
+
const ruta = path.join(base, ARCHIVO);
|
|
40
|
+
if (!lstatSync(ruta, { throwIfNoEntry: false })?.isFile())
|
|
41
|
+
return {};
|
|
42
|
+
const fd = openSync(ruta, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
43
|
+
try {
|
|
44
|
+
const info = fstatSync(fd);
|
|
45
|
+
if (!info.isFile() || info.size > 16_384)
|
|
46
|
+
return {};
|
|
47
|
+
const valor = JSON.parse(readFileSync(fd, 'utf8'));
|
|
48
|
+
const cuotas = z.object({ codex: z.unknown().optional(), antigravity: z.unknown().optional() }).safeParse(valor);
|
|
49
|
+
if (!cuotas.success)
|
|
50
|
+
return {};
|
|
51
|
+
const datos = {};
|
|
52
|
+
for (const ia of IAExterna.options) {
|
|
53
|
+
const guardado = EstadoEnDisco.safeParse(cuotas.data[ia]);
|
|
54
|
+
if (!guardado.success)
|
|
55
|
+
continue;
|
|
56
|
+
const { agotadaHasta, fuente, fecha: medida, ...estado } = guardado.data;
|
|
57
|
+
const tieneMedicion = estado.ventanas !== undefined || estado.porcentajeUsado !== undefined;
|
|
58
|
+
const fuentePredeterminada = ia === 'codex' ? 'consulta' : 'barra';
|
|
59
|
+
const fuenteMedicion = fuente === 'error' ? (tieneMedicion ? fuentePredeterminada : undefined) : fuente;
|
|
60
|
+
const bloqueo = estado.bloqueo ?? (agotadaHasta === undefined ? undefined : {
|
|
61
|
+
hasta: agotadaHasta, motivo: 'Límite informado por el proveedor', fecha: medida ?? agotadaHasta,
|
|
62
|
+
});
|
|
63
|
+
datos[ia] = {
|
|
64
|
+
...estado,
|
|
65
|
+
...(fuenteMedicion === undefined ? {} : { fuente: fuenteMedicion }),
|
|
66
|
+
...(medida === undefined || fuenteMedicion === undefined ? {} : { fecha: medida }),
|
|
67
|
+
...(bloqueo === undefined ? {} : { bloqueo }),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
return datos;
|
|
71
|
+
}
|
|
72
|
+
finally {
|
|
73
|
+
closeSync(fd);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
return {};
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/** Las consultas de la CLI y las notificaciones de otros procesos pueden coincidir. */
|
|
81
|
+
async function actualizar(home, ia, cambiar) {
|
|
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())
|
|
95
|
+
throw new ErrorCandadoOcupado('El candado de cuotas caducó');
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
finally {
|
|
99
|
+
await propio.liberar();
|
|
100
|
+
}
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
catch (error) {
|
|
104
|
+
if (!(error instanceof ErrorCandadoOcupado))
|
|
105
|
+
throw error;
|
|
106
|
+
const restante = limite - performance.now();
|
|
107
|
+
if (restante <= 0)
|
|
108
|
+
return;
|
|
109
|
+
await esperar(Math.min(20, restante));
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
// La cuota es informativa si el estado local no se puede guardar.
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
export async function guardarVentanasCodex(home, ventanas, fuente) {
|
|
118
|
+
if (!CLAVES_VENTANA.some((clave) => ventanas[clave] !== undefined))
|
|
119
|
+
return;
|
|
120
|
+
const ahora = Date.now();
|
|
121
|
+
await actualizar(home, 'codex', (anterior) => {
|
|
122
|
+
const fusionadas = { ...ventanas };
|
|
123
|
+
if (fuente === 'notificación') {
|
|
124
|
+
for (const clave of CLAVES_VENTANA) {
|
|
125
|
+
const previa = anterior?.ventanas?.[clave];
|
|
126
|
+
if (fusionadas[clave] === undefined && previa !== undefined) {
|
|
127
|
+
// Si no hay reinicio conocido, la vigencia depende de cuándo se recibió esta ventana.
|
|
128
|
+
fusionadas[clave] = previa.reinicio === undefined ? { ...previa, fecha: previa.fecha ?? anterior?.fecha } : previa;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
const medidas = Object.values(fusionadas).filter((v) => v !== undefined);
|
|
133
|
+
const mayor = medidas.sort((a, b) => b.porcentajeUsado - a.porcentajeUsado)[0];
|
|
134
|
+
const bloqueo = medidas.some((v) => v.porcentajeUsado >= UMBRAL_AGOTADA) ? bloqueoVigente(anterior, ahora) : undefined;
|
|
135
|
+
return {
|
|
136
|
+
porcentajeUsado: mayor?.porcentajeUsado,
|
|
137
|
+
reinicio: mayor?.reinicio,
|
|
138
|
+
ventanas: fusionadas,
|
|
139
|
+
fuente,
|
|
140
|
+
fecha: new Date(ahora).toISOString(),
|
|
141
|
+
bloqueo,
|
|
142
|
+
};
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
export async function guardarCuotaAntigravity(home, cuota, ahora = Date.now()) {
|
|
146
|
+
if (!Number.isFinite(cuota.porcentajeUsado))
|
|
147
|
+
return;
|
|
148
|
+
const porcentajeUsado = Math.min(100, Math.max(0, Math.round(cuota.porcentajeUsado)));
|
|
149
|
+
const minimo = cuota.porcentajeMinimoUsado;
|
|
150
|
+
const porcentajeMinimoUsado = minimo !== undefined && Number.isFinite(minimo)
|
|
151
|
+
? Math.min(Math.max(0, cuota.porcentajeUsado), Math.max(0, minimo), 100)
|
|
152
|
+
: undefined;
|
|
153
|
+
const reinicioMs = typeof cuota.reinicio === 'string' ? Date.parse(cuota.reinicio) : Number.NaN;
|
|
154
|
+
const reinicio = Number.isFinite(reinicioMs) ? new Date(reinicioMs).toISOString() : undefined;
|
|
155
|
+
await actualizar(home, 'antigravity', (anterior) => ({
|
|
156
|
+
porcentajeUsado,
|
|
157
|
+
porcentajeMinimoUsado,
|
|
158
|
+
reinicio,
|
|
159
|
+
fuente: 'barra',
|
|
160
|
+
fecha: new Date(ahora).toISOString(),
|
|
161
|
+
bloqueo: bloqueoVigente(anterior, ahora),
|
|
162
|
+
}));
|
|
163
|
+
}
|
|
164
|
+
const vigente = (hasta, ahora) => Date.parse(hasta ?? '') > ahora;
|
|
165
|
+
const enUnaHora = (ahora) => new Date(ahora + HORA_MS).toISOString();
|
|
166
|
+
export function bloqueoVigente(estado, ahora = Date.now()) {
|
|
167
|
+
return vigente(estado?.bloqueo?.hasta, ahora) ? estado?.bloqueo : undefined;
|
|
168
|
+
}
|
|
169
|
+
function limiteMedicion(estado, ventana, ahora) {
|
|
170
|
+
const medida = Date.parse(ventana.fecha ?? estado.fecha ?? '');
|
|
171
|
+
if (!Number.isFinite(medida) || ventana.porcentajeUsado === undefined)
|
|
172
|
+
return undefined;
|
|
173
|
+
const duracion = estado.fuente === 'barra' ? CADUCIDAD_BARRA_MS : HORA_MS;
|
|
174
|
+
if (estado.fuente === 'barra' && ahora - medida >= duracion)
|
|
175
|
+
return undefined;
|
|
176
|
+
const hasta = ventana.reinicio ?? new Date(medida + duracion).toISOString();
|
|
177
|
+
return vigente(hasta, ahora) ? hasta : undefined;
|
|
178
|
+
}
|
|
179
|
+
export function ventanasCuota(estado, ahora) {
|
|
180
|
+
const ventanas = estado?.ventanas;
|
|
181
|
+
if (estado === undefined || ventanas === undefined)
|
|
182
|
+
return undefined;
|
|
183
|
+
const resultado = {};
|
|
184
|
+
for (const clave of CLAVES_VENTANA) {
|
|
185
|
+
const ventana = ventanas[clave];
|
|
186
|
+
if (ventana !== undefined)
|
|
187
|
+
resultado[clave] = { ...ventana, vigente: limiteMedicion(estado, ventana, ahora) !== undefined };
|
|
188
|
+
}
|
|
189
|
+
return resultado;
|
|
190
|
+
}
|
|
191
|
+
/** Devuelve el límite de uso efectivo de las ventanas que todavía siguen abiertas. */
|
|
192
|
+
export function estadoCuota(estado, ahora = Date.now()) {
|
|
193
|
+
if (estado === undefined)
|
|
194
|
+
return {};
|
|
195
|
+
const ventanas = estado.ventanas === undefined
|
|
196
|
+
? [[undefined, estado]]
|
|
197
|
+
: CLAVES_VENTANA.map((clave) => [clave, estado.ventanas?.[clave]]);
|
|
198
|
+
const efectivo = {};
|
|
199
|
+
const bloqueo = bloqueoVigente(estado, ahora);
|
|
200
|
+
if (bloqueo !== undefined)
|
|
201
|
+
efectivo.agotadaHasta = bloqueo.hasta;
|
|
202
|
+
for (const [clave, ventana] of ventanas) {
|
|
203
|
+
if (ventana?.porcentajeUsado === undefined)
|
|
204
|
+
continue;
|
|
205
|
+
const hasta = limiteMedicion(estado, ventana, ahora);
|
|
206
|
+
if (hasta === undefined)
|
|
207
|
+
continue;
|
|
208
|
+
if (efectivo.porcentajeUsado === undefined || ventana.porcentajeUsado > efectivo.porcentajeUsado) {
|
|
209
|
+
efectivo.porcentajeUsado = ventana.porcentajeUsado;
|
|
210
|
+
if (ventana.reinicio === undefined)
|
|
211
|
+
delete efectivo.reinicio;
|
|
212
|
+
else
|
|
213
|
+
efectivo.reinicio = ventana.reinicio;
|
|
214
|
+
}
|
|
215
|
+
const umbral = estado.fuente === 'barra' ? estado.porcentajeMinimoUsado : ventana.porcentajeUsado;
|
|
216
|
+
if (umbral !== undefined && umbral >= UMBRAL_AGOTADA &&
|
|
217
|
+
(efectivo.agotadaHasta === undefined || Date.parse(hasta) >= Date.parse(efectivo.agotadaHasta))) {
|
|
218
|
+
efectivo.agotadaHasta = hasta;
|
|
219
|
+
if (clave !== undefined)
|
|
220
|
+
efectivo.ventanaAgotada = clave;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
return efectivo;
|
|
224
|
+
}
|
|
225
|
+
export function fechaCuota(fecha, ahora = Date.now()) {
|
|
226
|
+
const dia = new Date(fecha);
|
|
227
|
+
const hoy = new Date(ahora);
|
|
228
|
+
const mañana = new Date(ahora);
|
|
229
|
+
mañana.setDate(mañana.getDate() + 1);
|
|
230
|
+
const etiqueta = dia.toDateString() === hoy.toDateString() ? 'hoy'
|
|
231
|
+
: dia.toDateString() === mañana.toDateString() ? 'mañana' : `${dia.getDate()}/${dia.getMonth() + 1}`;
|
|
232
|
+
return `${etiqueta} ${dia.toLocaleTimeString('es', { hour: '2-digit', minute: '2-digit', hourCycle: 'h23' })}`;
|
|
233
|
+
}
|
|
234
|
+
export const nombreCuota = (ia) => ia === 'codex' ? 'Codex' : 'Antigravity';
|
|
235
|
+
export const sinCuota = (ia, hasta, ventana, ahora) => `${nombreCuota(ia)} sin cuota hasta ${fechaCuota(hasta, ahora)}${ventana === undefined ? '' : ` (ventana ${NOMBRES_VENTANA[ventana]})`}`;
|
|
236
|
+
export const pocaCuota = (ia, porcentaje, reinicio, ahora) => `${nombreCuota(ia)} tiene poca cuota (${porcentaje} % usado${reinicio === undefined ? '' : `, reinicio ${fechaCuota(reinicio, ahora)}`})`;
|
|
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
|
+
function fechaReintento(linea, ahora) {
|
|
245
|
+
const grupos = REINTENTO.exec(linea)?.groups;
|
|
246
|
+
if (grupos === undefined)
|
|
247
|
+
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))
|
|
252
|
+
return undefined;
|
|
253
|
+
const reinicio = new Date(ahora);
|
|
254
|
+
reinicio.setHours(periodo === undefined ? h : h % 12 + (periodo.toLowerCase() === 'pm' ? 12 : 0), m, 0, 0);
|
|
255
|
+
if (mes === undefined) {
|
|
256
|
+
if (reinicio.getTime() <= ahora)
|
|
257
|
+
reinicio.setDate(reinicio.getDate() + 1);
|
|
258
|
+
return reinicio.toISOString();
|
|
259
|
+
}
|
|
260
|
+
const nombre = mes.toLowerCase();
|
|
261
|
+
const indice = MESES.findIndex((mes) => mes === nombre || mes.slice(0, 3) === nombre);
|
|
262
|
+
if (indice === -1)
|
|
263
|
+
return undefined;
|
|
264
|
+
const diaDelMes = Number(dia);
|
|
265
|
+
reinicio.setFullYear(año === undefined ? reinicio.getFullYear() : Number(año), indice, diaDelMes);
|
|
266
|
+
if (año === undefined && reinicio.getTime() <= ahora) {
|
|
267
|
+
reinicio.setFullYear(reinicio.getFullYear() + 1, indice, diaDelMes);
|
|
268
|
+
}
|
|
269
|
+
return reinicio.getMonth() === indice && reinicio.getDate() === diaDelMes && reinicio.getTime() > ahora
|
|
270
|
+
? reinicio.toISOString() : undefined;
|
|
271
|
+
}
|
|
272
|
+
/** Interpreta la hora local del proveedor. Una hora anterior se refiere al día siguiente. */
|
|
273
|
+
export function detectarAgotamiento(motivo, ahora = Date.now()) {
|
|
274
|
+
const lineas = motivo.slice(-8192).split(/\r?\n|(?<=\. )(?=Salida de error:)/iu);
|
|
275
|
+
for (let linea of lineas) {
|
|
276
|
+
linea = linea.trim();
|
|
277
|
+
while (PREFIJO.test(linea))
|
|
278
|
+
linea = linea.replace(PREFIJO, '');
|
|
279
|
+
if (!LIMITE.test(linea) && !LIMITE_BREVE.test(linea))
|
|
280
|
+
continue;
|
|
281
|
+
return fechaReintento(linea, ahora) ??
|
|
282
|
+
(TRANSITORIO.test(linea) ? new Date(ahora + 10 * 60_000).toISOString() : enUnaHora(ahora));
|
|
283
|
+
}
|
|
284
|
+
return undefined;
|
|
285
|
+
}
|
|
286
|
+
export async function registrarFalloDeCuota(home, ia, motivo) {
|
|
287
|
+
const ahora = Date.now();
|
|
288
|
+
if (motivo === undefined)
|
|
289
|
+
return;
|
|
290
|
+
const hasta = detectarAgotamiento(motivo, ahora);
|
|
291
|
+
if (hasta === undefined)
|
|
292
|
+
return;
|
|
293
|
+
await actualizar(home, ia, (anterior) => ({
|
|
294
|
+
...anterior,
|
|
295
|
+
bloqueo: bloqueoVigente(anterior, Date.parse(hasta)) ?? {
|
|
296
|
+
hasta, motivo: motivo.trim().slice(-1024), fecha: new Date(ahora).toISOString(),
|
|
297
|
+
},
|
|
298
|
+
}));
|
|
299
|
+
}
|
package/dist/fabrica/ejecutor.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createHash, randomBytes } from 'node:crypto';
|
|
2
2
|
import os from 'node:os';
|
|
3
|
+
import { registrarFalloDeCuota } from './cuotas.js';
|
|
3
4
|
import { leerDiff } from './diff.js';
|
|
4
5
|
import { clasificarCambios, instantanea } from './disco.js';
|
|
5
6
|
import { calcularCoste, comprobarHuella, descarte } from './enrutador.js';
|
|
@@ -348,6 +349,8 @@ async function correrConPlaza(ej, trabajo, timeoutMs, graciaMs) {
|
|
|
348
349
|
final = { ...resultado, estado: 'cancelada', motivo: CANCELADA };
|
|
349
350
|
else
|
|
350
351
|
final = resultado;
|
|
352
|
+
if (final.estado === 'fallida' && trabajo.ia !== 'claude')
|
|
353
|
+
await registrarFalloDeCuota(ej.home, trabajo.ia, final.motivo);
|
|
351
354
|
// Primero el archivo de la estación, para que un estado terminado siempre tenga su resultado.
|
|
352
355
|
try {
|
|
353
356
|
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 { clasificarCambios, instantanea } from '../disco.js';
|
|
10
11
|
import { descarte } from '../enrutador.js';
|
|
11
12
|
import { AGOTADO, avisoIgnorados, bloqueLecciones, conGracia, conTope, GRACIA_MS, INTERVALO_ACTIVO_MS, TOPE_CATALOGO_MS } from '../ejecutor.js';
|
|
@@ -390,6 +391,10 @@ export async function ejecutarEncargo(opciones) {
|
|
|
390
391
|
b.avisos.push(`No se usa el modelo normal de ${quien}: ${texto}`);
|
|
391
392
|
}
|
|
392
393
|
const { ia: iaElegida, conector, modelo, esfuerzo } = elegida;
|
|
394
|
+
const { porcentajeUsado, reinicio } = estadoCuota(leerCuotas(home)[iaElegida]);
|
|
395
|
+
if (porcentajeUsado !== undefined && porcentajeUsado >= UMBRAL_CUOTA_BAJA) {
|
|
396
|
+
b.avisos.push(pocaCuota(iaElegida, porcentajeUsado, reinicio));
|
|
397
|
+
}
|
|
393
398
|
b.ia = iaElegida;
|
|
394
399
|
b.modelo = modelo;
|
|
395
400
|
b.esfuerzo = esfuerzo;
|
|
@@ -499,6 +504,7 @@ export async function ejecutarEncargo(opciones) {
|
|
|
499
504
|
else if (resultado.estado === 'fallida') {
|
|
500
505
|
b.estado = 'fallido';
|
|
501
506
|
b.motivo = limpiar(resultado.motivo ?? 'la IA no completó el encargo');
|
|
507
|
+
await registrarFalloDeCuota(home, elegida.ia, resultado.motivo);
|
|
502
508
|
}
|
|
503
509
|
else {
|
|
504
510
|
b.estado = 'ok';
|
|
@@ -631,17 +637,26 @@ export async function ejecutarEncargo(opciones) {
|
|
|
631
637
|
/** Abre el conector, valida el modelo normal y reúne las alternativas compatibles con el esfuerzo. */
|
|
632
638
|
async function preparar(quien, ordenes, reunirCandidatos) {
|
|
633
639
|
const sinModelo = (motivo) => ({ candidatos: [], motivo });
|
|
640
|
+
const previa = leerCuotas(home)[quien];
|
|
641
|
+
const agotada = estadoCuota(previa);
|
|
642
|
+
const aviso = agotada.agotadaHasta === undefined ? undefined : sinCuota(quien, agotada.agotadaHasta, agotada.ventanaAgotada);
|
|
643
|
+
if (aviso !== undefined && (quien !== 'codex' || bloqueoVigente(previa) === undefined))
|
|
644
|
+
return sinModelo(aviso);
|
|
634
645
|
const fabrica = fabricas[quien];
|
|
635
646
|
if (fabrica === undefined)
|
|
636
|
-
return sinModelo(`${quien} no está disponible`);
|
|
647
|
+
return sinModelo(aviso ?? `${quien} no está disponible`);
|
|
637
648
|
let conector;
|
|
638
649
|
try {
|
|
639
650
|
conector = await fabrica({ raiz: w.dir, ordenesPermitidas: ordenes, ...(tmpCreado ? { tmp } : {}) });
|
|
640
651
|
}
|
|
641
652
|
catch (error) {
|
|
642
|
-
return sinModelo(`${quien} no está disponible: ${datosDe(error)}`);
|
|
653
|
+
return sinModelo(aviso ?? `${quien} no está disponible: ${datosDe(error)}`);
|
|
643
654
|
}
|
|
644
655
|
abiertos[quien] = conector;
|
|
656
|
+
await conector.consultarCuota?.().catch(() => undefined);
|
|
657
|
+
const { agotadaHasta, ventanaAgotada } = estadoCuota(leerCuotas(home)[quien]);
|
|
658
|
+
if (agotadaHasta !== undefined)
|
|
659
|
+
return sinModelo(sinCuota(quien, agotadaHasta, ventanaAgotada));
|
|
645
660
|
let catalogo;
|
|
646
661
|
try {
|
|
647
662
|
catalogo = await conTope(Promise.resolve().then(() => conector.catalogo()), topeCatalogoMs);
|