Skip to main content
AgentClient is the low-level transport for talking to agentd through a running sandbox’s relay socket. For most applications, use Sandbox, exec, and fs instead. Reach for AgentClient when you are building a protocol-level integration or an SDK layer. AgentBridge wraps the same connection in concrete, FFI-shaped types for the Node, Python, and Go bindings. The client has two tiers that share one socket and one background reader task:
  • Typed methods encode and decode microsandbox protocol messages for you.
  • Raw methods move framed CBOR bytes without decoding the message body.
The raw body is the full CBOR-encoded protocol Message body (v, t, and p), not just the inner payload. The typed and raw methods reach the connection through Deref to the underlying client; everything below is callable directly on the value connect_sandbox returns.

Typical flow

use microsandbox::{
    agent,
    protocol::{
        fs::{FsOp, FsRequest, FsResponse},
        message::MessageType,
    },
};

let client = agent::connect_sandbox("dev").await?;   // 1. resolve name + connect

let response = client                                // 2. one-shot typed RPC
    .request(
        MessageType::FsRequest,
        &FsRequest {
            op: FsOp::Stat {
                path: "/etc/os-release".to_string(),
                follow_symlink: true,
            },
        },
    )
    .await?;

let fs_response: FsResponse = response.payload()?;   // 3. decode the payload
client.close().await;                                // 4. close

Module functions

agent::connect_sandbox()

async fn connect_sandbox(name: &str) -> AgentClientResult<AgentClient>
use microsandbox::agent;

let client = agent::connect_sandbox("dev").await?;
Resolve a sandbox name to its agent relay socket path and connect, using the default ten-second handshake timeout. The socket lives under the SDK’s configured runtime directory at a short, name-derived path. Sandbox names are limited to 128 UTF-8 bytes.

Parameters

name&str
Sandbox name, up to 128 UTF-8 bytes.

Returns

Connected client.

agent::connect_sandbox_with_timeout()

async fn connect_sandbox_with_timeout(name: &str, timeout: Duration) -> AgentClientResult<AgentClient>
use std::time::Duration;
use microsandbox::agent;

let client = agent::connect_sandbox_with_timeout("dev", Duration::from_secs(2)).await?;
Like connect_sandbox, but with an explicit handshake timeout instead of the ten-second default.

Parameters

name&str
Sandbox name, up to 128 UTF-8 bytes.
timeoutDuration
Maximum time to wait for the relay handshake.

Returns

Connected client.

AgentClient: static methods

AgentClient::connect()

async fn connect(sock_path: impl AsRef<Path>) -> AgentClientResult<AgentClient>
use microsandbox::agent::AgentClient;

let path = AgentClient::socket_path("dev")?;
let client = AgentClient::connect(&path).await?;
Connect to an arbitrary agent relay socket by path, using the default ten-second handshake timeout. The connection performs the relay handshake, validates the cached core.ready frame, and starts one background reader task.

Parameters

sock_pathimpl AsRef<Path>
Path to the agent relay socket.

Returns

Connected client.

AgentClient::connect_with_timeout()

async fn connect_with_timeout(sock_path: impl AsRef<Path>, timeout: Duration) -> AgentClientResult<AgentClient>
Connect to an arbitrary agent relay socket by path with an explicit handshake timeout.

Parameters

sock_pathimpl AsRef<Path>
Path to the agent relay socket.
timeoutDuration
Maximum time to wait for the relay handshake.

Returns

Connected client.

AgentClient::connect_with_deadline()

async fn connect_with_deadline(sock_path: impl AsRef<Path>, deadline: Instant) -> AgentClientResult<AgentClient>
Connect to an arbitrary agent relay socket by path with an explicit handshake deadline. The deadline bounds both handshake reads, so an accepted connection that stalls before writing the handshake bytes cannot block this call indefinitely.

Parameters

sock_pathimpl AsRef<Path>
Path to the agent relay socket.
deadlineInstant
Tokio instant by which the handshake must complete.

Returns

Connected client.

AgentClient::connect_sandbox()

