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 / protocol-messages-and-compatibility

Protocol messages and compatibility

The agent protocol is the shared contract between the host and the guest agent. It carries startup state, command execution, filesystem access, TCP streams, health signals, workload control, and errors over framed CBOR messages. This page gives the message model and the rules that let a newer host work with an older sandbox.

Read API protocol for the parent overview of the host-to-guest interface.

Message envelope

The crates/…/message.rs envelope puts a protocol generation, a wire message type, and a CBOR payload together. A correlation ID and lifecycle flags sit outside that payload so a relay can route frames without decoding the full message. CBOR means the compact binary object format used for the envelope and each typed payload.

Wire layout

The transport uses one length-prefixed frame for each message. The fixed header stays stable while the message payload evolves.

flowchart LR
    A[Length prefix] --> B[Correlation ID]
    B --> C[Lifecycle flags]
    C --> D[CBOR envelope]
    D --> E[Generation v]
    D --> F[Wire type t]
    D --> G[CBOR payload p]

The length covers the binary header and CBOR body. The current frame limit is 4 MiB. A frame can be handled as a raw frame by a relay or decoded into a typed message by an SDK. id ties requests, responses, and stream chunks to one session. The terminal flag marks the last frame for that ID. The session-start flag marks a new exec, filesystem, or TCP session. The shutdown flag marks a request to stop the sandbox. References: crates/…/codec.rs• L1-6, crates/…/codec.rs• L19-23, crates/…/message.rs• L11-78

Correlation and lifecycle flags

The protocol treats a correlation ID as the identity of a request or stream. A one-shot operation ends with a terminal response, while a stream keeps the same ID for data and control messages until a terminal event arrives.

FlagMeaningMain message examples
TerminalNo more messages for the correlation IDcore.exec.exited, core.fs.response, core.tcp.closed
Session startOpens a new operation or streamcore.exec.request, core.fs.request, core.tcp.connect
ShutdownRequests sandbox shutdowncore.shutdown
BulkSelects a raw data record body for supported generation-8 streamsBulk data records

Relays use these hints without reading the CBOR body. A message type and its flags must agree. The bulk flag is an exclusive body selector, not a lifecycle flag. References: crates/…/message.rs• L14-35, crates/…/message.rs• L345-362

Message families

The wire type names group messages by the capability they serve. Each family uses the same envelope but has its own request, progress, result, and failure pattern.

Core messages

Core messages manage the agent session and host-level sandbox state rather than one user operation. core.ready tells the host that the guest agent is ready and carries boot timing plus optional capability data. Init messages pass the resolved default user to the host and acknowledge setup. Other core messages request shutdown, synchronize the guest wall clock, report a relay client disconnect, or maintain session state.

Generation 9 adds workload control and root-disk messages. A host can identify a freeze attempt, receive a confirmed boundary with absolute input credit, release the freeze in continue or restore mode, and receive the thaw result. The same core family also supports root-disk preflight, growth, and state reporting. These messages let checkpoint and storage flows coordinate with the guest without treating a transport counter or a disk target as a fresh resource grant. References: crates/…/core.rs• L11-26, crates/…/core.rs• L32-81, crates/…/core.rs• L122-230, crates/…/message.rs• L101-191

core.ready is a key input to connection setup: the host reads it before it starts normal requests. Its product version and optional transport capabilities describe the running agent, while the protocol generation in the envelope remains the compatibility value. Older peers can omit the newer optional fields. References: crates/…/core.rs• L32-81, crates/…/core.rs• L325-373

Bootstrap messages

core.bootstrap is a one-shot host-to-guest message for a new guest boot. It supplies the guest setup that must exist before normal agent initialization, such as root assembly, mounts, network settings, default execution context, resource limits, security policy, and optional init handoff.

The bootstrap contract also carries an initialization-failure acknowledgment and supports both directory and file mounts. Environment values are guest-visible data, so secret entries use placeholders rather than host secret values. Bootstrap is not a reconnect mechanism: an already-running guest continues with the normal handshake and does not receive a later bootstrap frame. References: crates/…/bootstrap.rs• L13-81, crates/…/bootstrap.rs• L83-126, crates/…/bootstrap.rs• L148-214, crates/…/bootstrap.rs• L271-310, crates/…/VERSIONING.md• L60-64

Execution messages

Execution messages turn a command request into a live process session. The host sends the command and its execution context. The guest confirms start, streams standard output and standard error, and then reports either a process exit or a start failure. The host can send stdin, resize a PTY, or signal the process while the session is active. Generation 10 adds explicit output and stdin credit messages so execution streams can return consumed capacity to their sender.

An exit means the program ran and returned a code. A failed start means the program did not run; the payload gives a coarse cause and diagnostic context. An stdin write error is non-terminal, so later output and the final process result can still arrive. References: crates/…/exec.rs• L11-48, crates/…/exec.rs• L63-143, crates/…/exec.rs• L193-207, crates/…/message.rs• L193-244

