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.
Files changed (64) hide show
  1. package/.claude-plugin/marketplace.json +10 -5
  2. package/README.md +20 -4
  3. package/assets/runtime/package-lock.json +2 -2
  4. package/catalogs/generadores.json +936 -0
  5. package/package.json +1 -1
  6. package/plugins/nexakit-ahorro/.claude-plugin/plugin.json +1 -0
  7. package/plugins/nexakit-ahorro/README.md +13 -0
  8. package/plugins/nexakit-ahorro/hooks/compactar.js +39 -0
  9. package/plugins/nexakit-ahorro/hooks/hooks.json +1 -0
  10. package/plugins/nexakit-ahorro/hooks/register.js +32 -0
  11. package/plugins/nexakit-lecciones/.claude-plugin/plugin.json +1 -0
  12. package/plugins/nexakit-lecciones/README.md +19 -0
  13. package/plugins/nexakit-lecciones/hooks/hooks.json +1 -0
  14. package/plugins/nexakit-lecciones/hooks/lecciones.js +39 -0
  15. package/plugins/nexakit-lecciones/hooks/register.js +61 -0
  16. package/plugins/nexakit-modelo/.claude-plugin/plugin.json +1 -1
  17. package/plugins/nexakit-modelo/hooks/barra.js +72 -0
  18. package/plugins/nexakit-modelo/hooks/recomendar.js +27 -0
  19. package/plugins/nexakit-modelo/hooks/register.js +73 -17
  20. package/plugins/nexakit-modelo/hooks/umbrales.js +3 -0
  21. package/plugins/nexakit-modelo/tests/register.test.ts +1 -1
  22. package/plugins/nexakit-sesion/.claude-plugin/plugin.json +1 -1
  23. package/plugins/nexakit-sesion/README.md +3 -3
  24. package/plugins/nexakit-sesion/hooks/aviso.js +28 -11
  25. package/plugins/nexakit-sesion/hooks/register.js +30 -2
  26. package/plugins/nexakit-sesion/tests/register.test.ts +3 -16
  27. package/plugins/niveles/agents/nivel-alto.md +3 -3
  28. package/plugins/niveles/agents/nivel-exigente.md +3 -3
  29. package/plugins/niveles/agents/nivel-ligero.md +3 -3
  30. package/plugins/niveles/agents/nivel-normal.md +3 -3
  31. package/schemas/generators.schema.json +299 -0
  32. package/skills/quality-gate/SKILL.md +1 -1
  33. package/skills/revisar/SKILL.md +46 -6
  34. package/src/clean-command.js +29 -0
  35. package/src/clean-project-flow.js +105 -0
  36. package/src/clean-project.js +431 -0
  37. package/src/cli-executable.js +1 -1
  38. package/src/gemini-files.js +3 -3
  39. package/src/gemini-tools.js +23 -8
  40. package/src/generators-catalog.js +63 -0
  41. package/src/level-agents.js +4 -3
  42. package/src/project-root.js +21 -2
  43. package/src/project-signals.js +6 -0
  44. package/src/redact.js +9 -0
  45. package/src/review-instructions.js +18 -29
  46. package/src/setup-state.js +7 -0
  47. package/src/setup-tui.js +98 -6
  48. package/src/skill-recommendations.js +25 -2
  49. package/src/toolkit-cli.js +0 -4
  50. package/src/toolkit-commands-guide.js +1 -1
  51. package/src/toolkit-setup.js +2 -2
  52. package/plugins/nexakit-modelo/hooks/status.js +0 -8
  53. package/plugins/nexakit-panel/.claude-plugin/plugin.json +0 -1
  54. package/plugins/nexakit-panel/README.md +0 -20
  55. package/plugins/nexakit-panel/hooks/hooks.json +0 -1
  56. package/plugins/nexakit-panel/hooks/lienzo.js +0 -382
  57. package/plugins/nexakit-panel/hooks/panel.js +0 -279
  58. package/plugins/nexakit-panel/hooks/register.tsx +0 -248
  59. package/plugins/nexakit-panel/tests/lienzo.test.ts +0 -142
  60. package/plugins/nexakit-panel/tests/panel.test.ts +0 -240
  61. package/plugins/nexakit-panel/tests/register.test.ts +0 -167
  62. package/plugins/nexakit-panel/types/index.d.ts +0 -41
  63. package/skills/revision-cruzada/SKILL.md +0 -59
  64. package/src/panel-cli.js +0 -182