async fn connect_sandbox(name: &str) -> AgentClientResult<AgentClient>
Resolve a sandbox name to its agent socket path and connect. Equivalent to the module-level agent::connect_sandbox.

Parameters

name&str
Sandbox name, up to 128 UTF-8 bytes.

Returns

Connected client.

AgentClient::connect_sandbox_with_timeout()

async fn connect_sandbox_with_timeout(name: &str, timeout: Duration) -> AgentClientResult<AgentClient>
Resolve a sandbox name to its agent socket path and connect with an explicit handshake timeout. Equivalent to the module-level agent::connect_sandbox_with_timeout.

Parameters

name&str
Sandbox name, up to 128 UTF-8 bytes.
timeoutDuration
Maximum time to wait for the relay handshake.

Returns

Connected client.

AgentClient::socket_path()

fn socket_path(name: &str) -> MicrosandboxResult<PathBuf>
use microsandbox::agent::AgentClient;

let path = AgentClient::socket_path("dev")?;
println!("{}", path.display());
Resolve a sandbox’s relay socket path without connecting. Returns the same path connect_sandbox would dial: the hashed path under the runtime directory when it fits the platform’s Unix-socket length limit, and the legacy name-derived path otherwise. Useful for talking to agentd over a raw byte transport (for example a transparent relay that splices bytes to and from the socket) instead of this frame client. The sandbox need not be running.

Parameters

name&str
Sandbox name, up to 128 UTF-8 bytes.

Returns

PathBuf
Relay socket path.

AgentClient::ensure_version_compat_for()

fn ensure_version_compat_for(t: MessageType, negotiated: u8) -> AgentClientResult<()>
use microsandbox::{agent::AgentClient, protocol::message::MessageType};

AgentClient::ensure_version_compat_for(MessageType::FsRequest, 2)?;
Check a message type against an explicit negotiated generation. The single place the rule lives, exposed for callers that hold the negotiated generation but not a live client. Returns AgentClientError::UnsupportedOperation if the type was introduced after the given generation.

Parameters

tMessageType
Protocol message type to gate.
negotiatedu8
Protocol generation to check against.

AgentClient: instance methods

client.request()

async fn request<T: Serialize>(&self, t: MessageType, payload: &T) -> AgentClientResult<Message>
use microsandbox::protocol::{
    fs::{FsOp, FsRequest, FsResponse},
    message::MessageType,
};

let response = client
    .request(
        MessageType::FsRequest,
        &FsRequest {
            op: FsOp::Stat {
                path: "/etc/os-release".to_string(),
                follow_symlink: true,
            },
        },
    )
    .await?;
let fs_response: FsResponse = response.payload()?;
Send one typed protocol message and wait for one response frame with the same correlation id. Flags are derived from the message type. Use this for one-shot RPCs such as filesystem stat or list requests. Fails fast with AgentClientError::UnsupportedOperation if the connected sandbox is too old for the message type.

Parameters

tMessageType
Protocol message type.
payload&T: Serialize
Message payload, serialized with CBOR.

Returns

Message
Decoded response message.

client.stream()

async fn stream<T: Serialize>(&self, t: MessageType, payload: &T) -> AgentClientResult<(u32, Receiver<Message>)>
use microsandbox::protocol::{exec::ExecRequest, message::MessageType};

let (id, mut rx) = client
    .stream(MessageType::ExecRequest, &ExecRequest {
        cmd: "echo".into(),
        args: vec!["hi".into()],
        env: Vec::new(),
        cwd: None,
        user: None,
        tty: false,
        rows: 24,
        cols: 80,
        rlimits: Vec::new(),
    })
    .await?;

while let Some(msg) = rx.recv().await {
    println!("{:?}", msg.t);
}
Open a typed streaming session. The returned id is the protocol correlation id. Use it with send() for follow-up messages such as stdin, resize, signal, or file data chunks. The receiver yields messages until a terminal frame is delivered or the connection closes.

Parameters

