Angel Miranda

Agencia: the local multi-agent control room behind this site

How I built it & reconciliation, November 2026

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.

Try the real Agencia Studio UI

Compiled directly from the React 19 + xyflow frontend in static Demo Mode (zero backend, OpSec-sanitized with NFSU, Max Payne, and CaliChess running inside).

4 → 1runtimes unified in one local snapshot
18 mssnapshot latency after moving ps/lsof to RAM
~150 msdirect Unix-socket relay, zero model tokens
6 viewsinbox, console, graph, blind audit, slices, RE

1. 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).

Agencia Consola view showing four runtimes running side by side on NFSU-WASM with the live inspector open
Consola (V): Claude Opus orchestrator, Codex worker, DeepSeek intern, Sonnet subagent, and Antigravity CLI unified in one live tree with the inspector docked on the right.
RuntimeDiscoveryLive signalDirect relay
Claude CodeSession registry + process tableIncremental .jsonl tail + subagent filescartero.py → Unix socket (uds:)
CodexDaily rollout .jsonl + job filesJSON event stream + 5 h quota from rolloutsjobs.py + app-server JSON-RPC archive
OpenCodeLocal HTTP API + lsof cwdTool-use JSON stream, hard deadline & step capjobs.py + session interrupt API
Antigravity CLIpresence/*.lock + local SQLiteTranscript events + subagent lineageagylink.py → agentapi send-message
Agencia Bandeja priority inbox highlighting one waiting decision and one failed worker
Bandeja (I): instead of hunting across terminals, the inbox surfaces only what needs a human decision right now, what failed, and what is ready to close.

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.

Agencia Real Slices view showing timed sprint progress, per-account caps, and APFS worktree diffs
Slices (S): a live Agencia Real sprint tracking elapsed budget, per-account weekly caps, chain of command, and per-worktree diffs.

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.

Agencia Tablero blind auditor view comparing agent claims against verified evidence
Tablero (T): blind auditor verdicts side by side with agent claims. Here it caught an intern overclaiming a 375 fps fix while approving a verified GC reduction.

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.

Agencia Lupa RE view showing Speed.exe WinMainCRTStartup decompilation and plain explanation
Lupa (R): live reverse-engineering view showing the addresses workers are currently analyzing alongside on-demand Ghidra C output.

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.

Prueba la app real de Agencia Studio

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).

4 → 1runtimes unificados en una sola foto local
18 mslatencia de snapshot al pasar ps/lsof a RAM
~150 msrelay directo por socket Unix, cero tokens
6 vistasbandeja, consola, red, auditor ciego, slices, RE

1. 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).

Vista Consola de Agencia mostrando cuatro runtimes en paralelo sobre NFSU-WASM con el inspector abierto
Consola (V): orquestador Claude Opus, trabajador Codex, becario DeepSeek, subagente Sonnet y Antigravity CLI unificados en un árbol vivo con el inspector a la derecha.
RuntimeDescubrimientoSeñal en vivoRelay directo
Claude CodeRegistro de sesiones + tabla de procesosCola incremental de .jsonl + subagentescartero.py → socket Unix (uds:)
CodexRollouts .jsonl + archivos de trabajoFlujo JSON de eventos + cuota de 5 h desde rolloutsjobs.py + archivo vía app-server JSON-RPC
OpenCodeAPI HTTP local + lsof de cwdFlujo JSON de herramientas, plazo y tope de pasosjobs.py + API de interrupción de sesión
Antigravity CLIpresence/*.lock + SQLite localEventos de transcript + linaje de subagentesagylink.py → agentapi send-message
Vista Bandeja de prioridades en Agencia resaltando una decisión en espera y un trabajador fallido
Bandeja (I): en lugar de cazar ventanas, la bandeja sube arriba solo lo que pide tu decisión ahora, lo que falló y lo que ya se puede cerrar.

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.

Vista Slices de Agencia Real mostrando progreso del sprint, topes por cuenta y diffs por worktree
Slices (S): una corrida viva de Agencia Real siguiendo presupuesto consumido, topes semanales por cuenta, cadena de mando y diffs por worktree.

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.

Vista Tablero del auditor ciego comparando lo que afirman los agentes contra la evidencia real
Tablero (T): veredictos del auditor ciego frente a lo que dice cada agente. Aquí atrapó a un becario exagerando un arreglo de 375 fps mientras aprobó una reducción verificada de GC.

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.

Vista Lupa binaria mostrando WinMainCRTStartup de Speed.exe decompilado y su explicación en llano
Lupa (R): vista de ingeniería inversa en vivo con las direcciones que los trabajadores están analizando y el C de Ghidra bajo demanda.

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).

Line 1 · Handshakelocal key
{"type":"auth","token":"<ephemeral-local-key>"}
Line 2 · Envelope~150 ms
{"msgV":1,"type":"user","priority":"next",
 "message":{"role":"user","content":"<cross-session-message>..."}}

6. What is still open

  • Protocol coupling: cartero.py targets 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_cwds with a live OpenCode TUI and stopped() against a real SIGSTOP process remain unverified end-to-end.

More: Open Agencia Studio Demo · GitHub · Gallery & code extracts · Chess reconciliations

6. Qué sigue abierto

  • Acoplamiento de protocolo: cartero.py apunta 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_cwds con una TUI viva de OpenCode y stopped() contra un proceso pausado con SIGSTOP siguen pendientes de verificación en vivo.

Más: Abrir Agencia Studio Demo · GitHub · Galería y extractos de código · Reconciliaciones de Chess