Agencia: the local multi-agent control room behind this site
Four runtimes converge on a local dispatch core (18 ms), stream to the UI over SSE, and loop back over direct sockets with no model in the middle. Painted on Canvas 2D with layered washes and drying bristles.
Every big project on this site — 13,770 functions of Need for Speed Underground, 15,702 functions of Max Payne, and a ~3039 Elo chess engine written in 36 hours — was built on one Mac mini M4. Not by chatting with a single coding assistant, but by running 15 to 30 specialized agents in parallel across four different runtimes. Agencia is the local harness and control room I built so one person can direct that fleet without losing track of what is true.
Compiled directly from the React 19 + xyflow frontend in static Demo Mode (zero backend, OpSec-sanitized with NFSU, Max Payne, and CaliChess running inside).
ps/lsof to RAM1. Why I built it: the chaos of parallel agents
When you run one coding agent in a terminal, you read its output and press enter. When you run Claude Code orchestrators, Codex workers, cheap OpenCode interns, and Antigravity sessions at the same time across three repositories, four things break immediately:
- Terminal blindness: you have 15 windows open and no idea which one is blocked waiting for a yes/no decision, which one crashed, and which one finished 20 minutes ago.
- Quota burn: different providers reset on 5-hour and weekly rolling windows; one runaway loop can empty an account while you are looking at another tab.
- Self-grading illusions: agents love to report "all tests pass" after editing half the file or timing the wrong benchmark.
- Slow handoffs: copy-pasting context between terminals or spawning wrapper models just to deliver a short instruction wastes seconds and tokens.
Agencia solves this without wrapping or proxying any model. Every runtime keeps running natively on macOS. Agencia simply observes the real artifacts each runtime already writes to disk or holds open in the kernel, merges them into a single JSON state every second, and streams it over SSE to a keyboard-first workbench (I/V/G/T/S/R, ⌘K).
| Runtime | Discovery | Live signal | Direct relay |
|---|---|---|---|
| Claude Code | Session registry + process table | Incremental .jsonl tail + subagent files | cartero.py → Unix socket (uds:) |
| Codex | Daily rollout .jsonl + job files | JSON event stream + 5 h quota from rollouts | jobs.py + app-server JSON-RPC archive |
| OpenCode | Local HTTP API + lsof cwd | Tool-use JSON stream, hard deadline & step cap | jobs.py + session interrupt API |
| Antigravity CLI | presence/*.lock + local SQLite | Transcript events + subagent lineage | agylink.py → agentapi send-message |
2. Dispatching work at scale: flat JSON, APFS slices, and spend guards
Orchestrators delegate work through tiny CLI verbs: cdx launches an isolated Codex worker, bec launches a cheap OpenCode/DeepSeek Flash intern with a hard wall-clock deadline and step cap (default 300 steps), and slice creates an isolated git worktree under <repo>-wt/<name>.
There is no queue database, no message broker, and no tmux. Every job is one plain file in jobs/<id>.json. Concurrency slots are enforced atomically with fcntl.flock. Because macOS uses APFS, slice clones ignored build directories with copy-on-write (cp -cR), so parallel workers compile in isolation in milliseconds without duplicating gigabytes of build cache.
For multi-hour pushes, Agencia Real arms a timed sprint with per-account spend ceilings and automatic stops when a Codex 5-hour window hits 92%, scaling cheap interns up to 60 concurrent workers when needed.
3. Keeping order: live lines, blind auditing, and binary inspection
Watching twenty agents fails if cards either dump raw JSON or wait minutes for an LLM summary. Agencia splits the work: live_line() translates the last tool call deterministically in under a millisecond so cards are never stale, while two sleepy background Haiku narrators write a structured Did / Next recap only when the activity signature changes and a human is actually watching (AWAKE_S = 300 s).
Even more important is avance.py, the blind auditor. Agents grading their own work is how bugs slip through. Whenever a milestone or task settles, an independent Sonnet auditor opens the real evidence first — git show, cited files, logs, and headless screenshots — decides whether the work genuinely advances GOAL.md, and only then reads what the agent claimed. When I disagree with a verdict on the board, my vote and note are injected into the next audit prompt as the governing criterion.
Alongside the auditor, a background reconcile_loop dispatches four cheap reviewers every 7 minutes to catch loose ends across finished jobs, janitor_loop archives idle Codex threads, and Lupa (R) lets me inspect live Ghidra decompilations of the exact addresses reverse-engineering agents are touching.
4. The forensic reconciliation: 420 ms down to 18 ms
Once Agencia was running daily, I ran a forensic audit on the harness itself. The HTTP server answered in 0.7 ms from cache, yet the page felt sluggish and spun up the fan whenever left open. Profiling snapshot() exposed the tax: every second, under one global lock L, it spawned seven external ps and lsof subprocesses (212 ms) and re-parsed 1,228 finished job JSON files (55 ms). Worse, after any server restart, the browser closed SSE and stayed stuck in 3-second polling forever.
The fix (core-rapido) was surgical: procs.py runs one background ps every 2 s and caches lsof per PID; jobs.py caches parsed jobs by (mtime_ns, size); and the frontend reconnects SSE with exponential backoff (1 s to 15 s) while napping after 10 minutes idle.
Cada proyecto grande de este sitio — las 13,770 funciones de Need for Speed Underground, las 15,702 funciones de Max Payne y un motor de ajedrez de ~3039 Elo en 36 horas — salió de una sola Mac mini M4. No chateando con una sola ventana de IA, sino corriendo de 15 a 30 agentes especializados en paralelo sobre cuatro runtimes distintos. Agencia es el harness y cuarto de control local que construí para dirigir esa flota sin perder el control ni tragarme reportes falsos.
Compilada directo desde el frontend React 19 + xyflow en Modo Demo estático (cero backend, saneada por OpSec con NFSU, Max Payne y CaliChess corriendo adentro).
ps/lsof a RAM1. Por qué la construí: el caos de correr agentes en paralelo
Cuando corres un solo agente en terminal, lees lo que hace y le das enter. Cuando corres orquestadores de Claude Code, trabajadores en Codex, becarios baratos en OpenCode y sesiones de Antigravity al mismo tiempo en tres repositorios, se rompen cuatro cosas al instante:
- Ceguera de terminales: tienes 15 ventanas abiertas y no sabes cuál te está esperando una decisión, cuál tronó ni cuál terminó hace 20 minutos.
- Quema de cuota: cada proveedor resetea por ventanas de 5 horas y semanales; un bucle atascado puede vaciar una cuenta mientras miras otra pestaña.
- Auto-calificación mentirosa: a los agentes les encanta decir «todas las pruebas pasan» tras editar medio archivo o medir el benchmark equivocado.
- Mensajería lenta: copiar y pegar contexto entre terminales o levantar un modelo extra solo para mandar una instrucción corta quema segundos y tokens.
Agencia resuelve esto sin envolver ni interceptar a ningún modelo. Cada runtime sigue corriendo nativo en macOS. Agencia observa los artefactos reales que ya escriben en disco o mantienen abiertos en el kernel, los funde en una sola foto JSON cada segundo y la transmite por SSE a una interfaz pensada para teclado (I/V/G/T/S/R, ⌘K).
| Runtime | Descubrimiento | Señal en vivo | Relay directo |
|---|---|---|---|
| Claude Code | Registro de sesiones + tabla de procesos | Cola incremental de .jsonl + subagentes | cartero.py → socket Unix (uds:) |
| Codex | Rollouts .jsonl + archivos de trabajo | Flujo JSON de eventos + cuota de 5 h desde rollouts | jobs.py + archivo vía app-server JSON-RPC |
| OpenCode | API HTTP local + lsof de cwd | Flujo JSON de herramientas, plazo y tope de pasos | jobs.py + API de interrupción de sesión |
| Antigravity CLI | presence/*.lock + SQLite local | Eventos de transcript + linaje de subagentes | agylink.py → agentapi send-message |
2. Despacho a escala: JSON plano, slices APFS y topes de gasto
Los orquestadores delegan trabajo con verbos chicos de CLI: cdx lanza un trabajador aislado en Codex, bec lanza un becario barato en OpenCode/DeepSeek Flash con plazo duro de reloj y tope de pasos (300 por defecto), y slice abre un worktree git aislado en <repo>-wt/<nombre>.
No hay base de datos de colas, ni broker, ni tmux. Cada trabajo es un archivo plano en jobs/<id>.json. Los lugares concurrentes se garantizan con fcntl.flock. Como macOS usa APFS, slice clona las carpetas ignoradas de compilación con copy-on-write (cp -cR), así que los agentes compilan en paralelo en milisegundos sin duplicar gigabytes.
Para corridas largas, Agencia Real arma un sprint cronometrado con tope de gasto por cuenta y paro automático al 92 % de la ventana de 5 horas en Codex, subiendo el tope de becarios concurrentes hasta 60 cuando hace falta.
3. Mantener el orden: línea viva, auditor ciego y lupa binaria
Observar veinte agentes falla si las tarjetas escupen JSON crudo o esperan minutos por un resumen de modelo. Agencia parte el trabajo: live_line() traduce la última llamada a herramienta de forma determinista en menos de un milisegundo para que ninguna tarjeta vaya atrasada, mientras dos narradores Haiku dormilones redactan el recuento Hizo / Sigue solo cuando cambia la firma de actividad y hay alguien mirando (AWAKE_S = 300 s).
Todavía más importante es avance.py, el auditor ciego. Dejar que los agentes se califiquen solos es como se cuelan los bugs. Cuando una tarea o meta se asienta, un auditor independiente en Sonnet abre primero la evidencia real — git show, archivos citados, logs y capturas headless — decide si avanza literalmente el GOAL.md y solo después lee lo que afirmó el agente. Si voto que no coincido en el tablero, mi criterio entra directo al siguiente prompt de auditoría.
Junto al auditor, un reconcile_loop despacha cuatro revisores cada 7 minutos para atrapar cabos sueltos, janitor_loop archiva hilos quietos de Codex y Lupa (R) me deja ver la decompilación de Ghidra de las direcciones exactas que están tocando los agentes de ingeniería inversa.
4. La reconciliación forense: de 420 ms a 18 ms
Cuando Agencia ya corría todos los días, audité el propio harness. El servidor HTTP contestaba en 0.7 ms desde caché, pero la página se sentía pesada con la pestaña abierta. Perfilar snapshot() expuso el impuesto: cada segundo, bajo un solo candado global L, lanzaba siete subprocesos ps y lsof (212 ms) y releía 1,228 JSON de trabajos ya terminados (55 ms). Peor: tras cualquier reinicio del servidor, el navegador cerraba SSE y se quedaba atascado en sondeo cada 3 segundos.
El arreglo (core-rapido) fue quirúrgico: procs.py corre un solo ps cada 2 s en fondo y guarda lsof por PID; jobs.py cachea cada trabajo por (mtime_ns, size); y el frontend reconecta SSE con espera exponencial (1 s a 15 s) entrando en siesta a los 10 minutos sin toque.
Snapshot pulse & SSE reconnect
Measured timings before (462eb77) and after core-rapido (a50e179).
5. Direct relay: dropping the model from the mailroom
Originally, sending a message from the dashboard to a live Claude window spawned an entire one-shot Haiku process just to call SendMessage, blocking HTTP for seconds. cartero.py speaks the same two-line protocol directly over the window's Unix domain socket: authenticate with the local session peer key, write the cross-session-message envelope, wait 150 ms, and close. Antigravity windows route through agylink.py and agentapi send-message.
5. Relay directo: sacar al modelo de la mensajería
Antes, mandar un recado desde el tablero a una ventana viva de Claude lanzaba un proceso entero de Haiku solo para llamar SendMessage, bloqueando HTTP durante segundos. cartero.py habla directo el protocolo de dos líneas sobre el socket Unix de la ventana: autentica con la llave local de sesión, escribe el sobre cross-session-message, espera 150 ms y cierra. Las ventanas de Antigravity se enlazan con agylink.py vía agentapi send-message.
Direct relay (cartero.py) vs. model-spawned courier
Sanitized 2-line protocol over local Unix socket (0 model tokens).
{"type":"auth","token":"<ephemeral-local-key>"}
{"msgV":1,"type":"user","priority":"next",
"message":{"role":"user","content":"<cross-session-message>..."}}
6. What is still open
- Protocol coupling:
cartero.pytargets Claude Code 2.1.329's Unix socket wire format; an upstream CLI update can change the framing and require re-verification. - Monolith split:
agencia.py(1,843 lines) still keeps sources, background threads, and HTTP routes in one file; splitting it comes after stability, not before. - Unverified edge paths:
tui_cwdswith a live OpenCode TUI andstopped()against a realSIGSTOPprocess remain unverified end-to-end.
More: Open Agencia Studio Demo · GitHub · Gallery & code extracts · Chess reconciliations
6. Qué sigue abierto
- Acoplamiento de protocolo:
cartero.pyapunta al formato de socket de Claude Code 2.1.329; una actualización del CLI puede cambiar el framing y pedir nueva verificación. - Partir el monolito:
agencia.py(1,843 líneas) todavía concentra fuentes, hilos de fondo y rutas HTTP en un archivo; dividirlo viene después de la estabilidad, no antes. - Rutas sin prueba E2E:
tui_cwdscon una TUI viva de OpenCode ystopped()contra un proceso pausado conSIGSTOPsiguen pendientes de verificación en vivo.
Más: Abrir Agencia Studio Demo · GitHub · Galería y extractos de código · Reconciliaciones de Chess