tMessageType
Protocol message type for the opening frame.
payload&T: Serialize
Opening message payload, serialized with CBOR.

Returns

(u32, Receiver<Message>)
Correlation id and a typed message receiver.

client.send()

async fn send<T: Serialize>(&self, id: u32, t: MessageType, payload: &T) -> AgentClientResult<()>
use microsandbox::protocol::{exec::ExecStdin, message::MessageType};

client.send(id, MessageType::ExecStdin, &ExecStdin { data: b"input\n".to_vec() }).await?;
Send a typed follow-up message on an existing correlation id (the id returned by stream()).

Parameters

idu32
Correlation id from the open stream.
tMessageType
Protocol message type.
payload&T: Serialize
Message payload, serialized with CBOR.

client.request_raw()

async fn request_raw(&self, flags: u8, body: Vec<u8>) -> AgentClientResult<RawFrame>
let frame = client.request_raw(flags, body).await?;
println!("id={} flags={}", frame.id, frame.flags);
Allocate a correlation id, send one raw frame with (flags, body), and wait for one raw response frame with the matching id. CBOR encoding and decoding are left to the caller.

Parameters

flagsu8
Frame flag byte.
bodyVec<u8>
CBOR-encoded protocol message body.

Returns

Raw response frame.

client.stream_raw()

async fn stream_raw(&self, flags: u8, body: Vec<u8>) -> AgentClientResult<(u32, Receiver<RawFrame>)>
Open a raw streaming session. The receiver yields raw frames for the returned correlation id until a frame with the terminal flag arrives or the receiver is dropped. Use send_raw() with the returned id to send follow-up frames.

Parameters

flagsu8
Frame flag byte for the opening frame.
bodyVec<u8>
CBOR-encoded protocol message body.

Returns

(u32, Receiver<RawFrame>)
Correlation id and a raw frame receiver.

client.send_raw()

async fn send_raw(&self, id: u32, flags: u8, body: &[u8]) -> AgentClientResult<()>
Send a raw follow-up frame on an existing correlation id (the id returned by stream_raw()).

Parameters

idu32
Correlation id from the open raw stream.
flagsu8
Frame flag byte.
body&[u8]
CBOR-encoded protocol message body.

client.ready()

fn ready(&self) -> AgentClientResult<Ready>
let ready = client.ready()?;
println!("boot {} ns", ready.boot_time_ns);
Return the decoded core.ready payload captured during the handshake (boot timings and the runtime’s self-reported version).

Returns

Ready
Decoded handshake payload.

client.ready_bytes()

fn ready_bytes(&self) -> &[u8]
Return the cached handshake core.ready frame body as CBOR bytes. Useful for bindings that want to deserialize the ready payload with their own CBOR tooling. For typed access, use ready().

Returns

&[u8]
CBOR-encoded ready frame body.

client.protocol()

fn protocol(&self) -> AgentProtocol
The agent protocol generation (wire codec) negotiated for this connection.

Returns

Codec generation: Current or LegacyV1.

client.is_legacy_protocol()

fn is_legacy_protocol(&self) -> bool
Whether this connection is using the legacy pre-0.5 protocol.

Returns

bool
true if the relay speaks the pre-0.5 protocol.

client.negotiated_version()

fn negotiated_version(&self) -> u8
The negotiated protocol generation for this connection: the lower of what this client speaks and what the sandbox advertised at handshake. This is the capability gate that drives supports() and the typed send path, and it is distinct from protocol(), which selects the wire codec.

Returns

u8
Negotiated capability generation.

client.agent_version()

fn agent_version(&self) -> &str
The runtime’s self-reported package version, taken from its core.ready frame. Empty when the runtime predates this field (an older agent), in which case fall back to the generation for diagnostics.

Returns

&str
Runtime package version, or empty if unknown.

client.supports()

fn supports(&self, t: MessageType) -> bool
use microsandbox::protocol::message::MessageType;

if client.supports(MessageType::FsRequest) {
    // safe to issue filesystem RPCs
}
Whether the connected sandbox is new enough to handle the given message type. The single source of truth for feature gating: callers that cannot gate by sending (for example the SSH/SFTP layer) consult this instead of inspecting the protocol generation directly.

