SLOPSHOPPER

model-picker

A band above the prompt to pick which model, and which version of it, runs the next requests, with cost, tokens and cache stats an animated pane of charts and…

panebandguardcommandtoastprompt
v0.5.0MITupdated 2026-10-11juampymdd/claude-code-model-picker
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · model-picker
│ ┃ model-picker-stats ✕ › fix the failing auth test and add an audit log call │ ┃ 1: costo2: modelos3: tools4: ritmo5: agentes │ ┃ ▣ client module ./live.tsx ⏺ Read(src/auth.ts) │ ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /modelo │ ⎿ model-picker: Modelo: Opus 5.5. Uso: /modelo auto | fable | opus │ │ ▌ MODELO fableopussonnethaikustats ▣ client module ./live.tsx ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
▌ MODELO fableopussonnethaikustats ▣ client module ./live.tsx
Pane · model-picker-stats
1: costo2: modelos3: tools4: ritmo5: agentes6: juegos7: teor ▣ client module ./live.tsx
README

model-picker

test license: MIT

Elegí el modelo de Claude, y su versión, desde una banda arriba del prompt de Claude Code. Un clic y la próxima request sale con otro modelo: sin /model, sin diálogos, sin tocar tu modelo por defecto. Y debajo, lo que la API informó: qué modelo respondió, cuánto costó, tokens y cache.

🇬🇧 Read this in English

La banda de model-picker: un clic cambia el modelo, y el chip activo despliega sus versiones con precio

▶ Ver el video completo (30 s)

▌ MODELO   ✦ Fable 5.1  ▐ ◆ Opus 5.5 ▾ ▌  ▲ Sonnet 5.5   ● Haiku 5.5    razonamiento profundo
  respondió Opus 5.5 · sesión ~$0.42 · turno ~$0.031 · effort medium · 48k→1.2k tok · cache ▰▰▰▰▰▰ 94% · contexto ▰▰▱▱▱▱ 38%

Con el dropdown de versiones abierto:

▌ MODELO   ✦ Fable 5.1  ▐ ◆ Opus 5.5 ▴ ▌  ▲ Sonnet 5.5   ● Haiku 5.5
                          ● Opus 5.5 $4/$20 por MTok
                          ○ Opus 5 $5/$25 por MTok
                          ○ Opus 4.8 $5/$25 por MTok
                          ○ Opus 4.7 $5/$25 por MTok
                          ○ Opus 4.6 $5/$25 por MTok

Contenido

Qué hace

  • Un chip por familia (Fable, Opus, Sonnet, Haiku), cada uno con su color. El activo va relleno.
  • Dropdown de versiones con precio: un clic en el chip activo lista todas las versiones de esa familia y su precio de lista.
  • Arranca en tu modelo real: al abrir una sesión marca el modelo que la sesión ya usa.
  • Cambio instantáneo: la elección se aplica a la request siguiente.
  • Fila de datos: modelo que respondió, costo estimado de la sesión y del turno, effort, tokens y porcentaje de cache.
  • Panel de estadísticas animado, con gráficos de costo, modelos, herramientas y ritmo de la sesión, y los agentes en vivo: qué hace cada uno, con qué modelo y cuánto gasta.
  • 15 juegos en el panel (Pong, Tetris, Snake, Buscaminas, 2048… y dos hechos con los datos de tu sesión), en la pestaña ▶ Jugar.
  • Pestaña Teoría: mientras trabaja, Claude anota los conceptos y decisiones de diseño que aplica, explicados desde cero o solo con el trade-off.
  • Comando /modelo para hacer lo mismo desde el teclado.
  • Se actualiza solo: una vez por día busca una versión nueva y la instala. Se puede apagar.

Requisitos

  • Claude Code 2.1.295 o más nuevo, con soporte de mods (hooks de función). Verificá tu versión con claude --version.
  • Una terminal con color de 24 bits para ver los colores tal cual (Windows Terminal, iTerm2, la terminal de VS Code, etc.).
  • La banda se dibuja en la terminal y en la app de escritorio. Está probada en la terminal.

La API de mods de Claude Code es de acceso anticipado y puede cambiar entre versiones. Si una actualización de Claude Code rompe el mod, abrí un issue.

Instalación

Elegí una sola de las opciones. Instalar por dos caminos a la vez hace que una copia no cargue (ver Problemas frecuentes).

Opción A: como plugin (recomendada)

Desde cualquier terminal:

claude plugin marketplace add juampymdd/claude-code-model-picker
claude plugin install model-picker@model-picker

El primer comando registra este repositorio como marketplace; el segundo instala el mod para tu usuario, en todos tus proyectos. Abrí una sesión nueva de Claude Code y la banda aparece arriba del prompt.

Para instalarlo solo en un proyecto, corré el segundo comando dentro de ese proyecto con --scope project.

También se puede instalar desde adentro de una sesión de Claude Code en la terminal:

/plugin install model-picker --marketplace juampymdd/claude-code-model-picker

Respondé y para agregar el marketplace y elegí el alcance.

Opción B: clonando el repositorio

Claude Code carga solo cualquier mod que esté en tu carpeta ~/.claude/skills/. La carpeta tiene que llamarse model-picker.

macOS / Linux:

git clone https://github.com/juampymdd/claude-code-model-picker.git ~/.claude/skills/model-picker

Windows (PowerShell):

git clone https://github.com/juampymdd/claude-code-model-picker.git "$env:USERPROFILE\.claude\skills\model-picker"

Abrí una sesión nueva de Claude Code. Esta opción sirve si querés editar el mod: los cambios en esa carpeta se recargan solos.

Opción C: probarlo sin instalar

git clone https://github.com/juampymdd/claude-code-model-picker.git
claude --plugin-dir ./claude-code-model-picker

El mod queda cargado solo en esa sesión.

Comprobar que quedó instalado

claude plugin list

Tiene que aparecer model-picker con estado enabled o loaded:

❯ model-picker@model-picker
  Version: 0.4.0
  Scope: user
  Status: ✔ enabled

Después, en una sesión nueva, escribí /modelo. Si responde Modelo: Opus 5.5. Uso: … (con tu modelo), el mod está cargado.

Uso

Con el mouse

AcciónResultado
Clic en un chip de otra familiaCambia a la versión más nueva de esa familia
Clic en el chip activo (▾)Abre la lista de versiones, con su precio, debajo del chip
Clic en una versión de la listaCambia a esa versión y cierra la lista (● marca la actual)
Clic otra vez en el chip activo (▴)Cierra la lista sin cambiar nada
Elegir el modelo que ya usa la sesiónQuita la elección y vuelve a seguir a la sesión

Con el comando

ComandoResultado
/modeloMuestra el modelo actual y la ayuda
/modelo sonnetCambia a la versión más nueva de Sonnet
/modelo opus 4.8Cambia a esa versión puntual
/modelo autoVuelve al modelo de la sesión
/modelo statsAbre o cierra el panel de estadísticas
/modelo juegosOculta o muestra la pestaña de juegos del panel
/modelo teoriaApaga o enciende las notas de teoría; con aprender o experto cambia el nivel

Familias válidas: fable, opus, sonnet, haiku.

La fila de datos

Debajo de los chips hay una fila con lo que la API informó. Antes de la primera respuesta de la sesión dice costo, tokens y cache: tras la próxima respuesta; después:

respondió Opus 5.5 · sesión ~$0.42 · turno ~$0.031 · effort medium · 48k→1.2k tok · cache ▰▰▰▰▰▰ 94% · contexto ▰▰▱▱▱▱ 38% · manual
DatoQué es
respondió Opus 5.5El modelo que la API dice que respondió la última request. Sirve para comprobar que el cambio se aplicó
sesión ~$0.42Costo estimado de todas las requests de la sesión, subagentes incluidos
turno ~$0.031Costo estimado del turno actual (tu último mensaje y todas las llamadas que disparó)
effort mediumNivel de razonamiento con el que salió la última request
48k→1.2k tokTokens de la última request: prompt completo (cache incluida) → respuesta
cache ▰▰▰▰▰▰ 94%Qué parte de ese prompt salió de la cache, con su medidor: verde si es alta, ámbar bajo 70 %, rojo bajo 30 %. Baja a 0% justo después de cambiar de modelo
contexto ▰▰▱▱▱▱ 38%Cuán llena está la ventana de contexto: verde, ámbar desde 70 %, rojo desde 90 %
manualHay un modelo elegido a mano, distinto al de la sesión

Si la terminal es angosta, la fila deja primero los datos de la izquierda y descarta los últimos. Mientras el dropdown está abierto, la fila se oculta.

Los costos son una estimación: tokens informados por la API multiplicados por el precio de lista. Si usás una suscripción en vez de pagar por token, tomalos como referencia de consumo, no como tu factura. Ver Limitaciones.

El panel de estadísticas

Un panel con gráficos de toda la sesión. Se abre y se cierra con el botón ▦ stats del final de la banda, o con /modelo stats. En terminales anchas (110 columnas o más, en pantalla completa) se acopla a la derecha; si no, se muestra arriba del prompt. Se cierra también con Esc cuando tiene el foco.

sesión 1h12m · ~$0.42 · 31 turnos · contexto ▰▰▰▱▱▱▱▱ 38%
 1: Costo   2: Modelos   3: Tools   4: Ritmo   5: Agentes   6: ▶ Jugar   7: Teoría

Las pestañas se cambian con un clic o, con el panel enfocado (clic en el panel o ctrl+x tab), con las teclas 1 a 7. Los gráficos están hechos con caracteres de bloque, sin librerías, así que se ven igual en la terminal y en la app de escritorio.

1 · Costo

Cuánto costó cada turno, es decir, cada mensaje tuyo con todas las requests que disparó.

COSTO POR TURNO · últimos 28 de 31 · máx $0.21
      █
  ▂   █    ▅
▁▃█▂▁▂█▃▁▁▂█▂▁▁▃▂▁▁▂▃▁▂▅▂▁▂▃
   #  costo   ▒ entrada █ salida    tok          cache
  31  $0.084  ▒▒▒▒▒▒██████████      48k→1.2k     94%
  30  $0.012  ▒▒█                   12k→300      88%
total ~$0.42 · 1.9M→41k tok · cache 91% · subagentes $0.05
  • Arriba, un gráfico de columnas con el costo de los últimos turnos.
  • La tabla lista los 50 turnos más recientes, el último primero. La barra es el costo del turno: ▒ lo que costó el prompt y █ lo que costó la respuesta, con el color del modelo que respondió.
  • tok son los tokens del turno (prompt completo, cache incluida → respuesta) y cache la parte del prompt que salió de la cache.
  • En paneles angostos la tabla pierde primero tok y después cache.

2 · Modelos

Cómo se reparte el costo de la sesión entre modelos, subagentes incluidos.

USO POR MODELO
◆ Opus 5.5    ████████████▌   $0.31   74%  1.4M→30k  22 req
● Haiku 5.5   ██▏             $0.05   12%  410k→9k   14 req
subagentes: $0.05 (12% del total)

3 · Tools

Qué herramientas se usaron, de todos los loops: cuántas veces, cuántas fallaron, tiempo total y promedio.

TOOLS · 87 llamadas · 3 errores · 2m41s
Bash          ██████████▏   42  2 err   1m12s   1.7s
Read          ██████▎       26  –          4s  150ms

Una llamada cuenta como error si la herramienta devolvió error o si otro plugin la rechazó. El tiempo incluye las confirmaciones de permisos que haya pedido la herramienta.

4 · Ritmo

Cuánto tiempo trabajó Claude y a qué ritmo.

RITMO · activo 18m de 1h12m (25%) · 4.2 pasos/turno · prom 35s
duración   ▁▂▁▅▃▁▁█▂▁▃▂▁▁▄▂   máx 3m12s
pasos      ▁▁▂▇▃▁▁█▂▁▂▂▁▁▃▂   máx 23
actividad  ··▁▃█▅···▂▃▁··▂▅   16 tramos de 4m30s
  31  12s     3 pasos  respuesta
  30  3m12s   23 pasos abortado
  • duración y pasos son un gráfico por turno (duración y cantidad de requests del loop principal).
  • actividad reparte los pasos a lo largo del tiempo de la sesión; un · es un tramo sin actividad.
  • Cada turno termina en respuesta, abortado, rechazo o error, y mientras corre dice en curso.

5 · Agentes

Los subagentes de la sesión, en vivo. Claude Code ya muestra qué agentes corren; esta pestaña agrega lo que no muestra: cuánto gasta cada uno, con qué modelo, qué herramientas usó, en cuál está ahora y cuánto lleva.

AGENTES  ● 2 corriendo  ✕ 1 fallaron  $1.04
────────────────────────────────────────────────────────────────────────
● Explore   buscar usos de FAMILIES                        1m12s  $0.058
  ● Haiku 5.5  12 req  Grep ×3 Read ×2  ▸ ⠹ Grep 4s          ▁▂▃▅▇█
● Plan      diseñar pestaña de agentes                     3m02s   $0.98
  ◆ Opus 5.5  8 req  Read ×6            ▸ pensando..         ▁▁▂▄▆█
✕ general   correr los tests                                  3s  $0.000 error
  ◆ Opus 5.5  1 req  Bash ×1 ✕1

Cada agente ocupa dos filas. Arriba: estado, tipo, descripción, tiempo y costo. Abajo: modelo, requests, herramientas más usadas, lo que hace ahora (▸) y un gráfico del costo de sus últimas requests.

EstadoGlifoColor
Corriendo● (late)verde
Esperando, pendiente o inactivo◐ (late)ámbar
Terminado○gris
Falló o fue cancelado✕rojo
  • Los colores de estado son los del tema de Claude Code, así que siguen tu tema claro u oscuro. El modelo lleva el color de su familia, igual que los chips de la banda.
  • ▸ muestra la herramienta en curso con su tiempo, o pensando cuando el agente espera al modelo. El tiempo de una herramienta se pone ámbar pasados 10 segundos (suele ser una confirmación de permisos pendiente) y el del agente, pasados 5 minutos.
  • Una herramienta con fallos lleva ✕ y la cantidad en rojo. Un costo mayor a $1 se pone rojo.
  • Un agente lanzado por otro agente aparece debajo, con └.
  • Primero van los que corren (el más nuevo arriba) y después los últimos 10 terminados; ocultar terminados los saca de la lista.
  • Mientras hay agentes trabajando, al lado del botón ▦ stats de la banda late un ● con la cantidad, así te enterás sin abrir el panel.

6 · Jugar

Para los ratos en que Claude trabaja solo: 15 juegos dentro del panel, en la pestaña ▶ Jugar, siempre a la vista al lado de las demás.

 ☰ juegos   ◆ Pong · récord 7

☰ juegos abre la lista con todos los juegos y el récord de cada uno; un clic en uno lo abre. Para jugar con el teclado hay que hacer clic sobre el juego (así toma el foco); Esc se lo devuelve al prompt. El mouse funciona siempre.

Teclas comunes a todos:

