Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Architecture

Banner: this page describes the current implementation shape. Every key=value count is machine-rendered from AGENTS.counts; design proposals and retired models live in plan/ and must not be read as shipped behaviour.

ZERG is a production-grade agentic orchestration platform built on four pillars: Sol (Erlang/OTP server), Luna (LuaJIT agent), Mango (Python/Tornado auth), and Limon (TypeScript/Vue3 dashboard).

System Architecture

┌─────────────┐     ┌─────────────┐     ┌─────────────┐
│   Limon     │     │  ZERG CLI   │     │   API       │
│  (Vue 3)    │     │  (LuaJIT)   │     │  Clients    │
└──────┬──────┘     └──────┬──────┘     └──────┬──────┘
       │                   │                   │
       └───────────┬───────┴───────────────────┘
                    │ HTTP/SSE/WebSocket
       ┌───────────┴───────────┐
       │      Sol Server        │
       │    (Erlang/OTP 29.1)   │
       │  ┌─────────────────┐  │
       │  │ Cowboy HTTP     │  │
        │  │ 202 spec routes │  │
       │  │ endpoints       │  │
       │  ├─────────────────┤  │
       │  │ Event Store     │  │
        │  │ (Mnesia, 100    │  │
       │  │  event types)   │  │
       │  ├─────────────────┤  │
       │  │ Workflow Engine │  │
       │  │ (gen_statem)    │  │
       │  ├─────────────────┤  │
       │  │ ZMQ Gateway     │  │
       │  │ (chumak ROUTER) │  │
       │  ├─────────────────┤  │
       │  │ Plugin Bridge   │  │
       │  │ (Luerl, 16      │  │
       │  │  modules)       │  │
       │  └─────────────────┘  │
       └───────────┬───────────┘
                    │ ZMQ ROUTER/DEALER (chumak)
       ┌───────────┴───────────┐
       │     Worker Boundary    │
       │  ┌─────┐  ┌─────┐    │
       │  │Luna │  │Luna │    │
       │  │     │  │     │    │
       │  └─────┘  └─────┘    │
       │  (LuaJIT, <10MB each) │
       └───────────────────────┘

Component Details

Machine counts (, — renderer-maintained via ci/render-docs-counts.py, do not hand-edit): sol_modules=489 sol_lines=201310 event_types=102 provider_adapters=14 heir_owners=34 luna_modules=268 luna_lines=100104 tools=92 mango_modules=62 limon_files=253

Sol Server (Erlang/OTP 29.1)

sol_modules=489 modules, sol_lines=201310 lines of Erlang code 180 route tuples / 202 spec rows with SSE streaming (docs/api-reference.md) WebSocket bidirectional chat with Mnesia history (7-day retention shipped via event_retention_days; the code fallback is 30) Event sourcing with Mnesia (event_types=102 event types across 16 groups) gen_statem-based workflow engine with compensation 14 provider adapters with 8 circuit-breaker protected (the machine count includes the sol_provider_egress policy helper; the 12 wire adapters are Anthropic, OpenAI, OpenAI-compat, Responses, z.ai, Ollama, Gemini, DeepSeek, Alibaba, Bedrock, Xiaomi, declarative) llama.cpp local inference with remote provider fallback Prometheus metrics (OpenTelemetry tracing was retired by design — it had zero consumers; re-introduction is tracked, not scheduled) 34 ETS heir-owner tables under sol_owners_sup

Luna Agent (LuaJIT)

luna_modules=268 modules, luna_lines=100104 lines of Lua code ~1 MB stripped secure binary (full build ~4.8 MB; bytecode + XOR + CRC32, statically linked libzmq) 92 registered tools (74 built-in + 12 computer-use + 6 desktop-environment are platform-conditional) + MCP discovery 8 agent modes (Build/Plan/Explore/Review/General/Coordinate/Leader/Teammate) + user-defined MCP client (stdio + HTTP + WebSocket, multi-server, OAuth PKCE) Dual-write sessions (JSONL + SQLite with FTS5 full-text search) Git auto-snapshots, undo stack, diff view 4 sub-agent backends (local/zmq/team/background)

Mango (Python/Tornado)

mango_modules=62 modules — auth and identity service Token validation and RBAC (~27 endpoint-specific permission strings) ZMQ event bridge to Sol for live cache invalidation ( sol_mango_event_subscriber) Migration runner, rate limiting (IP + per-account brute-force) Microservice framework for extending the platform

Limon (TypeScript/Vue 3)