Parameters

tMessageType
Protocol message type to check.

Returns

bool
true if the runtime can handle the type.

client.ensure_version_compat()

fn ensure_version_compat(&self, t: MessageType) -> AgentClientResult<()>
use microsandbox::protocol::message::MessageType;

client.ensure_version_compat(MessageType::TcpConnect)?;
Reject a message type the connected sandbox is too old to handle, against this connection’s negotiated generation. Fails before any bytes are sent, so only that one operation fails and the session continues. The typed request(), stream(), and send() methods call this internally.

Parameters

tMessageType
Protocol message type to gate.

client.close()

async fn close(self)
client.close().await;
Close the client by consuming it. Drops the writer and aborts the reader task; any in-flight requests resolve with AgentClientError::Closed. Dropping the client has the same effect.

AgentBridge

Bytes-in/bytes-out wrapper around AgentClient, with concrete, monomorphic types suitable for crossing FFI boundaries. The Node, Python, and Go bindings build on it. No generics, no consuming-self methods, no callbacks across FFI: each method takes &self and is idempotent where the underlying operation allows. CBOR (de)serialization happens entirely in the caller’s language; the bridge only moves bytes. One instance owns one Unix-socket connection; multiple concurrent streams are supported, each identified by an opaque StreamHandle.

AgentBridge::connect_sandbox()

async fn connect_sandbox(name: &str) -> AgentClientResult<AgentBridge>
Connect to a sandbox by name, resolving the socket path from SDK config. Sandbox names are limited to 128 UTF-8 bytes.

Parameters

name&str
Sandbox name, up to 128 UTF-8 bytes.

Returns

Connected bridge.

AgentBridge::connect_sandbox_with_timeout()

async fn connect_sandbox_with_timeout(name: &str, timeout: Duration) -> AgentClientResult<AgentBridge>
Connect to a sandbox by name with an explicit handshake timeout.

Parameters

name&str
Sandbox name, up to 128 UTF-8 bytes.
timeoutDuration
Maximum time to wait for the relay handshake.

Returns

Connected bridge.

AgentBridge::connect_path()

async fn connect_path(path: &str) -> AgentClientResult<AgentBridge>
Connect to an arbitrary agentd relay socket by path.

Parameters

path&str
Path to the agent relay socket.

Returns

Connected bridge.

AgentBridge::connect_path_with_timeout()

async fn connect_path_with_timeout(path: &str, timeout: Duration) -> AgentClientResult<AgentBridge>
Connect to an arbitrary agentd relay socket by path with an explicit handshake timeout.

Parameters

path&str
Path to the agent relay socket.
timeoutDuration
Maximum time to wait for the relay handshake.

Returns

Connected bridge.

bridge.request()

async fn request(&self, flags: u8, body: Vec<u8>) -> AgentClientResult<BridgeFrame>
One-shot request: send (flags, body) and wait for one response frame.

Parameters

flagsu8
Frame flag byte.
bodyVec<u8>
CBOR-encoded protocol message body.

Returns

Response frame.

bridge.send()

async fn send(&self, id: u32, flags: u8, body: Vec<u8>) -> AgentClientResult<()>
Send a follow-up frame on an existing correlation id.

Parameters

idu32
Correlation id from an open stream.
flagsu8
Frame flag byte.
bodyVec<u8>
CBOR-encoded protocol message body.

bridge.stream_open()

async fn stream_open(&self, flags: u8, body: Vec<u8>) -> AgentClientResult<(u32, StreamHandle)>
Open a streaming session. Returns the protocol correlation id (for follow-up sends via send()) and an opaque stream handle (for stream_next() and stream_close()).

Parameters

flagsu8
Frame flag byte for the opening frame.
bodyVec<u8>
CBOR-encoded protocol message body.

Returns

Correlation id and an opaque stream handle.

bridge.stream_next()