Filesystem messages

Filesystem messages provide request and stream semantics for guest paths and open handles. A request can inspect or change paths, list directories, manage handles, or read and write file data. Simple operations return a result in core.fs.response; streaming operations send core.fs.data chunks before the terminal response.

Host-provided single-file mounts use a synthetic one-entry filesystem before agentd binds the file to its guest path. This keeps sibling files out of the guest-visible mount while preserving the file mount contract. The response separates success from result data. The data can be metadata, a directory listing, a handle, or a resolved path. An unsuccessful response carries an error string. File data uses bounded chunks so a stream stays within the frame limit. References: crates/…/fs.rs• L9-12, crates/…/fs.rs• L18-178, crates/…/fs.rs• L227-307, crates/…/message.rs• L246-256, crates/…/lib.rs• L217-240

Heartbeat and activity data

Heartbeat data gives the host a view of guest liveness and sandbox activity. It is written to /.msb/heartbeat.json, rather than sent as a normal message family. The record contains heartbeat and activity sequence numbers, timestamps, active session counts, and cumulative byte or message counters.

The core reachability messages complement this file. core.ping checks that the agent can respond, while core.touch records explicit sandbox activity without opening an exec, filesystem, or TCP session. Ping traffic does not refresh the idle timer; a successful touch returns the new activity sequence. References: crates/…/heartbeat.rs• L10-54, crates/…/core.rs• L93-120

TCP messages

TCP messages represent a byte stream opened from inside the guest. The host requests a destination, the guest confirms or rejects the connection, and both sides exchange data on the same correlation ID. EOF closes one write half; close and closed messages finish the session.

TCP connection failure is terminal and carries a human-readable reason. Data direction is represented by the sender of each core.tcp.data message, so the protocol can carry traffic in both directions without a second channel. References: crates/…/tcp.rs• L9-48, crates/…/message.rs• L258-284

Error messages

core.error reports a recoverable protocol error tied to a correlation ID. Its machine-readable kind identifies malformed messages, unknown message types, unsupported generations, invalid flags, invalid payloads, invalid sessions, unavailable capabilities, or failed guest initialization. Optional details identify the offending type, the initialization cause, or the workload-freeze disposition.

Errors that prevent safe frame parsing are different. An oversized frame, a frame too short for its header, an incomplete stream, or a CBOR decode failure belongs to transport or decoding failure handling. Such a failure can close the transport instead of producing a normal core.error response. References: crates/…/core.rs• L232-323, crates/…/error.rs• L9-48

Compatibility contract

Compatibility exists because the host can be upgraded while a sandbox keeps an older guest agent. The protocol uses one generation number per connection. The current Rust protocol generation is 10, and each message type records the generation that introduced it. References: crates/…/message.rs• L11-12, crates/…/message.rs• L365-385

Generation negotiation

At connection time, the host reads the relay's ID range and the cached core.ready frame. It verifies that the frame is a ready message, then sets the negotiated generation to the lower of the host generation and the generation echoed by the guest. The host uses that value as a capability gate for later sends.

sequenceDiagram
    participant H as Host
    participant R as Relay
    participant G as Guest agent
    H->>R: Connect
    R-->>H: ID range and core.ready
    Note over H: negotiated generation = lower(host, guest)
    H->>R: Send supported request
    R->>G: Route by correlation ID
    G-->>R: Response or stream
    R-->>H: Matching frames

If a message needs a newer generation, the host rejects that operation before sending bytes. The connection and other supported operations remain usable. A legacy pre-0.5 connection supports the generation-1 execution baseline but does not support filesystem streaming or newer families. References: packages/…/client.rs• L83-114, packages/…/client.rs• L568-653, packages/…/client.rs• L384-411, crates/…/VERSIONING.md• L39-58

Message availability

Availability is based on the introducing generation of the message type. The baseline core and execution types require generation 1. Filesystem messages require generation 2. TCP messages require generation 4. core.error requires generation 5. Reachability and activity messages require generation 6. Bootstrap requires generation 7. Raw bulk control messages require generation 8. Workload control and root-disk messages require generation 9. Execution output and stdin credit messages require generation 10.

The host applies the same rule to typed requests, streams, and follow-up messages. Code that must decide before sending can use the same availability predicate. It must not infer support from the product version string in core.ready. References: crates/…/message.rs• L365-435, crates/…/gen-10.json• L20-204, packages/…/client.rs• L419-460

Field evolution

New fields in an existing payload must be optional and must have a safe default. An older peer ignores an unknown field, while a newer peer fills a missing field with its default. This rule keeps a field addition from turning a whole connection into a failure.

A field whose meaning changes is not an additive change. It needs a separate compatibility plan. A new message type is also a capability change: add it without reusing an old wire name, assign its introducing generation, and gate it for older peers. Unknown workload failure details do not authorize a recovery action; callers need the explicit disposition. References: crates/…/schema_snapshot.rs• L94-143, crates/…/core.rs• L274-323, crates/…/VERSIONING.md• L104-113

