nexakit 0.13.2 → 0.15.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.
Files changed (80) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/README.md +8 -8
  3. package/assets/runtime/package-lock.json +2 -2
  4. package/dist/fabrica/banco/ejecutar.js +26 -13
  5. package/dist/fabrica/cli.js +12 -5
  6. package/dist/fabrica/conectores/antigravity.js +32 -4
  7. package/dist/fabrica/decision.js +1 -3
  8. package/dist/fabrica/encargo/candado.js +24 -5
  9. package/dist/fabrica/encargo/ejecutar.js +218 -85
  10. package/dist/fabrica/encargo/reparto.js +153 -0
  11. package/dist/fabrica/enrutador.js +16 -2
  12. package/dist/fabrica/mcp.js +31 -26
  13. package/dist/fabrica/plena-capacidad.js +54 -0
  14. package/dist/fabrica/tabla-modelos.json +10 -7
  15. package/package.json +1 -1
  16. package/plugins/huellas.json +8 -8
  17. package/plugins/nexakit-ahorro/.claude-plugin/plugin.json +2 -2
  18. package/plugins/nexakit-ahorro/README.md +9 -3
  19. package/plugins/nexakit-ahorro/hooks/register.js +17 -0
  20. package/plugins/nexakit-ahorro/tests/register.test.ts +40 -6
  21. package/plugins/nexakit-modelo/.claude-plugin/plugin.json +2 -2
  22. package/plugins/nexakit-modelo/hooks/barra.js +4 -27
  23. package/plugins/nexakit-modelo/hooks/decidir.js +15 -46
  24. package/plugins/nexakit-modelo/hooks/recomendar.js +8 -13
  25. package/plugins/nexakit-modelo/hooks/register.js +13 -134
  26. package/plugins/nexakit-modelo/tests/register.test.ts +31 -230
  27. package/plugins/nexakit-sesion/.claude-plugin/plugin.json +1 -1
  28. package/plugins/nexakit-sesion/hooks/aviso.js +5 -6
  29. package/plugins/nexakit-sesion/hooks/register.js +1 -1
  30. package/plugins/niveles/.claude-plugin/plugin.json +2 -2
  31. package/plugins/niveles/agents/cazador-de-flakes.md +2 -5
  32. package/plugins/niveles/agents/cierre-de-memoria.md +2 -4
  33. package/plugins/niveles/agents/investigador.md +6 -9
  34. package/plugins/niveles/agents/nivel-alto.md +6 -7
  35. package/plugins/niveles/agents/nivel-exigente.md +6 -7
  36. package/plugins/niveles/agents/nivel-ligero.md +7 -8
  37. package/plugins/niveles/agents/nivel-normal.md +6 -7
  38. package/plugins/niveles/agents/revisor-de-calidad.md +2 -4
  39. package/plugins/niveles/agents/sincronizador-docs.md +2 -4
  40. package/plugins/niveles/agents/subir-al-repo.md +2 -4
  41. package/skills/elegir-modelo/SKILL.md +13 -14
  42. package/skills/elegir-modelo/modelos.mjs +1 -0
  43. package/skills/fabrica/SKILL.md +10 -11
  44. package/src/agent-models.d.ts +2 -0
  45. package/src/agent-models.js +21 -7
  46. package/src/ahorro-command.js +26 -4
  47. package/src/antigravity-agents.js +10 -8
  48. package/src/antigravity-barra.js +5 -18
  49. package/src/antigravity-hook.js +1 -1
  50. package/src/antigravity-pre-tool.js +3 -1
  51. package/src/antigravity-recommendation.js +49 -51
  52. package/src/codex-audit.js +2 -2
  53. package/src/codex-auto-output.js +3 -0
  54. package/src/codex-hook.js +1 -1
  55. package/src/codex-output.js +6 -1
  56. package/src/codex-pre-tool.js +7 -0
  57. package/src/codex-recommendation.js +6 -10
  58. package/src/codex-routing.js +1 -1
  59. package/src/codex-setup.js +4 -3
  60. package/src/codex-team.js +20 -19
  61. package/src/fabrica/banco/ejecutar.ts +26 -13
  62. package/src/fabrica/cli.ts +11 -5
  63. package/src/fabrica/conectores/antigravity.ts +28 -4
  64. package/src/fabrica/decision.ts +1 -3
  65. package/src/fabrica/encargo/candado.ts +27 -5
  66. package/src/fabrica/encargo/ejecutar.ts +223 -82
  67. package/src/fabrica/encargo/reparto.ts +182 -0
  68. package/src/fabrica/enrutador.ts +14 -2
  69. package/src/fabrica/mcp.ts +28 -24
  70. package/src/fabrica/plena-capacidad.ts +63 -0
  71. package/src/fabrica/tabla-modelos.json +10 -7
  72. package/src/gemini-tools.js +1 -1
  73. package/src/level-agents.js +9 -7
  74. package/src/model-command.js +16 -7
  75. package/src/mods.js +2 -2
  76. package/src/preferencias-globales.js +80 -0
  77. package/src/review-instructions.js +31 -37
  78. package/src/toolkit-cli.js +2 -2
  79. package/src/regla-ordenes-simples.d.ts +0 -2
  80. package/src/regla-ordenes-simples.js +0 -4
@@ -1,7 +1,8 @@
1
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: uso diario por defecto; ante un fallo sube el esfuerzo (verificar importa) y
3
- // solo sube de modelo si ya se intentó y falló, es intermitente o es de seguridad; el más capaz para diseñar;
4
- // lo mecánico se delega. Las reglas se ajustaron contrastándolas con mensajes reales de uso.
2
+ // Sigue la guía de elegir-modelo: uso diario con su esfuerzo por defecto como mínimo; ante un fallo sube el
3
+ // esfuerzo (verificar importa) y sube de modelo si ya se intentó y falló, es intermitente o es de seguridad; el más
4
+ // capaz para diseñar. Modo completo (0.14.0): nunca propone un modelo ligero, un esfuerzo bajo ni delegar.
5
+ // Las reglas se ajustaron contrastándolas con mensajes reales de uso.
5
6
 