limon_files=253 source files — mission-control dashboard 21 views: Login, Dashboard, Chat, Workflows, Audit, Workers, Recipes, Settings, Channels, Skills, Goals, BgWorkers, Providers, Memory, Events, Schedules, Teams, System, ManagedSettings, Seats, Telemetry WebSocket chat, SSE streaming, real-time worker status

ZMQ Gateway Architecture

The ZMQ gateway uses a dedicated sharded architecture for scalability and security:

Sol_zmq_sender — owns the ROUTER socket, serializes all outbound sends Sol_zmq_recv_dispatcher — dedicated gen_server for inbound message routing Sol_zmq_result_router — routes child task results, manages parent/child cleanup Sol_zmq_recv_bridge — recv loop with error backoff (EAGAIN resilience) Sol_zmq_ownership — per-frame ownership enforcement: every result/token/error/event/spawn frame is verified against the dispatch index; unknown_task is allowed (post-restart leniency) but not_owner is dropped with a CRITICAL log + alertable counter Sol_zmq_task_dispatcher — task lifecycle: dispatch, queue, retry with error strategy (skip/retry/abort), per-task execution timeout Sol_zmq_worker_manager — worker registration, heartbeat tracking, stale-worker eviction, task assignment ETS indexes (sol_zmq_task_index, sol_zmq_id_index) for O(1) lookups Plugin tool executor pool (simple_one_for_one) isolates plugin tool execution

Worker Registration Security

When zmq_worker_secret is configured, the DEALER’s ready frame must carry nonce + hmac (HMAC-SHA256 of nonce with the shared secret). Sol rejects registrations without a valid HMAC. Secrets < 16 bytes are refused outright.

Task Lifecycle

dispatch → pending → ok / error / cancelled
                ↑         ↑
                |         |
             store_pending    terminal-state guard
                               (once ok/completed,
              |                later writes rejected)
   queued (no worker ready) →

store_pending — tasks are written to sol_task_results at dispatch time (both dispatched and queued paths) so GET /api/v1/tasks/:id returns {status: "pending"} instead of 404 during the in-flight window Terminal-state guard — store_result_/4 rejects writes to a task already in ok/completed state, preventing the double-result race (eviction retries to worker B, but worker A’s late result silently overwrites) Valid transitions: pending→ok, pending→error, error→pending (retry reset), pending→cancelled

Extension System

Plugins register custom tools, commands, modes, and event handlers via Luerl (Lua-in-Erlang) bridges:

16 bridge modules (log, http, config, events, channel, json, time, tools, commands, sessions, providers, workflows, agents, memory, scheduler, util) Extension lifecycle (init/register/start/stop) with context invalidation Plugin tool dispatch via ZMQ RPC (server-side Luerl execution) 3 sandbox backends — Landlock (write-deny fork layer), bwrap (namespace/network/read owner), seatbelt (macOS alternate) — and 6 permission modes (default/allow-all/deny-all/read-only/plan/auto) Permission priority chain: user config > extension rules > mode defaults

Memory Pipeline

Cross-session persistent memory with extraction and consolidation:

Heuristic memory extractor (fact/preference extraction from conversations) Algorithmic consolidator (dedup + prune with 85% similarity threshold) Reflection clustering for cross-session insight synthesis Session close hook triggers memory extraction KV+TTL storage with provider abstraction

Durability + encoding: the file (MEMORY.md) and JSON backends fsync the temp file before an atomic rename; values that are empty, ## -leading, #-leading, or whitespace-ambiguous are stored as a single =json=-sentineled escaped line (keys starting =json= are reserved); the SQLite backend stores scalars with a =j: prefix so "42" stays a string and 42 stays a number. Dual mode (JSON + SQLite) is FIFO-serialized sqlite-first with JSON as the durable base — best-effort convergence, not a transaction. Same-path multi-process writes to memory.json are protected by an advisory flock (not transactionally safe). Memory scoping is one effective uuid (instance → module → "system"); instance-scoped sets are visible to instance-scoped search only.

Key Design Decisions

  1. Erlang/OTP 29.1 for massive concurrency and fault tolerance
  2. LuaJIT for ultra-lightweight worker nodes (sub-10MB footprint)
  3. ZMQ (chumak) for the polyglot worker boundary — msgpack wire format
  4. Event sourcing as the orchestration backbone (event_types=102 event types)
  5. Luerl sandbox for safe server-side plugin execution
  6. llama.cpp for local-first inference with cloud fallback