@@ -1,382 +0,0 @@
1
- // Dibuja la orquesta carácter a carácter, en posiciones fijas, como una pantalla de terminal de 104 columnas.
2
- // Devuelve filas de tramos con estilo; la terminal (nexakit panel) y el panel de Claude los pintan igual.
3
- import {
4
- alias, barra, barraEsfuerzo, duracion, estadoPorFamilia, etiquetaEnjambre, etiquetaModelo, familia, hora,
5
- resumenDelegacion, tituloDeOrquesta, tokens,
6
- } from './panel.js';
7
-
8
- export const ANCHO = 104;
9
- export const COLOR = {
10
- sonnet: '#fb923c', haiku: '#60a5fa', opus: '#a78bfa', fable: '#f472b6', otro: '#9ca3af',
11
- ok: '#4ade80', error: '#f87171', texto: '#e5e7eb', tenue: '#6b7280', resalte: '#2e2a4a',
12
- codex: '#2dd4bf', antigravity: '#fbbf24', claude: '#fb923c',
13
- };
14
- const NOMBRE_IA = { codex: 'Codex', antigravity: 'Antigravity', claude: 'Claude' };
15
- const colorIA = (ia) => COLOR[ia] ?? COLOR.otro;
16
- const REVISION = { x: 84, w: 20, h: 8 };
17
- const colorDe = (modelo) => COLOR[familia(modelo)] ?? COLOR.otro;
18
-
19
- // Geometría, tomada de la imagen de referencia.
20
- const CX = 66; // eje del flujo central
21
- const ASESOR = { x: 2, w: 26 };
22
- const LIDER = { w: 34, y: 4, h: 7 };
23
- const DELEGACION = { w: 52, y: 12, h: 7 };
24
- const SUB = { xs: [29, 54, 79], w: 24, y: 23, h: 8 };
25
- const VUELTA = { w: 40, y: 34, h: 4 };
26
- const REGISTRO_Y = 39;
27
-
28
- function lienzo(alto) {
29
- const celdas = Array.from({ length: alto }, () => Array.from({ length: ANCHO }, () => ({ ch: ' ' })));
30
- const poner = (x, y, txt, estilo = {}) => {
31
- [...String(txt)].forEach((ch, i) => {
32
- const xx = x + i;
33
- if (y >= 0 && y < alto && xx >= 0 && xx < ANCHO) celdas[y][xx] = { ch, ...estilo };
34
- });
35
- };
36
- const corto = (txt, ancho) => ([...String(txt)].length <= ancho ? String(txt) : `${[...String(txt)].slice(0, Math.max(0, ancho - 1)).join('')}…`);
37
- const centro = (x, w, y, txt, estilo) => {
38
- const t = corto(txt, w);
39
- poner(x + Math.floor((w - [...t].length) / 2), y, t, estilo);
40
- };
41
- const caja = (x, y, w, h, color, titulo) => {
42
- const borde = { c: color };
43
- poner(x, y, `┌${'─'.repeat(w - 2)}┐`, borde);
44
- for (let i = 1; i < h - 1; i++) { poner(x, y + i, '│', borde); poner(x + w - 1, y + i, '│', borde); }
45
- poner(x, y + h - 1, `└${'─'.repeat(w - 2)}┘`, borde);
46
- if (titulo) poner(x + 4, y, `┤ ${titulo} ├`, { c: COLOR.tenue });
47
- };
48
- return { celdas, poner, centro, caja, corto };
49
- }
50
-
51
- // Junta las celdas contiguas con el mismo estilo en tramos.
52
- function aTramos(celdas) {
53
- return celdas.map((fila) => {
54
- const tramos = [];
55
- for (const { ch, ...estilo } of fila) {
56
- const ultimo = tramos.at(-1);
57
- const clave = JSON.stringify(estilo);
58
- if (ultimo && ultimo.clave === clave) ultimo.t += ch;
59
- else tramos.push({ t: ch, ...estilo, clave });
60
- }
61
- return tramos.map(({ clave, ...resto }) => resto);
62
- });
63
- }
64
-
65
- export const texto = (filas) => filas.map((tramos) => tramos.map((x) => x.t).join(''));
66
-
67
- export function dibujar(estado, { ahora, uso, carpeta = '', filasMax, asesorModelo = null, esEjemplo = false, codex = null } = {}) {
68
- const s = estado;
69
- const vacio = s.pasos === 0 && s.agentes.length === 0 && s.registro.length === 0;
70
- const medidores = medidoresDeUso(uso);
71
-
72
- if (vacio) {
73
- const L = lienzo(codex ? 8 : 7);
74
- L.centro(0, ANCHO, 0, 'NEXAKIT · ORQUESTA', { c: COLOR.opus, b: true });
75
- L.poner(2, 1, '═'.repeat(ANCHO - 4), { c: COLOR.tenue });
76
- L.centro(0, ANCHO, 3, 'Aún no hay actividad en esta sesión.', { c: COLOR.texto });
77
- L.centro(0, ANCHO, 4, 'Trabaja con normalidad: este panel se llena solo.', { c: COLOR.tenue });
78
- if (medidores.length) pintarMedidores(L, 6, medidores);
79
- if (codex) pintarCodex(L, medidores.length ? 7 : 6, codex, ahora);
80
- return { filas: aTramos(L.celdas), ancho: ANCHO, alto: codex ? 8 : 7 };
81
- }
82
-
83
- // El registro ocupa lo que sobre: entre 1 y 8 líneas (4 por defecto, como la referencia).
84
- // Filas fijas: hasta el registro, sus dos bordes, una en blanco, la orden, el estado y el uso si lo hay.
85
- const lineaModelo = s.lider.modelo ? modeloFrenteARecomendado(s) : null;
86
- const fijas = REGISTRO_Y + 2 + 3 + (medidores.length ? 1 : 0) + (lineaModelo ? 1 : 0) + (codex ? 1 : 0);
87
- const lineasRegistro = Math.max(1, Math.min(8, filasMax ? filasMax - fijas : 4, s.registro.length || 1));
88
- const alto = fijas + lineasRegistro;
89
- const L = lienzo(alto);
90
- const r = resumenDelegacion(s.agentes);
91
- const lider = etiquetaModelo(s.lider.modelo);
92
- const cLider = colorDe(s.lider.modelo);
93
- const enjambre = etiquetaEnjambre(s.agentes);
94
- const cEnjambre = s.agentes.length ? colorDe([...s.agentes].reverse().find((a) => etiquetaModelo(a.modelo) === enjambre)?.modelo) : COLOR.haiku;
95
-
96
- // ---- Cabecera
97
- const titulo = tituloDeOrquesta(s);
98
- const x0 = Math.floor((ANCHO - [...titulo].length) / 2);
99
- let x = x0;
100
- for (const [i, parte] of titulo.split(' · ').entries()) {
101
- const sep = i === 0 ? '' : ' · ';
102
- L.poner(x, 0, sep, { c: COLOR.tenue }); x += sep.length;
103
- const color = /DIRIGE/.test(parte) ? cLider : /ENJAMBRE/.test(parte) ? cEnjambre : COLOR.texto;
104
- L.poner(x, 0, parte, { c: color, b: true }); x += [...parte].length;
105
- }
106
- L.poner(2, 1, '═'.repeat(ANCHO - 4), { c: COLOR.tenue });
107
- if (esEjemplo) L.centro(0, ANCHO, 3, 'EJEMPLO · datos ficticios para ver el diseño', { c: '#facc15', b: true });
108
- const leyenda = [];
109
- if (s.lider.modelo) leyenda.push([`${lider.toLowerCase()} · líder`, cLider]);
110
- if (enjambre) leyenda.push([`${enjambre.toLowerCase()} · enjambre`, cEnjambre]);
111
- leyenda.push(['delegación', COLOR.ok], ['asesor', COLOR.opus]);
112
- const revision = (s.revisiones ?? []).at(-1);
113
- if (revision) leyenda.push([`${revision.ia} · revisa`, colorIA(revision.ia)]);
114
- x = 4;
115
- for (const [txt, color] of leyenda) { L.poner(x, 2, '■', { c: color }); L.poner(x + 2, 2, txt, { c: COLOR.texto }); x += [...txt].length + 7; }
116
-
117
- // ---- Líder
118
- const lx = CX - LIDER.w / 2;
119
- L.caja(lx, LIDER.y, LIDER.w, LIDER.h, cLider);
120
- L.centro(lx + 1, LIDER.w - 2, LIDER.y + 1, `${lider} · sesión principal`, { c: cLider, b: true });
121
- L.centro(lx + 1, LIDER.w - 2, LIDER.y + 2, `pasos ${s.pasos} · herramientas ${s.lider.herramientas ?? 0}`, { c: COLOR.texto });
122
- L.centro(lx + 1, LIDER.w - 2, LIDER.y + 3, `leídos ${tokens(s.lider.leidos)} · escritos ${tokens(s.lider.escritos)}`, { c: COLOR.texto });
123
- const esf = `esfuerzo ${barraEsfuerzo(s.lider.esfuerzo)} ${s.lider.esfuerzo ?? ''}`.trimEnd();
124
- L.centro(lx + 1, LIDER.w - 2, LIDER.y + 4, esf, { c: COLOR.texto });
125
- L.centro(lx + 1, LIDER.w - 2, LIDER.y + 5, `--model ${alias(s.lider.modelo)}`, { c: COLOR.tenue });
126
-
127
- // ---- Revisión externa (a la derecha del líder)
128
- if (revision) {
129
- const c = colorIA(revision.ia);
130
- L.poner(lx + LIDER.w, LIDER.y + 3, '▶', { c });
131
- L.caja(REVISION.x, LIDER.y, REVISION.w, REVISION.h, c);
132
- const dentro = (y, txt, estilo) => L.centro(REVISION.x + 1, REVISION.w - 2, y, txt, estilo);
133
- dentro(LIDER.y + 1, 'REVISIÓN', { c, b: true });
134
- dentro(LIDER.y + 2, NOMBRE_IA[revision.ia] ?? revision.ia, { c });
135
- dentro(LIDER.y + 3, revision.respondio ?? revision.modelo ?? 'modelo ?', { c: COLOR.texto });
136
- dentro(LIDER.y + 4, revision.esfuerzo ? `esfuerzo ${revision.esfuerzo}` : '', { c: COLOR.tenue });
137
- const t = duracion((revision.fin ?? ahora) - revision.inicio);
138
- const est = revision.estado === 'lista' ? [`✓ lista · ${t}`, COLOR.ok] : revision.estado === 'error' ? ['✗ falló', COLOR.error] : [`◐ revisando ${t}`, c];
139
- dentro(LIDER.y + 5, est[0], { c: est[1] });
140
- const total = (revision.entrada ?? 0) + (revision.salida ?? 0);
141
- dentro(LIDER.y + 6, total ? `tokens ${tokens(total)}` : 'tokens —', { c: COLOR.tenue });
142
- }
143
-
144
- // ---- Delegación
145
- const dx = CX - DELEGACION.w / 2;
146
- L.poner(CX, LIDER.y + LIDER.h, '┊', { c: COLOR.tenue });
147
- L.caja(dx, DELEGACION.y, DELEGACION.w, DELEGACION.h, COLOR.ok);
148
- L.poner(dx + 2, DELEGACION.y + 1, 'DELEGACIÓN · subagentes', { c: COLOR.ok, b: true });
149
- L.poner(dx + DELEGACION.w - 3 - String(r.total).length, DELEGACION.y + 1, String(r.total), { c: COLOR.texto, b: true });
150
- const filaD = (y, nombre, n, color) => {
151
- L.poner(dx + 2, y, nombre, { c: COLOR.texto });
152
- L.poner(dx + 15, y, barra(r.total ? n / r.total : 0, 22), { c: color });
153
- L.poner(dx + 39, y, `${n}/${r.total}`, { c: COLOR.texto });
154
- };
155
- filaD(DELEGACION.y + 2, 'listos', r.listos, COLOR.ok);
156
- filaD(DELEGACION.y + 3, 'corriendo', r.corriendo, cEnjambre);
157
- filaD(DELEGACION.y + 4, 'con error', r.errores, COLOR.error);
158
- const tokSub = s.agentes.reduce((n, a) => n + a.leidos, 0);
159
- L.poner(dx + 2, DELEGACION.y + 5, `herramientas ${r.herramientas} · tokens leídos ${tokens(tokSub)}`, { c: COLOR.ok });
160
-
161
- // ---- Delegar y subagentes
162
- const dy = DELEGACION.y + DELEGACION.h;
163
- L.poner(CX, dy, '┊', { c: COLOR.tenue });
164
- const frase = `delegar a subagentes · ${enjambre ?? '—'}`;
165
- const fx = CX - Math.floor([...frase].length / 2);
166
- L.poner(fx, dy + 1, 'delegar a subagentes · ', { c: COLOR.texto });
167
- L.poner(fx + 'delegar a subagentes · '.length, dy + 1, enjambre ?? '—', { c: cEnjambre, b: true });
168
- const visibles = s.agentes.slice(-3);
169
- const centros = SUB.xs.slice(0, Math.max(1, visibles.length)).map((x1) => x1 + SUB.w / 2);
170
- const by = SUB.y - 2;
171
- if (visibles.length > 1) {
172
- L.poner(centros[0], by, `┌${'─'.repeat(centros.at(-1) - centros[0] - 1)}┐`, { c: COLOR.tenue });
173
- L.poner(CX, by, centros.includes(CX) ? '┴' : '┴', { c: COLOR.tenue });
174
- } else {
175
- L.poner(centros[0], by, '┊', { c: COLOR.tenue });
176
- }
177
- centros.forEach((cx, i) => L.poner(cx, by + 1, i === 1 ? '●' : '▼', { c: cEnjambre }));
178
- const totalSub = visibles.reduce((n, a) => n + a.leidos, 0);
179
- visibles.forEach((a, i) => {
180
- const x1 = SUB.xs[i];
181
- const c = colorDe(a.modelo);
182
- L.caja(x1, SUB.y, SUB.w, SUB.h, c);
183
- const dentro = (y, txt, estilo) => L.centro(x1 + 1, SUB.w - 2, y, txt, estilo);
184
- dentro(SUB.y + 1, a.nombre, { c: COLOR.texto, b: true });
185
- dentro(SUB.y + 2, etiquetaModelo(a.modelo), { c });
186
- const parte = totalSub ? a.leidos / totalSub : 0;
187
- L.poner(x1 + 2, SUB.y + 3, barra(parte, 13), { c, d: a.estado === 'corriendo' && parte === 0 });
188
- const pct = `${Math.round(parte * 100)}%`;
189
- L.poner(x1 + SUB.w - 2 - pct.length, SUB.y + 3, pct, { c: COLOR.texto });
190
- dentro(SUB.y + 4, a.ultimo || '—', { c: COLOR.texto });
191
- const est = a.estado === 'listo' ? ['✓ listo', COLOR.ok] : a.estado === 'error' ? ['✗ con error', COLOR.error] : ['◐ corriendo', c];
192
- dentro(SUB.y + 5, est[0], { c: est[1] });
193
- dentro(SUB.y + 6, `leídos ${tokens(a.leidos)} · ${duracion((a.fin ?? ahora) - a.inicio)}`, { c: COLOR.tenue });
194
- });
195
- if (s.agentes.length > visibles.length) L.poner(SUB.xs[0], SUB.y + SUB.h, `+${s.agentes.length - visibles.length} más`, { c: COLOR.tenue });
196
-
197
- // ---- Vuelta al líder
198
- const my = SUB.y + SUB.h;
199
- if (visibles.length > 1) {
200
- centros.forEach((cx) => L.poner(cx, my, '│', { c: COLOR.tenue }));
201
- L.poner(centros[0], my + 1, `└${'─'.repeat(centros.at(-1) - centros[0] - 1)}┘`, { c: COLOR.tenue });
202
- L.poner(CX, my + 1, '●', { c: COLOR.texto });
203
- } else {
204
- L.poner(centros[0], my, '┊', { c: COLOR.tenue });
205
- }
206
- L.poner(CX, my + 2, '┊', { c: COLOR.tenue });
207
- const vx = CX - VUELTA.w / 2;
208
- L.caja(vx, VUELTA.y, VUELTA.w, VUELTA.h, cLider);
209
- L.centro(vx + 1, VUELTA.w - 2, VUELTA.y + 1, `de vuelta en ${lider} · líder`, { c: cLider, b: true });
210
- L.centro(vx + 1, VUELTA.w - 2, VUELTA.y + 2, r.corriendo > 0 ? `esperando ${r.corriendo} ${r.corriendo === 1 ? 'subagente' : 'subagentes'}` : 'subagentes terminados', { c: COLOR.texto });
211
-
212
- // ---- Asesor (columna izquierda, de arriba a la vuelta al líder)
213
- const ay = LIDER.y;
214
- const ah = VUELTA.y + VUELTA.h - ay;
215
- L.caja(ASESOR.x, ay, ASESOR.w, ah, COLOR.opus);
216
- L.centro(ASESOR.x + 1, ASESOR.w - 2, ay + 1, asesorModelo ? etiquetaModelo(asesorModelo).toUpperCase() : 'ASESOR', { c: COLOR.opus, b: true });
217
- L.centro(ASESOR.x + 1, ASESOR.w - 2, ay + 2, s.asesor.llamadas > 0 ? 'asesor · consultado' : 'asesor · en espera', { c: COLOR.opus });
218
- const consultas = s.registro.filter((e) => e.quien === 'asesor').slice(-6);
219
- const primera = LIDER.y + 3;
220
- const ultima = VUELTA.y + 1;
221
- const filasC = consultas.length <= 1 ? [primera]
222
- : consultas.map((_, i) => (i === 0 ? primera : i === consultas.length - 1 ? ultima : Math.round(primera + 5 + ((ultima - primera - 10) * i) / (consultas.length - 1))));
223
- const ocupadas = new Set(filasC.flatMap((y) => [y, y + 1]));
224
- if (consultas.length > 1) for (let y = filasC[0] + 1; y < filasC.at(-1); y++) if (!ocupadas.has(y)) L.poner(ASESOR.x + 2, y, '┊', { c: COLOR.tenue });
225
- consultas.forEach((c, i) => {
226
- const y = filasC[i];
227
- const final = i === consultas.length - 1;
228
- const estilo = final ? { c: COLOR.opus, b: true, bg: COLOR.resalte } : { c: COLOR.texto };
229
- if (final) L.poner(ASESOR.x + 1, y, ' '.repeat(ASESOR.w - 2), { bg: COLOR.resalte });
230
- L.poner(ASESOR.x + 2, y, `${final ? '◆' : '◇'} ${hora(c.t)} consulta`, estilo);
231
- if (c.ms) L.poner(ASESOR.x + 4, y + 1, `duró ${duracion(c.ms)}`, { c: COLOR.tenue });
232
- });
233
- if (consultas.length > 0) {
234
- L.poner(ASESOR.x + ASESOR.w + 1, filasC[0], `${'┈'.repeat(lx - (ASESOR.x + ASESOR.w + 1) - 2)}▶`, { c: COLOR.tenue });
235
- if (consultas.length > 1) L.poner(ASESOR.x + ASESOR.w + 1, filasC.at(-1), `${'┈'.repeat(vx - (ASESOR.x + ASESOR.w + 1) - 2)}▶`, { c: COLOR.tenue });
236
- } else {
237
- L.centro(ASESOR.x + 1, ASESOR.w - 2, primera, 'sin consultas', { c: COLOR.tenue });
238
- }
239
- const sy = ay + ah - 5;
240
- L.poner(ASESOR.x + 2, sy, 'consultas', { c: COLOR.texto });
241
- L.poner(ASESOR.x + ASESOR.w - 3 - String(s.asesor.llamadas).length, sy, String(s.asesor.llamadas), { c: COLOR.opus, b: true });
242
- L.poner(ASESOR.x + 2, sy + 1, 'tiempo', { c: COLOR.texto });
243
- const t = duracion(s.asesor.tiempo ?? 0);
244
- L.poner(ASESOR.x + ASESOR.w - 2 - [...t].length, sy + 1, t, { c: COLOR.opus });
245
-
246
- // ---- Registro de sesión
247
- const ry = REGISTRO_Y;
248
- L.caja(2, ry, ANCHO - 4, lineasRegistro + 2, COLOR.tenue, 'registro de sesión');
249
- const quienColor = (q) => (q === 'líder' ? cLider : q === 'asesor' ? COLOR.opus : colorDe(s.agentes.find((a) => a.nombre === q)?.modelo));
250
- s.registro.slice(-lineasRegistro).forEach((e, i) => {
251
- const y = ry + 1 + i;
252
- L.poner(4, y, hora(e.t), { c: COLOR.tenue });
253
- L.poner(14, y, L.corto(e.quien, 14), { c: quienColor(e.quien), b: true });
254
- const [herramienta, ...resto] = e.texto.split(' · ');
255
- if (resto.length && /^[A-Z]/.test(herramienta) && !/^(empieza|terminó|consultado)/.test(e.texto)) {
256
- L.poner(30, y, L.corto(herramienta, 14), { c: COLOR.texto });
257
- L.poner(46, y, `→ ${L.corto(resto.join(' · '), 52)}`, { c: COLOR.texto });
258
- } else {
259
- L.poner(30, y, L.corto(e.texto, 68), { c: COLOR.texto });
260
- }
261
- });
262
-
263
- // ---- Orden y estado
264
- const oy = ry + lineasRegistro + 3;
265
- const prefijo = `~/${carpeta || ''} $ `.replace('~/ $', '~ $');
266
- L.poner(2, oy, prefijo, { c: COLOR.tenue });
267
- L.poner(2 + [...prefijo].length, oy, `claude --model ${alias(s.lider.modelo)}${asesorModelo ? ` --advisor ${alias(asesorModelo)}` : ''}`, { c: COLOR.texto, b: true });
268
- x = 2;
269
- for (const etiqueta of estadoPorFamilia(s)) {
270
- const m = etiqueta.match(/^(.*?) \[(.*)\]$/u);
271
- L.poner(x, oy + 1, `${m[1]} `, { c: COLOR.tenue }); x += m[1].length + 1;
272
- const c = /enjambre/.test(m[2]) ? cEnjambre : /consultado/.test(m[2]) ? COLOR.opus : /error/.test(m[2]) ? COLOR.error : COLOR.ok;
273
- L.poner(x, oy + 1, `[${m[2]}]`, { c, b: true }); x += m[2].length + 2 + 3;
274
- }
275
- let ly = oy + 2;
276
- if (medidores.length) pintarMedidores(L, ly++, medidores);
277
- if (lineaModelo) {
278
- L.poner(2, ly, lineaModelo.actual, { c: COLOR.texto });
279
- L.poner(2 + [...lineaModelo.actual].length, ly, lineaModelo.cola, { c: lineaModelo.coincide ? COLOR.ok : '#facc15', b: !lineaModelo.coincide });
280
- ly++;
281
- }
282
- if (codex) pintarCodex(L, ly, codex, ahora);
283
-
284
- return { filas: aTramos(L.celdas), ancho: ANCHO, alto };
285
- }
286
-
287
- // ---- Uso y modelo, como las líneas de estado de nexakit-sesion y nexakit-modelo, pero con barras
288
- const esNumero = (v) => typeof v === 'number' && Number.isFinite(v);
289
- export function medidoresDeUso(uso) {
290
- const m = [];
291
- if (esNumero(uso?.context?.percent)) m.push(['contexto', uso.context.percent]);
292
- for (const l of uso?.rateLimits ?? []) {
293
- if (!esNumero(l?.percentUsed)) continue;
294
- if (l.kind === 'five_hour') m.push(['5 h', l.percentUsed]);
295
- if (l.kind === 'seven_day') m.push(['semana', l.percentUsed]);
296
- }
297
- return m;
298
- }
299
- const colorDeNivel = (p) => (p >= 85 ? COLOR.error : p >= 60 ? '#facc15' : COLOR.ok);
300
- function pintarMedidores(L, y, medidores) {
301
- let x = 2;
302
- for (const [nombre, p] of medidores) {
303
- L.poner(x, y, nombre, { c: COLOR.tenue }); x += [...nombre].length + 1;
304
- L.poner(x, y, barra(p / 100, 10), { c: colorDeNivel(p) }); x += 11;
305
- const pct = `${Math.round(p)} %`;
306
- L.poner(x, y, pct, { c: COLOR.texto, b: true }); x += pct.length + 4;
307
- }
308
- }
309
- const hace = (ms) => (ms < 60_000 ? `hace ${Math.max(0, Math.round(ms / 1000))} s` : ms < 3_600_000 ? `hace ${Math.round(ms / 60_000)} min` : `hace ${Math.round(ms / 3_600_000)} h`);
310
- // Uso de Codex leído de su propia sesión: tokens, límites y cuándo fue la última actividad.
311
- function pintarCodex(L, y, codex, ahora) {
312
- let x = 2;
313
- const cabeza = `codex ${codex.modelo ?? '?'}${codex.esfuerzo ? ` · ${codex.esfuerzo}` : ''}`;
314
- L.poner(x, y, cabeza, { c: COLOR.codex, b: true }); x += [...cabeza].length + 2;
315
- const tok = `leídos ${tokens(codex.leidos)} · escritos ${tokens(codex.escritos)}`;
316
- L.poner(x, y, tok, { c: COLOR.texto }); x += [...tok].length + 2;
317
- for (const [nombre, p] of [['5 h', codex.limite5h], ['semana', codex.limiteSemana]]) {
318
- if (!esNumero(p)) continue;
319
- L.poner(x, y, nombre, { c: COLOR.tenue }); x += [...nombre].length + 1;
320
- L.poner(x, y, barra(p / 100, 5), { c: colorDeNivel(p) }); x += 6;
321
- const pct = `${Math.round(p)} %`;
322
- L.poner(x, y, pct, { c: COLOR.texto, b: true }); x += pct.length + 2;
323
- }
324
- if (esNumero(codex.actualizado)) L.poner(x, y, hace(ahora - codex.actualizado), { c: COLOR.tenue });
325
- }
326
-
327
- export function modeloFrenteARecomendado(s) {
328
- const actual = `modelo ${s.lider.modelo} · ${s.lider.esfuerzo ?? 'esfuerzo ?'}`;
329
- const rec = s.recomendacion;
330
- if (!rec) return { actual, cola: '', coincide: true };
331
- const coincide = familia(s.lider.modelo) === familia(rec.modelo) && s.lider.esfuerzo === rec.esfuerzo;
332
- return { actual, cola: coincide ? ' ✓' : ` → recomendado: ${rec.modelo} · ${rec.esfuerzo}`, coincide };
333
- }
334
-
335
- // Para el panel de Claude: los espacios sin estilo se pegan al tramo vecino, para no dejar textos solo de espacios.
336
- export function tramosParaPanel(filas) {
337
- return filas.map((tramos) => {
338
- const salida = [];
339
- let pendiente = '';
340
- for (const t of tramos) {
341
- const soloEspacio = /^ +$/u.test(t.t) && !t.bg && !t.c;
342
- if (soloEspacio) {
343
- if (salida.length) salida.at(-1).t += t.t;
344
- else pendiente += t.t;
345
- continue;
346
- }
347
- salida.push({ ...t, t: pendiente + t.t });
348
- pendiente = '';
349
- }
350
- if (pendiente) salida.push({ t: pendiente });
351
- return salida;
352
- });
353
- }
354
-
355
- // ---- A ANSI para la terminal
356
- const rgb = (hex) => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16));
357
- const a256 = ([r, g, b]) => 16 + 36 * Math.round((r / 255) * 5) + 6 * Math.round((g / 255) * 5) + Math.round((b / 255) * 5);
358
- const a16 = ([r, g, b]) => {
359
- const brillo = (r + g + b) / 3 > 140 ? 60 : 0;
360
- return 30 + brillo + (r > 127 ? 1 : 0) + (g > 127 ? 2 : 0) + (b > 127 ? 4 : 0);
361
- };
362
- function sgr(tramo, nivel) {
363
- const partes = [];
364
- if (tramo.b) partes.push('1');
365
- if (tramo.d) partes.push('2');
366
- if (tramo.c) {
367
- const c = rgb(tramo.c);
368
- partes.push(nivel === 'truecolor' ? `38;2;${c.join(';')}` : nivel === '256' ? `38;5;${a256(c)}` : String(a16(c)));
369
- }
370
- if (tramo.bg) {
371
- const c = rgb(tramo.bg);
372
- partes.push(nivel === 'truecolor' ? `48;2;${c.join(';')}` : nivel === '256' ? `48;5;${a256(c)}` : String(a16(c) + 10));
373
- }
374
- return partes.join(';');
375
- }
376
- export function aAnsi(filas, nivel) {
377
- return filas.map((tramos) => tramos.map((t) => {
378
- if (nivel === 'none') return t.t;
379
- const codigo = sgr(t, nivel);
380
- return codigo ? `\x1b[${codigo}m${t.t}\x1b[0m` : t.t;
381
- }).join('')).join('\n');
382
- }
@@ -1,279 +0,0 @@
1
- // Lógica pura del panel: reduce los eventos de la sesión a un estado que el panel dibuja. Sin datos inventados:
2
- // todo sale de lo que el motor informa (pasos, subagentes, llamadas del servidor, herramientas).
3
- export const MAX_REGISTRO = 60;
4
- export const MAX_AGENTES = 8;
5
-
6
- export const crear = () => ({
7
- lider: { modelo: null, esfuerzo: null, leidos: 0, escritos: 0, herramientas: 0 },
8
- agentes: [],
9
- asesor: { llamadas: 0, ultimo: null, tiempo: 0 },
10
- registro: [],
11
- pasos: 0,
12
- recomendacion: null,
13
- revisiones: [],
14
- });
15
-
16
- export function familia(modelo) {
17
- const m = String(modelo ?? '').toLowerCase();
18
- for (const nombre of ['haiku', 'sonnet', 'opus', 'fable']) if (m.includes(nombre)) return nombre;
19
- return 'otro';
20
- }
21
-
22
- // «claude-sonnet-5-5» → «Sonnet 5.5»; ignora la fecha final de los identificadores largos.
23
- export function etiquetaModelo(modelo) {
24
- if (!modelo) return 'modelo ?';
25
- const m = String(modelo).toLowerCase().replace(/^claude-/u, '');
26
- const partes = m.match(/^(haiku|sonnet|opus|fable)(?:-(\d{1,2})(?:-(\d{1,2}))?)?(?:-|$)/u);
27
- if (!partes) return String(modelo);
28
- const nombre = partes[1][0].toUpperCase() + partes[1].slice(1);
29
- if (!partes[2]) return nombre;
30
- return `${nombre} ${partes[2]}${partes[3] ? `.${partes[3]}` : ''}`;
31
- }
32
-
33
- const NIVELES = { low: 1, medium: 2, high: 3, xhigh: 4, max: 4 };
34
- export function barraEsfuerzo(esfuerzo) {
35
- const llenos = NIVELES[esfuerzo] ?? 0;
36
- return '▮'.repeat(llenos) + '▯'.repeat(4 - llenos);
37
- }
38
-
39
- export function duracion(ms) {
40
- if (!Number.isFinite(ms) || ms < 1000) return '0 s';
41
- if (ms < 60_000) return `${Math.round(ms / 1000)} s`;
42
- return `${Math.floor(ms / 60_000)} min ${Math.round((ms % 60_000) / 1000)} s`;
43
- }
44
-
45
- export function hora(ms) {
46
- const d = new Date(ms);
47
- return [d.getHours(), d.getMinutes(), d.getSeconds()].map((n) => String(n).padStart(2, '0')).join(':');
48
- }
49
-
50
- const conRegistro = (estado, entrada) => ({ ...estado, registro: [...estado.registro, entrada].slice(-MAX_REGISTRO) });
51
- const nombreDe = (estado, id) => (id ? (estado.agentes.find((a) => a.id === id)?.nombre ?? 'agente') : 'líder');
52
-
53
- export function registrarPaso(estado, { modelo, esfuerzo, agentId }) {
54
- if (agentId) {
55
- return { ...estado, agentes: estado.agentes.map((a) => (a.id === agentId && modelo ? { ...a, modelo } : a)) };
56
- }
57
- return {
58
- ...estado,
59
- pasos: estado.pasos + 1,
60
- lider: { ...estado.lider, modelo: modelo ?? estado.lider.modelo, esfuerzo: esfuerzo ?? estado.lider.esfuerzo },
61
- };
62
- }
63
-
64
- export function iniciarAgente(estado, { id, nombre, modelo, at }) {
65
- const agente = { id, nombre, modelo, estado: 'corriendo', inicio: at, fin: null, herramientas: 0, leidos: 0, escritos: 0, ultimo: '' };
66
- return conRegistro(
67
- { ...estado, agentes: [...estado.agentes, agente].slice(-MAX_AGENTES) },
68
- { t: at, quien: nombre, texto: `empieza · ${etiquetaModelo(modelo)}` },
69
- );
70
- }
71
-
72
- export function terminarAgente(estado, { id, ok, at }) {
73
- const existe = estado.agentes.some((a) => a.id === id);
74
- if (!existe) return estado;
75
- const agentes = estado.agentes.map((a) => (a.id === id ? { ...a, estado: ok ? 'listo' : 'error', fin: at } : a));
76
- return conRegistro({ ...estado, agentes }, { t: at, quien: nombreDe(estado, id), texto: ok ? 'terminó' : 'terminó con error' });
77
- }
78
-
79
- export function registrarHerramienta(estado, { tool, detalle, agentId, at }) {
80
- const texto = detalle ? `${tool} · ${detalle}` : tool;
81
- const agentes = agentId
82
- ? estado.agentes.map((a) => (a.id === agentId ? { ...a, herramientas: a.herramientas + 1, ultimo: texto } : a))
83
- : estado.agentes;
84
- const lider = agentId ? estado.lider : { ...estado.lider, herramientas: (estado.lider.herramientas ?? 0) + 1 };
85
- return conRegistro({ ...estado, agentes, lider }, { t: at, quien: nombreDe(estado, agentId), texto });
86
- }
87
-
88
- export function registrarAsesor(estado, { llamadas, at, tiempo = 0 }) {
89
- if (!llamadas) return estado;
90
- return conRegistro(
91
- { ...estado, asesor: { llamadas: estado.asesor.llamadas + llamadas, ultimo: at, tiempo: (estado.asesor.tiempo ?? 0) + tiempo } },
92
- { t: at, quien: 'asesor', texto: `consultado ${llamadas} ${llamadas === 1 ? 'vez' : 'veces'}`, ms: tiempo },
93
- );
94
- }
95
-
96
- const esNumero = (valor) => typeof valor === 'number' && Number.isFinite(valor);
97
- // Línea de uso: solo lo que se conoce; undefined si no hay nada que mostrar.
98
- export function textoDeUso(uso) {
99
- const partes = [];
100
- if (esNumero(uso?.context?.percent)) partes.push(`contexto ${Math.round(uso.context.percent)} %`);
101
- for (const limite of uso?.rateLimits ?? []) {
102
- if (!esNumero(limite?.percentUsed)) continue;
103
- if (limite.kind === 'five_hour') partes.push(`5 h ${Math.round(limite.percentUsed)} %`);
104
- if (limite.kind === 'seven_day') partes.push(`semana ${Math.round(limite.percentUsed)} %`);
105
- }
106
- return partes.length > 0 ? partes.join(' · ') : undefined;
107
- }
108
-
109
- // --- Diagrama ---------------------------------------------------------------------------------------------------
110
- export function barra(fraccion, ancho) {
111
- const valor = Number.isFinite(fraccion) ? Math.min(1, Math.max(0, fraccion)) : 0;
112
- const llenos = Math.round(valor * ancho);
113
- return '█'.repeat(llenos) + '░'.repeat(ancho - llenos);
114
- }
115
-
116
- export function resumenDelegacion(agentes) {
117
- return {
118
- total: agentes.length,
119
- corriendo: agentes.filter((a) => a.estado === 'corriendo').length,
120
- listos: agentes.filter((a) => a.estado === 'listo').length,
121
- errores: agentes.filter((a) => a.estado === 'error').length,
122
- herramientas: agentes.reduce((suma, a) => suma + a.herramientas, 0),
123
- };
124
- }
125
-
126
- // Lo que se escribe en --model: la familia si se reconoce, y el texto tal cual si no.
127
- export function alias(modelo) {
128
- if (!modelo) return '?';
129
- const f = familia(modelo);
130
- return f === 'otro' ? String(modelo) : f;
131
- }
132
-
133
- // La familia de subagentes más usada, en el orden en que aparecieron si hay empate.
134
- function familiaDominante(agentes) {
135
- const cuentas = new Map();
136
- for (const a of agentes) cuentas.set(familia(a.modelo), (cuentas.get(familia(a.modelo)) ?? 0) + 1);
137
- let mejor = null;
138
- for (const [nombre, n] of cuentas) if (mejor === null || n > cuentas.get(mejor)) mejor = nombre;
139
- return mejor;
140
- }
141
-
142
- // «Haiku 5.5» si es la familia de subagentes más usada; null si no hay subagentes.
143
- export function etiquetaEnjambre(agentes) {
144
- if (agentes.length === 0) return null;
145
- const dominante = familiaDominante(agentes);
146
- const representante = [...agentes].reverse().find((a) => familia(a.modelo) === dominante);
147
- return etiquetaModelo(representante.modelo);
148
- }
149
-
150
- export function tituloDeOrquesta(estado) {
151
- let titulo = 'NEXAKIT · ORQUESTA';
152
- if (estado.lider.modelo) titulo += ` · ${etiquetaModelo(estado.lider.modelo).toUpperCase()} DIRIGE`;
153
- const enjambre = etiquetaEnjambre(estado.agentes);
154
- if (enjambre) titulo += ` · ${enjambre.toUpperCase()} EN ENJAMBRE`;
155
- return titulo;
156
- }
157
-
158
- // Una etiqueta por familia de subagentes, el avance de la delegación y el asesor; solo lo que ocurre.
159
- export function estadoPorFamilia(estado) {
160
- const partes = [];
161
- const familias = [];
162
- for (const a of estado.agentes) if (!familias.includes(familia(a.modelo))) familias.push(familia(a.modelo));
163
- for (const nombre of familias) {
164
- const suyos = estado.agentes.filter((a) => familia(a.modelo) === nombre);
165
- const etiqueta = suyos.some((a) => a.estado === 'corriendo') ? 'enjambre' : suyos.some((a) => a.estado === 'error') ? 'con error' : 'listo';
166
- partes.push(`${nombre === 'otro' ? 'agente' : nombre} [${etiqueta}]`);
167
- }
168
- if (estado.agentes.length > 0) {
169
- const r = resumenDelegacion(estado.agentes);
170
- partes.push(`subagentes [${r.total - r.corriendo}/${r.total}]`);
171
- }
172
- if (estado.asesor.llamadas > 0) partes.push(`asesor [consultado ${estado.asesor.llamadas}]`);
173
- const ultimaPorIa = new Map((estado.revisiones ?? []).map((r) => [r.ia, r]));
174
- for (const [ia, r] of ultimaPorIa) partes.push(`${ia} [${r.estado === 'revisando' ? 'revisando' : r.estado === 'lista' ? 'revisó' : 'falló'}]`);
175
- return partes;
176
- }
177
-
178
- // Datos ficticios para ver el diseño sin esperar a que haya actividad real. Siempre se muestran marcados como ejemplo.
179
- export function ejemplo(ahora) {
180
- const t = (segundos) => ahora - segundos * 1000;
181
- let s = { ...registrarPaso(crear(), { modelo: 'claude-sonnet-5-5', esfuerzo: 'high' }), pasos: 24 };
182
- s = registrarUso(s, { usage: { input_tokens: 8_400, output_tokens: 12_300, cache_read_input_tokens: 660_000, cache_creation_input_tokens: 0 } });
183
- s = registrarAsesor(s, { llamadas: 1, at: t(95), tiempo: 4_200 });
184
- s = iniciarAgente(s, { id: 'ej1', nombre: 'search', modelo: 'claude-haiku-5-5', at: t(40) });
185
- s = iniciarAgente(s, { id: 'ej2', nombre: 'grep', modelo: 'claude-haiku-5-5', at: t(38) });
186
- s = iniciarAgente(s, { id: 'ej3', nombre: 'audit', modelo: 'claude-haiku-5-5', at: t(36) });
187
- s = registrarHerramienta(s, { tool: 'Glob', detalle: 'src/**/*.ts', agentId: 'ej1', at: t(31) });
188
- s = registrarHerramienta(s, { tool: 'Grep', detalle: 'verifyToken', agentId: 'ej2', at: t(28) });
189
- s = registrarHerramienta(s, { tool: 'Read', detalle: 'src/auth.ts', agentId: 'ej3', at: t(24) });
190
- s = registrarHerramienta(s, { tool: 'Read', detalle: 'src/session.ts', agentId: 'ej3', at: t(20) });
191
- s = registrarHerramienta(s, { tool: 'Bash', detalle: 'npm test', agentId: 'ej3', at: t(14) });
192
- s = registrarUso(s, { agentId: 'ej1', usage: { input_tokens: 41_000, output_tokens: 900, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 } });
193
- s = registrarUso(s, { agentId: 'ej2', usage: { input_tokens: 72_000, output_tokens: 1_400, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 } });
194
- s = registrarUso(s, { agentId: 'ej3', usage: { input_tokens: 230_000, output_tokens: 3_100, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 } });
195
- s = terminarAgente(s, { id: 'ej3', ok: true, at: t(10) });
196
- s = registrarHerramienta(s, { tool: 'Edit', detalle: 'src/auth.ts', at: t(8) });
197
- s = registrarAsesor(s, { llamadas: 1, at: t(5), tiempo: 2_800 });
198
- return s;
199
- }
200
-
201
- // Uso real de cada paso: leídos = entrada + caché leída + caché escrita; escritos = salida.
202
- export function registrarUso(estado, { agentId, usage }) {
203
- if (!usage) return estado;
204
- const leidos = (usage.input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0);
205
- const escritos = usage.output_tokens ?? 0;
206
- if (agentId) {
207
- return { ...estado, agentes: estado.agentes.map((a) => (a.id === agentId ? { ...a, leidos: a.leidos + leidos, escritos: a.escritos + escritos } : a)) };
208
- }
209
- return { ...estado, lider: { ...estado.lider, leidos: estado.lider.leidos + leidos, escritos: estado.lider.escritos + escritos } };
210
- }
211
-
212
- export function tokens(n) {
213
- if (!Number.isFinite(n) || n < 1000) return String(Math.max(0, Math.round(n || 0)));
214
- if (n < 1_000_000) {
215
- const k = n / 1000;
216
- return `${k < 10 ? Math.round(k * 10) / 10 : Math.round(k)}k`;
217
- }
218
- return `${Math.round(n / 100_000) / 10}M`;
219
- }
220
-
221
- // La recomendación que registra el mod nexakit-modelo, observada en su llamada.
222
- export function registrarRecomendacion(estado, { modelo, esfuerzo, motivo }) {
223
- return { ...estado, recomendacion: { modelo, esfuerzo, motivo } };
224
- }
225
-
226
- // Tacha los secretos evidentes de un detalle antes de mostrarlo o guardarlo en disco.
227
- export function sinSecretos(texto) {
228
- return String(texto)
229
- .replace(/\b([A-Za-z0-9_]*(?:TOKEN|KEY|SECRET|PASSWORD|PASSWD)[A-Za-z0-9_]*)=([^\s"']+)/giu, '$1=***')
230
- .replace(/(Bearer\s+)[^\s"']+/giu, '$1***')
231
- .replace(/(--?(?:password|passwd|token|secret|api-key)[= ])[^\s"']+/giu, '$1***');
232
- }
233
-
234
- // --- Revisiones que la sesión manda a otra IA con `nexakit revision --con <ia>` -----------------------------------
235
- export function esRevision(comando) {
236
- const c = String(comando ?? '');
237
- if (!/nexakit(?:\.cmd)?['"]?\s+revision\b/u.test(c) || /--disponibles\b/u.test(c)) return null;
238
- const valor = (bandera) => {
239
- const m = c.match(new RegExp(`${bandera}\\s+(?:"([^"]+)"|'([^']+)'|(\\S+))`, 'u'));
240
- return m ? (m[1] ?? m[2] ?? m[3]) : null;
241
- };
242
- const ia = valor('--con');
243
- return ia ? { ia, modelo: valor('--modelo'), esfuerzo: valor('--esfuerzo') } : null;
244
- }
245
-
246
- // Las dos líneas fijas que imprime `nexakit revision` al terminar: modelo que respondió y tokens.
247
- export function leerSalidaRevision(texto) {
248
- const t = String(texto ?? '');
249
- const numero = (v) => (v && /^\d+$/u.test(v.trim()) ? Number(v.trim()) : null);
250
- const tokensLinea = t.match(/Tokens: entrada (.+?) \(caché (.+?)\) · salida (.+?)\s*$/mu);
251
- const respondio = t.match(/Modelo que respondió: (.+?) · /u)?.[1]?.trim();
252
- return {
253
- respondio: respondio && respondio !== 'no informado' ? respondio : null,
254
- entrada: numero(tokensLinea?.[1]),
255
- cache: numero(tokensLinea?.[2]),
256
- salida: numero(tokensLinea?.[3]),
257
- };
258
- }
259
-
260
- export function iniciarRevision(estado, { id, ia, modelo, esfuerzo, at }) {
261
- const revision = { id, ia, modelo, esfuerzo, estado: 'revisando', inicio: at, fin: null, entrada: null, cache: null, salida: null, respondio: null };
262
- return conRegistro(
263
- { ...estado, revisiones: [...(estado.revisiones ?? []), revision].slice(-4) },
264
- { t: at, quien: ia, texto: `revisión · ${modelo ?? 'modelo ?'}${esfuerzo ? ` · ${esfuerzo}` : ''}` },
265
- );
266
- }
267
-
268
- export function terminarRevision(estado, { id, ok, at, cifras }) {
269
- if (!(estado.revisiones ?? []).some((r) => r.id === id)) return estado;
270
- let ia = '';
271
- const revisiones = estado.revisiones.map((r) => {
272
- if (r.id !== id) return r;
273
- ia = r.ia;
274
- const datos = Object.fromEntries(Object.entries(cifras ?? {}).filter(([, v]) => v != null));
275
- return { ...r, ...datos, estado: ok ? 'lista' : 'error', fin: at };
276
- });
277
- const total = (cifras?.entrada ?? 0) + (cifras?.salida ?? 0);
278
- return conRegistro({ ...estado, revisiones }, { t: at, quien: ia, texto: ok ? `revisión lista${total ? ` · tokens ${tokens(total)}` : ''}` : 'revisión falló' });
279
- }