6
7
  // Solo cuenta como confirmación un mensaje hecho únicamente de estas palabras, separadas entre sí:
7
8
  // «ok, depura esto» y «sídale» no lo son.
@@ -43,15 +44,9 @@ const ESCRIBIR_PRUEBAS = /\b(?:escrib|a[ñn]ad|agreg|crea|cubr|complet|ampl[ií]
43
44
  export function recomendarPorTexto(texto, previa = null) {
44
45
  const limpio = String(texto ?? '').trim();
45
46
  if (limpio === '' || (previa && CONFIRMACION.test(limpio))) return previa ?? porDefecto();
46
- // Quien anuncia una pregunta quiere una explicación, mencione o no un error; si es larga o trae otra
47
- // petición, merece el esfuerzo normal.
48
- // `delegar` nombra el subagente que hace el mismo trabajo sin cambiar el modelo de la sesión: cada modelo
49
- // tiene su caché y cambiarlo relee todo el historial sin ella; un subagente no toca la caché de la sesión.
50
47
  const esFallo = FALLO.test(limpio);
51
- if (DIFICIL.test(limpio) || (SIN_CAUSA.test(limpio) && (esFallo || SINTOMA.test(limpio))) || (previa?.fallo && REINTENTO.test(limpio))) return { model: 'opus', effort: 'high', reason: 'fallo difícil, reintento o seguridad: hace falta el más capaz', delegar: 'nivel-alto', fallo: true };
52
- // Subir el esfuerzo no rompe la caché; subir el modelo, sí.
53
- // Quien anuncia una pregunta quiere una explicación, mencione o no un error; si es larga o trae otra
54
- // petición, merece el esfuerzo normal.
48
+ if (DIFICIL.test(limpio) || (SIN_CAUSA.test(limpio) && (esFallo || SINTOMA.test(limpio))) || (previa?.fallo && REINTENTO.test(limpio))) return { model: 'opus', effort: 'high', reason: 'fallo difícil, reintento o seguridad: hace falta el más capaz', fallo: true };
49
+ // Quien anuncia una pregunta quiere una explicación, mencione o no un error.
55
50
  if (SOLO_PREGUNTA.test(limpio)) return limpio.length <= MAX_PREGUNTA && !MECANICO.test(limpio) ? pregunta() : porDefecto();
56
51
  if (esFallo) return { model: 'sonnet', effort: 'high', reason: 'fallo: verificar importa', fallo: true };
57
52
  // Seguir con lo que ya estaba en marcha conserva la recomendación de ese trabajo.
@@ -61,14 +56,14 @@ export function recomendarPorTexto(texto, previa = null) {
61
56
  return { model: 'sonnet', effort: 'high', reason: 'pruebas o casos borde: verificar importa' };
62
57
  }
63
58
  if ((MECANICO.test(limpio) || BUSQUEDA.test(limpio)) && !TRABAJO.test(limpio) && !PREGUNTA.test(limpio)) {
64
- return { model: 'haiku', effort: 'low', reason: 'tarea mecánica: mejor delegarla', delegar: 'nivel-ligero' };
59
+ return { model: 'sonnet', effort: 'medium', reason: 'tarea mecánica', mecanica: true };
65
60
  }
66
61
  if (PREGUNTA_SIMPLE.test(limpio) && limpio.length <= MAX_PREGUNTA && !TRABAJO.test(limpio) && !PETICION.test(limpio)) return pregunta();
67
62
  return porDefecto();
68
63
  }
69
64
 
70
65
  function pregunta() {
71
- return { model: 'sonnet', effort: 'low', reason: 'pregunta o explicación: respuesta rápida' };
66
+ return { model: 'sonnet', effort: 'medium', reason: 'pregunta o explicación' };
72
67
  }
73
68
 
74
69
  function porDefecto() {
@@ -1,5 +1,4 @@
1
- import { activoDeTexto, alAbortarTurno, columnaDeAgentes, columnaDeFabrica, familia, filasDeAgentes, filasDeFabrica, instruccionDeDelegar, segmentosDeBarra, sumarTokens, tokensVacios } from './barra.js';
2
- import { ajustarPorLimite } from './decidir.js';
1
+ import { activoDeTexto, columnaDeAgentes, columnaDeFabrica, familia, filasDeAgentes, filasDeFabrica, segmentosDeBarra, sumarTokens, tokensVacios } from './barra.js';
3
2
  import { recomendarPorTexto } from './recomendar.js';
4
3
 
5
4
  async function refrescar($, estado, { usage = false } = {}) {
@@ -27,35 +26,7 @@ async function sincronizarAgentes($, agentes) {
27
26
  $.ui.invalidate('ui.render');
28
27
  }
29
28
 
30
- const mismaRecomendacion = (a, b) =>
31
- a?.model === b?.model && a?.effort === b?.effort && a?.delegar === b?.delegar;
32
-
33
- // La caché de la conversación caduca tras un rato sin actividad: una hora con suscripción (la API informa
34
- // límites de uso) y cinco minutos con clave de API. Con la caché fría, cambiar de modelo ya no cuesta nada extra.
35
- const MINUTO = 60 * 1000;
36
- const vidaDeCache = (usage) => ((usage?.rateLimits ?? []).length > 0 ? 60 : 5) * MINUTO;
37
- const RANGO = { haiku: 0, sonnet: 1, opus: 2, fable: 3 };
38
- const rango = (model) => RANGO[familia(model)] ?? -1;
39
-
40
- async function medirCacheFria($, estado) {
41
- try {
42
- const fria = estado.ultimaActividad !== null && (await $.clock.now()) - estado.ultimaActividad > vidaDeCache(estado.usage);
43
- if (fria === estado.cacheFria) return false;
44
- estado.cacheFria = fria;
45
- return true;
46
- } catch {
47
- return false;
48
- }
49
- }
50
-
51
- async function marcarActividad($, estado) {
52
- try {
53
- estado.ultimaActividad = await $.clock.now();
54
- estado.cacheFria = false;
55
- } catch {
56
- // Sin reloj no se sabe si la caché está fría: se asume caliente.
57
- }
58
- }
29
+ const mismaRecomendacion = (a, b) => a?.model === b?.model && a?.effort === b?.effort;
59
30
 
60
31
  const cacheVacia = () => ({ read: 0, creation: 0, input: 0, turnos: 0 });
61
32
  const tokens = (v) => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : 0);
@@ -84,29 +55,14 @@ async function activoDeLaFabrica($) {
84
55
  }
85
56
  }
86
57
 
87
- const HERRAMIENTA_ENCARGO = 'mcp__nexakit-fabrica__fabrica_encargar';
88
- const MARCA_SIN_ENCARGO = '[sin encargo]';
89
- const MENSAJE_ENCARGO = 'Primero encarga esta implementación con fabrica_encargar (Codex o Antigravity): ahorra tokens de Claude. Si el encargo no es posible (repo sin commits, otro encargo en marcha, sin conector) o ya falló, vuelve a lanzar el subagente con [sin encargo] en la descripción.';
90
-
91
- // Un subagente niveles:nivel-normal pedido por la sesión principal sin la marca [sin encargo].
92
- function vetaSubagenteNormal(e) {
93
- if (e.agentId || e.subagent_type !== 'niveles:nivel-normal') return false;
94
- return !`${e.description ?? ''}\n${e.prompt ?? ''}`.toLowerCase().includes(MARCA_SIN_ENCARGO);
95
- }
58
+ // Estado inicial de la barra; session.end vuelve a él.
59
+ const estadoInicial = () => ({ model: null, effort: null, modeloDelEsfuerzo: null, recommendation: null, enviada: null, usage: null, cache: cacheVacia() });
96
60
 
97
- // ¿Existe la herramienta de encargos? Si no se puede saber, se asume que sí.
98
- async function hayEncargos($) {
99
- try {
100
- return (await $.tool.list()).some((t) => t.name === HERRAMIENTA_ENCARGO);
101
- } catch {
102
- return true;
103
- }
104
- }
105
-
106
- // Una sola barra sobre el prompt con modelo, esfuerzo, recomendación y uso. Solo muestra:
107
- // nunca cambia el modelo ni el esfuerzo de la sesión.
61
+ // Una sola barra sobre el prompt con modelo, esfuerzo, caché, contexto, límites y subagentes. Solo informa: nunca
62
+ // cambia el modelo ni el esfuerzo de la sesión, no veta subagentes y no empuja a delegar ni a bajar de modelo;
63
+ // como mucho propone subir cuando el mensaje lo pide (un fallo difícil, un diseño).
108
64
  export function register(on) {
109
- const estado = { model: null, effort: null, modeloDelEsfuerzo: null, recommendation: null, enviada: null, usage: null, cache: cacheVacia(), ultimaActividad: null, cacheFria: false, rutinaSeguidas: 0, turnoActivo: false, turnoId: null, delegado: false, enviando: false, ultimoTexto: null, borrador: '' };
65
+ const estado = estadoInicial();
110
66
  // Subagentes de esta petición, por id, con el modelo y el esfuerzo que de verdad usaron.
111
67
  const agentes = new Map();
112
68
 
@@ -132,23 +88,13 @@ export function register(on) {
132
88
  return { result: 'Recomendación mostrada; no se cambió el modelo ni el esfuerzo.' };
133
89
  });
134
90
 
135
- // La implementación de nivel normal se encarga primero (fabrica_encargar en Codex o Antigravity, que ahorra tokens de
136
- // Claude). Solo se veta el subagente niveles:nivel-normal lanzado por la sesión principal y sin la marca
137
- // [sin encargo] (para cuando el encargo no es posible o ya falló); nada más se bloquea.
138
- on('tool.call', { tool: 'Agent' }, async ($, e, next) => {
139
- if (!vetaSubagenteNormal(e) || !(await hayEncargos($))) return next(e);
140
- return { deny: MENSAJE_ENCARGO };
141
- });
142
-
143
91
  // Mientras se escribe: la recomendación aparece antes de pulsar Enter, cuando todavía se puede cambiar
144
- // de modelo o delegar. Parte de la del último mensaje enviado, para que «ok, dale» la conserve.
92
+ // de modelo. Parte de la del último mensaje enviado, para que «ok, dale» la conserve.
145
93
  on('prompt.edit', async ($, e, next) => {
146
94
  const r = await next(e);
147
95
  try {
148
- estado.borrador = r?.text ?? '';
149
96
  const nueva = recomendarPorTexto(r?.text ?? '', estado.enviada);
150
- const cambioCache = await medirCacheFria($, estado);
151
- if (cambioCache || !mismaRecomendacion(nueva, estado.recommendation)) {
97
+ if (!mismaRecomendacion(nueva, estado.recommendation)) {
152
98
  estado.recommendation = nueva;
153
99
  $.ui.invalidate('ui.render');
154
100
  }
@@ -159,40 +105,13 @@ export function register(on) {
159
105
  });
160
106
 
161
107
  on('prompt.submit', async ($, e, next) => {
162
- // Lo que envía el propio botón no es un mensaje de la persona: no cambia la recomendación ni «el último mensaje».
163
- if (estado.enviando && e.origin?.kind === 'plugin') return next(e);
164
- estado.delegado = false;
165
- estado.ultimoTexto = e.text;
166
- estado.borrador = '';
167
108
  estado.recommendation = recomendarPorTexto(e.text, estado.enviada);
168
109
  estado.enviada = estado.recommendation;
169
- await medirCacheFria($, estado);
170
- // Turnos seguidos de rutina en un modelo más caro del que hace falta: al quinto se propone sesión nueva.
171
- const limite = Math.max(-1, ...(estado.usage?.rateLimits ?? []).map((l) => (Number.isFinite(l?.percentUsed) ? l.percentUsed : -1)));
172
- const necesaria = ajustarPorLimite(estado.recommendation, limite < 0 ? undefined : limite);
173
- estado.rutinaSeguidas = estado.model && !necesaria.delegar && rango(necesaria.model) < rango(estado.model) ? estado.rutinaSeguidas + 1 : 0;
174
110
  for (const [id, a] of agentes) if (['completed', 'idle', 'failed', 'killed'].includes(a.status)) agentes.delete(id);
175
111
  $.ui.invalidate('ui.render');
176
112
  return next(e);
177
113
  });
178
114
 
179
- // Solo un turno real de la sesión principal oculta el botón (un envío que no llega a empezar turno no lo deja bloqueado).
180
- on('turn.start', async ($, e, next) => {
181
- if (!e.agentId) {
182
- estado.turnoActivo = true;
183
- estado.turnoId = e.turnId ?? null;
184
- $.ui.invalidate('ui.render');
185
- }
186
- return next(e);
187
- });
188
-
189
- // El turno de la sesión principal se interrumpió: el botón de delegar puede volver, y también reintentarse.
190
- // turn.abort solo trae el id del turno: un subagente aborta el suyo, que no es el principal.
191
- on('turn.abort', async ($, e, next) => {
192
- if (alAbortarTurno(estado, e)) $.ui.invalidate('ui.render');
193
- return next(e);
194
- });
195
-
196
115
  on('turn.step', async function* ($, e, next) {
197
116
  if (!e.agentId) {
198
117
  // El último esfuerzo visto se conserva entre turnos; el siguiente paso lo corrige si cambió.
@@ -227,11 +146,8 @@ export function register(on) {
227
146
  on('turn.complete', async ($, e, next) => {
228
147
  const r = await next(e);
229
148
  if (!e.agentId) {
230
- estado.turnoActivo = false;
231
- estado.turnoId = null;
232
149
  // Solo la sesión principal: cada subagente tiene su propia caché y no toca la de la sesión.
233
150
  sumarCache(estado, r?.usage);
234
- await marcarActividad($, estado);
235
151
  await refrescar($, estado, { usage: true });
236
152
  if (agentes.size > 0) await sincronizarAgentes($, agentes);
237
153
  }
@@ -240,45 +156,8 @@ export function register(on) {
240
156
 
241
157
  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
242
158
  if (e.props?.hasSurvey || !estado.model) return next(e);
243
- const { Box, Text, Button } = $.ui.resolve(e);
244
- // El botón solo en la app de escritorio, sin turno en curso, sin pulsar ya y con la caja vacía o con el mismo
245
- // texto del último mensaje: se delega «mi mensaje anterior», así que ni la recomendación ni el texto
246
- // pueden ser de otro borrador.
247
- const borrador = estado.borrador.trim();
248
- const hayBoton = Boolean(Button) && e.surface === 'desktop' && !estado.turnoActivo && !estado.delegado
249
- && Boolean(estado.enviada) && (borrador === '' || borrador === estado.ultimoTexto?.trim())
250
- && (estado.recommendation === estado.enviada || mismaRecomendacion(estado.recommendation, estado.enviada));
251
- const tramos = segmentosDeBarra(estado).map((s, i) => {
252
- if (hayBoton && s.accion === 'delegar') {
253
- const nivel = s.nivel;
254
- return h(Button, {
255
- key: 'delegar',
256
- label: s.etiqueta,
257
- variant: 'primary',
258
- onPress: async () => {
259
- if (estado.delegado || estado.turnoActivo || estado.enviando) return;
260
- Object.assign(estado, { delegado: true, turnoActivo: true, enviando: true });
261
- $.ui.invalidate('ui.render');
262
- try {
263
- const r = await $.prompt.submit({ text: instruccionDeDelegar(nivel) });
264
- if (r?.drop !== undefined) throw new Error(r.drop);
265
- } catch {
266
- // El envío no empezó: se devuelve el botón y se avisa para poder reintentar.
267
- Object.assign(estado, { delegado: false, turnoActivo: false });
268
- try {
269
- $.ui.toast('No se pudo enviar la delegación. Pulsa el botón de nuevo para reintentar.', { timeoutMs: 8000 });
270
- } catch {
271
- // Sin aviso, el botón vuelve igual.
272
- }
273
- } finally {
274
- estado.enviando = false;
275
- $.ui.invalidate('ui.render');
276
- }
277
- },
278
- });
279
- }
280
- return h(Text, { key: String(i), color: s.color, dimColor: s.dim, bold: s.bold }, s.text);
281
- });
159
+ const { Box, Text } = $.ui.resolve(e);
160
+ const tramos = segmentosDeBarra(estado).map((s, i) => h(Text, { key: String(i), color: s.color, dimColor: s.dim, bold: s.bold }, s.text));
282
161
  const linea = (partes, clave) => h(Box, { key: clave, flexDirection: 'row' },
283
162
  ...partes.map((s, i) => h(Text, { key: String(i), color: s.color, dimColor: s.dim, bold: s.bold }, s.text)));
284
163
  const subagentes = [...agentes.values()];
@@ -299,7 +178,7 @@ export function register(on) {
299
178
 
300
179
  on('session.end', async ($, e, next) => {
301
180
  agentes.clear();
302
- Object.assign(estado, { model: null, effort: null, modeloDelEsfuerzo: null, recommendation: null, enviada: null, usage: null, cache: cacheVacia(), ultimaActividad: null, cacheFria: false, rutinaSeguidas: 0, turnoActivo: false, turnoId: null, delegado: false, enviando: false, ultimoTexto: null, borrador: '' });
181
+ Object.assign(estado, estadoInicial());
303
182
  return next(e);
304
183
  });
305
184
  }
@@ -97,256 +97,57 @@ describe('nexakit-modelo API', () => {
97
97
  expect(await pintar($)).not.toContain('↳');
98
98
  });
99
99
 
100
- // Botón para delegar: la sesión tiene 50 % de contexto, así que un mensaje difícil desde Sonnet recomienda delegar
101
- // en nivel-alto y uno mecánico desde Opus en nivel-ligero (sin cambiar de modelo, que costaría releer el contexto).
102
- const prepararBoton = ($: any, on: any, modelo = 'claude-opus-5-5', extra: { avisos?: string[]; falla?: { valor: boolean } } = {}) => {
103
- const enviados: { text: string; plugin: boolean }[] = [];
100
+ // Modo completo: la barra solo informa. No hay botón de delegar ni veto a ningún subagente.
101
+ const prepararSesion = ($: any, on: any, modelo = 'claude-sonnet-5-5') => {
102
+ const lanzados: string[] = [];
104
103
  on('session.start', ($: any, e: any) => ({ cwd: e.cwd }));
105
104
  on('session.model', () => ({ value: modelo }));
106
- on('session.usage', () => ({ value: { context: { percent: 50, tokens: 100000 }, rateLimits: [] } }));
105
+ on('session.usage', () => ({ value: { context: { percent: 50, tokens: 100000 }, rateLimits: [{ kind: 'five_hour', percentUsed: 95 }] } }));
107
106
  on('turn.start', ($: any, e: any) => ({ text: e.text, turnId: e.turnId }));
108
107
  on('turn.complete', ($: any, e: any) => ({ text: e.answer }));
109
- on('turn.abort', () => undefined);
110
108
  on('clock.now', () => ({ value: Date.now() }));
111
109
  on('tool.register', ($: any, e: any) => ({ value: { tool: e.name } }));
112
110
  on('env.get', () => ({ value: undefined }));
113
- on('ui.toast', (_: any, e: any) => {
114
- extra.avisos?.push(e.text);
115
- return { value: undefined };
116
- });
117
- on('prompt.edit', ($: any, e: any) => {
118
- const text = e.text.slice(0, e.start) + e.inputText + e.text.slice(e.end);
119
- return { text, cursor: e.start + e.inputText.length };
120
- });
121
- on('prompt.submit', ($: any, e: any) => {
122
- if (extra.falla?.valor && e.origin?.kind === 'plugin') return { drop: 'bloqueado' };
123
- enviados.push({ text: e.text, plugin: e.origin?.kind === 'plugin' });
124
- return { text: e.text, origin: e.origin };
111
+ on('prompt.submit', ($: any, e: any) => ({ text: e.text, origin: e.origin }));
112
+ on('tool.list', () => ({ value: [{ name: 'Agent', description: 'subagentes', mcp: false }, { name: 'mcp__nexakit-fabrica__fabrica_encargar', description: 'encargar', mcp: true }] }));
113
+ on('tool.call', ($: any, e: any) => {
114
+ lanzados.push(`${e.agentId ?? 'main'}:${e.subagent_type}`);
115
+ return { result: 'lanzado' };
125
116
  });
126
- return enviados;
117
+ return lanzados;
127
118
  };
128
- const MENSAJES = {
129
- 'nivel-ligero': 'haz commit y push',
130
- 'nivel-alto': 'el login sigue fallando y no sé por qué',
131
- } as const;
132
119
  const BARRA = (surface: string) => ({ plugin: 'nexakit-modelo', surface, component: 'AbovePrompt', props: { hasSurvey: false } }) as any;
133
- const turno = async ($: any, sufijo: string) => {
134
- await $.turn.start({ text: 'x', turnId: `t${sufijo}` });
135
- await $.turn.complete({ answer: 'ok', durationMs: 1, isAborted: false, turnId: `t${sufijo}`, reason: 'answer' });
136
- };
137
120
 
138
- test('en el escritorio la sugerencia de delegar es un botón y envía la instrucción de su nivel', async ($, on) => {
139
- const enviados = prepararBoton($, on);
121
+ test('en el escritorio no hay botón de delegar: la barra solo informa', async ($, on) => {
122
+ prepararSesion($, on);
140
123
  await $.session.start({ surface: 'desktop', isInteractive: true, cwd: '/test' });
141
- await $.prompt.submit({ text: MENSAJES['nivel-ligero'] });
142
- await turno($, '1');
143
- const ui = await $.ui.mount(BARRA('desktop'));
144
- const boton = await ui.find({ type: 'Button' });
145
- expect(boton?.props.label).toBe('→ delega: nivel-ligero');
146
- await ui.press({ key: 'delegar' });
147
- const enviado = enviados.at(-1)!;
148
- expect(enviado.plugin).toBe(true);
149
- expect(enviado.text).toContain('fabrica_encargar en Codex o Antigravity');
150
- expect(enviado.text).toContain('niveles:nivel-ligero');
151
- await ui.unmount();
152
- });
153
-
154
- test('para nivel-alto el botón delega directo en el subagente', async ($, on) => {
155
- // Desde Sonnet con contexto lleno, subir a Opus releería todo: se delega.
156
- const enviados = prepararBoton($, on, 'claude-sonnet-5-5');
157
- await $.session.start({ surface: 'desktop', isInteractive: true, cwd: '/test' });
158
- await $.prompt.submit({ text: MENSAJES['nivel-alto'] });
159
- await turno($, '1');
160
- const ui = await $.ui.mount(BARRA('desktop'));
161
- expect((await ui.find({ type: 'Button' }))?.props.label).toBe('→ delega: nivel-alto');
162
- await ui.press({ key: 'delegar' });
163
- expect(enviados.at(-1)!.text).toBe('Delega la tarea de mi mensaje anterior en el subagente niveles:nivel-alto y comprueba su informe.');
164
- await ui.unmount();
165
- });
166
-
167
- test('en la terminal la sugerencia sigue siendo texto', async ($, on) => {
168
- prepararBoton($, on);
169
- await $.session.start({ surface: 'terminal', isInteractive: true, cwd: '/test' });
170
- await $.prompt.submit({ text: MENSAJES['nivel-ligero'] });
171
- await turno($, '1');
172
- const ui = await $.ui.mount(BARRA('terminal'));
173
- expect(await ui.find({ type: 'Button' })).toBeUndefined();
174
- expect(await pintar($)).toContain('→ delega: nivel-ligero');
175
- await ui.unmount();
176
- });
177
-
178
- test('durante un turno en curso de la sesión principal no hay botón; un envío que no empieza turno no lo oculta', async ($, on) => {
179
- prepararBoton($, on);
180
- await $.session.start({ surface: 'desktop', isInteractive: true, cwd: '/test' });
181
- await $.prompt.submit({ text: MENSAJES['nivel-ligero'] });
182
- // El envío por sí solo no es un turno: el botón sigue (si el envío fallara, no quedaría bloqueado).
183
- const sinTurno = await $.ui.mount(BARRA('desktop'));
184
- expect(await sinTurno.find({ type: 'Button' })).toBeDefined();
185
- await sinTurno.unmount();
186
- await $.turn.start({ text: 'x', turnId: 't1' });
187
- const ui = await $.ui.mount(BARRA('desktop'));
188
- expect(await ui.find({ type: 'Button' })).toBeUndefined();
189
- await ui.unmount();
190
- await $.turn.complete({ answer: 'ok', durationMs: 1, isAborted: false, turnId: 't1', reason: 'answer' });
191
- const despues = await $.ui.mount(BARRA('desktop'));
192
- expect(await despues.find({ type: 'Button' })).toBeDefined();
193
- await despues.unmount();
194
- });
195
-
196
- test('sin mensaje previo de la persona no hay botón', async ($, on) => {
197
- prepararBoton($, on);
198
- await $.session.start({ surface: 'desktop', isInteractive: true, cwd: '/test' });
199
- const ui = await $.ui.mount(BARRA('desktop'));
200
- expect(await ui.find({ type: 'Button' })).toBeUndefined();
201
- await ui.unmount();
202
- });
203
-
204
- test('tras pulsar el botón no se puede enviar dos veces', async ($, on) => {
205
- const enviados = prepararBoton($, on);
206
- await $.session.start({ surface: 'desktop', isInteractive: true, cwd: '/test' });
207
- await $.prompt.submit({ text: MENSAJES['nivel-ligero'] });
208
- await turno($, '1');
209
- const ui = await $.ui.mount(BARRA('desktop'));
210
- await ui.press({ key: 'delegar' });
211
- await ui.unmount();
212
- const antes = enviados.length;
213
- // El turno de la delegación termina y el botón sigue sin volver para el mismo mensaje.
214
- await turno($, '2');
215
- const otra = await $.ui.mount(BARRA('desktop'));
216
- expect(await otra.find({ type: 'Button' })).toBeUndefined();
217
- expect(enviados).toHaveLength(antes);
218
- await otra.unmount();
219
- });
220
-
221
- test('el envío del botón no cambia el último mensaje de la persona', async ($, on) => {
222
- const enviados = prepararBoton($, on);
223
- await $.session.start({ surface: 'desktop', isInteractive: true, cwd: '/test' });
224
- await $.prompt.submit({ text: MENSAJES['nivel-ligero'] });
225
- await turno($, '1');
226
- const ui = await $.ui.mount(BARRA('desktop'));
227
- await ui.press({ key: 'delegar' });
228
- await ui.unmount();
229
- // «ok, dale» hereda la recomendación del último mensaje: si la instrucción del botón la hubiera cambiado, no saldría ligero.
230
- await $.prompt.submit({ text: 'ok, dale' });
231
- await turno($, '2');
232
- const otra = await $.ui.mount(BARRA('desktop'));
233
- expect((await otra.find({ type: 'Button' }))?.props.label).toBe('→ delega: nivel-ligero');
234
- expect(enviados.map((x) => x.plugin)).toEqual([false, true, false]);
235
- await otra.unmount();
236
- });
237
-
238
- test('si el envío del botón falla, avisa en español y el botón vuelve para reintentar', async ($, on) => {
239
- const avisos: string[] = [];
240
- const falla = { valor: true };
241
- const enviados = prepararBoton($, on, 'claude-opus-5-5', { avisos, falla });
242
- await $.session.start({ surface: 'desktop', isInteractive: true, cwd: '/test' });
243
- await $.prompt.submit({ text: MENSAJES['nivel-ligero'] });
244
- await turno($, '1');
245
- const ui = await $.ui.mount(BARRA('desktop'));
246
- await ui.press({ key: 'delegar' });
247
- expect(avisos).toHaveLength(1);
248
- expect(avisos[0]).toContain('reintentar');
249
- expect(enviados).toHaveLength(1);
250
- expect((await ui.find({ type: 'Button' }))?.props.label).toBe('→ delega: nivel-ligero');
251
- falla.valor = false;
252
- await ui.press({ key: 'delegar' });
253
- expect(enviados).toHaveLength(2);
254
- expect(enviados[1]!.plugin).toBe(true);
255
- await ui.unmount();
256
- });
257
-
258
- test('un borrador con otro texto oculta el botón aunque la recomendación sea la misma; vacío o igual lo conserva', async ($, on) => {
259
- prepararBoton($, on);
260
- await $.session.start({ surface: 'desktop', isInteractive: true, cwd: '/test' });
261
- await $.prompt.submit({ text: MENSAJES['nivel-ligero'] });
262
- await turno($, '1');
263
- const editar = (text: string, inputText: string) => $.prompt.edit({ origin: { kind: 'composer' }, text, cursor: text.length, start: 0, end: text.length, inputText });
264
- const hayBoton = async () => {
124
+ for (const text of ['haz commit y push', 'el login sigue fallando y no sé por qué']) {
125
+ await $.prompt.submit({ text });
126
+ await $.turn.start({ text, turnId: 't1' });
127
+ await $.turn.complete({ answer: 'ok', durationMs: 1, isAborted: false, turnId: 't1', reason: 'answer' });
265
128
  const ui = await $.ui.mount(BARRA('desktop'));
266
- const boton = await ui.find({ type: 'Button' });
267
- await ui.unmount();
268
- return boton !== undefined;
269
- };
270
- expect(await hayBoton()).toBe(true);
271
- // «ok, dale» conserva la recomendación del último mensaje, pero es otro texto.
272
- await editar('', 'ok, dale');
273
- expect(await hayBoton()).toBe(false);
274
- await editar('ok, dale', '');
275
- expect(await hayBoton()).toBe(true);
276
- await editar('', ` ${MENSAJES['nivel-ligero']} `);
277
- expect(await hayBoton()).toBe(true);
278
- });
279
-
280
- test('el botón solo aparece en la app de escritorio, no en otras superficies con botones', async ($, on) => {
281
- prepararBoton($, on);
282
- await $.session.start({ surface: 'desktop', isInteractive: true, cwd: '/test' });
283
- await $.prompt.submit({ text: MENSAJES['nivel-ligero'] });
284
- await turno($, '1');
285
- for (const surface of ['mobile', 'vscode', 'terminal'] as const) {
286
- const ui = await $.ui.mount(BARRA(surface));
287
129
  expect(await ui.find({ type: 'Button' })).toBeUndefined();
288
130
  await ui.unmount();
131
+ expect(await pintar($)).not.toContain('delega');
289
132
  }
290
- const escritorio = await $.ui.mount(BARRA('desktop'));
291
- expect(await escritorio.find({ type: 'Button' })).toBeDefined();
292
- await escritorio.unmount();
293
- });
294
-
295
- // Guarda de subagentes: la implementación de nivel normal se encarga primero con fabrica_encargar.
296
- const prepararAgentes = ($: any, on: any, { conEncargos = true, listaFalla = false } = {}) => {
297
- const lanzados: string[] = [];
298
- on('session.start', ($: any, e: any) => ({ cwd: e.cwd }));
299
- on('session.model', () => ({ value: 'claude-opus-5-5' }));
300
- on('tool.register', ($: any, e: any) => ({ value: { tool: e.name } }));
301
- on('tool.list', () => {
302
- if (listaFalla) throw new Error('sin lista');
303
- const base = [{ name: 'Agent', description: 'subagentes', mcp: false }];
304
- return { value: conEncargos ? [...base, { name: 'mcp__nexakit-fabrica__fabrica_encargar', description: 'encargar', mcp: true }] : base };
305
- });
306
- on('tool.call', ($: any, e: any) => {
307
- lanzados.push(`${e.agentId ?? 'main'}:${e.subagent_type}`);
308
- return { result: 'lanzado' };
309
- });
310
- return lanzados;
311
- };
312
- const agente = (extra: object) => ({ tool: 'Agent', description: 'implementar exportación', prompt: 'Añade el botón de exportar.', subagent_type: 'niveles:nivel-normal', ...extra }) as any;
313
-
314
- test('el subagente niveles:nivel-normal se veta con el mensaje de encargar primero', async ($, on) => {
315
- const lanzados = prepararAgentes($, on);
316
- await $.session.start({ surface: 'desktop', isInteractive: true, cwd: '/test' });
317
- const r: any = await $.tool.call(agente({}));
318
- expect(r.deny).toContain('Primero encarga esta implementación con fabrica_encargar (Codex o Antigravity): ahorra tokens de Claude.');
319
- expect(r.deny).toContain('[sin encargo]');
320
- expect(lanzados).toHaveLength(0);
321
- });
322
-
323
- test('con la marca [sin encargo] en la descripción o en el prompt el subagente normal pasa', async ($, on) => {
324
- const lanzados = prepararAgentes($, on);
325
- await $.session.start({ surface: 'desktop', isInteractive: true, cwd: '/test' });
326
- expect((await $.tool.call(agente({ description: 'implementar [sin encargo]' }))).deny).toBeUndefined();
327
- expect((await $.tool.call(agente({ prompt: 'Contexto. [Sin encargo] porque el encargo falló.' }))).deny).toBeUndefined();
328
- expect(lanzados).toHaveLength(2);
329
133
  });
330
134
 
331
- test('no se veta nada más: ligero, exigente, alto, otros agentes, sin tipo ni subagentes de subagentes', async ($, on) => {
332
- const lanzados = prepararAgentes($, on);
333
- await $.session.start({ surface: 'desktop', isInteractive: true, cwd: '/test' });
334
- for (const subagent_type of ['niveles:nivel-ligero', 'niveles:nivel-exigente', 'niveles:nivel-alto', 'niveles:investigador', 'Explore', undefined])
335
- expect((await $.tool.call(agente({ subagent_type }))).deny).toBeUndefined();
336
- // Un subagente que lanza otro normal: el veto es solo de la sesión principal.
337
- expect((await $.tool.call(agente({ agentId: 'a1' }))).deny).toBeUndefined();
338
- expect(lanzados).toHaveLength(7);
339
- });
340
-
341
- test('sin la herramienta fabrica_encargar no se veta; si no se puede saber, se veta igual', async ($, on) => {
342
- prepararAgentes($, on, { conEncargos: false });
343
- await $.session.start({ surface: 'desktop', isInteractive: true, cwd: '/test' });
344
- expect((await $.tool.call(agente({}))).deny).toBeUndefined();
135
+ test('un fallo difícil propone subir a Opus, aunque haya mucho contexto y el límite de uso esté alto', async ($, on) => {
136
+ prepararSesion($, on);
137
+ await $.session.start({ surface: 'terminal', isInteractive: true, cwd: '/test' });
138
+ await $.prompt.submit({ text: 'el login sigue fallando y no sé por qué' });
139
+ await $.turn.start({ text: 'x', turnId: 't1' });
140
+ await $.turn.complete({ answer: 'ok', durationMs: 1, isAborted: false, turnId: 't1', reason: 'answer' });
141
+ expect(await pintar($)).toContain('→ Opus · high');
345
142
  });
346
143
 
347
- test('si la lista de herramientas falla, se veta igual', async ($, on) => {
348
- prepararAgentes($, on, { listaFalla: true });
144
+ test('ningún subagente se veta: tampoco niveles:nivel-normal sin la marca [sin encargo]', async ($, on) => {
145
+ const lanzados = prepararSesion($, on, 'claude-opus-5-5');
349
146
  await $.session.start({ surface: 'desktop', isInteractive: true, cwd: '/test' });
350
- expect((await $.tool.call(agente({}))).deny).toContain('fabrica_encargar');
147
+ for (const subagent_type of ['niveles:nivel-normal', 'niveles:nivel-ligero', 'niveles:nivel-alto', 'Explore']) {
148
+ const r: any = await $.tool.call({ tool: 'Agent', description: 'implementar exportación', prompt: 'Añade el botón de exportar.', subagent_type } as any);
149
+ expect(r.deny).toBeUndefined();
150
+ }
151
+ expect(lanzados).toHaveLength(4);
351
152
  });
352
153
  });
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nexakit-sesion",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "Avisa cuándo conviene cerrar la sesión y abrir otra, sin cerrarla por ti.",
5
5
  "author": {
6
6
  "name": "Juan Jaller"
@@ -26,7 +26,7 @@ export function mensajeDeAviso(nivel, percent) {
26
26
  return undefined;
27
27
  }
28
28
 
29
- // Cuota de 5 horas: a partir de aquí los subagentes en paralelo agotan el límite antes de terminar.
29
+ // Cuota de 5 horas: a partir de estos umbrales el modelo lo sabe, solo como información.
30
30
  export const CUOTA_SERIE = 70;
31
31
  export const CUOTA_CRITICA = 90;
32
32
 
@@ -38,12 +38,11 @@ export function nivelDeCuota(usage) {
38
38
  return 0;
39
39
  }
40
40
 
41
- // Nota para el modelo, no para la persona: va al final del mensaje solo al cambiar de nivel.
41
+ // Nota para el modelo, no para la persona: va al final del mensaje solo al cambiar de nivel. Modo completo
42
+ // (0.14.0): solo informa del porcentaje; no ordena serializar subagentes ni rebajar niveles.
42
43
  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;
44
+ if (nivel !== 1 && nivel !== 2) return undefined;
45
+ return `[nexakit: cuota de 5 h al ${entero(percent)} %.]`;
47
46
  }
48
47
 
49
48
  // Lo que el resumen de una compactación debe conservar para poder seguir la tarea sin releer todo.
@@ -20,7 +20,7 @@ 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.
23
+ // Con la cuota de 5 h alta, el modelo lo sabe una vez por nivel (solo el porcentaje, sin órdenes).
24
24
  on('prompt.submit', async ($, e, next) => {
25
25
  try {
26
26
  const usage = await $.session.usage();
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "niveles",
3
- "version": "0.3.1",
4
- "description": "Agentes por nivel (ligero, normal, exigente, alto) con modelo y esfuerzo fijos para delegar sin cambiar /model, y especialistas por tarea con tope de pasos: investigador, revisor de calidad, cierre de memoria, subir al repo, sincronizador de documentación y cazador de pruebas intermitentes.",
3
+ "version": "0.4.0",
4
+ "description": "Agentes por nivel con capacidad completa (ligero sonnet medium, normal sonnet high, exigente opus high, alto opus xhigh), sin tope de turnos, y especialistas por tarea: investigador, revisor de calidad, cierre de memoria, subir al repo, sincronizador de documentación y cazador de pruebas intermitentes.",
5
5
  "author": {
6
6
  "name": "Juan Jaller"
7
7
  }
@@ -2,9 +2,7 @@
2
2
  name: cazador-de-flakes
3
3
  description: Averigua si un fallo del CI es intermitente mirando el historial de ejecuciones y con qué frecuencia. Úsalo cuando una prueba falle en un sistema y no tenga relación con el cambio.
4
4
  model: sonnet
5
- effort: medium
6
- maxTurns: 20
7
- omitClaudeMd: true
5
+ effort: high
8
6
  tools: Bash, Read, Grep
9
7
  ---
10
8
 
@@ -15,5 +13,4 @@ Eres el cazador de pruebas intermitentes: la sesión principal te da un fallo de
15
13
  - Mira las últimas 30 ejecuciones de la rama principal y de otros PR: cuántas veces falló esa prueba sobre el total, en qué sistemas, y si pasó en la ejecución hermana del mismo commit.
16
14
  - Lee solo la parte fallida del log (`--log-failed`, filtrando por el nombre de la prueba). Nunca vuelques un log entero.
17
15
  - Termina con un veredicto: INTERMITENTE (falla y pasa con el mismo código), REGRESIÓN (falla siempre desde un commit concreto) o SIN DATOS. Añade la evidencia (ejecuciones con su enlace) y si relanzar una sola vez es razonable.
18
- - Informe en español de máximo 200 palabras: el veredicto primero y después las cifras.
19
- - Una orden por llamada al shell. Usa rutas absolutas en lugar de `cd`. No encadenes con `;`, `&&` ni `||`, y no uses paréntesis ni subshells `( … )`. Un `|` hacia `head`, `tail` o `grep` está permitido. Para leer y buscar, usa las herramientas de lectura y búsqueda en lugar de `cat`, `grep` o `ls` cuando existan. Las llamadas independientes se lanzan en paralelo, no encadenadas.
16
+ - Informe en español: el veredicto primero y después las cifras.