nexakit 0.2.0 → 0.4.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 +10 -5
- package/README.md +20 -4
- package/assets/runtime/package-lock.json +2 -2
- package/catalogs/generadores.json +936 -0
- package/package.json +1 -1
- package/plugins/nexakit-ahorro/.claude-plugin/plugin.json +1 -0
- package/plugins/nexakit-ahorro/README.md +13 -0
- package/plugins/nexakit-ahorro/hooks/compactar.js +39 -0
- package/plugins/nexakit-ahorro/hooks/hooks.json +1 -0
- package/plugins/nexakit-ahorro/hooks/register.js +32 -0
- package/plugins/nexakit-lecciones/.claude-plugin/plugin.json +1 -0
- package/plugins/nexakit-lecciones/README.md +19 -0
- package/plugins/nexakit-lecciones/hooks/hooks.json +1 -0
- package/plugins/nexakit-lecciones/hooks/lecciones.js +39 -0
- package/plugins/nexakit-lecciones/hooks/register.js +61 -0
- package/plugins/nexakit-modelo/.claude-plugin/plugin.json +1 -1
- package/plugins/nexakit-modelo/hooks/barra.js +72 -0
- package/plugins/nexakit-modelo/hooks/recomendar.js +27 -0
- package/plugins/nexakit-modelo/hooks/register.js +73 -17
- package/plugins/nexakit-modelo/hooks/umbrales.js +3 -0
- package/plugins/nexakit-modelo/tests/register.test.ts +1 -1
- package/plugins/nexakit-sesion/.claude-plugin/plugin.json +1 -1
- package/plugins/nexakit-sesion/README.md +3 -3
- package/plugins/nexakit-sesion/hooks/aviso.js +28 -11
- package/plugins/nexakit-sesion/hooks/register.js +30 -2
- package/plugins/nexakit-sesion/tests/register.test.ts +3 -16
- package/plugins/niveles/agents/nivel-alto.md +3 -3
- package/plugins/niveles/agents/nivel-exigente.md +3 -3
- package/plugins/niveles/agents/nivel-ligero.md +3 -3
- package/plugins/niveles/agents/nivel-normal.md +3 -3
- package/schemas/generators.schema.json +299 -0
- package/skills/quality-gate/SKILL.md +1 -1
- package/skills/revisar/SKILL.md +46 -6
- package/src/clean-command.js +29 -0
- package/src/clean-project-flow.js +105 -0
- package/src/clean-project.js +431 -0
- package/src/cli-executable.js +1 -1
- package/src/gemini-files.js +3 -3
- package/src/gemini-tools.js +23 -8
- package/src/generators-catalog.js +63 -0
- package/src/level-agents.js +4 -3
- package/src/project-root.js +21 -2
- package/src/project-signals.js +6 -0
- package/src/redact.js +9 -0
- package/src/review-instructions.js +18 -29
- package/src/setup-state.js +7 -0
- package/src/setup-tui.js +98 -6
- package/src/skill-recommendations.js +25 -2
- package/src/toolkit-cli.js +0 -4
- package/src/toolkit-commands-guide.js +1 -1
- package/src/toolkit-setup.js +2 -2
- package/plugins/nexakit-modelo/hooks/status.js +0 -8
- package/plugins/nexakit-panel/.claude-plugin/plugin.json +0 -1
- package/plugins/nexakit-panel/README.md +0 -20
- package/plugins/nexakit-panel/hooks/hooks.json +0 -1
- package/plugins/nexakit-panel/hooks/lienzo.js +0 -382
- package/plugins/nexakit-panel/hooks/panel.js +0 -279
- package/plugins/nexakit-panel/hooks/register.tsx +0 -248
- package/plugins/nexakit-panel/tests/lienzo.test.ts +0 -142
- package/plugins/nexakit-panel/tests/panel.test.ts +0 -240
- package/plugins/nexakit-panel/tests/register.test.ts +0 -167
- package/plugins/nexakit-panel/types/index.d.ts +0 -41
- package/skills/revision-cruzada/SKILL.md +0 -59
- package/src/panel-cli.js +0 -182
package/package.json
CHANGED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"name": "nexakit-ahorro", "version": "0.1.0", "description": "Recorta la salida larga de los comandos antes de que entre al contexto y guarda la completa en ~/.nexakit/salidas.", "license": "MIT"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# nexakit-ahorro
|
|
2
|
+
|
|
3
|
+
Cada línea que devuelve un comando entra al contexto y se vuelve a pagar en todos los turnos siguientes. Este
|
|
4
|
+
mod recorta la salida de Bash que pasa de 120 líneas o 12 000 caracteres: conserva las 20 primeras, las 40
|
|
5
|
+
últimas y hasta 40 líneas con señales de fallo (`error`, `fail`, `not ok`, `✖`…), quita los códigos de color y
|
|
6
|
+
acorta las líneas gigantes. La salida completa queda en `~/.nexakit/salidas/` y el aviso dice la ruta.
|
|
7
|
+
|
|
8
|
+
Para ver una salida entera, pon `NEXAKIT_SALIDA=completa` delante del comando. Los comandos en segundo plano y
|
|
9
|
+
las imágenes no se tocan.
|
|
10
|
+
|
|
11
|
+
## Pruebas
|
|
12
|
+
|
|
13
|
+
`node --test test/ahorro-salida.test.js` desde la raíz del repositorio.
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// Recorta la salida larga de un comando antes de que entre al contexto: cada línea que entra se vuelve a pagar
|
|
2
|
+
// en todos los turnos siguientes. Conserva el principio, el final y las líneas que delatan un fallo.
|
|
3
|
+
|
|
4
|
+
export const LIMITE_LINEAS = 120;
|
|
5
|
+
const LIMITE_CARACTERES = 12000;
|
|
6
|
+
const CABEZA = 20;
|
|
7
|
+
const COLA = 40;
|
|
8
|
+
const MAX_FALLOS = 40;
|
|
9
|
+
const MAX_LINEA = 400;
|
|
10
|
+
const ANSI = /\u001b\[[0-9;?]*[ -/]*[@-~]/gu;
|
|
11
|
+
const FALLO = /(error|fail|falla|✖|✗|not ok|exception|traceback|panic|assert|warn|denied|refused|cannot|no se pudo)/iu;
|
|
12
|
+
|
|
13
|
+
const recortarLinea = (l) => (l.length > MAX_LINEA ? `${l.slice(0, MAX_LINEA)} … (${l.length - MAX_LINEA} caracteres más)` : l);
|
|
14
|
+
|
|
15
|
+
export function compactarSalida(texto, { ruta } = {}) {
|
|
16
|
+
const limpio = String(texto ?? '').replace(ANSI, '');
|
|
17
|
+
const todas = limpio.split('\n');
|
|
18
|
+
if (todas.length <= LIMITE_LINEAS && limpio.length <= LIMITE_CARACTERES) return { texto: String(texto ?? ''), omitidas: 0 };
|
|
19
|
+
|
|
20
|
+
const cabeza = todas.slice(0, CABEZA);
|
|
21
|
+
const cola = todas.length > CABEZA ? todas.slice(Math.max(CABEZA, todas.length - COLA)) : [];
|
|
22
|
+
const medio = todas.slice(CABEZA, Math.max(CABEZA, todas.length - COLA));
|
|
23
|
+
const vistos = new Set();
|
|
24
|
+
const fallos = [];
|
|
25
|
+
for (const l of medio) {
|
|
26
|
+
if (!FALLO.test(l)) continue;
|
|
27
|
+
const clave = l.trim();
|
|
28
|
+
if (vistos.has(clave)) continue;
|
|
29
|
+
vistos.add(clave);
|
|
30
|
+
if (fallos.length < MAX_FALLOS) fallos.push(l);
|
|
31
|
+
}
|
|
32
|
+
const omitidas = Math.max(0, medio.length - fallos.length) + todas.filter((l) => l.length > MAX_LINEA).length;
|
|
33
|
+
const donde = ruta ? ` Salida completa: ${ruta}` : '';
|
|
34
|
+
const aviso = `… [nexakit: ${medio.length - fallos.length} líneas omitidas de ${todas.length}.${donde} Repite con NEXAKIT_SALIDA=completa delante del comando si necesitas verla entera.]`;
|
|
35
|
+
const partes = [...cabeza, aviso];
|
|
36
|
+
if (fallos.length > 0) partes.push('… [líneas con posibles fallos:]', ...fallos);
|
|
37
|
+
partes.push(...cola);
|
|
38
|
+
return { texto: partes.map(recortarLinea).join('\n'), omitidas: Math.max(omitidas, 1) };
|
|
39
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"modules":["./register.js"]}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { compactarSalida } from './compactar.js';
|
|
2
|
+
|
|
3
|
+
const COMPLETA = /(^|\s)NEXAKIT_SALIDA=completa(\s|$)/u;
|
|
4
|
+
|
|
5
|
+
// Guarda la salida entera fuera del contexto para poder consultarla con grep o tail si hace falta.
|
|
6
|
+
async function guardar($, texto) {
|
|
7
|
+
const home = (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE'));
|
|
8
|
+
if (!home) return null;
|
|
9
|
+
const ruta = `${home}/.nexakit/salidas/${await $.clock.now()}-${Math.random().toString(36).slice(2, 8)}.log`;
|
|
10
|
+
await $.fs.write(ruta, texto);
|
|
11
|
+
return ruta;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function register(on) {
|
|
15
|
+
on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
|
|
16
|
+
const r = await next(e);
|
|
17
|
+
const salida = r?.result;
|
|
18
|
+
if (!salida || typeof salida.stdout !== 'string' || salida.isImage || salida.backgroundTaskId) return r;
|
|
19
|
+
if (COMPLETA.test(e.command ?? '')) return r;
|
|
20
|
+
const unida = salida.stderr ? `${salida.stdout}\n${salida.stderr}` : salida.stdout;
|
|
21
|
+
if (compactarSalida(unida).omitidas === 0) return r;
|
|
22
|
+
let ruta = null;
|
|
23
|
+
try {
|
|
24
|
+
ruta = await guardar($, unida);
|
|
25
|
+
} catch {
|
|
26
|
+
// Sin copia en disco igual se recorta; el aviso explica cómo pedirla completa.
|
|
27
|
+
}
|
|
28
|
+
const { texto } = compactarSalida(unida, { ruta });
|
|
29
|
+
// Sin `ref` ni `text`, el motor vuelve a presentar al modelo el resultado recortado.
|
|
30
|
+
return { result: { ...salida, stdout: texto, stderr: '' }, ...(r.context ? { context: r.context } : {}), ...(r.isError ? { isError: r.isError } : {}) };
|
|
31
|
+
});
|
|
32
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"name": "nexakit-lecciones", "version": "0.1.0", "description": "Frena los comandos que repiten un fallo, avisa cuando un error se repite y pide guardar tus correcciones como lecciones.", "license": "MIT"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# nexakit-lecciones
|
|
2
|
+
|
|
3
|
+
Repetir lo que ya falló, o lo que la persona ya corrigió, gasta tokens dos veces. Este mod:
|
|
4
|
+
|
|
5
|
+
- **Frena el comando que acaba de fallar igual.** Si un comando de Bash falla y se intenta otra vez sin que nada
|
|
6
|
+
haya cambiado (ninguna edición ni otro comando que saliera bien), no se ejecuta: el modelo recibe el error
|
|
7
|
+
anterior y tiene que cambiar de enfoque. `NEXAKIT_REPETIR=1` delante del comando lo permite a propósito.
|
|
8
|
+
Cada subagente lleva su propio historial.
|
|
9
|
+
- **Pide parar ante el error repetido.** Al tercer error del mismo tipo en una sesión (se ignoran números, rutas y
|
|
10
|
+
textos entre comillas), el modelo recibe una nota para explicar la causa raíz antes de otro intento.
|
|
11
|
+
- **Convierte tus correcciones en lecciones.** Si tu mensaje suena a corrección («te dije», «ya te había dicho»,
|
|
12
|
+
«otra vez lo mismo», «háblame en…», «deja de…», «no vuelvas a…»), el modelo recibe una nota para guardar la
|
|
13
|
+
lección en su memoria persistente (tipo feedback) y aplicarla. Si no era una corrección, la ignora.
|
|
14
|
+
|
|
15
|
+
La detección es local y no llama a ningún modelo. Al compactar, `nexakit-sesion` pide conservar las correcciones.
|
|
16
|
+
|
|
17
|
+
## Pruebas
|
|
18
|
+
|
|
19
|
+
`node --test test/lecciones.test.js` desde la raíz del repositorio.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"modules":["./register.js"]}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// Reglas puras de nexakit-lecciones: reconocer correcciones y comparar comandos y errores.
|
|
2
|
+
|
|
3
|
+
const CORRECCION = new RegExp([
|
|
4
|
+
String.raw`^\s*no[,.!]?\s+(eso|era|es\s+as[ií]|as[ií]|hagas|uses|me\s+(pidas|preguntes|hables|digas|hagas))\b`,
|
|
5
|
+
// «otra vez» solo cuenta como queja («otra vez lo mismo», «¿otra vez?»), no como petición («córrelo otra vez»).
|
|
6
|
+
String.raw`\botra\s+vez\s+(lo\s+mismo|con\s+eso|el\s+mismo|igual)\b|¿\s*otra\s+vez\s*\?|^\s*otra\s+vez\s*[!?.]*\s*$`,
|
|
7
|
+
String.raw`\bte\s+(dije|he\s+dicho|hab[ií]a\s+dicho|ped[ií])\b`,
|
|
8
|
+
String.raw`\bya\s+te\s+(dije|hab[ií]a)\b`,
|
|
9
|
+
String.raw`\bh[aá]blame\s+en\b`,
|
|
10
|
+
String.raw`\bdeja\s+de\s+(?!lado\b)\p{L}+(r|rme|rte|rlo|rla)\b`,
|
|
11
|
+
String.raw`\b(est[aá]|eso\s+est[aá])\s+mal\b`,
|
|
12
|
+
String.raw`^\s*nunca\b|^\s*siempre\s+que\s+(hagas|vayas|termines|abras|crees|uses)\b`,
|
|
13
|
+
String.raw`\bte\s+equivocaste\b`,
|
|
14
|
+
String.raw`\bvolviste\s+a\b`,
|
|
15
|
+
String.raw`\bno\s+vuelvas\s+a\b`,
|
|
16
|
+
String.raw`\bcu[aá]ntas\s+veces\b`,
|
|
17
|
+
].join('|'), 'iu');
|
|
18
|
+
|
|
19
|
+
export const NOTA_CORRECCION = '[nexakit: este mensaje parece una corrección. Si de verdad corrige algo que hiciste, guarda la lección en tu memoria persistente (tipo feedback, con el porqué y cómo aplicarla) si no está ya, y aplícala desde ahora; si no lo es, ignora esta nota.]';
|
|
20
|
+
|
|
21
|
+
export function esCorreccion(texto) {
|
|
22
|
+
return CORRECCION.test(String(texto ?? ''));
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function claveDeComando(comando) {
|
|
26
|
+
return String(comando ?? '').replace(/(^|\s)NEXAKIT_REPETIR=1(?=\s)/gu, ' ').replace(/\s+/gu, ' ').trim();
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Primera línea con contenido, sin textos entre comillas, números ni rutas: lo que tienen en común dos errores
|
|
30
|
+
// del mismo tipo.
|
|
31
|
+
export function claveDeError(texto) {
|
|
32
|
+
const linea = String(texto ?? '').split('\n').map((l) => l.trim()).find(Boolean);
|
|
33
|
+
if (!linea) return null;
|
|
34
|
+
return linea
|
|
35
|
+
.replace(/'[^']*'|"[^"]*"|`[^`]*`/gu, '<…>')
|
|
36
|
+
.replace(/(?:\/[^\s'"]+)+/gu, '<ruta>')
|
|
37
|
+
.replace(/\d+/gu, '#')
|
|
38
|
+
.slice(0, 160);
|
|
39
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { claveDeComando, claveDeError, esCorreccion, NOTA_CORRECCION } from './lecciones.js';
|
|
2
|
+
|
|
3
|
+
const REPETIR = /(^|\s)NEXAKIT_REPETIR=1(\s|$)/u;
|
|
4
|
+
const CAMBIAN_ESTADO = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit']);
|
|
5
|
+
const TOPE_MISMO_ERROR = 3;
|
|
6
|
+
|
|
7
|
+
const textoDeError = (r) => {
|
|
8
|
+
const res = r?.result;
|
|
9
|
+
if (typeof res === 'string') return res;
|
|
10
|
+
return [res?.stderr, res?.stdout, r?.text].filter((t) => typeof t === 'string' && t.trim()).join('\n');
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export function register(on) {
|
|
14
|
+
// Por bucle (sesión principal o cada subagente): comandos que fallaron y cuántas veces salió cada tipo de error.
|
|
15
|
+
const bucles = new Map();
|
|
16
|
+
const bucle = (id = 'principal') => {
|
|
17
|
+
if (!bucles.has(id)) bucles.set(id, { fallidos: new Map(), errores: new Map() });
|
|
18
|
+
return bucles.get(id);
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
on('tool.call', async ($, e, next) => {
|
|
22
|
+
const b = bucle(e.agentId);
|
|
23
|
+
if (e.tool !== 'Bash') {
|
|
24
|
+
const r = await next(e);
|
|
25
|
+
if (CAMBIAN_ESTADO.has(e.tool) && !r?.isError && !r?.deny) b.fallidos.clear();
|
|
26
|
+
return r;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const clave = claveDeComando(e.command);
|
|
30
|
+
const previo = b.fallidos.get(clave);
|
|
31
|
+
if (previo && !REPETIR.test(e.command ?? '')) {
|
|
32
|
+
return { deny: `nexakit: este comando ya falló así y no ha cambiado nada desde entonces:\n${previo}\nCambia de enfoque. Si de verdad corregiste la causa por otra vía, repítelo con NEXAKIT_REPETIR=1 delante.` };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const r = await next(e);
|
|
36
|
+
if (!r?.isError) {
|
|
37
|
+
// Otro comando que salió bien pudo cambiar el estado (un commit, un pull): los fallos anteriores ya no valen.
|
|
38
|
+
if (r && !r.deny) b.fallidos.clear();
|
|
39
|
+
return r;
|
|
40
|
+
}
|
|
41
|
+
const error = textoDeError(r);
|
|
42
|
+
b.fallidos.set(clave, error.split('\n').slice(0, 3).join('\n').slice(0, 400));
|
|
43
|
+
const tipo = claveDeError(error);
|
|
44
|
+
if (!tipo) return r;
|
|
45
|
+
const veces = (b.errores.get(tipo) ?? 0) + 1;
|
|
46
|
+
b.errores.set(tipo, veces);
|
|
47
|
+
if (veces !== TOPE_MISMO_ERROR) return r;
|
|
48
|
+
return {
|
|
49
|
+
result: r.result,
|
|
50
|
+
isError: r.isError,
|
|
51
|
+
context: [...(r.context ?? []), `[nexakit: el mismo tipo de error salió ${veces} veces en esta tarea («${tipo}»). Para, explica la causa raíz antes de otro intento y cambia de enfoque; si es una lección que vale para el futuro, guárdala en tu memoria persistente.]`],
|
|
52
|
+
};
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
on('prompt.submit', async ($, e, next) => (esCorreccion(e.text) ? next({ ...e, text: `${e.text}\n\n${NOTA_CORRECCION}` }) : next(e)));
|
|
56
|
+
|
|
57
|
+
on('session.end', async ($, e, next) => {
|
|
58
|
+
bucles.clear();
|
|
59
|
+
return next(e);
|
|
60
|
+
});
|
|
61
|
+
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"nexakit-modelo","version":"0.1.0","description":"
|
|
1
|
+
{"name":"nexakit-modelo","version":"0.1.0","description":"Barra sobre el prompt con modelo, esfuerzo, recomendación por mensaje y uso de contexto y límites, sin cambiar nada."}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// Contenido de la barra sobre el prompt: datos puros (texto y color por tramo) para poder probarlos.
|
|
2
|
+
import { UMBRAL_AVISO, UMBRAL_URGENTE } from './umbrales.js';
|
|
3
|
+
|
|
4
|
+
const FAMILIA = /(haiku|sonnet|opus|fable)(?:-(\d+)-(\d+))?/iu;
|
|
5
|
+
const esNumero = (v) => typeof v === 'number' && Number.isFinite(v);
|
|
6
|
+
const mayuscula = (s) => s.charAt(0).toUpperCase() + s.slice(1).toLowerCase();
|
|
7
|
+
|
|
8
|
+
export function familia(model) {
|
|
9
|
+
return model?.match(FAMILIA)?.[1]?.toLowerCase() ?? model;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function nombreModelo(model) {
|
|
13
|
+
if (!model) return 'modelo ?';
|
|
14
|
+
const m = model.match(FAMILIA);
|
|
15
|
+
if (!m) return model;
|
|
16
|
+
return m[2] ? `${mayuscula(m[1])} ${m[2]}.${m[3]}` : mayuscula(m[1]);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function medidor(percent, celdas = 10) {
|
|
20
|
+
const llenas = Math.min(celdas, Math.max(0, Math.ceil((percent / 100) * celdas)));
|
|
21
|
+
return '▰'.repeat(llenas) + '▱'.repeat(celdas - llenas);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function tono(percent) {
|
|
25
|
+
if (percent >= UMBRAL_URGENTE) return 'error';
|
|
26
|
+
if (percent >= UMBRAL_AVISO) return 'warning';
|
|
27
|
+
return 'success';
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function segmentosDeBarra({ model, effort, recommendation, usage }) {
|
|
31
|
+
const s = [
|
|
32
|
+
{ text: nombreModelo(model), color: 'claude', bold: true },
|
|
33
|
+
effort ? { text: ` · ${effort}` } : { text: ' · esfuerzo ?', dim: true },
|
|
34
|
+
];
|
|
35
|
+
if (recommendation) {
|
|
36
|
+
const coincide = effort && familia(model) === familia(recommendation.model) && effort === recommendation.effort;
|
|
37
|
+
s.push(coincide
|
|
38
|
+
? { text: ' ✓', color: 'success' }
|
|
39
|
+
: { text: ` → ${nombreModelo(recommendation.model)} · ${recommendation.effort}`, color: 'suggestion' });
|
|
40
|
+
}
|
|
41
|
+
const ctx = usage?.context?.percent;
|
|
42
|
+
if (esNumero(ctx)) {
|
|
43
|
+
s.push({ text: ' ctx ', dim: true }, { text: medidor(ctx), color: tono(ctx) }, { text: ` ${Math.round(ctx)}%` });
|
|
44
|
+
}
|
|
45
|
+
for (const l of usage?.rateLimits ?? []) {
|
|
46
|
+
if (!esNumero(l?.percentUsed)) continue;
|
|
47
|
+
const nombre = l.kind === 'five_hour' ? '5h' : l.kind === 'seven_day' ? 'sem' : null;
|
|
48
|
+
if (nombre) s.push({ text: ` ${nombre} `, dim: true }, { text: `${Math.round(l.percentUsed)}%`, color: tono(l.percentUsed) });
|
|
49
|
+
}
|
|
50
|
+
return s;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const MAX_FILAS = 4;
|
|
54
|
+
const ICONO = {
|
|
55
|
+
pending: ['…', 'warning'], running: ['…', 'warning'], waiting: ['…', 'warning'],
|
|
56
|
+
idle: ['✓', 'success'], completed: ['✓', 'success'], failed: ['✗', 'error'], killed: ['✗', 'error'],
|
|
57
|
+
};
|
|
58
|
+
const ancho = (texto, n) => (texto.length >= n ? `${texto.slice(0, n - 1)}…` : texto.padEnd(n));
|
|
59
|
+
|
|
60
|
+
// Una fila por subagente (los más recientes): nivel, modelo y esfuerzo observados, encargo y estado.
|
|
61
|
+
export function filasDeAgentes(agentes) {
|
|
62
|
+
return agentes.slice(-MAX_FILAS).map((a) => {
|
|
63
|
+
const nivel = String(a.type ?? '?').replace(/^niveles:nivel-/u, '');
|
|
64
|
+
const [icono, color] = ICONO[a.status] ?? ['?', undefined];
|
|
65
|
+
return [
|
|
66
|
+
{ text: ` ↳ ${ancho(nivel, 9)}`, dim: true },
|
|
67
|
+
{ text: ancho(`${nombreModelo(a.model)}${a.effort ? ` · ${a.effort}` : ''}`, 20), color: 'claude' },
|
|
68
|
+
{ text: ` ${ancho(a.description ?? '', 32)} ` },
|
|
69
|
+
{ text: icono, color },
|
|
70
|
+
];
|
|
71
|
+
});
|
|
72
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// Recomendación local por el texto del mensaje: sin llamar a ningún modelo ni gastar tokens.
|
|
2
|
+
// Sigue la guía de elegir-modelo: ligero solo para lo mecánico, uso diario por defecto, el más capaz
|
|
3
|
+
// para diseño y fallos; high solo cuando verificar importa.
|
|
4
|
+
|
|
5
|
+
// Solo cuenta como confirmación un mensaje hecho únicamente de estas palabras, separadas entre sí:
|
|
6
|
+
// «ok, depura esto» y «sídale» no lo son.
|
|
7
|
+
const PALABRA = '(?:s[ií]|ok|okay|dale|listo|vale|perfecto|bien|contin[uú]a|sigue|hazlo|adelante|gracias|de una|claro|no)';
|
|
8
|
+
const CONFIRMACION = new RegExp(`^¡?${PALABRA}(?:[\\s.!,¡]+${PALABRA})*[\\s.!,]*$`, 'iu');
|
|
9
|
+
// «error» solo cuenta como fallo si no es parte de «mensajes de error» o similar.
|
|
10
|
+
const FALLO = /(\bbugs?\b|(?<!de )\berror|\bfall[aeo]|no funciona|no guarda|no carga|\broto\b|\brompe|por qu[eé]|\bdepura|\bdebug|\barregl|\bcorrig|seguridad|vulnerab)/iu;
|
|
11
|
+
const DISENO = /(\bdise[ñn]|arquitectura|\bplanific|\brefactori|\bmigra|investiga)/iu;
|
|
12
|
+
const MECANICO = /(\bcommit|\bpush\b|\bmerge\b|\brenombra|\bmueve\b|\bformatea|\bejecuta|\bcorre\b|\binstala|\btypo\b|\btraduce|\bborra la rama|\babre el\b)/iu;
|
|
13
|
+
// Un verbo de construir convierte el mensaje en trabajo habitual aunque además pida un commit.
|
|
14
|
+
const TRABAJO = /(\bimplement|\bañad|\bagreg|\bcrea\b|\bcrear\b|\bconstru|\bmodific|\bcambia\b|\bescrib|\bhaz que\b)/iu;
|
|
15
|
+
|
|
16
|
+
export function recomendarPorTexto(texto, previa = null) {
|
|
17
|
+
const limpio = String(texto ?? '').trim();
|
|
18
|
+
if (limpio === '' || (previa && CONFIRMACION.test(limpio))) return previa ?? porDefecto();
|
|
19
|
+
if (FALLO.test(limpio)) return { model: 'opus', effort: 'high', reason: 'fallo o seguridad: verificar importa' };
|
|
20
|
+
if (DISENO.test(limpio)) return { model: 'opus', effort: 'medium', reason: 'diseño o ambigüedad' };
|
|
21
|
+
if (MECANICO.test(limpio) && !TRABAJO.test(limpio)) return { model: 'haiku', effort: 'low', reason: 'tarea mecánica' };
|
|
22
|
+
return porDefecto();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function porDefecto() {
|
|
26
|
+
return { model: 'sonnet', effort: 'medium', reason: 'trabajo habitual' };
|
|
27
|
+
}
|
|
@@ -1,12 +1,38 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
import { familia, filasDeAgentes, segmentosDeBarra } from './barra.js';
|
|
2
|
+
import { recomendarPorTexto } from './recomendar.js';
|
|
3
|
+
|
|
4
|
+
async function refrescar($, estado, { usage = false } = {}) {
|
|
5
|
+
try {
|
|
6
|
+
estado.model = await $.session.model();
|
|
7
|
+
// El esfuerzo se observó en un modelo concreto: si cambió de modelo, ya no se sabe.
|
|
8
|
+
if (familia(estado.model) !== familia(estado.modeloDelEsfuerzo)) estado.effort = null;
|
|
9
|
+
if (usage) estado.usage = await $.session.usage();
|
|
10
|
+
} catch {
|
|
11
|
+
// Medir nunca debe romper el turno.
|
|
12
|
+
}
|
|
13
|
+
$.ui.invalidate('ui.render');
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// Completa los subagentes vistos con lo que dice el motor: tipo, encargo y estado.
|
|
17
|
+
async function sincronizarAgentes($, agentes) {
|
|
18
|
+
try {
|
|
19
|
+
for (const info of await $.agent.list()) {
|
|
20
|
+
const visto = agentes.get(info.id);
|
|
21
|
+
if (visto) Object.assign(visto, { type: info.type, description: info.description, status: info.status });
|
|
22
|
+
}
|
|
23
|
+
} catch {
|
|
24
|
+
// Sin lista, se conserva lo último conocido.
|
|
25
|
+
}
|
|
26
|
+
$.ui.invalidate('ui.render');
|
|
5
27
|
}
|
|
6
28
|
|
|
29
|
+
// Una sola barra sobre el prompt con modelo, esfuerzo, recomendación y uso. Solo muestra:
|
|
30
|
+
// nunca cambia el modelo ni el esfuerzo de la sesión.
|
|
7
31
|
export function register(on) {
|
|
8
|
-
|
|
9
|
-
|
|
32
|
+
const estado = { model: null, effort: null, modeloDelEsfuerzo: null, recommendation: null, usage: null };
|
|
33
|
+
// Subagentes de esta petición, por id, con el modelo y el esfuerzo que de verdad usaron.
|
|
34
|
+
const agentes = new Map();
|
|
35
|
+
|
|
10
36
|
on('session.start', async ($, e, next) => {
|
|
11
37
|
await $.tool.register({
|
|
12
38
|
name: 'nexakit_recomendacion',
|
|
@@ -18,31 +44,61 @@ export function register(on) {
|
|
|
18
44
|
additionalProperties: false,
|
|
19
45
|
},
|
|
20
46
|
});
|
|
21
|
-
await
|
|
47
|
+
await refrescar($, estado, { usage: true });
|
|
22
48
|
return next(e);
|
|
23
49
|
});
|
|
50
|
+
|
|
24
51
|
on('tool.call', { tool: 'mcp__nexakit-modelo__nexakit_recomendacion' }, async ($, e) => {
|
|
25
|
-
recommendation = { model: e.model, effort: e.effort, reason: e.reason };
|
|
26
|
-
await
|
|
52
|
+
estado.recommendation = { model: e.model, effort: e.effort, reason: e.reason };
|
|
53
|
+
await refrescar($, estado);
|
|
27
54
|
return { result: 'Recomendación mostrada; no se cambió el modelo ni el esfuerzo.' };
|
|
28
55
|
});
|
|
56
|
+
|
|
57
|
+
on('prompt.submit', async ($, e, next) => {
|
|
58
|
+
estado.recommendation = recomendarPorTexto(e.text, estado.recommendation);
|
|
59
|
+
for (const [id, a] of agentes) if (['completed', 'idle', 'failed', 'killed'].includes(a.status)) agentes.delete(id);
|
|
60
|
+
$.ui.invalidate('ui.render');
|
|
61
|
+
return next(e);
|
|
62
|
+
});
|
|
63
|
+
|
|
29
64
|
on('turn.step', async function* ($, e, next) {
|
|
30
65
|
if (!e.agentId) {
|
|
31
|
-
|
|
32
|
-
|
|
66
|
+
// El último esfuerzo visto se conserva entre turnos; el siguiente paso lo corrige si cambió.
|
|
67
|
+
estado.model = e.model;
|
|
68
|
+
estado.effort = e.effort ?? null;
|
|
69
|
+
estado.modeloDelEsfuerzo = e.model;
|
|
70
|
+
$.ui.invalidate('ui.render');
|
|
71
|
+
} else {
|
|
72
|
+
const nuevo = !agentes.has(e.agentId);
|
|
73
|
+
const a = agentes.get(e.agentId) ?? { status: 'running' };
|
|
74
|
+
agentes.set(e.agentId, Object.assign(a, { model: e.model, effort: e.effort ?? null }));
|
|
75
|
+
if (nuevo) await sincronizarAgentes($, agentes);
|
|
33
76
|
}
|
|
34
77
|
yield* next(e);
|
|
35
78
|
});
|
|
79
|
+
|
|
36
80
|
on('turn.complete', async ($, e, next) => {
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
81
|
+
if (!e.agentId) {
|
|
82
|
+
await refrescar($, estado, { usage: true });
|
|
83
|
+
if (agentes.size > 0) await sincronizarAgentes($, agentes);
|
|
84
|
+
}
|
|
40
85
|
return next(e);
|
|
41
86
|
});
|
|
87
|
+
|
|
88
|
+
on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
|
|
89
|
+
if (e.props?.hasSurvey || !estado.model) return next(e);
|
|
90
|
+
const { Box, Text } = $.ui.resolve(e);
|
|
91
|
+
const tramos = segmentosDeBarra(estado).map((s, i) =>
|
|
92
|
+
h(Text, { key: String(i), color: s.color, dimColor: s.dim, bold: s.bold }, s.text));
|
|
93
|
+
const linea = (partes, clave) => h(Box, { key: clave, flexDirection: 'row' },
|
|
94
|
+
...partes.map((s, i) => h(Text, { key: String(i), color: s.color, dimColor: s.dim, bold: s.bold }, s.text)));
|
|
95
|
+
const filas = filasDeAgentes([...agentes.values()]).map((f, i) => linea(f, `agente-${i}`));
|
|
96
|
+
return h(Box, { flexDirection: 'column' }, h(Box, { key: 'principal', flexDirection: 'row' }, ...tramos), ...filas);
|
|
97
|
+
});
|
|
98
|
+
|
|
42
99
|
on('session.end', async ($, e, next) => {
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
$.ui.status(undefined);
|
|
100
|
+
agentes.clear();
|
|
101
|
+
Object.assign(estado, { model: null, effort: null, modeloDelEsfuerzo: null, recommendation: null, usage: null });
|
|
46
102
|
return next(e);
|
|
47
103
|
});
|
|
48
104
|
}
|
|
@@ -16,6 +16,6 @@ describe('nexakit-modelo API', () => {
|
|
|
16
16
|
});
|
|
17
17
|
await $.session.start({ surface: 'terminal', isInteractive: true, cwd: '/test' });
|
|
18
18
|
expect(tools).toContain('nexakit_recomendacion');
|
|
19
|
-
expect(statuses
|
|
19
|
+
expect(statuses).toHaveLength(0);
|
|
20
20
|
});
|
|
21
21
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name": "nexakit-sesion", "version": "0.1.0", "description": "
|
|
1
|
+
{"name": "nexakit-sesion", "version": "0.1.0", "description": "Avisa cuándo conviene cerrar la sesión y abrir otra, sin cerrarla por ti.", "license": "MIT"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
# nexakit-sesion
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
Al pasar del 60 % y del 80 % de contexto avisa una vez de que es buen momento para escribir el traspaso y abrir
|
|
4
|
+
una sesión nueva. Solo avisa: nunca cierra la sesión. El contexto y los límites de 5 horas y semanal se ven en la
|
|
5
|
+
barra de `nexakit-modelo`, con los mismos umbrales de color.
|
|
6
6
|
|
|
7
7
|
Los datos salen de Claude Code (`$.session.usage()`); los límites se mueven en puntos enteros y solo cuando una
|
|
8
8
|
respuesta de la API informa un valor nuevo.
|
|
@@ -13,17 +13,6 @@ export function avisoDeContexto(percent) {
|
|
|
13
13
|
return 0;
|
|
14
14
|
}
|
|
15
15
|
|
|
16
|
-
// Línea de estado: solo lo que se conoce; undefined si no hay nada que mostrar.
|
|
17
|
-
export function textoDeEstado(usage) {
|
|
18
|
-
const partes = [];
|
|
19
|
-
if (esNumero(usage?.context?.percent)) partes.push(`contexto ${entero(usage.context.percent)} %`);
|
|
20
|
-
for (const limite of usage?.rateLimits ?? []) {
|
|
21
|
-
if (!esNumero(limite?.percentUsed)) continue;
|
|
22
|
-
if (limite.kind === 'five_hour') partes.push(`5 h ${entero(limite.percentUsed)} %`);
|
|
23
|
-
if (limite.kind === 'seven_day') partes.push(`semana ${entero(limite.percentUsed)} %`);
|
|
24
|
-
}
|
|
25
|
-
return partes.length > 0 ? partes.join(' · ') : undefined;
|
|
26
|
-
}
|
|
27
16
|
|
|
28
17
|
// El aviso solo recomienda: nunca promete ni hace el cierre por la persona.
|
|
29
18
|
export function mensajeDeAviso(nivel, percent) {
|
|
@@ -36,3 +25,31 @@ export function mensajeDeAviso(nivel, percent) {
|
|
|
36
25
|
}
|
|
37
26
|
return undefined;
|
|
38
27
|
}
|
|
28
|
+
|
|
29
|
+
// Cuota de 5 horas: a partir de aquí los subagentes en paralelo agotan el límite antes de terminar.
|
|
30
|
+
export const CUOTA_SERIE = 70;
|
|
31
|
+
export const CUOTA_CRITICA = 90;
|
|
32
|
+
|
|
33
|
+
export function nivelDeCuota(usage) {
|
|
34
|
+
const cinco = (usage?.rateLimits ?? []).find((l) => l?.kind === 'five_hour')?.percentUsed;
|
|
35
|
+
if (!esNumero(cinco)) return 0;
|
|
36
|
+
if (cinco >= CUOTA_CRITICA) return 2;
|
|
37
|
+
if (cinco >= CUOTA_SERIE) return 1;
|
|
38
|
+
return 0;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Nota para el modelo, no para la persona: va al final del mensaje solo al cambiar de nivel.
|
|
42
|
+
export function notaDeCuota(nivel, percent) {
|
|
43
|
+
const p = entero(percent);
|
|
44
|
+
if (nivel === 1) return `[nexakit: cuota de 5 h al ${p} %. Lanza los subagentes en serie, no en paralelo.]`;
|
|
45
|
+
if (nivel === 2) return `[nexakit: cuota de 5 h al ${p} %. Subagentes solo en serie y en los niveles ligero o normal; avisa antes de algo largo.]`;
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Lo que el resumen de una compactación debe conservar para poder seguir la tarea sin releer todo.
|
|
50
|
+
export const CONSERVAR_AL_COMPACTAR = [
|
|
51
|
+
'Conserva literalmente: la rama y el directorio de trabajo, los archivos tocados, las decisiones',
|
|
52
|
+
'tomadas con la persona y su porqué, lo pendiente en orden, los comandos de comprobación con su',
|
|
53
|
+
'último resultado, cualquier autorización o prohibición que haya dado la persona y cada corrección',
|
|
54
|
+
'suya con la lección que deja.',
|
|
55
|
+
].join(' ');
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import { avisoDeContexto, mensajeDeAviso,
|
|
1
|
+
import { avisoDeContexto, CONSERVAR_AL_COMPACTAR, mensajeDeAviso, nivelDeCuota, notaDeCuota } from './aviso.js';
|
|
2
2
|
|
|
3
3
|
export function register(on) {
|
|
4
4
|
// Último nivel avisado: solo se vuelve a avisar al subir de nivel o tras bajar y volver a subir.
|
|
5
5
|
let ultimoAviso = 0;
|
|
6
|
+
let ultimaCuota = 0;
|
|
6
7
|
|
|
7
8
|
on('turn.complete', async ($, e, next) => {
|
|
8
9
|
try {
|
|
9
10
|
if (!e.agentId) {
|
|
10
11
|
const usage = await $.session.usage();
|
|
11
|
-
$.ui.status(textoDeEstado(usage));
|
|
12
12
|
const percent = usage?.context?.percent;
|
|
13
13
|
const nivel = avisoDeContexto(percent);
|
|
14
14
|
if (nivel > ultimoAviso) $.ui.toast(mensajeDeAviso(nivel, percent), { timeoutMs: 10000 });
|
|
@@ -20,8 +20,36 @@ export function register(on) {
|
|
|
20
20
|
return next(e);
|
|
21
21
|
});
|
|
22
22
|
|
|
23
|
+
// Con la cuota de 5 h alta, el modelo lo sabe una vez por nivel para no lanzar subagentes en paralelo.
|
|
24
|
+
on('prompt.submit', async ($, e, next) => {
|
|
25
|
+
try {
|
|
26
|
+
const usage = await $.session.usage();
|
|
27
|
+
const nivel = nivelDeCuota(usage);
|
|
28
|
+
const anterior = ultimaCuota;
|
|
29
|
+
ultimaCuota = nivel;
|
|
30
|
+
if (nivel > anterior) {
|
|
31
|
+
const cinco = usage.rateLimits.find((l) => l.kind === 'five_hour').percentUsed;
|
|
32
|
+
return next({ ...e, text: `${e.text}\n\n${notaDeCuota(nivel, cinco)}` });
|
|
33
|
+
}
|
|
34
|
+
} catch {
|
|
35
|
+
// Sin datos de uso, el mensaje pasa tal cual.
|
|
36
|
+
}
|
|
37
|
+
return next(e);
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
// Antes de compactar la conversación principal, el resumen sabe qué no puede perder.
|
|
41
|
+
on('session.compact', async ($, e, next) => {
|
|
42
|
+
if (e.agentId || (e.trigger !== 'auto' && e.trigger !== 'manual')) return next(e);
|
|
43
|
+
const instructions = e.instructions ? `${e.instructions}\n\n${CONSERVAR_AL_COMPACTAR}` : CONSERVAR_AL_COMPACTAR;
|
|
44
|
+
const r = await next({ ...e, instructions });
|
|
45
|
+
if (r?.messages) $.ui.toast('Contexto compactado. Si la tarea es larga, pide actualizar el traspaso con project-handoff.', { timeoutMs: 10000 });
|
|
46
|
+
return r;
|
|
47
|
+
});
|
|
48
|
+
|
|
23
49
|
on('session.end', async ($, e, next) => {
|
|
24
50
|
ultimoAviso = 0;
|
|
51
|
+
ultimaCuota = 0;
|
|
52
|
+
// Limpia la línea de estado que dejaban versiones anteriores; el uso se ve ahora en la barra de nexakit-modelo.
|
|
25
53
|
$.ui.status(undefined);
|
|
26
54
|
return next(e);
|
|
27
55
|
});
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { describe, expect, test } from 'claude-code/testing';
|
|
2
|
-
import { avisoDeContexto,
|
|
2
|
+
import { avisoDeContexto, mensajeDeAviso } from '../hooks/aviso.js';
|
|
3
3
|
|
|
4
4
|
describe('nexakit-sesion · lógica', () => {
|
|
5
5
|
test('los umbrales avisan al 60 % y al 80 %, y nunca sin dato', () => {
|
|
@@ -13,19 +13,6 @@ describe('nexakit-sesion · lógica', () => {
|
|
|
13
13
|
expect(avisoDeContexto(Number.NaN)).toBe(0);
|
|
14
14
|
});
|
|
15
15
|
|
|
16
|
-
test('la línea de estado junta contexto y límites de Claude, y omite lo que no se conoce', () => {
|
|
17
|
-
const usage = {
|
|
18
|
-
context: { window: 1000000, percent: 41.6 },
|
|
19
|
-
rateLimits: [
|
|
20
|
-
{ kind: 'five_hour', percentUsed: 88 },
|
|
21
|
-
{ kind: 'seven_day', percentUsed: 14.5 },
|
|
22
|
-
{ kind: 'spend_limit', percentUsed: 3 },
|
|
23
|
-
],
|
|
24
|
-
};
|
|
25
|
-
expect(textoDeEstado(usage)).toBe('contexto 42 % · 5 h 88 % · semana 15 %');
|
|
26
|
-
expect(textoDeEstado({ context: { window: 1000 }, rateLimits: [] })).toBeUndefined();
|
|
27
|
-
expect(textoDeEstado({ context: { window: 1000, percent: 5 }, rateLimits: [] })).toBe('contexto 5 %');
|
|
28
|
-
});
|
|
29
16
|
|
|
30
17
|
test('cada aviso dice el porcentaje, propone el traspaso y no promete cerrar nada', () => {
|
|
31
18
|
const uno = mensajeDeAviso(1, 62.2);
|
|
@@ -85,10 +72,10 @@ describe('nexakit-sesion · en la sesión', () => {
|
|
|
85
72
|
await terminar(); // 20 -> tras compactar o limpiar
|
|
86
73
|
await terminar(); // 70 -> vuelve a avisar
|
|
87
74
|
expect(avisos).toHaveLength(3);
|
|
88
|
-
expect(estados.
|
|
75
|
+
expect(estados.filter((texto) => texto !== undefined)).toHaveLength(0);
|
|
89
76
|
});
|
|
90
77
|
|
|
91
|
-
test('al terminar la sesión limpia
|
|
78
|
+
test('al terminar la sesión limpia la línea de estado de versiones anteriores', async ($, on) => {
|
|
92
79
|
const { estados } = await montar($, on, [10]);
|
|
93
80
|
await $.session.end({ reason: 'exit' });
|
|
94
81
|
expect(estados.at(-1)).toBeUndefined();
|