TeclaAcción
espacio o clicEmpieza; sigue después de una pausa
p o EnterPausa y sigue
rPartida nueva
JuegoDe qué se trataTecladoMouse
◆ PongContra la máquina, a 11 puntos↑ ↓ mueven · espacio pausala paleta sigue al puntero
▲ Space InvadersTres filas que bajan cada vez más rápido, escudos, tres vidas← → · espacio disparala nave sigue al puntero · clic dispara
● SnakeCome, crece y acelera cada cinco comidasflechas giranclic apunta hacia ahí
▟ TetrisSiete piezas en bolsa, pieza guardada y sombra de caída← → · ↑/x gira · z al revés · ↓ baja · espacio cae · c guardaclic a un lado mueve, en el medio gira · derecho cae
▬ BreakoutSeis filas de ladrillos, tres vidas, niveles más rápidos← → · espacio lanzala paleta sigue al puntero · clic lanza
▦ 2048Deslizar y fusionar fichas igualesflechasarrastrar
✸ BuscaminasEl primer clic nunca es mina; tablero según el ancho del panelflechas + espacio abre · f marcaclic abre · derecho marca · clic en un número abre alrededor
▶ FlappyPasar entre los tubos; el hueco se achicaespacio o ↑ aleteaclic aletea
▙ DinoSaltar cactus, agacharse bajo los pájarosespacio/↑ salta · ↓ se agachaclic salta
☻ FroggerCruzar la ruta y el río hasta los cinco nidos, con tiempoflechas saltanclic salta hacia ahí
◇ AsteroidsCampo sin bordes, rocas que se parten en dos← → giran · ↑ empuja · espacio disparaapunta al puntero · clic dispara · derecho empuja
▣ SokobanSeis niveles: empujar cada caja a su metaflechas · u deshace · n/b cambian de nivelclic al lado del jugador
░ Juego de la vidaNo se gana: se dibuja y se mira evolucionarespacio pausa · c limpia · g planeador · 1–5 velocidaddibuja (derecho borra)
$ Token InvadersInvaders con tus herramientas como invasorescomo Invaderscomo Invaders
⚑ Carrera de agentesLos subagentes de la sesión en una pistano se juega—

Dos juegos usan los datos de tu sesión:

  • Token Invaders: cada invasor es una herramienta que usó Claude (Ba Bash, Ed Edit, Re Read…), las más usadas primero. Verde si nunca falló, ámbar si falló alguna vez, rojo si falló más de una de cada cinco. Bajan más rápido cuanto más costó la sesión: al doble desde $10.
  • Carrera de agentes: una pista por subagente, que avanza una celda por request, con su costo al final. Los que siguen trabajando llevan el color de su modelo y un ▶ que late; los que terminaron quedan con ✔ o ✕.

Cosas a saber:

  • Los récords se guardan entre sesiones. En Buscaminas el récord premia el menor tiempo; en Sokoban cuenta los niveles resueltos; el Juego de la vida y la Carrera no tienen.
  • La terminal no avisa cuando se suelta una tecla: cada pulsación mueve un paso (mantenerla apretada repite). Asteroids y Breakout se juegan mejor con el mouse.
  • Mientras el juego tiene el foco, las teclas 1 a 7 de las pestañas pueden no responder: Esc primero.
  • Cada juego necesita un ancho mínimo (entre 20 y 38 columnas) y avisa si el panel no llega.
  • Los juegos corren en la terminal y en la app de escritorio.

Ocultar la pestaña: /modelo juegos la saca o la vuelve a poner para la sesión. Para no verla nunca, /config → Juegos en el panel (model-picker.games) → desactivar.

7 · Teoría

Mientras Claude trabaja, anota acá la teoría detrás de lo que está armando: cada concepto, patrón, algoritmo o decisión de diseño que aplica, explicado en el momento en que lo usa. Sirve para aprender mirando, sin frenar el trabajo para preguntar.

TEORÍA · 2 notas · nivel aprendiendo
────────────────────────────────────────────────────────────────────
◆ Debounce                                                       12s
  src/hooks/useSearch.ts
  Es esperar a que el usuario deje de escribir antes de disparar la
  búsqueda. Evita una request por tecla. Lo elegí en vez de throttle
  porque acá importa el texto final, no los intermedios.

◆ Índice compuesto                                              2m10s
  migrations/0008_meals.sql
  Un índice sobre dos columnas juntas (user_id, fecha)…

 apagar notas   nivel: solo decisiones   borrar

La nota más nueva va arriba. Cada una tiene el concepto, dónde se aplica (si Claude lo dijo), la explicación y hace cuánto se anotó. Las notas no aparecen en la conversación ni cuentan en la pestaña Tools.

Hay dos niveles:

NivelQué escribe Claude
aprender (por defecto)El concepto desde cero, en 2 a 4 oraciones: qué es, qué problema resuelve y por qué lo eligió frente a la alternativa obvia
expertoSolo la decisión y su trade-off, en 1 o 2 oraciones

Los botones de abajo apagan o encienden las notas, cambian el nivel y borran la lista. Lo mismo con el comando: /modelo teoria (alterna), /modelo teoria on, off, aprender o experto. El nivel queda guardado entre sesiones. Para que arranque apagado: /config → Notas de teoría (model-picker.theory) → off.

A saber:

  • Funciona con una herramienta propia del mod (mcp__model-picker__teoria) y un párrafo que el mod agrega al system prompt pidiéndole a Claude que la use. Cuántas notas escribe depende del modelo: es un pedido, no una garantía.
  • Tiene costo: el párrafo suma unos 150 tokens de entrada por request (quedan en cache) y cada nota son tokens de salida. Con las notas apagadas el párrafo no se envía.
  • Solo anota el loop principal; los subagentes no reciben el pedido.
  • Se guardan las últimas 100 notas y se muestran las 30 más nuevas. Un /clear las borra.

Animaciones

En la terminal y en la app de escritorio el panel se mueve; en las demás superficies se dibuja quieto, con los mismos datos.

QuéCómo se mueve
Tiempos (sesión, turno en curso, agentes, herramienta en curso)Corren solos, segundo a segundo
Estado de un agente activoEl glifo late
Herramienta en curso / pensandoUn spinner y puntos que avanzan
Barras de Modelos y Tools, medidor de contextoCrecen hasta su valor al abrir la pestaña y cuando llega un dato nuevo
Columnas de costoSuben desde cero al abrir la pestaña
Agente nuevoEntra deslizándose desde la derecha
Agente que terminaDestella un instante y después se atenúa
Último tramo de actividadLate mientras hay un turno corriendo
Chip del modelo en la bandaSe enciende un instante al cambiar de modelo

El medidor de contexto (▰▰▰▱▱▱▱▱ 38%) pasa de verde a ámbar al 70 % y a rojo al 90 %. Cuando nada se mueve el panel no se redibuja, y con solo relojes en pantalla lo hace una vez por segundo.

Cosas a saber

  • El panel cuenta lo que ve el mod desde que cargó: no conoce lo que pasó antes. Un /clear lo reinicia.
  • Los costos son estimaciones a precio de lista (ver Limitaciones). Si Claude Code informa un costo propio, el encabezado lo muestra al lado como /cost.
  • La duración de un turno y el tiempo de una tool son tiempo real: incluyen esperas por permisos.
  • Un subagente que sigue corriendo después de que termina tu turno suma su costo al turno que esté abierto en ese momento. Los totales por modelo y de sesión son exactos igual.
  • Un agente aparece cuando el mod lo ve: al lanzarse, o en su primera request o herramienta. Los que terminaron antes de que cargara el mod no están.
  • El estado de cada agente se trae de la lista de Claude Code cada 2 segundos mientras haya alguno trabajando. Un agente de un workflow no está en esa lista: se muestra igual, con tipo agente y sin descripción.
  • pensando y el ámbar de una herramienta lenta son deducciones del mod (no hay herramienta en curso; lleva más de 10 segundos), no estados que informe Claude Code.
  • Se guardan los últimos 200 turnos, hasta 40 nombres de herramientas (el resto se cuenta como otros) y hasta 100 agentes; los totales siempre incluyen todo.

Modelos y precios

Precios de lista de la API de Anthropic, en dólares por millón de tokens (MTok), al 6 de octubre de 2026.

ModeloEntradaSalida
✦ Fable 5.1$10$50
✦ Fable 5$10$50
◆ Opus 5.5$4$20
◆ Opus 5$5$25
◆ Opus 4.8$5$25
◆ Opus 4.7$5$25
◆ Opus 4.6$5$25
▲ Sonnet 5.5$2$10
▲ Sonnet 5$2$10
▲ Sonnet 4.6$3$15
● Haiku 5.5$0.10$0.50
● Haiku 4.5$1$5

Tu cuenta tiene que tener acceso al modelo que elijas. Los precios pueden cambiar: los vigentes están en la página de precios de Anthropic.

Cómo funciona

El mod registra estos hooks:

HookPara qué
session.startRegistra el comando /modelo y la herramienta de las notas de teoría
command.runResponde a /modelo
turn.stepAntes de cada request del loop principal, pone el modelo elegido; después, suma lo que la API informó de la respuesta
turn.start, turn.completeAbren y cierran cada turno en el historial del panel de estadísticas
tool.callCuenta y cronometra cada herramienta sin modificar la llamada; responde la de las notas de teoría
tool.checkAprueba la herramienta de las notas, que no cambia nada, para que no pida permiso
prompt.composeCon las notas encendidas, agrega al system prompt el pedido de anotarlas
agent.spawnAnota cada agente que se lanza, con su tipo y descripción
session.endReinicia los números con un /clear
ui.renderDibuja la banda arriba del prompt y el panel de estadísticas
ui.messageRecibe el puntaje de una partida terminada y guarda el récord

Además, en session.start lanza en segundo plano la

