Workers and Agents
Sol orchestrates swarms of Luna worker agents over ZMQ and JSONL transports. This guide covers connecting workers, the wire protocol, agent modes, and headless operation.
Transport Comparison
| Feature | ZMQ DEALER | JSONL Stdio |
|---|---|---|
| Protocol | msgpack over ZMQ | JSON lines over stdin/stdout |
| Language | Any (ZMQ + msgpack bindings) | Any (stdin/stdout) |
| Process management | External (worker manages itself) | Sol spawns via erlexec |
| Streaming tokens | Yes | Yes |
| Task cancellation | Yes | Yes |
| Child task spawning | Yes | No |
| Reconnection | Automatic (ZMQ) | Process restart |
| Dependencies | libzmq, msgpack | None |
| Best for | Long-running workers, polyglot | Short-lived workers, simple agents |
ZMQ DEALER Workers (Recommended)
Connection Model
Workers connect to Sol’s ZMQ ROUTER gateway as DEALER sockets. Communication is asynchronous: workers announce readiness, Sol dispatches tasks, workers stream results back.
Worker (DEALER) <--> Sol ROUTER (port 5555)
Multiple workers can connect simultaneously. Sol routes tasks to the first available (ready) worker. If no workers are ready, tasks queue until one becomes available.
Connect and Register
The ZMQ gateway uses a dedicated sharded architecture for high throughput:
Sol_zmq_sender — owns the ROUTER socket, serializes all outbound sends through a dedicated gen_server
Sol_zmq_recv_dispatcher — dedicated gen_server for inbound message routing
Sol_zmq_result_router — routes child task results and manages parent/child cleanup
Sol_zmq_recv_bridge — recv loop with error backoff, extracted from gateway
ETS indexes — sol_zmq_tasks and sol_zmq_workers tables for O(1) lookups
Plugin tool executor pool — simple_one_for_one supervisor isolates plugin tool execution from the gateway
Registration is credentialed: a bare ready is refused with
registration_hmac_failed unless Sol runs the explicit loopback dev ack
(SOL_ZMQ_ALLOW_LOCAL_UNREGISTERED=true in dev). Provision the worker
first — a per-worker enrollment key is the recommended form:
# Sol: one JSON entry per worker (secret >= 16 bytes). Restart/reload picks
# this up; the entry is bound to the exact worker_id.
export SOL_ZMQ_ENROLLMENT_KEYS='{"my-worker-1":{"worker_id":"my-worker-1","secret":"<32-byte-secret>"}}'
import hashlib
import hmac
import os
import time
import msgpack
import zmq
PROTOCOL_VERSION = 4 # sol_zmq_protocol:protocol_version/0
WORKER_ID = os.environ.get("ZERG_WORKER_ID", "my-worker-1")
URL = os.environ.get("SOL_ZMQ_URL", "tcp://127.0.0.1:5555")
# Per-worker enrollment secret (recommended) or the fleet secret.
SECRET = os.environ["SOL_ZMQ_WORKER_SECRET"].encode()
# Per-worker enrollment id. Omit it to present the legacy fleet secret
# (only while zmq_fleet_legacy_compat is explicitly reopened).
KEY_ID = os.environ.get("ZERG_WORKER_KEY_ID", "")
ctx = zmq.Context()
sock = ctx.socket(zmq.DEALER)
sock.setsockopt_string(zmq.IDENTITY, WORKER_ID)
sock.connect(URL)
# The payload goes out BARE — no empty delimiter frame (the old two-frame
# delimiter shape is dropped by the gateway; see
# docs/zmq-protocol-reference.md §Message Framing, ).
nonce = os.urandom(16).hex()
ctr = time.time_ns() // 1_000_000 # strictly increasing u64 milliseconds
material = (
nonce.encode()
+ len(WORKER_ID).to_bytes(2, "big")
+ WORKER_ID.encode()
+ len(WORKER_ID).to_bytes(2, "big")
+ WORKER_ID.encode()
+ (0).to_bytes(4, "big") # child_depth
+ ctr.to_bytes(8, "big")
)
ready = {
"type": "ready",
"worker_id": WORKER_ID,
"version": PROTOCOL_VERSION,
"capabilities": ["python", "streaming"],
"nonce": nonce,
"ctr": ctr,
"hmac": hmac.new(SECRET, material, hashlib.sha256).hexdigest(),
}
if KEY_ID:
ready["key_id"] = KEY_ID
sock.send_multipart([msgpack.packb(ready, use_bin_type=True)])
Luna does the same handshake automatically from LUNA_ZMQ_KEY_ID +
LUNA_ZMQ_WORKER_SECRET (the HMAC material is built by
client/core/zmq_protocol.lua; see the full reference implementation in
example/python/zmq_worker.py).
Receive and Execute Tasks
poller = zmq.Poller()
poller.register(sock, zmq.POLLIN)
while True:
events = dict(poller.poll(timeout=1000))
if sock not in events:
continue
frames = sock.recv_multipart()
msg = msgpack.unpackb(frames[-1], raw=False)
msg_type = msg.get("type")
if msg_type == "task":
task_id = msg["task_id"]
prompt = msg["prompt"]
Stream Results
sock.send_multipart([msgpack.packb({
"type": "token",
"task_id": task_id,
"content": "partial output..."
}, use_bin_type=True)])
sock.send_multipart([msgpack.packb({
"type": "result",
"task_id": task_id,
"status": "ok",
"content": "final output"
}, use_bin_type=True)])
# The worker stays REGISTERED after the result — the gateway dispatches
# the next task to any idle registered worker. Do NOT re-send `ready`
# (see the re-READY hazard under "Protocol Hardening" below).
Handle Cancellation
if msg_type == "cancel":
task_id = msg["task_id"]
sock.send_multipart([msgpack.packb({
"type": "result",
"task_id": task_id,
"status": "cancelled",
"content": ""
}, use_bin_type=True)])
Luna maintains registration with a dedicated plain heartbeat frame every 5
seconds. Since the ready frame is sent ONCE at registration — it is
NEVER re-sent (the old 60-second re-READY cycle was removed: proof-less
re-ready tripped Sol’s fail-closed adoption gate; liveness is served by the
heartbeat alone, see client/core/zmq_worker.lua). A full Python reference
implementation is at example/python/zmq_worker.py.
See ZMQ Protocol for the complete specification.
Protocol version and per-frame MAC
The live worker wire protocol is version 4. A v1/v2 worker is refused loudly; v3 is admitted only while the N/N-1 skew window is open. Credentialed worker-plane frames carry a trailing multipart MAC derived from the session key; the gateway verifies it before dispatch. The full field contract and refusal catalog are in the Worker Integration reference and ZMQ protocol reference.
Protocol Hardening
The ZMQ boundary has been progressively hardened against forged and untracked frames:
** →, re-based — ZMQ ownership enforcement.** result/token/error frames pass allow_result_frame/4: the sender must be the task’s dispatched-to worker (index match); on an index miss it must equal the recorded executor stamped at dispatch (bounded WARNING grace), otherwise the frame is refused and counted. The previous “currently registered sender” grace is DELETED. event frames require registration and the worker event namespace is closed to telemetry.*/agent.*. spawn frames require the parent task to belong to the sender; team_*/acp frames require registration (worker-supplied from/member_id are never identity).
Worker registration HMAC. With a fleet secret (SOL_ZMQ_WORKER_SECRET) or a per-worker enrollment key (key_id) configured, the ready frame must carry a fresh nonce, a strictly increasing u64 ctr, and an HMAC over the canonical signed material nonce || u16(len(identity)) || identity || u16(len(worker_id)) || worker_id || u32(child_depth) || u64(ctr) (registration_signed_material/5 — the routing identity is bound before the claimed worker_id); Sol validates the HMAC and the counter before accepting the worker. A bare ready from an unauthenticated peer is rejected. The early HMAC(worker_secret, nonce) challenge-response form is retired, and the legacy compatibility windows are CLOSED by default.
Pending task store. ZMQ-dispatched tasks are written to sol_task_results at dispatch time via sol_task_store:store_pending/2, so GET /api/v1/tasks/:id returns {status: pending} immediately instead of 404 during the in-flight window before the first terminal event.
JSONL Stdio Workers
Sol spawns an OS process via erlexec and communicates via JSON lines over stdin/stdout. The worker reads JSON objects from stdin (one per line) and writes JSON objects to stdout (one per line, flushed after each).
Message Types
Worker to Sol (stdout)
| Type | Fields | Description |
|---|---|---|
ready | – | Announce worker is ready |
token | id, content | Streaming partial output |
result | id, status, content | Task completion |
log | level, message | Diagnostic log |
Sol to Worker (stdin)
| Type | Fields | Description |
|---|---|---|
task | id, prompt, opts | Task assignment |
cancel | id | Cancel running task |
Minimal Worker Example
#!/usr/bin/env python3
import sys
import json
def send(msg):
sys.stdout.write(json.dumps(msg) + "\n")
sys.stdout.flush()
send({"type": "ready"})
for line in sys.stdin:
msg = json.loads(line.strip())
if msg.get("type") == "task":
task_id = msg["id"]
prompt = msg["prompt"]
send({"type": "token", "id": task_id, "content": "Working...\n"})
send({"type": "result", "id": task_id, "status": "ok", "content": f"Done: {prompt}"})
elif msg.get("type") == "cancel":
send({"type": "result", "id": msg["id"], "status": "cancelled", "content": ""})
Spawn Configuration
Configure in sys.config:
{worker_path, "/path/to/my-worker"},
{max_workers, 16}
Or override per-spawn via the HTTP API:
zerg spawn --worker-path /path/to/my-worker
The worker_path is validated against a configurable prefix to prevent arbitrary binary execution. The JSONL task deadline is the shipped task_timeout_ms (300-second idle deadline, re-armed by progress) and is capped by task_max_lifetime_ms (default 1200000 ms) for a chatty-but-endless task. Worker stdout is buffered up to 256KB.
Worker Configuration
| Config Key | Default | Description |
|---|---|---|
worker_path | "client/build/luna" | Path to worker binary |
max_workers | 16 | Maximum concurrent workers |
zmq_router_port | 5555 | ZMQ ROUTER socket port |
zmq_pub_port | 5556 | ZMQ PUB event socket port |
zmq_bind_addr | "127.0.0.1" | ZMQ bind address |
zmq_enabled | true | Enable ZMQ gateway |
Agent Modes
Luna workers operate in 8 built-in agent modes (6 primary + 2 swarm), each tuned for a specific task category. Mode selection changes the system prompt, tool permissions, and agent behavior.
| Mode | Purpose | Tool Policy |
|---|---|---|
| Build | Code creation and modification | Read/search allowed, writes require approval |
| Plan | Analysis and planning | Read/search allowed, all writes denied |
| Explore | Codebase exploration | Read/search/lsp only, all writes denied |
| Review | Code review and audit | Read/search/web allowed, writes denied |
| General | General-purpose tasks | All tools allowed, bash/delete require approval |
| Coordinate | Multi-agent orchestration | All tools allowed (orchestrator needs full access) |
| Leader | Team leader — coordinate a team of teammates | All tools allowed + team_mail (+ team directives) |
| Teammate | Execute assigned tasks as part of a team | Curated allowlist incl. team_mail |
Switch modes with Tab in the TUI or the switch_mode tool:
> /mode build
User-defined modes can be registered via the agent configuration.
Headless Mode
Run Luna without the TUI for scripted or CI/CD workflows:
luajit client/main.lua --print "Analyze this codebase and report issues"
luajit client/main.lua --print "Fix the bug in main.rs" --permission-mode allow-all
Workers are provider-keyless when connected to Sol (the LLM lane grant arrives per task via POST /api/v1/start / POST /api/v1/prepare/:name; list lanes with GET /api/v1/inference/lanes) — this is not registration-keyless: the ZMQ handshake still requires the enrollment credential above. Output is written to stdout in plain text.
Monitoring Workers
zerg zmq-workers
zerg zmq-status
zerg agents
zerg task-status <id>