Schema snapshots

Schema snapshots preserve the protocol surface that controls compatibility. Each checked-in crates/…/gen-<N>.json file records the generation, frame constants, flag bits, bulk limits, and every message wire string with its introducing generation. The generation-10 snapshot records the current surface, including the execution credit messages. The snapshot test renders the live surface in a stable order and compares it with the current file.

Prior snapshots are frozen. The append-only check requires every earlier message type to remain present with the same introducing generation. An intended surface change must update the current snapshot and review the diff; it must not rewrite an older generation's record. The snapshot is a compatibility ledger, not a replacement for reviewing payload field changes. References: crates/…/schema_snapshot.rs• L1-16, crates/…/schema_snapshot.rs• L30-56, crates/…/schema_snapshot.rs• L66-143, crates/…/gen-10.json• L1-207

Cross-language surfaces

The Rust protocol crate is the current reference surface for generation 10. The TypeScript client at packages/…/message.ts declares generation 5 and does not list the later reachability, bootstrap, bulk, workload, or execution credit types. It therefore provides a subset of the current generation-10 type contract, not a full generation-10 type contract.

When a binding sends a message, its declared wire names, generation, flags, and availability table must agree with the peer contract. A binding that is behind the shared surface must reject or avoid newer types rather than label them as supported. References: packages/…/message.ts• L1-42, packages/…/message.ts• L147-199, crates/…/gen-10.json• L20-204, crates/…/VERSIONING.md• L45-58

Change checklist

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

  • Add a new MessageType only with a new wire name, an introducing generation, and the matching current-generation snapshot.
  • Keep the binary frame header stable. A relay depends on the length, correlation ID, and flags being readable without CBOR parsing.
  • When adding a payload field, make it optional with a safe default in every decoding surface that must cross a version gap.
  • Update each language binding's wire-name union, generation constant, flag map, and availability map as one contract.
  • Keep terminal and session-start flags aligned with the lifecycle of the new message. A wrong flag can strand a request or stream in a relay.
  • Keep the 4 MiB frame limit and filesystem or bulk record budget compatible. A new payload must not make its normal frame exceed the limit.
  • Preserve old schema snapshots. A generation bump writes a new snapshot; it does not revise a prior generation. Generation 10 adds the execution output and stdin credit types.
  • Treat workload freeze counters and credit as cumulative state. Do not turn a restore into a fresh input window.

Important failure modes

TriggerConsequenceGuard
Host sends a message above the negotiated generationThe requested feature fails before the guest sees it; other sessions can continueGate every send with the message's introducing generation
A binding uses a wire name or flag map that differs from the shared surfaceThe peer rejects the message or a relay misreads its lifecycleKeep wire strings, flags, and snapshots in sync across bindings
A terminal response is missing its terminal flagThe client can keep waiting for a stream that has already endedDerive flags from the message type and review lifecycle changes
A frame exceeds 4 MiB or is shorter than the binary headerThe codec rejects it; no typed protocol error is safeBound payload and stream records before framing
A new required payload field reaches an older peerThe old decoder can fail instead of ignoring the additionAdd fields as optional with defaults
A prior schema snapshot is removed or its introduction generation changesCompatibility history no longer proves append-only evolutionKeep prior snapshots frozen and run the snapshot checks
A restore treats frozen absolute credit as a new windowThe guest can accept duplicate input or exceed its retained-data boundCarry cumulative positions and grants across freeze and restore
The host accepts an unknown workload failure disposition as safeIt may report a workload as running when recovery is still requiredTreat unknown dispositions as non-authorizing and require confirmed thaw

Key files

FileWhy to read it
crates/…/message.rsDefines the envelope, wire names, lifecycle flags, bulk marker, execution credit messages, and per-message generation rules.
crates/…/codec.rsShows the stable length-prefixed frame and the raw-frame boundary used by relays.
crates/…/core.rsDefines readiness, init, reachability, workload control, root-disk, and recoverable error payloads.
crates/…/bootstrap.rsDefines the one-shot guest startup configuration contract.
crates/…/exec.rsDefines command sessions, output streams, process results, start failures, and execution flow control.
crates/…/fs.rsDefines filesystem operations, handles, results, and data streaming.
crates/…/heartbeat.rsDefines the guest liveness and activity record.
crates/…/tcp.rsDefines guest TCP connection and stream lifecycle messages.
crates/…/lib.rsDefines shared channel and mount constants that connect protocol setup with the guest runtime.
crates/…/schema_snapshot.rsEnforces the checked-in compatibility surface and append-only history.
crates/…/gen-10.jsonGives the current generation's frozen frame, bulk, and message surface.
crates/…/VERSIONING.mdExplains the version negotiation and evolution contract in contributor detail.
packages/…/client.rsShows handshake negotiation and the pre-send capability gate used by the host client.
packages/…/message.tsShows the TypeScript binding's current message and compatibility surface.