Live pane of subagents with a Clawd per agent: status, model, tokens, cost and context

Panel en vivo para Claude Code que muestra tus subagentes. Cada uno es un Clawd, la mascota de Claude Code:
▐▛███▜▌
▝▜█████▛▘
▘▘ ▝▝
Cada tarjeta muestra:
! que titila), terminó (duerme, con una z) o falló (gris). Un agente que terminó se oculta si en 30 segundos no recibe otra instrucción; la tarjeta muestra la cuenta regresiva.El skin de Clawd dice quién es el agente: sale de su tipo (y de su tarea, para el auditor) y no cambia mientras trabaja.
| Skin | Tipo de agente | Animación |
|---|---|---|
| research | Explore, Plan, researcher, buscador, lector | Explorador que marcha con una bandera que flamea; al terminar, la bandera cae |
| developer | developer, engineer, builder, coder, frontend, backend, prototyper, architect | Audífonos y laptop: teclea con un brazo y luego con el otro, y el código corre en pantalla |
| auditor | Su tipo o su tarea habla de review, audit, seguridad o QA (palabras completas) | Gafas con un barrido rojo y un portapapeles con un hallazgo que titila |
| general · generalista | general-purpose, claude y todo lo demás | Llave inglesa que oscila junto a una caja de herramientas |
| base | Sólo la mascota del panel vacío | Camina y parpadea |
La línea ◆ de la tarjeta dice qué hace ahora, según sus últimas llamadas: más escrituras que lecturas (Edit, Write, Bash) es «programando»; si no, «investigando». Un auditor siempre dice «auditando». Hasta su primera herramienta, la línea no aparece.
La animación empalma sin saltos: en el escritorio cada animación SVG lleva su fase atada a la hora del reloj, así que un re-dibujo del panel no la reinicia; en la terminal todos los skins usan 8, 4, 2 o 1 cuadros por segundo.
A la derecha de cada tarjeta (debajo de la descripción si la terminal tiene menos de 70 columnas):
⎇ rama y worktree <nombre>. El worktree sale del cwd con que se lanzó el agente o de las rutas .claude/worktrees/<nombre>/ que toca; la rama, de git rev-parse --abbrev-ref HEAD en su worktree o cwd (una vez por directorio) o, si no tiene, en el directorio de la sesión.·) o escribió (✎, en negrita), el más nuevo arriba, con la ruta relativa a su worktree, cwd o sesión (si queda fuera, sólo el nombre). Mientras no haya ninguno: «sin archivos todavía».Cuanto más caro el modelo, más destaca, sin tocar el borde de la tarjeta (que es del estado):
| Modelo | Etiqueta | Clawd |
|---|---|---|
| Haiku | gris tenue | normal |
| Sonnet | ● Sonnet con punto azul | normal |
| Opus | ◆ Opus violeta en negrita | dos chispas que titilan |
| Fable | ✦ Fable dorado en negrita | halo dorado que late y chispas |
Si hay Opus o Fable trabajando, el encabezado los cuenta: ◆ 1 Opus · ✦ 1 Fable activos.
La ventana de contexto y el costo salen de hooks/models.ts, con los precios de lista de la API de Anthropic (Bedrock y Vertex cobran aparte, así que el costo es estimado). Los modelos actuales tienen 1M de contexto; Haiku 4.5 y los anteriores, 200k.
Para ver todos los skins en todos los estados, genera la vista previa y abre docs/catalogo.html:
node scripts/catalogo.ts
Funciona en la terminal y en la app de escritorio (pestaña Code).
claude plugin marketplace add jorgehsy/claude-mods
claude plugin install agent-monitor@jorge-mods --scope user
Desde ahí carga en todas tus sesiones, en la terminal y en la app de escritorio.
/agent-monitor. Con una ventana de 144 columnas o más, el panel se abre solo con cada subagente nuevo, aunque lo hayas cerrado.claude plugin marketplace update jorge-mods
claude plugin update agent-monitor@jorge-mods
Después escribe /reload-plugins en la sesión abierta.
MIT. Ver LICENSE.
hooks/register.tsx 397 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { AgentRow } from '../types'
5import { SKINS, svgOf, cellsOf, withTier, COLS, ROWS, type Mood, type Role } from './skins.ts'
6import { modelInfo, costOf, tierOf, TIER_STYLE, type Tier } from './models.ts'
7import { skinOf, activityOf, kindOf, fileOf, addFile, worktreeOf, relPath, RECENT } from './roles.ts'
8
9const PANE = 'agent-monitor'
10const rows = atom({ plugin: 'agent-monitor', key: 'rows' } as const, {})
11const frame = atom({ plugin: 'agent-monitor', key: 'frame' } as const, 0)
12// La hora del panel, al segundo: mueve la cuenta regresiva de los que terminaron.
13const now = atom({ plugin: 'agent-monitor', key: 'now' } as const, 0)
14
15// Cada tick del reloj del panel dura TICK ms; los cuadros de cada skin se
16// reparten según sus propios fps.
17const TICK = 125
18// Un agente que terminó y no recibe otra instrucción en este tiempo se oculta.
19const LINGER = 30_000
20
21// ── Precio y ventana: ver models.ts ─────────────────────────────────────────
22const k = (n: number) => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n))
23
24function prettyModel(model: string) {
25 if (!model || model === '-') return '—'
26 const m = model.replace(/^.*claude-/, '').replace(/\[.*\]$/, '')
27 const [fam = '', ...v] = m.split('-')
28 return `${fam.charAt(0).toUpperCase()}${fam.slice(1)} ${v.filter(x => /^\d+$/.test(x)).join('.')}`.trim()
29}
30
31// ── Estados ──────────────────────────────────────────────────────────────────
32const moodOf = (s: string): Mood =>
33 s === 'waiting' ? 'wait' : s === 'failed' || s === 'killed' ? 'dead'
34 : s === 'running' || s === 'pending' ? 'work' : 'sleep'
35const LABEL: Record<string, string> = {
36 running: 'trabajando', pending: 'arrancando', waiting: 'espera tu respuesta',
37 idle: 'inactivo', completed: 'terminó', failed: 'falló', killed: 'detenido',
38}
39const STATUS_COLOR: Record<Mood, string> = { work: '#4EBA65', wait: '#E5B93C', sleep: '#8A8A8A', dead: '#E5534B' }
40
41// ── Datos ────────────────────────────────────────────────────────────────────
42const blank = (id: string): AgentRow => ({
43 id, type: '?', description: '', status: 'running', model: '-',
44 input: 0, output: 0, cacheRead: 0, cacheWrite: 0, context: 0, usd: 0, tools: [], files: [],
45})
46
47// ── Dónde está: la rama de git, una sola vez por directorio ──────────────────
48const branches = new Map<string, Promise<string | null>>()
49
50function branchOf($: EngineInterface, dir: string): Promise<string | null> {
51 let p = branches.get(dir)
52 if (!p) {
53 p = $.process.run(['git', '-C', dir, 'rev-parse', '--abbrev-ref', 'HEAD'], { timeoutMs: 5000 })
54 .then(res => {
55 const name = res.stdout.trim()
56 // Fuera de un repositorio, o con HEAD suelto, no hay rama que mostrar.
57 return res.exitCode === 0 && name !== '' && name !== 'HEAD' ? name : null
58 })
59 .catch(err => {
60 $.ui.log(`agent-monitor: sin rama para ${dir}: ${String(err)}`, { to: 'debug' })
61 return null
62 })
63 branches.set(dir, p)
64 }
65 return p
66}
67
68/** Anota la rama del agente: la de su worktree o cwd; si no tiene, la de la sesión. */
69async function locate($: EngineInterface, id: string) {
70 try {
71 const r = ((await read($, rows)) as Record<string, AgentRow>)[id]
72 if (!r) return
73 const dir = r.root ?? r.cwd ?? (await $.session.cwd())
74 const branch = await branchOf($, dir)
75 if (branch && branch !== r.branch) {
76 await update($, rows, (all: Record<string, AgentRow>) => (all[id] ? { ...all, [id]: { ...all[id]!, branch } } : all))
77 }
78 } catch (err) {
79 $.ui.log(`agent-monitor: no se pudo ubicar a ${id}: ${String(err)}`, { to: 'debug' })
80 }
81}
82
83const isLive = (status: string) => {
84 const m = moodOf(status)
85 return m === 'work' || m === 'wait'
86}
87
88async function sync($: EngineInterface) {
89 const list = await $.agent.list()
90 const t = await $.clock.now()
91 await update($, rows, (all: Record<string, AgentRow>) => {
92 const next = { ...all }
93 for (const a of list) {
94 const prev = next[a.id] ?? blank(a.id)
95 const live = isLive(String(a.status))
96 // Al terminar arranca la cuenta; si vuelve a trabajar, se cancela.
97 const endedAt = live ? undefined : prev.endedAt ?? t
98 next[a.id] = { ...prev, type: a.type, description: a.description, status: a.status, endedAt }
99 }
100 // El motor ya no lista a uno que figuraba trabajando: terminó sin avisar.
101 const seen = new Set(list.map(a => a.id))
102 for (const [id, r] of Object.entries(next)) {
103 if (!seen.has(id) && isLive(r.status)) next[id] = { ...r, status: 'completed', endedAt: r.endedAt ?? t }
104 }
105 return next
106 })
107}
108
109/** Oculto por defecto: cada agente nuevo lo abre, aunque la persona lo haya cerrado antes. */
110async function openPane($: EngineInterface) {
111 await $.ui.open({ id: PANE, title: 'Agentes' })
112}
113
114function b64(words: Uint32Array) {
115 const bytes = new Uint8Array(words.buffer)
116 let s = ''
117 for (const b of bytes) s += String.fromCharCode(b)
118 return btoa(s)
119}
120
121const ctxColor = (r: number) => (r < 0.6 ? '#4EBA65' : r < 0.85 ? '#E5B93C' : '#E5534B')
122
123function barSvg(ratio: number, color: string): string {
124 const w = Number.isFinite(ratio) ? Math.max(0, Math.min(1, ratio)) * 100 : 0
125 return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 6" width="220" height="8" preserveAspectRatio="none"><rect width="100" height="6" rx="3" fill="#8A8A8A" opacity=".2"/><rect width="${w.toFixed(2)}" height="6" rx="3" fill="${color}"/></svg>`
126}
127
128export const register: Register = on => {
129 on('session.start', async ($, e, next) => {
130 await $.command.register({ name: 'agent-monitor', description: 'Abre el panel de subagentes' })
131 $.clock.every(TICK, async () => {
132 const all = Object.values(await read($, rows)) as AgentRow[]
133 if (all.some(r => moodOf(r.status) === 'work' || moodOf(r.status) === 'wait')) {
134 await update($, frame, (n: number) => n + 1)
135 }
136 })
137 // Cada segundo: estado al día, cuenta regresiva y ocultar a los que se cumplió.
138 $.clock.every(1000, async () => {
139 const all = Object.values(await read($, rows)) as AgentRow[]
140 const t = await $.clock.now()
141 if (all.some(r => r.endedAt === undefined || t - r.endedAt < LINGER + 1000)) {
142 await sync($)
143 // Los que ya no lista el motor también cuentan desde ahora.
144 await update($, rows, (cur: Record<string, AgentRow>) => {
145 const out = { ...cur }
146 for (const [id, r] of Object.entries(out)) {
147 if (!isLive(r.status) && r.endedAt === undefined) out[id] = { ...r, endedAt: t }
148 }
149 return out
150 })
151 await update($, now, () => t)
152 }
153 })
154 return next(e)
155 })
156
157 on('command.run', { command: 'agent-monitor' }, async $ => {
158 await openPane($)
159 return { text: 'Panel de agentes abierto.' }
160 })
161
162 // El panel no se abre al iniciar la sesión: lo abre cada subagente nuevo.
163 on('agent.spawn', async ($, e, next) => {
164 const r = await next(e)
165 // El cwd del lanzamiento va al agente por el id que devuelve el motor.
166 const id = (r as { agentId?: string }).agentId
167 if (id && e.cwd) {
168 const cwd = String(e.cwd)
169 const wt = worktreeOf(cwd)
170 await update($, rows, (all: Record<string, AgentRow>) => {
171 const cur = all[id] ?? blank(id)
172 return { ...all, [id]: { ...cur, cwd, ...(wt ? { worktree: wt.name, root: wt.root } : {}) } }
173 })
174 }
175 await sync($)
176 await openPane($)
177 if (id) await locate($, id)
178 return r
179 })
180
181 // Cada herramienta que usa un subagente decide su skin, ya resuelta.
182 on('tool.call', async ($, e, next) => {
183 const res = await next(e)
184 const id = e.agentId
185 if (id) {
186 try {
187 const kind = kindOf(String(e.tool), (res as { isReadOnly?: boolean }).isReadOnly)
188 const file = fileOf(String(e.tool), e as unknown as Record<string, unknown>)
189 const wt = worktreeOf(file?.path)
190 let moved = false
191 await update($, rows, (all: Record<string, AgentRow>) => {
192 const r = all[id] ?? blank(id)
193 const upd: AgentRow = { ...r, tools: [...(r.tools ?? []), kind].slice(-RECENT) }
194 if (file) upd.files = addFile(r.files, file)
195 // Un worktree nuevo cambia la raíz y, con ella, la rama.
196 if (wt && wt.root !== r.root) { upd.worktree = wt.name; upd.root = wt.root; moved = true }
197 return { ...all, [id]: upd }
198 })
199 if (moved || ((await read($, rows)) as Record<string, AgentRow>)[id]?.branch === undefined) await locate($, id)
200 } catch (err) {
201 // El panel nunca frena una herramienta; el fallo queda en el log de depuración.
202 $.ui.log(`agent-monitor: no se pudo anotar ${String(e.tool)}: ${String(err)}`, { to: 'debug' })
203 }
204 }
205 return res
206 })
207
208 on('turn.step', async function* ($, e, next) {
209 const res = yield* next(e)
210 const id = e.agentId
211 if (id && res.usage) {
212 const n = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : 0)
213 const u = {
214 model: String(res.usage.model ?? '-'),
215 input_tokens: n(res.usage.input_tokens),
216 output_tokens: n(res.usage.output_tokens),
217 cache_read_input_tokens: n(res.usage.cache_read_input_tokens),
218 cache_creation_input_tokens: n(res.usage.cache_creation_input_tokens),
219 }
220 const cost = costOf(u.model, {
221 input: u.input_tokens, output: u.output_tokens,
222 cacheRead: u.cache_read_input_tokens, cacheWrite: u.cache_creation_input_tokens,
223 })
224 await update($, rows, (all: Record<string, AgentRow>) => {
225 const r = all[id] ?? blank(id)
226 return {
227 ...all,
228 [id]: {
229 ...r,
230 model: u.model,
231 input: r.input + u.input_tokens,
232 output: r.output + u.output_tokens,
233 cacheRead: r.cacheRead + u.cache_read_input_tokens,
234 cacheWrite: r.cacheWrite + u.cache_creation_input_tokens,
235 context: u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens,
236 usd: r.usd + cost,
237 },
238 }
239 })
240 }
241 await sync($)
242 return res
243 })
244
245 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
246 const els = $.ui.resolve(e)
247 const { Box, Text } = els
248 const isTerm = e.surface === 'terminal'
249 const every = Object.values(await read($, rows)) as AgentRow[]
250 const t = (await read($, now)) as number
251 // Hora del render: ancla el SMIL del escritorio para que un SVG recreado siga en su fase.
252 let phase = t
253 try { phase = await $.clock.now() } catch { /* sin reloj, la hora del último segundo */ }
254 let sessionDir = ''
255 try { sessionDir = await $.session.cwd() } catch { /* sin directorio, rutas por nombre */ }
256 const left = (r: AgentRow) => (r.endedAt === undefined ? null : Math.max(0, Math.ceil((LINGER - (t - r.endedAt)) / 1000)))
257 // Un id que el motor nunca listó (compactación, memoria) no es un subagente.
258 const all = every.filter(r => left(r) !== 0 && r.type !== '?')
259 // Sólo el terminal anima cuadro a cuadro; el SVG del escritorio se anima solo.
260 const tick = isTerm ? ((await read($, frame)) as number) : 0
261 // Tokens y costo: toda la sesión, también los que ya se ocultaron.
262 const total = every.reduce((s, r) => s + r.usd, 0)
263 const tokens = every.reduce((s, r) => s + r.input + r.output + r.cacheRead + r.cacheWrite, 0)
264 const live = all.filter(r => moodOf(r.status) === 'work').length
265 const waiting = all.filter(r => moodOf(r.status) === 'wait').length
266 // Opus y Fable trabajando o esperando: se cuentan arriba para verlos sin bajar.
267 const busy = all.filter(r => moodOf(r.status) === 'work' || moodOf(r.status) === 'wait')
268 const costly = (['top', 'high'] as const)
269 .map(t => [t, busy.filter(r => tierOf(r.model) === t).length] as [Tier, number])
270 .filter(([, n]) => n > 0)
271 const cols = (e.props as any)?.bodyColumns ?? 40
272 const barW = Math.max(10, Math.min(30, cols - 12))
273
274 const mascot = (role: Role, mood: Mood, key: string, tier: Tier = 'mid') => {
275 const anim = withTier(SKINS[role].animate(mood), tier, mood, isTerm ? 'term' : 'svg')
276 if (isTerm && 'Raster' in els) {
277 const { Raster } = els as any
278 const n = anim.frames.length
279 const i = Math.floor((tick * TICK * anim.fps) / 1000) % n
280 return <Raster key={`m-${key}`} columns={COLS} rows={ROWS} cells={b64(cellsOf(anim.frames[i]!))} />
281 }
282 if ('Svg' in els) {
283 const { Svg } = els as any
284 return <Svg source={svgOf(anim, mood, 104, phase)} alt={`Clawd ${SKINS[role].label}`} width={104} height={68} />
285 }
286 return <Text>✳</Text>
287 }
288
289 const ctxBar = (ratio: number) => {
290 const color = ctxColor(ratio)
291 if (!isTerm && 'Svg' in els) {
292 const { Svg } = els as any
293 return <Svg source={barSvg(ratio, color)} alt={`contexto ${Math.round(ratio * 100)}%`} width={220} height={8} />
294 }
295 const full = Math.round(Math.max(0, Math.min(1, ratio)) * barW)
296 return (
297 <Text>
298 <Text color={color}>{'━'.repeat(full)}</Text>
299 <Text dimColor>{'━'.repeat(barW - full)}</Text>
300 </Text>
301 )
302 }
303
304 const wide = cols >= 70
305 const sideW = Math.max(22, Math.floor(cols * 0.36))
306
307 // Dónde trabaja (rama, worktree) y los últimos archivos que tocó.
308 const where = (r: AgentRow, dim: boolean) => {
309 const recent = [...(r.files ?? [])].slice(-5).reverse()
310 const bases = [r.root, r.cwd, sessionDir]
311 return (
312 <Box flexDirection="column" width={wide ? sideW : undefined}>
313 {r.branch ? <Text dimColor={dim} wrap="truncate-end">⎇ {r.branch}</Text> : null}
314 {r.worktree ? <Text dimColor wrap="truncate-end">worktree {r.worktree}</Text> : null}
315 {recent.length === 0
316 ? <Text dimColor>sin archivos todavía</Text>
317 : recent.map(f => (
318 <Text key={f.path} dimColor={f.kind === 'read'} bold={f.kind === 'write'} color={f.kind === 'write' ? '#E5B93C' : undefined} wrap="truncate-start">
319 {f.kind === 'write' ? '✎' : '·'} {relPath(f.path, bases)}
320 </Text>
321 ))}
322 </Box>
323 )
324 }
325
326 const order: Record<Mood, number> = { wait: 0, work: 1, dead: 2, sleep: 3 }
327 const sorted = [...all].sort((a, b) => order[moodOf(a.status)] - order[moodOf(b.status)])
328
329 return (
330 <Box flexDirection="column" gap={1}>
331 <Box flexDirection="column" paddingX={1}>
332 <Text>
333 <Text bold color="#D97757">✻ Agentes</Text>
334 <Text dimColor> {all.length} en el panel</Text>
335 </Text>
336 <Text>
337 <Text color={STATUS_COLOR.work}>● {live} trabajando</Text>
338 {waiting > 0 && <Text color={STATUS_COLOR.wait} bold> ▲ {waiting} esperan</Text>}
339 </Text>
340 {costly.length > 0 && (
341 <Text>
342 {costly.map(([tier, n], i) => (
343 <Text key={tier} color={TIER_STYLE[tier].color} bold>{i > 0 ? ' · ' : ''}{TIER_STYLE[tier].mark}{n} {tier === 'top' ? 'Fable' : 'Opus'}</Text>
344 ))}
345 <Text dimColor> activos</Text>
346 </Text>
347 )}
348 <Text dimColor>{k(tokens)} tokens · ~US$ {total.toFixed(3)} en la sesión</Text>
349 </Box>
350
351 {all.length === 0 && (
352 <Box flexDirection="column" alignItems="center" paddingY={1}>
353 {mascot('base', 'sleep', 'empty')}
354 <Text dimColor>Todavía no hay subagentes.</Text>
355 </Box>
356 )}
357
358 {sorted.map(r => {
359 const role = skinOf(r.type, r.description)
360 const act = activityOf(r.tools, r.type, r.description)
361 const tier = tierOf(r.model)
362 const ts = TIER_STYLE[tier]
363 const mood = moodOf(r.status)
364 const win = modelInfo(r.model).window
365 const ratio = r.context / win
366 const dim = mood === 'sleep'
367 const border = mood === 'wait' ? (tick % 4 < 2 ? STATUS_COLOR.wait : '#D97757') : STATUS_COLOR[mood]
368 return (
369 <Box key={r.id} borderStyle={mood === 'wait' ? 'bold' : 'round'} borderColor={border} paddingX={1} flexDirection="column">
370 <Box flexDirection="row" gap={1}>
371 {mascot(role, mood, r.id, tier)}
372 <Box flexDirection="column" flexGrow={1}>
373 <Text bold dimColor={dim}>{r.type}</Text>
374 <Text color={STATUS_COLOR[mood]} bold={mood === 'wait'}>
375 {mood === 'wait' ? '▲ ' : '● '}{LABEL[r.status] ?? r.status}
376 {left(r) !== null && <Text dimColor> · se oculta en {left(r)} s</Text>}
377 </Text>
378 {act && (mood === 'work' || mood === 'wait') && <Text color={SKINS[act].accent}>◆ {SKINS[act].label}</Text>}
379 <Text color={ts.color} bold={ts.bold} dimColor={ts.dim}>{ts.mark}{prettyModel(r.model)}</Text>
380 </Box>
381 {wide && where(r, dim)}
382 </Box>
383 {r.description !== '' && <Text dimColor={dim} wrap="truncate-end">{r.description}</Text>}
384 {!wide && where(r, dim)}
385 <Text dimColor={dim}>
386 ↑ {k(r.input + r.cacheRead + r.cacheWrite)} ↓ {k(r.output)} · ~US$ {r.usd.toFixed(3)}
387 </Text>
388 {ctxBar(ratio)}
389 <Text dimColor>contexto {k(r.context)} / {k(win)} · {Math.round(ratio * 100)}%</Text>
390 </Box>
391 )
392 })}
393 </Box>
394 )
395 })
396}
397hooks/skins.ts 465 lines1// Catálogo de skins de Clawd. Datos puros, sin dependencias: el panel los
2// pinta en el terminal (Raster, cuartos de bloque) y en el escritorio (SVG).
3//
4// Lienzo de W×H píxeles; cada píxel es 1 de ancho por 2 de alto, como las
5// celdas del logo de Claude Code. Clawd ocupa x 0–17; los accesorios, x 17–25.
6
7import type { Tier } from './models.ts'
8
9export const W = 26
10export const H = 8
11
12export type Px = [number, number, number] // x, y, color 0xRRGGBB
13export type Frame = Px[]
14export type Mood = 'work' | 'wait' | 'sleep' | 'dead'
15export type Role = 'research' | 'developer' | 'auditor' | 'general' | 'base'
16
17export type Animation = {
18 fps: number
19 frames: Frame[]
20 /** Píxeles sólo para el SVG: brillos, sombras, vidrio. */
21 shine?: Frame
22 /** Halo difuso detrás de Clawd, sólo en el SVG (color CSS). */
23 glow?: string
24}
25
26export type Skin = {
27 role: Role
28 label: string
29 accent: string
30 animate: (mood: Mood) => Animation
31}
32
33// ── Paleta ───────────────────────────────────────────────────────────────────
34export const C = {
35 body: 0xd97757,
36 bodyHi: 0xeb9a78,
37 bodySh: 0xb35f42,
38 lid: 0x9c4f37,
39 dead: 0x7d7d7d,
40 deadSh: 0x5f5f5f,
41 ink: 0x1f1e1d,
42 white: 0xf2efe8,
43 steel: 0xa9a9a9,
44 dark: 0x2e2e2e,
45 screen: 0x14202e,
46 green: 0x4eba65,
47 blue: 0x6b8afd,
48 yellow: 0xe5b93c,
49 red: 0xe5534b,
50 redHot: 0xff6b5e,
51 redDim: 0x7a2a26,
52 wood: 0x8b5a2b,
53 woodSh: 0x6b4420,
54 box: 0x4a5a8c,
55 boxSh: 0x35416b,
56}
57
58const span = (y: number, a: number, b: number, c: number): Px[] =>
59 Array.from({ length: b - a + 1 }, (_, i) => [a + i, y, c] as Px)
60
61// ── Clawd ────────────────────────────────────────────────────────────────────
62type Eyes = 'open' | 'right' | 'closed' | 'covered'
63type Arms = 'out' | 'typeL' | 'typeR' | 'hold'
64
65type Pose = { eyes: Eyes; arms: Arms; legs: 0 | 1; color: number }
66
67const LEGS: [number[], number[]] = [[4, 6, 11, 13], [5, 7, 10, 12]]
68
69function clawd({ eyes, arms, legs, color }: Pose): Px[] {
70 // Los ojos son huecos en la fila 3, como en el logo.
71 const holes = eyes === 'right' ? [6, 13] : [5, 12]
72 const row3: Px[] = []
73 for (let x = 3; x <= 14; x++) {
74 if (holes.includes(x)) {
75 if (eyes === 'closed') row3.push([x, 3, C.lid])
76 else if (eyes === 'covered') row3.push([x, 3, color])
77 } else row3.push([x, 3, color])
78 }
79 const arm = (side: 'L' | 'R', down: boolean): Px[] => {
80 const xs = side === 'L' ? [1, 2] : [15, 16]
81 return xs.map(x => [x, down ? 5 : 4, color] as Px)
82 }
83 const armL = arm('L', arms === 'typeL')
84 const armR = arms === 'hold' ? [[15, 4, color], [16, 4, color], [17, 4, color]] as Px[] : arm('R', arms === 'typeR')
85 return [
86 ...span(2, 3, 14, color),
87 ...row3,
88 ...span(4, 3, 14, color),
89 ...armL,
90 ...armR,
91 ...span(5, 3, 14, color),
92 ...LEGS[legs].map(x => [x, 6, color] as Px),
93 ]
94}
95
96/** Brillo arriba y sombra abajo, sólo en el SVG. */
97function bodyShine(color: number): Frame {
98 const hi = color === C.dead ? C.steel : C.bodyHi
99 const sh = color === C.dead ? C.deadSh : C.bodySh
100 return [...span(2, 4, 13, hi), ...span(5, 3, 14, sh)]
101}
102
103const bodyOf = (mood: Mood) => (mood === 'dead' ? C.dead : C.body)
104const tint = (mood: Mood, c: number) => (mood === 'dead' ? C.deadSh : c)
105
106/** El signo de espera, arriba a la derecha, en dos cuadros. */
107const BANG: Px[] = [[16, 0, C.yellow], [16, 1, C.yellow]]
108// Todos los fps son 8, 4, 2 o 1: dividen los 8 ticks por segundo del panel y
109// cada cuadro dura lo mismo.
110const WAIT_FPS = 4
111const waitFrames = (pose: Frame, blinkPose: Frame): Frame[] => [
112 [...pose, ...BANG],
113 [...pose, ...BANG],
114 [...pose],
115 [...blinkPose],
116]
117
118// ── Research: explorador que marcha con una bandera que flamea ─────────────
119// Tela: L = 1 claro, D = 2 sombra (la onda que corre), . = vacío. x 19–24, y 0–2.
120const FLAG_WAVE = [
121 ['11211.', '112111', '1121..'],
122 ['111211', '11121.', '11121.'],
123 ['1111..', '111121', '111112'],
124 ['12111.', '12111.', '121111'],
125]
126const FLAG_LIMP = ['11.', '11.', '1..', '1..'] // caída, sin viento: y 1–4, x 19–21
127
128function research(mood: Mood): Animation {
129 const color = bodyOf(mood)
130 const pole = tint(mood, C.steel)
131 const lite = tint(mood, C.yellow)
132 const dark = tint(mood, 0xb8891f)
133 const staff: Px[] = [[18, 0, tint(mood, C.yellow)], ...[1, 2, 3, 4, 5, 6].map(y => [18, y, pole] as Px)]
134 const cloth = (rows: string[], y0: number): Px[] =>
135 rows.flatMap((row, dy) => [...row].flatMap((ch, dx) =>
136 ch === '1' ? [[19 + dx, y0 + dy, lite] as Px] : ch === '2' ? [[19 + dx, y0 + dy, dark] as Px] : []))
137 if (mood === 'work') {
138 return {
139 fps: 8,
140 frames: Array.from({ length: 8 }, (_, f) => [
141 ...clawd({ eyes: f === 7 ? 'closed' : 'right', arms: 'hold', legs: (f >> 1) % 2 as 0 | 1, color }),
142 ...staff,
143 ...cloth(FLAG_WAVE[f % 4]!, 0),
144 ]),
145 shine: bodyShine(color),
146 }
147 }
148 const limp = cloth(FLAG_LIMP, 1)
149 const still = [...clawd({ eyes: mood === 'wait' ? 'open' : 'closed', arms: 'hold', legs: 0, color }), ...staff, ...limp]
150 if (mood === 'wait') {
151 const blink = [...clawd({ eyes: 'closed', arms: 'hold', legs: 0, color }), ...staff, ...limp]
152 return { fps: WAIT_FPS, frames: waitFrames(still, blink), shine: bodyShine(color) }
153 }
154 return { fps: 1, frames: [still], shine: bodyShine(color) }
155}
156
157// ── Developer: audífonos, laptop con código que corre, brazos tecleando ──────
158const CODE: Array<Array<[number, number]>> = [
159 // [largo, color] por segmento; cada fila cabe en x 20–24
160 [[2, C.blue], [2, C.white]],
161 [[1, 0x5a5a5a], [3, C.green]],
162 [[1, 0x5a5a5a], [2, C.yellow], [1, C.white]],
163 [[3, C.red], [1, C.white]],
164 [[2, C.blue], [1, C.white], [1, C.green]],
165 [[1, 0x5a5a5a], [1, 0x5a5a5a], [2, C.white]],
166 [[4, C.green]],
167 [[2, C.white], [2, C.blue]],
168]
169function codeRow(line: number, y: number): Px[] {
170 const out: Px[] = []
171 let x = 20
172 for (const [len, c] of CODE[line % CODE.length]!) {
173 for (let i = 0; i < len && x <= 24; i++) out.push([x++, y, c])
174 }
175 return out
176}
177
178function developer(mood: Mood): Animation {
179 const color = bodyOf(mood)
180 const phones = (led: boolean): Px[] => [
181 // Diadema fina sobre la cabeza y copas a los lados.
182 ...span(1, 3, 14, 0x3a3a3a),
183 [2, 1, C.dark], [2, 2, C.dark], [2, 3, C.dark], [15, 1, C.dark], [15, 2, C.dark], [15, 3, C.dark],
184 ...(led ? [[2, 3, tint(mood, C.green)] as Px] : []),
185 ]
186 const laptop = (scroll: number | null, cursor: boolean): Px[] => {
187 const frame = tint(mood, 0x4a4a4a)
188 const px: Px[] = [
189 ...span(1, 19, 25, frame), [19, 2, frame], [19, 3, frame], [19, 4, frame],
190 [25, 2, frame], [25, 3, frame], [25, 4, frame], ...span(5, 19, 25, frame),
191 ...span(6, 17, 25, tint(mood, 0x9a9a9a)),
192 ]
193 for (let y = 2; y <= 4; y++) px.push(...span(y, 20, 24, C.screen))
194 if (scroll !== null && mood !== 'dead') {
195 px.push(...codeRow(scroll, 2), ...codeRow(scroll + 1, 3))
196 const last = codeRow(scroll + 2, 4).slice(0, 2)
197 px.push(...last)
198 if (cursor) px.push([20 + last.length, 4, C.white])
199 }
200 return px
201 }
202 if (mood === 'work') {
203 return {
204 fps: 8,
205 // 16 cuadros: el código avanza una línea cada dos (0..7) y da la vuelta
206 // exacta sobre las 8 líneas de CODE; los brazos alternan cada cuadro.
207 frames: Array.from({ length: 16 }, (_, f) => [
208 ...clawd({ eyes: f === 13 ? 'closed' : 'right', arms: f % 2 ? 'typeL' : 'typeR', legs: 0, color }),
209 ...phones(f % 2 === 0),
210 ...laptop(f >> 1, f % 2 === 0),
211 ]),
212 shine: bodyShine(color),
213 }
214 }
215 const still = [...clawd({ eyes: mood === 'wait' ? 'open' : 'closed', arms: 'out', legs: 0, color }), ...phones(false), ...laptop(mood === 'wait' ? 0 : null, false)]
216 if (mood === 'wait') {
217 const blink = [...clawd({ eyes: 'closed', arms: 'out', legs: 0, color }), ...phones(false), ...laptop(0, false)]
218 return { fps: WAIT_FPS, frames: waitFrames(still, blink), shine: bodyShine(color) }
219 }
220 return { fps: 1, frames: [still], shine: bodyShine(color) }
221}
222
223// ── Auditor: visor con barrido rojo y portapapeles que se va marcando ───────
224function auditor(mood: Mood): Animation {
225 const color = bodyOf(mood)
226 const visor = (at: number | null): Px[] => {
227 // Gafas: no tocan los bordes, así Clawd sigue entero.
228 const band = span(3, 4, 13, C.dark)
229 if (at === null) return band
230 const lit: Px[] = [[at, 3, C.redHot], [at + 1, 3, C.red]]
231 const trail: Px[] = [[at - 1, 3, C.redDim], [at + 2, 3, C.redDim]].filter(([x]) => x! >= 4 && x! <= 13) as Px[]
232 return [...band, ...trail, ...lit]
233 }
234 const board = (checks: number, finding: boolean): Px[] => {
235 const wood = tint(mood, C.wood)
236 const px: Px[] = [
237 ...span(1, 18, 23, wood), ...span(6, 18, 23, tint(mood, C.woodSh)),
238 [18, 2, wood], [18, 3, wood], [18, 4, wood], [18, 5, wood],
239 [23, 2, wood], [23, 3, wood], [23, 4, wood], [23, 5, wood],
240 ...span(0, 20, 21, C.steel),
241 ]
242 for (let y = 2; y <= 5; y++) {
243 px.push([19, y, C.white], ...span(y, 20, 22, 0xbdbab3))
244 }
245 for (let i = 0; i < 4; i++) {
246 const y = 2 + i
247 if (i < checks) px.push([19, y, tint(mood, C.green)])
248 if (finding && i === 3) px.push([19, y, C.red])
249 }
250 return px
251 }
252 if (mood === 'work') {
253 // Ida y vuelta sin repetir los extremos; el portapapeles no se reinicia:
254 // dos marcas fijas y el hallazgo se enciende mientras el barrido está a la derecha.
255 const path = [4, 6, 8, 10, 12, 10, 8, 6]
256 return {
257 fps: 8,
258 frames: path.map(at => [
259 ...clawd({ eyes: 'covered', arms: 'out', legs: 0, color }),
260 ...visor(at),
261 ...board(2, at >= 10),
262 ]),
263 shine: bodyShine(color),
264 }
265 }
266 const still = [...clawd({ eyes: 'covered', arms: 'out', legs: 0, color }), ...visor(mood === 'wait' ? 8 : null), ...board(mood === 'sleep' ? 3 : 1, false)]
267 if (mood === 'wait') {
268 const dim = [...clawd({ eyes: 'covered', arms: 'out', legs: 0, color }), ...visor(null), ...board(1, false)]
269 return { fps: WAIT_FPS, frames: waitFrames(still, dim), shine: bodyShine(color) }
270 }
271 return { fps: 1, frames: [still], shine: bodyShine(color) }
272}
273
274// ── General: llave inglesa que oscila y caja de herramientas al lado ───────────
275// Cinco posturas de la llave, de vertical a horizontal: [mango desde la mano, quijadas].
276const WRENCH: Array<[Array<[number, number]>, Array<[number, number]>]> = [
277 [[[17, 3], [17, 2], [17, 1]], [[16, 0], [18, 0]]],
278 [[[18, 3], [18, 2], [18, 1]], [[17, 0], [19, 0]]],
279 [[[18, 3], [19, 2], [20, 1]], [[21, 0], [21, 2]]],
280 [[[18, 4], [19, 3], [20, 2]], [[21, 1], [21, 3]]],
281 [[[18, 4], [19, 4], [20, 4]], [[21, 3], [21, 5]]],
282]
283// Ida y vuelta sin repetir los extremos: 0,1,2,3,4,3,2,1.
284const SWING = [0, 1, 2, 3, 4, 3, 2, 1]
285
286function general(mood: Mood): Animation {
287 const color = bodyOf(mood)
288 const wrench = (pose: number): Px[] => {
289 const [handle, jaws] = WRENCH[pose]!
290 return [
291 ...handle.map(([x, y]) => [x, y, tint(mood, C.steel)] as Px),
292 ...jaws.map(([x, y]) => [x, y, tint(mood, C.blue)] as Px),
293 ]
294 }
295 const toolbox = (): Px[] => [
296 [23, 3, tint(mood, C.steel)], [24, 3, tint(mood, C.steel)],
297 ...span(4, 22, 25, tint(mood, C.blue)),
298 ...span(5, 22, 25, tint(mood, C.box)),
299 ...span(6, 22, 25, tint(mood, C.boxSh)),
300 [23, 5, tint(mood, C.yellow)],
301 ]
302 if (mood === 'work') {
303 return {
304 fps: 8,
305 frames: SWING.map((pose, f) => [
306 ...clawd({ eyes: f === 7 ? 'closed' : 'right', arms: 'hold', legs: 0, color }),
307 ...toolbox(),
308 ...wrench(pose),
309 ]),
310 shine: bodyShine(color),
311 }
312 }
313 // En reposo la llave descansa horizontal sobre la caja.
314 const still = [...clawd({ eyes: mood === 'wait' ? 'open' : 'closed', arms: 'hold', legs: 0, color }), ...toolbox(), ...wrench(4)]
315 if (mood === 'wait') {
316 const blink = [...clawd({ eyes: 'closed', arms: 'hold', legs: 0, color }), ...toolbox(), ...wrench(4)]
317 return { fps: WAIT_FPS, frames: waitFrames(still, blink), shine: bodyShine(color) }
318 }
319 return { fps: 1, frames: [still], shine: bodyShine(color) }
320}
321
322// ── Base: Clawd solo, mientras no se sabe qué hace ──────────────────────────
323function base(mood: Mood): Animation {
324 const color = bodyOf(mood)
325 if (mood === 'work') {
326 return {
327 fps: 4,
328 frames: Array.from({ length: 8 }, (_, f) =>
329 clawd({ eyes: f === 7 ? 'closed' : 'open', arms: 'out', legs: (f % 2) as 0 | 1, color })),
330 shine: bodyShine(color),
331 }
332 }
333 const still = clawd({ eyes: mood === 'wait' ? 'open' : 'closed', arms: 'out', legs: 0, color })
334 if (mood === 'wait') {
335 return { fps: WAIT_FPS, frames: waitFrames(still, clawd({ eyes: 'closed', arms: 'out', legs: 0, color })), shine: bodyShine(color) }
336 }
337 return { fps: 1, frames: [still], shine: bodyShine(color) }
338}
339
340export const SKINS: Record<Role, Skin> = {
341 research: { role: 'research', label: 'investigando', accent: '#E5B93C', animate: research },
342 developer: { role: 'developer', label: 'programando', accent: '#4EBA65', animate: developer },
343 auditor: { role: 'auditor', label: 'auditando', accent: '#E5534B', animate: auditor },
344 general: { role: 'general', label: 'generalista', accent: '#6B8AFD', animate: general },
345 base: { role: 'base', label: 'arrancando', accent: '#D97757', animate: base },
346}
347
348// ── Nivel del modelo: chispas para Opus, halo y chispas doradas para Fable ──
349const SPARK_HIGH = 0xc4b5fd
350const SPARK_TOP = 0xf2c14e
351const HALO_TOP = [0x7a5a12, 0xb8891f] // tenue y brillante, late cuadro a cuadro
352
353/** Chispas en las esquinas libres de Clawd, alternando entre dos lugares. */
354const sparks = (c: number, on: 0 | 1): Px[] =>
355 on === 0 ? [[0, 0, c], [1, 7, c]] : [[0, 6, c], [17, 0, c]]
356
357/** Contorno de píxeles alrededor de Clawd, para el terminal (en el SVG es un brillo). */
358const halo = (c: number): Px[] => [
359 ...span(1, 4, 13, c), [2, 1, c], [15, 1, c],
360 [2, 2, c], [2, 3, c], [0, 4, c], [17, 4, c], [2, 5, c], [15, 5, c], [15, 2, c], [15, 3, c],
361]
362
363/**
364 * Suma el nivel del modelo a una animación. `low` y `mid` no suman nada; así
365 * las chispas y el halo saltan a la vista. Con Clawd caído no se adorna.
366 */
367export function withTier(anim: Animation, tier: Tier, mood: Mood, surface: 'term' | 'svg'): Animation {
368 if (tier === 'low' || tier === 'mid' || mood === 'dead') return anim
369 // Una pose quieta se duplica para que las chispas titilen.
370 const base = anim.frames.length === 1 ? [anim.frames[0]!, anim.frames[0]!] : anim.frames
371 // Dos cuadros a 2 fps: las chispas titilan cada medio segundo (fps ∈ {8, 4, 2, 1}).
372 const fps = anim.frames.length === 1 ? 2 : anim.fps
373 const spark = tier === 'top' ? SPARK_TOP : SPARK_HIGH
374 const frames = base.map((f, i) => {
375 // Cuatro tramos por vuelta (uno por cuadro si hay pocos): el último empalma con el primero.
376 const on = (Math.floor(i / Math.max(1, base.length / 4)) % 2) as 0 | 1
377 // El halo va debajo: Clawd y sus accesorios lo tapan donde se cruzan.
378 const under = tier === 'top' && surface === 'term' ? halo(HALO_TOP[on]!) : []
379 return [...under, ...f, ...sparks(spark, on)]
380 })
381 return { ...anim, fps, frames, glow: tier === 'top' && surface === 'svg' ? '#F2C14E' : anim.glow }
382}
383
384// ── Pintores ─────────────────────────────────────────────────────────────────
385const hex = (n: number) => `#${n.toString(16).padStart(6, '0')}`
386const key = ([x, y, c]: Px) => `${x},${y},${c}`
387
388function flatten(frame: Frame): Map<string, number> {
389 // El último píxel escrito en una posición gana.
390 const m = new Map<string, number>()
391 for (const [x, y, c] of frame) if (x >= 0 && x < W && y >= 0 && y < H) m.set(`${x},${y}`, c)
392 return m
393}
394const toPx = (m: Map<string, number>): Px[] =>
395 [...m].map(([k, c]) => { const [x, y] = k.split(',').map(Number); return [x!, y!, c] as Px })
396
397const rects = (px: Px[], extra = '') =>
398 px.map(([x, y, c]) => `<rect x="${x}" y="${y}" width="1.02" height="1.02" fill="${hex(c)}"${extra}/>`).join('')
399
400/**
401 * SVG animado (SMIL, cuadros discretos); `px` de ancho. Con `phaseMs` (la hora
402 * del render) cada animación lleva `begin` negativo: un SVG recreado continúa
403 * donde iba y el ciclo no vuelve al cuadro 0 a mitad de camino.
404 */
405export function svgOf(anim: Animation, mood: Mood, px: number, phaseMs?: number): string {
406 const frames = anim.frames.map(f => toPx(flatten(f)))
407 const shared = frames.slice(1).reduce(
408 (acc, f) => { const s = new Set(f.map(key)); return acc.filter(p => s.has(key(p))) },
409 frames[0]!,
410 )
411 const sharedKeys = new Set(shared.map(key))
412 const n = frames.length
413 const dur = `${(n / anim.fps).toFixed(3)}s`
414 const begin = (durMs: number) =>
415 phaseMs !== undefined && Number.isFinite(phaseMs)
416 ? ` begin="-${((((phaseMs % durMs) + durMs) % durMs) / 1000).toFixed(3)}s"`
417 : ''
418 const frameBegin = begin(Math.round((n / anim.fps) * 1000))
419 const keyTimes = Array.from({ length: n }, (_, i) => (i / n).toFixed(4)).join(';')
420 const layers = n === 1 ? '' : frames.map((f, i) => {
421 const values = Array.from({ length: n }, (_, j) => (j === i ? 'visible' : 'hidden')).join(';')
422 return `<g visibility="${i === 0 ? 'visible' : 'hidden'}">${rects(f.filter(p => !sharedKeys.has(key(p))))}<animate attributeName="visibility" values="${values}" keyTimes="${keyTimes}" dur="${dur}"${frameBegin} calcMode="discrete" repeatCount="indefinite"/></g>`
423 }).join('')
424 // El brillo sólo cae sobre píxeles del cuerpo que siguen siendo cuerpo.
425 const bodyKeys = new Set(shared.filter(([, , c]) => c === C.body || c === C.dead).map(([x, y]) => `${x},${y}`))
426 const shine = (anim.shine ?? []).filter(([x, y]) => bodyKeys.has(`${x},${y}`))
427 const zz = mood === 'sleep'
428 ? `<text x="15.5" y="3.4" font-size="3.6" font-family="ui-monospace,Menlo,monospace" font-weight="700" fill="#8A8A8A">z<animate attributeName="opacity" values=".15;1;.15" dur="2.4s"${begin(2400)} repeatCount="indefinite"/><animateTransform attributeName="transform" type="translate" values="0 0;0 -1.2;0 0" dur="2.4s"${begin(2400)} repeatCount="indefinite"/></text>`
429 : ''
430 const ground = `<ellipse cx="9" cy="14.6" rx="7.5" ry=".7" fill="#000" opacity=".22"/>`
431 const glow = anim.glow
432 ? `<defs><radialGradient id="g"><stop offset="0" stop-color="${anim.glow}" stop-opacity=".75"/><stop offset="1" stop-color="${anim.glow}" stop-opacity="0"/></radialGradient></defs><ellipse cx="9" cy="8" rx="11" ry="8.5" fill="url(#g)"><animate attributeName="opacity" values=".45;1;.45" dur="1.8s"${begin(1800)} repeatCount="indefinite"/></ellipse>`
433 : ''
434 const h = Math.round((px * (H * 2 + 1)) / W)
435 return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -1 ${W} ${H * 2 + 1}" width="${px}" height="${h}" shape-rendering="crispEdges">${glow}${ground}<g transform="scale(1 2)">${anim.glow ? `<rect x="3" y="2" width="12" height="4" fill="${hex(C.ink)}"/>` : ''}${rects(shared)}${rects(shine, ' opacity=".55"')}${layers}</g>${zz}</svg>`
436}
437
438/** Celdas del Raster del terminal para un cuadro: cuartos de bloque, 2×2 píxeles. */
439export const COLS = W / 2
440export const ROWS = H / 2
441const QUAD = ' ▘▝▀▖▌▞▛▗▚▐▜▄▙▟█'
442const DEFAULT = 0x01000000
443
444export function cellsOf(frame: Frame): Uint32Array {
445 const m = flatten(frame)
446 const at = (x: number, y: number) => m.get(`${x},${y}`) ?? -1
447 const words = new Uint32Array(COLS * ROWS * 3)
448 for (let r = 0; r < ROWS; r++) {
449 for (let cx = 0; cx < COLS; cx++) {
450 const q = [at(2 * cx, 2 * r), at(2 * cx + 1, 2 * r), at(2 * cx, 2 * r + 1), at(2 * cx + 1, 2 * r + 1)]
451 const count = new Map<number, number>()
452 for (const c of q) if (c >= 0) count.set(c, (count.get(c) ?? 0) + 1)
453 const ranked = [...count.entries()].sort((a, b) => b[1] - a[1]).map(([c]) => c)
454 const i = (r * COLS + cx) * 3
455 if (ranked.length === 0) { words.set([0x20, DEFAULT, DEFAULT], i); continue }
456 const fg = ranked[0]!
457 const bg = q.some(c => c < 0) ? DEFAULT : ranked[1] ?? DEFAULT
458 let mask = 0
459 q.forEach((c, b) => { if (c === fg) mask |= 1 << b })
460 words.set([QUAD.charCodeAt(mask), fg, bg], i)
461 }
462 }
463 return words
464}
465hooks/models.ts 79 lines1// Ventana de contexto y precio de lista por modelo (API de Anthropic, USD por
2// millón de tokens). Fuente: tabla de modelos de la referencia de la API al
3// 2026-10-06. Bedrock y Vertex cobran aparte: el costo del panel es estimado.
4//
5// Se busca por prefijo del id, de lo más específico a lo más general.
6
7export type ModelInfo = {
8 /** Tokens de entrada que caben. */
9 window: number
10 /** [entrada, salida, lectura de caché, escritura de caché] */
11 price: [number, number, number, number]
12}
13
14const M = 1_000_000
15const K200 = 200_000
16// Escritura de caché a 1,25× la entrada (TTL de 5 minutos).
17const p = (inp: number, out: number, read: number): ModelInfo['price'] => [inp, out, read, inp * 1.25]
18
19const TABLE: Array<[string, ModelInfo]> = [
20 ['fable-5-1', { window: M, price: p(10, 50, 0.25) }],
21 ['mythos-5-1', { window: M, price: p(10, 50, 0.25) }],
22 ['fable-5', { window: M, price: p(10, 50, 1) }],
23 ['mythos-5', { window: M, price: p(10, 50, 1) }],
24 ['opus-5-5', { window: M, price: p(4, 20, 0.2) }],
25 ['opus-5', { window: M, price: p(5, 25, 0.5) }],
26 ['opus-4-8', { window: M, price: p(5, 25, 0.5) }],
27 ['opus-4-7', { window: M, price: p(5, 25, 0.5) }],
28 ['opus-4-6', { window: M, price: p(5, 25, 0.5) }],
29 ['opus-4-5', { window: K200, price: p(5, 25, 0.5) }],
30 ['opus', { window: K200, price: p(15, 75, 1.5) }],
31 ['sonnet-5-5', { window: M, price: p(2, 10, 0.2) }],
32 ['sonnet-5', { window: M, price: p(2, 10, 0.2) }],
33 ['sonnet-4-6', { window: M, price: p(3, 15, 0.3) }],
34 ['sonnet', { window: K200, price: p(3, 15, 0.3) }],
35 ['haiku-5-5', { window: M, price: p(0.1, 0.5, 0.01) }],
36 ['haiku-4-5', { window: K200, price: p(1, 5, 0.1) }],
37 ['haiku', { window: K200, price: p(1, 5, 0.1) }],
38]
39
40const UNKNOWN: ModelInfo = { window: K200, price: p(3, 15, 0.3) }
41
42export function modelInfo(model: string): ModelInfo {
43 const id = model.toLowerCase()
44 const hit = TABLE.find(([key]) => id.includes(key))?.[1] ?? UNKNOWN
45 // Un sufijo [1m] fuerza la ventana de un millón.
46 return /\[1m\]/.test(id) ? { ...hit, window: M } : hit
47}
48
49export type Usage = { input: number; output: number; cacheRead: number; cacheWrite: number }
50
51/** Costo en USD de un paso. Haiku 5.5 cobra 5× por encima de 100k tokens de prompt. */
52export function costOf(model: string, u: Usage): number {
53 let [inp, out, read, write] = modelInfo(model).price
54 const prompt = u.input + u.cacheRead + u.cacheWrite
55 if (/haiku-5-5/i.test(model) && prompt > 100_000) {
56 inp *= 5; out *= 5; read *= 5; write *= 5
57 }
58 return (u.input * inp + u.output * out + u.cacheRead * read + u.cacheWrite * write) / M
59}
60
61// ── Nivel de costo: cuánto destaca el modelo en el panel ────────────────────
62export type Tier = 'low' | 'mid' | 'high' | 'top'
63
64export function tierOf(model: string): Tier {
65 const id = model.toLowerCase()
66 if (/fable|mythos/.test(id)) return 'top'
67 if (/opus/.test(id)) return 'high'
68 if (/haiku/.test(id)) return 'low'
69 return 'mid'
70}
71
72/** Cómo se escribe el modelo: Haiku apagado, Sonnet normal, Opus violeta, Fable dorado. */
73export const TIER_STYLE: Record<Tier, { mark: string; color?: string; bold: boolean; dim: boolean }> = {
74 low: { mark: '', dim: true, bold: false },
75 mid: { mark: '● ', color: '#6B8AFD', dim: false, bold: false },
76 high: { mark: '◆ ', color: '#A78BFA', dim: false, bold: true },
77 top: { mark: '✦ ', color: '#F2C14E', dim: false, bold: true },
78}
79hooks/roles.ts 102 lines1// Quién es cada agente y qué está haciendo. Lógica pura, sin motor: se prueba suelta.
2//
3// skin → por su TIPO y su descripción (quién es); no cambia mientras trabaja.
4// actividad → por sus últimas llamadas (qué hace ahora); es la etiqueta de la tarjeta.
5
6import type { Role } from './skins.ts'
7
8export const AUDIT = /\breview(er)?\b|\baudit\w*|\bsecurity\b|\bseguridad\b|\bvuln\w*|\bqa\b|\bchecker\b|\bevidence\b/i
9const RESEARCH = /explore|plan|research|buscador|lector/i
10const DEVELOPER = /develop|engineer|builder|constructor|coder|frontend|backend|prototyper|architect/i
11
12const WRITES = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'Bash'])
13const READS = new Set(['Read', 'Grep', 'Glob', 'LS', 'WebSearch', 'WebFetch'])
14const MCP_READ = /^(get_|list_|search_|read_|query_|fetch_|describe_|find_)/
15const MCP_WRITE = /^(send_|create_|update_|delete_|trash_|write_|set_|apply_|label_|forward_|reply)/
16export const RECENT = 6
17export const MAX_FILES = 5
18
19export type Kind = 'read' | 'write' | 'other'
20export type FileKind = 'read' | 'write'
21export type FileRef = { path: string; kind: FileKind }
22
23/**
24 * Qué fue una llamada. El motor marca `isReadOnly` con el mismo chequeo de sus
25 * permisos: un `ls` o un `git diff` por Bash es lectura, un `pnpm build` no.
26 */
27export function kindOf(tool: string, isReadOnly: boolean | undefined): Kind {
28 if (isReadOnly || READS.has(tool)) return 'read'
29 if (WRITES.has(tool)) return 'write'
30 if (tool.startsWith('mcp__')) {
31 const name = tool.slice(tool.lastIndexOf('__') + 2)
32 if (MCP_READ.test(name)) return 'read'
33 if (MCP_WRITE.test(name)) return 'write'
34 }
35 return 'other'
36}
37
38/** El skin dice QUIÉN es: sólo mira el tipo (y la tarea, para el auditor). */
39export function skinOf(type: string, description = ''): Role {
40 if (AUDIT.test(`${type} ${description}`)) return 'auditor'
41 if (RESEARCH.test(type)) return 'research'
42 if (DEVELOPER.test(type)) return 'developer'
43 return 'general'
44}
45
46/**
47 * Qué hace ahora, de sus últimas llamadas: más escrituras que lecturas es
48 * programar, si no investigar. Sin ninguna de las dos todavía, `null`. Un
49 * auditor siempre audita.
50 */
51export function activityOf(tools: string[] | undefined, type = '', description = ''): Role | null {
52 if (AUDIT.test(`${type} ${description}`)) return 'auditor'
53 const kinds = (tools ?? []).filter(t => t === 'read' || t === 'write')
54 if (kinds.length === 0) return null
55 const writes = kinds.filter(t => t === 'write').length
56 return writes > kinds.length - writes ? 'developer' : 'research'
57}
58
59// ── Dónde trabaja y qué toca ─────────────────────────────────────────────────
60const WORKTREE = /^(.*\/\.claude\/worktrees\/([^/]+))(?:\/|$)/
61
62/** Un worktree de Claude Code por la ruta que toca: nombre y raíz. */
63export function worktreeOf(path: string | undefined): { name: string; root: string } | null {
64 const m = path ? WORKTREE.exec(path) : null
65 return m ? { name: m[2]!, root: m[1]! } : null
66}
67
68const baseName = (p: string) => p.replace(/\/+$/, '').split('/').pop() || p
69
70/** La ruta relativa al primer directorio que la contiene; si ninguno, sólo el nombre. */
71export function relPath(path: string, bases: Array<string | undefined>): string {
72 for (const b of bases) {
73 if (!b) continue
74 const dir = b.replace(/\/+$/, '')
75 if (path.startsWith(`${dir}/`)) return path.slice(dir.length + 1)
76 }
77 return baseName(path)
78}
79
80/** El archivo que toca una herramienta, con qué intención; `null` si ninguno. */
81export function fileOf(tool: string, input: Record<string, unknown>): FileRef | null {
82 const str = (v: unknown) => (typeof v === 'string' && v !== '' ? v : null)
83 if (tool === 'Grep' || tool === 'Glob') {
84 const p = str(input.path)
85 return p ? { path: p, kind: 'read' } : null
86 }
87 const p = str(input.file_path) ?? str(input.notebook_path)
88 if (!p) return null
89 return { path: p, kind: tool === 'Read' ? 'read' : tool === 'Edit' || tool === 'Write' || tool === 'MultiEdit' || tool === 'NotebookEdit' ? 'write' : 'read' }
90}
91
92/**
93 * Anota un archivo: de más viejo a más nuevo, sin repetidos y con los últimos
94 * `MAX_FILES`. Una vez escrito, sigue marcado como escrito aunque se relea.
95 */
96export function addFile(files: FileRef[] | undefined, ref: FileRef): FileRef[] {
97 const old = files ?? []
98 const prev = old.find(f => f.path === ref.path)
99 const kind: FileKind = prev?.kind === 'write' ? 'write' : ref.kind
100 return [...old.filter(f => f.path !== ref.path), { path: ref.path, kind }].slice(-MAX_FILES)
101}
102types/index.d.ts 34 lines1export type AgentRow = {
2 id: string
3 type: string
4 description: string
5 status: string
6 model: string
7 input: number
8 output: number
9 cacheRead: number
10 cacheWrite: number
11 context: number
12 usd: number
13 /** Qué fueron sus últimas llamadas ('read' | 'write' | 'other'), de la más vieja a la más nueva. */
14 tools: string[]
15 /** Directorio en que corre, si la llamada que lo lanzó lo fijó. */
16 cwd?: string
17 /** Nombre del worktree de Claude Code en que trabaja (`.claude/worktrees/<nombre>`). */
18 worktree?: string
19 /** Raíz de ese worktree, para mostrar las rutas relativas. */
20 root?: string
21 /** Rama de git de su worktree, su cwd o, en su defecto, la sesión. */
22 branch?: string
23 /** Los últimos archivos que leyó o escribió, del más viejo al más nuevo. */
24 files: { path: string; kind: 'read' | 'write' }[]
25 /** Cuándo dejó de trabajar (ms); sin valor mientras trabaja o espera. */
26 endedAt?: number
27}
28
29declare module 'claude-code' {
30 interface PluginState {
31 'agent-monitor': { rows: Record<string, AgentRow>; frame: number; now: number }
32 }
33}
34