async fn stream_next(&self, handle: StreamHandle) -> AgentClientResult<Option<BridgeFrame>>
let (id, handle) = bridge.stream_open(flags, body).await?;
while let Some(frame) = bridge.stream_next(handle).await? {
    // decode frame.body with your own CBOR tooling
}
Pull the next frame from a stream. Returns None when the stream has ended (the terminal frame was already delivered, or the stream was closed or dropped).

Parameters

Handle returned by stream_open().

Returns

Option<BridgeFrame>
Next frame, or None at end of stream.

bridge.stream_close()

async fn stream_close(&self, handle: StreamHandle)
Close a stream and drop its handle. Idempotent.

Parameters

Handle returned by stream_open().

bridge.ready_bytes()

fn ready_bytes(&self) -> AgentClientResult<Vec<u8>>
The cached handshake core.ready frame body bytes (CBOR). Errors with AgentClientError::Closed if the bridge has been closed.

Returns

Vec<u8>
CBOR-encoded ready frame body.

bridge.close()

async fn close(&self)
bridge.close().await;
Close the connection. Idempotent. After close, every operation except another close returns AgentClientError::Closed.

Types

AgentClient

Returned by agent::connect_sandbox(), AgentClient::connect() · wrapped by AgentBridge

Client for communicating with agentd through a running sandbox’s relay. A newtype over the underlying microsandbox_agent_client::AgentClient; the typed and raw transport methods reach the inner client through Deref. See the static and instance method sections above.

BridgeFrame

Returned by bridge.request(), bridge.stream_next()

FFI-friendly view of a RawFrame: id, flags, body bytes.
FieldTypeDescription
idu32Correlation ID from the frame header.
flagsu8Frame flags from the frame header.
bodyVec<u8>Raw CBOR-encoded body bytes.

StreamHandle

Returned by bridge.stream_open() · used by bridge.stream_next(), bridge.stream_close()

pub type StreamHandle = u64;
Opaque handle identifying an open stream on an AgentBridge. Foreign-language wrappers reference streams by this u64 instead of owning a tokio receiver.

AgentProtocol

Returned by client.protocol()

Agent protocol generation (wire codec) spoken by a connected sandbox relay.
VariantDescription
CurrentCurrent protocol generation.
LegacyV1Pre-0.5 microsandbox relay handshake and agent protocol.

RawFrame

Returned by client.request_raw(), client.stream_raw()

A framed protocol message at the byte level. id is the protocol correlation id, flags is the frame flag byte, and body is the CBOR-encoded protocol message body. Re-exported from microsandbox::protocol::codec.
FieldTypeDescription
idu32Protocol correlation id.
flagsu8Frame flag byte.
bodyVec<u8>CBOR-encoded protocol message body.

AgentClientError

Error variant of AgentClientResult

Errors raised by AgentClient and AgentBridge.
VariantDescription
Connect { path, source }Failed to open the Unix socket connection to the relay.
Handshake(String)Handshake with the relay failed (timeout, EOF, or malformed frame).
SandboxNotFound(String)Sandbox name could not be resolved to an agent socket path.
InvalidSandboxName(String)Sandbox name failed SDK validation before socket resolution.
Io(std::io::Error)An I/O error occurred on the socket after connect.
Protocol(ProtocolError)A wire-protocol error (framing, CBOR, oversize frame).
Cbor(String)CBOR encoding or decoding failed.
InvalidPacket(String)The supplied packet did not contain exactly one complete transport frame.
UnsupportedOperation { msg_type, needs, peer }The connected sandbox’s runtime is older than the requested feature needs; restart the sandbox to update its runtime.
ReaderClosed(u32)The reader task closed before the in-flight request received its response.
ClosedThe client has been closed.
IdRangeExhaustedThe relay-assigned correlation ID range has no available IDs.
NotImplemented(&'static str)The operation is not implemented yet.

AgentClientResult

Returned by most AgentClient and AgentBridge methods

pub type AgentClientResult<T> = Result<T, AgentClientError>;
Result alias for agent client operations. The error is AgentClientError.