Panel lateral de agentes y tareas: qué está haciendo ahora, presupuesto (5 h, semana, contexto y caché), agentes desplegables con historial y acciones, el plan…

Dos mods para Claude Code que muestran en pantalla lo que normalmente no se ve: qué hacen tus subagentes, cuánto te queda de cuota y cómo va la caché de prompts.
El panel de agent-bots en la app de escritorio, con agentes y tareas de ejemplo.
Aviso: la API de mods de Claude Code es de acceso anticipado y puede cambiar entre versiones. Probados con Claude Code 2.1.292 y 2.1.299.
| Mod | Qué hace | Dónde se ve |
|---|---|---|
agent-bots | Panel lateral «Agentes y tareas»: qué está haciendo ahora (paso, tiempo y acción), presupuesto en barras finas (5 h, semana y contexto) con el estado de la caché y botones para compactar o limpiar, agentes y comandos como robots con la etiqueta de su modelo y desplegables con su historial y acciones (detener, preguntar, copiar resultado), el plan de la sesión y los cambios en git con su diff. Las secciones se pliegan y lo plegado se recuerda entre sesiones | App de escritorio (en terminal, versión de texto) |
medidor | Banda sobre el prompt: modelo y esfuerzo, contexto, límites de 5 h y semana con su reinicio, costo, duración y estado de la caché con cuenta regresiva | Terminal |
Los dos se complementan: medidor solo dibuja en la terminal y agent-bots hace lo mismo en la app de escritorio. Puedes instalar solo uno.
/plugin marketplace add gabriel9004/claude-code-mods
/plugin install agent-bots@claude-code-mods
/plugin install medidor@claude-code-mods
/reload-plugins
Luego /tareas o /bots abre el panel y /medidor [completo|compacto|oculto] cambia la banda.
Un mod se ejecuta con acceso a la sesión, así que conviene saber qué toca. Ninguno envía datos a ningún sitio. Lo único que se guarda entre sesiones es qué secciones del panel de agent-bots tienes plegadas.
session.usage), el uso de tokens de cada petición para la caché y tres variables de entorno de solo lectura (FORCE_PROMPT_CACHING_5M, CLAUDE_CODE_PROMPT_CACHE_TTL, ENABLE_PROMPT_CACHING_1H). Registra una herramienta propia, tareas, y solo añade una línea al prompt de sistema si la sesión no trae ninguna herramienta de tareas. Para la sección de cambios ejecuta git diff y git ls-files en la carpeta de la sesión, solo lectura. Solo actúa cuando pulsas un botón: «Detener» llama a TaskStop y «Detener» del turno lo interrumpe, ambos con confirmación; «Preguntar» escribe en tu caja del prompt sin enviar; «Compactar» y «Limpiar» (con confirmación) equivalen a /compact y /clear; en la app de escritorio, donde el motor aún no deja hacerlo a un mod, dejan el comando escrito en tu caja del prompt para que pulses Enter.Cada mod trae sus pruebas:
cd agent-bots && claude plugin validate . && claude plugin test .
cd ../medidor && claude plugin validate .
MIT. La lógica de la caché toma ideas de otro proyecto MIT; ver NOTICE.md.
Two Claude Code mods: agent-bots (a desktop side panel with animated robots for subagents, a live task list and quota/cache rings) and medidor (a terminal band with model, context, 5 h / weekly limits, cost and prompt-cache countdown). The mods API is early access and may change.
/plugin marketplace add gabriel9004/claude-code-mods
/plugin install agent-bots@claude-code-mods
/plugin install medidor@claude-code-mods
MIT licensed. The UI text is in Spanish.
hooks/register.tsx 1589 lines1import { atom, read, update } from 'claude-code'
2import type { AgentInfo, EngineInterface, Register, Timer } from 'claude-code'
3
4import type { Bot, BotKind, BotMood, Change, Changes, Ctx, Limit, Muestra, Task, TaskStatus } from '../types'
5import { aciertos, decidirTtl, observarTtl, restanteMs, tokens } from './cache'
6
7const PANE = 'agent-bots'
8const TITLE = 'Agentes y tareas'
9const KEEP = 12
10
11const bots = atom({ plugin: 'agent-bots', key: 'bots' } as const, [])
12const tasks = atom({ plugin: 'agent-bots', key: 'tasks' } as const, [])
13const limits = atom({ plugin: 'agent-bots', key: 'limits' } as const, [])
14const replayed = atom({ plugin: 'agent-bots', key: 'replayed' } as const, false)
15const samples = atom({ plugin: 'agent-bots', key: 'muestras' } as const, [])
16const cacheTtl = atom({ plugin: 'agent-bots', key: 'ttl' } as const, '5m')
17const copies = atom({ plugin: 'agent-bots', key: 'copias' } as const, [])
18const duplicated = atom({ plugin: 'agent-bots', key: 'duplicado' } as const, false)
19// Las tareas hechas se pueden ocultar sin borrarlas; la elección dura toda la sesión, recargas incluidas.
20const hideDone = atom({ plugin: 'agent-bots', key: 'ocultarHechas' } as const, false)
21// Cada sección se puede plegar desde su encabezado.
22const foldAgents = atom({ plugin: 'agent-bots', key: 'plegarAgentes' } as const, false)
23const foldTasks = atom({ plugin: 'agent-bots', key: 'plegarTareas' } as const, false)
24// Con planes largos solo se ven las próximas pendientes; el resto, a demanda.
25const allPending = atom({ plugin: 'agent-bots', key: 'verPendientes' } as const, false)
26const PENDING_PREVIEW = 5
27const foldBudget = atom({ plugin: 'agent-bots', key: 'plegarPresupuesto' } as const, false)
28const foldChanges = atom({ plugin: 'agent-bots', key: 'plegarCambios' } as const, false)
29// Los agentes terminados se pliegan en «Ver N listos»: la atención va a lo que sigue activo.
30const showEnded = atom({ plugin: 'agent-bots', key: 'verListos' } as const, false)
31const context = atom({ plugin: 'agent-bots', key: 'contexto' } as const, null)
32const changes = atom({ plugin: 'agent-bots', key: 'cambios' } as const, null)
33const diffView = atom({ plugin: 'agent-bots', key: 'diff' } as const, null)
34// Agente desplegado y acción que espera confirmación («turn», «clear» o «stop:<clave>»).
35const opened = atom({ plugin: 'agent-bots', key: 'abierto' } as const, null)
36const confirming = atom({ plugin: 'agent-bots', key: 'confirmar' } as const, null)
37// El hilo principal está en un turno; su modelo y lo último que hizo.
38const busy = atom({ plugin: 'agent-bots', key: 'ocupado' } as const, false)
39const mainModel = atom({ plugin: 'agent-bots', key: 'modelo' } as const, '')
40const mainAction = atom({ plugin: 'agent-bots', key: 'accion' } as const, '')
41const LOG_KEEP = 6
42const CTX_WARN = 70
43// Lo plegado se recuerda entre sesiones ($.store dura más que el estado de la sesión).
44type FoldKey = 'plegarPresupuesto' | 'plegarAgentes' | 'plegarTareas' | 'plegarCambios'
45
46// Sin señales en este tiempo, un robot que dice trabajar pasa a «¿Colgado?». Un comando
47// (compilar, una consulta larga) no da señales mientras corre: se le da más margen.
48const STALL_AGENT_MS = 10 * 60_000
49const STALL_SHELL_MS = 20 * 60_000
50
51// Cada carga del módulo es una copia; dos copias vivas cuentan todo doble.
52const INSTANCE = Math.random().toString(36).slice(2, 10)
53const BEAT_MS = 15_000
54const ALIVE_MS = 40_000
55
56// Las dos ventanas de cuota que se dibujan, en este orden.
57const QUOTA: { kind: string; label: string; ramp: [string, string] }[] = [
58 { kind: 'five_hour', label: '5 h', ramp: ['#AFA9EC', '#7F77DD'] },
59 { kind: 'seven_day', label: 'Semana', ramp: ['#5DCAA5', '#1D9E75'] },
60]
61const WARN: [string, string] = ['#FAC775', '#EF9F27']
62const HOT: [string, string] = ['#F09595', '#E24B4A']
63const now = atom({ plugin: 'agent-bots', key: 'now' } as const, 0)
64
65const TASK_LABEL: Record<TaskStatus, [string, string]> = {
66 in_progress: ['En curso', '#378ADD'],
67 pending: ['Pendiente', '#888780'],
68 completed: ['Hecha', '#639922'],
69}
70const TASK_GLYPH: Record<TaskStatus, string> = { in_progress: '🔄', pending: '⏳', completed: '✅' }
71
72// Herramientas de la app que mueven la lista de tareas (se reconocen por el sufijo del nombre).
73const PLAN_TOOL = '__update_plan'
74const WRAP_TOOL = '__wrap_up'
75
76// Herramienta propia del mod, para las sesiones que no traen ninguna de tareas.
77const OWN_TOOL = 'mcp__agent-bots__tareas'
78const OWN_SPEC = {
79 name: 'tareas',
80 description:
81 'Muestra al usuario, en un panel lateral, la lista de tareas de la sesión. Envía el plan completo con «items»; ' +
82 'después marca el avance con «advance», «done» o «start». Un paso a la vez en curso.',
83 isDeferred: false,
84 inputSchema: {
85 type: 'object',
86 properties: {
87 items: {
88 type: 'array',
89 description: 'La lista completa de pasos, en orden; sustituye a la anterior.',
90 items: {
91 type: 'object',
92 properties: {
93 content: { type: 'string', description: 'El paso, en pocas palabras.' },
94 status: { type: 'string', enum: ['pending', 'in_progress', 'completed'] },
95 },
96 required: ['content', 'status'],
97 },
98 },
99 advance: { type: 'boolean', description: 'Marca como hecho el paso en curso y pone en curso el siguiente pendiente.' },
100 done: { type: 'array', items: { type: 'number' }, description: 'Números de paso (desde 1) que pasan a hechos.' },
101 start: { type: 'number', description: 'Número de paso (desde 1) que pasa a en curso.' },
102 },
103 },
104}
105const OWN_PROMPT =
106 `Dispones de la herramienta \`${OWN_TOOL}\`, que muestra al usuario la lista de tareas en un panel lateral. ` +
107 'En un trabajo de varios pasos, envía el plan completo al empezar (items, cada uno con status pending, in_progress o completed), ' +
108 'llama con advance: true al terminar cada paso y reenvía la lista completa si el plan cambia. No la uses para preguntas simples.'
109// Si la sesión ya trae su propia herramienta de tareas, la del mod no se ofrece en el prompt.
110const HOST_LISTS = (name: string) =>
111 name.endsWith(PLAN_TOOL) || name === 'TodoWrite' || name === 'TaskCreate' || name === 'TaskUpdate'
112
113// Relleno, trazo y tinta de cada familia de modelo (rampas del mockup).
114type Ramp = [string, string, string]
115type Family = 'opus' | 'sonnet' | 'haiku' | 'other'
116const RAMP: Record<Family, Ramp> = {
117 opus: ['#EEEDFE', '#7F77DD', '#3C3489'],
118 sonnet: ['#E6F1FB', '#378ADD', '#0C447C'],
119 haiku: ['#E1F5EE', '#1D9E75', '#085041'],
120 other: ['#F1EFE8', '#888780', '#444441'],
121}
122const FAIL: Ramp = ['#FCEBEB', '#E24B4A', '#791F1F']
123const SHELL: Ramp = ['#FAEEDA', '#BA7517', '#633806']
124
125const LABEL: Record<BotMood, [string, string]> = {
126 run: ['Trabajando', '#378ADD'],
127 sleep: ['Esperando', '#BA7517'],
128 done: ['Listo', '#639922'],
129 fail: ['Falló', '#E24B4A'],
130}
131const GLYPH: Record<BotMood, string> = { run: '🤖', sleep: '😴', done: '✅', fail: '💥' }
132
133function family(model: string): Family {
134 const m = model.toLowerCase()
135 for (const f of ['opus', 'sonnet', 'haiku'] as const) if (m.includes(f)) return f
136 return 'other'
137}
138
139function modelName(model: string): string {
140 const f = family(model)
141 if (f === 'other') return model || '?'
142 const v = /(\d+)[-.](\d+)/.exec(model)
143 return f.charAt(0).toUpperCase() + f.slice(1) + (v ? ` ${v[1]}.${v[2]}` : '')
144}
145
146function mood(status: string): BotMood {
147 if (status === 'running' || status === 'pending') return 'run'
148 if (status === 'waiting' || status === 'idle') return 'sleep'
149 if (status === 'completed') return 'done'
150 return 'fail'
151}
152
153const isEnded = (status: string) => ['completed', 'failed', 'killed'].includes(status)
154
155// Por minutos a propósito: con segundos el panel tendría que redibujarse cada segundo, y cada
156// redibujo reinicia las animaciones de los SVG y repinta los botones (el parpadeo).
157function elapsed(ms: number): string {
158 const m = Math.floor(Math.max(0, ms) / 60_000)
159 if (m < 1) return '<1 min'
160 return m < 60 ? `${m} min` : `${Math.floor(m / 60)}h ${String(m % 60).padStart(2, '0')}m`
161}
162
163// La hora que dibuja el panel solo avanza de minuto en minuto: lo que muestra no tiene más detalle.
164async function tick($: EngineInterface, t: number) {
165 const cur = await read($, now)
166 if (Math.floor(cur / 60_000) !== Math.floor(t / 60_000)) await update($, now, () => t)
167}
168
169function bar(done: number, total: number, width = 16): string {
170 const full = total ? Math.round((done / total) * width) : 0
171 return '█'.repeat(full) + '░'.repeat(width - full)
172}
173
174function base(path: unknown): string {
175 return typeof path === 'string' ? path.split(/[\\/]/).pop() || path : ''
176}
177
178function clip(text: unknown, n = 38): string {
179 const t = typeof text === 'string' ? text.replace(/\s+/g, ' ').trim() : ''
180 return t.length > n ? t.slice(0, n - 1) + '…' : t
181}
182
183// Lo que dice el bocadillo según la herramienta que el agente acaba de usar.
184function action(tool: string, input: Record<string, unknown>): string {
185 switch (tool) {
186 case 'Read': return `📖 Leyendo ${base(input.file_path)}`
187 case 'Write': return `✏️ Creando ${base(input.file_path)}`
188 case 'Edit': return `✏️ Editando ${base(input.file_path)}`
189 case 'Grep': return `🔍 Grep "${clip(input.pattern, 28)}"`
190 case 'Glob': return `🗂️ Buscando ${clip(input.pattern, 28)}`
191 case 'Bash':
192 case 'PowerShell': return `⚙️ ${clip(input.command)}`
193 case 'WebFetch':
194 case 'WebSearch': return `🌐 ${clip(input.url ?? input.query)}`
195 case 'Agent': return `🤖 Lanzando ${clip(input.description, 30)}`
196 default: return `🔧 ${clip(tool.replace(/^mcp__[^_]+__/, ''), 34)}`
197 }
198}
199
200function robot(m: BotMood, model: string, kind: BotKind = 'agent'): string {
201 const [fill, stroke, ink] = m === 'fail' ? FAIL : kind === 'shell' ? SHELL : RAMP[family(model)]
202 const loop = 'repeatCount="indefinite"'
203 const bodyAnim =
204 m === 'run' ? `<animateTransform attributeName="transform" type="translate" values="0 0;0 -3;0 0" dur="1.2s" ${loop}/>`
205 : m === 'done' ? `<animateTransform attributeName="transform" type="translate" values="0 0;0 -8;0 0;0 0" keyTimes="0;0.2;0.4;1" dur="2.5s" ${loop}/>`
206 : m === 'fail' ? `<animateTransform attributeName="transform" type="translate" values="0 0;-2 0;2 0;0 0" dur="0.4s" repeatCount="3"/>`
207 : ''
208 const blink = m === 'run' ? `<animate attributeName="opacity" values="1;0.2;1" dur="0.8s" ${loop}/>` : ''
209 const look = m === 'run'
210 ? `<animateTransform attributeName="transform" type="translate" values="0 0;0 0;2.5 0;2.5 0;0 0" keyTimes="0;0.4;0.5;0.9;1" dur="3s" ${loop}/>`
211 : ''
212 const eyes =
213 m === 'sleep' ? `<rect x="20" y="25" width="8" height="2" rx="1" fill="${ink}"/><rect x="36" y="25" width="8" height="2" rx="1" fill="${ink}"/>`
214 : m === 'fail' ? `<path d="M20 22l7 6M27 22l-7 6M37 22l7 6M44 22l-7 6" stroke="${ink}" stroke-width="2"/>`
215 : `<g>${look}<circle cx="24" cy="25" r="4" fill="${ink}"/><circle cx="40" cy="25" r="4" fill="${ink}"/><circle cx="25.5" cy="23.5" r="1.2" fill="#fff"/><circle cx="41.5" cy="23.5" r="1.2" fill="#fff"/></g>`
216 const mouth =
217 m === 'done' ? `<path d="M26 33q6 5 12 0" stroke="${ink}" stroke-width="2" fill="none"/>`
218 : m === 'fail' ? `<path d="M26 36q6-5 12 0" stroke="${ink}" stroke-width="2" fill="none"/>`
219 : `<rect x="27" y="33" width="10" height="2" rx="1" fill="${ink}"/>`
220 const z = (x: number, y: number, size: number, begin: string) =>
221 `<text x="${x}" y="${y}" font-size="${size}" font-family="sans-serif" fill="${stroke}" opacity="0">z` +
222 `<animate attributeName="opacity" values="0;1;0" dur="2.4s" begin="${begin}" ${loop}/>` +
223 `<animateTransform attributeName="transform" type="translate" values="0 0;8 -14" dur="2.4s" begin="${begin}" ${loop}/></text>`
224 const extra =
225 m === 'sleep' ? z(46, 14, 11, '0s') + z(50, 10, 9, '1.2s')
226 : m === 'done' ? `<circle cx="52" cy="52" r="7" fill="#639922"/><path d="M48.5 52l2.5 2.5 4-4.5" stroke="#fff" stroke-width="1.8" fill="none"/>`
227 : ''
228 // El robot de un comando lleva un engranaje en lugar de antena, que gira mientras corre.
229 const spin = m === 'run'
230 ? `<animateTransform attributeName="transform" type="rotate" values="0 32 7;360 32 7" dur="2s" ${loop}/>`
231 : ''
232 const top = kind === 'shell'
233 ? `<g>${spin}<circle cx="32" cy="7" r="5" fill="none" stroke="${stroke}" stroke-width="3" stroke-dasharray="2.6 1.6"/>` +
234 `<circle cx="32" cy="7" r="2.2" fill="${stroke}"/></g>`
235 : `<line x1="32" y1="6" x2="32" y2="13" stroke="${stroke}" stroke-width="2"/>` +
236 `<circle cx="32" cy="5" r="3" fill="${stroke}">${blink}</circle>`
237 return (
238 `<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">` +
239 `<g opacity="${m === 'done' ? 0.8 : 1}"><g>${bodyAnim}` +
240 top +
241 `<rect x="12" y="13" width="40" height="28" rx="9" fill="${fill}" stroke="${stroke}" stroke-width="1.5"/>` +
242 eyes + mouth +
243 `<rect x="20" y="43" width="24" height="14" rx="5" fill="${fill}" stroke="${stroke}" stroke-width="1.5"/>` +
244 `<circle cx="32" cy="50" r="2.5" fill="${stroke}">${blink}</circle>` +
245 `</g></g>${extra}</svg>`
246 )
247}
248
249// Recorta la lista: primero se van los terminados más antiguos.
250function trim(list: Bot[]): Bot[] {
251 let out = list
252 while (out.length > KEEP) {
253 const i = out.findIndex(b => isEnded(b.status))
254 out = out.filter((_, j) => j !== (i === -1 ? 0 : i))
255 }
256 return out
257}
258
259// Anillo de cuota, estático a propósito: el panel se redibuja cada segundo mientras hay tareas en curso
260// y cualquier animación SMIL en el SVG se reinicia con cada redibujo (ese era el latido). El color avisa:
261// ámbar desde el 70 % y rojo desde el 90 %, salvo en los anillos donde llenarse es bueno (caché).
262function gauge(pct: number, ramp: [string, string], id: string, warn = true): string {
263 const p = Math.max(0, Math.min(100, pct))
264 const [light, deep] = warn && p >= 90 ? HOT : warn && p >= 70 ? WARN : ramp
265 const c = 2 * Math.PI * 30
266 const len = ((p / 100) * c).toFixed(1)
267 return (
268 `<svg xmlns="http://www.w3.org/2000/svg" width="80" height="80" viewBox="0 0 80 80">` +
269 `<defs><linearGradient id="q-${id}" x1="0" y1="0" x2="1" y2="1">` +
270 `<stop offset="0" stop-color="${light}"/><stop offset="1" stop-color="${deep}"/></linearGradient></defs>` +
271 `<circle cx="40" cy="40" r="30" fill="none" stroke="#888780" stroke-opacity="0.22" stroke-width="7"/>` +
272 `<g transform="rotate(-90 40 40)"><circle cx="40" cy="40" r="30" fill="none" stroke="url(#q-${id})" stroke-width="7" ` +
273 `stroke-linecap="round" stroke-dasharray="${len} ${c.toFixed(1)}"/></g>` +
274 `<text x="40" y="46" text-anchor="middle" font-family="sans-serif" font-size="17" font-weight="600" fill="${deep}">${Math.round(p)}%</text>` +
275 `</svg>`
276 )
277}
278
279// Etiqueta de cada robot: el nombre del modelo sobre su color, legible sin mirar la leyenda.
280function modelChip(b: Bot): { text: string; ramp: Ramp } {
281 if (b.kind === 'shell') return { text: 'Comando', ramp: SHELL }
282 if (!b.model) return { text: 'sin dato', ramp: RAMP.other }
283 return { text: modelName(b.model), ramp: RAMP[family(b.model)] }
284}
285
286// Barra de avance de las tareas, redondeada y con el degradado de los anillos (estática: sin SMIL).
287function progressBar(frac: number, complete: boolean): string {
288 const w = 220
289 const f = Math.round(w * Math.max(0, Math.min(1, frac)))
290 const [a, b] = complete ? ['#97C459', '#639922'] : ['#85B7EB', '#378ADD']
291 return (
292 `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="10" viewBox="0 0 ${w} 10">` +
293 `<defs><linearGradient id="pb" x1="0" x2="1"><stop offset="0" stop-color="${a}"/><stop offset="1" stop-color="${b}"/></linearGradient></defs>` +
294 `<rect x="0" y="1" width="${w}" height="8" rx="4" fill="#888780" fill-opacity="0.22"/>` +
295 (f > 0 ? `<rect x="0" y="1" width="${Math.max(8, f)}" height="8" rx="4" fill="url(#pb)"/>` : '') +
296 `</svg>`
297 )
298}
299
300// Barra fina de presupuesto (estática: sin SMIL, para que el redibujo no la haga latir).
301function thinBar(pct: number, color: string, w = 84): string {
302 const f = Math.round(w * Math.max(0, Math.min(1, pct / 100)))
303 return (
304 `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="6" viewBox="0 0 ${w} 6">` +
305 `<rect x="0" y="0" width="${w}" height="6" rx="3" fill="#888780" fill-opacity="0.22"/>` +
306 (f > 0 ? `<rect x="0" y="0" width="${Math.max(6, f)}" height="6" rx="3" fill="${color}"/>` : '') +
307 `</svg>`
308 )
309}
310
311// Color de una barra de presupuesto: el suyo, ámbar desde el 70 % y rojo desde el 90 %.
312function budgetColor(pct: number, own: string): string {
313 return pct >= 90 ? HOT[1] : pct >= CTX_WARN ? WARN[1] : own
314}
315
316// Minutos y segundos desde el arranque del agente, para su historial.
317function offset(ms: number): string {
318 const s = Math.max(0, Math.floor(ms / 1000))
319 return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`
320}
321
322function bar10(pct: number): string {
323 const full = Math.round(Math.max(0, Math.min(100, pct)) / 10)
324 return '█'.repeat(full) + '░'.repeat(10 - full)
325}
326
327// Cuánto falta para que la ventana se reinicie: «45 min», «2h 14m» o «3d 4h».
328function resetIn(iso: string | undefined, t: number): string {
329 const at = iso ? Date.parse(iso) : NaN
330 if (!Number.isFinite(at)) return ''
331 const m = Math.max(0, Math.round((at - t) / 60000))
332 if (m < 60) return `${m} min`
333 const h = Math.floor(m / 60)
334 if (h < 24) return `${h}h ${String(m % 60).padStart(2, '0')}m`
335 return `${Math.floor(h / 24)}d ${h % 24}h`
336}
337
338// Guarda las ventanas de 5 h y semana; avisa una vez al cruzar el 90 %.
339async function readLimits($: EngineInterface, fresh: readonly { kind: string; percentUsed: number; resetsAt?: string }[]) {
340 const before = await read($, limits)
341 const next: Limit[] = []
342 for (const { kind, label } of QUOTA) {
343 const got = fresh.find(l => l.kind === kind)
344 if (!got) continue
345 const old = before.find(l => l.kind === kind)
346 next.push({ kind, percentUsed: got.percentUsed, prevPercent: old?.percentUsed ?? 0, resetsAt: got.resetsAt })
347 if ((old?.percentUsed ?? 0) < 90 && got.percentUsed >= 90) {
348 try {
349 void $.ui.toast(`Cuota de ${label} al ${Math.round(got.percentUsed)} %`)
350 } catch {}
351 }
352 }
353 if (next.length) await update($, limits, () => next)
354 startQuotaClock($)
355}
356
357let quotaClock: Timer | undefined
358
359// La cuenta regresiva del reinicio se mueve aunque no haya agentes: un pulso por minuto.
360function startQuotaClock($: EngineInterface) {
361 if (quotaClock) return
362 quotaClock = $.clock.every(60000, () => {
363 void $.clock.now().then(t => tick($, t)).catch(() => {})
364 })
365}
366
367function asStatus(value: unknown): TaskStatus {
368 return value === 'in_progress' || value === 'completed' ? value : 'pending'
369}
370
371// El indicador de cada tarea: anillo que gira, visto verde o círculo punteado.
372function taskMark(s: TaskStatus): string {
373 const loop = 'repeatCount="indefinite"'
374 const body =
375 s === 'completed'
376 ? `<circle cx="12" cy="12" r="10" fill="#639922"/><path d="M7.5 12.5l3 3 6-7" stroke="#fff" stroke-width="2.2" fill="none" stroke-linecap="round" stroke-linejoin="round"/>`
377 : s === 'in_progress'
378 ? `<circle cx="12" cy="12" r="9" fill="none" stroke="#B5D4F4" stroke-width="3"/>` +
379 `<g><animateTransform attributeName="transform" type="rotate" values="0 12 12;360 12 12" dur="1s" ${loop}/>` +
380 `<path d="M12 3a9 9 0 0 1 9 9" fill="none" stroke="#378ADD" stroke-width="3" stroke-linecap="round"/></g>`
381 : `<circle cx="12" cy="12" r="9" fill="none" stroke="#B4B2A9" stroke-width="2" stroke-dasharray="3 3"/>`
382 return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">${body}</svg>`
383}
384
385// Recibe una lista nueva y conserva los tiempos de las tareas que ya estaban.
386function fromItems(old: Task[], items: { content: string; status: TaskStatus }[], t: number): Task[] {
387 const used = new Set<number>()
388 return items.map((it, i) => {
389 const j = old.findIndex((o, k) => !used.has(k) && o.content === it.content)
390 if (j !== -1) used.add(j)
391 const prev = j === -1 ? undefined : old[j]
392 return {
393 key: prev?.key ?? `p${t}:${i}`,
394 ref: prev?.ref,
395 content: it.content,
396 status: it.status,
397 startedAt: it.status === 'pending' ? undefined : (prev?.startedAt ?? t),
398 endedAt: it.status === 'completed' ? (prev?.endedAt ?? t) : undefined,
399 }
400 })
401}
402
403function setStatus(task: Task, status: TaskStatus, t: number): Task {
404 if (task.status === status) return task
405 return {
406 ...task,
407 status,
408 startedAt: status === 'pending' ? undefined : (task.startedAt ?? t),
409 endedAt: status === 'completed' ? t : undefined,
410 }
411}
412
413// update_plan de la app: «items» sustituye la lista; «advance», «done» y «start» mueven pasos.
414function applyPlan(list: Task[], input: Record<string, unknown>, t: number): Task[] {
415 if (Array.isArray(input.items)) {
416 const items = (input.items as Record<string, unknown>[]).map(it => ({
417 content: String(it?.content ?? ''),
418 status: asStatus(it?.status),
419 }))
420 return fromItems(list, items, t)
421 }
422 const next = [...list]
423 const at = (n: unknown) => (typeof n === 'number' ? n - 1 : -1)
424 if (input.advance === true) {
425 const cur = next.findIndex(x => x.status === 'in_progress')
426 if (cur !== -1) next[cur] = setStatus(next[cur], 'completed', t)
427 const nxt = next.findIndex(x => x.status === 'pending')
428 if (nxt !== -1) next[nxt] = setStatus(next[nxt], 'in_progress', t)
429 }
430 if (Array.isArray(input.done)) {
431 for (const n of input.done) if (next[at(n)]) next[at(n)] = setStatus(next[at(n)], 'completed', t)
432 }
433 if (next[at(input.start)]) next[at(input.start)] = setStatus(next[at(input.start)], 'in_progress', t)
434 return next
435}
436
437// wrap_up cierra el turno: lo que seguía en curso queda hecho.
438function applyWrap(list: Task[], t: number): Task[] {
439 return list.map(x => (x.status === 'in_progress' ? setStatus(x, 'completed', t) : x))
440}
441
442function applyTodos(list: Task[], input: Record<string, unknown>, t: number): Task[] {
443 const todos = Array.isArray(input.todos) ? (input.todos as Record<string, unknown>[]) : []
444 return fromItems(
445 list,
446 todos.map(it => ({ content: String(it?.content ?? ''), status: asStatus(it?.status) })),
447 t,
448 )
449}
450
451function applyUpdate(list: Task[], input: Record<string, unknown>, t: number): Task[] {
452 const id = String(input.taskId ?? '')
453 if (input.status === 'deleted') return list.filter(x => x.ref !== id)
454 return list.map(x => {
455 if (x.ref !== id) return x
456 const renamed = typeof input.subject === 'string' && input.subject ? { ...x, content: input.subject } : x
457 return input.status ? setStatus(renamed, asStatus(input.status), t) : renamed
458 })
459}
460
461// Qué le hace una llamada a la lista de tareas; undefined si la herramienta no es de tareas.
462// «fresh» marca una lista nueva entera (abre el panel).
463function step(tool: string, input: Record<string, unknown>, result: unknown, t: number):
464 { apply: (list: Task[]) => Task[]; fresh: boolean } | undefined {
465 if (tool.endsWith(PLAN_TOOL) || tool === OWN_TOOL) {
466 return { apply: l => applyPlan(l, input, t), fresh: Array.isArray(input.items) }
467 }
468 if (tool.endsWith(WRAP_TOOL)) return { apply: l => applyWrap(l, t), fresh: false }
469 if (tool === 'TodoWrite') return { apply: l => applyTodos(l, input, t), fresh: true }
470 if (tool === 'TaskCreate') {
471 const made = (result as { task?: { id?: unknown } } | null | undefined)?.task?.id
472 const ref = typeof made === 'string' ? made : undefined
473 return {
474 apply: l => [...l, { key: `c${t}:${l.length}`, ref, content: String(input.subject ?? ''), status: 'pending' }],
475 fresh: false,
476 }
477 }
478 if (tool === 'TaskUpdate') return { apply: l => applyUpdate(l, input, t), fresh: false }
479 return undefined
480}
481
482async function track($: EngineInterface, tool: string, input: Record<string, unknown>, result: unknown) {
483 const t = await $.clock.now()
484 const s = step(tool, input, result, t)
485 if (!s) return
486 const before = await read($, tasks)
487
488 await update($, tasks, s.apply)
489 await tick($, t)
490 if (s.fresh || before.length === 0) void $.ui.open({ id: PANE, title: TITLE }).catch(() => {})
491 const after = await read($, tasks)
492 if (after.some(x => x.status === 'in_progress')) startTicker($)
493 const allDone = (l: Task[]) => l.length > 0 && l.every(x => x.status === 'completed')
494 if (allDone(after) && !allDone(before)) toast($, `✅ Plan terminado: ${after.length} tareas`)
495}
496
497// La primera vez que el mod se carga en una sesión, rehace la lista con las llamadas que ya
498// hubo, para no arrancar vacío con un plan a medias. Una sola vez por sesión: si luego se
499// limpia la lista, una recarga no la resucita.
500async function replay($: EngineInterface) {
501 if (await read($, replayed)) return
502 await update($, replayed, () => true)
503 if ((await read($, tasks)).length) return
504 const t = await $.clock.now()
505 let list: Task[] = []
506 for (const m of await $.session.messages()) {
507 for (const use of m.toolUses ?? []) {
508 if (use.isError) continue
509 const s = step(use.tool, use.input, use.result, t)
510 if (s) list = s.apply(list)
511 }
512 }
513 if (!list.length) return
514 // El historial no trae horas: lo hecho queda sin duración y lo que sigue en curso cuenta desde ahora.
515 list = list.map(x => (x.status === 'completed' ? { ...x, startedAt: undefined, endedAt: undefined } : x))
516 await update($, tasks, () => list)
517 await tick($, t)
518 if (list.some(x => x.status === 'in_progress')) startTicker($)
519}
520
521function toast($: EngineInterface, text: string) {
522 try {
523 void $.ui.toast(text)
524 } catch {}
525}
526
527// Avisa una sola vez de cada agente en segundo plano o comando que terminó o falló: lo de primer
528// plano no, porque la sesión ya está esperándolo. «told» queda en el estado, así una recarga no repite.
529async function tellEnds($: EngineInterface) {
530 const list = await read($, bots)
531 const fresh = list.filter(b => isEnded(b.status) && !b.told && (b.kind === 'shell' || b.background))
532 if (!fresh.length) return
533 await update($, bots, l => l.map(b => (fresh.some(f => f.key === b.key) ? { ...b, told: true } : b)))
534 for (const b of fresh) {
535 const what = b.kind === 'shell' ? 'Comando' : 'Agente'
536 toast($, b.status === 'completed' ? `✅ ${what} terminado: ${clip(b.description, 50)}` : `💥 ${what} falló: ${clip(b.description, 50)}`)
537 }
538}
539
540// Lo que ya había terminado al cargarse esta versión no se anuncia.
541async function quietEnded($: EngineInterface) {
542 await update($, bots, l => l.map(b => (isEnded(b.status) && !b.told ? { ...b, told: true } : b)))
543}
544
545let beat: Timer | undefined
546// Cuándo arrancó esta copia y cuándo procesó su último evento de la sesión.
547let bornAt = 0
548let lastEvent = 0
549
550// Latido de esta copia; si otra copia late a la vez, el panel lo avisa. Solo cuenta una copia que
551// procesó eventos después de que arrancara esta: al recargar, la copia vieja aún da un último
552// latido antes de apagarse, pero ya no recibe eventos, y eso no es un duplicado.
553function startBeat($: EngineInterface) {
554 if (beat) return
555 const pulse = async () => {
556 const t = await $.clock.now()
557 let alive = 0
558 await update($, copies, l => {
559 const next = [
560 ...l.filter(c => c.id !== INSTANCE && t - c.at < ALIVE_MS),
561 { id: INSTANCE, at: t, ev: lastEvent },
562 ]
563 alive = next.filter(c => (c.ev ?? 0) > bornAt).length
564 return next
565 })
566 const dup = alive > 1
567 if (dup !== (await read($, duplicated))) {
568 await update($, duplicated, () => dup)
569 if (dup) toast($, '⚠ agent-bots está cargado dos veces: los conteos saldrán dobles')
570 }
571 }
572 beat = $.clock.every(BEAT_MS, () => void pulse().catch(() => {}))
573 void pulse().catch(() => {})
574}
575
576let seq = 0
577let ticker: Timer | undefined
578
579// Une la lista viva del motor con lo que guardamos al lanzar cada agente (sin efectos: la usa sync).
580function merge(list: Bot[], infos: AgentInfo[], t: number): Bot[] {
581 const taken = new Set(list.map(b => b.id).filter(Boolean))
582 const next = list.map(b => {
583 if (b.kind === 'shell') return b
584 let info = b.id ? infos.find(i => i.id === b.id) : undefined
585 if (!b.id) {
586 info = infos.find(i => !taken.has(i.id) && i.description === b.description)
587 if (info) taken.add(info.id)
588 }
589 if (!info) return b
590 const ended = isEnded(info.status)
591 return {
592 ...b,
593 id: info.id,
594 status: info.status,
595 endedAt: ended ? (b.endedAt ?? t) : undefined,
596 }
597 })
598 // Adopta los agentes vivos cuyo arranque el mod no vio (lanzados antes de cargarse).
599 // Su modelo no se conoce: salen en gris y sin hora de inicio exacta.
600 for (const info of infos) {
601 if (taken.has(info.id) || isEnded(info.status)) continue
602 taken.add(info.id)
603 next.push({
604 key: `adopted:${info.id}`,
605 kind: 'agent',
606 id: info.id,
607 description: info.description || info.name || info.type,
608 type: info.type,
609 model: '',
610 status: info.status,
611 startedAt: t,
612 lastSeen: t,
613 background: true,
614 action: '👀 Ya estaba en marcha',
615 calls: 0,
616 })
617 }
618 return trim(next)
619}
620
621// Corre cada segundo mientras hay actividad: solo escribe si algo cambió de verdad, porque cada
622// escritura redibuja el panel entero.
623async function sync($: EngineInterface): Promise<boolean> {
624 const infos: AgentInfo[] = await $.agent.list()
625 const t = await $.clock.now()
626 const current = await read($, bots)
627 const seen = merge(current, infos, t)
628 if (JSON.stringify(seen) !== JSON.stringify(current)) {
629 await update($, bots, list => merge(list, infos, t))
630 }
631 await tick($, t)
632 await tellEnds($).catch(() => {})
633 return seen.some(b => !isEnded(b.status))
634}
635
636// Un solo reloj por carga del módulo; se apaga solo cuando no queda nadie activo.
637function startTicker($: EngineInterface) {
638 if (ticker) return
639 ticker = $.clock.every(1000, () => {
640 sync($)
641 .then(async active => {
642 const doing = (await read($, tasks)).some(x => x.status === 'in_progress')
643 if (!active && !doing && ticker) {
644 ticker.cancel()
645 ticker = undefined
646 }
647 })
648 .catch(() => {})
649 })
650}
651
652// Respaldo: al acabar un turno el motor puede entregar la lista de lo que sigue en marcha,
653// y lo que falta en ella ya terminó. No siempre la trae; la señal principal es el aviso.
654async function settleShells($: EngineInterface, inFlight: readonly { id: string }[] | undefined) {
655 if (!Array.isArray(inFlight)) return
656 const alive = new Set(inFlight.map(task => task.id))
657 const t = await $.clock.now()
658 await update($, bots, list =>
659 list.map(b =>
660 b.kind === 'shell' && !isEnded(b.status) && b.taskId && !alive.has(b.taskId)
661 ? { ...b, status: 'completed', endedAt: t }
662 : b,
663 ),
664 )
665 await tellEnds($).catch(() => {})
666}
667
668// Cuando un comando en segundo plano termina, la sesión recibe un aviso de tarea
669// (<task-notification>) con su id, la llamada que lo lanzó y cómo acabó.
670function tag(text: string, name: string): string | undefined {
671 const m = new RegExp(`<${name}>([^<]*)</${name}>`).exec(text)
672 return m?.[1]?.trim() || undefined
673}
674
675async function finishFromNotice($: EngineInterface, text: string) {
676 const taskId = tag(text, 'task-id')
677 const toolUseId = tag(text, 'tool-use-id')
678 const status = tag(text, 'status')
679 if (!taskId && !toolUseId) return
680 const ended = status === 'failed' || status === 'killed' ? status : 'completed'
681 const t = await $.clock.now()
682 await update($, bots, list =>
683 list.map(b =>
684 b.kind === 'shell' && !isEnded(b.status) &&
685 ((taskId && b.taskId === taskId) || (toolUseId && b.toolUseId === toolUseId))
686 ? { ...b, status: ended, endedAt: t }
687 : b,
688 ),
689 )
690 await tellEnds($).catch(() => {})
691}
692
693// Lo cambiado respecto a HEAD: «git diff --numstat» da las líneas exactas, no una cuenta de ediciones.
694// Fuera de un repositorio (o sin git) la sección no se dibuja.
695async function readChanges($: EngineInterface): Promise<Changes | null> {
696 const cwd = await $.session.cwd()
697 const diff = await $.process.run(['git', '-C', cwd, 'diff', '--numstat', 'HEAD'], { timeoutMs: 8000 })
698 if (diff.exitCode !== 0) return null
699 const files: Change[] = []
700 for (const line of diff.stdout.split('\n')) {
701 const [a, d, ...rest] = line.split('\t')
702 const path = rest.join('\t')
703 if (!path) continue
704 files.push({ path, add: Number(a) || 0, del: Number(d) || 0 })
705 }
706 files.sort((x, y) => y.add + y.del - (x.add + x.del))
707 const extra = await $.process.run(['git', '-C', cwd, 'ls-files', '--others', '--exclude-standard'], { timeoutMs: 8000 })
708 const untracked = extra.exitCode === 0 ? extra.stdout.split('\n').filter(Boolean).length : 0
709 return {
710 files,
711 add: files.reduce((n, f) => n + f.add, 0),
712 del: files.reduce((n, f) => n + f.del, 0),
713 untracked,
714 }
715}
716
717let changesTimer: Timer | undefined
718// El turno del hilo principal que está corriendo, para poder detenerlo desde el panel.
719let currentTurn: string | undefined
720// Tras una edición se relee git una sola vez cada pocos segundos, aunque lleguen muchas seguidas.
721function refreshChanges($: EngineInterface, wait = 1500) {
722 if (changesTimer) return
723 changesTimer = $.clock.after(wait, () => {
724 changesTimer = undefined
725 void readChanges($)
726 .then(c => update($, changes, () => c))
727 .catch(() => {})
728 })
729}
730
731const EDITS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit'])
732
733// Cada atom se nombra a mano: el escáner de estado necesita ver la clave literal en cada escritura.
734async function loadFolds($: EngineInterface) {
735 const get = async (key: FoldKey) => {
736 const v = await $.store.get(key)
737 return typeof v === 'boolean' ? v : undefined
738 }
739 const b = await get('plegarPresupuesto')
740 if (b !== undefined) await update($, foldBudget, () => b)
741 const a = await get('plegarAgentes')
742 if (a !== undefined) await update($, foldAgents, () => a)
743 const t = await get('plegarTareas')
744 if (t !== undefined) await update($, foldTasks, () => t)
745 const c = await get('plegarCambios')
746 if (c !== undefined) await update($, foldChanges, () => c)
747}
748
749function toggleFold($: EngineInterface, key: FoldKey) {
750 const save = (v: boolean) => $.store.set(key, v)
751 const run = async () => {
752 if (key === 'plegarPresupuesto') {
753 await update($, foldBudget, v => !v)
754 await save(await read($, foldBudget))
755 } else if (key === 'plegarAgentes') {
756 await update($, foldAgents, v => !v)
757 await save(await read($, foldAgents))
758 } else if (key === 'plegarTareas') {
759 await update($, foldTasks, v => !v)
760 await save(await read($, foldTasks))
761 } else {
762 await update($, foldChanges, v => !v)
763 await save(await read($, foldChanges))
764 }
765 }
766 void run().catch(() => {})
767}
768
769async function readContext($: EngineInterface, c: Ctx) {
770 await update($, context, () => ({ tokens: c.tokens, window: c.window, percent: c.percent }))
771}
772
773// En la app de escritorio la sesión es de SDK: ahí el motor aún no deja a un mod compactar ni
774// limpiar. Entonces se deja el comando escrito en la caja del prompt y basta con pulsar Enter.
775async function viaPrompt($: EngineInterface, command: string): Promise<boolean> {
776 const box = await $.prompt.read().catch(() => ({ text: '', cursor: 0 }))
777 if (box.text.trim()) {
778 toast($, `Tu caja del prompt tiene texto: borra o envía antes de usar ${command}`)
779 return false
780 }
781 const r = await $.prompt.fill({ text: command }).catch(() => ({ isFilled: false }))
782 toast($, r.isFilled ? `${command} listo en la caja del prompt: pulsa Enter` : `Escribe ${command} en la caja del prompt`)
783 return r.isFilled
784}
785
786export const register: Register = on => {
787 on('session.start', async ($, e, next) => {
788 ticker = undefined
789 quotaClock = undefined
790 beat = undefined
791 bornAt = await $.clock.now()
792 lastEvent = 0
793 // Una copia que arranca borra los latidos viejos: tras una recarga, la copia anterior ya no está.
794 await update($, copies, () => []).catch(() => {})
795 startBeat($)
796 await quietEnded($).catch(() => {})
797 // La cuota se lee al arrancar; después llega sola con cada medición.
798 await $.session.usage()
799 .then(async u => {
800 await readLimits($, u.rateLimits)
801 await readContext($, u.context)
802 })
803 .catch(() => {})
804 await loadFolds($).catch(() => {})
805 await $.session.model().then(m => update($, mainModel, () => m)).catch(() => {})
806 changesTimer = undefined
807 currentTurn = undefined
808 refreshChanges($, 0)
809 await $.command.register({
810 name: 'bots',
811 description: 'Abre el panel de agentes y tareas',
812 })
813 await $.command.register({
814 name: 'tareas',
815 description: 'Abre el panel de agentes y tareas',
816 })
817 await $.tool.register(OWN_SPEC).catch(() => {})
818 await replay($).catch(() => {})
819 // Recoge también los agentes que ya corrían cuando el mod se cargó.
820 void sync($)
821 .then(active => {
822 if (active) startTicker($)
823 })
824 .catch(() => {})
825
826 return next(e)
827 })
828
829 on('command.run', { command: 'bots' }, async $ => {
830 await $.ui.open({ id: PANE, title: TITLE })
831 await sync($)
832 refreshChanges($, 0)
833
834 return { text: 'Panel de agentes y tareas abierto.' }
835 })
836
837 on('command.run', { command: 'tareas' }, async $ => {
838 await $.ui.open({ id: PANE, title: TITLE })
839 await sync($)
840 refreshChanges($, 0)
841
842 return { text: 'Panel de agentes y tareas abierto.' }
843 })
844
845 // Solo observa: el panel nunca debe impedir ni duplicar un lanzamiento, así que
846 // lo suyo va en try y, si aun así algo falla, el .catch deja pasar el original.
847 on('agent.spawn', async ($, e, next) => {
848 const key = `${e.tool_use_id}:${++seq}`
849 const model = e.fork ? e.parentModel : (e.model ?? e.parentModel)
850 try {
851 const bot: Bot = {
852 key,
853 description: e.description || e.subagentType,
854 type: e.subagentType,
855 model,
856 status: 'pending',
857 startedAt: await $.clock.now(),
858 background: e.background,
859 action: '💭 Pensando…',
860 calls: 0,
861 }
862 bot.lastSeen = bot.startedAt
863 await update($, bots, list => trim([...list, bot]))
864 void $.ui.open({ id: PANE, title: TITLE }).catch(() => {})
865 startTicker($)
866 } catch {}
867
868 const set = (patch: Partial<Bot>) =>
869 update($, bots, list => list.map(b => (b.key === key ? { ...b, ...patch } : b))).catch(() => {})
870 let ran
871 try {
872 ran = await next(e)
873 } catch (err) {
874 await set({ status: 'failed', action: '✗ No arrancó' })
875 throw err
876 }
877 if (ran.deny) await set({ status: 'failed', action: `✗ ${clip(ran.deny, 40)}` })
878 else await set({ id: ran.agentId, model: ran.model || model, status: 'running' })
879
880 return ran
881 }).catch(($, e, next) => next(e))
882
883 on('tool.call', async ($, e, next) => {
884 void $.clock.now().then(t => (lastEvent = t)).catch(() => {})
885 // Los parámetros de la herramienta vienen en el propio evento.
886 const input = e as unknown as Record<string, unknown>
887 const agentId = e.agentId
888
889 // La herramienta propia la atiende el mod mismo: actualiza la lista y le contesta al modelo.
890 if (e.tool === OWN_TOOL) {
891 if (agentId) return { result: 'La lista de tareas la mantiene la sesión principal.' }
892 if (!Array.isArray(input.items) && !input.advance && !Array.isArray(input.done) && typeof input.start !== 'number') {
893 return { result: 'Indica «items» (lista completa), «advance», «done» o «start».' }
894 }
895 await track($, e.tool, input, undefined)
896 const list = await read($, tasks)
897 const doing = list.find(x => x.status === 'in_progress')
898 const done = list.filter(x => x.status === 'completed').length
899 return { result: `Lista actualizada: ${done}/${list.length} hechas${doing ? `; en curso: ${doing.content}` : ''}.` }
900 }
901
902 if (agentId) {
903 const text = action(e.tool, input)
904 const seen = await $.clock.now()
905 void update($, bots, list =>
906 list.map(b =>
907 b.id === agentId
908 ? {
909 ...b,
910 action: text,
911 calls: b.calls + 1,
912 lastSeen: seen,
913 status: isEnded(b.status) ? b.status : 'running',
914 log: [...(b.log ?? []), { at: seen, text }].slice(-LOG_KEEP),
915 }
916 : b,
917 ),
918 ).catch(() => {})
919 }
920
921 // Lo último que hizo el hilo principal, para la línea de estado de arriba.
922 if (!agentId && !step(e.tool, input, undefined, 0) && e.tool !== 'Agent') {
923 void update($, mainAction, () => action(e.tool, input)).catch(() => {})
924 }
925
926 const ran = await next(e)
927
928 if (EDITS.has(e.tool)) refreshChanges($)
929
930 // El texto final de un agente de primer plano llega al cerrarse su llamada: se guarda para copiarlo.
931 if (e.tool === 'Agent' && !agentId) {
932 const text = (ran as { text?: unknown }).text
933 if (typeof text === 'string' && text.trim()) {
934 const prefix = `${e.tool_use_id}:`
935 void update($, bots, list =>
936 list.map(b => (b.key.startsWith(prefix) ? { ...b, result: text.slice(0, 20000) } : b)),
937 ).catch(() => {})
938 }
939 }
940
941 // Un comando que quedó en segundo plano (pedido así o con Ctrl+B) recibe su propio robot.
942 if (e.tool === 'Bash' || e.tool === 'PowerShell') {
943 const result = ran.result as { backgroundTaskId?: unknown } | null | undefined
944 const taskId = result && typeof result.backgroundTaskId === 'string' ? result.backgroundTaskId : undefined
945 if (taskId) {
946 try {
947 const shell: Bot = {
948 key: `shell:${taskId}`,
949 kind: 'shell',
950 taskId,
951 toolUseId: e.tool_use_id,
952 description: clip(input.description, 60) || clip(input.command, 60) || e.tool,
953 type: e.tool,
954 model: '',
955 status: 'running',
956 startedAt: await $.clock.now(),
957 action: `⚙️ ${clip(input.command)}`,
958 calls: 0,
959 }
960 shell.lastSeen = shell.startedAt
961 await update($, bots, list => trim([...list.filter(b => b.key !== shell.key), shell]))
962 void $.ui.open({ id: PANE, title: TITLE }).catch(() => {})
963 startTicker($)
964 } catch {}
965 }
966 }
967
968 // La lista de tareas es la de la sesión: las llamadas de un subagente son de su propia lista.
969 if (!agentId) {
970 try {
971 await track($, e.tool, input, ran.result)
972 } catch {}
973 }
974
975 return ran
976 }).catch(($, e, next) => next(e))
977
978 // Cada petición del hilo principal (los subagentes tienen su propio prefijo): qué hizo la caché con ella.
979 on('turn.step', async function* ($, e, next) {
980 if (e.agentId) return yield* next(e)
981 currentTurn = e.turnId
982 void update($, busy, () => true).catch(() => {})
983 if (e.model) void update($, mainModel, () => e.model).catch(() => {})
984 const inicio = await $.clock.now()
985 const r = yield* next(e)
986 try {
987 if (r.usage) {
988 const nueva: Muestra = {
989 modelo: r.usage.model || e.model,
990 inicio,
991 leido: r.usage.cache_read_input_tokens,
992 escrito: r.usage.cache_creation_input_tokens,
993 nuevo: r.usage.input_tokens,
994 }
995 const lista = [...(await read($, samples)), nueva].slice(-2)
996 await update($, samples, () => lista)
997 const plan = (await read($, limits)).map(l => ({ kind: l.kind, percentUsed: l.percentUsed }))
998 const env = {
999 force5m: await $.env.get('FORCE_PROMPT_CACHING_5M').catch(() => undefined),
1000 ttlVar: await $.env.get('CLAUDE_CODE_PROMPT_CACHE_TTL').catch(() => undefined),
1001 enable1h: await $.env.get('ENABLE_PROMPT_CACHING_1H').catch(() => undefined),
1002 }
1003 const observado = observarTtl(lista[0] === nueva ? undefined : lista[0], nueva, undefined)
1004 await update($, cacheTtl, () => observado ?? decidirTtl(env, plan).ttl)
1005 await tick($, inicio)
1006 }
1007 } catch {}
1008 return r
1009 })
1010
1011 on('session.measure', async ($, e, next) => {
1012 if (e.changed.includes('rateLimits')) await readLimits($, e.rateLimits).catch(() => {})
1013 if (e.changed.includes('context')) await readContext($, e.context).catch(() => {})
1014 return next(e)
1015 }).catch(($, e, next) => next(e))
1016
1017 on('prompt.compose', async ($, e, next) => {
1018 const ran = await next(e)
1019 if (e.tools.some(HOST_LISTS)) return ran
1020 return { sections: [...ran.sections, { id: 'agent-bots:tareas', text: OWN_PROMPT, scope: 'session' as const }] }
1021 }).catch(($, e, next) => next(e))
1022
1023 on('prompt.submit', async ($, e, next) => {
1024 if (e.origin.kind === 'task-notification') await finishFromNotice($, e.text).catch(() => {})
1025 return next(e)
1026 }).catch(($, e, next) => next(e))
1027
1028 on('classic.Stop', async ($, e, next) => {
1029 currentTurn = undefined
1030 await update($, busy, () => false).catch(() => {})
1031 await update($, mainAction, () => '').catch(() => {})
1032 await settleShells($, e.background_tasks).catch(() => {})
1033 return next(e)
1034 }).catch(($, e, next) => next(e))
1035
1036 on('classic.SubagentStop', async ($, e, next) => {
1037 await settleShells($, e.background_tasks).catch(() => {})
1038 return next(e)
1039 }).catch(($, e, next) => next(e))
1040
1041 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
1042 const els = $.ui.resolve(e)
1043 const { Box, Text, Button } = els
1044 const Svg = 'Svg' in els ? els.Svg : undefined
1045 // Línea divisoria entre secciones: caracteres de caja tenues al ancho del panel, que se ve
1046 // igual en la app y en la terminal (no hay borde de un solo lado en los elementos).
1047 const rule = (key: string) => (
1048 <Text key={key} dimColor wrap="truncate-end">
1049 {'─'.repeat(Math.max(8, e.props.bodyColumns || 40))}
1050 </Text>
1051 )
1052 const list = await read($, bots)
1053 const t = (await read($, now)) || (await $.clock.now())
1054 const clock = await $.clock.now()
1055
1056 const order: Record<BotMood, number> = { run: 0, sleep: 1, fail: 2, done: 3 }
1057 const sorted = [...list].sort(
1058 (a, b) => order[mood(a.status)] - order[mood(b.status)] || b.startedAt - a.startedAt,
1059 )
1060 const count = (m: BotMood) => list.filter(b => mood(b.status) === m).length
1061 const live = sorted.filter(b => !isEnded(b.status))
1062 const finished = sorted.filter(b => isEnded(b.status))
1063
1064 const todo = await read($, tasks)
1065 const hiding = await read($, hideDone)
1066 const done = todo.filter(x => x.status === 'completed').length
1067 const doing = todo.filter(x => x.status === 'in_progress')
1068 const left = todo.length - done - doing.length
1069 const tmood: BotMood = doing.length ? 'run' : todo.length && done === todo.length ? 'done' : 'sleep'
1070 const since = todo.reduce((min, x) => (x.startedAt !== undefined && x.startedAt < min ? x.startedAt : min), Infinity)
1071 const pct = todo.length ? Math.round((done / todo.length) * 100) : 0
1072
1073 const quota = await read($, limits)
1074 const ctx = await read($, context)
1075 const ctxPct = ctx?.percent
1076 const recent = await read($, samples)
1077 const last = recent[recent.length - 1]
1078 const ttl = await read($, cacheTtl)
1079 const leftMs = last ? restanteMs(last, ttl, clock) : 0
1080
1081 const silentFor = (b: Bot) => t - (b.lastSeen ?? b.startedAt)
1082 const isStalled = (b: Bot) =>
1083 mood(b.status) === 'run' && silentFor(b) > (b.kind === 'shell' ? STALL_SHELL_MS : STALL_AGENT_MS)
1084 const stalled = list.filter(isStalled).length
1085 const twice = await read($, duplicated)
1086 const foldB = await read($, foldBudget)
1087 const foldA = await read($, foldAgents)
1088 const foldT = await read($, foldTasks)
1089 const foldC = await read($, foldChanges)
1090 const showE = await read($, showEnded)
1091 const showAll = await read($, allPending)
1092 const openKey = await read($, opened)
1093 const asking = await read($, confirming)
1094 const isBusy = await read($, busy)
1095 const model = await read($, mainModel)
1096 const doingNow = await read($, mainAction)
1097 const ch = await read($, changes)
1098 const dv = await read($, diffView)
1099
1100 const pendingCount = todo.filter(x => x.status === 'pending').length
1101 let pendingShown = 0
1102 const visibleTasks = todo.filter(x => {
1103 if (x.status === 'completed') return !hiding
1104 if (x.status === 'in_progress') return true
1105 pendingShown += 1
1106 return showAll || pendingShown <= PENDING_PREVIEW
1107 })
1108 const hiddenPending = showAll ? 0 : Math.max(0, pendingCount - PENDING_PREVIEW)
1109
1110 const ask = (key: string | null) => {
1111 void update($, confirming, () => key).catch(() => {})
1112 }
1113 const no = <Button key="confirm-no" label="No" onPress={() => ask(null)} />
1114 const chip = (text: string, ramp: Ramp) => (
1115 <Text backgroundColor={ramp[0]} color={ramp[2]}>{` ${text} `}</Text>
1116 )
1117
1118 // Estado de arriba: lo que está haciendo ahora y, si hace falta, cómo pararlo.
1119 const cur = doing[0]
1120 const stepNo = cur ? todo.indexOf(cur) + 1 : 0
1121 const headline = cur
1122 ? cur.content
1123 : isBusy ? 'Trabajando'
1124 : live.length ? `${live.length} en segundo plano`
1125 : 'En espera'
1126 const detail = [
1127 stepNo ? `Paso ${stepNo} de ${todo.length}` : '',
1128 cur?.startedAt !== undefined ? elapsed(t - cur.startedAt) : '',
1129 isBusy ? doingNow : '',
1130 ].filter(Boolean).join(' · ')
1131
1132 // Presupuesto: 5 h, semana y contexto como barras finas en tres columnas.
1133 const cols: { key: string; label: string; pct: number; color: string; sub: string; alt: string }[] = []
1134 for (const { kind, label, ramp } of QUOTA) {
1135 const l = quota.find(x => x.kind === kind)
1136 if (!l) continue
1137 const reset = resetIn(l.resetsAt, clock)
1138 cols.push({ key: kind, label, pct: l.percentUsed, color: ramp[1], sub: reset ? `↻ ${reset}` : '', alt: `Cuota ${label}` })
1139 }
1140 if (ctx && ctxPct !== undefined) {
1141 cols.push({
1142 key: 'context',
1143 label: 'Contexto',
1144 pct: ctxPct,
1145 color: '#378ADD',
1146 sub: ctx.tokens !== undefined ? `${tokens(ctx.tokens)} / ${tokens(ctx.window)}` : '',
1147 alt: 'Contexto',
1148 })
1149 }
1150 const ctxHigh = ctxPct !== undefined && ctxPct >= CTX_WARN
1151 const cacheLine = !last
1152 ? ''
1153 : last.leido + last.escrito === 0
1154 ? 'Caché sin usar'
1155 : leftMs > 0
1156 ? `Caché caliente · vence en ${leftMs < 60000 ? '<1 min' : `${Math.ceil(leftMs / 60000)} min`} · ${tokens(last.leido)} leído`
1157 : `Caché vencida · ${tokens(last.leido)} por reescribir`
1158
1159 const head = (fold: FoldKey, key: string, folded: boolean, title: string, extra?: unknown, right?: unknown) => (
1160 <Box key={`h:${key}`} flexDirection="row" justifyContent="space-between" alignItems="center" gap={1}>
1161 <Box flexDirection="row" alignItems="center" gap={1} flexShrink={1}>
1162 <Button key={key} plain label={`${folded ? '▸' : '▾'} ${title}`} onPress={() => toggleFold($, fold)} />
1163 {extra as never}
1164 </Box>
1165 {right as never}
1166 </Box>
1167 )
1168
1169 const row = (b: Bot) => {
1170 const hung = isStalled(b)
1171 const m = hung ? 'sleep' : mood(b.status)
1172 const [label, color] = hung ? ['¿Colgado?', WARN[1]] : LABEL[m]
1173 const shell = b.kind === 'shell'
1174 const c = modelChip(b)
1175 const isOpen = openKey === b.key
1176 const target = shell ? b.taskId : b.background ? (b.id ?? b.description) : undefined
1177 const canStop = !isEnded(b.status) && !!target
1178 return (
1179 <Box key={b.key} flexDirection="column">
1180 <Box flexDirection="row" gap={1} alignItems="center">
1181 {Svg ? (
1182 <Svg source={robot(m, b.model, b.kind)} alt={`Robot ${label.toLowerCase()}`} width={36} height={36} isInteractive />
1183 ) : (
1184 <Text>{shell && m === 'run' ? '⚙️' : GLYPH[m]}</Text>
1185 )}
1186 <Box flexDirection="column" flexGrow={1} flexShrink={1}>
1187 <Box flexDirection="row" justifyContent="space-between" gap={1}>
1188 <Text bold wrap="truncate-end">{b.description}</Text>
1189 <Box flexDirection="row" gap={1}>
1190 <Button
1191 key={`open:${b.key}`}
1192 plain
1193 label={isOpen ? '▾' : '▸'}
1194 onPress={() => {
1195 void update($, opened, k => (k === b.key ? null : b.key)).catch(() => {})
1196 }}
1197 />
1198 <Button
1199 key={`x:${b.key}`}
1200 plainhooks/cache.ts 111 lines1// Lógica pura de la caché de prompts (sin `$`). Ideas tomadas de
2// davila7/claude-code-templates · observability/prompt-cache-control (MIT,
3// commit 8da17d67), reescritas y simplificadas para el medidor:
4// - la caché vive 5 min por defecto y 1 h si se pide; cada lectura la renueva
5// gratis y la vida se cuenta desde el INICIO de la petición
6// - prompt = input_tokens (sin caché) + cache_read + cache_creation
7// - escribir cuesta 1,25× (5 min) o 2× (1 h) la entrada; leer ≈ 0,1×: lo caro es
8// que venza con un contexto grande
9// - un cambio del prefijo (modelo, esfuerzo, herramientas, system prompt,
10// CLAUDE.md) hace que la siguiente petición escriba en vez de leer
11import type { Muestra, Ttl } from '../types'
12
13export type Consejo = {
14 tipo: 'fria' | 'sin-cache' | 'caliente' | 'pronto' | 'vencida' | 'fallo'
15 texto: string
16}
17
18const HOLGURA_MS = 10_000
19
20export const ttlMs = (ttl: Ttl) => (ttl === '1h' ? 3_600_000 : 300_000)
21export const tokensPrompt = (m: Muestra) => m.leido + m.escrito + m.nuevo
22export const aciertos = (m: Muestra) => (tokensPrompt(m) === 0 ? 0 : m.leido / tokensPrompt(m))
23
24export function restanteMs(m: Muestra, ttl: Ttl, ahora: number): number {
25 if (m.leido + m.escrito === 0) return 0
26 return Math.max(0, m.inicio + ttlMs(ttl) - ahora)
27}
28
29/** Duración que pide Claude Code según el entorno y la cuenta (orden de su documentación). */
30export function decidirTtl(
31 env: { force5m?: string; ttlVar?: string; enable1h?: string },
32 limites: { kind: string; percentUsed: number }[],
33): { ttl: Ttl; fuente: string } {
34 const si = (v?: string) => v === '1' || v?.toLowerCase() === 'true'
35 if (si(env.force5m)) return { ttl: '5m', fuente: 'FORCE_PROMPT_CACHING_5M' }
36 if (env.ttlVar === '5m' || env.ttlVar === '1h') return { ttl: env.ttlVar, fuente: 'CLAUDE_CODE_PROMPT_CACHE_TTL' }
37 if (si(env.enable1h)) return { ttl: '1h', fuente: 'ENABLE_PROMPT_CACHING_1H' }
38 const plan = limites.filter(l => l.kind === 'five_hour' || l.kind === 'seven_day')
39 if (plan.length === 0) return { ttl: '5m', fuente: 'sin suscripción visible' }
40 if (plan.some(l => l.percentUsed >= 100)) return { ttl: '5m', fuente: 'créditos de uso' }
41 return { ttl: '1h', fuente: 'suscripción' }
42}
43
44/**
45 * Lo que el tráfico dice de la duración: un acierto más de 5 min después de la
46 * petición anterior prueba 1 h; un fallo entre 5 y 60 min con el mismo modelo y
47 * un prompt que no encogió apunta a 5 min (más débil: un prefijo cambiado se ve igual).
48 */
49export function observarTtl(prev: Muestra | undefined, cur: Muestra, conocido: Ttl | undefined): Ttl | undefined {
50 if (!prev || prev.leido + prev.escrito === 0 || cur.modelo !== prev.modelo) return conocido
51 const hueco = cur.inicio - prev.inicio
52 const antes = tokensPrompt(prev)
53 if (hueco <= ttlMs('5m') + HOLGURA_MS) return conocido
54 if (cur.leido >= antes * 0.5) return '1h'
55 if (conocido === '1h') return conocido
56 const vencio = cur.escrito > 0 && tokensPrompt(cur) >= antes * 0.7 && hueco < ttlMs('1h') + HOLGURA_MS
57 return vencio ? '5m' : conocido
58}
59
60/** Por qué una petición que debía leer la caché la escribió; undefined si no falló. */
61export function causaFallo(prev: Muestra | undefined, cur: Muestra, ttl: Ttl): string | undefined {
62 if (!prev) return undefined
63 const antes = tokensPrompt(prev)
64 // Un prompt que encogió es /compact o /clear, no un fallo.
65 if (antes === 0 || tokensPrompt(cur) < antes * 0.7) return undefined
66 if (cur.leido >= antes * 0.5 || cur.escrito === 0) return undefined
67 if (cur.modelo !== prev.modelo) return 'cambió el modelo'
68 if (cur.inicio - prev.inicio > ttlMs(ttl)) return `había vencido (${ttl === '1h' ? '1 h' : '5 min'})`
69 return 'cambió el prefijo (esfuerzo, herramientas, system prompt o CLAUDE.md)'
70}
71
72export function aconsejar(
73 ultima: Muestra | undefined,
74 previa: Muestra | undefined,
75 ttl: Ttl,
76 ahora: number,
77 avisoMs: number,
78 compactarDesde: number,
79): Consejo {
80 if (!ultima) return { tipo: 'fria', texto: 'sin peticiones aún: la primera escribe la caché' }
81 if (ultima.leido + ultima.escrito === 0) return { tipo: 'sin-cache', texto: 'esta petición no usó caché' }
82 const resta = restanteMs(ultima, ttl, ahora)
83 const tam = tokensPrompt(ultima)
84 if (resta <= 0) {
85 return tam >= compactarDesde
86 ? { tipo: 'vencida', texto: `vencida: el próximo mensaje reescribe ${tokens(tam)}; /compact antes, o /clear si terminaste` }
87 : { tipo: 'vencida', texto: `vencida: solo ${tokens(tam)} por reconstruir, sigue` }
88 }
89 if (resta <= avisoMs) return { tipo: 'pronto', texto: 'vence pronto: cualquier mensaje la renueva gratis' }
90 const fallo = causaFallo(previa, ultima, ttl)
91 if (fallo) return { tipo: 'fallo', texto: `falló: ${fallo}` }
92 return { tipo: 'caliente', texto: 'caliente: sigue' }
93}
94
95export function tokens(n: number): string {
96 if (n < 1000) return String(n)
97 if (n < 100_000) return `${(n / 1000).toFixed(1).replace(/\.0$/, '')}k`
98 if (n < 1_000_000) return `${Math.round(n / 1000)}k`
99 return `${(n / 1_000_000).toFixed(1).replace(/\.0$/, '')}M`
100}
101
102/** m:ss, o h:mm:ss desde una hora. */
103export function reloj(ms: number): string {
104 const t = Math.max(0, Math.ceil(ms / 1000))
105 const h = Math.floor(t / 3600)
106 const m = Math.floor((t % 3600) / 60)
107 const s = t % 60
108 const dos = (n: number) => String(n).padStart(2, '0')
109 return h > 0 ? `${h}:${dos(m)}:${dos(s)}` : `${m}:${dos(s)}`
110}
111types/index.d.ts 107 lines1export type BotMood = 'run' | 'sleep' | 'done' | 'fail'
2
3export type BotKind = 'agent' | 'shell'
4
5export type Bot = {
6 key: string
7 kind?: BotKind
8 taskId?: string
9 toolUseId?: string
10 id?: string
11 description: string
12 type: string
13 model: string
14 status: string
15 startedAt: number
16 endedAt?: number
17 action: string
18 calls: number
19 // Lanzado en segundo plano: al terminar avisa con una notificación.
20 background?: boolean
21 // Última señal de vida (lanzamiento o herramienta usada), para detectar los colgados.
22 lastSeen?: number
23 // Ya se avisó de su fin.
24 told?: boolean
25 // Últimas acciones, para desplegar su historial: «at» en ms desde la época.
26 log?: { at: number; text: string }[]
27 // Texto final que devolvió (solo los de primer plano, al cerrar su llamada).
28 result?: string
29}
30
31// Contexto del hilo principal, como lo mide el motor.
32export type Ctx = { tokens?: number; window: number; percent?: number }
33
34// Un archivo cambiado respecto a HEAD, según git.
35export type Change = { path: string; add: number; del: number }
36export type Changes = { files: Change[]; add: number; del: number; untracked: number }
37
38// Las primeras líneas del diff de un archivo, para verlo sin salir del panel.
39export type Diff = { path: string; lines: string[] }
40
41// Una copia cargada del mod y su último latido.
42// ev: cuándo procesó su último evento de la sesión (0 si ninguno desde que arrancó).
43export type Copy = { id: string; at: number; ev?: number }
44
45export type TaskStatus = 'pending' | 'in_progress' | 'completed'
46
47export type Task = {
48 key: string
49 // Id que el motor le dio con TaskCreate; las tareas de un plan no lo tienen.
50 ref?: string
51 content: string
52 status: TaskStatus
53 startedAt?: number
54 endedAt?: number
55}
56
57// Una ventana de cuota de la cuenta (5 h o semana) con la lectura anterior, para animar el cambio.
58export type Limit = {
59 kind: string
60 percentUsed: number
61 prevPercent: number
62 resetsAt?: string
63}
64
65export type Ttl = '5m' | '1h'
66
67// Una petición del hilo principal, como la reportó la API: de ella sale el estado de la caché de prompts.
68export type Muestra = {
69 modelo: string
70 // ms desde la época al empezar la petición: la vida de la caché cuenta desde aquí
71 inicio: number
72 leido: number
73 escrito: number
74 nuevo: number
75}
76
77declare module 'claude-code' {
78 interface PluginState {
79 'agent-bots': {
80 bots: Bot[]
81 tasks: Task[]
82 limits: Limit[]
83 replayed: boolean
84 now: number
85 muestras: Muestra[]
86 ttl: Ttl
87 copias: Copy[]
88 duplicado: boolean
89 ocultarHechas: boolean
90 plegarAgentes: boolean
91 plegarTareas: boolean
92 verPendientes: boolean
93 plegarPresupuesto: boolean
94 plegarCambios: boolean
95 verListos: boolean
96 contexto: Ctx | null
97 cambios: Changes | null
98 diff: Diff | null
99 abierto: string | null
100 confirmar: string | null
101 ocupado: boolean
102 modelo: string
103 accion: string
104 }
105 }
106}
107