Source 32 files
hooks/register.tsx 606 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { GameData } from './arcade'
5import { GAMES } from './catalog'
6import { addStep, addTool, closeAgent, closeTurn, EMPTY, isDone, openAgent, openTurn, startTool, syncAgents } from './history'
7import { FAMILIES, latest, pickOfId, pickOfName, pickOfText } from './models'
8import type { Pick } from './models'
9import { drawPane, PANE } from './pane'
10import { liveAgents, plainData } from './rows'
11import type { LiveProps } from './rows'
12import type { Best, Level } from '../types'
13import { paint } from './paint'
14import { priceLabel, statsSegs, tally } from './stats'
15import { addNote, isLevel, LEVELS, noteOf, SECTION_ID, sectionFor, SPEC, TOOL } from './theory'
16import { selfUpdate } from './update'
17import type { Host } from './update'
18
19const COMMAND = 'modelo'
20const NAMES = ['auto', ...FAMILIES.map(f => f.choice)].join(' | ')
21const INK = '#18181B'
22// What the band draws before its first chip.
23const HEAD = '▌ MODELO '
24
25// Below these widths the band drops the note, then the unpicked names.
26const NOTE_COLUMNS = 106
27const NAME_COLUMNS = 70
28
29const WAITING = 'costo, tokens y cache: tras la próxima respuesta'
30
31const choice = atom({ plugin: 'model-picker', key: 'choice' } as const, 'auto')
32// The family whose version dropdown is open; '' while none is.
33const open = atom({ plugin: 'model-picker', key: 'open' } as const, '')
34// What the API reported of the session's responses; null before the first.
35const stats = atom({ plugin: 'model-picker', key: 'stats' } as const, null)
36// What the stats pane charts: the session's turns, models and tools, and its tab.
37const history = atom({ plugin: 'model-picker', key: 'record' } as const, EMPTY)
38const tabOf = atom({ plugin: 'model-picker', key: 'tab' } as const, 'costo')
39// Whether the agents tab lists the finished ones.
40const showDone = atom({ plugin: 'model-picker', key: 'showDone' } as const, true)
41// When the model was last switched, while its chip is still lit; 0 otherwise.
42const flash = atom({ plugin: 'model-picker', key: 'flash' } as const, 0)
43
44// The games tab: whether it is offered this session (it is, unless turned off), the game shown, the best scores.
45const gamesOn = atom({ plugin: 'model-picker', key: 'games' } as const, true)
46const gameOf = atom({ plugin: 'model-picker', key: 'game' } as const, 'pong')
47const best = atom({ plugin: 'model-picker', key: 'best' } as const, {})
48// Whether the list of games is open.
49const menu = atom({ plugin: 'model-picker', key: 'menu' } as const, false)
50
51// The theory tab: whether the agent is asked for notes (it is, unless turned off), how deep, and the notes.
52const theoryOn = atom({ plugin: 'model-picker', key: 'theory' } as const, true)
53const levelOf = atom({ plugin: 'model-picker', key: 'level' } as const, 'aprender')
54const notes = atom({ plugin: 'model-picker', key: 'notes' } as const, [])
55
56// The key the notes' level is kept under between sessions.
57const LEVEL_KEY = 'theory.level'
58
59// The key the best scores are kept under between sessions.
60const BEST_KEY = 'games.best'
61
62const FLASH_MS = 600
63const AGENT_POLL_MS = 2000
64const FLASH_FILL = '#FFFFFF'
65
66const OPEN = { id: PANE, title: 'Estadísticas', focus: true, closeOnEscape: true, columns: 72 } as const
67
68// Shows the stats pane, or closes it when it is up; says whether it is up now.
69const togglePane = async ($: EngineInterface): Promise<boolean> => {
70  const mine = (await $.ui.panes()).find(pane => pane.id === PANE)
71  if (mine?.isShown) {
72    await $.ui.close({ id: PANE })
73
74    return false
75  }
76
77  // One that is open but not drawn (too narrow, or behind another tab) is reopened so it surfaces.
78  if (mine !== undefined) await $.ui.close({ id: PANE })
79  await $.ui.open(OPEN)
80
81  return true
82}
83
84// What the pane shows of the session beyond its own history; nothing where it cannot be read.
85const sessionUsage = async ($: EngineInterface) => {
86  try {
87    const usage = await $.session.usage()
88
89    return { startedAt: usage.startedAt, percent: usage.context.percent, usd: usage.cost?.usd }
90  } catch {
91    return undefined
92  }
93}
94
95// The session's own model as `/model` names it (`Opus 5.5`, `claude-opus-5-5`).
96const pickOfSession = async ($: EngineInterface): Promise<Pick | undefined> => {
97  try {
98    return pickOfName(await $.session.model())
99  } catch {
100    return undefined
101  }
102}
103
104// The main loop's requests name the picked model (`turn.step` below), which
105// is instant and touches neither `/model` nor the saved default. Picking the
106// session's own model drops the override.
107const switchTo = async ($: EngineInterface, target: Pick): Promise<void> => {
108  const own = await pickOfSession($)
109  const isOwn = own?.family === target.family && own.version.version === target.version.version
110
111  await update($, choice, () => (isOwn ? 'auto' : target.version.model))
112  await update($, open, () => '')
113  $.ui.invalidate('ui.render')
114
115  // The chip lights up for a moment; a switch is done whether or not it does.
116  try {
117    const at = await $.clock.now()
118    await update($, flash, () => at)
119    $.clock.after(FLASH_MS, () => void update($, flash, was => (was === at ? 0 : was)))
120  } catch {
121    // no clock, no light
122  }
123}
124
125// Brings the agents the pane lists up to Claude Code's own list, while any is at work.
126const pollAgents = async ($: EngineInterface): Promise<void> => {
127  try {
128    const data = await read($, history)
129    if (liveAgents(data) === 0) return
130
131    const list = await $.agent.list()
132    const now = await $.clock.now()
133    const next = syncAgents(data, list, now)
134    if (next !== data) await update($, history, was => syncAgents(was, list, now))
135  } catch {
136    // the list is a refinement: the pane keeps what the hooks saw
137  }
138}
139
140// Sets how deep the notes go, for this session and the next ones.
141const setLevel = async ($: EngineInterface, level: Level): Promise<void> => {
142  await update($, levelOf, () => level)
143  try {
144    await $.store.set(LEVEL_KEY, level)
145  } catch {
146    // kept for the session all the same
147  }
148}
149
150// The host as the self-update reaches it.
151const hostOf = ($: EngineInterface): Host => ({
152  name: $.plugin.name,
153  root: $.plugin.root,
154  now: () => $.clock.now(),
155  get: key => $.store.get(key),
156  set: (key, value) => $.store.set(key, value),
157  read: path => $.fs.read(path),
158  exists: path => $.fs.exists(path),
159  fetch: url => $.http.fetch(url),
160  run: (argv, init) => $.process.run(argv, init),
161  toast: text => $.ui.toast(text),
162})
163
164export const register: Register = (on, options) => {
165  on('session.start', async ($, e, next) => {
166    await $.command.register({
167      name: COMMAND,
168      description: `Elige el modelo de las próximas requests (${NAMES}) y su versión: /${COMMAND} opus 4.8; /${COMMAND} stats abre las estadísticas`,
169    })
170
171    // Left running: the session does not wait on the network to start.
172    if (options.autoUpdate !== false) void selfUpdate(hostOf($))
173
174    // The games are offered unless the option says not; their best scores come from the store.
175    try {
176      if (options.games === false) await update($, gamesOn, () => false)
177
178      const kept = (await $.store.get(BEST_KEY)) as Best | undefined
179      if (kept !== undefined && kept !== null) {
180        const scores = Object.fromEntries(Object.entries(kept).filter(([, score]) => typeof score === 'number'))
181        await update($, best, was => ({ ...was, ...scores }))
182      }
183    } catch {
184      // no store: the scores start at zero
185    }
186
187    // The tool the agent tells its notes through, and the level they were last left at.
188    try {
189      if (options.theory === false) await update($, theoryOn, () => false)
190      await $.tool.register(SPEC)
191
192      const kept = await $.store.get(LEVEL_KEY)
193      if (isLevel(kept)) await update($, levelOf, () => kept)
194    } catch {
195      // without the tool the tab stays empty
196    }
197
198    try {
199      $.clock.every(AGENT_POLL_MS, () => void pollAgents($))
200    } catch {
201      // without the timer the agents still show what the hooks saw of them
202    }
203
204    return next(e)
205  })
206
207  on('command.run', { command: COMMAND }, async ($, e) => {
208    const text = e.args.trim().toLowerCase()
209
210    if (text === '') {
211      const own = await pickOfSession($)
212
213      return { text: `Modelo: ${own ? `${own.family.label} ${own.version.version}` : 'desconocido'}. Uso: /${COMMAND} ${NAMES} [versión]` }
214    }
215
216    if (text === 'juegos') {
217      const isOn = !(await read($, gamesOn))
218      await update($, gamesOn, () => isOn)
219      if (!isOn) await update($, tabOf, was => (was === 'juegos' ? 'costo' : was))
220
221      return { text: `Juegos: ${isOn ? 'habilitados (pestaña ▶ Jugar del panel de estadísticas)' : 'deshabilitados'}` }
222    }
223
224    if (text === 'teoria' || text.startsWith('teoria ')) {
225      const word = text.slice('teoria'.length).trim()
226      if (isLevel(word)) await setLevel($, word)
227
228      const isOn = word === 'on' || isLevel(word) ? true : word === 'off' ? false : word === '' ? !(await read($, theoryOn)) : undefined
229      if (isOn === undefined) return { text: `Uso: /${COMMAND} teoria [on | off | aprender | experto]` }
230
231      await update($, theoryOn, () => isOn)
232
233      return {
234        text: isOn ? `Notas de teoría: encendidas, nivel ${LEVELS[await read($, levelOf)]} (pestaña Teoría del panel)` : 'Notas de teoría: apagadas',
235      }
236    }
237
238    if (text === 'stats') {
239      const isUp = await togglePane($)
240
241      return { text: `Estadísticas: ${isUp ? 'abiertas' : 'cerradas'}` }
242    }
243
244    if (text === 'auto') {
245      await update($, choice, () => 'auto')
246      $.ui.invalidate('ui.render')
247
248      return { text: 'Modelo: el de la sesión' }
249    }
250
251    const target = pickOfText(text)
252    if (target === undefined) return { text: `Modelo desconocido. Uso: /${COMMAND} ${NAMES} [versión]` }
253
254    await switchTo($, target)
255
256    return { text: `Modelo: ${target.family.label} ${target.version.version}` }
257  })
258
259  // The main loop's requests name the picked model; a subagent keeps its own.
260  // What the API reports of every response is tallied for the band.
261  on('turn.step', async function* ($, e, next) {
262    const isMain = e.agentId === undefined
263    const override = isMain ? pickOfId(await read($, choice)) : undefined
264    const response = yield* next(override === undefined ? e : { ...e, model: override.version.model })
265
266    const usage = response.usage
267    if (usage !== null) await update($, stats, was => tally(was, e, usage, isMain))
268
269    // The pane's record is a side note: it must never fail the request.
270    try {
271      const now = await $.clock.now()
272      await update($, history, was => addStep(was, { turnId: e.turnId, isMain, agentId: e.agentId }, usage, now))
273    } catch {
274      // the request already answered; its chart just misses a point
275    }
276
277    return response
278  })
279
280  // While the notes are on and the request offers their tool, the system prompt asks for them.
281  on('prompt.compose', async ($, e, next) => {
282    const composed = await next(e)
283
284    try {
285      if (!e.tools.includes(TOOL) || !(await read($, theoryOn))) return composed
286
287      const text = sectionFor(await read($, levelOf))
288      const others = composed.sections.filter(section => section.id !== SECTION_ID)
289
290      return { sections: [...others, { id: SECTION_ID, text, scope: 'session' as const }] }
291    } catch {
292      return composed
293    }
294  })
295
296  // A note is the agent's own to tell: it changes nothing, so it is never asked about.
297  on('tool.check', { tool: 'mcp__model-picker__teoria' }, () => ({ decision: 'allow' as const })).catch(($, e, next) => next(e))
298
299  on('turn.start', async ($, e, next) => {
300    try {
301      const now = await $.clock.now()
302      await update($, history, was => openTurn(was, e.turnId, now))
303    } catch {
304      // the turn runs all the same
305    }
306
307    return next(e)
308  })
309
310  on('turn.complete', async ($, e, next) => {
311    const done = await next(e)
312
313    try {
314      const agentId = e.agentId
315      if (agentId === undefined) {
316        await update($, history, was => closeTurn(was, { turnId: e.turnId, durationMs: e.durationMs, reason: e.reason }))
317      } else {
318        const now = await $.clock.now()
319        await update($, history, was => closeAgent(was, { id: agentId, reason: e.reason }, now))
320      }
321    } catch {
322      // the answer is already out
323    }
324
325    return done
326  })
327
328  // A spawned agent is listed from the start, under the name its spawn gave it.
329  on('agent.spawn', async ($, e, next) => {
330    const spawned = await next(e)
331
332    try {
333      const id = spawned.deny === undefined ? spawned.agentId : undefined
334      if (id !== undefined) {
335        const now = await $.clock.now()
336        await update($, history, was =>
337          openAgent(was, { id, type: e.subagentType, description: e.description, parentId: e.parentAgentId, model: spawned.model }, now),
338        )
339      }
340    } catch {
341      // the agent runs all the same
342    }
343
344    return spawned
345  }).catch(($, e, next) => next(e))
346
347  // Every tool call of every loop is timed and counted, and none is ever changed.
348  on('tool.call', async ($, e, next) => {
349    // The mod's own tool: the note goes to the theory tab, and is no tool call of the session's.
350    if (e.tool === TOOL) {
351      const fields = noteOf(e as unknown as Record<string, unknown>)
352      if (fields === undefined) return { deny: 'La nota necesita `title` y `explanation`, los dos con texto.' }
353
354      const at = await $.clock.now()
355      await update($, notes, was => addNote(was, fields, at))
356
357      return { result: `Anotado en el panel: ${fields.title}` }
358    }
359
360    const started = await $.clock.now()
361    const agentId = e.agentId
362    let isError = false
363
364    if (agentId !== undefined) {
365      try {
366        await update($, history, was => startTool(was, agentId, e.tool, started))
367      } catch {
368        // the call goes on unlisted
369      }
370    }
371
372    try {
373      const ran = await next(e)
374      isError = ran.deny !== undefined || ran.isError === true
375
376      return ran
377    } catch (error) {
378      isError = true
379
380      throw error
381    } finally {
382      try {
383        const ms = (await $.clock.now()) - started
384        await update($, history, was => addTool(was, { name: e.tool, ms, isError, agentId }))
385      } catch {
386        // the call is over; only its count is lost
387      }
388    }
389  }).catch(($, e, next) => next(e))
390
391  // A /clear starts the session's numbers over.
392  on('session.end', async ($, e, next) => {
393    if (e.reason === 'clear') {
394      await update($, history, () => EMPTY)
395      await update($, stats, () => null)
396      await update($, notes, () => [])
397    }
398
399    return next(e)
400  })
401
402  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
403    const record = await read($, history)
404    const hasGames = await read($, gamesOn)
405    const picked = await read($, tabOf)
406    const current = picked === 'juegos' && !hasGames ? 'costo' : picked
407    const game = await read($, gameOf)
408    const isShowingDone = await read($, showDone)
409    const now = await $.clock.now()
410    const usage = await sessionUsage($)
411    const parts = $.ui.resolve(e)
412    // The player's color is the active model's.
413    const color = (pickOfId(await read($, choice)) ?? (await pickOfSession($)))?.family.color ?? 'claude'
414    const data: GameData = {
415      cost: record.total.cost,
416      tools: record.tools.map(tool => ({ name: tool.name, count: tool.count, errors: tool.errors })),
417      agents: record.agents.map(agent => ({
418        id: agent.id,
419        type: agent.type,
420        model: agent.model,
421        steps: agent.steps,
422        cost: agent.cost,
423        state: agent.status === 'failed' || agent.status === 'killed' ? 'failed' : isDone(agent) ? 'done' : 'live',
424      })),
425    }
426    const room = { game, color, columns: e.props.bodyColumns, rows: e.props.scroll.bodyRows, seed: Math.floor(now) % 1_000_000_007, data }
427
428    return drawPane(
429      h,
430      parts,
431      {
432        columns: e.props.bodyColumns,
433        tab: current,
434        history: record,
435        now,
436        showDone: isShowingDone,
437        usage,
438        games: hasGames,
439        game,
440        best: await read($, best),
441        menu: await read($, menu),
442        theory: await read($, theoryOn),
443        level: await read($, levelOf),
444        notes: await read($, notes),
445      },
446      {
447        onTab: next => update($, tabOf, () => next),
448        onShowDone: show => update($, showDone, () => show),
449        onGame: async next => {
450          await update($, gameOf, () => next)
451          await update($, menu, () => false)
452        },
453        onMenu: isOpen => update($, menu, () => isOpen),
454        onTheory: isOn => update($, theoryOn, () => isOn),
455        onLevel: level => setLevel($, level),
456        onForget: () => update($, notes, () => []),
457      },
458      // Where the surface runs surface modules, the rows are drawn in motion and the games can run.
459      'Client' in parts ? props => <parts.Client key="live" module="./live.tsx" props={plainData(props)} /> : undefined,
460      'Client' in parts ? () => <parts.Client key="game" module="./games.tsx" props={plainData(room)} /> : undefined,
461    )
462  })
463
464  // A finished game posts its score: the best of each is kept, between sessions too.
465  on('ui.message', async ($, e, next) => {
466    const data = e.data as { game?: unknown; score?: unknown } | null
467    const game = data?.game
468    if (e.element !== 'game' || typeof game !== 'string' || !GAMES.some(def => def.id === game) || typeof data?.score !== 'number') return next(e)
469
470    const score = data.score
471    const was = await read($, best)
472
473    if (score > (was[game] ?? 0)) {
474      const now = { ...was, [game]: score }
475      await update($, best, () => now)
476      try {
477        await $.store.set(BEST_KEY, now)
478      } catch {
479        // kept for the session all the same
480      }
481    }
482
483    return {}
484  })
485
486  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
487    if (e.props.hasSurvey) return next(e)
488
489    const parts = $.ui.resolve(e)
490    const { Box, Button, Text } = parts
491    const own = await pickOfSession($)
492    const isLit = (await read($, flash)) !== 0
493    const working = liveAgents(await read($, history))
494    const beat: LiveProps = {
495      tab: 'band',
496      now: 0,
497      rows: [{ segs: [{ text: '●', alt: '◉', fx: 'pulse', color: 'success' }, { text: `${working} `, color: 'success' }] }],
498    }
499    const override = pickOfId(await read($, choice))
500    const picked = override ?? own
501    const shown = await read($, open)
502    const columns = e.props.bodyColumns
503    const hasNames = columns >= NAME_COLUMNS
504    const opened = FAMILIES.find(f => f.choice === shown)
505    const seen = await read($, stats)
506    // Before the session's first response there is nothing to report yet.
507    const facts: LiveProps = {
508      tab: 'band',
509      now: 0,
510      rows: [
511        {
512          segs:
513            seen === null
514              ? [{ text: WAITING, dim: true }]
515              : statsSegs(seen, override !== undefined, columns - 2, (await sessionUsage($))?.percent),
516        },
517      ],
518    }
519
520    const chips = FAMILIES.map(family => {
521      const isActive = picked?.family === family
522      const version = isActive ? picked.version.version : latest(family).version.version
523      const text = isActive
524        ? ` ${family.glyph} ${family.label} ${version} ${family === opened ? '▴' : '▾'} `
525        : ` ${family.glyph}${hasNames ? ` ${family.label} ${version}` : ''} `
526
527      return { family, isActive, text }
528    })
529
530    // The dropdown hangs under its family's chip: the cells drawn before it.
531    const at = chips.findIndex(chip => chip.family === opened)
532    const indent = HEAD.length + chips.slice(0, at).reduce((sum, chip) => sum + [...chip.text].length, 0)
533
534    return (
535      <Box flexDirection="column">
536        <Box>
537          <Text color={picked?.family.color} bold>
538            ▌
539          </Text>
540          <Text dimColor> MODELO </Text>
541          {chips.map(({ family, isActive, text }) => (
542            <Button
543              key={family.choice}
544              plain
545              dimColor={!isActive}
546              // The active chip opens its versions; another switches to its newest.
547              onPress={() =>
548                isActive
549                  ? update($, open, now => (now === family.choice ? '' : family.choice))
550                  : switchTo($, latest(family))
551              }
552            >
553              {isActive ? (
554                <Text backgroundColor={isLit ? FLASH_FILL : family.color} color={INK} bold>
555                  {text}
556                </Text>
557              ) : (
558                <Text color={family.color}>{text}</Text>
559              )}
560            </Button>
561          ))}
562          <Button key="stats" plain dimColor onPress={() => togglePane($)}>
563            <Text>{hasNames ? ' ▦ stats ' : ' ▦ '}</Text>
564          </Button>
565          {working > 0 &&
566            ('Client' in parts ? (
567              <parts.Client key="agents" module="./live.tsx" props={plainData(beat)} />
568            ) : (
569              <Text color="success">●{working} </Text>
570            ))}
571          {columns >= NOTE_COLUMNS && picked !== undefined && (
572            <Text color={picked.family.color} italic>
573              {'  '}
574              {picked.family.note}
575            </Text>
576          )}
577        </Box>
578        {opened?.versions.map(version => {
579          const isCurrent = picked?.family === opened && picked.version.version === version.version
580
581          return (
582            <Box marginLeft={indent}>
583              <Button
584                key={`${opened.choice}-${version.version}`}
585                plain
586                dimColor={!isCurrent}
587                onPress={() => switchTo($, { family: opened, version })}
588              >
589                <Text color={opened.color} bold={isCurrent}>
590                  {` ${isCurrent ? '●' : '○'} ${opened.label} ${version.version} `}
591                </Text>
592              </Button>
593              <Text dimColor>{priceLabel(version.price)} por MTok</Text>
594            </Box>
595          )
596        })}
597        {opened === undefined && (
598          <Box marginLeft={2}>
599            {'Client' in parts ? <parts.Client key="datos" module="./live.tsx" props={plainData(facts)} /> : paint(h, parts, facts, null)}
600          </Box>
601        )}
602      </Box>
603    )
604  })
605}
606
hooks/arcade.ts 124 lines
1// What every game of the stats pane is, so the module that runs them knows
2// none of them: a state, and the functions that make, move and draw it.
3
4import type { Phase } from './pong'
5import type { Seg } from './rows'
6
7export type { Phase } from './pong'
8
9export type Pointer = { type: 'down' | 'move' | 'up'; x: number; y: number; button?: 'left' | 'middle' | 'right' }
10
11// What the mod knows of the session, for the games made of it.
12export type GameData = {
13  cost: number
14  tools: { name: string; count: number; errors: number }[]
15  agents: { id: string; type: string; model: string; steps: number; cost: number; state: 'live' | 'done' | 'failed' }[]
16}
17
18export const NO_DATA: GameData = { cost: 0, tools: [], agents: [] }
19
20export type Playable = { phase: Phase }
21
22export type GameDef<S extends Playable> = {
23  id: string
24  label: string
25  glyph: string
26  // The line of keys under the field.
27  hint: string
28  // The field it can be played in: cells across and rows of text down.
29  minW: number
30  maxW: number
31  minRows: number
32  maxRows: number
33  // A game with no score worth keeping.
34  noRecord?: boolean
35  // Milliseconds between its steps, when it needs fewer than the module's own twenty a second.
36  every?: number
37  // It draws its own notices (waiting, paused, over).
38  ownNotice?: boolean
39  create: (w: number, rows: number, seed: number, data: GameData) => S
40  // Absent for a game that only moves when played.
41  step?: (s: S, dt: number, data: GameData) => S
42  key: (s: S, key: string) => S
43  // The pointer over the field, in its cells.
44  pointer: (s: S, e: Pointer) => S
45  score: (s: S) => number
46  // The line above the field, and the field itself: `w` cells by `rows` rows.
47  hud?: (s: S, color: string, data: GameData) => Seg[]
48  draw: (s: S, color: string, data: GameData) => Seg[][]
49  // What a finished game says, when not just that it is over.
50  over?: (s: S) => string
51}
52
53export const clamp = (n: number, low: number, high: number): number => Math.min(high, Math.max(low, n))
54
55/** The next number of a seeded sequence, and that number as a fraction of one. */
56export const lcg = (seed: number): number => (Math.imul(seed, 1664525) + 1013904223) >>> 0
57export const unit = (seed: number): number => seed / 4294967296
58/** A whole number below `n` from a seed. */
59export const below = (seed: number, n: number): number => Math.floor(unit(seed) * n)
60
61const SPACE = ' '
62const normal = (key: string): string => (key === 'space' ? SPACE : key.length === 1 ? key.toLowerCase() : key)
63
64/**
65 * A key, as every game takes it: `r` starts over, `p` or Enter pause and
66 * resume, space starts a game that waits and resumes a paused one, and
67 * anything else is the game's own (starting it if it waited).
68 */
69export const pressKey = <S extends Playable>(def: GameDef<S>, s: S, key: string, fresh: () => S): S => {
70  const k = normal(key)
71
72  if (k === 'r') return { ...fresh(), phase: 'playing' }
73  if (s.phase === 'over') return k === SPACE || k === 'return' ? { ...fresh(), phase: 'playing' } : s
74  if (k === 'p' || k === 'return') return { ...s, phase: s.phase === 'playing' ? 'paused' : 'playing' }
75  if (s.phase === 'paused') return k === SPACE ? { ...s, phase: 'playing' } : s
76  if (s.phase === 'ready') return k === SPACE ? { ...s, phase: 'playing' } : def.key({ ...s, phase: 'playing' }, k)
77
78  return def.key(s, k)
79}
80
81/** The pointer, as every game takes it: a press starts, resumes or restarts; the rest is the game's own while it runs. */
82export const pressPointer = <S extends Playable>(def: GameDef<S>, s: S, e: Pointer, fresh: () => S): S => {
83  if (e.type === 'down') {
84    if (s.phase === 'over') return { ...fresh(), phase: 'playing' }
85    if (s.phase === 'paused') return { ...s, phase: 'playing' }
86    if (s.phase === 'ready') return def.pointer({ ...s, phase: 'playing' }, e)
87  }
88
89  return s.phase === 'playing' ? def.pointer(s, e) : s
90}
91
92const centered = (text: string, w: number, color?: string): Seg[] => {
93  const glyphs = [...text].slice(0, w)
94  const left = Math.floor((w - glyphs.length) / 2)
95
96  return [
97    { text: ' '.repeat(left) },
98    { text: glyphs.join(''), bold: true, ...(color === undefined ? {} : { color }) },
99    { text: ' '.repeat(Math.max(0, w - left - glyphs.length)) },
100  ]
101}
102
103const NOTICE: Readonly<Record<Exclude<Phase, 'playing' | 'over'>, string>> = {
104  ready: 'clic o espacio para jugar',
105  paused: 'PAUSA · espacio sigue',
106}
107
108/** A game as it is shown: its line above, its field with a notice over it while it is not played, and its keys. */
109export const screenOf = <S extends Playable>(def: GameDef<S>, s: S, w: number, color: string, data: GameData): Seg[][] => {
110  const field = def.draw(s, color, data)
111  const middle = Math.max(0, Math.floor(field.length / 2) - 1)
112
113  if (def.ownNotice !== true && s.phase !== 'playing') {
114    if (s.phase === 'over') {
115      field[middle] = centered(def.over?.(s) ?? 'GAME OVER', w, 'error')
116      if (field[middle + 1] !== undefined) field[middle + 1] = centered('r para otra', w)
117    } else {
118      field[middle] = centered(NOTICE[s.phase], w)
119    }
120  }
121
122  return [...(def.hud === undefined ? [] : [def.hud(s, color, data)]), ...field, [{ text: def.hint, dim: true }]]
123}
124
hooks/catalog.ts 42 lines
1// The games the stats pane offers, in the order its menu lists them.
2
3import type { GameDef } from './arcade'
4import { asteroids } from './asteroids'
5import { breakout } from './breakout'
6import { invaders, pong } from './classics'
7import { dino } from './dino'
8import { flappy } from './flappy'
9import { frogger } from './frogger'
10import { g2048 } from './g2048'
11import { life } from './life'
12import { mines } from './mines'
13import { race, tokens } from './sessiongames'
14import { snake } from './snake'
15import { sokoban } from './sokoban'
16import { tetris } from './tetris'
17
18// Each game keeps a state of its own shape; the catalog only ever hands a
19// state back to the game that made it.
20// eslint-disable-next-line @typescript-eslint/no-explicit-any
21export type AnyGame = GameDef<any>
22
23export const GAMES: readonly AnyGame[] = [
24  pong,
25  invaders,
26  snake,
27  tetris,
28  breakout,
29  g2048,
30  mines,
31  flappy,
32  dino,
33  frogger,
34  asteroids,
35  sokoban,
36  life,
37  tokens,
38  race,
39]
40
41export const gameOf = (id: string): AnyGame => GAMES.find(game => game.id === id) ?? (GAMES[0] as AnyGame)
42
hooks/history.ts 331 lines
1import type { AgentStat, AgentStatus, History, ModelStat, ToolStat, Turn } from '../types'
2import { pickOfId } from './models'
3import { costParts } from './stats'
4import type { Usage } from './stats'
5
6export const TURN_CAP = 200
7export const TOOL_CAP = 40
8export const AGENT_CAP = 100
9// How many of an agent's latest requests its sparkline keeps.
10export const COSTS_KEPT = 12
11const OTHERS = 'otros'
12
13export const EMPTY: History = {
14  turns: [],
15  dropped: 0,
16  models: {},
17  tools: [],
18  agents: [],
19  total: { cost: 0, agentCost: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, steps: 0 },
20}
21
22const blank = (turnId: string, startedAt: number): Turn => ({
23  turnId,
24  startedAt,
25  steps: 0,
26  model: '',
27  cost: 0,
28  costOut: 0,
29  agentCost: 0,
30  input: 0,
31  output: 0,
32  cacheRead: 0,
33  cacheWrite: 0,
34})
35
36// The turn list with `turnId` last, opened if it was not there; the oldest go past the cap.
37const withTurn = (h: History, turnId: string, startedAt: number): History => {
38  if (h.turns.some(turn => turn.turnId === turnId)) return h
39
40  const turns = [...h.turns, blank(turnId, startedAt)]
41  const cut = Math.max(0, turns.length - TURN_CAP)
42
43  return { ...h, turns: turns.slice(cut), dropped: h.dropped + cut }
44}
45
46const mapTurn = (h: History, turnId: string, change: (turn: Turn) => Turn): History => ({
47  ...h,
48  turns: h.turns.map(turn => (turn.turnId === turnId ? change(turn) : turn)),
49})
50
51const OVER: readonly AgentStatus[] = ['completed', 'failed', 'killed']
52
53/** Whether an agent's loop is over. */
54export const isDone = (agent: AgentStat): boolean => agent.endedAt !== undefined || OVER.includes(agent.status)
55
56const blankAgent = (id: string, startedAt: number): AgentStat => ({
57  id,
58  type: 'agente',
59  description: '',
60  model: '',
61  startedAt,
62  status: 'running',
63  steps: 0,
64  cost: 0,
65  costs: [],
66  input: 0,
67  output: 0,
68  tools: [],
69})
70
71// The agent list with `id` in it, added if it was not; past the cap the finished ones longest gone go first.
72const withAgent = (h: History, id: string, now: number): History => {
73  if (h.agents.some(agent => agent.id === id)) return h
74
75  const agents = [...h.agents, blankAgent(id, now)]
76  if (agents.length <= AGENT_CAP) return { ...h, agents }
77
78  const oldest = agents
79    .filter(isDone)
80    .sort((a, b) => (a.endedAt ?? a.startedAt) - (b.endedAt ?? b.startedAt))
81    .slice(0, agents.length - AGENT_CAP)
82
83  return { ...h, agents: agents.filter(agent => !oldest.includes(agent)).slice(-AGENT_CAP) }
84}
85
86const mapAgent = (h: History, id: string, change: (agent: AgentStat) => AgentStat): History => ({
87  ...h,
88  agents: h.agents.map(agent => (agent.id === id ? change(agent) : agent)),
89})
90
91// An agent seen working again after it had ended (a teammate's next turn) runs again.
92const revived = (agent: AgentStat): AgentStat => {
93  if (agent.endedAt === undefined) return agent
94
95  const { endedAt: _, ...rest } = agent
96
97  return { ...rest, status: 'running' }
98}
99
100/** The history with agent `seed.id` in it, named as its spawn named it; one already there keeps its numbers. */
101export const openAgent = (
102  h: History,
103  seed: { id: string; type?: string; description?: string; parentId?: string; model?: string },
104  now: number,
105): History =>
106  mapAgent(withAgent(h, seed.id, now), seed.id, agent => ({
107    ...agent,
108    type: seed.type ?? agent.type,
109    description: seed.description ?? agent.description,
110    ...(seed.parentId === undefined ? {} : { parentId: seed.parentId }),
111    model: agent.model === '' && seed.model !== undefined ? keyOf(seed.model) : agent.model,
112  }))
113
114/** The history with agent `agentId` inside a call of `tool` since `now`. */
115export const startTool = (h: History, agentId: string, tool: string, now: number): History =>
116  mapAgent(withAgent(h, agentId, now), agentId, agent => ({ ...revived(agent), busy: { tool, since: now } }))
117
118/** The history with agent `done.id` finished at `now`; an id it never saw is ignored. */
119export const closeAgent = (
120  h: History,
121  done: { id: string; reason: NonNullable<Turn['reason']> },
122  now: number,
123): History =>
124  h.agents.some(agent => agent.id === done.id)
125    ? mapAgent(h, done.id, agent => {
126        const { busy: _, ...idle } = agent
127        const status: AgentStatus = done.reason === 'answer' ? 'completed' : done.reason === 'aborted' ? 'killed' : 'failed'
128
129        return { ...idle, endedAt: now, status }
130      })
131    : h
132
133/**
134 * The history brought up to Claude Code's own list of agents: each one listed
135 * takes its type, description, parent and status from it, and one it reports
136 * over is ended. The same history when nothing differs.
137 */
138export const syncAgents = (
139  h: History,
140  list: readonly { id: string; type: string; description: string; status: AgentStatus; parentId?: string }[],
141  now: number,
142): History => {
143  let next = h
144
145  for (const info of list) {
146    const was = next.agents.find(agent => agent.id === info.id)
147    const isOver = OVER.includes(info.status)
148    const isSame =
149      was !== undefined &&
150      was.type === info.type &&
151      was.description === info.description &&
152      was.parentId === info.parentId &&
153      was.status === info.status &&
154      (was.endedAt !== undefined) === isOver
155
156    if (isSame) continue
157
158    next = mapAgent(withAgent(next, info.id, now), info.id, agent => {
159      const { busy, endedAt, parentId: _, ...rest } = agent
160
161      return {
162        ...rest,
163        type: info.type,
164        description: info.description,
165        status: info.status,
166        ...(info.parentId === undefined ? {} : { parentId: info.parentId }),
167        ...(isOver ? { endedAt: endedAt ?? now } : busy === undefined ? {} : { busy }),
168      }
169    })
170  }
171
172  return next
173}
174
175/** A model id as the model list names it, else as the API wrote it. */
176const keyOf = (id: string): string => pickOfId(id)?.version.model ?? id
177
178/** The history with turn `turnId` open; a turn already open is left as it is. */
179export const openTurn = (h: History, turnId: string, now: number): History => withTurn(h, turnId, now)
180
181/**
182 * The history after one more response. A main-loop response adds to its turn
183 * (opening it if `turn.start` never came), to its model and to the session; a
184 * subagent's adds to its model and the session, and to the latest turn's
185 * `agentCost`. A response with no usage still counts as a step.
186 */
187export const addStep = (
188  h: History,
189  step: { turnId: string; isMain: boolean; agentId?: string },
190  usage: Usage | null,
191  now: number,
192): History => {
193  const parts = usage === null ? null : costParts(usage)
194  const cost = parts === null ? 0 : parts.input + parts.output + parts.cacheRead + parts.cacheWrite
195  const prompt = usage === null ? 0 : usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens
196
197  const next = step.isMain ? withTurn(h, step.turnId, now) : h
198
199  const models = { ...next.models }
200  if (usage !== null) {
201    const key = keyOf(usage.model)
202    const was: ModelStat = models[key] ?? { cost: 0, input: 0, output: 0, steps: 0 }
203    models[key] = { cost: was.cost + cost, input: was.input + prompt, output: was.output + usage.output_tokens, steps: was.steps + 1 }
204  }
205
206  const total = {
207    ...next.total,
208    cost: next.total.cost + cost,
209    agentCost: next.total.agentCost + (step.isMain ? 0 : cost),
210    input: next.total.input + (usage?.input_tokens ?? 0),
211    output: next.total.output + (usage?.output_tokens ?? 0),
212    cacheRead: next.total.cacheRead + (usage?.cache_read_input_tokens ?? 0),
213    cacheWrite: next.total.cacheWrite + (usage?.cache_creation_input_tokens ?? 0),
214    steps: next.total.steps + 1,
215  }
216
217  const base = { ...next, models, total }
218
219  if (step.isMain) {
220    return mapTurn(base, step.turnId, turn => ({
221      ...turn,
222      steps: turn.steps + 1,
223      model: usage === null ? turn.model : keyOf(usage.model),
224      cost: turn.cost + cost,
225      costOut: turn.costOut + (parts?.output ?? 0),
226      input: turn.input + (usage?.input_tokens ?? 0),
227      output: turn.output + (usage?.output_tokens ?? 0),
228      cacheRead: turn.cacheRead + (usage?.cache_read_input_tokens ?? 0),
229      cacheWrite: turn.cacheWrite + (usage?.cache_creation_input_tokens ?? 0),
230    }))
231  }
232
233  const last = base.turns[base.turns.length - 1]
234  const charged = last === undefined ? base : mapTurn(base, last.turnId, turn => ({ ...turn, agentCost: turn.agentCost + cost }))
235
236  if (step.agentId === undefined) return charged
237
238  return mapAgent(withAgent(charged, step.agentId, now), step.agentId, agent => ({
239    ...revived(agent),
240    steps: agent.steps + 1,
241    model: usage === null ? agent.model : keyOf(usage.model),
242    cost: agent.cost + cost,
243    costs: [...agent.costs, cost].slice(-COSTS_KEPT),
244    input: agent.input + prompt,
245    output: agent.output + (usage?.output_tokens ?? 0),
246  }))
247}
248
249/** The history with turn `done.turnId` finished; an id it never opened is ignored. */
250export const closeTurn = (
251  h: History,
252  done: { turnId: string; durationMs: number; reason: NonNullable<Turn['reason']> },
253): History =>
254  h.turns.some(turn => turn.turnId === done.turnId)
255    ? mapTurn(h, done.turnId, turn => ({ ...turn, durationMs: done.durationMs, reason: done.reason }))
256    : h
257
258/** The history after one more tool call, counted for the session and for the agent that made it. */
259export const addTool = (
260  h: History,
261  call: { name: string; ms: number; isError: boolean; agentId?: string },
262): History => {
263  const counted = { ...h, tools: counting(h.tools, call) }
264  if (call.agentId === undefined || !counted.agents.some(agent => agent.id === call.agentId)) return counted
265
266  // The agent's own count, and its call is over.
267  return mapAgent(counted, call.agentId, agent => {
268    const { busy: _, ...idle } = agent
269
270    return { ...idle, tools: counting(agent.tools, call) }
271  })
272}
273
274// A tool list after one more call; names past the cap are counted under `otros`.
275const counting = (tools: readonly ToolStat[], call: { name: string; ms: number; isError: boolean }): ToolStat[] => {
276  const named = tools.some(tool => tool.name === call.name)
277  const name = named || tools.filter(tool => tool.name !== OTHERS).length < TOOL_CAP ? call.name : OTHERS
278  const known = tools.some(tool => tool.name === name)
279
280  const bump = (tool: ToolStat): ToolStat => ({
281    ...tool,
282    count: tool.count + 1,
283    errors: tool.errors + (call.isError ? 1 : 0),
284    totalMs: tool.totalMs + Math.max(0, call.ms),
285  })
286
287  return known
288    ? tools.map(tool => (tool.name === name ? bump(tool) : tool))
289    : [...tools, bump({ name, count: 0, errors: 0, totalMs: 0 })]
290}
291
292/**
293 * The main loop's steps per time bucket between `from` and `to`: each turn's
294 * steps are spread evenly over the time it ran (up to `to` while it still runs).
295 */
296export const activity = (turns: readonly Turn[], from: number, to: number, buckets: number): number[] => {
297  const out: number[] = Array.from({ length: Math.max(0, buckets) }, () => 0)
298  const span = to - from
299  if (buckets <= 0 || span <= 0) return out
300
301  const size = span / buckets
302
303  for (const turn of turns) {
304    const start = turn.startedAt
305    const end = Math.max(start + 1, turn.startedAt + (turn.durationMs ?? to - turn.startedAt))
306    const perMs = turn.steps / (end - start)
307
308    for (let i = 0; i < buckets; i += 1) {
309      const low = Math.max(start, from + i * size)
310      const high = Math.min(end, from + (i + 1) * size)
311      if (high > low) out[i] = (out[i] ?? 0) + (high - low) * perMs
312    }
313  }
314
315  return out
316}
317
318/** Pace over the turns that finished: how many, their total and mean duration, and mean steps. */
319export const pace = (h: History): { turns: number; activeMs: number; avgMs: number; avgSteps: number } => {
320  const done = h.turns.filter(turn => turn.durationMs !== undefined)
321  const activeMs = done.reduce((all, turn) => all + (turn.durationMs ?? 0), 0)
322  const steps = done.reduce((all, turn) => all + turn.steps, 0)
323
324  return {
325    turns: done.length,
326    activeMs,
327    avgMs: done.length === 0 ? 0 : activeMs / done.length,
328    avgSteps: done.length === 0 ? 0 : steps / done.length,
329  }
330}
331
hooks/models.ts 128 lines
1export type Version = {
2  version: string
3  // The Claude API's id of the model.
4  model: string
5  // List price in dollars per million tokens: input, output.
6  price: readonly [input: number, output: number]
7  // Dollars per million cached input tokens read, where the list price names it.
8  cacheRead?: number
9}
10
11export type Family = {
12  choice: string
13  label: string
14  glyph: string
15  color: string
16  note: string
17  // Newest first: a family's chip shows the first, its dropdown lists them all.
18  versions: readonly Version[]
19}
20
21export type Pick = { family: Family; version: Version }
22
23// The versions the Claude API serves, by its own model ids, at its list prices.
24export const FAMILIES: readonly Family[] = [
25  {
26    choice: 'fable',
27    label: 'Fable',
28    glyph: '✦',
29    color: '#C084FC',
30    note: 'el más capaz',
31    versions: [
32      { version: '5.1', model: 'claude-fable-5-1', price: [10, 50], cacheRead: 0.25 },
33      { version: '5', model: 'claude-fable-5', price: [10, 50] },
34    ],
35  },
36  {
37    choice: 'opus',
38    label: 'Opus',
39    glyph: '◆',
40    color: '#FB923C',
41    note: 'razonamiento profundo',
42    versions: [
43      { version: '5.5', model: 'claude-opus-5-5', price: [4, 20], cacheRead: 0.2 },
44      { version: '5', model: 'claude-opus-5', price: [5, 25] },
45      { version: '4.8', model: 'claude-opus-4-8', price: [5, 25] },
46      { version: '4.7', model: 'claude-opus-4-7', price: [5, 25] },
47      { version: '4.6', model: 'claude-opus-4-6', price: [5, 25] },
48    ],
49  },
50  {
51    choice: 'sonnet',
52    label: 'Sonnet',
53    glyph: '▲',
54    color: '#38BDF8',
55    note: 'equilibrado',
56    versions: [
57      { version: '5.5', model: 'claude-sonnet-5-5', price: [2, 10], cacheRead: 0.2 },
58      { version: '5', model: 'claude-sonnet-5', price: [2, 10] },
59      { version: '4.6', model: 'claude-sonnet-4-6', price: [3, 15] },
60    ],
61  },
62  {
63    choice: 'haiku',
64    label: 'Haiku',
65    glyph: '●',
66    color: '#34D399',
67    note: 'rápido y barato',
68    versions: [
69      { version: '5.5', model: 'claude-haiku-5-5', price: [0.1, 0.5] },
70      { version: '4.5', model: 'claude-haiku-4-5', price: [1, 5] },
71    ],
72  },
73]
74
75export const latest = (family: Family): Pick => ({ family, version: family.versions[0] as Version })
76
77/**
78 * The family and version of a model id: the id itself, else the longest listed
79 * id it starts with (an id the API reports with a suffix).
80 */
81export const pickOfId = (id: string): Pick | undefined => {
82  let found: Pick | undefined
83
84  for (const family of FAMILIES) {
85    for (const version of family.versions) {
86      if (version.model === id) return { family, version }
87
88      const isLonger = found === undefined || version.model.length > found.version.model.length
89      if (id.startsWith(`${version.model}-`) && isLonger) found = { family, version }
90    }
91  }
92
93  return found
94}
95
96/** `opus`, `opus 4.8`: a family and, when written, one of its versions. */
97export const pickOfText = (text: string): Pick | undefined => {
98  const [name = '', written] = text.trim().toLowerCase().split(/\s+/)
99  const family = FAMILIES.find(f => f.choice === name)
100  if (family === undefined) return undefined
101
102  const version = family.versions.find(v => v.version === written)
103
104  return written === undefined ? latest(family) : version && { family, version }
105}
106
107/** The family and version a model name holds (`Opus 5.5`, `claude-opus-5-5`). */
108export const pickOfName = (name: string): Pick | undefined => {
109  const lower = name.toLowerCase()
110  const family = FAMILIES.find(f => lower.includes(f.choice))
111  if (family === undefined) return undefined
112
113  const written = /(\d+)(?:[.-](\d{1,2})(?!\d))?/.exec(lower)
114  const text = written === null ? undefined : [written[1], written[2]].filter(Boolean).join('.')
115  const known = family.versions.find(v => v.version === text)
116  const newest = latest(family).version
117
118  // A version the list lacks is still named as written, at no known price.
119  return { family, version: known ?? { ...newest, version: text ?? newest.version, model: '' } }
120}
121
122/** A model id as the band names it (`claude-opus-5-5` -> `Opus 5.5`). */
123export const nameOfId = (id: string): string => {
124  const known = pickOfId(id)
125
126  return known === undefined ? id : `${known.family.label} ${known.version.version}`
127}
128
hooks/pane.tsx 139 lines
1/** @jsx hyper */
2import type { EngineInterface, RenderNode } from 'claude-code'
3
4import type { Game, Level, Tab } from '../types'
5import { gameOf, GAMES } from './catalog'
6import { paint } from './paint'
7import type { Hyper } from './paint'
8import { headRow, rowsFor } from './rows'
9import type { LiveProps, View } from './rows'
10
11export const PANE = 'model-picker-stats'
12
13export const TABS: readonly { tab: Tab; label: string; hotkey: string }[] = [
14  { tab: 'costo', label: 'Costo', hotkey: '1' },
15  { tab: 'modelos', label: 'Modelos', hotkey: '2' },
16  { tab: 'tools', label: 'Tools', hotkey: '3' },
17  { tab: 'ritmo', label: 'Ritmo', hotkey: '4' },
18  { tab: 'agentes', label: 'Agentes', hotkey: '5' },
19  { tab: 'juegos', label: '▶ Jugar', hotkey: '6' },
20  { tab: 'teoria', label: 'Teoría', hotkey: '7' },
21]
22
23export type Parts = Pick<ReturnType<EngineInterface['ui']['resolve']>, 'Box' | 'Text' | 'Button'>
24
25// Draws the rows in motion. The hooks module makes it, since a surface module's
26// path is only read off that module's own source; absent where the surface runs none.
27export type Live = (props: LiveProps) => RenderNode | null | undefined
28
29export type Handlers = {
30  onTab: (tab: Tab) => unknown
31  onShowDone: (show: boolean) => unknown
32  onGame: (game: Game) => unknown
33  onMenu: (open: boolean) => unknown
34  onTheory: (isOn: boolean) => unknown
35  onLevel: (level: Level) => unknown
36  onForget: () => unknown
37}
38
39// Draws the game in play; the hooks module makes it, as it makes `Live`.
40export type Play = () => RenderNode | null | undefined
41
42/** The pane's props for its drawing: the header and the chosen tab's rows. */
43export const liveProps = (view: View): LiveProps => ({
44  tab: view.tab,
45  now: view.now,
46  rows: [headRow(view), ...rowsFor(view)],
47})
48
49/**
50 * The pane's tree: the tabs, then the header and the chosen tab. Given `live`
51 * the rows move (`live.tsx`); without it they are drawn as they stand.
52 */
53export const drawPane = (hyper: Hyper, parts: Parts, view: View, on: Handlers, live?: Live, play?: Play) => {
54  const { Box, Text, Button } = parts
55  const isGames = view.tab === 'juegos'
56  const isMenu = view.menu === true
57  const current = gameOf(view.game ?? '')
58  // A game's entry in the list: its glyph, its name and its best score, at one width.
59  const widest = GAMES.reduce((most, game) => Math.max(most, [...game.label].length), 0)
60  const tag = (game: { id: string; glyph: string; label: string }): string =>
61    ` ${game.glyph} ${game.label.padEnd(widest)} ${String(view.best?.[game.id] ?? 0).padStart(5)} `
62  const perShelf = Math.max(1, Math.floor(view.columns / (widest + 10)))
63  const shelves = GAMES.reduce<(typeof GAMES)[number][][]>((all, game, i) => {
64    if (i % perShelf === 0) all.push([])
65    all[all.length - 1]?.push(game)
66
67    return all
68  }, [])
69  const tabs = TABS.filter(({ tab }) => tab !== 'juegos' || view.games === true)
70  // Each tab takes its key, a colon, a space and its name with one more space.
71  const isRoomy = tabs.reduce((all, { label }) => all + 3 + [...label].length + 1, 0) <= view.columns
72  const props = liveProps(view)
73  const hasDone = view.history.agents.some(agent => agent.endedAt !== undefined)
74
75  return (
76    <Box flexDirection="column">
77      <Box>
78        {tabs.map(({ tab, label, hotkey }) => {
79          // The button draws its own key (`1:`); a pane too narrow for every name keeps only the shown tab's.
80          const name = isRoomy || tab === view.tab ? `${label} ` : ''
81
82          return (
83            <Button key={tab} plain hotkey={hotkey} dimColor={tab !== view.tab} onPress={() => on.onTab(tab)}>
84              {tab === view.tab ? <Text bold inverse>{name}</Text> : <Text>{name}</Text>}
85            </Button>
86          )
87        })}
88      </Box>
89      {live === undefined ? paint(hyper, parts, props, null) : live(props)}
90      {isGames && (
91        <Box>
92          <Button key="menu" plain dimColor={!isMenu} onPress={() => on.onMenu(!isMenu)}>
93            {isMenu ? <Text bold inverse>{' ☰ juegos '}</Text> : <Text>{' ☰ juegos '}</Text>}
94          </Button>
95          <Text dimColor>
96            {`  ${current.glyph} ${current.label} · récord ${view.best?.[current.id] ?? 0}`}
97          </Text>
98        </Box>
99      )}
100      {isGames &&
101        isMenu &&
102        shelves.map(shelf => (
103          <Box>
104            {shelf.map(game => (
105              <Button key={game.id} plain dimColor={game.id !== current.id} onPress={() => on.onGame(game.id)}>
106                {game.id === current.id ? <Text bold inverse>{tag(game)}</Text> : <Text>{tag(game)}</Text>}
107              </Button>
108            ))}
109          </Box>
110        ))}
111      {isGames &&
112        !isMenu &&
113        (play === undefined ? <Text dimColor>Los juegos corren en la terminal y en la app de escritorio.</Text> : play())}
114      {view.tab === 'teoria' && (
115        <Box>
116          <Button key="theory" plain dimColor onPress={() => on.onTheory(view.theory === false)}>
117            <Text>{view.theory === false ? ' encender notas ' : ' apagar notas '}</Text>
118          </Button>
119          <Button key="level" plain dimColor onPress={() => on.onLevel(view.level === 'experto' ? 'aprender' : 'experto')}>
120            <Text>{view.level === 'experto' ? ' nivel: explicar desde cero ' : ' nivel: solo decisiones '}</Text>
121          </Button>
122          {(view.notes?.length ?? 0) > 0 && (
123            <Button key="forget" plain dimColor onPress={() => on.onForget()}>
124              <Text>{' borrar '}</Text>
125            </Button>
126          )}
127        </Box>
128      )}
129      {view.tab === 'agentes' && hasDone && (
130        <Box>
131          <Button key="done" plain dimColor onPress={() => on.onShowDone(!view.showDone)}>
132            <Text>{view.showDone ? ' ocultar terminados ' : ' mostrar terminados '}</Text>
133          </Button>
134        </Box>
135      )}
136    </Box>
137  )
138}
139
hooks/rows.ts 443 lines
1// The stats pane as data: each tab is a list of rows of text runs, some of
2// them marked to move (a clock, a spinner, a bar that grows). `paint.tsx`
3// draws them, still or animated; nothing here touches the engine.
4
5import type { AgentStat, Best, Game, History, Level, Note, Tab, Turn } from '../types'
6import { cell, duration, hbar, pct, sparkline, stack, wrap } from './charts'
7import { activity, isDone, pace } from './history'
8import { pickOfId } from './models'
9import { count, money } from './stats'
10import { LEVELS } from './theory'
11
12// One run of text in a row. `fx` says how it moves when the row is animated:
13//  pulse  alternates `text` and `alt`        spin   a spinner in its place
14//  dots   `text` then one to three dots      clock  time since `since`, `width` cells
15//  grow   `text` revealed cell by cell       meter  a gauge of `value` percent, `width` cells
16export type Seg = {
17  text: string
18  color?: string
19  dim?: boolean
20  bold?: boolean
21  fill?: string
22  fx?: 'pulse' | 'spin' | 'dots' | 'clock' | 'grow' | 'meter'
23  alt?: string
24  since?: number
25  width?: number
26  align?: 'left' | 'right'
27  // clock: past this many milliseconds it turns to the warning color.
28  warnAfter?: number
29  // grow, meter: what tells one bar from another between draws.
30  key?: string
31  value?: number
32  // meter: a high value is the good one (cache served), so the colors run the other way.
33  isGoodHigh?: boolean
34}
35
36// A line of runs, or a column chart. A keyed line slides in when it first
37// appears and fades once `isDone`.
38export type Row =
39  | { key?: string; segs: Seg[]; isDone?: boolean }
40  | { key: string; chart: number[]; height: number; max?: number; color?: string }
41
42// What the animated drawing is handed: plain data only.
43export type LiveProps = { tab: string; now: number; rows: Row[] }
44
45export type View = {
46  columns: number
47  tab: Tab
48  history: History
49  now: number
50  showDone: boolean
51  // The games tab: whether it is offered, which game it shows, the best scores.
52  games?: boolean
53  game?: Game
54  best?: Best
55  menu?: boolean
56  // The theory tab: whether notes are asked for, how deep, and the ones told.
57  theory?: boolean
58  level?: Level
59  notes?: readonly Note[]
60  // From `$.session.usage()`: when the session started, how full its context is, Claude Code's own cost.
61  usage?: { startedAt?: number; percent?: number; usd?: number }
62}
63
64const WAITING = 'Todavía no hay datos: llegan tras la próxima respuesta.'
65const NO_AGENTS = 'Sin agentes en esta sesión. Aparecen cuando Claude delega trabajo (Agent, Explore, Plan…).'
66const REASONS: Readonly<Record<NonNullable<Turn['reason']>, string>> = {
67  answer: 'respuesta',
68  aborted: 'abortado',
69  refusal: 'rechazo',
70  error: 'error',
71}
72const NO_NOTES = 'Sin notas todavía. Aparecen cuando Claude aplica un concepto mientras trabaja.'
73const NOTES_OFF = 'Notas apagadas: Claude no las escribe. El botón de abajo las enciende.'
74const NOTES_SHOWN = 30
75const TABLE_ROWS = 50
76const LIST_ROWS = 20
77const DONE_SHOWN = 10
78const SLOW_AGENT_MS = 300_000
79const SLOW_TOOL_MS = 10_000
80const DEAR = 1
81
82const dim = (text: string): Seg => ({ text, dim: true })
83const plain = (text: string): Seg => ({ text })
84const line = (...segs: Seg[]): Row => ({ segs })
85
86const clamp = (n: number, low: number, high: number): number => Math.min(high, Math.max(low, n))
87const colorOf = (model: string): string | undefined => pickOfId(model)?.family.color
88const promptOf = (t: { input: number; cacheRead: number; cacheWrite: number }): number => t.input + t.cacheRead + t.cacheWrite
89const seen = (h: History): number => h.turns.length + h.dropped
90
91/** The header every tab shares: session time, cost, turns and how full the context is. */
92export const headRow = (view: View): Row => {
93  const { history: h, now } = view
94  const started = view.usage?.startedAt ?? h.turns[0]?.startedAt
95  const segs: Seg[] = [dim('sesión ')]
96
97  segs.push(started === undefined ? plain('–') : { text: duration(Math.max(0, now - started)), fx: 'clock', since: started })
98  segs.push(dim(' · '), plain(`~${money(h.total.cost)}`), dim(` · ${seen(h)} turnos`))
99
100  if (view.usage?.percent !== undefined) {
101    const percent = Math.round(view.usage.percent)
102    segs.push(dim(' · contexto '), { text: '', fx: 'meter', key: 'context', value: percent, width: 8 }, plain(` ${percent}%`))
103  }
104  if (view.usage?.usd !== undefined) segs.push(dim(` · /cost ${money(view.usage.usd)}`))
105
106  return { segs }
107}
108
109const costRows = (view: View): Row[] => {
110  const { columns, history: h } = view
111  const shown = h.turns.slice(-Math.max(1, columns))
112  const costs = shown.map(turn => turn.cost)
113  const top = costs.reduce((most, cost) => Math.max(most, cost), 0)
114  const withTok = columns >= 48
115  const withCache = columns >= 40
116  const barWidth = clamp(columns - 4 - 1 - 8 - 1 - (withTok ? 13 : 0) - (withCache ? 6 : 0), 4, 40)
117  const recent = h.turns.slice(-TABLE_ROWS).reverse()
118  const worst = recent.reduce((most, turn) => Math.max(most, turn.cost), 0)
119  const all = h.total
120
121  return [
122    line(dim(`COSTO POR TURNO · últimos ${shown.length} de ${seen(h)} · máx ${money(top)}`)),
123    { key: 'cost', chart: costs, height: 3, max: top },
124    line(
125      dim(`${cell('#', 4, 'right')} ${cell('costo', 8)}`),
126      dim(cell('▒ entrada █ salida', barWidth)),
127      ...(withTok ? [dim(` ${cell('tok', 12)}`)] : []),
128      ...(withCache ? [dim(` ${cell('cache', 5)}`)] : []),
129    ),
130    ...recent.map((turn, index) => {
131      const [light = 0, full = 0] = stack([turn.cost - turn.costOut, turn.costOut], worst, barWidth)
132      const color = colorOf(turn.model)
133
134      return line(
135        plain(`${cell(String(seen(h) - index), 4, 'right')} ${cell(money(turn.cost), 8)}`),
136        { text: '▒'.repeat(light), color, dim: true },
137        { text: '█'.repeat(full), color },
138        plain(' '.repeat(Math.max(0, barWidth - light - full))),
139        ...(withTok ? [dim(` ${cell(`${count(promptOf(turn))}→${count(turn.output)}`, 12)}`)] : []),
140        ...(withCache ? [dim(` ${cell(pct(turn.cacheRead, promptOf(turn)), 5)}`)] : []),
141      )
142    }),
143    line(
144      dim(
145        `total ~${money(all.cost)} · ${count(promptOf(all))}→${count(all.output)} tok · cache ${pct(all.cacheRead, promptOf(all))}` +
146          (all.agentCost > 0 ? ` · subagentes ${money(all.agentCost)}` : ''),
147      ),
148    ),
149  ]
150}
151
152const modelRows = (view: View): Row[] => {
153  const { columns, history: h } = view
154  const entries = Object.entries(h.models).sort((a, b) => b[1].cost - a[1].cost)
155  const top = entries.reduce((most, [, stat]) => Math.max(most, stat.cost), 0)
156  const withTok = columns >= 56
157  const withReq = columns >= 46
158  const barWidth = clamp(columns - 2 - 13 - 1 - 7 - 5 - (withTok ? 13 : 0) - (withReq ? 8 : 0), 3, 30)
159
160  return [
161    line(dim('USO POR MODELO')),
162    ...entries.map(([id, stat]) => {
163      const known = pickOfId(id)
164      const name = known === undefined ? id : `${known.family.label} ${known.version.version}`
165
166      return line(
167        { text: `${known?.family.glyph ?? '·'} `, color: known?.family.color },
168        { text: cell(name, 12), dim: known === undefined },
169        plain(' '),
170        { text: hbar(stat.cost, top, barWidth), color: known?.family.color, fx: 'grow', key: `model:${id}`, width: barWidth },
171        plain(` ${cell(money(stat.cost), 7, 'right')}`),
172        dim(` ${cell(pct(stat.cost, h.total.cost), 4, 'right')}`),
173        ...(withTok ? [dim(` ${cell(`${count(stat.input)}→${count(stat.output)}`, 12)}`)] : []),
174        ...(withReq ? [dim(` ${cell(`${stat.steps} req`, 7)}`)] : []),
175      )
176    }),
177    ...(h.total.agentCost > 0
178      ? [line(dim(`subagentes: ${money(h.total.agentCost)} (${pct(h.total.agentCost, h.total.cost)} del total)`))]
179      : []),
180  ]
181}
182
183const toolRows = (view: View): Row[] => {
184  const { columns, history: h } = view
185  const tools = [...h.tools].sort((a, b) => b.count - a.count)
186  const calls = tools.reduce((all, tool) => all + tool.count, 0)
187  const errors = tools.reduce((all, tool) => all + tool.errors, 0)
188  const spent = tools.reduce((all, tool) => all + tool.totalMs, 0)
189  const top = tools.reduce((most, tool) => Math.max(most, tool.count), 0)
190  const withErr = columns >= 44
191  const withTime = columns >= 54
192  const withAvg = columns >= 62
193  const barWidth = clamp(columns - 12 - 1 - 1 - 4 - (withErr ? 7 : 0) - (withTime ? 8 : 0) - (withAvg ? 7 : 0), 3, 14)
194
195  return [
196    line(dim(`TOOLS · ${calls} llamadas · ${errors} errores · ${duration(spent)}`)),
197    ...tools.map(tool =>
198      line(
199        plain(`${cell(tool.name, 12)} `),
200        { text: hbar(tool.count, top, barWidth), fx: 'grow', key: `tool:${tool.name}`, width: barWidth },
201        plain(` ${cell(String(tool.count), 4, 'right')}`),
202        ...(withErr
203          ? [tool.errors > 0 ? ({ text: ` ${cell(`${tool.errors} err`, 6)}`, color: 'error' } as Seg) : dim(` ${cell('–', 6)}`)]
204          : []),
205        ...(withTime ? [dim(` ${cell(duration(tool.totalMs), 7, 'right')}`)] : []),
206        ...(withAvg ? [dim(` ${cell(duration(tool.totalMs / Math.max(1, tool.count)), 6, 'right')}`)] : []),
207      ),
208    ),
209  ]
210}
211
212const paceRows = (view: View): Row[] => {
213  const { columns, history: h, now } = view
214  const summary = pace(h)
215  const first = h.turns[0]?.startedAt ?? now
216  const span = Math.max(1, now - (view.usage?.startedAt ?? first))
217  const width = clamp(columns - 11 - 1 - 14, 8, 40)
218  const recent = h.turns.slice(-width)
219  const lengths = recent.map(turn => turn.durationMs ?? Math.max(0, now - turn.startedAt))
220  const steps = recent.map(turn => turn.steps)
221  const buckets = [...sparkline(activity(h.turns, first, Math.max(first + 1, now), width))]
222  const isRunning = h.turns.some(turn => turn.durationMs === undefined)
223  const longest = lengths.reduce((most, ms) => Math.max(most, ms), 0)
224  const busiest = steps.reduce((most, n) => Math.max(most, n), 0)
225
226  return [
227    line(
228      dim(
229        `RITMO · activo ${duration(summary.activeMs)} de ${duration(span)} (${pct(summary.activeMs, span)})` +
230          ` · ${summary.avgSteps.toFixed(1)} pasos/turno · prom ${duration(summary.avgMs)}`,
231      ),
232    ),
233    line(dim(cell('duración', 10)), plain(` ${sparkline(lengths)}`), dim(`   máx ${duration(longest)}`)),
234    line(dim(cell('pasos', 10)), plain(` ${sparkline(steps)}`), dim(`   máx ${busiest}`)),
235    line(
236      dim(cell('actividad', 10)),
237      plain(` ${buckets.slice(0, -1).join('')}`),
238      // The newest stretch beats while a turn runs.
239      isRunning
240        ? { text: buckets[buckets.length - 1] ?? '·', alt: '█', fx: 'pulse', color: 'claude' }
241        : plain(buckets[buckets.length - 1] ?? ''),
242      dim(`   ${width} tramos de ${duration(Math.max(1, now - first) / width)}`),
243    ),
244    ...h.turns
245      .slice(-LIST_ROWS)
246      .reverse()
247      .map((turn, index) => {
248        const isOpen = turn.durationMs === undefined
249
250        return line(
251          plain(`${cell(String(seen(h) - index), 4, 'right')}  `),
252          isOpen
253            ? { text: '', fx: 'clock', since: turn.startedAt, width: 7, color: 'claude' }
254            : plain(cell(duration(turn.durationMs ?? 0), 7)),
255          dim(` ${cell(`${turn.steps} pasos`, 9)} ${isOpen ? 'en curso' : REASONS[turn.reason ?? 'answer']}`),
256        )
257      }),
258  ]
259}
260
261// How an agent's state is drawn: its glyph, the one it beats with, its color.
262const STATE = {
263  running: { glyph: '●', alt: '◉', color: 'success', label: 'corriendo' },
264  waiting: { glyph: '◐', alt: '◑', color: 'warning', label: 'esperando' },
265  done: { glyph: '○', alt: '○', color: 'inactive', label: 'terminados' },
266  failed: { glyph: '✕', alt: '✕', color: 'error', label: 'fallaron' },
267} as const
268
269type StateName = keyof typeof STATE
270
271const stateOf = (agent: AgentStat): StateName => {
272  if (agent.status === 'failed' || agent.status === 'killed') return 'failed'
273  if (isDone(agent)) return 'done'
274
275  return agent.status === 'running' ? 'running' : 'waiting'
276}
277
278const ORDER: readonly StateName[] = ['running', 'waiting', 'failed', 'done']
279
280/** The agents as the pane lists them: the live ones first, newest on top, then the latest finished. */
281export const listedAgents = (h: History, showDone: boolean): AgentStat[] => {
282  const live = h.agents.filter(agent => !isDone(agent)).sort((a, b) => b.startedAt - a.startedAt)
283  const done = h.agents
284    .filter(isDone)
285    .sort((a, b) => (b.endedAt ?? b.startedAt) - (a.endedAt ?? a.startedAt))
286    .slice(0, DONE_SHOWN)
287
288  return [...live.sort((a, b) => ORDER.indexOf(stateOf(a)) - ORDER.indexOf(stateOf(b))), ...(showDone ? done : [])]
289}
290
291const agentRows = (view: View): Row[] => {
292  const { columns, history: h, now } = view
293  if (h.agents.length === 0) return [line(dim(NO_AGENTS))]
294
295  const tally = (name: StateName): number => h.agents.filter(agent => stateOf(agent) === name).length
296  const spent = h.agents.reduce((all, agent) => all + agent.cost, 0)
297  const head: Seg[] = [dim('AGENTES ')]
298
299  for (const name of ORDER) {
300    const n = tally(name)
301    if (n === 0) continue
302
303    const state = STATE[name]
304    head.push(
305      plain(' '),
306      name === 'running' || name === 'waiting'
307        ? { text: state.glyph, alt: state.alt, fx: 'pulse', color: state.color }
308        : { text: state.glyph, color: state.color },
309      dim(` ${n} ${state.label} `),
310    )
311  }
312  head.push(plain(` ${money(spent)}`))
313
314  const rows: Row[] = [{ segs: head }, line({ text: '─'.repeat(Math.max(1, columns)), color: 'subtle' })]
315  const ids = new Set(h.agents.map(agent => agent.id))
316
317  for (const agent of listedAgents(h, view.showDone)) {
318    const name = stateOf(agent)
319    const state = STATE[name]
320    const over = name === 'done' || name === 'failed'
321    const isChild = agent.parentId !== undefined && ids.has(agent.parentId)
322    const lead = isChild ? '  └ ' : ''
323    const room = clamp(columns - [...lead].length - 2 - 10 - 1 - 7 - 1 - 7, 4, 60)
324    const known = pickOfId(agent.model)
325
326    rows.push({
327      key: `a:${agent.id}`,
328      isDone: over,
329      segs: [
330        dim(lead),
331        name === 'running' || name === 'waiting'
332          ? { text: state.glyph, alt: state.alt, fx: 'pulse', color: state.color }
333          : { text: state.glyph, color: state.color },
334        { text: ` ${cell(agent.type, 9)} `, color: state.color, bold: true },
335        { text: cell(agent.description, room), dim: over },
336        plain(' '),
337        over
338          ? dim(cell(duration(Math.max(0, (agent.endedAt ?? now) - agent.startedAt)), 7, 'right'))
339          : { text: '', fx: 'clock', since: agent.startedAt, width: 7, align: 'right', warnAfter: SLOW_AGENT_MS },
340        { text: ` ${cell(money(agent.cost), 7, 'right')}`, ...(agent.cost > DEAR ? { color: 'error' } : {}) },
341        ...(name === 'failed' ? [{ text: agent.status === 'killed' ? ' cancelado' : ' error', color: 'error' } as Seg] : []),
342      ],
343    })
344
345    const detail: Seg[] = [plain(isChild ? '      ' : '  ')]
346    detail.push(
347      known === undefined
348        ? dim('· ')
349        : { text: `${known.family.glyph} ${known.family.label} ${known.version.version} `, color: known.family.color },
350      dim(` ${agent.steps} req `),
351    )
352
353    if (columns >= 50) {
354      for (const tool of [...agent.tools].sort((a, b) => b.count - a.count).slice(0, columns >= 64 ? 4 : 2)) {
355        detail.push(dim(` ${tool.name} ×${tool.count}`))
356        if (tool.errors > 0) detail.push({ text: ` ✕${tool.errors}`, color: 'error' })
357      }
358    }
359
360    if (!over) {
361      detail.push({ text: '  ▸ ', color: 'claude' })
362      if (agent.busy === undefined) {
363        detail.push({ text: 'pensando', fx: 'dots', color: 'claude' })
364      } else {
365        detail.push(
366          { text: '⠋', fx: 'spin', color: 'claude' },
367          { text: ` ${agent.busy.tool} `, color: 'claude' },
368          { text: '', fx: 'clock', since: agent.busy.since, warnAfter: SLOW_TOOL_MS, color: 'claude' },
369        )
370      }
371    }
372
373    if (columns >= 56 && agent.costs.length > 1) {
374      detail.push(plain('  '), { text: sparkline(agent.costs), color: known?.family.color, dim: over })
375    }
376
377    rows.push({ key: `b:${agent.id}`, isDone: over, segs: detail })
378  }
379
380  return rows
381}
382
383const theoryRows = (view: View): Row[] => {
384  const notes = view.notes ?? []
385  const room = Math.max(8, view.columns - 2)
386  const rows: Row[] = [
387    line(dim(`TEORÍA · ${notes.length} ${notes.length === 1 ? 'nota' : 'notas'} · nivel ${LEVELS[view.level ?? 'aprender']}`)),
388    line({ text: '─'.repeat(Math.max(1, view.columns)), color: 'subtle' }),
389  ]
390
391  if (view.theory === false) rows.push(line(dim(NOTES_OFF)))
392  else if (notes.length === 0) rows.push(line(dim(NO_NOTES)))
393
394  // The newest first: it is the one being built now.
395  for (const note of [...notes].reverse().slice(0, NOTES_SHOWN)) {
396    rows.push({
397      key: `n:${note.id}`,
398      segs: [
399        { text: '◆ ', color: 'claude' },
400        { text: cell(note.title, Math.max(4, view.columns - 2 - 9)), bold: true },
401        dim(' '),
402        { text: '', fx: 'clock', since: note.at, width: 7, align: 'right', dim: true },
403      ],
404    })
405    if (note.where !== undefined) rows.push(line({ text: `  ${cell(note.where, room)}`, color: 'claude', dim: true }))
406    for (const text of wrap(note.text, room)) rows.push(line(plain(`  ${text}`)))
407    rows.push(line(plain(' ')))
408  }
409
410  return rows
411}
412
413const TABS: Readonly<Record<Tab, (view: View) => Row[]>> = {
414  costo: costRows,
415  modelos: modelRows,
416  tools: toolRows,
417  ritmo: paceRows,
418  agentes: agentRows,
419  // The games draw themselves (`games.tsx`).
420  juegos: () => [],
421  teoria: theoryRows,
422}
423
424/** The chosen tab's rows; a session with nothing yet says so (the agents tab says its own). */
425export const rowsFor = (view: View): Row[] => {
426  const h = view.history
427  const isEmpty = h.total.steps === 0 && h.tools.length === 0 && h.agents.length === 0
428
429  const hasOwnWord = view.tab === 'agentes' || view.tab === 'juegos' || view.tab === 'teoria'
430
431  return isEmpty && !hasOwnWord ? [line(dim(WAITING))] : TABS[view.tab](view)
432}
433
434/**
435 * A value as a surface module may be handed it: plain data, with nothing
436 * `undefined` left in it (a color a model has none of, an absent field), which
437 * the engine refuses in a module's props.
438 */
439export const plainData = <T>(value: T): T => JSON.parse(JSON.stringify(value)) as T
440
441/** How many agents are at work now. */
442export const liveAgents = (h: History): number => h.agents.filter(agent => !isDone(agent)).length
443
hooks/paint.tsx 246 lines
1/** @jsx hyper */
2// Draws rows (`rows.ts`), still or in motion. The motion is a small state
3// stepped on a timer: `stepAnim` moves it, `paint` reads it. With no state the
4// rows are drawn as they stand, which is what a surface with no timer gets.
5
6import type { EngineInterface, RenderNode } from 'claude-code'
7
8import { cell, columns as columnChart, duration } from './charts'
9import type { LiveProps, Row, Seg } from './rows'
10
11// JSX compiles to calls of `hyper` (the pragma above): the caller hands in its own `h`.
12export type Hyper = (
13  tag: string | ((props: never) => RenderNode | null | undefined),
14  props: Record<string, unknown> | null | undefined,
15  ...children: unknown[]
16) => RenderNode | null | undefined
17
18// The elements `paint` draws with, as every surface names them.
19export type Parts = Pick<ReturnType<EngineInterface['ui']['resolve']>, 'Box' | 'Text'>
20
21// Where the motion stands. Frames count ticks; the maps are by row or bar key.
22export type Anim = {
23  frame: number
24  // Milliseconds since the props in hand were made, which clocks add to their `now`.
25  ms: number
26  propsNow: number
27  tab: string
28  // The frame the tab was shown at: its charts rise from there.
29  tabFrame: number
30  // The frame each keyed row first appeared at, and the one it was first seen done at.
31  seen: Record<string, number>
32  over: Record<string, number>
33  // How much of each growing bar or meter is drawn so far.
34  shown: Record<string, number>
35}
36
37const SPINNER = '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'
38// A frame so long ago that nothing is in motion because of it.
39const LONG_AGO = -1000
40const SLIDE_FRAMES = 4
41const SLIDE_CELLS = 4
42const FADE_FRAMES = 6
43const RISE_FRAMES = 5
44const PULSE_FRAMES = 8
45
46const isLine = (row: Row): row is Extract<Row, { segs: Seg[] }> => 'segs' in row
47const lengthOf = (text: string): number => [...text].length
48const targetOf = (seg: Seg): number => (seg.fx === 'meter' ? (seg.value ?? 0) : lengthOf(seg.text))
49
50const movers = (props: LiveProps): Seg[] =>
51  props.rows.flatMap(row => (isLine(row) ? row.segs.filter(seg => (seg.fx === 'grow' || seg.fx === 'meter') && seg.key !== undefined) : []))
52
53// The state a tab starts from: its rows are already there (none slides in or
54// fades), its bars and charts start empty and rise.
55const fresh = (props: LiveProps, frame: number): Anim => {
56  const seen: Record<string, number> = {}
57  const over: Record<string, number> = {}
58
59  for (const row of props.rows) {
60    if (row.key === undefined) continue
61    seen[row.key] = LONG_AGO
62    if (isLine(row) && row.isDone) over[row.key] = LONG_AGO
63  }
64
65  return { frame, ms: 0, propsNow: props.now, tab: props.tab, tabFrame: frame, seen, over, shown: {} }
66}
67
68// One step of `from` toward `to`: a third of the way, a whole unit at least.
69const toward = (from: number, to: number): number => {
70  const gap = to - from
71  if (gap === 0) return from
72
73  return from + Math.sign(gap) * Math.max(1, Math.ceil(Math.abs(gap) / 3))
74}
75
76/**
77 * How often the drawing has to be stepped: `fast` while something turns,
78 * slides, fades or grows; `slow` when only clocks run (a step a second is
79 * enough); `still` when nothing moves.
80 */
81export const paceOf = (props: LiveProps, anim: Anim): 'fast' | 'slow' | 'still' => {
82  let hasClock = false
83
84  for (const row of props.rows) {
85    if (!isLine(row)) {
86      if (anim.frame - anim.tabFrame <= RISE_FRAMES) return 'fast'
87      continue
88    }
89
90    if (row.key !== undefined) {
91      if (anim.seen[row.key] === undefined || anim.frame - (anim.seen[row.key] ?? 0) <= SLIDE_FRAMES) return 'fast'
92      if (row.isDone && (anim.over[row.key] === undefined || anim.frame - (anim.over[row.key] ?? 0) <= FADE_FRAMES)) return 'fast'
93    }
94
95    for (const seg of row.segs) {
96      if (seg.fx === 'pulse' || seg.fx === 'spin' || seg.fx === 'dots') return 'fast'
97      if ((seg.fx === 'grow' || seg.fx === 'meter') && seg.key !== undefined && (anim.shown[seg.key] ?? 0) !== targetOf(seg)) return 'fast'
98      if (seg.fx === 'clock') hasClock = true
99    }
100  }
101
102  return hasClock ? 'slow' : 'still'
103}
104
105/**
106 * The motion `dt` milliseconds later. With none before, the state the props
107 * start from; a change of tab starts over from that tab's.
108 */
109export const stepAnim = (was: Anim | undefined, props: LiveProps, dt: number): Anim => {
110  if (was === undefined) return fresh(props, 0)
111
112  const base = props.tab === was.tab ? was : fresh(props, was.frame)
113  const frame = base.frame + 1
114  const seen: Record<string, number> = {}
115  const over: Record<string, number> = {}
116  const shown: Record<string, number> = {}
117
118  for (const row of props.rows) {
119    if (row.key === undefined) continue
120    seen[row.key] = base.seen[row.key] ?? frame
121    if (isLine(row) && row.isDone) over[row.key] = base.over[row.key] ?? frame
122  }
123  for (const seg of movers(props)) {
124    const key = seg.key as string
125    shown[key] = toward(base.shown[key] ?? 0, targetOf(seg))
126  }
127
128  return {
129    frame,
130    ms: props.now === base.propsNow ? base.ms + dt : 0,
131    propsNow: props.now,
132    tab: props.tab,
133    tabFrame: base.tabFrame,
134    seen,
135    over,
136    shown,
137  }
138}
139
140/**
141 * The motion as these props are to be drawn with it: the held state, brought
142 * in line when the props are newer than it (another tab, a later `now`), so no
143 * frame is drawn with the last props' motion.
144 */
145export const animFor = (held: Anim | undefined, props: LiveProps): Anim => {
146  if (held === undefined) return fresh(props, 0)
147  if (held.tab !== props.tab) return fresh(props, held.frame)
148
149  return held.propsNow === props.now ? held : { ...held, ms: 0, propsNow: props.now }
150}
151
152// A run as it reads at this frame: its text, and the color it takes.
153const settle = (seg: Seg, props: LiveProps, anim: Anim | null): { text: string; color?: string } => {
154  const frame = anim?.frame ?? 0
155
156  switch (seg.fx) {
157    case 'pulse':
158      return { text: anim !== null && frame % PULSE_FRAMES >= PULSE_FRAMES / 2 ? (seg.alt ?? seg.text) : seg.text, color: seg.color }
159    case 'spin':
160      return { text: anim === null ? seg.text : (SPINNER[frame % SPINNER.length] as string), color: seg.color }
161    case 'dots':
162      return { text: seg.text + cell('.'.repeat(anim === null ? 3 : 1 + (Math.floor(frame / 3) % 3)), 3), color: seg.color }
163    case 'clock': {
164      const elapsed = Math.max(0, props.now + (anim?.ms ?? 0) - (seg.since ?? props.now))
165      const text = duration(elapsed)
166
167      return {
168        text: seg.width === undefined ? text : cell(text, seg.width, seg.align),
169        color: seg.warnAfter !== undefined && elapsed > seg.warnAfter ? 'warning' : seg.color,
170      }
171    }
172    case 'grow': {
173      const glyphs = [...seg.text]
174      const upTo = anim === null || seg.key === undefined ? glyphs.length : Math.min(glyphs.length, anim.shown[seg.key] ?? 0)
175
176      return { text: cell(glyphs.slice(0, upTo).join(''), seg.width ?? glyphs.length), color: seg.color }
177    }
178    case 'meter': {
179      const width = seg.width ?? 8
180      const percent = anim === null || seg.key === undefined ? (seg.value ?? 0) : (anim.shown[seg.key] ?? 0)
181      const filled = Math.max(0, Math.min(width, Math.round((percent / 100) * width)))
182
183      return {
184        text: '▰'.repeat(filled) + '▱'.repeat(width - filled),
185        color: seg.isGoodHigh
186          ? percent >= 70 ? 'success' : percent >= 30 ? 'warning' : 'error'
187          : percent >= 90 ? 'error' : percent >= 70 ? 'warning' : 'success',
188      }
189    }
190    default:
191      return { text: seg.text, color: seg.color }
192  }
193}
194
195/** The rows as a tree: one line of text per row, a chart as its rows of columns. */
196export const paint = (hyper: Hyper, parts: Parts, props: LiveProps, anim: Anim | null) => {
197  const { Box, Text } = parts
198  const frame = anim?.frame ?? 0
199
200  return (
201    <Box flexDirection="column">
202      {props.rows.map(row => {
203        if (!isLine(row)) {
204          // A chart rises from nothing when its tab is shown.
205          const risen = anim === null ? 1 : Math.min(1, (frame - anim.tabFrame + 1) / RISE_FRAMES)
206
207          return columnChart(row.chart.map(value => value * risen), row.height, row.max).map(text => (
208            <Text wrap="truncate-end" color={row.color || undefined}>
209              {text}
210            </Text>
211          ))
212        }
213
214        const key = row.key
215        // A row that just appeared slides in from the right; one that just ended flashes, then fades.
216        const age = anim === null || key === undefined ? SLIDE_FRAMES : frame - (anim.seen[key] ?? frame)
217        const gone = anim === null || key === undefined ? FADE_FRAMES : frame - (anim.over[key] ?? frame)
218        const pad = age < SLIDE_FRAMES ? ' '.repeat((SLIDE_FRAMES - age) * SLIDE_CELLS) : ''
219        const isFlash = row.isDone === true && gone < FADE_FRAMES / 2
220        const isFaded = row.isDone === true && gone >= FADE_FRAMES
221
222        return (
223          <Text wrap="truncate-end">
224            {pad}
225            {row.segs.map(seg => {
226              const now = settle(seg, props, anim)
227
228              return (
229                <Text
230                  // An empty color is no color: the engine refuses it as a value.
231                  color={now.color || undefined}
232                  backgroundColor={seg.fill || undefined}
233                  bold={seg.bold === true || isFlash}
234                  dimColor={seg.dim === true || isFaded}
235                >
236                  {now.text}
237                </Text>
238              )
239            })}
240          </Text>
241        )
242      })}
243    </Box>
244  )
245}
246
hooks/stats.ts 154 lines
1import type { Stats } from '../types'
2import { nameOfId, pickOfId } from './models'
3import type { Seg } from './rows'
4
5// What a response reports of itself: the API's token counts and model id.
6export type Usage = {
7  model: string
8  input_tokens: number
9  output_tokens: number
10  cache_read_input_tokens: number
11  cache_creation_input_tokens: number
12}
13
14const MILLION = 1_000_000
15// Where a list price names no cache rate: a read at a tenth of the input
16// price, a write at a quarter over it.
17const CACHE_READ = 0.1
18const CACHE_WRITE = 1.25
19
20const EMPTY: Stats = {
21  answeredBy: '',
22  effort: '',
23  turnId: '',
24  input: 0,
25  output: 0,
26  cacheRead: 0,
27  turnCost: 0,
28  sessionCost: 0,
29}
30
31/** What a response cost in dollars at list price, by kind of token; all 0 for a model with none listed. */
32export const costParts = (usage: Usage): { input: number; output: number; cacheRead: number; cacheWrite: number } => {
33  const version = pickOfId(usage.model)?.version
34  if (version === undefined) return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }
35
36  const [input, output] = version.price
37  const cacheRead = version.cacheRead ?? input * CACHE_READ
38
39  return {
40    input: (usage.input_tokens * input) / MILLION,
41    output: (usage.output_tokens * output) / MILLION,
42    cacheRead: (usage.cache_read_input_tokens * cacheRead) / MILLION,
43    cacheWrite: (usage.cache_creation_input_tokens * input * CACHE_WRITE) / MILLION,
44  }
45}
46
47/** A response's cost in dollars at list price; 0 for a model with none listed. */
48export const costOf = (usage: Usage): number => {
49  const parts = costParts(usage)
50
51  return parts.input + parts.output + parts.cacheRead + parts.cacheWrite
52}
53
54/**
55 * The stats after one more response. Every loop's response adds to the
56 * session's cost; the main loop's also becomes the latest one shown, and adds
57 * to its turn's cost.
58 */
59export const tally = (
60  was: Stats | null,
61  step: { turnId: string; effort?: string | number },
62  usage: Usage,
63  isMain: boolean,
64): Stats => {
65  const before = was ?? EMPTY
66  const cost = costOf(usage)
67  const sessionCost = before.sessionCost + cost
68
69  if (!isMain) return { ...before, sessionCost }
70
71  return {
72    answeredBy: usage.model,
73    effort: step.effort === undefined ? '' : String(step.effort),
74    turnId: step.turnId,
75    input: usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens,
76    output: usage.output_tokens,
77    cacheRead: usage.cache_read_input_tokens,
78    turnCost: (before.turnId === step.turnId ? before.turnCost : 0) + cost,
79    sessionCost,
80  }
81}
82
83export const money = (dollars: number): string => `$${dollars.toFixed(dollars < 0.1 ? 3 : 2)}`
84
85export const count = (tokens: number): string => {
86  if (tokens >= MILLION) return `${(tokens / MILLION).toFixed(1)}M`
87  if (tokens >= 1000) return `${(tokens / 1000).toFixed(tokens < 10_000 ? 1 : 0)}k`
88
89  return String(tokens)
90}
91
92/** A version's list price as its dropdown row shows it (`$4/$20`). */
93export const priceLabel = ([input, output]: readonly [number, number]): string => {
94  const one = (n: number) => `$${Number.isInteger(n) ? n : n.toFixed(2)}`
95
96  return `${one(input)}/${one(output)}`
97}
98
99const METER_CELLS = 6
100const SEPARATOR = ' · '
101
102const widthOf = (segs: readonly Seg[]): number =>
103  segs.reduce((all, seg) => all + (seg.fx === 'meter' ? (seg.width ?? 0) : [...seg.text].length), 0)
104
105const meterText = (seg: Seg): string => {
106  const width = seg.width ?? 0
107  const filled = Math.max(0, Math.min(width, Math.round(((seg.value ?? 0) / 100) * width)))
108
109  return '▰'.repeat(filled) + '▱'.repeat(width - filled)
110}
111
112/**
113 * The stats row as runs of text, the most useful part first, as many parts as
114 * fit `columns` with ` · ` between them: the model that answered, the costs,
115 * the effort, the tokens, then a meter of the cache's share and one of how
116 * full the context is (`context`, a percent, when known). Empty with nothing to show.
117 */
118export const statsSegs = (stats: Stats | null, isManual: boolean, columns: number, context?: number): Seg[] => {
119  const word = (text: string): Seg => ({ text, dim: true })
120  const parts: Seg[][] = []
121
122  if (stats !== null) {
123    if (stats.answeredBy !== '') parts.push([word(`respondió ${nameOfId(stats.answeredBy)}`)])
124    if (stats.sessionCost > 0) parts.push([word(`sesión ~${money(stats.sessionCost)}`)])
125    if (stats.turnCost > 0) parts.push([word(`turno ~${money(stats.turnCost)}`)])
126    if (stats.effort !== '') parts.push([word(`effort ${stats.effort}`)])
127    if (stats.answeredBy !== '') parts.push([word(`${count(stats.input)}→${count(stats.output)} tok`)])
128    if (stats.input > 0) {
129      const share = Math.round((stats.cacheRead / stats.input) * 100)
130      parts.push([
131        word('cache '),
132        { text: '', fx: 'meter', key: 'cache', value: share, width: METER_CELLS, isGoodHigh: true },
133        word(` ${share}%`),
134      ])
135    }
136  }
137  if (context !== undefined) {
138    const full = Math.round(context)
139    parts.push([word('contexto '), { text: '', fx: 'meter', key: 'context', value: full, width: METER_CELLS }, word(` ${full}%`)])
140  }
141  if (isManual) parts.push([word('manual')])
142
143  const total = () => parts.reduce((all, part) => all + widthOf(part), 0) + Math.max(0, parts.length - 1) * SEPARATOR.length
144  while (parts.length > 1 && total() > columns) parts.pop()
145
146  return parts.flatMap((part, index) => (index === 0 ? part : [word(SEPARATOR), ...part]))
147}
148
149/** The stats row as plain text, its meters drawn full. */
150export const statsLine = (stats: Stats | null, isManual: boolean, columns: number, context?: number): string =>
151  statsSegs(stats, isManual, columns, context)
152    .map(seg => (seg.fx === 'meter' ? meterText(seg) : seg.text))
153    .join('')
154
hooks/theory.ts 83 lines
1// The theory tab's notes: what the agent says of the concepts it applies, as
2// it applies them. It tells them through a tool of the mod's; nothing here
3// touches the engine.
4
5import type { Level, Note } from '../types'
6
7/** The tool's short name, and the name the model calls it by. */
8export const TOOL_NAME = 'teoria'
9export const TOOL = 'mcp__model-picker__teoria'
10
11/** The system prompt section that asks for the notes. */
12export const SECTION_ID = 'model-picker:teoria'
13
14export const NOTE_CAP = 100
15const TITLE_MAX = 80
16const TEXT_MAX = 900
17const WHERE_MAX = 120
18
19export const LEVELS: Readonly<Record<Level, string>> = { aprender: 'aprendiendo', experto: 'experto' }
20
21export const isLevel = (value: unknown): value is Level => value === 'aprender' || value === 'experto'
22
23export const SPEC = {
24  name: TOOL_NAME,
25  description:
26    'Anota en el panel "Teoría" del usuario un concepto, patrón o decisión de diseño que estás aplicando en lo que construís. ' +
27    'No cambia nada: solo muestra la nota. Una llamada por concepto.',
28  inputSchema: {
29    type: 'object',
30    properties: {
31      title: { type: 'string', description: 'El concepto, en pocas palabras (p. ej. "Debounce", "Índice compuesto").' },
32      explanation: { type: 'string', description: 'Qué es y por qué lo usás acá, en texto plano.' },
33      where: { type: 'string', description: 'Dónde se aplica: archivo, función o parte del sistema. Opcional.' },
34    },
35    required: ['title', 'explanation'],
36  },
37  isDeferred: false,
38} as const
39
40// How much each level asks of a note.
41const DEPTH: Readonly<Record<Level, string>> = {
42  aprender:
43    'El usuario está aprendiendo: explicá el concepto desde cero, con palabras simples, en 2 a 4 oraciones: ' +
44    'qué es, qué problema resuelve y por qué lo elegiste acá en vez de la alternativa más obvia.',
45  experto:
46    'El usuario ya conoce los conceptos: en 1 o 2 oraciones, solo la decisión que tomaste y su trade-off frente a la alternativa.',
47}
48
49/** What the system prompt says of the notes, at a level. */
50export const sectionFor = (level: Level): string =>
51  [
52    '# Notas de teoría',
53    `El usuario tiene abierto un panel "Teoría" donde lee, mientras trabajás, la teoría detrás de lo que construís. ` +
54      `Cada vez que apliques un concepto, patrón, algoritmo o decisión de diseño que no sea trivial, anotalo llamando a \`${TOOL}\` ` +
55      'en el momento en que lo aplicás, junto con las demás herramientas del paso.',
56    DEPTH[level],
57    'Una nota por concepto y solo la primera vez que aparece; las tareas sin teoría (renombrar, mover, leer archivos) no llevan nota. ' +
58      'La nota va en el panel y no en tu respuesta: no la repitas ni la menciones en el chat. Escribila en el idioma del usuario.',
59  ].join('\n\n')
60
61const clip = (text: string, max: number): string => {
62  const cells = [...text.trim().replace(/\s+/g, ' ')]
63
64  return cells.length > max ? `${cells.slice(0, max - 1).join('')}…` : cells.join('')
65}
66
67/** What a call to the tool holds, as a note's fields; undefined when it names no concept or says nothing of it. */
68export const noteOf = (input: Record<string, unknown>): Pick<Note, 'title' | 'text' | 'where'> | undefined => {
69  const title = typeof input.title === 'string' ? clip(input.title, TITLE_MAX) : ''
70  const text = typeof input.explanation === 'string' ? clip(input.explanation, TEXT_MAX) : ''
71  const where = typeof input.where === 'string' ? clip(input.where, WHERE_MAX) : ''
72  if (title === '' || text === '') return undefined
73
74  return where === '' ? { title, text } : { title, text, where }
75}
76
77/** The notes with one more, the latest `NOTE_CAP` kept. */
78export const addNote = (notes: readonly Note[], fields: Pick<Note, 'title' | 'text' | 'where'>, at: number): Note[] => {
79  const id = (notes[notes.length - 1]?.id ?? 0) + 1
80
81  return [...notes, { id, at, ...fields }].slice(-NOTE_CAP)
82}
83
hooks/update.ts 109 lines
1// The mod updating itself: once a day it reads the version published on the
2// repository's main branch and, when that is newer than the one loaded,
3// brings the new one in the way this copy was installed.
4
5const REPO = 'juampymdd/claude-code-model-picker'
6const MARKETPLACE = 'model-picker'
7const MANIFEST = '.claude-plugin/plugin.json'
8const PUBLISHED = `https://raw.githubusercontent.com/${REPO}/main/${MANIFEST}`
9const DAY_MS = 86_400_000
10const UPDATE_TIMEOUT_MS = 120_000
11const CHECKED_AT = 'update.checkedAt'
12
13// What the update needs of the host, so a test can stand in for each part.
14export type Host = {
15  // The mod's own name and folder.
16  name: string
17  root: string
18  now: () => Promise<number>
19  get: (key: string) => Promise<unknown>
20  set: (key: string, value: unknown) => Promise<void>
21  read: (path: string) => Promise<string>
22  exists: (path: string) => Promise<boolean>
23  fetch: (url: string) => Promise<{ ok: boolean; text: string }>
24  run: (argv: readonly string[], init: { timeoutMs: number }) => Promise<{ exitCode: number }>
25  toast: (text: string) => void
26}
27
28export type Outcome = 'throttled' | 'unreachable' | 'current' | 'updated' | 'failed' | 'manual'
29
30/** The `version` of a plugin.json's text when it is `1.2.3`-shaped, else undefined. */
31export const versionIn = (manifest: string): string | undefined => {
32  try {
33    const version: unknown = (JSON.parse(manifest) as { version?: unknown }).version
34
35    return typeof version === 'string' && /^\d+\.\d+\.\d+$/.test(version) ? version : undefined
36  } catch {
37    return undefined
38  }
39}
40
41export const isNewer = (published: string, loaded: string): boolean => {
42  const a = published.split('.').map(Number)
43  const b = loaded.split('.').map(Number)
44
45  for (let i = 0; i < 3; i += 1) {
46    if ((a[i] ?? 0) !== (b[i] ?? 0)) return (a[i] ?? 0) > (b[i] ?? 0)
47  }
48
49  return false
50}
51
52/**
53 * The commands that bring the published version into this copy, by how it was
54 * installed; undefined for a copy neither Claude Code nor git keeps.
55 */
56export const stepsFor = async (host: Host): Promise<readonly (readonly string[])[] | undefined> => {
57  if (host.root.replace(/\\/g, '/').includes('/plugins/cache/')) {
58    return [
59      ['claude', 'plugin', 'marketplace', 'update', MARKETPLACE],
60      ['claude', 'plugin', 'update', `${host.name}@${MARKETPLACE}`],
61    ]
62  }
63
64  if (await host.exists(`${host.root}/.git`)) return [['git', '-C', host.root, 'pull', '--ff-only']]
65
66  return undefined
67}
68
69/**
70 * Checks for a newer published version, at most once a day, and installs it.
71 * Never rejects: offline, or with anything unexpected, it leaves the mod as is.
72 */
73export const selfUpdate = async (host: Host): Promise<Outcome> => {
74  try {
75    const now = await host.now()
76    if (now - Number((await host.get(CHECKED_AT)) ?? 0) < DAY_MS) return 'throttled'
77
78    const response = await host.fetch(PUBLISHED)
79    const published = response.ok ? versionIn(response.text) : undefined
80    const loaded = versionIn(await host.read(`${host.root}/${MANIFEST}`))
81    if (published === undefined || loaded === undefined) return 'unreachable'
82
83    await host.set(CHECKED_AT, now)
84    if (!isNewer(published, loaded)) return 'current'
85
86    const steps = await stepsFor(host)
87    if (steps === undefined) {
88      host.toast(`${host.name} ${published} disponible: github.com/${REPO}`)
89
90      return 'manual'
91    }
92
93    for (const argv of steps) {
94      const { exitCode } = await host.run(argv, { timeoutMs: UPDATE_TIMEOUT_MS })
95      if (exitCode !== 0) {
96        host.toast(`${host.name} ${published} disponible, no se pudo instalar solo: ${argv.join(' ')}`)
97
98        return 'failed'
99      }
100    }
101
102    host.toast(`${host.name} actualizado a ${published} · /reload-plugins o sesión nueva para aplicar`)
103
104    return 'updated'
105  } catch {
106    return 'unreachable'
107  }
108}
109
hooks/live.tsx 52 lines
1// The stats pane's moving part: a surface module, drawn on the drawing thread
2// with a timer of its own. It has no `$`: the hooks hand it rows as props and
3// it draws them, stepping the motion while something is moving.
4
5import type { ClientSurface, JsonValue } from 'claude-code'
6
7import { animFor, paceOf, paint, stepAnim } from './paint'
8import type { Anim } from './paint'
9import type { LiveProps } from './rows'
10
11const TICK_MS = 120
12const SECOND_MS = 1000
13
14// Each instance's latest props and the time not yet stepped, for its timer
15// (which outlives the call that started it).
16const held = new WeakMap<object, { props: LiveProps; pending: number }>()
17
18const Live = (props: JsonValue, surface: ClientSurface<Anim>) => {
19  const rows = props as unknown as LiveProps
20  const mine = held.get(surface)
21
22  if (mine === undefined) {
23    held.set(surface, { props: rows, pending: 0 })
24
25    surface.every(TICK_MS, () => {
26      const now = held.get(surface)
27      if (now === undefined) return
28
29      now.pending += TICK_MS
30      const anim = animFor(surface.state, now.props)
31      const pace = paceOf(now.props, anim)
32
33      // Nothing moving asks for no redraw; clocks alone, for one a second.
34      if (pace === 'still' && anim === surface.state) {
35        now.pending = 0
36
37        return
38      }
39      if (pace === 'slow' && anim === surface.state && now.pending < SECOND_MS) return
40
41      surface.setState(stepAnim(surface.state, now.props, now.pending))
42      now.pending = 0
43    })
44  } else {
45    mine.props = rows
46  }
47
48  return paint(h, surface.elements, rows, animFor(surface.state, rows))
49}
50
51export default Live
52