Introducing a new way to review your PRs.

Read the announcement

superradcompany / microsandbox

🧱 easy, fast, programmable and local-first microVM runtime and library

View on GitHub

27 documents · Updated Nov 23, 2026

docs / api-protocol

Runtime protocol and transports

The runtime protocol is the versioned boundary between host-side clients and sandbox services. It carries control messages and streamed data through a shared frame shape while keeping agent traffic, host control, and private recovery contracts on separate compatibility paths.

Protocol boundary

The agent protocol connects a host client to agentd inside a sandbox. A host relay carries its frames over the agent virtio-console port. The control protocol is separate and connects a client to the host runtime for resource, checkpoint, secret, and other host-owned operations.

The boundary keeps message meaning separate from the byte path. A local socket, pipe, WebSocket, or asynchronous byte stream can carry the same protocol without changing its message rules.

This diagram shows the public agent and control paths and the private recovery paths.

flowchart LR
    C[Host client]
    C -->|Agent protocol| R[Host relay]
    R -->|agent port| A[Sandbox agent]
    C -->|Control protocol| H[Host runtime]
    C -->|Legacy discovery when needed| H
    P[Private recovery client] --> V[Isolated restore or editor guest]

Private restore, storage inspection, and captured-disk editing use their own bounded contracts. They are not new public agent message domains.

References: crates/…/VERSIONING.md• L1-18 crates/…/lib.rs• L453-472 crates/…/restore_transport.rs• L11-38 crates/…/snapshot_patch.rs• L5-20

Connection lifecycle

An agent connection starts with relay setup and then moves into correlation-routed frame traffic. The relay supplies an ID range and the cached core.ready frame. A supported legacy path supplies an offset followed by the same ready frame, so the client can retain peer capability and compatibility data.

The host control connection starts with control.hello and control.welcome. The client offers a generation range and limits. The runtime selects the highest shared generation and the lower limit for frame size and in-flight requests. Existing runtimes can still select the legacy JSON path through read-only capability discovery.

After setup, a nonzero correlation ID identifies one request or stream. A terminal response ends that correlation. Agent relay ranges let several clients share one guest channel without mixing responses. Transport identity and client incarnation data stop a stale owner from using a range after reuse.

This diagram shows the normal agent setup and request flow.

sequenceDiagram
    participant C as Host client
    participant R as Agent relay
    participant A as Sandbox agent
    C->>R: Connect through a supported transport
    R-->>C: ID range and core.ready
    C->>R: Framed request
    R->>A: Route by correlation ID
    A-->>R: Response or stream frames
    R-->>C: Frames for that correlation ID

The control handshake uses ID zero for setup. Application requests use nonzero IDs after the welcome. A framed control client does not probe the agent endpoint, and the compatibility connection does not treat malformed discovery as permission to retry a mutation through another representation.

References: crates/…/VERSIONING.md• L39-58 crates/…/VERSIONING.md• L78-114 crates/…/control_contract.rs• L442-490

Frame model

A frame is the routing container shared by the framed agent and control protocols. Its fixed binary header lets a relay read the length, correlation ID, and flags without decoding the message body.

LayerContentsPurpose
Length prefix4-byte unsigned length in big-endian orderGives the size of the remaining frame.
Binary header4-byte correlation ID and 1-byte flags fieldSupports routing and lifecycle handling.
Control bodyCBOR envelope with generation, wire name, and payload bytesCarries a typed operation.
Bulk bodyRaw data header and payload when the bulk flag is setCarries filesystem or TCP stream bytes.

The length covers the binary header and body but not the prefix. The ordinary frame limit is 4 MiB after the prefix. Terminal, session-start, and shutdown flags describe request lifecycle. The bulk flag selects an exclusive raw body and cannot be combined with control flags.

The outer frame stays stable while body formats are added by negotiated capability. A change to the header would require every relay, codec, and transport adapter to change together.

References: crates/…/message.rs• L11-35 crates/…/message.rs• L41-79 crates/…/gen-11.json• L12-18 crates/…/VERSIONING.md• L20-37

Codec layers

The codec boundary provides a raw view for routing and a checked view for protocol behavior. Relays can forward a complete frame without understanding its body. Typed code decodes the body only when it must validate or act on the operation.

ViewUnderstandsMain use
Raw frameLength, ID, flags, and opaque body bytesRelaying and forwarding.
Generic envelopeGeneration, wire name, and encoded payloadSharing envelope rules across domains.
Typed messageEnvelope plus a known message contractNormal request and response handling.
Bulk recordData kind, direction, offset, and opaque bytesOrdered filesystem and TCP streaming.

The checked control decoder accepts unknown optional fields but rejects duplicate keys, invalid types, and trailing data. An unknown wire name remains available to code that owns its interpretation. A forwarder should keep the original frame when it does not own the schema because decoding and rebuilding can remove unknown fields.

