Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Worker Integration Guide
Sol supports two worker integration paths for connecting external agents to the orchestration platform.
Path 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 |
Path A: ZMQ DEALER Worker (Recommended)
How It Works
Worker (DEALER) ←──msgpack──→ Sol ROUTER (port 5555)
Workers connect to Sol’s ZMQ ROUTER gateway, register with a ready message, and receive task messages asynchronously. Results are streamed back via token and result messages. Liveness while connected is carried by plain heartbeat frames.
Re-READY hazard:
readyis a (re)connect signal ONLY — it is sent once on connect and again on a genuine reconnect (with the resume proof). Never re-sendreadywhile connected: if the worker finished its task but Sol still holds it (result delayed in a queue), a proof-less re-ready trips Sol’s fail-closed adoption gate and orphans the in-flight task with aworker_reconnectederror — exactly on the re-ready mark. Heartbeats carry liveness (touch_worker); the gateway dispatches the next task to any idle registered worker automatically after yourresult.
Dependencies
# Python
pip install pyzmq msgpack
# Lua (Luna)
# Built into client/ffi/zmq.lua
# Rust
cargo add zmq msgpack
Step 1: Connect and Register
import zmq
import msgpack
ctx = zmq.Context()
sock = ctx.socket(zmq.DEALER)
sock.setsockopt_string(zmq.IDENTITY, "my-worker-1")
sock.connect("tcp://127.0.0.1:5555")
# Register immediately
# NOTE: the payload goes out BARE — no empty delimiter frame. The old
# two-frame delimiter shape taught here previously was dropped by the
# gateway (it matches neither [Identity, Payload] nor
# [Identity, Payload, Mac]; see docs/zmq-protocol-reference.md §Message
# Framing, ).
sock.send_multipart([msgpack.packb({
"type": "ready",
"worker_id": "my-worker-1",
"version": 4, # REQUIRED — the gateway rejects the handshake
# with missing_fields without it (protocol
# version, sol_zmq_protocol:protocol_version/0;
# v1/v2 are refused loudly, v3 is admitted only
# while the N/N-1 skew window is on —
# zmq_wire_skew_window,;
# v4 since then —
# inference_binding + lane_control)
"capabilities": ["python", "streaming"]
}, use_bin_type=True)])
Live protocol version: 4 (version = 4). A v1/v2 worker is refused
loudly; v3 is admitted only while the N/N-1 skew window is open. The field is
validated by sol_zmq_protocol:protocol_version/0.
The per-frame MAC plane
On the worker plane, every credentialed multipart frame carries a trailing
MAC frame derived from the session key established by the verified
credential. The gateway verifies it before dispatch; a frame with a missing
or mismatched MAC is refused and counted, never executed. The MAC set is
generated in contract/zmq_frame_mac_sets.yaml and documented in
zmq-security.md and
zmq-protocol-reference.md.
When a fleet secret (SOL_ZMQ_WORKER_SECRET) or per-worker enrollment key
(zmq_enrollment_keys + key_id) is configured, the ready frame must
also carry a fresh nonce, a strictly increasing ctr, and an hmac over
nonce || u16(len(identity)) || identity || u16(len(worker_id)) || worker_id || u32(child_depth) || u64(ctr)
(see zmq-security.md — the reference implementation is
example/python/zmq_worker.py).
Step 2: 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"]
#... execute task...
Step 3: Stream Results
# Stream tokens during execution — each token carries a per-task
# monotonically increasing `seq` (Sol requires it from a v2+ worker;
# retransmits re-send the same seq)
sock.send_multipart([msgpack.packb({
"type": "token",
"task_id": task_id,
"seq": 1,
"content": "partial output..."
}, use_bin_type=True)])
# Send final result
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 idle registered workers. Do NOT send `ready` again
# here (see the re-READY hazard above).
Step 4: Handle Cancellation
if msg_type == "cancel":
task_id = msg["task_id"]
# Abort work, send cancelled result
sock.send_multipart([msgpack.packb({
"type": "result",
"task_id": task_id,
"status": "cancelled",
"content": ""
}, use_bin_type=True)])
Step 5: Heartbeat
Send a plain heartbeat frame every 5 seconds while connected — liveness,
NOT re-registration. Do not gate the heartbeat on idleness: a
heartbeat is processed whenever the worker is registered, and for a busy
worker it does MORE than keep the eviction sweep away —
# Heartbeat (repeats every 5s while connected — busy or idle)
sock.send_multipart([msgpack.packb({
"type": "heartbeat",
"worker_id": "my-worker-1"
}, use_bin_type=True)])
Each heartbeat (required: CURRENT registration — an unregistered identity’s
heartbeat is refused + counted) refreshes the worker’s last_seen and, when
the worker holds a task, also refreshes that task’s ownership-index liveness
timestamp (a long-running task never ages into the 1h sweep) and renews the
workflow bridge-correlation lease (sol_zmq_handler_worker.erl heartbeat
handler). The liveness sweep evicts workers silent for longer than
worker_heartbeat_timeout_ms — shipped sys.config/sys.prod.config =
15000 ms (the code fallback when the key is absent is 45000 ms; check
cycle 10s). Use 15000 ms when sizing your heartbeat interval against a
shipped fleet.
Complete Example
A full reference implementation is available at example/python/zmq_worker.py (530 lines). Run it:
pip install pyzmq msgpack
python3 example/python/zmq_worker.py tcp://127.0.0.1:5555 my-worker
See zmq-protocol-reference.md — the canonical wire-protocol reference.
Path B: JSONL Stdio Worker
How It Works
Sol (erlexec) spawns process
│
├── stdin → JSON task messages
└── stdout ← JSON result messages
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).
Step 1: Protocol
Messages are JSON objects, one per line, terminated by newline (\n). Each message has a type field.
Step 2: Message Types
Worker → Sol (stdout)
| Type | Fields | Description |
|---|---|---|
ready | — | Announce worker is ready |
token | id, content | Streaming partial output |
result | id, status, content | Task completion |
permission_request | task_id, request_id, tool_name, input_summary, analysis, expires_in_ms | — ask the operator for a tool decision (bounded command/path summary only; never the raw input) |
log | level, message | Diagnostic log |
Sol → Worker (stdin)
| Type | Fields | Description |
|---|---|---|
task | id, task_id, prompt, stream, user_uuid, permissions?, session_id?, inference_binding? | Task assignment; inference_binding is the pre-spawn lane grant |
cancel | id | Cancel running task |
permission_reply | request_id, decision, reason | — the operator answer (allow/deny/always); absorbed MID-TURN by the stdio drive |
Lane binding: Sol resolves the task’s lane before
the stdio process is spawned and stamps every task line with a granted
inference_binding — the same pinned descriptor the ZMQ plane sends
(lane, endpoint, wire_format, caps, ctx, lease_id, expires_at,
expires_in_ms, holder, status="granted"). Luna builds a per-task
Provider.from_lane from it (keyless; no startup key required) and honors
the receipt-relative expires_in_ms even when the host wall clock is skewed.
There is no lane_control over stdio and no protocol-version bump; a
lane-named model with no grantable warm lane fails the SPAWN typed
(lane_<reason>, e.g. lane_no_lane) instead of booting a keyless crash
loop. A non-lane model keeps the keyed startup-provider posture.
Standalone stdio: --stdio is also an
operator/editor transport. It starts no ZMQ worker (that is --connect
only), reads JSONL tasks from stdin, and streams frames to stdout:
# declare the endpoint once (~/.luna/settings.json):
# {"providers":{"local":{"base_url":"http://localhost:11434",
# "wire_format":"openai","models":["qwen2.5-coder:7b"],"no_api_key":true}}}
client/run --stdio --no-persist --model qwen2.5-coder:7b
{"type":"ready"}
{"type":"task","id":"t1","prompt":"first prompt"}
{"type":"token","id":"t1","content":"..."}
{"type":"result","id":"t1","status":"ok","content":"..."}
{"type":"task","id":"t2","prompt":"second prompt"} # carries t1 history
ONE Session/Agent serves the whole process, so prompt 2 sees prompt 1’s
history; the session is closed once at stdin EOF (clean exit 0). cancel
and permission_reply lines are honored while a turn runs; a task line that
arrives mid-turn is queued and served after the result.
Permission-ask contract: a worker hook with no operator
surface used to deny silently. Headless stdio workers now emit ONE
permission_request line, then park (yielding permission_wait) until the
matching permission_reply line arrives — the stdio drive reads it
MID-TURN, so a task is never finished around the ask. The deadline is the
frame’s expires_in_ms (worker-enforced locally too); a lapse is a typed
deny. always may persist in the worker’s 600s decision cache; one-shot
allow/deny never does. Sol routes the ask to the session’s WebSocket and
records a STRICT, content-free audit row (permission_decided:
tool/decision/reason/input_hash/session/worker/owner/source) on every
decision — operator, timeout, disconnect, or task-finished.
Cancel contract: a cancel line is honored
MID-TURN, not just between tasks. Luna’s --stdio worker drives
run_turn_async and polls stdin between yields, so a cancel arriving
while the model is streaming interrupts the turn immediately (the model
turn ends with the interrupted terminal) and the worker emits
{"type":"result","id":...,"status":"cancelled","content":""} once the
partial output is stopped. A task line that arrives while a turn is
running is queued and served after the result — it is never dropped.
Embedders that do not poll stdin between yields may only rely on process
termination as the cancellation mechanism.
Turn lifecycle and intake queues
Luna has two in-process intake queues. Steering is injected at the next
loop boundary before the next provider request; follow-ups are injected
only when the inner loop would otherwise stop. Each queue drains all
(historical behavior) or one-at-a-time (steering_mode /
follow_up_mode). Steer wins over follow-up at the same boundary.
| Phase | Queue action | Events |
|---|---|---|
| Turn start | none (pre-queued messages wait for the first boundary) | turn_start |
| Provider stream | none mid-stream | text_delta, thinking_delta, usage, provider_retry |
| Tool batch | none mid-batch (the batch is atomic) | tool_start, tool_done, tools_running |
| Post-stream B1 | drain steer; re-arm the loop if anything was injected | steering (one per message) |
| Late B2 | drain steer queued during compaction/recovery/stop hooks | steering |
| Outer B3 | steer first, then follow-up; one provider round each (cap 3 each) | steering or follow_up |
| Interrupt / terminal error | queues preserved (no drain) | interrupted → turn_done |
Step 3: Minimal Worker Example
#!/usr/bin/env python3
import sys
import json
def send(msg):
sys.stdout.write(json.dumps(msg) + "\n")
sys.stdout.flush()
# Announce ready
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"]
# Stream tokens
send({"type": "token", "id": task_id, "content": "Working...\n"})
# Send result
send({"type": "result", "id": task_id, "status": "ok", "content": f"Done: {prompt}"})
elif msg.get("type") == "cancel":
task_id = msg["id"]
send({"type": "result", "id": task_id, "status": "cancelled", "content": ""})
Step 4: 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.
Task Timeout
task_timeout_ms is an idle deadline (default 300000 ms): Sol re-arms it
on every token/heartbeat progress for the task, so a live-streaming task
is not hard-killed at 5 minutes. The progress-renewed lease is separately
bounded by task_max_lifetime_ms (default 1200000 ms; 0 = uncapped) — a
chatty-but-endless task is cancelled at that cap. task_timeout_ms=0
disables the gateway deadline; the wire field then carries the documented
24h sentinel.
Output Buffer
Worker stdout is buffered up to 256KB. Output exceeding this limit is truncated with [...output truncated...].
Worker Configuration Reference
| 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 |
Monitoring Workers
ZMQ Workers
zerg zmq-workers # List connected workers
zerg zmq-status # Gateway status
JSONL Workers
zerg agents # List spawned workers
zerg task-status <id> # Check task result