Bulk records use exact offsets and receive credit. A sender may emit only data within the granted absolute limit. This keeps large data flows separate from the small control path.

References: crates/…/codec.rs• L37-62 crates/…/codec.rs• L227-260 crates/…/codec.rs• L367-489 crates/…/control_contract.rs• L329-411

Message domains

Message domains group related operations under stable wire names. Agent domains describe work inside the sandbox. The control domain describes host runtime operations and uses its own generation number.

DomainBoundary roleTypical lifetime
CoreReadiness, health, lifecycle, workload flow control, and resource observationsShort exchanges or session-wide control.
ExecCommand start, input, output, terminal control, signals, and completionOne execution can emit many events before a terminal result.
FilesystemPath and handle operations plus file dataDirect replies or negotiated bulk streams.
TCPGuest-side connection setup, stream data, and close stateOne connection from open to close or failure.
BootstrapOne-shot guest setup before readinessConsumed during VM startup.
ControlHost capabilities, resources, secrets, checkpoints, jobs, labels, and pause stateHost-side request and terminal response.

Agent names use the core.<domain>.<action> form. Control names use forms such as control.hello, control.memory.target, and control.checkpoint.create. The child page Protocol messages and compatibility covers payload contracts, introduction generations, and message-level compatibility rules.

The current agent surface includes generation-11 resource observations. These reports are query-bound evidence about guest CPU and memory readiness. They do not claim that a host resize operation completed.

Host-only extensions add capabilities without changing guest message meaning. They include runtime-owned jobs, operation-bound resize tracking, label updates, execution signal delivery, and command-origin evidence. Optional readiness fields also report init selection and relay support. Older readers can ignore these fields when they are absent or unknown.

References: crates/…/message.rs• L100-297 crates/…/message.rs• L16-34 crates/…/types.rs• L17-91 crates/…/jobs.rs• L144-313 crates/…/resize.rs• L96-139 crates/…/labels.rs• L33-97 crates/…/resources.rs• L16-55

Version negotiation

The agent and control protocols negotiate separate generation numbers. The agent protocol currently declares generation 11. The control protocol supports generations 1 and 2. A generation is agreed during setup, then used as a capability gate for operations.

Protocol or featureCurrent boundary
Agent protocolGeneration 11.
Agent raw bulk bodyGeneration 8.
Agent workload barriers and root-disk messagesGeneration 9.
Agent execution acknowledgementsGeneration 10.
Agent resource observationsGeneration 11. They also need relay observation capability version 1.
Host controlGenerations 1 and 2.
Host transport profilesSeparate capability formats, not guest generations.

Each known agent message records the generation that introduced it. The host checks that value before sending. An unsupported operation fails locally while unrelated streams remain usable. The generation in an envelope describes the negotiated protocol instance; it is not a second message-local version.

Control generation 1 keeps the released capability, resource, and secret operations. Generation 2 adds checkpoint and branch operations, pause and resume, root-disk growth, disk compaction, runtime-owned jobs, resize tracking, and label updates. The generation-two capability inventory is the source for deciding which of these operations the runtime can perform.

Evolution uses additive message types and optional fields. A newer peer speaks the older format when needed. A peer must negotiate both the required generation and any separate relay or transport capability before it sends a new feature.

The send sequence is:

  1. Establish protocol and transport capabilities.
  2. Select the highest generation or format both peers can read.
  3. Check each message or transport feature against that selection.
  4. Reject only the unsupported operation when the connection can continue.

See Protocol messages and compatibility for the support matrix and detailed compatibility rules.

References: crates/…/VERSIONING.md• L39-70 crates/…/VERSIONING.md• L78-124 crates/…/message.rs• L382-453 crates/…/message.rs• L189-218 crates/…/resources.rs• L8-33

Transport mechanisms

Transports move complete protocol packets or agreed raw records. They do not define message meaning. Each transport preserves ordering and reports partial input or closure as a transport condition rather than as a valid message.

Environment or laneSupported mechanismBoundary behavior
Host to sandboxVirtio-console port agentCarries ordinary agent frames between the relay and agentd.
Host to sandbox bulk laneOptional virtio-console port agent-bulkCarries raw filesystem or TCP records after a per-boot binding check.
Local host clientUnix domain socket or Windows named pipeCarries length-prefixed packets to the relay or host runtime.
Browser or front endWebSocketCarries binary packets while the adapter assembles complete packets.
Rust integrationCaller-owned asynchronous byte streamCarries the same relay setup and frames through an authenticated reader and writer.
Local optimized data pathShared arena capabilityUses a separately negotiated local format that the guest does not interpret.
Legacy host controlJSON over the existing control endpointPreserves old one-request and one-response behavior after discovery.

The optional dual-port profile adds a per-boot client identity to the bulk lane and uses ordered control records to retire old owners before an ID range is reused. This identity protects ownership without changing the public frame or message contract.

References: crates/…/VERSIONING.md• L78-114 crates/…/VERSIONING.md• L167-181 crates/…/lib.rs• L81-90 crates/…/codec.rs• L136-215

Correlation routing

After setup, a reader turns incoming packets into frames and routes them by correlation ID. Typed callers decode the body. Raw callers keep it opaque for forwarding or custom decoding. Streaming callers remain attached until a terminal frame, transport failure, or local cleanup.

Agent relay slots use half-open ID ranges. Boundary IDs remain unused so ownership can be checked without ambiguity. A bulk record uses the same correlation ID as its control exchange.

Control requests use the full nonzero ID space on their connection. The handshake uses ID zero. Terminal replies end application requests. This keeps setup records separate from ordinary operations and prevents late data from reviving a completed stream.

References: crates/…/VERSIONING.md• L80-96 crates/…/codec.rs• L94-175 crates/…/message.rs• L63-74

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the five-byte outer header, 4 MiB limit, and exclusive bulk flag aligned across codecs, relays, clients, and transport adapters.
  • When adding an agent message, update its stable wire name, introduction generation, capability gate, and current schema snapshot.
  • Keep agent generation, control generation, relay capability versions, and transport profile versions separate.
  • Preserve optional-field behavior and raw forwarding of unknown envelope and payload fields.
  • When changing bulk records, keep offsets, directions, payload limits, credit windows, finish rules, and dual-port ownership aligned.
  • When changing resource observations, keep guest generation 11, relay capability version 1, query identity, and the distinction from resize outcomes aligned.
  • When changing control extensions, keep generation-one shapes stable and keep generation-two capability discovery aligned with jobs, resize, labels, and checkpoint operations.
  • When changing execution extensions, keep host-only authority out of guest payloads and preserve the distinction between physical delivery and process results.
  • When changing private restore or disk-editor contracts, keep their markers, bounded replies, and completion receipts aligned with the isolated guest helpers.
  • Keep the generation-11 schema and control wire fixtures in sync with intentional protocol changes.

Important failure modes

TriggerConsequenceGuard
A frame exceeds 4 MiB or is shorter than the fixed headerThe receiver cannot safely parse or allocate it.Check the shared length limit and minimum header before body decoding.
A bulk flag is combined with lifecycle flags or has an invalid bodyThe receiver cannot identify the data lane safely.Require the exclusive bulk flag and validate record bounds.
A message needs a newer agent generationThat operation is rejected while unrelated work can continue.Check the per-message introduction generation before sending.
A generation-11 observation lacks relay capability version 1The observation is refused before dispatch.Require both guest generation and host relay capability.
A resource observation is treated as proof that resize completedA client can report a false resource state.Combine the query-bound report with runtime, operation, target, and freshness evidence.
A generation-two control operation reaches a generation-one runtimeThe operation is unsupported or may be misrouted.Gate extensions from negotiated generation and runtime capability inventory.
A checked record has duplicate keys or trailing dataDispatch can become ambiguous or malformed input can reach host actions.Decode one complete record and validate nested records before dispatch.
A transport closes during a partial framePending requests cannot receive a complete message.Treat incomplete reads as transport failure and release pending work.
A stale runtime or job identity is usedA request can target an old runtime or miss retained output.Fence host operations with the current runtime identity and bounded cursors.
A private contract uses the wrong marker or an unbounded replyThe host can interpret incompatible or unsafe recovery data.Verify the contract marker and enforce reply bounds before use.

Key files

FileWhy to read it
crates/…/VERSIONING.mdExplains the independent agent and control generations, legacy discovery, and additive evolution rules.
crates/…/message.rsDefines the agent generation, wire names, flags, lifecycle mapping, and per-message gates.
crates/…/gen-11.jsonRecords the current frame constants and agent message introduction inventory.
crates/…/codec.rsDefines raw, typed, envelope, and bulk frame handling.
crates/…/message.rsDefines control wire names, generation-two dispatch, and operation gates.
crates/…/types.rsDefines capability records and the host resource, secret, checkpoint, and pause contracts.
crates/…/resources.rsDefines query-bound guest resource observations and the host relay capability.
crates/…/jobs.rsDefines the runtime-owned job extension and bounded output replay.
crates/…/resize.rsDefines operation-bound CPU and memory resize tracking.
crates/…/labels.rsDefines capability-probed host metadata updates.
crates/…/exec_control.rsDefines host-only execution signal delivery and its connection authority.
crates/…/exec_bindings.rsDefines host-only command origin evidence that is removed before guest delivery.
crates/…/init_observation.rsDefines optional init-selection evidence carried with readiness.
crates/…/restore_transport.rsDefines private restore readiness and freeze/thaw extensions.
crates/…/control_contract.rsPins control bytes and checks strict records, future fields, handshake limits, and additive dispatch.
crates/…/resource_observations.rsChecks resource observation generation, relay admission, identity, and terminal behavior.