Parameters
ctxcontext.ContextnamestringReturns
Parameters
ctxcontext.ContextpathstringReturns
Parameters
namestringReturns
Returned by ConnectAgentSandbox() · ConnectAgentPath()
Low-level client for raw agent frames. #### c.Request() ```go theme={null} func (c *AgentClient) Request(ctx context.Context, flags uint8, body []byte) (*RawFrame, error) ```Parameters
ctxcontext.Contextflagsuint8FlagSessionStart.body\[]byteReturns
Parameters
ctxcontext.Contextflagsuint8FlagSessionStart.body\[]byteReturns
Parameters
ctxcontext.Contextiduint32flagsuint8body\[]byteReturns
Returns
core.ready frame body.Returns
Parameters
ctxcontext.ContextReturns
Returned by Stream()
An open raw agent streaming session. Drive it by calling [`Next()`](#s-next) until it returns `nil`, which happens after a frame carrying [`FlagTerminal`](#flagterminal) or when the underlying stream is exhausted. #### s.Next() ```go theme={null} func (s *AgentStream) Next(ctx context.Context) (*RawFrame, error) ```Parameters
ctxcontext.ContextReturns
nil at EOF.Returns
Parameters
ctxcontext.ContextReturns
Returned by Request() · yielded by Next()
A raw protocol frame. `Body` is the CBOR-encoded `Message` body (`v`, `t`, `p`) as it appeared on the wire; decode it with a CBOR library such as `fxamacker/cbor`. | Field | Type | Description | | - | - | - | | ID | `uint32` | Correlation id from the frame header | | Flags | `uint8` | Frame flags (`FlagTerminal`, `FlagSessionStart`, ...) | | Body | `[]byte` | Raw CBOR-encoded body bytes | # Execution Source: https://docs.microsandbox.dev/sdk/go/execution Run sandbox commands and stream their output with the Go SDK. Non-zero exit codes are returned in [`ExecOutput`](#execoutput), not as Go errors. See [Commands](/sandboxes/commands) for usage examples. ## Sandbox The exec entry points live on [`*Sandbox`](/sdk/go/sandbox#sandbox). #### sb.Exec() ```go theme={null} func (s *Sandbox) Exec(ctx context.Context, cmd string, args []string, opts ...ExecOption) (*ExecOutput, error) ```Parameters
ctxcontext.Contextcmdstringargs\[]stringnil.opts...ExecOptionReturns
Parameters
ctxcontext.Contextcommandstring-c.opts...ExecOptionReturns
Parameters
ctxcontext.Contextcmdstringargs\[]stringnil.opts...ExecOptionReturns
Parameters
ctxcontext.Contextcommandstring-c.opts...ExecOptionReturns
Returned by sb.ExecStream() · sb.ShellStream()
A handle to a running streaming execution and its events. A configured streaming timeout is enforced by the SDK even when the caller is not reading output. At expiry, the SDK waits for process startup before sending SIGKILL. Waiting or collecting reports `ErrExecTimeout` after the guest confirms exit; cancelling a pending wait does not cancel the deadline. Raw event readers receive the actual exit event. If termination cannot be delivered, the SDK reports a separate error without claiming the process exited. The SDK connection must remain open for this client-owned deadline to run. #### h.ID() ```go theme={null} func (h *ExecHandle) ID() (string, error) ``` Return the unique identifier for this exec session, assigned by the guest agent. Useful for correlating log entries or referencing the session from external tooling.Returns
Returns
nil if unavailable.Parameters
ctxcontext.ContextReturns
Parameters
ctxcontext.ContextReturns
Parameters
ctxcontext.ContextReturns
Parameters
ctxcontext.ContextParameters
ctxcontext.Contextsignalintint(syscall.SIGTERM).Parameters
ctxcontext.Contextrowsuint16colsuint16Returned by sb.Exec() · sb.Shell() · h.Collect()
Collected output and exit status. Non-zero exit codes are results, not Go errors. #### out.Stdout() ```go theme={null} func (e *ExecOutput) Stdout() string ``` Captured standard output as a string.Returns
Returns
Returns
Returns
Returns
-1.Returns
true if ExitCode() is 0.Returned by h.TakeStdin()
```go theme={null} type ExecSink = ffi.ExecSink ``` A write-only pipe to a running process's stdin. Implements `io.WriteCloser`. #### sink.Write() ```go theme={null} func (sk *ExecSink) Write(p []byte) (int, error) ```Parameters
p\[]byteReturns
Parameters
ctxcontext.Contextp\[]byteReturns
Parameters
pathstringParameters
dtime.DurationParameters
enabledbooltrue to allocate a pseudo-terminal.Parameters
userstringParameters
envmap\[string]stringReturned by h.Recv()
One event from a streaming exec session. [`Kind`](#execeventkind) identifies which fields are populated. | Field | Type | Description | | - | - | - | | `Kind` | [`ExecEventKind`](#execeventkind) | Identifies which fields are populated | | `PID` | `uint32` | Guest process id, set on `ExecEventStarted` | | `Data` | `[]byte` | Chunk of stdout or stderr, set on `ExecEventStdout` / `ExecEventStderr` | | `ExitCode` | `int` | Process exit code, set on `ExecEventExited` | | `Failure` | [`*ExecFailure`](#execfailure) | Failure detail, set on `ExecEventFailed` and `ExecEventStdinError` | ### ExecEventKindField of ExecEvent
```go theme={null} type ExecEventKind = ffi.ExecEventKind ``` Identifies what an [`ExecEvent`](#execevent) carries. | Constant | Description | | - | - | | `ExecEventStarted` | Sent once when the guest process starts; `PID` is valid | | `ExecEventStdout` | A chunk of stdout; in TTY mode, carries the combined terminal output stream. `Data` is valid | | `ExecEventStderr` | A chunk of stderr; not emitted separately in TTY mode. `Data` is valid | | `ExecEventExited` | The process exited; `ExitCode` is valid | | `ExecEventFailed` | The user program never started (binary missing, permission denied, ...); `Failure` is valid and `ExitCode` is not meaningful | | `ExecEventStdinError` | A stdin write failed; `Failure` is valid. Non-terminal: the process may still exit normally | | `ExecEventDone` | All events have been consumed | ### ExecFailureField of ExecEvent
```go theme={null} type ExecFailure = ffi.ExecFailure ``` Structured detail about a failed-to-start exec, populated on `ExecEventFailed` and `ExecEventStdinError`. See [Error Handling](/sdk/errors#spawn-time-exec-failures) for the kinds it carries (`not_found`, `permission_denied`, etc.) and how to branch on them. | Field | Type | Description | | - | - | - | | `Kind` | `string` | Failure category, e.g. `not_found`, `permission_denied` | | `Errno` | `*int` | Underlying errno, if known | | `ErrnoName` | `string` | Symbolic errno name, if known | | `Message` | `string` | Human-readable failure message | | `Path` | `string` | Offending path, if applicable | ### ExecConfigPopulated by ExecOption
Configures a single [`Exec`](#sb-exec) or [`ExecStream`](#sb-execstream) call. Most callers set fields through the `WithExec*` functional options; `ExecConfig` is exported for parity with the other SDKs' config types. | Field | Type | Description | | - | - | - | | `Cwd` | `string` | Working directory inside the guest | | `Timeout` | `time.Duration` | Kill the process after this duration; sub-second precision is rounded up | | `StdinPipe` | `bool` | Enable a stdin pipe; required for [`TakeStdin`](#h-takestdin) | | `TTY` | `bool` | Allocate a pseudo-terminal; default `false` | | `User` | `string` | Guest user (UID or name) | | `Env` | `map[string]string` | Per-command environment variables | ### ExecOptionAccepted by sb.Exec() · sb.Shell() · sb.ExecStream() · sb.ShellStream()
```go theme={null} type ExecOption func(*ExecConfig) ``` A functional option that mutates an [`ExecConfig`](#execconfig). Construct them with the `WithExec*` functions below. ## Managed jobs Run and reconnect to background commands. See [Background jobs](/sandboxes/commands#background-jobs) for lifecycle, retention, and runtime limits. #### sb.ExecDetached() ```go theme={null} func (s *Sandbox) ExecDetached(ctx context.Context, cmd string, args []string, opts ...JobExecOption) (*Job, error) ``` Start a job after confirming guest startup. Accepts existing `ExecOption` values and the job options below. Stdin defaults to a retained pipe.Parameters
ctxcontext.Contextpathstring"/app/config.json".Returns
Parameters
ctxcontext.ContextpathstringReturns
Parameters
ctxcontext.Contextpathstringdata\[]byteParameters
ctxcontext.ContextpathstringcontentstringParameters
ctxcontext.ContextpathstringReturns
Parameters
ctxcontext.ContextpathstringReturns
Parameters
ctxcontext.ContextpathstringParameters
ctxcontext.ContextpathstringParameters
ctxcontext.ContextpathstringParameters
ctxcontext.ContextsrcstringdststringParameters
ctxcontext.ContextsrcstringdststringParameters
ctxcontext.ContextpathstringReturns
true if the path exists.Parameters
ctxcontext.ContexthostPathstringguestPathstringParameters
ctxcontext.ContextguestPathstringhostPathstringParameters
ctxcontext.ContextpathstringReturns
Parameters
ctxcontext.ContextpathstringReturns
Close(ctx) it to finalize.Returned by ReadStream()
An open streaming read from a guest file. Must be closed with `Close` when done. #### readStream.Recv() ```go theme={null} Recv(ctx context.Context) ``` Receive the next chunk; returns `(nil, nil)` at EOFReturns
`([]byte, error)` #### readStream.WriteTo() ```go theme={null} WriteTo(w io.Writer) ``` Drain the stream into `w` using `context.Background()`; implements `io.WriterTo`Returns
`(int64, error)` #### readStream.CopyTo() ```go theme={null} CopyTo(ctx context.Context, w io.Writer) ``` Drain into `w` honoring `ctx` for per-chunk cancellationReturns
`(int64, error)` #### readStream.Close() ```go theme={null} Close() ``` Release the read stream handleReturns
`error` On a write error or partial write, `WriteTo` and `CopyTo` return the partial byte count and leave the stream open so you can recover; close it explicitly in either case. ## FsWriteStreamReturned by WriteStream()
An open streaming write to a guest file. Must be closed with `Close(ctx)` to finalize the write. #### writeStream.Write() ```go theme={null} Write(p []byte) ``` Send a chunk; implements `io.Writer`, uses `context.Background()` internallyReturns
`(int, error)` #### writeStream.WriteCtx() ```go theme={null} WriteCtx(ctx context.Context, data []byte) ``` Send a chunk with explicit context controlReturns
`error` #### writeStream.Close() ```go theme={null} Close(ctx context.Context) ``` Send the EOF marker and wait for the guest to confirm; must be called to complete the writeReturns
`error` ## Types ### FsEntryReturned by List()
A single directory listing entry. | Field | Type | Description | | - | - | - | | Path | `string` | File path | | Kind | [`FsEntryKind`](#fsentrykind) | Entry type | | Size | `int64` | File size in bytes | | Mode | `uint32` | Unix permission bits | ### FsEntryKindUsed by FsEntry.Kind
Classifies a directory listing entry. Defined as `type FsEntryKind string`. | Constant | Value | Description | | - | - | - | | `FsEntryKindFile` | `"file"` | Regular file | | `FsEntryKindDirectory` | `"directory"` | Directory | | `FsEntryKindSymlink` | `"symlink"` | Symbolic link | | `FsEntryKindOther` | `"other"` | Other entry type | ### FsStatReturned by Stat()
Detailed file metadata. | Field | Type | Description | | - | - | - | | Path | `string` | File path | | Size | `int64` | File size in bytes | | Mode | `uint32` | Unix permission bits | | ModTime | `time.Time` | Last modified timestamp; zero value if the guest did not report one | | IsDir | `bool` | Whether the path is a directory | # Images Source: https://docs.microsandbox.dev/sdk/go/images Inspect and manage the local OCI image cache with the Go SDK.Parameters
ctxcontext.Contextreferencestring"python:3.12".Returns
ErrImageNotFound when the reference is not cached.Parameters
ctxcontext.ContextReturns
Parameters
ctxcontext.Contextreferencestring"python:3.12".Returns
ErrImageNotFound when the reference is not cached.Parameters
ctxcontext.Contextreferencestringforcebooltrue, remove even if sandboxes still reference it.Returns
ErrImageInUse when in use and force is false.Parameters
ctxcontext.ContextReturns
Parameters
ctxcontext.ContextinputPathstringtags...stringReturns
Parameters
ctxcontext.Contextreferences\[]string"python:3.12".outputPathstringformatImageArchiveFormatImageArchiveDocker (default; "" behaves the same) or ImageArchiveOCI.Returns
ErrImageNotFound when any reference is not cached.Returned by Image.Get() · Image.List()
A metadata handle for a cached OCI image. #### h.Reference() ```go theme={null} func (h *ImageHandle) Reference() string ``` The image reference, e.g. `"docker.io/library/python:3.12"`.Returns
Returns
Returns
Returns
Returns
Returns
nil.Returns
Returns
Parameters
ctxcontext.Contextforcebooltrue, remove even if sandboxes still reference it.Returns
ErrImageInUse when in use and force is false.Parameters
ctxcontext.ContextReturns
Returned by Image.Inspect() · Inspect()
Bundles an [`ImageHandle`](#imagehandle) (embedded, so all its accessors are promoted) with the parsed OCI config and layer list. ```go theme={null} type ImageDetail struct { *ImageHandle Config *ImageConfig Layers []ImageLayer } ``` | Field | Type | Description | | - | - | - | | `*ImageHandle` | [`*ImageHandle`](#imagehandle) | Embedded metadata handle (accessors promoted) | | Config | [`*ImageConfig`](#imageconfig) | Parsed OCI config block | | Layers | `[]`[`ImageLayer`](#imagelayer) | Layers in manifest order | ### ImageConfigUsed by ImageDetail.Config
The parsed OCI config block. | Field | Type | Description | | - | - | - | | Digest | `string` | Config blob digest | | Env | `[]string` | Environment variables (`KEY=VALUE`) | | Cmd | `[]string` | Default command | | Entrypoint | `[]string` | Entrypoint | | WorkingDir | `string` | Working directory | | User | `string` | Default user | | Labels | `map[string]string` | OCI labels | | StopSignal | `string` | Stop signal | ### ImageLayerUsed by ImageDetail.Layers
One layer of an image manifest. | Field | Type | Description | | - | - | - | | DiffID | `string` | Uncompressed layer diff ID | | BlobDigest | `string` | Compressed blob digest | | MediaType | `string` | Layer media type | | CompressedSizeBytes | `*int64` | Compressed size in bytes, or `nil` | | ErofsSizeBytes | `*int64` | EROFS size in bytes, or `nil` | | Position | `int32` | Index in the layer stack | ### ImagePruneReportReturned by Image.Prune()
Summarizes the artifacts removed by [`Image.Prune`](#image-prune). | Field | Type | Description | | - | - | - | | ImageRefsRemoved | `uint32` | Image references removed | | ManifestsRemoved | `uint32` | Manifests removed | | LayersRemoved | `uint32` | Layers removed | | FsmetaRemoved | `uint32` | Fsmeta files removed | | VMDKRemoved | `uint32` | VMDK files removed | | BytesReclaimed | `*uint64` | Bytes reclaimed, or `nil` when unknown | ### ImageArchiveFormatUsed by Image.Save()
Selects the archive layout written by [`Image.Save`](#image-save). ```go theme={null} type ImageArchiveFormat string ``` | Constant | Value | Description | | - | - | - | | `ImageArchiveDocker` | `"docker"` | `docker save` compatible archive, loadable with `docker load` (the default; the empty string means the same) | | `ImageArchiveOCI` | `"oci"` | OCI Image Layout archive | # Networking Source: https://docs.microsandbox.dev/sdk/go/networking Configure sandbox network policies with the Go SDK. See [Networking](/networking/overview) for network policies, DNS, TLS, and port publishing. ## Functions #### m.WithNetwork() ```go theme={null} func WithNetwork(net *NetworkConfig) SandboxOption ```Parameters
Returns
Parameters
portsmap\[uint16]uint16Returns
Parameters
portsmap\[uint16]uint16Returns
Parameters
bindings...PortBindingReturns
Returns
Returns
Returns
Returns
Returns
[`PolicyRule`](#policyrule) #### Rule.DenyDNS() ```go theme={null} Rule.DenyDNS() ``` Deny gateway DNS over UDP and TCP port 53.Returns
[`PolicyRule`](#policyrule) ```go theme={null} network := m.NetworkPolicy.FromProfiles(m.NetworkProfilePublic) network.Rules = append([]m.PolicyRule{m.Rule.DenyDNS()}, network.Rules...) ```Custom rules
Build a custom firewall by populating [`NetworkConfig.Rules`](#networkconfig). Rules are evaluated **first-match-wins** per direction; `DefaultEgress` and `DefaultIngress` set the fall-through action. A broad rule placed before a narrow one swallows it, so put specific rules first.Destination groups
Used by PolicyRule.Destination
The `Destination` field on [`PolicyRule`](#policyrule) accepts these well-known group names alongside literal CIDRs and domains. A domain prefixed with `.` becomes a suffix match: `.example.com` matches `api.example.com` but not `example.com`. | Value | Description | | - | - | | `"public"` | Every address not in any other group | | `"private"` | Private/RFC 1918 addresses + ULA + CGN (`10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `100.64.0.0/10`, `fc00::/7`) | | `"loopback"` | Loopback addresses (`127.0.0.0/8`, `::1`); the **guest's own** loopback, not the host. See [Reaching the host](/networking/overview#reaching-the-host) | | `"link-local"` | Link-local addresses (`169.254.0.0/16`, `fe80::/10`) excluding metadata | | `"metadata"` | Cloud metadata endpoints (`169.254.169.254`) | | `"multicast"` | Multicast addresses (`224.0.0.0/4`, `ff00::/8`) | | `"host"` | The host machine, reached via `host.microsandbox.internal`. The right group for "let the sandbox reach my host's localhost", not `"loopback"` | ## Types ### NetworkConfigUsed by WithNetwork() · returned by NetworkPolicy
```go theme={null} type NetworkConfig struct { Rules []PolicyRule DefaultEgress PolicyAction DefaultIngress PolicyAction DenyDomains []string DenyDomainSuffixes []string DNS *DNSConfig DNSRebindProtection *bool TLS *TLSConfig DisableStrict bool Ports map[uint16]uint16 PortBindings []PortBinding TCPAcceptQueueSize *uint32 IPv4Pool string IPv6Pool string MaxConnections *uint MaxTCPConnections *uint MaxUDPConnections *uint RateLimiter *NetworkRateLimiterConfig SecretViolationAction ViolationAction TrustHostCAs *bool HTTP *HTTPConfig } ``` The full network stack configuration passed via [`WithNetwork`](#m-withnetwork). | Field | Type | Description | | - | - | - | | Rules | `[]`[`PolicyRule`](#policyrule) | Ordered custom rules (first match wins) | | DefaultEgress | [`PolicyAction`](#policyaction) | Fall-through action for outbound when no rule matches. Defaults to `"deny"` | | DefaultIngress | [`PolicyAction`](#policyaction) | Fall-through action for inbound when no rule matches. Defaults to `"allow"` | | DenyDomains | `[]string` | Exact domain names to refuse DNS resolution for | | DenyDomainSuffixes | `[]string` | Domain suffixes (e.g. `.ads`) to block, including the apex and any subdomain | | DNS | [`*DNSConfig`](#dnsconfig) | In-VM DNS proxy settings | | DNSRebindProtection | `*bool` | Legacy convenience for `DNS.RebindProtection`. When `DNS` is also set, the nested value wins | | TLS | [`*TLSConfig`](#tlsconfig) | Transparent TLS interception proxy settings | | DisableStrict | `bool` | Opt out of strict hostname policy enforcement. By default, hostname allows require inspectable request authority: plain HTTP exposes `Host`; HTTPS requires TLS interception that is not bypassed | | Ports | `map[uint16]uint16` | Host to guest TCP port mappings bound to `127.0.0.1` | | PortBindings | `[]`[`PortBinding`](#portbinding) | Host to guest mappings with explicit bind addresses | | TCPAcceptQueueSize | `*uint32` | Accept-queue depth for published TCP port listeners, 1 to 2147483647. `nil` keeps the default, 1,024; the host kernel caps it at its own `somaxconn` (4,096 by default on Linux, 128 on macOS) | | IPv4Pool | `string` | Pool used to derive per-sandbox `/30` guest subnets. Defaults to `172.16.0.0/12` | | IPv6Pool | `string` | Pool used to derive per-sandbox `/64` guest prefixes. Defaults to `fd42:6d73:62::/48` | | NAT64Prefixes | `[]string` | NAT64 `/96` prefixes for policy classification. Defaults to `64:ff9b::/96` | | MaxTCPConnections | `*uint` | TCP connection cap; defaults to unlimited for single-tenant and 1,024 for multi-tenant; zero means unlimited | | MaxConnections | `*uint` | Deprecated TCP alias; cannot be combined with MaxTCPConnections | | MaxUDPConnections | `*uint` | UDP relay session cap; defaults to unlimited for single-tenant and 1,024 for multi-tenant; zero means unlimited. At capacity, the least recently active session is evicted. | | RateLimiter | [`*NetworkRateLimiterConfig`](#networkratelimiterconfig) | Rate limits grouped by direction. `nil` means unlimited | | SecretViolationAction | [`ViolationAction`](/sdk/go/secrets#violationactionstring-enum) | Sandbox-wide action when a secret is sent to a disallowed host. Per-secret overrides via `SecretEntry.ViolationAction` | | TrustHostCAs | `*bool` | Ship the host's extra CA bundles into the guest. Opt-in for corporate MITM proxies whose gateway CA is unknown to the guest's stock bundle | | HTTP | `*HTTPConfig` |Used by NetworkConfig.Rules
```go theme={null} type PolicyRule struct { Action PolicyAction Direction PolicyDirection Destination string Protocol PolicyProtocol Protocols []PolicyProtocol Port string Ports []string } ``` A single firewall rule. Ingress rules carrying ICMP protocols are rejected at sandbox creation, since the host has no inbound ICMP path; use `PolicyDirectionEgress` for ICMP. | Field | Type | Description | | - | - | - | | Action | [`PolicyAction`](#policyaction) | `allow` or `deny` | | Direction | [`PolicyDirection`](#policydirection) | Direction this rule considers. `PolicyDirectionAny` matches in either | | Destination | `string` | Target filter: a [destination group](#destination-groups), domain, domain suffix (prefixed with `.`), CIDR (`10.0.0.0/8`), exact IP, or `"*"` | | Protocol | [`PolicyProtocol`](#policyprotocol) | Legacy single-protocol field. The empty string means any. Prefer `Protocols` when matching multiple | | Protocols | `[]`[`PolicyProtocol`](#policyprotocol) | Protocol set. Empty means any | | Port | `string` | Single port (`"443"`) or range (`"8000-9000"`) | | Ports | `[]string` | Several port values at once | ### DNSConfigUsed by NetworkConfig.DNS
```go theme={null} type DNSConfig struct { RebindProtection *bool Nameservers []string QueryTimeoutMs *uint64 } ``` In-VM DNS proxy configuration. | Field | Type | Description | | - | - | - | | RebindProtection | `*bool` | Block DNS responses resolving to private IPs. Defaults to `true` when unset | | Nameservers | `[]string` | Upstream resolvers (e.g. `"1.1.1.1:53"`). Replaces `/etc/resolv.conf` when non-empty | | QueryTimeoutMs | `*uint64` | Per-DNS-query timeout in milliseconds | ### TLSConfigUsed by NetworkConfig.TLS
```go theme={null} type TLSConfig struct { Bypass []string VerifyUpstream *bool InterceptedPorts []uint16 BlockQUIC *bool CACert string CAKey string UpstreamCACerts []string ScopedUpstreamCACerts []ScopedUpstreamCACert ScopedVerifyUpstream []ScopedVerifyUpstream } ```Used by TLSConfig.ScopedUpstreamCACerts
```go theme={null} type ScopedUpstreamCACert struct { Pattern string Path string } ``` Host-scoped upstream CA bundle configuration. | Field | Type | Description | | - | - | - | | Pattern | `string` | Exact host or `*.suffix` wildcard | | Path | `string` | CA bundle path trusted for matching upstream hosts | ### ScopedVerifyUpstreamUsed by TLSConfig.ScopedVerifyUpstream
```go theme={null} type ScopedVerifyUpstream struct { Pattern string Verify bool } ``` Host-scoped upstream certificate verification override. | Field | Type | Description | | - | - | - | | Pattern | `string` | Exact host or `*.suffix` wildcard | | Verify | `bool` | Whether to verify certificates for matching upstream hosts | ### NetworkRateLimiterConfigUsed by NetworkConfig.RateLimiter
Held by NetworkRateLimiterConfig
```go theme={null} type RateLimiterConfig struct { Bandwidth *TokenBucketConfig Ops *TokenBucketConfig } ``` Rate limiter for one traffic direction. Caps bandwidth (bytes) and packet rate (frames) independently; a `nil` bucket leaves that dimension unlimited. | Field | Type | Description | | - | - | - | | Bandwidth | [`*TokenBucketConfig`](#tokenbucketconfig) | Byte budget; one token per byte of frame data | | Ops | [`*TokenBucketConfig`](#tokenbucketconfig) | Packet budget; one token per network frame | ### TokenBucketConfigUsed by RateLimiterConfig
```go theme={null} type TokenBucketConfig struct { Size uint64 RefillTime time.Duration OneTimeBurst uint64 } ``` One token bucket of a rate limiter. The bucket starts full and refills continuously: `Size` tokens every `RefillTime`. The one-time burst is spent before the regular budget and never refills. | Field | Type | Description | | - | - | - | | Size | `uint64` | Bucket capacity in tokens: bytes for bandwidth buckets, frames for ops buckets. Must be greater than zero | | RefillTime | `time.Duration` | Time to refill `Size` tokens. Must be at least one millisecond | | OneTimeBurst | `uint64` | Extra startup-only tokens. Optional | ### PortBindingUsed by WithPortBindings() · NetworkConfig.PortBindings
```go theme={null} type PortBinding struct { Bind string HostPort uint16 GuestPort uint16 Protocol PortProtocol } ``` A host-to-guest port mapping with an explicit host bind address. `Protocol` defaults to TCP when empty. Use `Bind: "0.0.0.0"` to expose the published port on all IPv4 interfaces. | Field | Type | Description | | - | - | - | | Bind | `string` | Host IP address to bind, such as `127.0.0.1`, `0.0.0.0`, or `::` | | HostPort | `uint16` | Port on the host | | GuestPort | `uint16` | Port inside the sandbox | | Protocol | [`PortProtocol`](#portprotocol) | `PortProtocolTCP` or `PortProtocolUDP`. Empty defaults to TCP | ### PortProtocolUsed by PortBinding.Protocol
```go theme={null} type PortProtocol string ``` Identifies the protocol for an exposed sandbox service. | Constant | Value | Description | | - | - | - | | `PortProtocolTCP` | `"tcp"` | TCP port mapping | | `PortProtocolUDP` | `"udp"` | UDP port mapping | ### PolicyActionUsed by PolicyRule.Action · NetworkConfig.DefaultEgress
```go theme={null} type PolicyAction string ``` The action half of a [`PolicyRule`](#policyrule). | Constant | Value | Description | | - | - | - | | `PolicyActionAllow` | `"allow"` | Permit the traffic | | `PolicyActionDeny` | `"deny"` | Drop the traffic silently | ### PolicyDirectionUsed by PolicyRule.Direction
```go theme={null} type PolicyDirection string ``` The direction half of a [`PolicyRule`](#policyrule). The Go SDK follows the Python naming (`egress`/`ingress`); the wire format carries these values. | Constant | Value | Description | | - | - | - | | `PolicyDirectionEgress` | `"egress"` | Traffic leaving the sandbox | | `PolicyDirectionIngress` | `"ingress"` | Traffic entering the sandbox | | `PolicyDirectionAny` | `"any"` | Rule applies in either direction | ### PolicyProtocolUsed by PolicyRule.Protocol · PolicyRule.Protocols
```go theme={null} type PolicyProtocol string ``` The protocol half of a [`PolicyRule`](#policyrule). | Constant | Value | Description | | - | - | - | | `PolicyProtocolTCP` | `"tcp"` | TCP traffic | | `PolicyProtocolUDP` | `"udp"` | UDP traffic | | `PolicyProtocolICMPv4` | `"icmpv4"` | ICMPv4 traffic (egress only) | | `PolicyProtocolICMPv6` | `"icmpv6"` | ICMPv6 traffic (egress only) | ### NetworkProfile ```go theme={null} type NetworkProfile string ``` Composable profile names accepted by [`NetworkPolicy.FromProfiles()`](#networkpolicy-fromprofiles). | Constant | Value | Description | | - | - | - | | `NetworkProfilePublic` | `"public"` | Public internet addresses | | `NetworkProfilePrivate` | `"private"` | Private/LAN ranges | | `NetworkProfileHost` | `"host"` | Sandbox host gateway addresses | # Proxies Source: https://docs.microsandbox.dev/sdk/go/proxies Route outbound sandbox connections through an HTTP CONNECT, SOCKS4, or SOCKS5 proxy with the Go SDK. Configure one HTTP CONNECT, SOCKS4, or SOCKS5 proxy for outbound sandbox connections with [`WithProxy`](#m-withproxy). Proxy protocols are mutually exclusive. See [Proxies](/networking/outbound-proxy) for routing behavior, security considerations, and limits.Parameters
proxy\*OutboundProxyParameters
ctxcontext.Contextnamestringopts...SandboxOptionReturns
\*Error, see Error handling.Parameters
* `ctx`: controls this operation; cancellation does not stop a sandbox already returned. * `name`: reusable sandbox name, up to 128 UTF-8 bytes. * `opts`: the same creation options accepted by [`CreateSandbox`](#m-createsandbox), used only when creation is necessary.Returns
`(*`[`Sandbox`](#sandbox)`, error)` #### m.GetSandbox() ```go theme={null} func GetSandbox(ctx context.Context, name string) (*SandboxHandle, error) ```Parameters
namestringReturns
Returns
Parameters
options...SandboxListOptionWithListLimit, WithListCursor, and/or WithListLabels options.Returns
Parameters
namestringReturns
Parameters
namestringReturns
Parameters
namestringReturns
Returns
Returns
Returns
Parameters
optsLogOptionsTail, Since, Until, Sources. The zero value returns everything for the default stdout and stderr sources.Returns
Parameters
optsLogStreamOptionsSince or FromCursor start point.Returns
Recv in a loop.Returns
Returns
Parameters
optsModifyOptionsPolicy and DryRun. Zero-valued fields are left unchanged.Returns
DryRun is set.Returns
Parameters
intervaltime.DurationReturns
Recv in a loop.Parameters
cmdstringargs...stringReturns
Parameters
cmdstringargs\[]stringnil.opts...AttachOptionReturns
Returns
Parameters
opts...StopOptionWithStopTimeout(30 \* time.Second); expiry never force-kills.Parameters
opts...KillOptionReturns
Returns
true for a local attached handle.Returns
true if attached, false on detach or error.Parameters
limituint32Parameters
cursorstringParameters
labelsmap\[string]stringParameters
imagestringParameters
diskRootDiskConfigParameters
mebibytesuint32Parameters
pathstringfstypestringParameters
mebibytesuint32Parameters
mebibytesuint32Parameters
policyTHPPolicyTHPAlways, THPMadvise, or THPNever.Parameters
cpusuint8Parameters
cpusuint8Parameters
pathstringParameters
shellstring"/bin/bash".Parameters
profileSecurityProfileParameters
envmap\[string]stringParameters
labelsmap\[string]stringParameters
keystringvaluestringParameters
hostnamestringParameters
userstringParameters
timeouttime.DurationParameters
ephemeralbooltrue to delete all state on termination.Parameters
cmd...stringParameters
cfgInitConfigParameters
levelLogLevelParameters
scriptsmap\[string]stringParameters
Parameters
dtime.DurationParameters
dtime.DurationParameters
authRegistryAuthParameters
pem\[]byteParameters
pathstringParameters
portsmap\[uint16]uint16Parameters
portsmap\[uint16]uint16Parameters
bindings...PortBindingParameters
Parameters
proxy\*OutboundProxyParameters
secrets...SecretEntryParameters
patches...PatchConfigParameters
mountsmap\[string]MountConfigParameters
timeouttime.DurationParameters
timeouttime.DurationAttach options
#### WithAttachCwd() ```go theme={null} func WithAttachCwd(path string) AttachOption ``` Set the working directory for the attached session. Defaults to the sandbox's workdir.Parameters
pathstringParameters
userstringuser:group.Parameters
envmap\[string]stringParameters
keysstringProduces PatchConfig for WithPatches()
Factory for [`PatchConfig`](#patchconfig) values. #### Patch.Text() ```go theme={null} func (patchFactory) Text(path, content string, opts PatchOptions) PatchConfig ``` Write UTF-8 text content at `path`.Parameters
pathstringcontentstringoptsPatchOptionsMode and Replace.Parameters
pathstringcontentstringParameters
pathstringoptsPatchOptionsMode applies.Parameters
pathstringParameters
targetstringlinkstringoptsPatchOptionsReplace applies.Parameters
srcstringdststringoptsPatchOptionsMode and Replace.Parameters
srcstringdststringoptsPatchOptionsReplace applies.Produces InitConfig for WithInit()
Factory for [`InitConfig`](#initconfig) values. #### Init.Auto() ```go theme={null} func (initFactory) Auto() InitConfig ```Returns
Parameters
cmdstringoptsInitOptionsReturned by GetSandbox() · ListSandboxes() · ListSandboxesWith()
A sandbox metadata and lifecycle handle that does not require an active guest-agent connection. #### h.Name() ```go theme={null} Name() ``` Sandbox name, up to 128 UTF-8 bytesReturns
`string` #### h.ID() ```go theme={null} func (h *SandboxHandle) ID() string ``` Return the opaque stable identity captured by this metadata handle. Receiver lifecycle calls remain bound to this value and return `ErrSandboxReplaced` when the reusable name now points to another sandbox. #### h.Status() ```go theme={null} Status() ``` Last-known lifecycle statusReturns
[`SandboxStatus`](#sandboxstatus) #### h.ConfigJSON() ```go theme={null} ConfigJSON() ``` Raw JSON configurationReturns
`string` #### h.Config()Returns
`(*`[`SandboxConfig`](#sandboxconfig)`, error)` #### h.CreatedAt() ```go theme={null} CreatedAt() ``` Creation time, zero value if unknownReturns
`time.Time` #### h.UpdatedAt() ```go theme={null} UpdatedAt() ``` Last-update time, zero value if unknownReturns
`time.Time` #### h.Refresh() ```go theme={null} Refresh(ctx) ``` Fresh handle for the same nameReturns
`(*SandboxHandle, error)` #### h.Ping()Returns
`(*`[`SandboxPingResult`](#sandboxpingresult)`, error)` #### h.Touch()Returns
`(*`[`SandboxTouchResult`](#sandboxtouchresult)`, error)` #### h.Modify()Returns
`(*`[`SandboxModificationPlan`](#sandboxmodificationplan)`, error)` #### h.Metrics()Returns
`(*`[`Metrics`](#metrics)`, error)` #### h.Logs()Returns
`([]`[`LogEntry`](#logentry)`, error)` #### h.LogStream() ```go theme={null} LogStream(ctx, opts) ``` Stream captured outputReturns
`(*`[`LogStreamHandle`](#logstreamhandle)`, error)` #### h.Connect() ```go theme={null} Connect(ctx) ``` Reattach to the running sandboxReturns
`(*`[`Sandbox`](#sandbox)`, error)` #### h.ConnectOrStart() ```go theme={null} func (h *SandboxHandle) ConnectOrStart(ctx context.Context, opts ...ConnectOrStartOption) (*Sandbox, error) ``` Connect when this exact sandbox is running, wait through `SandboxStatusStarting`, or start it when it is created, stopped, or crashed. Draining and paused states are rejected. `WithConnectOrStartDetached` affects only a required local start; connecting to an already-running sandbox does not change ownership. #### h.Start() ```go theme={null} Start(ctx) ``` Boot a stopped sandbox. The returned local handle is attached; a cloud handle does not own the service-managed VM.Returns
`(*`[`Sandbox`](#sandbox)`, error)` #### h.StartDetached() ```go theme={null} StartDetached(ctx) ``` Boot a stopped sandbox in detached modeReturns
`(*`[`Sandbox`](#sandbox)`, error)` #### h.WaitForStatus() ```go theme={null} func (h *SandboxHandle) WaitForStatus(ctx context.Context, status SandboxStatus) (*SandboxHandle, error) ``` Wait until this exact sandbox reaches `status`, returning a refreshed handle. The context supplies cancellation or a deadline. Returns `ErrSandboxReplaced` rather than rebinding to a replacement. #### h.Restart() ```go theme={null} func (h *SandboxHandle) Restart(ctx context.Context, opts ...RestartOption) (*Sandbox, error) ``` Restart this exact sandbox with the same state and option semantics as [`Sandbox.Restart`](#sb-restart). #### h.Destroy() ```go theme={null} func (h *SandboxHandle) Destroy(ctx context.Context, opts ...DestroyOption) error ``` Stop and remove this exact sandbox. A stale handle returns `ErrSandboxReplaced` instead of destroying a same-name replacement. #### h.Stop()Returns
`error` #### h.StopWithTimeout() ```go theme={null} StopWithTimeout(ctx, timeout) ``` Bound graceful shutdown for this exact sandbox run. Expiry returns `ErrStopTimeout` without force-killing; zero or a negative duration expires before sending a request. #### h.RequestStop() ```go theme={null} RequestStop(ctx) ``` Send a graceful shutdown request without waiting for completion or scheduling forced termination.Returns
`error` #### h.Kill()Returns
`error` #### h.RequestKill()Returns
`error` #### h.RequestDrain()Returns
`error` #### h.WaitUntilStopped() ```go theme={null} WaitUntilStopped(ctx) ``` Block until terminal stateReturns
`(*`[`SandboxStopResult`](#sandboxstopresult)`, error)` #### h.Remove() ```go theme={null} Remove(ctx) ``` Delete sandbox and persisted stateReturns
`error` #### h.Snapshot()Returns
`(*SnapshotArtifact, error)` ## MetricsStreamHandleReturned by MetricsStream()
Live metrics subscription. Call `Close` to release Rust-side resources. #### metricsStream.Recv() ```go theme={null} Recv(ctx) ``` Block until the next snapshot arrives. Returns `(nil, nil)` when the stream ends (sandbox exited)Returns
`(*`[`Metrics`](#metrics)`, error)` #### metricsStream.Close() ```go theme={null} Close() ``` Stop the stream and release Rust-side resourcesReturns
`error` ## LogEntryReturned by Logs() · LogStream()
A single captured log entry. | Field | Type | Description | | - | - | - | | `Source` | [`LogSource`](#logsource) | Origin of the captured data | | `SessionID` | `*uint64` | Relay-monotonic session id; nil for system entries | | `Timestamp` | `time.Time` | Wall-clock capture time on the host | | `Data` | `[]byte` | The captured bytes | | `Cursor` | `string` | Opaque resume token; pass to [`LogStreamOptions.FromCursor`](#logstreamoptions) | #### entry.Text() ```go theme={null} Text() ``` Captured bytes as a stringReturns
`string` ## LogStreamHandleReturned by LogStream()
Live log subscription. Call `Close` to release Rust-side resources. #### logStream.Recv() ```go theme={null} Recv(ctx) ``` Block until the next entry arrives. Returns `(nil, nil)` when the stream endsReturns
`(*`[`LogEntry`](#logentry)`, error)` #### logStream.Close() ```go theme={null} Close() ``` Stop the stream and release Rust-side resourcesReturns
`error` ## Types ### SandboxPingResultReturned by Ping()
Agent reachability result. | Field | Type | Description | | - | - | - | | Name | `string` | Sandbox name | | Latency | `time.Duration` | Round-trip latency | ### SandboxTouchResultReturned by Touch()
Explicit idle-refresh result. | Field | Type | Description | | - | - | - | | Name | `string` | Sandbox name | | ActivitySeq | `uint64` | Monotonic activity sequence after the touch | ### ModifyOptionsUsed by Modify()
A requested sandbox modification. Zero-valued fields are left unchanged (`0` is not a valid CPU, memory, or disk size). | Field | Type | Description | | - | - | - | | CPUs | `uint8` | Desired effective vCPU count. Live when within the booted `MaxCPUs` | | MaxCPUs | `uint8` | Boot-time maximum possible vCPUs (restart-backed) | | MemoryMiB | `uint32` | Desired effective guest memory in MiB. Live when within the booted `MaxMemoryMiB` | | MaxMemoryMiB | `uint32` | Boot-time maximum hotpluggable memory in MiB (restart-backed) | | RootDiskSizeMiB | `uint32` | Desired root disk size in MiB. Managed and flat OCI disks are grow-only; applies on restart or next start | | Env | `map[string]string` | Environment variables to set for future execs | | EnvRemove | `[]string` | Environment variable keys to remove | | Labels | `map[string]string` | Labels to set | | LabelsRemove | `[]string` | Label keys to remove | | Workdir | `string` | Working directory for future execs | | Secrets | `map[string]SecretModifySpec` | Desired secret specs keyed by stable secret name | | SecretsRemove | `[]string` | Secret names to remove explicitly | | Policy | `ModificationPolicy` | `ModificationPolicyNoRestart` (default) applies only changes that can complete without restarting; `ModificationPolicyNextStart` persists changes for the next start without mutating a running VM; `ModificationPolicyRestart` restarts if needed so restart-required changes become active now | | DryRun | `bool` | Compute the plan without applying anything | ### SecretModifySpecUsed by Modify()
Desired state for one secret. `Env`, `Value`, and `Store` are mutually exclusive sources. Leave all three empty to update only the placeholder or allowed hosts. | Field | Type | Description | | - | - | - | | Env | `string` | Host environment variable to resolve when applying the modification | | Value | `string` | Raw secret value. Stored in the durable sandbox config until replaced by a source reference | | Store | `string` | Reserved for a host-side secret store reference; currently unsupported | | Placeholder | `string` | Explicit guest-visible placeholder. New secrets default to `$MSB_Returned by Modify()
Dry-run or apply plan for a sandbox modification. Values never appear in a plan: secret entries carry only guest-visible references. | Field | Type | Description | | - | - | - | | Sandbox | `string` | Sandbox being modified | | Status | `string` | Status used for classification (`"running"`, `"stopped"`, ...) | | Applied | `bool` | Whether the changes were applied; `false` for dry runs | | Policy | `ModificationPolicy` | Policy used to produce the plan | | Changes | `[]PlannedChange` | Planned changes, one entry per field or secret (see below) | | Conflicts | `[]ModificationConflict` | Conflicts (`Field` + `Message`) that must be resolved before the patch can apply | | Warnings | `[]ModificationWarning` | Non-fatal warnings (`Field` + `Message`), e.g. the future-execs-only env caveat | | ResizeStatus | `[]ResourceResizeStatus` | Live resource resize outcomes, populated by apply when a live change ran (see below) | `PlannedChange` is one planned entry. `Kind` is `"config"` or `"secret"`; config entries carry `Before` / `After` while secret entries carry `Name`, `BeforeRef` / `AfterRef` (guest-visible references, values are omitted by construction), and `AllowHosts`: | Field | Type | Description | | - | - | - | | Kind | `string` | `"config"` or `"secret"` | | Field | `string` | Config field being changed; always `"secret"` for secret entries | | Name | `string` | Secret name (secret entries only) | | Change | `string` | `"added"`, `"updated"`, or `"removed"` for config; `"added"`, `"rotated"`, `"removed"`, `"renamed"`, `"hosts updated"`, or `"placeholder updated"` for secrets | | Before / After | `*string` | Previous / new visible state (config entries) | | BeforeRef / AfterRef | `*string` | Previous / new guest-visible reference (secret entries) | | Disposition | `string` | `"live"`, `"next start"`, `"requires restart"`, or `"unsupported"` | | AllowHosts | `[]string` | Allowed hosts after the requested change (secret entries) | | Reason | `*string` | Human-readable reason for the classification, when useful | `ResourceResizeStatus` reports runtime convergence for a live resize; enforcement applies immediately, the guest converges asynchronously: | Field | Type | Description | | - | - | - | | Resource | `string` | `"cpus"` or `"memory"` | | Requested | `string` | Requested value | | Actual | `string` | Actual value observed in the guest/runtime | | Enforced | `string` | Host/VMM-enforced value | | State | `string` | `"applied"` when requested, actual, and enforced match; `"converging"` while the guest is still onlining CPUs or plugging memory; `"guest-refused"` when the guest would not cooperate (the host enforces the new limit anyway); `"accepted"` or `"failed"` otherwise | ### SandboxPage One stable, newest-first page returned by [`ListSandboxes`](#m-listsandboxes) or [`ListSandboxesWith`](#m-listsandboxeswith). Pass `NextCursor` back through `WithListCursor` with the same filters to continue. | Field | Type | Description | | - | - | - | | `Sandboxes` | `[]*SandboxHandle` | Handles in this page | | `NextCursor` | `*string` | Opaque continuation cursor, or `nil` on the final page | ### SandboxListOption Functional options accepted by [`ListSandboxesWith`](#m-listsandboxeswith). ### SandboxConfigPopulated by SandboxOption · parsed by SandboxHandle.Config()
The full configuration of a sandbox. Most callers build a sandbox via `CreateSandbox(ctx, name, ...opts)`; `SandboxConfig` is exported for callers that prefer to construct a value directly. | Field | Type | Description | | - | - | - | | Name | `string` | Sandbox name, up to 128 UTF-8 bytes | | Image | `string` | OCI image, local path, or disk image | | ImageFstype | `string` | Optional inner filesystem type for disk-image roots | | RootDisk | [`*RootDiskConfig`](#rootdiskconfig) | Root storage for an OCI image | | OCIUpperSizeMiB | `uint32` | Deprecated managed-root-disk size alias; ignored when `RootDisk` is set | | MemoryMiB | `uint32` | Guest memory in MiB | | CPUs | `uint8` | Virtual CPUs | | MaxMemoryMiB | `uint32` | Boot-time maximum hotpluggable memory in MiB | | MaxCPUs | `uint8` | Boot-time maximum possible virtual CPUs | | Workdir | `string` | Default working directory | | Shell | `string` | Shell binary used by `Shell` calls | | SecurityProfile | [`SecurityProfile`](#securityprofile) | In-guest security profile | | Hostname | `string` | Guest hostname | | User | `string` | Default guest user | | Replace | `bool` | Replace existing sandbox with same name | | ReplaceWithTimeout | `*time.Duration` | Timeout between SIGTERM and SIGKILL (implies `Replace`) | | Env | `map[string]string` | Environment variables | | Labels | `map[string]string` | Labels for metrics attribution and filtering | | Detached | `bool` | If `true`, sandbox survives after the process exits | | Ephemeral | `bool` | If `true`, all state is removed on termination | | Entrypoint | `[]string` | Override the image ENTRYPOINT used by default-workload execution | | Cmd | `[]string` | Override the image CMD used by default-workload execution; an empty non-nil slice clears CMD | | Init | [`*InitConfig`](#initconfig) | Hand PID 1 off to a guest init binary | | LogLevel | [`LogLevel`](#loglevel) | Sandbox log verbosity override | | QuietLogs | `bool` | Suppress sandbox-level log output | | Scripts | `map[string]string` | Named scripts mounted at `/.msb/scripts/` | | PullPolicy | [`PullPolicy`](#pullpolicy) | Image pull behavior | | MaxDuration | `time.Duration` | Maximum sandbox lifetime | | IdleTimeout | `time.Duration` | Idle timeout | | RegistryAuth | [`*RegistryAuth`](#registryauth) | Private registry credentials | | Ports | `map[uint16]uint16` | Host to guest TCP port mappings | | PortsUDP | `map[uint16]uint16` | Host to guest UDP port mappings | | PortBindings | [`[]PortBinding`](/sdk/go/networking#portbinding) | Port mappings with explicit bind addresses | | Network | [`*NetworkConfig`](/sdk/go/networking#networkconfig) | Network policy and configuration | | Secrets | [`[]SecretEntry`](/sdk/go/secrets#secretentrystruct) | Secret injection entries | | Patches | [`[]PatchConfig`](#patchconfig) | Rootfs modifications applied before boot | | Volumes | `map[string]MountConfig` | Volume mounts keyed by guest path | ### RootDisk Factory namespace for [`RootDiskConfig`](#rootdiskconfig) values. Pass the result to [`WithRootDisk`](#withrootdisk). ```go theme={null} m.RootDisk.Managed(8192) m.RootDisk.Tmpfs(m.RootDiskTmpfsOptions{SizeMiB: 512}) m.RootDisk.Disk("./scratch.qcow2", m.RootDiskImageOptions{Format: "qcow2", Fstype: "ext4"}) m.RootDisk.Flat(m.RootDiskFlatOptions{SizeMiB: 8192, Clone: m.FlatCloneAuto}) ``` ### RootDiskConfig Root storage configuration returned by the [`RootDisk`](#rootdisk) factory. Use [`Kind()`](#rootdiskconfig-kind) to inspect its backing. | Field | Type | Description | | - | - | - | | `SizeMiB` | `uint32` | Managed, tmpfs, or flat root-disk size; zero selects the runtime default where supported | | `Path` | `string` | Host path for a user-supplied disk image | | `Format` | `string` | Disk-image format: `raw` or `qcow2`; inferred from the path when empty | | `Fstype` | `string` | Inner filesystem type; defaults to `ext4` | | `Clone` | [`FlatClone`](#flatclone) | Private flat-root provisioning strategy | #### rootDiskConfig.Kind() ```go theme={null} func (r RootDiskConfig) Kind() RootDiskKind ``` Return the configured root-disk backing. ### RootDiskKind | Constant | Description | | - | - | | `RootDiskKindManaged` | Microsandbox-owned sparse ext4 writable layer | | `RootDiskKindTmpfs` | Ephemeral RAM-backed writable layer | | `RootDiskKindDiskImage` | User-supplied writable disk image | | `RootDiskKindFlat` | Complete OCI root filesystem mounted without guest OverlayFS | ### RootDiskTmpfsOptions | Field | Type | Description | | - | - | - | | `SizeMiB` | `uint32` | Tmpfs size; zero uses half of sandbox memory | ### RootDiskImageOptions | Field | Type | Description | | - | - | - | | `Format` | `string` | Optional `raw` or `qcow2` format; inferred from the path when empty | | `Fstype` | `string` | Optional inner filesystem type; defaults to `ext4` | ### RootDiskFlatOptions | Field | Type | Description | | - | - | - | | `SizeMiB` | `uint32` | Final guest capacity; zero uses the runtime default | | `Fstype` | `string` | Generated filesystem type; currently `ext4` | | `Clone` | [`FlatClone`](#flatclone) | Private disk provisioning strategy | ### FlatClone | Constant | Value | Description | | - | - | - | | `FlatCloneAuto` | `"auto"` | Try a native reflink, then fall back to a sparse copy | | `FlatCloneCopy` | `"copy"` | Always create a sparse copy | | `FlatCloneReflink` | `"reflink"` | Require a native reflink and fail when unavailable | ### SandboxOptionConsumed by CreateSandbox()
```go theme={null} type SandboxOption func(*SandboxConfig) ``` A functional option for [`CreateSandbox`](#m-createsandbox). Every `WithX` helper in the [Options](#options) section returns one. The lifecycle setters [`WithStopTimeout`](#withstoptimeout) and [`WithKillTimeout`](#withkilltimeout) return distinct `StopOption` / `KillOption` types passed to [`Stop`](#sb-stop) and [`Kill`](#sb-kill) instead. ### AttachConfigPopulated by AttachOption
Configures a single [`AttachWith`](#sb-attachwith) call. Most callers set fields through the `WithAttach*` functional options; `AttachConfig` is exported for parity with the other SDKs' config types. | Field | Type | Description | | - | - | - | | `Cwd` | `string` | Working directory inside the guest; defaults to the sandbox workdir | | `User` | `string` | Guest user (UID or name, optionally `user:group`); defaults to the sandbox user | | `Env` | `map[string]string` | Environment variables merged on top of the sandbox env | | `DetachKeys` | `string` | Detach key sequence; defaults to `ctrl-]` | ### AttachOptionAccepted by sb.AttachWith()
```go theme={null} type AttachOption func(*AttachConfig) ``` A functional option that mutates an [`AttachConfig`](#attachconfig). Construct them with the `WithAttach*` functions below. ### MetricsReturned by Metrics() · MetricsStream() · AllSandboxMetrics()
Point-in-time resource usage snapshot. | Field | Type | Description | | - | - | - | | CPUPercent | `float64` | CPU usage as a percentage | | VCPUTimeNs | `uint64` | Cumulative vCPU time in nanoseconds | | MemoryBytes | `uint64` | Current memory usage in bytes | | MemoryAvailableBytes | `*uint64` | Guest-reported available memory when known | | MemoryHostResidentBytes | `*uint64` | Host RSS backing the guest when known | | MemoryLimitBytes | `uint64` | Memory limit in bytes | | DiskReadBytes | `uint64` | Total bytes read from disk since boot | | DiskWriteBytes | `uint64` | Total bytes written to disk since boot | | NetRxBytes | `uint64` | Total bytes received over the network since boot | | NetTxBytes | `uint64` | Total bytes sent over the network since boot | | UpperUsedBytes | `*uint64` | Guest-visible OCI upper filesystem used bytes when the protected reporter is available and fresh | | UpperFreeBytes | `*uint64` | Guest-visible OCI upper filesystem free bytes when the protected reporter is available and fresh | | UpperHostAllocatedBytes | `*uint64` | Host-allocated bytes for the writable OCI upper image when available | | Uptime | `time.Duration` | Time since the sandbox was created | ### SandboxStopResultReturned by WaitUntilStopped()
Describes a terminal sandbox state observed by [`WaitUntilStopped`](#sb-waituntilstopped). | Field | Type | Description | | - | - | - | | Name | `string` | Sandbox name | | Status | [`SandboxStatus`](#sandboxstatus) | Terminal status (`stopped` or `crashed`) | | ExitCode | `*int` | Process exit code when known | | Signal | `*int` | Terminating signal when known | | ObservedAt | `time.Time` | When the terminal state was observed | | Source | `*string` | Origin of the stop observation when known | ### SandboxStatusUsed by SandboxHandle.Status() · SandboxStopResult.Status
```go theme={null} type SandboxStatus string ``` | Constant | Value | Description | | - | - | - | | `SandboxStatusCreated` | `"created"` | Persisted resource exists but has not started | | `SandboxStatusStarting` | `"starting"` | Runtime is booting or waiting for capacity | | `SandboxStatusRunning` | `"running"` | Guest agent is ready; `Exec`, `Shell`, `FS` work | | `SandboxStatusDraining` | `"draining"` | Graceful shutdown in progress; existing commands finish, new ones rejected | | `SandboxStatusPaused` | `"paused"` | VM is paused | | `SandboxStatusStopped` | `"stopped"` | VM shut down; configuration persisted; can be restarted | | `SandboxStatusCrashed` | `"crashed"` | VM exited unexpectedly (kernel panic, OOM, etc.) | ### LogOptionsUsed by Logs()
Filters passed to [`Logs`](#sb-logs). The zero value returns everything for the default sources (stdout + stderr). | Field | Type | Description | | - | - | - | | Tail | `uint64` | Keep only the last N matching entries | | Since | `time.Time` | Inclusive lower timestamp bound | | Until | `time.Time` | Exclusive upper timestamp bound | | Sources | `[]`[`LogSource`](#logsource) | Sources to include; empty = stdout + stderr. Add `LogSourceOutput` or `LogSourceSystem` for PTY-merged output or runtime/kernel diagnostics | ### LogStreamOptionsUsed by LogStream()
Configures a live log stream. The zero value reads the default sources from the beginning with follow off. `Since` and `FromCursor` are mutually exclusive. | Field | Type | Description | | - | - | - | | Sources | `[]`[`LogSource`](#logsource) | Sources to include; empty = stdout + stderr + output | | Since | `time.Time` | Start at the first entry with timestamp >= this; mutually exclusive with `FromCursor` | | FromCursor | `string` | Resume strictly after the entry whose `Cursor` matches; mutually exclusive with `Since` | | Until | `time.Time` | Stop at the first entry with timestamp >= this | | Follow | `bool` | Keep the stream open past EOF and yield new entries as written | ### LogSourceUsed by LogEntry.Source · LogOptions.Sources · LogStreamOptions.Sources
```go theme={null} type LogSource string ``` | Constant | Value | Description | | - | - | - | | `LogSourceStdout` | `"stdout"` | Captured stdout (pipe mode, streams stayed separated) | | `LogSourceStderr` | `"stderr"` | Captured stderr (pipe mode) | | `LogSourceOutput` | `"output"` | PTY-merged stdout and stderr from a session running in PTY mode | | `LogSourceSystem` | `"system"` | Synthetic lifecycle markers plus runtime/kernel diagnostic lines | ### LogLevelUsed by WithLogLevel()
```go theme={null} type LogLevel string ``` Sandbox process log verbosity. | Constant | Value | Description | | - | - | - | | `LogLevelDefault` | `""` | Runtime default | | `LogLevelTrace` | `"trace"` | Most verbose, all diagnostic output | | `LogLevelDebug` | `"debug"` | Debug and higher | | `LogLevelInfo` | `"info"` | Info and higher | | `LogLevelWarn` | `"warn"` | Warnings and errors only | | `LogLevelError` | `"error"` | Errors only | ### PullPolicyUsed by WithPullPolicy()
```go theme={null} type PullPolicy string ``` Controls when the SDK fetches an OCI image from the registry. | Constant | Value | Description | | - | - | - | | `PullPolicyDefault` | `""` | Runtime default (currently `PullPolicyIfMissing`) | | `PullPolicyAlways` | `"always"` | Pull every time, even if cached locally | | `PullPolicyIfMissing` | `"if-missing"` | Pull only if not already cached | | `PullPolicyNever` | `"never"` | Never pull; fail if missing | ### SecurityProfileUsed by WithSecurityProfile()
```go theme={null} type SecurityProfile string ``` Sandbox-wide in-guest security profile. | Constant | Value | Description | | - | - | - | | `SecurityProfileDefault` | `"default"` | Normal guest-root semantics | | `SecurityProfileRestricted` | `"restricted"` | Stronger hardening: `no_new_privs`, dropped mount-admin capability, forced `nosuid,nodev` on user mounts | ### RegistryAuthUsed by WithRegistryAuth()
Credentials for a private OCI registry. | Field | Type | Description | | - | - | - | | Username | `string` | Registry username | | Password | `string` | Registry password | ### InitConfigBuilt by Init · used by WithInit()
Custom guest PID-1 init specification. Construct via the [`Init`](#init) factory rather than building the struct directly. | Field | Type | Description | | - | - | - | | Cmd | `string` | Absolute path inside the guest, or `"auto"` | | Args | `[]string` | Supplemental argv (`argv[0]` is implicitly `Cmd`) | | Env | `map[string]string` | Extra env vars merged on top of the inherited env | ### InitOptionsUsed by Init.Cmd()
Tuning struct for [`Init.Cmd`](#init-cmd) beyond the required cmd. | Field | Type | Description | | - | - | - | | Args | `[]string` | Supplemental argv | | Env | `map[string]string` | Extra env vars | ### PatchConfigBuilt by Patch · used by WithPatches()
A single rootfs patch. Construct via the [`Patch`](#patch) factory; the fields populated depend on the [`PatchKind`](#patchkind). | Field | Type | Description | | - | - | - | | Kind | [`PatchKind`](#patchkind) | Patch flavor | | Path | `string` | Absolute guest path (text / append / mkdir / remove) | | Content | `string` | Text content (text / append) | | Mode | `*uint32` | File or directory mode, e.g. `0o644` | | Replace | `bool` | When `true`, overwrite an existing path at the destination | | Src | `string` | Host source path (copy\_file / copy\_dir) | | Dst | `string` | Guest destination path (copy\_file / copy\_dir) | | Target | `string` | Symlink target | | Link | `string` | Symlink path | ### PatchOptionsUsed by Patch methods
Tuning struct passed to [`Patch`](#patch) methods that accept a mode and replace flag. | Field | Type | Description | | - | - | - | | Mode | `*uint32` | File or directory mode | | Replace | `bool` | Overwrite an existing path | ### PatchKindUsed by PatchConfig.Kind
```go theme={null} type PatchKind string ``` Discriminator for [`PatchConfig`](#patchconfig). Prefer the [`Patch`](#patch) factory. | Constant | Value | | - | - | | `PatchKindText` | `"text"` | | `PatchKindAppend` | `"append"` | | `PatchKindMkdir` | `"mkdir"` | | `PatchKindRemove` | `"remove"` | | `PatchKindSymlink` | `"symlink"` | | `PatchKindCopyFile` | `"copy_file"` | | `PatchKindCopyDir` | `"copy_dir"` | ### InstallOptions See [Runtime setup](/sdk/setup#customize-installation) for the setup-only `InstallOptions` type. # Secrets Source: https://docs.microsandbox.dev/sdk/go/secrets Configure destination-bound sandbox credentials with the Go SDK. See [Secrets](/sandboxes/secrets) for usage examples and security boundaries. ## Functions #### WithSecrets() ```go theme={null} func WithSecrets(secrets ...SecretEntry) SandboxOption ```Parameters
secrets...SecretEntryReturns
Parameters
envVarstring= or NUL; shell-identifier syntax is not required.valuestringoptsSecretEnvOptionsReturns
accepted by WithSecrets() · returned by Secret.Env()
A single credential the network proxy substitutes at the transport layer. The value never reaches the guest VM. Usually produced by [`Secret.Env`](#secret-env); exported for callers that prefer struct literals. | Field | Type | Description | | - | - | - | | `EnvVar` | `string` | Environment variable name holding the placeholder inside the sandbox. Must be non-empty and cannot contain `=` or NUL; shell-identifier syntax is not required | | `Value` | `string` | Real secret value; stays on the host, including across the native FFI boundary | | `Allow` | `[]string` | Exact hosts or wildcard patterns allowed to receive the real value | | `Passthrough` | `[]string` | Exact hosts or wildcard patterns allowed to receive the unchanged placeholder | | `Substitution` | [`SecretSubstitution`](#secretsubstitutionstruct) | Enabled request locations; zero value enables headers only | | `Placeholder` | `string` | Custom placeholder shown inside the sandbox in place of the secret. Auto-generated from `EnvVar` when empty. Custom values must be non-empty, at most 1024 bytes, and cannot contain NUL, CR, or LF | | `RequireTLSIdentity` | `*bool` | Require a verified TLS identity before substituting. Defaults to `true` when `nil` | | `ViolationAction` | [`ViolationAction`](#violationactionstring-enum) | Override the sandbox-wide action when this secret is detected going to a disallowed host. This overrides the network default for this secret only | ### SecretEnvOptionsstructaccepted by Secret.Env()
Tunes [`Secret.Env`](#secret-env) beyond the required `envVar` and `value`. | Field | Type | Description | | - | - | - | | `Allow` | `[]string` | Exact hosts or wildcard patterns allowed to receive the real value | | `AllowPlaceholderFor` | `[]string` | Hosts allowed to receive the unchanged placeholder where substitution does not apply | | `Passthrough` | `[]string` | Deprecated alias; combined with `AllowPlaceholderFor` when both are supplied | | `Substitution` | [`SecretSubstitution`](#secretsubstitutionstruct) | Zero value enables headers only | | `Placeholder` | `string` | Custom placeholder: non-empty, up to 1024 bytes, no NUL/CR/LF | | `RequireTLSIdentity` | `*bool` | Require a verified TLS identity before substituting. Defaults to `true` when `nil` | | `ViolationAction` | [`ViolationAction`](#violationactionstring-enum) | Per-secret violation action | ### SecretSubstitutionstruct #### substitution.Headers ```go theme={null} Headers *bool ``` Substitute in headers, including Basic authentication. Default: `true` when `nil`; use a pointer to set `false`. #### substitution.HeaderFields ```go theme={null} HeaderFields []string ``` Restrict substitution to these header names. An empty list allows all headers. Requires header substitution to be enabled. Prefer only the intended credential header, such as `Authorization`, to prevent other headers from exposing a secret in a reflected response. #### substitution.Query ```go theme={null} Query bool ``` Substitute in the URL query string. Default: `false`. #### substitution.Body ```go theme={null} Body bool ``` Substitute in supported HTTP/1 bodies. Default: `false`. Fixed-length bodies up to 16 MiB update `Content-Length`; larger bodies are blocked. Chunked bodies are decoded and re-encoded. Encoded bodies pass through unchanged. HTTP/2 body substitution is unsupported, and matching placeholders are blocked. At least one substitution location must remain enabled. On verified allowed hosts, disabled locations forward the placeholder unchanged. Other destinations must match the passthrough policy or follow the violation action.field of SecretEntry · NetworkConfig
```go theme={null} type ViolationAction string ``` What happens when a secret placeholder cannot be substituted or passed through. Passthrough is a separate per-secret host policy, not a violation action. Configure the sandbox-wide default on [`NetworkConfig.SecretViolationAction`](/sdk/go/networking#networkconfig); override per-secret with [`SecretEntry.ViolationAction`](#secretentrystruct). | Constant | Value | Description | | - | - | - | | `ViolationActionDefault` | `""` | Leave the runtime default in place (currently `block-and-log`) | | `ViolationActionBlock` | `"block"` | Silently drop the request. The guest sees a connection reset | | `ViolationActionBlockAndLog` | `"block-and-log"` | Drop the request and emit a warning log on the host side | | `ViolationActionBlockAndTerminate` | `"block-and-terminate"` | Drop the request, log an error, and shut down the entire sandbox | # Snapshots Source: https://docs.microsandbox.dev/sdk/go/snapshots Create and restore sandbox snapshots with the Go SDK.Parameters
ctxcontext.ContextReturns
Parameters
ctxcontext.ContextpathOrNamestringgroup:member selector or artifact directory path.Returns
Parameters
ctxcontext.ContextnameOrDigeststringgroup:member, stable snapshot ID, digest, or artifact path.Returns
Returns
Parameters
ctxcontext.ContextdirstringReturns
Parameters
ctxcontext.ContextpathOrNamestringgroup:member, or artifact path.forceboolParameters
ctxcontext.ContextdirstringReturns
Parameters
ctxcontext.ContextnameOrPathstringgroup:member, or artifact path to save.outPathstringParameters
ctxcontext.Contextarchivestringdeststring"" for the default snapshots directory.Returns
Parameters
ctxcontext.ContextnamestringReturns
Returns
Returns
Parameters
ctxcontext.ContextforceboolSnapshot scopes
Returned by s.Scope() · h.Scope()
Scope of what a snapshot captures: disk-only or disk plus complete VM state. | Constant | Value | Description | | - | - | - | | `SnapshotScopeDisk` | `"disk"` | Disk-only snapshot | | `SnapshotScopeFull` | `"full"` | Disk plus complete VM execution state | ## Types ### SnapshotArtifactstructReturned by Snapshot.Create() · Snapshot.Open() · Snapshot.ListDir() · h.Snapshot() · h.Open()
A backend-neutral snapshot. Fields are unexported; read them through the accessor methods below. | Method | Returns | Description | | - | - | - | | `ID()` | `string` | Stable opaque snapshot identity | | `Path()` | `string` | Local artifact directory; panics on cloud | | `Reference()` | `string` | Stable backend-relative restore reference | | `ReferenceKind()` | `string` | `id` or `path` | | [`Digest()`](#s-digest) | `string` | Canonical manifest digest (`sha256:...`) | | [`SizeBytes()`](#s-sizebytes) | `*uint64` | Backend-reported stored payload size, when known | | [`ImageRef()`](#s-imageref) | `string` | Image reference the snapshot was taken from | | [`ImageManifestDigest()`](#s-imagemanifestdigest) | `string` | Pinned OCI manifest digest | | [`Format()`](#s-format) | `string` | `"raw"` or `"qcow2"` | | [`Scope()`](#s-scope) | `string` | `SnapshotScopeDisk` or `SnapshotScopeFull` | | [`Fstype()`](#s-fstype) | `string` | Filesystem type inside the upper layer | | [`Parent()`](#s-parent) | `*string` | Parent digest, or nil | | [`CreatedAt()`](#s-createdat) | `string` | RFC 3339 timestamp | | [`Labels()`](#s-labels) | `map[string]string` | User labels | | [`SourceSandbox()`](#s-sourcesandbox) | `*string` | Best-effort source sandbox name | | [`SaveTo(ctx, outPath, opts)`](#s-saveto) | `error` | Bundle using this snapshot's typed reference | | [`CopyTo(outputArchivePath)`](#s-copyto) | `*SnapshotCopyBuilder` | Configure a copied archive with replacement metadata | | [`Verify(ctx)`](#s-verify) | `(*SnapshotVerifyReport, error)` | Recompute content integrity | ### SnapshotCopyBuilderstruct Returned by [`SnapshotArtifact.CopyTo`](#s-copyto). Fields are unexported; use the fluent methods below. | Method | Returns | Description | | - | - | - | | `Labels(map[string]string)` | `*SnapshotCopyBuilder` | Replace all labels in the copied manifest | | `RecordIntegrity(bool)` | `*SnapshotCopyBuilder` | Compute integrity when true, or omit it when false | | `Save(context.Context)` | `error` | Write the configured archive | ### SnapshotHandlestructReturned by Snapshot.Get() · Snapshot.List() · Snapshot.Load()
A lightweight handle returned by the active backend. Fields are unexported; read them through the accessor methods below. | Method | Returns | Description | | - | - | - | | `ID()` | `string` | Stable opaque snapshot identity | | `Path()` | `string` | Local artifact directory; panics on cloud | | [`Digest()`](#h-digest) | `string` | Manifest digest | | [`Name()`](#h-name) | `*string` | Bare-name alias, if indexed with one | | [`ParentDigest()`](#h-parentdigest) | `*string` | Parent digest, or nil | | [`ImageRef()`](#h-imageref) | `string` | Pinned image reference | | [`Format()`](#h-format) | `string` | `"raw"` or `"qcow2"` | | [`Scope()`](#h-scope) | `string` | `SnapshotScopeDisk` or `SnapshotScopeFull` | | [`SizeBytes()`](#h-sizebytes) | `*uint64` | Backend-reported stored payload size | | `Reference()` | `string` | Stable backend-relative restore reference | | `ReferenceKind()` | `string` | `id` or `path` | | [`CreatedAt()`](#h-createdat) | `time.Time` | Snapshot creation time | | [`Open(ctx)`](#h-open) | `(*SnapshotArtifact, error)` | Open the artifact metadata | | [`Remove(ctx, force)`](#h-remove) | `error` | Remove this snapshot | | [`SaveTo(ctx, outPath, opts)`](#h-saveto) | `error` | Bundle using this handle's typed reference | ### SnapshotCreateOptionsstructAccepted by Snapshot.Create()
Configures [`Snapshot.Create`](#snapshot-create). `FromSandbox` is required. An empty `Name` is generated; an empty `Group` uses the source sandbox's name. | Field | Type | Description | | - | - | - | | Name | `string` | Member name within its group; generated when empty | | Group | `string` | Destination snapshot group; defaults to the source sandbox's name | | FromSandbox | `string` | Name of the source sandbox; local disk capture supports running, paused, stopped, and crashed sources. Cloud requires a stopped persistent source | | DestDir | `string` | Parent directory containing snapshot groups; empty = the default snapshots directory | | Labels | `map[string]string` | Arbitrary user labels recorded in the manifest | | Force | `bool` | Overwrite a direct archive output; rejected for installed group members | | RecordIntegrity | `bool` | Record content hashes so [`Verify`](#s-verify) can recompute them later | | Full | `bool` | Local-only when `true`: include memory and execution state from a running or paused source. With `false`, local disk capture supports running, paused, stopped, or crashed sources. Cloud requires `false` and a stopped persistent source | | GuestFlush | `GuestFlush` | Guest writeback policy; defaults to `GuestFlushAuto`. See [guest writeback](#guest-writeback) | ### SnapshotSaveOptionsstructAccepted by Snapshot.Save() and instance SaveTo() methods
Returned by s.Verify()
Result of [`Verify`](#s-verify). | Field | Type | Description | | - | - | - | | Digest | `string` | Recomputed manifest digest | | Path | `string` | Artifact directory that was verified | | Upper | [`SnapshotUpperVerifyStatus`](#snapshotupperverifystatusstruct) | Upper-layer integrity status | | Checkpoint | `*SnapshotCheckpointVerifyStatus` | Verified checkpoint root for full state; otherwise `nil` | ### SnapshotUpperVerifyStatusstructField of SnapshotVerifyReport
Upper-layer integrity details inside a [`SnapshotVerifyReport`](#snapshotverifyreportstruct). | Field | Type | Description | | - | - | - | | Kind | `string` | Integrity record kind | | Algorithm | `string` | Hash algorithm used | | Digest | `string` | Recomputed upper-layer digest | # SSH Source: https://docs.microsandbox.dev/sdk/go/ssh Open sandbox SSH sessions and transfer files over SFTP with the Go SDK. See [SSH](/sandboxes/ssh) for client sessions, server endpoints, and file transfer workflows. [Managed inactivity timeouts](/configuration#ssh) take precedence over all timeout options below, including disabling the timeout. This applies to local and cloud sessions using the sandbox backend's retained configuration. ## Sandbox #### sb.SSH() ```go theme={null} func (s *Sandbox) SSH() *SandboxSSHOps ```Returns
Returned by SSH()
SSH operations namespace for a sandbox. Obtained via [`sb.SSH()`](#sb-ssh). Holds no resources; it groups the client and server entry points. #### ssh.OpenClient() ```go theme={null} func (ssh *SandboxSSHOps) OpenClient(ctx context.Context, opts ...SSHClientOption) (*SSHClient, error) ```Parameters
ctxcontext.ContextReturns
Parameters
ctxcontext.ContextReturns
Returned by OpenClient()
A native in-process SSH client session. Obtained via [`OpenClient()`](#ssh-openclient). #### c.Exec() ```go theme={null} func (c *SSHClient) Exec(ctx context.Context, command string, opts ...SSHExecOption) (*SSHOutput, error) ```Parameters
ctxcontext.Contextcommandstringopts...SSHExecOptionReturns
Parameters
ctxcontext.ContextReturns
Parameters
ctxcontext.ContextReturns
Parameters
ctxcontext.ContextReturns
Returned by PrepareServer()
A prepared SSH server endpoint for a sandbox. Obtained via [`PrepareServer()`](#ssh-prepareserver). #### srv.ServeConnection() ```go theme={null} func (srv *SSHServer) ServeConnection(ctx context.Context) error ```Parameters
ctxcontext.ContextReturns
Parameters
ctxcontext.ContextReturns
Returned by Exec()
The output from an SSH exec request. | Field | Type | Description | | - | - | - | | `Status` | `int` | Exit status code | | `Stdout` | `[]byte` | Captured stdout bytes | | `Stderr` | `[]byte` | Captured stderr bytes | #### o.Success() ```go theme={null} func (o SSHOutput) Success() bool ```Returns
true when Status is 0.Returned by SFTP()
A high-level SFTP client session over an SSH connection. Obtained via [`SFTP()`](#c-sftp). #### sftp.Read() ```go theme={null} Read(ctx, path) ``` Read a file into memoryReturns
`([]byte, error)` #### sftp.Write() ```go theme={null} Write(ctx, path, data) ``` Write a file, creating or truncating itReturns
`error` #### sftp.Mkdir() ```go theme={null} Mkdir(ctx, path) ``` Create a directoryReturns
`error` #### sftp.RemoveFile() ```go theme={null} RemoveFile(ctx, path) ``` Remove a fileReturns
`error` #### sftp.RemoveDir() ```go theme={null} RemoveDir(ctx, path) ``` Remove an empty directoryReturns
`error` #### sftp.Rename() ```go theme={null} Rename(ctx, oldPath, newPath) ``` Rename a file or directoryReturns
`error` #### sftp.RealPath() ```go theme={null} RealPath(ctx, path) ``` Resolve a path to its canonical absolute formReturns
`(string, error)` #### sftp.ReadLink() ```go theme={null} ReadLink(ctx, path) ``` Read a symlink targetReturns
`(string, error)` #### sftp.Symlink() ```go theme={null} Symlink(ctx, target, linkPath) ``` Create a symlinkReturns
`error` #### sftp.Close() ```go theme={null} Close(ctx) ``` Close the session (consumes the handle)Returns
`error` ## Types ### SSHClientOptionUsed by OpenClient()
Functional option for [`OpenClient()`](#ssh-openclient). Defaults: user `root`, terminal from `$TERM` (falling back to `xterm`), SFTP enabled, and the global SSH inactivity timeout. | Option | Description | | - | - | | WithSSHUser(user) | SSH login user. Default `root` | | WithSSHTerm(term) | Terminal name for interactive sessions | | WithSSHClientSFTP(enabled) | Enable or disable SFTP on the internal server. Default `true` | | WithSSHClientInactivityTimeout(timeout) | Override the internal server inactivity timeout. A zero duration disables it | ### SSHExecOptionUsed by Exec()
Functional option for [`Exec()`](#c-exec). | Option | Description | | - | - | | WithSSHTTY(enabled) | Request a PTY for the exec channel | ### SSHAttachOptionUsed by Attach()
Functional option for [`Attach()`](#c-attach). The default terminal comes from `$TERM` (falling back to `xterm`); detach keys default to the standard sequence. | Option | Description | | - | - | | WithSSHAttachTerm(term) | Terminal name for the interactive shell | | WithSSHDetachKeys(keys) | Detach key sequence | ### SSHServerOptionUsed by PrepareServer()
Functional option for [`PrepareServer()`](#ssh-prepareserver). SFTP is enabled by default, the inactivity timeout inherits the global SSH setting, and the default authorized-keys file is loaded when no path is provided. | Option | Description | | - | - | | WithSSHHostKeyPath(path) | Override the host private key path | | WithSSHAuthorizedKeysPath(path) | Override the authorized-keys path | | WithSSHServerUser(user) | Override the guest user used for SSH exec requests | | WithSSHServerSFTP(enabled) | Enable or disable SFTP on the server endpoint. Default `true` | | WithSSHServerInactivityTimeout(timeout) | Override the SSH inactivity timeout. A zero duration disables it | # Volumes Source: https://docs.microsandbox.dev/sdk/go/volumes Create and mount persistent sandbox volumes with the Go SDK. See [Volumes](/sandboxes/volumes) for usage examples. ## Local filesystem paths Local operations stay inside the selected volume directory. Symlinked volume roots and links that ultimately resolve inside that directory remain supported. Each operation pins its root so replacing the root path cannot redirect an operation already in progress. Go previously cleaned `..` components before filesystem lookup. Paths where a symlink followed by `..` would select a different destination now return an error. Use the destination explicitly: ```go theme={null} // link -> nested/deep; config and nested/config are different files. err = fs.Write(ctx, "link/../config", data) // Error: ambiguous destination. err = fs.Write(ctx, "config", data) // Select the original Go destination. err = fs.Write(ctx, "nested/config", data) // Explicitly select the other file. ``` Ordinary contained `..` paths remain supported. `RemoveAll(ctx, ".")` and `RemoveAll(ctx, "")` delete the local volume directory and its contents. If the root itself is a symlink, they unlink that root link and preserve its target, matching Go's previous behavior. Descendant links never cause deletion outside the volume. ## Functions #### GetDefaultVolume()Parameters
ctxcontext.Contextnamestringopts...VolumeOptionReturns
Name and Path.Parameters
ctxcontext.ContextnamestringReturns
Parameters
ctxcontext.ContextReturns
Parameters
ctxcontext.ContextnamestringReturned by CreateVolume()
A named persistent volume. #### v.Name() ```go theme={null} func (v *Volume) Name() string ``` Return the volume's name. #### v.Path()Returns
Returned by GetVolume() · ListVolumes()
A `VolumeHandle` is the metadata reference returned by [`GetVolume`](#getvolume) and [`ListVolumes`](#listvolumes). #### h.Name() ```go theme={null} func (h *VolumeHandle) Name() string ``` Return the volume name. #### h.Path()Returns
Returns
Returned by Volume.FS() · VolumeHandle.FS()
Host-side filesystem operations for a named volume. #### vfs.Root() ```go theme={null} func (fs *VolumeFs) Root() string ``` Return the absolute host path of the volume's data directory. #### vfs.Read() ```go theme={null} func (fs *VolumeFs) Read(ctx context.Context, relPath string) ([]byte, error) ``` Read the contents of a file relative to the volume root.Parameters
relPathstringReturns
Parameters
relPathstringdata\[]byteReturns
true if a file or directory exists at the path.Parameters
kindVolumeKindParameters
mebibytesuint32Parameters
mebibytesuint32Parameters
labelsmap\[string]stringParameters
hostPathstringoptsMountOptionsParameters
namestringoptsMountOptionsParameters
namestringoptsMountOptionsnamedOptsNamedVolumeOptionsParameters
optsTmpfsOptionsParameters
hostPathstringoptsDiskOptionsReturned by Mount.Bind() · Mount.Named() · Mount.NamedWith() · Mount.Tmpfs() · Mount.Disk()
| Field | Type | Description | | - | - | - | | `Bind` | `string` | Host path for bind mounts | | `Named` | `string` | Volume name for named mounts | | `NamedMode` | `string` | Provisioning mode for named mounts (`"existing"`, `"create"`, `"ensure-exists"`) | | `NamedKind` | `string` | Kind for provisioned named mounts (`"dir"` or `"disk"`) | | `QuotaMiB` | `uint32` | Quota in MiB for provisioned directory volumes | | `Tmpfs` | `bool` | Set for tmpfs mounts | | `Disk` | `string` | Host path for disk images | | `Format` | `string` | Disk format | | `Fstype` | `string` | Inner filesystem type | | `Readonly` | `bool` | Whether the mount is read-only | | `Noexec` | `bool` | Whether direct execution from the mount is disabled | | `Nosuid` | `bool` | Whether setuid/setgid elevation from files on the mount is ignored | | `Nodev` | `bool` | Whether device files on the mount are ignored | | `SizeMiB` | `uint32` | Size limit for tmpfs / capacity for provisioned disk volumes | | `StatVirtualization` | `StatVirtualization` | Per-mount stat-virtualization policy (bind / named only) | | `HostPermissions` | `HostPermissions` | Per-mount host-permission propagation policy (bind / named only) | | `Owner` | `*MountOwner` | Guest owner fallback for host files without a per-file stat override (bind / directory-backed named only) | #### mount.Kind() ```go theme={null} Kind() ``` Which mount flavour this isReturns
[`MountKind`](#mountkind) ## Types ### ErrPathEscape ```go theme={null} var ErrPathEscape = errors.New("microsandbox: path escapes volume root") ``` Returned by every [`VolumeFs`](#volumefs) method when `relPath` is absolute, contains a `..` sequence that resolves outside the volume root, or traverses a symlink outside the volume's directory.Returned by VolumeFs methods
```go theme={null} if _, err := vfs.Read(ctx, "../etc/passwd"); errors.Is(err, m.ErrPathEscape) { log.Println("nice try") } ``` ### VolumeConfig The config struct populated by [`VolumeOption`](#volumeoption) functions. Most callers go through `CreateVolume(ctx, name, opts...)`; `VolumeConfig` is exported for callers that prefer to construct one directly.Mutated by VolumeOption
| Field | Type | Description | | - | - | - | | `QuotaMiB` | `uint32` | Maximum storage size in MiB (zero = unlimited) | | `Kind` | [`VolumeKind`](#volumekind) | Volume kind (`VolumeKindDir` by default) | | `SizeMiB` | `uint32` | Disk capacity in MiB for `VolumeKindDisk` | | `Labels` | `map[string]string` | Metadata labels | ### VolumeOption ```go theme={null} type VolumeOption func(*VolumeConfig) ``` A functional option for [`CreateVolume`](#createvolume). Constructed by the [`WithVolume*`](#options) helpers.Used by CreateVolume()
### VolumeKind ```go theme={null} type VolumeKind string ``` Describes the storage backing for a named volume.Used by VolumeConfig · WithVolumeKind() · VolumeHandle.Kind()
| Constant | Value | Description | | - | - | - | | `VolumeKindDir` | `"dir"` | Directory-backed named volume | | `VolumeKindDisk` | `"disk"` | Raw ext4 disk-backed named volume | ### MountKind ```go theme={null} type MountKind uint8 ``` Discriminates between the four mount flavours. Inspect via `mount.Kind()`.Returned by MountConfig.Kind()
| Constant | Description | | - | - | | `MountKindBind` | Host bind mount | | `MountKindNamed` | Named persistent volume | | `MountKindTmpfs` | In-memory tmpfs | | `MountKindDisk` | Host disk image | ### MountOptions Tuning struct for [`Mount.Bind`](#mount-bind), [`Mount.Named`](#mount-named), and [`Mount.NamedWith`](#mount-namedwith). `StatVirtualization`, `HostPermissions`, and `Owner` are virtiofs-only; owner is rejected for disk-backed named volumes and when stat virtualization is off. Zero policy values preserve the conservative defaults (strict, private), while a nil owner keeps the runtime fallback identity.Used by Mount.Bind() · Mount.Named() · Mount.NamedWith()
| Field | Type | Description | | - | - | - | | `Readonly` | `bool` | Mount as read-only; virtiofs-backed mounts also reject writes in the host filesystem server | | `Noexec` | `bool` | Prevent direct execution from the mount | | `Nosuid` | `bool` | Ignore setuid and setgid privilege elevation from files on the mount | | `Nodev` | `bool` | Ignore device files on the mount | | `QuotaMiB` | `uint32` | Guest-write quota in MiB, bounding growth beyond the host directory's existing contents; zero keeps the protective default (bind mounts only; named volumes use [`NamedVolumeOptions.QuotaMiB`](#namedvolumeoptions)) | | `StatVirtualization` | `StatVirtualization` | Per-mount stat-virtualization policy (virtiofs only) | | `HostPermissions` | `HostPermissions` | Per-mount host-permission propagation policy (virtiofs only) | | `Owner` | `*MountOwner` | Paired guest uid/gid fallback for host files without a per-file override; nil keeps the runtime fallback | ### MountOwner An inseparable guest ownership pair used by [`MountOptions.Owner`](#mountoptions). UID and GID may include zero; using a pointer to `MountOwner` keeps an unset owner distinct from root. ```go theme={null} Owner: &m.MountOwner{UID: 1000, GID: 1000} ``` | Field | Type | Description | | - | - | - | | `UID` | `uint32` | Guest user ID | | `GID` | `uint32` | Guest group ID | ### NamedVolumeOptions Tunes sandbox-time named volume provisioning for [`Mount.NamedWith`](#mount-namedwith).Used by Mount.NamedWith()
| Field | Type | Description | | - | - | - | | `Mode` | `string` | `"existing"`, `"create"`, or `"ensure-exists"`; empty means `"existing"` | | `Kind` | `string` | `"dir"` or `"disk"`; empty means `"dir"` | | `SizeMiB` | `uint32` | Disk capacity in MiB; required when creating or ensuring a missing disk volume | | `QuotaMiB` | `uint32` | Directory volume quota in MiB | ### TmpfsOptions Tuning struct for [`Mount.Tmpfs`](#mount-tmpfs).Used by Mount.Tmpfs()
| Field | Type | Description | | - | - | - | | `SizeMiB` | `uint32` | Maximum size in MiB | | `Readonly` | `bool` | Mount as read-only | | `Noexec` | `bool` | Prevent direct execution from the mount | | `Nosuid` | `bool` | Ignore setuid and setgid privilege elevation from files on the mount | | `Nodev` | `bool` | Ignore device files on the mount | ### DiskOptions Tuning struct for [`Mount.Disk`](#mount-disk).Used by Mount.Disk()
| Field | Type | Description | | - | - | - | | `Format` | `string` | Format hint (`"raw"`, `"qcow2"`, `"vmdk"`). Optional; the runtime can usually probe | | `Fstype` | `string` | Inner filesystem type (e.g. `"ext4"`, `"xfs"`). Optional; omitted means auto-detect | | `Readonly` | `bool` | Mount as read-only | | `Noexec` | `bool` | Prevent direct execution from the mount | | `Nosuid` | `bool` | Ignore setuid and setgid privilege elevation from files on the mount | | `Nodev` | `bool` | Ignore device files on the mount | # VSock Source: https://docs.microsandbox.dev/sdk/go/vsock Connect a sandbox to host Unix sockets or local Windows named pipes over virtio-vsock with the Go SDK. See [Host sockets](/networking/host-sockets) for guest connection details, platform support, and security considerations.Parameters
namestrtimeoutfloat | NoneNone uses the default.Returns
Parameters
pathstrtimeoutfloat | NoneNone uses the default.Returns
Parameters
namestrReturns
Instance methods
#### client.request() ```python theme={null} async def request(self, flags: int, body: bytes) -> RawFrame ```Parameters
flagsintFLAG\_\* constants.bodybytesReturns
Parameters
flagsintFLAG\_SESSION\_START to open a session.bodybytesReturns
Parameters
idintstream.id.flagsintbodybytesReturns
core.ready frame body.Returned by stream()
An async iterator of raw agent frames. #### stream.id `int` Protocol correlation id; pass to [`send()`](#client-send) for follow-up frames #### stream.next() ```python theme={null} next() ``` Read the next frame; returns `None` at EOFReturns
`Awaitable[`[`RawFrame`](#rawframe)` \| None]` #### stream.close() ```python theme={null} close() ``` Release the stream handle early; safe to call more than onceReturns
`Awaitable[None]`Returned by request() · yielded by AgentStream
A raw protocol frame with a CBOR-encoded body. ```python theme={null} class RawFrame(TypedDict): id: int flags: int body: bytes ``` | Field | Type | Description | | - | - | - | | id | `int` | Protocol correlation id | | flags | `int` | Frame flag byte (combination of `FLAG_*` constants) | | body | `bytes` | CBOR-encoded protocol message body | # Execution Source: https://docs.microsandbox.dev/sdk/python/execution Run sandbox commands and stream their output with the Python SDK. See [Commands](/sandboxes/commands) for usage examples. ## Sandbox #### sandbox.exec() ```python theme={null} async def exec( cmd: str, args: list[str] | ExecOptions | None = None, *, cwd: str | None = None, user: str | None = None, env: Mapping[str, str] | None = None, timeout: float | None = None, stdin: Stdin | bytes | None = None, tty: bool = False, rlimits: list[Rlimit] | None = None, ) -> ExecOutput ```Parameters
cmdstr"python3", "/usr/bin/node").argslist\[str] | ExecOptions | Noneargs list.cwdstr | Noneuserstr | NoneenvMapping\[str, str] | Nonetimeoutfloat | NonestdinStdin | bytes | Nonebytes are sent inline; default is /dev/null.ttyboolrlimitslist\[Rlimit] | NoneReturns
Parameters
scriptstr"ls -la /app && echo done").cwd, user, env, timeout, stdin, tty, rlimitsReturns
Stream methods
#### sandbox.exec\_stream() ```python theme={null} async def exec_stream( cmd: str, args: list[str] | ExecOptions | None = None, *, cwd: str | None = None, user: str | None = None, env: Mapping[str, str] | None = None, timeout: float | None = None, stdin: Stdin | bytes | None = None, tty: bool = False, rlimits: list[Rlimit] | None = None, ) -> ExecHandle ```Parameters
cmdstrargslist\[str] | ExecOptions | Nonecwd, user, env, timeout, stdin, tty, rlimitsReturns
Parameters
scriptstrcwd, user, env, timeout, stdin, tty, rlimitsReturns
Attach methods
#### sandbox.attach() ```python theme={null} async def attach( cmd: str, args: list[str] | None = None, *, cwd: str | None = None, user: str | None = None, env: Mapping[str, str] | None = None, detach_keys: str | None = None, ) -> int ```Parameters
cmdstrargslist\[str] | Nonecwdstr | Noneuserstr | NoneenvMapping\[str, str] | Nonedetach\_keysstr | None"ctrl-]" or "ctrl-p,ctrl-q").Returns
Returns
Returned by exec\_stream() · shell\_stream()
A handle to a running streaming execution and its events. A configured streaming timeout is enforced by the SDK even when the caller is not reading output. At expiry, the SDK waits for process startup before sending SIGKILL. Waiting or collecting reports `ExecTimeoutError` after the guest confirms exit; cancelling a pending wait does not cancel the deadline. Raw event readers receive the actual exit event. If termination cannot be delivered, the SDK reports a separate error without claiming the process exited. The SDK connection must remain open for this client-owned deadline to run. #### handle.id `str` Correlation ID for this execution #### handle.take\_stdin() ```python theme={null} take_stdin() ``` Take the stdin writer. Returns `None` after the first call, or when stdin wasn't pipedReturns
[`ExecSink`](#execsink) ` \| None` #### handle.recv() ```python theme={null} recv() ``` *(async)* Receive the next event. Returns `None` when the stream endsReturns
[`ExecEvent`](#execevent) ` \| None` #### handle.wait() ```python theme={null} wait() ``` *(async)* Wait for the process to exit. Returns `(code, success)`Returns
`tuple[int, bool]` #### handle.collect() ```python theme={null} collect() ``` *(async)* Drain remaining output and wait for exitReturns
[`ExecOutput`](#execoutput) #### handle.signal() ```python theme={null} signal(sig) ``` *(async)* Send a POSIX signal (numeric) to the process #### handle.kill() ```python theme={null} kill() ``` *(async)* Send SIGKILL to the process #### handle.resize() ```python theme={null} resize(rows, cols) ``` *(async)* Resize the PTY to the given `uint16` dimensions ## ExecSinkReturned by ExecHandle.take\_stdin()
Writer for sending data to a running process's stdin. Obtained from [`ExecHandle.take_stdin()`](#exechandle) when the execution was configured with `stdin=Stdin.pipe()`. #### sink.write() ```python theme={null} write(data) ``` *(async)* Write bytes to the process's stdin #### sink.close() ```python theme={null} close() ``` *(async)* Close the sink. Sends EOF in non-TTY pipe mode; the guest PTY remains open in TTY mode ## StdinUsed by exec() · shell() · exec\_stream() · shell\_stream()
Factory for process stdin configuration. #### Stdin.null() ```python theme={null} Stdin.null() ``` Connect stdin to `/dev/null` (default) #### Stdin.pipe() ```python theme={null} Stdin.pipe() ``` Open a writable pipe. Write via [`take_stdin()`](#exechandle) on the handle #### Stdin.bytes() ```python theme={null} Stdin.bytes(data) ``` Inline data sent before the process starts, then EOF The factories set the corresponding [`StdinMode`](#stdinmode) member. ## RlimitUsed by exec() · shell() · exec\_stream() · shell\_stream()
Frozen dataclass describing a POSIX resource limit. Construct one directly or via a factory, then pass a list as the `rlimits` argument. | Field | Type | Description | | - | - | - | | `resource` | [`RlimitResource`](#rlimitresource) | Which resource is limited | | `soft` | `int` | Soft limit | | `hard` | `int` | Hard limit | #### Rlimit.nofile() ```python theme={null} Rlimit.nofile(limit) ``` Max open file descriptors #### Rlimit.cpu() ```python theme={null} Rlimit.cpu(secs) ``` CPU time limit in seconds #### Rlimit.as\_() ```python theme={null} Rlimit.as_(\*, soft, hard) ``` Virtual memory size #### Rlimit.nproc() ```python theme={null} Rlimit.nproc(limit) ``` Max number of processes #### Rlimit.fsize() ```python theme={null} Rlimit.fsize(limit) ``` Max file size #### Rlimit.memlock() ```python theme={null} Rlimit.memlock(limit) ``` Max locked memory #### Rlimit.stack() ```python theme={null} Rlimit.stack(limit) ``` Max stack size ## Types ### ExecOptionsAccepted by exec() · exec\_stream()
Typed dictionary for passing arguments and per-call options together as the second positional argument. Use a [`Stdin`](#stdin) object to select a mode or raw `bytes` for inline data. | Key | Type | Description | | - | - | - | | args | `list[str]` | Command arguments | | cwd | `str` | Working directory | | user | `str` | Guest user | | env | `Mapping[str, str]` | Per-command environment variables | | timeout | `float` | Timeout in seconds | | stdin | [`Stdin`](#stdin) `\| bytes` | Stdin configuration or inline bytes | | stdin\_data | `bytes` | Inline stdin bytes when `stdin` is omitted | | tty | `bool` | Whether to allocate a pseudo-terminal | | rlimits | `list[`[`Rlimit`](#rlimit)`]` | POSIX resource limits | ### ExecOutputReturned by exec() · shell() · ExecHandle.collect()
The result of a completed command execution: collected output plus exit status. All members are properties. In TTY mode, `stdout_bytes` contains the combined terminal output and `stderr_bytes` is empty because a PTY doesn't preserve separate stdout and stderr streams. | Property | Type | Description | | - | - | - | | exit\_code | `int` | Process exit code | | success | `bool` | `True` when `exit_code == 0` | | stdout\_text | `str` | Collected stdout decoded as UTF-8. Raises on invalid encoding | | stderr\_text | `str` | Collected stderr decoded as UTF-8. Raises on invalid encoding | | stdout\_bytes | `bytes` | Raw stdout bytes | | stderr\_bytes | `bytes` | Raw stderr bytes | ### ExecEventEmitted by ExecHandle
Native event object emitted by [`recv()`](#exechandle) and by iterating an [`ExecHandle`](#exechandle). Fields that don't apply to a given event are `None`. | Property | Type | Description | | - | - | - | | event\_type | [`ExecEventType`](#execeventtype) | Exact event discriminator | | pid | `int \| None` | Guest PID, set on `ExecEventType.STARTED` | | data | `bytes \| None` | Output bytes on `STDOUT` / `STDERR`, or a UTF-8 failure message on `FAILED` / `STDIN_ERROR` | | code | `int \| None` | Exit code on `EXITED`, or errno when available on `FAILED` / `STDIN_ERROR` | ### ExecEventTypeReturned by ExecEvent.event\_type
String enum (`enum.StrEnum`) identifying a streaming execution event. | Member | Value | Description | | - | - | - | | `ExecEventType.STARTED` | `"started"` | Process started; `pid` is populated | | `ExecEventType.STDOUT` | `"stdout"` | Standard-output bytes are available in `data` | | `ExecEventType.STDERR` | `"stderr"` | Standard-error bytes are available in `data` | | `ExecEventType.EXITED` | `"exited"` | Process exited; `code` is populated | | `ExecEventType.FAILED` | `"failed"` | Process startup failed | | `ExecEventType.STDIN_ERROR` | `"stdin_error"` | Writing process stdin failed | ### ExitStatusUsed by ExecHandle.wait()
Frozen dataclass describing a process exit result. [`ExecHandle.wait()`](#exechandle) returns the same information as a `(code, success)` tuple. | Field | Type | Description | | - | - | - | | code | `int` | Process exit code | | success | `bool` | `True` when `code == 0` | ### StdinModeUsed internally by Stdin
String enum (`enum.StrEnum`) identifying how command stdin is connected. | Member | Value | Description | | - | - | - | | `StdinMode.NULL` | `"null"` | Connect stdin to `/dev/null` | | `StdinMode.PIPE` | `"pipe"` | Expose a writable [`ExecSink`](#execsink) | | `StdinMode.BYTES` | `"bytes"` | Send inline bytes, then EOF | ### RlimitResourceUsed by Rlimit.resource
String enum (`enum.StrEnum`) naming a limitable POSIX resource. | Member | Value | Description | | - | - | - | | `RlimitResource.CPU` | `"cpu"` | CPU time | | `RlimitResource.FSIZE` | `"fsize"` | File size | | `RlimitResource.DATA` | `"data"` | Data segment size | | `RlimitResource.STACK` | `"stack"` | Stack size | | `RlimitResource.CORE` | `"core"` | Core file size | | `RlimitResource.RSS` | `"rss"` | Resident set size | | `RlimitResource.NPROC` | `"nproc"` | Number of processes | | `RlimitResource.NOFILE` | `"nofile"` | Open file descriptors | | `RlimitResource.MEMLOCK` | `"memlock"` | Locked memory | | `RlimitResource.AS` | `"as"` | Virtual memory | | `RlimitResource.LOCKS` | `"locks"` | File locks | | `RlimitResource.SIGPENDING` | `"sigpending"` | Pending signals | | `RlimitResource.MSGQUEUE` | `"msgqueue"` | Message queue size | | `RlimitResource.NICE` | `"nice"` | Nice priority ceiling | | `RlimitResource.RTPRIO` | `"rtprio"` | Real-time priority ceiling | | `RlimitResource.RTTIME` | `"rttime"` | Real-time CPU time | ## Managed jobs Run and reconnect to background commands. See [Background jobs](/sandboxes/commands#background-jobs) for lifecycle, retention, and runtime limits. #### sandbox.exec\_detached() ```python theme={null} async def exec_detached( cmd: str, args: list[str] | ExecOptions | None = None, *, cwd: str | None = None, user: str | None = None, env: Mapping[str, str] | None = None, timeout: float | None = None, stdin: Stdin | bytes | None = None, tty: bool = False, rlimits: list[Rlimit] | None = None, ) -> Job ``` Start a job and return after guest startup is confirmed. Uses the same options as [`exec()`](#sandbox-exec). Stdin defaults to a retained pipe; `Stdin.null()` closes it, and bytes supply at most 64 KiB followed by EOF.Parameters
pathstr"/app/config.json".Returns
Parameters
pathstrReturns
Parameters
pathstrReturns
Parameters
pathstrdatabytesParameters
pathstrReturns
Parameters
pathstrReturns
Parameters
pathstrParameters
pathstrReturns
Parameters
pathstrReturns
True if the path exists.Parameters
pathstrParameters
srcstrdststrParameters
srcstrdststrParameters
pathstrParameters
host\_pathstrguest\_pathstrParameters
guest\_pathstrhost\_pathstrReturned by read\_stream()
Async stream for reading a file in chunks. Obtained via [`read_stream()`](#fs-read_stream). Iterate it with `async for chunk in stream:`, or call `collect()` to gather everything at once. #### stream.**aiter**() ```python theme={null} __aiter__() ``` Async iterator. Use `async for chunk in stream:`.Returns
`bytes` #### stream.**anext**() ```python theme={null} __anext__() ``` Async iterator. Use `async for chunk in stream:`.Returns
`bytes` #### stream.collect() ```python theme={null} collect() ``` *(async)* Collect all remaining data into a single `bytes` objectReturns
`bytes` ## FsWriteSinkReturned by write\_stream()
Async writer for streaming data into a file. Obtained via [`write_stream()`](#fs-write_stream). Supports the async context manager protocol, so `async with` closes the sink on exit. #### sink.write() ```python theme={null} write(data) ``` *(async)* Write a chunk of `bytes` to the file #### sink.close() ```python theme={null} close() ``` *(async)* Send EOF and finalize the file #### sink.**aenter**() ```python theme={null} __aenter__() ``` *(async)* Use with `async with` for automatic close on exitReturns
`FsWriteSink` #### sink.**aexit**() ```python theme={null} __aexit__() ``` *(async)* Use with `async with` for automatic close on exitReturns
`FsWriteSink` ## Types ### FsEntryReturned by list()
Metadata for a single directory entry, returned by [`list()`](#fs-list). | Property | Type | Description | | - | - | - | | path | `str` | Full path of the entry | | kind | [`FsEntryKind`](#fsentrykind) | Entry type | | size | `int` | File size in bytes | | mode | `int` | Unix permission bits | | modified | `float \| None` | Last-modified time, milliseconds since the Unix epoch | ### FsEntryKindDescribes FsEntry.kind · FsMetadata.kind
Filesystem entry type returned by [`FsEntry.kind`](#fsentry) and [`FsMetadata.kind`](#fsmetadata). | Member | Value | Description | | - | - | - | | `FsEntryKind.FILE` | `"file"` | Regular file | | `FsEntryKind.DIRECTORY` | `"directory"` | Directory | | `FsEntryKind.SYMLINK` | `"symlink"` | Symbolic link | | `FsEntryKind.OTHER` | `"other"` | Other entry type | ```python theme={null} from microsandbox import FsEntryKind files = [entry for entry in await sb.fs.list("/app") if entry.kind is FsEntryKind.FILE] ``` ### FsMetadataReturned by stat()
Detailed file metadata, returned by [`stat()`](#fs-stat). | Property | Type | Description | | - | - | - | | kind | [`FsEntryKind`](#fsentrykind) | Entry type | | size | `int` | File size in bytes | | mode | `int` | Unix permission bits | | readonly | `bool` | Whether the file is read-only | | modified | `float \| None` | Last-modified time, milliseconds since the Unix epoch | | created | `float \| None` | Creation time, milliseconds since the Unix epoch | # Images Source: https://docs.microsandbox.dev/sdk/python/images Configure sandbox image sources and manage the local cache with the Python SDK. See [Images](/images/overview) for image sources and caching behavior. ## Image Factory for sandbox image sources. #### Image.oci()Parameters
referencestr"python:3.12".root\_diskRootDiskConfig | int | Noneupper\_size\_mibint | Noneroot\_disk=RootDisk.managed(...).Returns
image=.Parameters
pathstrReturns
image=.Parameters
pathstr.qcow2, .raw, .vmdk).fstypestr | None"ext4". None auto-detects.Returns
image=.Cache management
These static methods inspect and prune images already pulled into the local OCI cache. ## Local image cacheParameters
referencestrReturns
Returns
Parameters
referencestrReturns
Parameters
referencestrforceboolFalse.Returns
Parameters
input\_pathstr"-" to read the archive from stdin.tagstr | NoneReturns
Parameters
referencestr | Sequence\[str]output\_pathstrformatImageArchiveFormatDOCKER.Returned by get() · list() · load()
A lightweight handle to a cached OCI image, returned by [`Image.get()`](#image-get), [`Image.list()`](#image-list), and [`Image.load()`](#image-load). Properties are read-only attributes; the two methods are async. | Field | Type | Description | | - | - | - | | `reference` | `str` | Image reference | | `size_bytes` | `int \| None` | Total size in bytes, or `None` when unknown | | `manifest_digest` | `str \| None` | Content-addressable manifest digest | | `architecture` | `str \| None` | Resolved architecture | | `os` | `str \| None` | Resolved operating system | | `layer_count` | `int` | Number of layers | | `last_used_at` | `float \| None` | Last referenced time, milliseconds since epoch | | `created_at` | `float \| None` | First-pulled time, milliseconds since epoch | #### handle.inspect() ```python theme={null} await inspect() ``` Fetch full detail for this imageReturns
[`ImageDetail`](#imagedetail) #### handle.remove() ```python theme={null} await remove(*, force=False) ``` Delete this image (raises [`ImageInUseError`](#errors) unless `force`) ## RootDisk Factory for writable OCI root disk configurations. ```python theme={null} from microsandbox import DiskImageFormat, RootDisk managed = RootDisk.managed(8192) temporary = RootDisk.tmpfs(512) existing = RootDisk.disk( "/data/upper.raw", format=DiskImageFormat.RAW, fstype="ext4", ) ``` #### RootDisk.managed() ```python theme={null} managed(size_mib=None) ``` Microsandbox-managed sparse ext4 diskReturns
[`RootDiskConfig`](#rootdiskconfig) #### RootDisk.tmpfs()Returns
[`RootDiskConfig`](#rootdiskconfig) #### RootDisk.disk()Returns
[`RootDiskConfig`](#rootdiskconfig) ## Types ### ImageSourceReturned by oci() · bind() · disk()
Explicit rootfs image source. Build one with [`Image.oci()`](#image-oci), [`Image.bind()`](#image-bind), or [`Image.disk()`](#image-disk), then pass it as the `image=` kwarg to [`Sandbox.create()`](/sdk/python/sandbox). A frozen dataclass; treat its fields as opaque. | Field | Type | Description | | - | - | - | | `_type` | [`ImageSourceKind`](#imagesourcekind) | Source kind | | `_path` | `str \| None` | Host path for `bind` / `disk` sources | | `_reference` | `str \| None` | OCI reference for `oci` sources | | `_root_disk` | [`RootDiskConfig`](#rootdiskconfig)` \| int \| None` | Writable root disk configuration or managed-disk size in MiB (OCI only) | | `_upper_size_mib` | `int \| None` | Deprecated managed-disk size alias | | `_fstype` | `str \| None` | Filesystem type for `disk` sources | | `_format` | [`DiskImageFormat`](#diskimageformat)` \| None` | Disk image format (inferred from extension) | ### RootDiskConfig Frozen root disk configuration produced by [`RootDisk`](#rootdisk). | Field | Type | Description | | - | - | - | | `kind` | [`RootDiskKind`](#rootdiskkind) | Root disk implementation | | `size_mib` | `int \| None` | Managed disk or tmpfs size | | `path` | `str \| None` | User-supplied disk image path | | `format` | [`DiskImageFormat`](#diskimageformat)` \| None` | Disk image format | | `fstype` | `str \| None` | Inner filesystem type | ### ImageDetailReturned by inspect() · ImageHandle.inspect()
Full detail for a cached image: the core handle, the parsed OCI config block, and per-layer metadata. | Property | Type | Description | | - | - | - | | `handle` | [`ImageHandle`](#imagehandle) | Core cached image metadata | | `config` | [`ImageConfigDetail`](#imageconfigdetail)` \| None` | Parsed OCI config block | | `layers` | `list[`[`ImageLayerDetail`](#imagelayerdetail)`]` | Layers in bottom-to-top order | ### ImageConfigDetailUsed by ImageDetail.config
OCI image config fields extracted from the local cache. | Property | Type | Description | | - | - | - | | `digest` | `str` | Config blob digest | | `env` | `list[str]` | Environment variables (`KEY=value`) | | `cmd` | `list[str] \| None` | Default command | | `entrypoint` | `list[str] \| None` | Image entrypoint | | `working_dir` | `str \| None` | Default working directory | | `user` | `str \| None` | Default user | | `labels` | `dict[str, Any] \| None` | OCI labels | | `stop_signal` | `str \| None` | Configured stop signal | ### ImageLayerDetailUsed by ImageDetail.layers
Metadata for a single image layer. | Property | Type | Description | | - | - | - | | `diff_id` | `str` | Uncompressed layer diff id | | `blob_digest` | `str` | Compressed blob digest | | `media_type` | `str \| None` | Layer media type | | `compressed_size_bytes` | `int \| None` | Compressed size in bytes | | `erofs_size_bytes` | `int \| None` | Size of the generated EROFS sidecar in bytes | | `position` | `int` | Layer position (bottom to top) | ### ImagePruneReportReturned by prune()
Summary of cached image data removed by [`Image.prune()`](#image-prune). | Property | Type | Description | | - | - | - | | `image_refs_removed` | `int` | Number of image refs removed | | `manifests_removed` | `int` | Number of manifests removed | | `layers_removed` | `int` | Number of layer blobs removed | | `fsmeta_removed` | `int` | Number of fsmeta sidecar files removed | | `vmdk_removed` | `int` | Number of VMDK files removed | | `bytes_reclaimed` | `int \| None` | Measured bytes reclaimed, or `None` when not measured | ### DiskImageFormatUsed by ImageSource.\_format
Disk image container format. | Member | Value | Description | | - | - | - | | `DiskImageFormat.QCOW2` | `"qcow2"` | QEMU copy-on-write v2 | | `DiskImageFormat.RAW` | `"raw"` | Raw block image | | `DiskImageFormat.VMDK` | `"vmdk"` | VMware disk image | ### ImageArchiveFormatUsed by Image.save(format=...)
Archive layout used when exporting cached images. | Member | Value | Description | | - | - | - | | `ImageArchiveFormat.DOCKER` | `"docker"` | Docker archive compatible with `docker load` | | `ImageArchiveFormat.OCI` | `"oci"` | OCI Image Layout archive | ### ImageSourceKindReturned in ImageSource.\_type
Root filesystem source kind. | Member | Value | Description | | - | - | - | | `ImageSourceKind.OCI` | `"oci"` | OCI image reference | | `ImageSourceKind.BIND` | `"bind"` | Host directory bind source | | `ImageSourceKind.DISK` | `"disk"` | Host disk-image source | ### RootDiskKindReturned in RootDiskConfig.kind
Writable OCI root disk implementation. | Member | Value | Description | | - | - | - | | `RootDiskKind.MANAGED` | `"managed"` | Microsandbox-managed sparse ext4 disk | | `RootDiskKind.TMPFS` | `"tmpfs"` | Ephemeral RAM-backed upper layer | | `RootDiskKind.DISK_IMAGE` | `"disk-image"` | User-supplied writable disk image | ### Errors Image operations raise these typed exceptions, all subclasses of `MicrosandboxError`. | Exception | Raised when | | - | - | | `ImageNotFoundError` | The image reference could not be resolved in the local cache | | `ImageInUseError` | The image is still referenced by one or more sandboxes (and `force` was not set) | | `ImagePullFailedError` | An image pull failed | | `UnsupportedError` | Cache operations were attempted on a backend that lacks a local cache | # Networking Source: https://docs.microsandbox.dev/sdk/python/networking Configure sandbox network policies with the Python SDK. See [Networking](/networking/overview) for network policies, DNS, TLS, and port publishing. ## NetworkUsed by Sandbox.create(network=...)
Sandbox network configuration. ```python theme={null} Network( policy: NetworkPolicy | None = None, ports: Mapping[int, int] | Sequence[PortBinding] = {}, deny_domains: tuple[str, ...] = (), deny_domain_suffixes: tuple[str, ...] = (), dns: DnsConfig | None = None, tls: TlsConfig | None = None, strict: bool = True, ipv4_pool: str | None = None, ipv6_pool: str | None = None, nat64_prefixes: tuple[str, ...] = ("64:ff9b::/96",), max_tcp_connections: int | None = None, max_udp_connections: int | None = None, tcp_accept_queue_size: int | None = None, secret_violation_action: ViolationAction = ViolationAction.BLOCK_AND_LOG, http: HttpConfig | None = None, ) ``` | Field | Type | Default | Description | | - | - | - | - | | `policy` | [`NetworkPolicy \| None`](#networkpolicy) | `None` | Concrete network policy | | `ports` | [`Mapping[int, int] \| Sequence[PortBinding]`](#portbinding) | `{}` | Port mappings from host to guest. Mapping form binds TCP to `127.0.0.1`; [`PortBinding`](#portbinding) can set an explicit bind address or UDP | | `deny_domains` | `tuple[str, ...]` | `()` | Deny egress to these exact domains. Each entry adds a `deny Domain("...")` policy rule that fires at DNS resolution (NXDOMAIN), TLS first-flight (SNI), and TCP egress (cache fallback). Prepended onto the policy so it takes precedence over later allow rules | | `deny_domain_suffixes` | `tuple[str, ...]` | `()` | Deny egress to all subdomains of these suffixes. Adds `deny DomainSuffix("...")` rules; same enforcement layers as `deny_domains` | | `dns` | [`DnsConfig \| None`](#dnsconfig) | `None` | DNS interception configuration | | `tls` | [`TlsConfig \| None`](#tlsconfig) | `None` | TLS interception configuration | | `strict` | `bool` | `True` | Require hostname-based policy allows to use an inspectable request authority. Plain HTTP exposes that authority in `Host`; HTTPS only exposes it when TLS interception is enabled and not bypassed. Without that visibility, strict mode denies HTTPS that would otherwise be allowed only by a hostname rule. | | `ipv4_pool` | `str \| None` | `None` | IPv4 pool used for per-sandbox `/30` guest subnets. Defaults to `172.16.0.0/12` | | `ipv6_pool` | `str \| None` | `None` | IPv6 pool used for per-sandbox `/64` guest prefixes. Defaults to `fd42:6d73:62::/48` | #### network.tcp\_accept\_queue\_size `int \| None` · Default: `None` (1,024) How many not-yet-accepted connections each published TCP port's host listener queues, from 1 to 2,147,483,647. Connections arriving while the queue is full never reach the sandbox, so raise this when a burst of parallel connections, such as a reverse proxy fanning out one page load, exceeds it. The host kernel caps the effective depth at its own `somaxconn` (4,096 by default on Linux, 128 on macOS). `Sandbox.restore(..., tcp_accept_queue_size=n)` applies it to the listeners a restored child publishes. #### network.nat64\_prefixes `tuple[str, ...]` · Default: `("64:ff9b::/96",)` NAT64 `/96` prefixes for policy classification. Destinations inside these prefixes are also evaluated by their embedded IPv4 address. Pass this field by keyword. Custom or empty prefix lists are supported only for local sandboxes; cloud creation rejects them. #### max\_udp\_connections `Network(max_udp_connections=512)` sets the runtime UDP relay session limit. Omission is unlimited in single-tenant mode and defaults to 1,024 in multi-tenant mode; zero explicitly selects unlimited. At a finite limit, a new session evicts the least recently active session. Sessions expire after 60 seconds of inactivity. #### network.max\_tcp\_connections `max_connections` remains a deprecated TCP-only alias. Specifying both names is an error. Either name can be combined with the UDP limit. `int \| None` · Default: `None` Maximum concurrent TCP connections. Zero selects unlimited. The same limits can be selected when restoring, without changing the captured guest interface: ```python theme={null} restored = await Sandbox.restore( "saved", name="child", max_tcp_connections=64, max_udp_connections=128, ) ``` Omitted restore limits use destination defaults. `restore_with_progress()` accepts the same options; `max_connections` remains a deprecated TCP-only alias, and supplying both TCP names is an error. | Field | Type | Default | Description | | - | - | - | - | | `rate_limiter` | [`NetworkRateLimiter \| None`](#networkratelimiter) | `None` | Ingress and egress rate limitsReturns
Returns
Returns
Used by NetworkPolicy(rules=...)
Frozen dataclass for a single network policy rule. Prefer the [`Rule.allow()`](#rule-allow) / [`Rule.deny()`](#rule-deny) class methods over the positional constructor. ```python theme={null} Rule( action: Action, direction: Direction = Direction.EGRESS, destination: str | NetworkDestination | None = None, protocol: Protocol | None = None, port: int | str | None = None, ) ``` | Field | Type | Default | Description | | - | - | - | - | | `action` | [`Action`](#action) | — | What to do when this rule matches | | `direction` | [`Direction`](#direction) | `EGRESS` | Which evaluator considers this rule. `Direction.ANY` matches in either direction | | `destination` | [`str \| NetworkDestination \| None`](#networkdestination) | `None` | Target filter. Prefer typed [`Destination`](#destination) helpers; string shorthand also works ([`DestGroup`](#destgroup) values, exact IPs, domains, CIDR ranges, domain suffixes prefixed with `"."`, or `"*"` for any). Domain and suffix strings are validated at sandbox creation; invalid names raise `ValueError` | | `protocol` | [`Protocol \| None`](#protocol) | `None` | Protocol filter | | `port` | `int \| str \| None` | `None` | Single port (`443`) or range (`"8000-9000"`) | Ingress rules carrying ICMP protocols are rejected at sandbox creation; the host has no inbound ICMP path. Use `Direction.EGRESS` for ICMP allow/deny. A [`NetworkPolicy`](#networkpolicy) is an ordered list of [`Rule`](#rule) values plus two per-direction defaults, evaluated first-match-wins per direction. The class methods below build rules; assemble them into `NetworkPolicy(rules=(...))` and pass it as `Network(policy=...)`. ```python theme={null} from microsandbox import Action, Destination, NetworkPolicy, Protocol, Rule policy = NetworkPolicy( default_egress=Action.DENY, default_ingress=Action.ALLOW, rules=( Rule.allow(protocol=Protocol.TCP, port=443, destination=Destination.ip("1.1.1.1")), Rule.deny(destination=Destination.domain("api.example.com")), ), ) ``` ### Rule order matters The first matching rule wins, so a broad rule placed before a narrow one swallows it: ```python theme={null} policy = NetworkPolicy( default_egress=Action.DENY, default_ingress=Action.ALLOW, rules=( Rule.allow(destination="10.0.0.0/8"), # matches everything in 10.x Rule.deny(destination="10.0.0.5"), # never reached ), ) ``` Put specific rules before general ones. #### Rule.allow() ```python theme={null} @classmethod def allow( *, direction: Direction = Direction.EGRESS, protocol: Protocol | None = None, port: int | str | None = None, destination: str | NetworkDestination | None = None, ) -> Rule ```Parameters
directionDirectionEGRESS.protocolProtocol | Noneportint | str | None443) or range ("8000-9000").destinationstr | NetworkDestination | NoneReturns
Parameters
directionDirectionEGRESS.protocolProtocol | Noneportint | str | None8000-9000. Invalid values and reversed ranges raise ValueError; omit the filter to match any port.destinationstr | NetworkDestination | NoneReturns
Returns
(udp\_rule, tcp\_rule) for DestGroup.HOST on port 53.Returns NetworkDestination · used by Rule.allow() / Rule.deny()
Factory for typed [`NetworkDestination`](#networkdestination) values. #### Destination.any() ```python theme={null} @staticmethod def any() -> NetworkDestination ``` Match any destination. #### Destination.ip() ```python theme={null} @staticmethod def ip(ip: str) -> NetworkDestination ``` Match an exact IPv4 or IPv6 address. Stored as `/32` for IPv4 or `/128` for IPv6.Parameters
ipstrParameters
cidrstr"10.0.0.0/8".Parameters
domainstrParameters
suffixstr".example.com".Parameters
groupDestGroupUsed by Network(ports=...)
Frozen dataclass for a published host-to-guest port with an optional host bind address. Prefer the [`PortBinding.tcp()`](#portbinding-tcp) / [`PortBinding.udp()`](#portbinding-udp) class methods. ```python theme={null} PortBinding( host_port: int, guest_port: int, bind: str = "127.0.0.1", protocol: PortProtocol = PortProtocol.TCP, ) ``` | Field | Type | Default | Description | | - | - | - | - | | `host_port` | `int` | — | Port on the host | | `guest_port` | `int` | — | Port inside the sandbox | | `bind` | `str` | `"127.0.0.1"` | Host address to bind. Use `0.0.0.0` for all IPv4 interfaces | #### binding.protocol [`PortProtocol`](#portprotocol) · Default: `TCP` Published port protocol [`PortBinding`](#portbinding) is a frozen dataclass for published ports that need an explicit host bind address or UDP. Prefer the protocol-specific constructors over building one by hand. ```python theme={null} PortBinding.tcp(8001, 8001, bind="0.0.0.0") PortBinding.udp(5353, 5353, bind="0.0.0.0") ``` Pass them to `Network(ports=(...))`. A plain `dict[int, int]` is also accepted for the common case, binding TCP to `127.0.0.1`. #### PortBinding.tcp() ```python theme={null} @classmethod def tcp(cls, host_port: int, guest_port: int, *, bind: str = "127.0.0.1") -> PortBinding ``` Publish a TCP port from the sandbox to the host.Parameters
host\_portintguest\_portintbindstr127.0.0.1; use 0.0.0.0 for all IPv4 interfaces.Returns
Parameters
host\_portintguest\_portintbindstr127.0.0.1.Returns
Used by Network(policy=...)
Ordered rules with per-direction defaults. ```python theme={null} NetworkPolicy( default_egress: Action = Action.DENY, default_ingress: Action = Action.ALLOW, rules: tuple[Rule, ...] = (), ) ``` | Field | Type | Default | Description | | - | - | - | - | | `default_egress` | [`Action`](#action) | `DENY` | Action when no egress-applicable rule matches | | `default_ingress` | [`Action`](#action) | `ALLOW` | Action when no ingress-applicable rule matches | | `rules` | [`tuple[Rule, ...]`](#rule) | `()` | Rules evaluated first-match-wins per direction | Class methods `none()` and `allow_all()` construct terminal whole policies. `from_profiles(profiles)` composes [`NetworkProfile`](#networkprofile) values with canonical ordering and automatic gateway DNS. #### NetworkPolicy.none() ```python theme={null} NetworkPolicy.none() ``` Deny all ingress and egress trafficReturns
`NetworkPolicy` #### NetworkPolicy.allow\_all() ```python theme={null} NetworkPolicy.allow_all() ``` Allow all ingress and egress trafficReturns
`NetworkPolicy` #### NetworkPolicy.from\_profiles() ```python theme={null} NetworkPolicy.from_profiles(profiles) ``` Compose the selected canonical network profilesReturns
`NetworkPolicy` ## Types ### NetworkProfile | Member | Value | Description | | - | - | - | | `NetworkProfile.PUBLIC` | `"public"` | Public internet addresses | | `NetworkProfile.PRIVATE` | `"private"` | Private/LAN ranges | | `NetworkProfile.HOST` | `"host"` | Sandbox host gateway addresses | ### NetworkDestinationProduced by Destination helpers
Frozen dataclass produced by [`Destination`](#destination) helpers. ```python theme={null} NetworkDestination( kind: NetworkDestinationKind, value: str | None = None, ) ``` | Field | Type | Default | Description | | - | - | - | - | | kind | [`NetworkDestinationKind`](#networkdestinationkind) | - | Destination variant | | value | `str \| None` | `None` | Variant value, omitted for `Destination.any()` | ### NetworkDestinationKindReturned in NetworkDestination.kind
Network destination variant. | Member | Value | Description | | - | - | - | | `NetworkDestinationKind.ANY` | `"any"` | Any destination | | `NetworkDestinationKind.IP` | `"ip"` | One IP address | | `NetworkDestinationKind.CIDR` | `"cidr"` | One CIDR network | | `NetworkDestinationKind.DOMAIN` | `"domain"` | One exact domain | | `NetworkDestinationKind.DOMAIN_SUFFIX` | `"domain_suffix"` | A domain suffix and its subdomains | | `NetworkDestinationKind.GROUP` | `"group"` | A well-known [`DestGroup`](#destgroup) | ### DnsConfigUsed by Network(dns=...)
Frozen dataclass for DNS interception settings. The value type of [`Network.dns`](#network); import it from `microsandbox.types`. ```python theme={null} DnsConfig( rebind_protection: bool = True, nameservers: tuple[str, ...] = (), query_timeout_ms: int | None = None, ) ``` | Field | Type | Default | Description | | - | - | - | - | | rebind\_protection | `bool` | `True` | Block DNS responses resolving to private IPs | | nameservers | `tuple[str, ...]` | `()` | Nameservers (`IP`, `IP:PORT`, `HOST`, or `HOST:PORT`). Overrides the host's `/etc/resolv.conf` when set. Hostnames are resolved once at startup via the host's OS resolver | | query\_timeout\_ms | `int \| None` | `None` | Per-DNS-query timeout in milliseconds. Defaults to `5000` | ### TlsConfigUsed by Network(tls=...)
Frozen dataclass for TLS interception settings within [`Network`](#network). ```python theme={null} TlsConfig( bypass: tuple[str, ...] = (), verify_upstream: bool = True, intercepted_ports: tuple[int, ...] = (443,), block_quic: bool = False, upstream_ca_certs: tuple[str, ...] = (), scoped_upstream_ca_certs: tuple[ScopedUpstreamCACert, ...] = (), scoped_verify_upstream: tuple[ScopedVerifyUpstream, ...] = (), ca_cert: str | None = None, ca_key: str | None = None, ca_cn: str | None = None, ) ``` | Field | Type | Default | Description | | - | - | - | - | | bypass | `tuple[str, ...]` | `()` | Domains to skip interception. Use for domains with certificate pinning | | verify\_upstream | `bool` | `True` | Verify upstream server certificates. Set to `False` only for self-signed servers | | intercepted\_ports | `tuple[int, ...]` | `(443,)` | TCP ports where TLS interception is active | | block\_quic | `bool` | `False` | Block QUIC/HTTP3 (UDP) on intercepted ports, forcing TCP/TLS fallback | | upstream\_ca\_certs | `tuple[str, ...]` | `()` | Paths to additional CA bundles trusted for every upstream host | | scoped\_upstream\_ca\_certs | `tuple[ScopedUpstreamCACert, ...]` | `()` | Host-pattern-scoped CA bundles trusted only for matching upstream hosts | | scoped\_verify\_upstream | `tuple[ScopedVerifyUpstream, ...]` | `()` | Host-pattern-scoped upstream certificate verification overrides | | ca\_cert | `str \| None` | `None` | Path to a custom interception CA certificate PEM file | | ca\_key | `str \| None` | `None` | Path to a custom interception CA private key PEM file | | ca\_cn | `str \| None` | `None` | Common name for the generated interception CA | ### ScopedUpstreamCACertUsed by TlsConfig(scoped\_upstream\_ca\_certs=...)
A CA bundle trusted only for upstream hosts matching a pattern. ```python theme={null} ScopedUpstreamCACert( pattern: str, path: str, ) ``` | Field | Type | Description | | - | - | - | | pattern | `str` | Exact host or `*.suffix` wildcard | | path | `str` | CA bundle path trusted for matching upstream hosts | ### ScopedVerifyUpstreamUsed by TlsConfig(scoped\_verify\_upstream=...)
A per-host override for upstream certificate verification. ```python theme={null} ScopedVerifyUpstream( pattern: str, verify: bool, ) ``` | Field | Type | Description | | - | - | - | | pattern | `str` | Exact host or `*.suffix` wildcard | | verify | `bool` | Whether to verify certificates for matching upstream hosts | ### NetworkRateLimiterUsed by Network.rate\_limiter
Groups local network limits by traffic direction. An omitted direction is unlimited. | Field | Type | Description | | - | - | - | | egress | [`RateLimiter`](#ratelimiter)` \| None` | Guest-to-runtime rate limiter | | ingress | [`RateLimiter`](#ratelimiter)` \| None` | Runtime-to-guest rate limiter | ### RateLimiterHeld by NetworkRateLimiter
Limits bandwidth and packet rate for one traffic direction. | Field | Type | Description | | - | - | - | | bandwidth | [`TokenBucket`](#tokenbucket)` \| None` | Byte budget; one token per byte of frame data | | ops | [`TokenBucket`](#tokenbucket)` \| None` | Packet budget; one token per network frame | ### TokenBucketUsed by RateLimiter
Token-bucket configuration for one rate-limiter dimension. | Field | Type | Description | | - | - | - | | size | `int` | Bucket capacity in bytes or frames. Must be greater than zero | | refill\_time\_ms | `int` | Time to refill `size` tokens. Must be greater than zero | | one\_time\_burst | `int` | Extra startup-only tokens. Default: `0` | ### ActionUsed by NetworkPolicy · Rule
Policy action. | Member | Value | Description | | - | - | - | | `Action.ALLOW` | `"allow"` | Permit the traffic | | `Action.DENY` | `"deny"` | Drop the traffic silently | ### DirectionUsed by Rule
String enum for traffic direction. | Member | Value | Description | | - | - | - | | `Direction.EGRESS` | `"egress"` | Traffic leaving the sandbox | | `Direction.INGRESS` | `"ingress"` | Traffic entering the sandbox (via published ports) | | `Direction.ANY` | `"any"` | Rule applies in either direction | ### ProtocolUsed by Rule
String enum for network protocols in policy rules. | Member | Value | Description | | - | - | - | | `Protocol.TCP` | `"tcp"` | TCP traffic | | `Protocol.UDP` | `"udp"` | UDP traffic | | `Protocol.ICMPV4` | `"icmpv4"` | ICMPv4 traffic | | `Protocol.ICMPV6` | `"icmpv6"` | ICMPv6 traffic | ### PortProtocolUsed by PortBinding
String enum for port-level protocol selection. | Member | Value | Description | | - | - | - | | `PortProtocol.TCP` | `"tcp"` | TCP port | | `PortProtocol.UDP` | `"udp"` | UDP port | ### DestGroupUsed by Destination.group()
String enum for well-known destination groups used in [`Destination.group()`](#destination-group) or string-shorthand [`Rule.destination`](#rule). | Member | Value | Description | | - | - | - | | `DestGroup.PUBLIC` | `"public"` | Complement of the named categories: every address not in any other group | | `DestGroup.PRIVATE` | `"private"` | Private/RFC 1918 addresses + ULA + CGN (`10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `100.64.0.0/10`, `fc00::/7`) | | `DestGroup.LOOPBACK` | `"loopback"` | Loopback addresses (`127.0.0.0/8`, `::1`); the **guest's own** loopback, not the host. See the [loopback-vs-host watch-out](/networking/overview#reaching-the-host) | | `DestGroup.LINK_LOCAL` | `"link-local"` | Link-local addresses (`169.254.0.0/16`, `fe80::/10`) excluding metadata | | `DestGroup.METADATA` | `"metadata"` | Cloud metadata endpoints (`169.254.169.254`) | | `DestGroup.MULTICAST` | `"multicast"` | Multicast addresses (`224.0.0.0/4`, `ff00::/8`) | | `DestGroup.HOST` | `"host"` | The host machine, reached via `host.microsandbox.internal`. This is the right group for "let the sandbox reach my host's localhost", not `"loopback"` | # Proxies Source: https://docs.microsandbox.dev/sdk/python/proxies Route outbound sandbox connections through an HTTP CONNECT, SOCKS4, or SOCKS5 proxy with the Python SDK. Configure one HTTP CONNECT, SOCKS4, or SOCKS5 proxy for outbound sandbox connections with the `proxy=` argument to [`Sandbox.create()`](/sdk/python/sandbox#sandbox-create). Proxy protocols are mutually exclusive. See [Proxies](/networking/outbound-proxy) for routing behavior, security considerations, and limits.Instance properties
#### sb.owns\_lifecycle ```python theme={null} @property async def owns_lifecycle(self) -> bool ``` Whether this handle owns the sandbox lifecycle. Local attached sandboxes returned by [`create()`](#sandbox-create) or [`start()`](#sandbox-start) own lifecycle. Local detached sandboxes, cloud sandboxes, and handles upgraded via [`SandboxHandle.connect()`](#sandboxhandle) return `False`. This is an async property; use `await sb.owns_lifecycle`.Returns
True if this handle owns the lifecycle.Returns
Static methods
#### Sandbox.create()Parameters
namestr\*\*kwargsSandboxConfigimage, cpus, memory, volumes, ports, network, proxy, secrets, detached, and more.Returns
Parameters
namestr\*\*kwargsSandboxConfigReturns
Parameters
* `name`: reusable sandbox name, up to 128 UTF-8 bytes. * `**kwargs`: the same creation fields accepted by [`Sandbox.create()`](#sandbox-create), used only if creation is necessary.Returns
[`Sandbox`](#instance-methods) #### Sandbox.start() ```python theme={null} @staticmethod async def start(name: str, *, detached: bool = False) -> Sandbox ```Parameters
namestrdetachedboolTrue, the sandbox survives after your process exits. Default False.Returns
Parameters
namestrReturns
Returns
Parameters
cursorstr | Nonenext\_cursor from the preceding page.limitint | NonelabelsMapping\[str, str] | NoneNone returns every sandbox, like list().Returns
Parameters
namestrInstance methods
Command execution (`exec`, `exec_stream`, `shell`, `shell_stream`) is documented on the [Execution](/sdk/python/execution) page; SSH (`ssh`) on the [SSH](/sdk/python/ssh) page. The lifecycle, attach, metrics, and logs methods follow. #### sb.name() ```python theme={null} async def name(self) -> str ```Returns
Parameters
cmdstrargslist\[str] | Nonecwdstr | Noneuserstr | NoneenvMapping\[str, str] | Nonedetach\_keysstr | NoneReturns
Returns
Returns
Returns
Parameters
cpusint | Nonemax\_cpus.max\_cpusint | Nonememoryint | Nonemax\_memory.max\_memoryint | Noneroot\_disk\_sizeint | NoneenvMapping\[str, str] | Noneenv\_rmlist\[str] | NonelabelsMapping\[str, str] | Nonelabels\_rmlist\[str] | Noneworkdirstr | NonesecretsMapping\[str, SecretModifySpec] | Noneenv, value, or store, plus optional placeholder and allowed\_hosts.secrets\_rmlist\[str] | NoneNO\_RESTART (default) applies only changes that can complete without restarting; NEXT\_START persists changes for the next start without mutating a running VM; RESTART restarts if needed so restart-required changes become active now.dry\_runboolTrue, compute the plan without applying anything. Default False.Returns
dry\_run=True.Returns
Parameters
intervalfloat1.0.Returns
Parameters
tailint | Nonesince\_msfloat | Noneuntil\_msfloat | Nonesourceslist\[LogReadSource] | NoneNone selects STDOUT, STDERR, and OUTPUT. Add SYSTEM to merge runtime/kernel diagnostics, or use ALL for all four.Returns
Parameters
sourceslist\[LogReadSource] | Nonesince\_msfloat | Nonefrom\_cursorstr | Noneuntil\_msfloat | NonefollowboolTrue, keep the stream open and yield new entries as they arrive. Default False.Returns
Parameters
timeoutfloat | NoneNone waits indefinitely; expiry raises StopTimeoutError without killing.Parameters
timeoutfloat | NoneReturns
Parameters
pathstrcontentstrmodeint | None0o644.replaceboolTrue, overwrite an existing path.Parameters
pathstrcontentbytesmodeint | None0o644.replaceboolTrue, overwrite an existing path.Parameters
pathstrcontentstrParameters
pathstrmodeint | None0o755.Parameters
pathstrParameters
srcstrdststrmodeint | None0o644. None keeps the source mode.replaceboolTrue, overwrite an existing path at dst.Parameters
srcstrdststrreplaceboolTrue, overwrite an existing path at dst.Parameters
targetstrlinkstrreplaceboolTrue, overwrite an existing path at link.Returned by Sandbox.get() · Sandbox.list() · Sandbox.list\_with()
A metadata and lifecycle handle for an existing sandbox. | Field | Type | Description | | - | - | - | | `name` | `str` | Sandbox name, up to 128 UTF-8 bytes | | `id` | `str` | Opaque stable identity captured by this metadata handle. Receiver lifecycle calls remain bound to this value and raise `SandboxReplacedError` when the reusable name now points to another sandbox. | | `status` | [`SandboxStatus`](#sandboxstatus) | Current status | | `config_json` | `str` | Raw JSON configuration | | `created_at` | `float \| None` | Creation timestamp (ms since epoch) | | `updated_at` | `float \| None` | Last update timestamp (ms since epoch) | #### handle.config()Returns
`dict[str, Any]` #### handle.refresh() ```python theme={null} refresh() ``` Re-fetch status and metadata, returning a fresh handleReturns
`Awaitable[`[`SandboxHandle`](#sandboxhandle)`]` #### handle.ping()Returns
`Awaitable[`[`SandboxPingResult`](#sandboxpingresult)`]` #### handle.touch()Returns
`Awaitable[`[`SandboxTouchResult`](#sandboxtouchresult)`]` #### handle.modify()Returns
`Awaitable[`[`SandboxModificationPlan`](#sandboxmodificationplan)`]` #### handle.connect() ```python theme={null} connect(timeout=None) ``` Connect to a running sandbox, optionally with an explicit timeout in secondsReturns
`Awaitable[`[`Sandbox`](#instance-methods)`]` #### handle.connect\_or\_start() ```python theme={null} async def connect_or_start(self, *, detached: bool = False) -> Sandbox ``` Connect when this exact sandbox is running, wait through `STARTING`, or start it when it is `CREATED`, `STOPPED`, or `CRASHED`. `DRAINING` and `PAUSED` are rejected. `detached=True` affects only a required local start; connecting to an already-running sandbox does not change ownership. #### handle.wait\_for\_status() ```python theme={null} async def wait_for_status(self, status: SandboxStatus) -> SandboxHandle ``` Wait without a built-in timeout until this exact sandbox reaches `status`, returning a refreshed handle. Raises `SandboxReplacedError` rather than rebinding to a replacement. #### handle.restart() ```python theme={null} async def restart( self, *, force: bool = False, timeout: float | None = None, detached: bool = False, ) -> Sandbox ``` Restart this exact sandbox with the same state and option semantics as [`sb.restart()`](#sb-restart). #### handle.destroy() ```python theme={null} async def destroy(self, *, force: bool = False, timeout: float | None = None) -> None ``` Stop and remove this exact sandbox. A stale handle cannot destroy a same-name replacement. #### handle.start() ```python theme={null} start(*, detached=False) ``` Start in attached or detached modeReturns
`Awaitable[`[`Sandbox`](#instance-methods)`]` #### handle.stop()Returns
`Awaitable[None]` #### handle.request\_stop() ```python theme={null} request_stop() ``` Request graceful shutdown without waitingReturns
`Awaitable[None]` #### handle.kill()Returns
`Awaitable[None]` #### handle.request\_kill()Returns
`Awaitable[None]` #### handle.request\_drain()Returns
`Awaitable[None]` #### handle.wait\_until\_stopped() ```python theme={null} wait_until_stopped() ``` Block until the sandbox reaches terminal stateReturns
`Awaitable[`[`SandboxStopResult`](#sandboxstopresult)`]` #### handle.remove() ```python theme={null} remove() ``` Delete sandbox and stateReturns
`Awaitable[None]` #### handle.metrics()Returns
`Awaitable[`[`SandboxMetrics`](#sandboxmetrics)`]` #### handle.logs()Returns
`Awaitable[list[`[`LogEntry`](#logentry)`]]` #### handle.log\_stream() ```python theme={null} log_stream(...) ``` Stream captured log entries (works without starting)Returns
`Awaitable[`[`LogStream`](#logstream)`]` #### handle.snapshot()Returns
`Awaitable[Snapshot]` ## MetricsStreamReturned by metrics\_stream()
Async stream for receiving periodic metrics snapshots. #### metrics\_stream.**aiter**() ```python theme={null} __aiter__() ``` Use with `async for`Returns
[`SandboxMetrics`](#sandboxmetrics) #### metrics\_stream.**anext**() ```python theme={null} __anext__() ``` Use with `async for`Returns
[`SandboxMetrics`](#sandboxmetrics) ## LogEntryReturned by logs() · iterated from LogStream
A single captured log entry returned by [`logs()`](#sb-logs) or iterated from a [`LogStream`](#logstream). | Field | Type | Description | | - | - | - | | `timestamp_ms` | `float` | Wall-clock capture time (ms since Unix epoch, UTC) | | `source` | [`LogSource`](#logsource) | Where the chunk came from | | `session_id` | `int \| None` | Relay-monotonic session id; `None` for `"system"` entries | | `cursor` | `str` | Opaque resume token; pass back via `log_stream(from_cursor=...)` | | `data` | `bytes` | The chunk's raw bytes | #### entry.text() ```python theme={null} text() ``` Convenience: UTF-8 decode of `data` (lossy; invalid bytes are replaced)Returns
`str` ## LogStreamReturned by log\_stream()
Async stream of [`LogEntry`](#logentry) values, returned by [`log_stream()`](#sb-log_stream). #### log\_stream.**aiter**() ```python theme={null} __aiter__() ``` Use with `async for`Returns
[`LogEntry`](#logentry) #### log\_stream.**anext**() ```python theme={null} __anext__() ``` Use with `async for`Returns
[`LogEntry`](#logentry) ## PullSessionReturned by create\_with\_progress()
Returned by [`create_with_progress()`](#sandbox-create_with_progress). The factory itself is synchronous; use the returned session as an async context manager to track image pull progress. #### session.progress `AsyncIterator[`[`PullEvent`](#pullevent)`]` Async iterator of pull progress events #### session.result() ```python theme={null} result() ``` Await once to get the final running sandbox. A second call raises `RuntimeError`Returns
`Awaitable[`[`Sandbox`](#instance-methods)`]` ```python theme={null} session = Sandbox.create_with_progress("my-sandbox", image="ubuntu:latest") async with session: async for event in session.progress: print(event) sb = await session.result() ``` ## Types ### SandboxConfigUsed by create() · create\_with\_progress()
Used by create(init=...)
Custom init specification. Pass it (or one of the equivalent shorthand shapes) as the `init=` kwarg to [`create()`](#sandbox-create) to hand PID 1 inside the guest off to your own init binary after agentd's setup. Frozen dataclass. See [Custom init system](/sandboxes/bootstrap#custom-init-system) for image picks, shutdown semantics, and tradeoffs. | Field | Type | Default | Description | | - | - | - | - | | cmd | `str` | - | Absolute path or `"auto"` to the init binary. Auto honors a known image ENTRYPOINT init before probing `/sbin/init`, `/lib/systemd/systemd`, and `/usr/lib/systemd/systemd`, and preserves attached init-entrypoint commands | | args | `tuple[str, ...]` | `()` | Supplemental argv (`argv[0]` is implicitly `cmd`) | | env | `Mapping[str, str]` | `{}` | Extra env vars merged on top of the inherited env | The `init=` kwarg accepts a bare scalar for the simple case, an [`InitConfig`](#initconfig) dataclass, or an [`InitOptions`](#initoptions) typed dictionary for the rich case. | Form | Equivalent to | | - | - | | `init="auto"` or `init="/sbin/init"` | `InitConfig(cmd=...)` | | `init={"cmd": ..., "args": [...], "env": {...}}` | dict equivalent of `InitConfig` | | `init=InitConfig(cmd="/sbin/init", args=("--foo",))` | itself | ```python theme={null} from microsandbox import InitConfig, Sandbox # Common case: bare string. sb = await Sandbox.create("worker", image="jrei/systemd-debian:12", init="auto") # Argv / env: dataclass. sb = await Sandbox.create( "worker", image="jrei/systemd-debian:12", init=InitConfig( cmd="/lib/systemd/systemd", args=("--unit=multi-user.target",), env={"container": "microsandbox"}, ), ) ``` ### InitOptionsUsed by create(init=...)
Typed-dictionary form of [`InitConfig`](#initconfig). `cmd` is required; `args` and `env` are optional. | Key | Type | Description | | - | - | - | | `cmd` | `str` | Absolute path or `"auto"` to the init binary | | `args` | `list[str]` | Supplemental argv | | `env` | `dict[str, str]` | Extra environment variables | ### SecurityProfileUsed by create(security=...)
Sandbox-wide in-guest security profile. | Member | Value | Description | | - | - | - | | `SecurityProfile.DEFAULT` | `"default"` | Standard profile | | `SecurityProfile.RESTRICTED` | `"restricted"` | Sets `no_new_privs`, drops mount-admin capability from user commands, and forces `nosuid,nodev` on user mounts | ### SandboxPage One stable, newest-first page returned by [`Sandbox.list()`](#sandbox-list) or [`Sandbox.list_with()`](#sandbox-list_with). | Property | Type | Description | | - | - | - | | `sandboxes` | `list[SandboxHandle]` | Handles in this page | | `next_cursor` | `str \| None` | Opaque continuation cursor, or `None` on the final page | ### SandboxPingResultReturned by ping()
Agent reachability result. | Property | Type | Description | | - | - | - | | name | `str` | Sandbox name | | latency\_ms | `float` | Round-trip latency in milliseconds | ### SandboxTouchResultReturned by touch()
Explicit idle-refresh result. | Property | Type | Description | | - | - | - | | name | `str` | Sandbox name | | activity\_seq | `int` | Monotonic activity sequence after the touch | ### SandboxStopResultReturned by wait\_until\_stopped()
Observed terminal sandbox state returned by [`wait_until_stopped()`](#sb-wait_until_stopped). | Property | Type | Description | | - | - | - | | name | `str` | Sandbox name | | status | [`SandboxStatus`](#sandboxstatus) | Terminal status that was observed | | exit\_code | `int \| None` | Process exit code when it is available | | signal | `int \| None` | Terminating signal number when the sandbox was killed by a signal | | observed\_at | `float` | When the terminal state was observed (ms since epoch) | | source | `str \| None` | Where the terminal observation came from | ### SandboxStatusUsed by SandboxHandle.status · SandboxStopResult.status
Sandbox lifecycle status returned by `status` fields. | Member | Value | Description | | - | - | - | | `SandboxStatus.CREATED` | `"created"` | Sandbox metadata exists but the VM has not started | | `SandboxStatus.STARTING` | `"starting"` | A start request is in progress | | `SandboxStatus.RUNNING` | `"running"` | Guest agent is ready; `exec`, `shell`, and `fs` work | | `SandboxStatus.STOPPED` | `"stopped"` | VM shut down; configuration persisted; can be restarted | | `SandboxStatus.CRASHED` | `"crashed"` | VM exited unexpectedly (kernel panic, OOM, etc.) | | `SandboxStatus.DRAINING` | `"draining"` | Graceful shutdown in progress; existing commands finish, new ones rejected | | `SandboxStatus.PAUSED` | `"paused"` | VM paused | ### BackendKindUsed by set\_default\_backend() · backend\_scope() · returned by default\_backend\_kind()
Used by modify(policy=...)
Controls how sandbox modifications that cannot apply live are handled. | Member | Value | Description | | - | - | - | | `ModificationPolicy.NO_RESTART` | `"no_restart"` | Apply only changes that do not require a restart | | `ModificationPolicy.NEXT_START` | `"next_start"` | Persist changes for the next start without restarting a running VM | | `ModificationPolicy.RESTART` | `"restart"` | Restart when required so changes become active immediately | ### SecretModifySpecUsed by modify(secrets=...)
Desired state for one secret. `env`, `value`, and `store` are mutually exclusive sources. Omit all three to update only the supplied policy or placeholder fields. | Key | Type | Description | | - | - | - | | `env` | `str` | Host environment variable to resolve when applying the modification | | `value` | `str` | Raw secret value. Stored in the durable sandbox config until replaced by a source reference | | `store` | `str` | Reserved for a host-side secret store reference; currently unsupported | | `placeholder` | `str` | Explicit guest-visible placeholder. New secrets default to `$MSB_Returned by metrics() · metrics\_stream()
Point-in-time resource usage snapshot. | Field | Type | Description | | - | - | - | | cpu\_percent | `float` | CPU usage as a percentage | | vcpu\_time\_ns | `int` | Cumulative vCPU time consumed since boot, in nanoseconds | | memory\_bytes | `int` | Current memory usage in bytes | | memory\_available\_bytes | `int \| None` | Guest-reported available memory in bytes when known | | memory\_host\_resident\_bytes | `int \| None` | Host-resident memory backing the guest in bytes when known | | memory\_limit\_bytes | `int` | Memory limit in bytes | | disk\_read\_bytes | `int` | Total bytes read from disk since boot | | disk\_write\_bytes | `int` | Total bytes written to disk since boot | | net\_rx\_bytes | `int` | Total bytes received over the network since boot | | net\_tx\_bytes | `int` | Total bytes sent over the network since boot | | upper\_used\_bytes | `int \| None` | Guest-visible OCI upper filesystem used bytes when the protected reporter is available and fresh | | upper\_free\_bytes | `int \| None` | Guest-visible OCI upper filesystem free bytes when the protected reporter is available and fresh | | upper\_host\_allocated\_bytes | `int \| None` | Host-allocated bytes for the writable OCI upper image when available | | uptime\_ms | `int` | Time since the sandbox was created (ms) | | timestamp\_ms | `float` | When this measurement was taken (ms since epoch) | ### LogSourceReturned by LogEntry.source
Source attached to each [`LogEntry`](#logentry). | Member | Value | Description | | - | - | - | | `LogSource.STDOUT` | `"stdout"` | Captured from a session's stdout (pipe mode, streams stayed separated) | | `LogSource.STDERR` | `"stderr"` | Captured from a session's stderr (pipe mode) | | `LogSource.OUTPUT` | `"output"` | Captured from a PTY session, where stdout and stderr are merged by the guest kernel | | `LogSource.SYSTEM` | `"system"` | Synthetic lifecycle or runtime diagnostic entry | ### LogReadSourceUsed by logs(sources=...) · log\_stream(sources=...)
Log source selector accepted by `logs()` and `log_stream()`. | Member | Value | Description | | - | - | - | | `LogReadSource.STDOUT` | `"stdout"` | Select stdout entries | | `LogReadSource.STDERR` | `"stderr"` | Select stderr entries | | `LogReadSource.OUTPUT` | `"output"` | Select PTY-merged output entries | | `LogReadSource.SYSTEM` | `"system"` | Select lifecycle and runtime diagnostic entries | | `LogReadSource.ALL` | `"all"` | Select all four sources | ### LogLevelUsed by create(log\_level=...)
Sandbox process log verbosity. | Member | Value | Description | | - | - | - | | `LogLevel.TRACE` | `"trace"` | Most verbose, all diagnostic output | | `LogLevel.DEBUG` | `"debug"` | Debug and higher | | `LogLevel.INFO` | `"info"` | Info and higher | | `LogLevel.WARN` | `"warn"` | Warnings and errors only | | `LogLevel.ERROR` | `"error"` | Errors only | ### PullPolicyUsed by create(pull\_policy=...)
Controls when the SDK fetches an OCI image from the registry. | Member | Value | Description | | - | - | - | | `PullPolicy.ALWAYS` | `"always"` | Pull the image every time, even if cached locally | | `PullPolicy.IF_MISSING` | `"if-missing"` | Pull only if the image is not already cached. This is the default | | `PullPolicy.NEVER` | `"never"` | Never pull; fail if the image is not cached locally | ### RegistryAuthUsed by create(registry\_auth=...)
Credentials for authenticating to a private container registry. Frozen dataclass; construct directly or via `RegistryAuth.basic(username, password)`. | Field | Type | Description | | - | - | - | | username | `str` | Registry username | | password | `str` | Registry password | ### PatchConfigReturned by Patch.\* factory methods · used by create(patches=...)
A single rootfs patch. Produced by the [`Patch`](#patch) factory; you'd normally not construct one directly. Frozen dataclass. | Field | Type | Description | | - | - | - | | kind | [`PatchKind`](#patchkind) | Patch operation | | path | `str \| None` | Absolute guest path (text / file / mkdir / remove / append) | | content | `str \| bytes \| None` | Text content for `TEXT` / `APPEND`, or binary content for `FILE` | | src | `str \| None` | Host source path (copy\_file / copy\_dir) | | dst | `str \| None` | Guest destination path (copy\_file / copy\_dir) | | target | `str \| None` | Symlink target | | link | `str \| None` | Symlink path | | mode | `int \| None` | File / directory mode for text, file, copy-file, or mkdir patches (e.g. `0o644`) | | replace | `bool` | When `True`, overwrite an existing destination for text, file, copy, or symlink patches. Defaults to `False` | ### PatchKindUsed by PatchConfig.kind
Rootfs patch operation. | Member | Value | Description | | - | - | - | | `PatchKind.TEXT` | `"text"` | Write a UTF-8 text file | | `PatchKind.FILE` | `"file"` | Write an arbitrary binary file | | `PatchKind.APPEND` | `"append"` | Append to a text file | | `PatchKind.COPY_FILE` | `"copy_file"` | Copy a host file into the guest | | `PatchKind.COPY_DIR` | `"copy_dir"` | Copy a host directory into the guest | | `PatchKind.SYMLINK` | `"symlink"` | Create a symbolic link | | `PatchKind.MKDIR` | `"mkdir"` | Create a directory | | `PatchKind.REMOVE` | `"remove"` | Remove a path | ### PullEventIterated from PullSession.progress
Native event object emitted by [`PullSession.progress`](#pullsession). Inspect `event_type` and the fields relevant to that event; fields that do not apply to a particular event are `None`. | Field | Type | Description | | - | - | - | | event\_type | [`PullEventType`](#pulleventtype) | Event discriminator | | reference | `str \| None` | Image reference being pulled | | manifest\_digest | `str \| None` | Resolved manifest digest | | layer\_count | `int \| None` | Number of layers | | total\_download\_bytes | `int \| None` | Total bytes to download across layers | | layer\_index | `int \| None` | Index of the layer this event concerns | | digest | `str \| None` | Layer blob digest | | diff\_id | `str \| None` | Layer diff id | | downloaded\_bytes | `int \| None` | Bytes downloaded so far for the layer | | total\_bytes | `int \| None` | Total bytes for the layer | | bytes\_read | `int \| None` | Bytes read during materialization | ```python theme={null} from microsandbox import PullEventType, Sandbox session = Sandbox.create_with_progress("my-sandbox", image="ubuntu:latest") async with session: async for event in session.progress: if event.event_type is PullEventType.RESOLVED: print(f"{event.layer_count} layers, {event.total_download_bytes} bytes") elif event.event_type is PullEventType.LAYER_DOWNLOAD_PROGRESS: print(f"layer {event.layer_index}: {event.downloaded_bytes}/{event.total_bytes}") sb = await session.result() ``` ### PullEventType Discriminator returned by [`PullEvent.event_type`](#pullevent). | Member | Value | Description | | - | - | - | | `PullEventType.RESOLVING` | `"resolving"` | Resolving the image reference | | `PullEventType.RESOLVED` | `"resolved"` | Manifest resolved | | `PullEventType.LAYER_DOWNLOAD_PROGRESS` | `"layer_download_progress"` | Layer download advanced | | `PullEventType.LAYER_DOWNLOAD_COMPLETE` | `"layer_download_complete"` | Layer download completed | | `PullEventType.LAYER_DOWNLOAD_VERIFYING` | `"layer_download_verifying"` | Layer digest is being verified | | `PullEventType.LAYER_MATERIALIZE_STARTED` | `"layer_materialize_started"` | Layer materialization started | | `PullEventType.LAYER_MATERIALIZE_PROGRESS` | `"layer_materialize_progress"` | Layer materialization advanced | | `PullEventType.LAYER_MATERIALIZE_WRITING` | `"layer_materialize_writing"` | Materialized layer is being written | | `PullEventType.LAYER_MATERIALIZE_COMPLETE` | `"layer_materialize_complete"` | Layer materialization completed | | `PullEventType.STITCH_MERGING_TREES` | `"stitch_merging_trees"` | Layer trees are being merged | | `PullEventType.STITCH_WRITING_FSMETA` | `"stitch_writing_fsmeta"` | Filesystem metadata is being written | | `PullEventType.STITCH_WRITING_VMDK` | `"stitch_writing_vmdk"` | VMDK image is being written | | `PullEventType.STITCH_COMPLETE` | `"stitch_complete"` | Image stitching completed | | `PullEventType.COMPLETE` | `"complete"` | Image pull completed | # Secrets Source: https://docs.microsandbox.dev/sdk/python/secrets Configure destination-bound sandbox credentials with the Python SDK. See [Secrets](/sandboxes/secrets) for usage examples and security boundaries. ## Secret #### Secret.env() ```python theme={null} @staticmethod def env( env_var: str, *, value: str, allow: Sequence[str] = (), allow_placeholder_for: Sequence[str] = (), passthrough: Sequence[str] = (), # deprecated alias placeholder: str | None = None, require_tls_identity: bool = True, violation_action: ViolationAction | None = None, substitution: SecretSubstitution | None = None, ) -> SecretEntry ```Parameters
env\_varstr= or NUL; shell-identifier syntax is not required.valuestrallowSequence\[str]().allow\_placeholder\_forSequence\[str]().placeholderstr | None\$MSB\_\ when None. Default None.require\_tls\_identityboolTrue.violation\_actionViolationAction | NoneNone inherits the network setting, whose default is BLOCK\_AND\_LOG.substitutionSecretSubstitution | NoneNone uses SecretSubstitution() defaults. Default None.Returns
Sandbox.create(secrets=\[...]).Returned by Secret.env()
A single secret entry, used in `Sandbox.create(secrets=[...])`. Construct it with [`Secret.env()`](#secret-env) rather than directly. | Field | Type | Default | Description | | - | - | - | - | | env\_var | `str` | required | Environment variable name (non-empty, no `=` or NUL) | | value | `str` | required | Secret value. Never enters the guest | | allow | `tuple[str, ...]` | `()` | Exact or wildcard hosts allowed to receive the real value | | passthrough | `tuple[str, ...]` | `()` | Exact or wildcard hosts allowed to receive the unchanged placeholder | | placeholder | `str \| None` | `None` | Placeholder string: non-empty, up to 1024 bytes, no NUL/CR/LF. Auto-generated as `$MSB_Used by Secret.env() · SecretEntry.violation\_action
String enum defining the blocking action when a placeholder cannot be substituted or passed through. Set the sandbox-wide default with `Network.secret_violation_action` or the top-level `Sandbox.create(secret_violation_action=...)`; the top-level value takes precedence if both are supplied. A secret's `violation_action` overrides that default. Passthrough is a host policy, not an enum member. | Member | Value | Description | | - | - | - | | `ViolationAction.BLOCK` | `"block"` | Silently drop the request. The guest sees a connection reset. | | `ViolationAction.BLOCK_AND_LOG` | `"block-and-log"` | Drop the request and emit a warning log on the host side. This is the default. | | `ViolationAction.BLOCK_AND_TERMINATE` | `"block-and-terminate"` | Drop the request, log an error, and shut down the entire sandbox. | ### SecretViolationErrorSubclass of MicrosandboxError
Returned by snapshot() · Snapshot.create() · Snapshot.open() · Snapshot.list\_dir() · handle.open()
Create, open, and manage snapshots. See [properties](#snapshot-properties) for returned metadata. #### Snapshot.create() ```python theme={null} @staticmethod async def create( name: str = "", *, from_sandbox: str, group: str | None = None, dest_dir: str | os.PathLike[str] | None = None, labels: dict[str, str] | None = None, force: bool = False, record_integrity: bool = False, full: bool = False, guest_flush: GuestFlush | None = None, ) -> Snapshot ``` Create a disk snapshot, or set `full=True` to include memory and execution state. `name` identifies a member within `group`; an omitted name is generated and an omitted group uses the source sandbox's name. `dest_dir` selects the parent directory containing the group. `from_sandbox` names the sandbox to capture and is required.Parameters
namestrfrom\_sandboxstrdest\_dirstr | os.PathLike\[str] | Nonelabelsdict\[str, str] | NoneforceboolFalse for installed group members. Since v0.7, True raises InvalidConfigError even when the name does not exist. Use a new or generated member name, or explicitly remove the existing member before recreating it. See the v0.6 upgrade example. Direct archive capture supports overwriting its output file.record\_integrityboolFalse.fullboolTrue: capture disk, memory, execution, and device state from a running or paused sandbox. Default False captures disk state; locally, the source can be running, paused, stopped, or crashed. Cloud requires False and a stopped persistent source.guest\_flushGuestFlush | NoneAUTO; see guest writeback.Returns
Parameters
path\_or\_namestrgroup:member, or artifact directory path.Returns
Parameters
name\_or\_digeststrgroup:member, stable snapshot ID, descriptor digest, or artifact path.Returns
Returns
Parameters
dirstr | os.PathLikeReturns
Parameters
path\_or\_namestrgroup:member, or artifact path.forceboolFalse.Parameters
dirstr | os.PathLike | NoneReturns
Parameters
name\_or\_pathstrgroup:member or artifact path to save.outstr | os.PathLikewith\_parentsboolFalse.with\_imageboolFalse.plain\_tarbool.tar instead of .msb. Default False.Parameters
archivestr | os.PathLike.msb or .tar).deststr | os.PathLike | NoneReturns
Returns
upper.kind field is "not\_recorded" when no integrity hash was stored, or "verified" with the recomputed digest.Returns
Parameters
forceboolFalse.Parameters
namestrReturns
Returned by snapshot() · Snapshot.create() · Snapshot.open() · Snapshot.list\_dir() · handle.open()
A fully parsed backend-neutral snapshot. Properties are read-only attributes. | Property / Method | Type | Description | | - | - | - | | `id` | `str` | Stable opaque snapshot identity | | `path` | `str` | Local artifact directory; raises `UnsupportedError` on cloud | | `reference` | `str` | Stable backend-relative restore reference | | `reference_kind` | `Literal["id", "path"]` | How the selected backend resolves the reference | | `digest` | `str` | Canonical descriptor digest (`sha256:hex`), separate from the stable ID | | `size_bytes` | `int \| None` | Backend-reported stored payload size in bytes | | `image_ref` | `str` | Image reference the snapshot was taken from | | `image_manifest_digest` | `str` | OCI manifest digest of the pinned image | | `state_kind` | [`SnapshotStateKind`](#snapshotstatekind) | File-backed or checkpoint-backed state | | `format` | [`SnapshotFormat`](#snapshotformat)` \| None` | On-disk format for file-backed state | | `scope` | [`SnapshotScope`](#snapshotscope) | Captured state scope | | `fstype` | `str \| None` | Filesystem type for file-backed state (e.g. `"ext4"`) | | `checkpoint_id` | `str \| None` | Checkpoint identifier for checkpoint-backed state | | `checkpoint_manifest_digest` | `str \| None` | Checkpoint manifest digest for checkpoint-backed state | | `parent` | `str \| None` | Parent snapshot's digest, or `None` for a root | | `created_at` | `str` | RFC 3339 timestamp | | `labels` | `dict[str, str]` | User-supplied labels | | `source_sandbox` | `str \| None` | Best-effort source-sandbox name | | `save_to(...)` | `Awaitable[None]` | Bundle through the backend retained by this snapshot | | `copy_to(path)` | [`SnapshotCopyBuilder`](#snapshotcopybuilder) | Configure a copied archive with replacement metadata | | `verify()` | `Awaitable[dict[str, Any]]` | Recompute and check the upper-layer integrity hash. See [`verify()`](#snap-verify) | ### SnapshotCopyBuilder Returned by [`Snapshot.copy_to()`](#snap-copy_to). Setters mutate the builder and return it so calls can be chained. | Method | Returns | Description | | - | - | - | | `labels(dict[str, str])` | `SnapshotCopyBuilder` | Replace all labels in the copied manifest | | `record_integrity(bool)` | `SnapshotCopyBuilder` | Compute integrity when true, or omit it when false | | `save()` | `Awaitable[None]` | Write the configured archive | ### SnapshotHandleReturned by Snapshot.get() · Snapshot.list() · Snapshot.load()
Lightweight handle returned by the active backend. Properties are read-only. | Property / Method | Type | Description | | - | - | - | | `id` | `str` | Stable opaque snapshot identity | | `path` | `str` | Local artifact directory; raises `UnsupportedError` on cloud | | `digest` | `str` | Canonical descriptor digest, separate from the stable ID | | `name` | `str \| None` | Convenience alias | | `parent_digest` | `str \| None` | Parent snapshot digest, or `None` for a root | | `image_ref` | `str` | Image the snapshot was taken from | | `state_kind` | [`SnapshotStateKind`](#snapshotstatekind) | File-backed or checkpoint-backed state | | `format` | [`SnapshotFormat`](#snapshotformat)` \| None` | On-disk format for file-backed state | | `scope` | [`SnapshotScope`](#snapshotscope) | Captured state scope | | `fstype` | `str \| None` | Filesystem type for file-backed state | | `checkpoint_manifest_digest` | `str \| None` | Checkpoint manifest digest for checkpoint-backed state | | `size_bytes` | `int \| None` | Backend-reported stored payload size, when known | | `locality` | `str` | Artifact locality reported by the index | | `availability` | `str` | Artifact availability reported by the index | | `migration_state` | `str` | Current migration state | | `migration_error_code` | `str \| None` | Migration error code, when migration failed | | `created_at` | `float` | ms since Unix epoch | | `reference` | `str` | Stable backend-relative restore reference | | `reference_kind` | `Literal["id", "path"]` | How the selected backend resolves the reference | | `open()` | `Awaitable[`[`Snapshot`](#snapshot)`]` | Load full metadata. See [`open()`](#handle-open) | | `remove(force=False)` | `Awaitable[None]` | Delete the artifact and its index row. See [`remove()`](#handle-remove) | | `save_to(...)` | `Awaitable[None]` | Bundle through the backend retained by this handle | ### SnapshotStateKindReturned by Snapshot.state\_kind · SnapshotHandle.state\_kind
Snapshot state representation. | Member | Value | Description | | - | - | - | | `SnapshotStateKind.FILE` | `"file"` | File-backed upper-layer state | | `SnapshotStateKind.CHECKPOINT` | `"checkpoint"` | Checkpoint-manifest-backed state | ### SnapshotFormatReturned by Snapshot.format · SnapshotHandle.format
On-disk format for file-backed snapshot state. | Member | Value | Description | | - | - | - | | `SnapshotFormat.RAW` | `"raw"` | Raw disk image | | `SnapshotFormat.QCOW2` | `"qcow2"` | QEMU copy-on-write v2 image | ### SnapshotScopeReturned by Snapshot.scope · SnapshotHandle.scope
Captured snapshot state scope. | Member | Value | Description | | - | - | - | | `SnapshotScope.DISK` | `"disk"` | Disk-only state | | `SnapshotScope.FULL` | `"full"` | Disk, memory, and device state | ```python theme={null} from microsandbox import SnapshotFormat, SnapshotScope, SnapshotStateKind assert snapshot.state_kind is SnapshotStateKind.FILE assert snapshot.format is SnapshotFormat.RAW assert snapshot.scope is SnapshotScope.DISK ``` # SSH Source: https://docs.microsandbox.dev/sdk/python/ssh Open sandbox SSH sessions and transfer files over SFTP with the Python SDK. See [SSH](/sandboxes/ssh) for client sessions, server endpoints, and file transfer workflows. [Managed inactivity timeouts](/configuration#ssh) take precedence over all timeout options below, including disabling the timeout. This applies to local and cloud sessions using the sandbox backend's retained configuration. ## Sandbox #### sb.ssh() ```python theme={null} def ssh() -> SandboxSshOps ```Returns
Returned by sb.ssh()
SSH operations for a sandbox. #### ssh.open\_client() ```python theme={null} async def open_client( *, user: str = "root", term: str | None = None, sftp: bool = True, inactivity_timeout: float | None = None, ) -> SshClient ```Parameters
userstr"root".termstr | None\$TERM.sftpboolTrue.inactivity\_timeoutfloat | None0 disables the timeout; None inherits the global setting.Returns
Parameters
host\_key\_pathstr | os.PathLike\[str] | Noneauthorized\_keys\_pathstr | os.PathLike\[str] | Noneuserstr | NonesftpboolTrue.inactivity\_timeoutfloat | None0 disables the timeout; None inherits the global setting.Returns
Returned by ssh.open\_client()
Native in-process SSH client session. A connected, native in-process SSH client session, obtained from [`ssh.open_client()`](#ssh-open_client). #### client.exec() ```python theme={null} async def exec(command: str, *, tty: bool = False) -> SshOutput ```Parameters
commandstrttyboolFalse.Returns
Parameters
termstr | None\$TERM.detach\_keysstr | None"ctrl-p,ctrl-q".Returns
Returns
Returned by ssh.prepare\_server()
Reusable SSH server endpoint for a sandbox. A reusable SSH server endpoint for a sandbox, obtained from [`ssh.prepare_server()`](#ssh-prepare_server). #### server.serve\_connection() ```python theme={null} async def serve_connection() -> None ```Returned by client.sftp()
High-level SFTP client session over an SSH connection. All methods are async. #### sftp.read() ```python theme={null} read(path) ``` Read a file into memory.Returns
`bytes` #### sftp.write() ```python theme={null} write(path, data) ``` Write a file, creating or truncating it. #### sftp.mkdir() ```python theme={null} mkdir(path) ``` Create a directory. #### sftp.remove\_file() ```python theme={null} remove_file(path) ``` Remove a file. #### sftp.remove\_dir() ```python theme={null} remove_dir(path) ``` Remove an empty directory. #### sftp.rename() ```python theme={null} rename(old_path, new_path) ``` Rename a file or directory. #### sftp.real\_path() ```python theme={null} real_path(path) ``` Resolve a path to its canonical absolute form.Returns
`str` #### sftp.read\_link() ```python theme={null} read_link(path) ``` Read a symlink target.Returns
`str` #### sftp.symlink() ```python theme={null} symlink(target, link_path) ``` Create a symlink. #### sftp.close() ```python theme={null} close() ``` Close the SFTP session. ## Types ### SshOutputReturned by client.exec()
Output from an SSH exec request. | Property | Type | Description | | - | - | - | | status | `int` | Exit status code. | | success | `bool` | Whether the command exited successfully. | | stdout\_text | `str` | Stdout as UTF-8 text. | | stderr\_text | `str` | Stderr as UTF-8 text. | | stdout\_bytes | `bytes` | Stdout as raw bytes. | | stderr\_bytes | `bytes` | Stderr as raw bytes. | # Volumes Source: https://docs.microsandbox.dev/sdk/python/volumes Create and mount persistent sandbox volumes with the Python SDK. See [Volumes](/sandboxes/volumes) for usage examples. ## VolumeInstance properties
| Field | Type | Description | | - | - | - | | `name` | `str` | Volume name. | | `path` | `str` | Host path to the volume's directory.Static methods
#### Volume.get\_default()Parameters
namestrkindVolumeKindDIRECTORY.size\_mibint | Nonekind=VolumeKind.DISK.quota\_mibint | Nonelabelsdict\[str, str] | NoneReturns
name and path.Parameters
namestrReturns
Returns
Parameters
namestrMount factories
Static factory methods on `Volume` that build a [`MountConfig`](#mountconfig). Pass the result as a value in the `volumes` dict when creating a sandbox, keyed by the guest mount point. #### Volume.bind()Parameters
pathstrreadonlyboolnoexecboolnosuidboolnodevboolstat\_virtualizationStatVirtualization | Nonehost\_permissionsHostPermissions | Noneuidint | Nonegid.gidint | Noneuid.Returns
Parameters
namestrsize\_mibint | Nonequota\_mibint | Nonereadonlyboolnoexecboolnosuidboolnodevboolstat\_virtualizationStatVirtualization | Nonehost\_permissionsHostPermissions | Noneuidint | Nonegid and use only with directory-backed volumes.gidint | Noneuid and use only with directory-backed volumes.Returns
Parameters
size\_mibint | NonereadonlyboolnoexecboolnosuidboolnodevboolReturns
Parameters
pathstrformatDiskImageFormat | Nonefstypestr | NonereadonlyboolnoexecboolnosuidboolnodevboolReturns
Returned by Volume.get(), Volume.list()
A lightweight handle to a named volume, with its database metadata and a host-side filesystem accessor. | Field | Type | Description | | - | - | - | | `name` | `str` | Volume name | | `kind` | [`VolumeKind`](#volumekind) | Volume storage kind | | `quota_mib` | `int \| None` | Storage quota in MiB | | `used_bytes` | `int` | Current disk usage in bytes | | `capacity_bytes` | `int \| None` | Disk capacity in bytes | | `disk_format` | [`DiskImageFormat \| None`](#diskimageformat) | Disk image format | | `disk_fstype` | `str \| None` | Disk filesystem type | | `labels` | `dict[str, str]` | Metadata labels | | `created_at` | `float \| None` | Creation timestamp (ms since epoch) | | `fs` | [`VolumeFs`](#volumefs) | Host-side filesystem handle | #### handle.remove() ```python theme={null} remove() ``` Delete this volumeReturns
*(async)* `None` ## VolumeFsReturned by VolumeHandle.fs
Host-side filesystem operations for a named volume. #### fs.read() ```python theme={null} async def read(path: str) -> bytes ```Parameters
pathstrReturns
Parameters
pathstrReturns
Parameters
pathstrdatabytesParameters
pathstrReturns
Parameters
pathstrParameters
pathstrParameters
pathstrReturns
True if the path exists.Returned by Volume.bind(), Volume.named(), Volume.tmpfs(), Volume.disk()
Frozen dataclass representing a mount configuration. Build one with a [mount factory](#mount-factories) and pass it as a value in the sandbox `volumes` dict. `stat_virtualization`, `host_permissions`, `override_uid`, and `override_gid` apply only to virtiofs-backed mounts (`BIND` and directory-backed `NAMED`). Owner IDs must be supplied together, must be integers from `0` through `4294967295`, and cannot be combined with `StatVirtualization.OFF`. | Field | Type | Default | Description | | - | - | - | - | | kind | [`MountKind`](#mountkind) | - | Type of mount (required) | | bind | `str \| None` | `None` | Host path for bind mounts | | named | `str \| None` | `None` | Volume name for named mounts | | named\_mode | [`NamedVolumeMode`](#namedvolumemode)` \| None` | `None` | Named-volume creation behavior | | named\_kind | [`VolumeKind`](#volumekind)` \| None` | `None` | Storage kind for created named volumes | | quota\_mib | `int \| None` | `None` | Quota in MiB for directory named volumes | | size\_mib | `int \| None` | `None` | Size limit for tmpfs, or capacity for disk named volumes | | readonly | `bool` | `False` | Whether the mount is read-only | | noexec | `bool` | `False` | Whether direct execution from the mount is disabled | | nosuid | `bool` | `False` | Whether setuid/setgid privilege elevation is ignored | | nodev | `bool` | `False` | Whether device files on the mount are ignored | | disk | `str \| None` | `None` | Host path to a disk image for disk mounts | | format | [`DiskImageFormat`](#diskimageformat)` \| None` | `None` | Disk image format for disk mounts | | fstype | `str \| None` | `None` | Inner filesystem type for disk mounts | | stat\_virtualization | [`StatVirtualization`](#statvirtualization)` \| None` | `None` | Per-mount stat-virtualization policy (virtiofs-backed only) | | host\_permissions | [`HostPermissions`](#hostpermissions)` \| None` | `None` | Per-mount host-permission policy (virtiofs-backed only) | | override\_uid | `int \| None` | `None` | Guest uid fallback for host files without a per-file override; set through factory `uid=` with `gid=` | | override\_gid | `int \| None` | `None` | Guest gid fallback for host files without a per-file override; set through factory `gid=` with `uid=` | ### MountKindUsed by MountConfig
String enum (`StrEnum`) for the type of mount. | Member | Value | Description | | - | - | - | | `MountKind.BIND` | `"bind"` | Host bind mount | | `MountKind.NAMED` | `"named"` | Named volume mount | | `MountKind.TMPFS` | `"tmpfs"` | In-memory filesystem | | `MountKind.DISK` | `"disk"` | Host disk image mount | ### VolumeKindUsed by Volume.create() · Volume.named() · VolumeHandle.kind
Storage kind for a named volume. | Member | Value | Description | | - | - | - | | `VolumeKind.DIRECTORY` | `"dir"` | Directory-backed volume mounted through virtiofs | | `VolumeKind.DISK` | `"disk"` | Raw ext4 disk-image volume mounted through virtio-blk | ### NamedVolumeModeUsed by Volume.named(mode=...) · MountConfig.named\_mode
Creation behavior for a named volume mount. | Member | Value | Description | | - | - | - | | `NamedVolumeMode.EXISTING` | `"existing"` | Require the named volume to exist | | `NamedVolumeMode.CREATE` | `"create"` | Create a new named volume | | `NamedVolumeMode.ENSURE_EXISTS` | `"ensure-exists"` | Reuse the named volume if present, otherwise create it | ### DiskImageFormatUsed by Volume.disk(), MountConfig
String enum (`StrEnum`) for the format of a backing disk image. | Member | Value | Description | | - | - | - | | `DiskImageFormat.QCOW2` | `"qcow2"` | QEMU copy-on-write v2 image | | `DiskImageFormat.RAW` | `"raw"` | Raw disk image | | `DiskImageFormat.VMDK` | `"vmdk"` | VMware disk image | ### StatVirtualizationUsed by MountConfig.stat\_virtualization
Stat virtualization policy for virtiofs-backed mounts. | Member | Value | Description | | - | - | - | | `StatVirtualization.STRICT` | `"strict"` | Fully virtualize guest-visible ownership and mode metadata | | `StatVirtualization.RELAXED` | `"relaxed"` | Apply relaxed metadata virtualization | | `StatVirtualization.OFF` | `"off"` | Expose host stat metadata directly | ### HostPermissionsUsed by MountConfig.host\_permissions
Host permission policy for virtiofs-backed mounts. | Member | Value | Description | | - | - | - | | `HostPermissions.PRIVATE` | `"private"` | Keep host-side permissions private to microsandbox | | `HostPermissions.MIRROR` | `"mirror"` | Mirror relevant host permissions into the guest view | # VSock Source: https://docs.microsandbox.dev/sdk/python/vsock Connect a sandbox to host Unix sockets or local Windows named pipes over virtio-vsock with the Python SDK. See [Host sockets](/networking/host-sockets) for guest connection details, platform support, and security considerations.Returns
Returns
Returns
Returns
Returns
Parameters
pathStringReturns
Parameters
pathStringReturns
Parameters
api\_keyStringurlString | nilReturns
Parameters
nameStringReturns
Parameters
commandStringargsArray\cwdStringuserStringenvHashtimeoutNumericstdinString | :null | :pipettyBooleanrlimitsHashReturns
Parameters
scriptStringoptionsHashReturns
Parameters
tailIntegersourcesArray\Returns
Returns
Returns
Returns
Returns
Returns
Returns
Returns
Returns
Returns
Returns
Returns
Returns
Parameters
pathStringReturns
Parameters
pathStringdataStringReturns
Parameters
pathStringReturns
Parameters
pathStringReturns
Parameters
pathStringReturns
Parameters
pathStringReturns
Parameters
fromStringtoStringReturns
Parameters
fromStringtoStringReturns
Parameters
pathStringReturns
Parameters
pathStringReturns
Parameters
host\_pathStringguest\_pathStringReturns
Parameters
guest\_pathStringhost\_pathStringReturns
Fields
"path"String"kind"String"size"Integer"mode"Integer"uid", "gid"Integer"modified", "accessed"String"readonly"Boolean"created"StringParameters
referenceStringReturns
Returns
Parameters
referenceStringforceBooleanReturns
Returns
Returns
Returns
Returns
Returns
Returns
Returns
Returns
Fields
allowed\_hostsArray\allowed\_portsArray\Fields
envStringvalueStringallowed\_hostStringParameters
addressStringReturns
Parameters
addressStringReturns
Parameters
valueStringReturns
Parameters
usernameStringpasswordSecretSourceReturns
Parameters
nameStringReturns
Class methods
#### Microsandbox::Sandbox.create() ```ruby theme={null} Microsandbox::Sandbox.create(name, **options) # => Sandbox ```Parameters
nameStringimageStringcpusIntegermax\_cpusIntegermemoryIntegermax\_memoryIntegerenvHashlabelsHashworkdirStringshellStringhostnameStringuserStringdetachedBooleanephemeralBooleanmax\_durationIntegeridle\_timeoutIntegerreplaceBooleanreplace\_timeoutNumericroot\_diskIntegerdisable\_networkBooleannetworkSymbol | HashproxyOutboundProxysecretsArray\quiet\_logsBooleanentrypointArray\initStringpull\_policyStringscriptsHashslugStringReturns
Parameters
nameStringReturns
Parameters
nameStringdetachedBooleanReturns
Parameters
nameStringReturns
Parameters
cursorStringlimitIntegerlabelsHashReturns
Parameters
nameStringReturns
Parameters
nameStringoptionsHashReturns
Parameters
nameStringoptionsHashReturns
Instance methods
#### sandbox.name ```ruby theme={null} sandbox.name # => String ```Returns
Returns
Returns
Returns
Returns
Parameters
timeoutNumericReturns
Returns
Returns
Returns
Returns
Returns
Returns
Parameters
timeoutNumericReturns
Parameters
secondsNumericReturns
Returns
Returns
Parameters
statusStringReturns
Parameters
forceBooleantimeoutNumeric | nildetachedBooleanReturns
Parameters
forceBooleantimeoutNumeric | nilReturns
Parameters
valueStringReturns
Parameters
valueIntegerReturns
Parameters
valueIntegerReturns
Parameters
valueIntegerReturns
Parameters
valueIntegerReturns
Parameters
keyStringvalueStringReturns
Parameters
valueStringReturns
Parameters
valueStringReturns
Parameters
valueStringReturns
Parameters
valueStringReturns
Parameters
valueBooleanReturns
Parameters
valueBooleanReturns
Parameters
valueIntegerReturns
Parameters
valueIntegerReturns
Returns
Parameters
valueIntegerReturns
Returns
Parameters
valueOutboundProxyReturns
Returns
Parameters
valueArray\Returns
Parameters
valueStringReturns
Parameters
keyStringvalueStringReturns
Parameters
secondsNumericReturns
Returns
Returns
Returns
Returns
Returns
Returns
Returns
Parameters
timeoutNumericReturns
Returns
Returns
Returns
Returns
Returns
Returns
Parameters
detachedBooleanReturns
Returns
Returns
Parameters
timeoutNumericReturns
Parameters
secondsNumericReturns
Parameters
detachedBooleanReturns
Parameters
statusStringReturns
Parameters
forceBooleantimeoutNumeric | nildetachedBooleanReturns
Parameters
forceBooleantimeoutNumeric | nilReturns
Returns
Fields
cpu\_percentFloatvcpu\_time\_nsIntegermemory\_bytesIntegermemory\_limit\_bytesIntegerdisk\_read\_bytesIntegerdisk\_write\_bytesIntegernet\_rx\_bytesIntegernet\_tx\_bytesIntegeruptime\_msIntegertimestampStringFields
nameStringstatusStringexit\_codeInteger | nilsignalInteger | nilobserved\_atStringsourceString | nilParameters
nameStringReturns
Parameters
referenceStringReturns
Parameters
nameStringReturns
Returns
Parameters
nameStringforceBooleanReturns
Parameters
referenceStringoutput\_pathStringwith\_parentsBooleanwith\_imageBooleanplain\_tarBooleansinceStringlast\_layersIntegerReturns
Parameters
output\_pathStringwith\_parentsBooleanwith\_imageBooleanplain\_tarBooleanReturns
Returns
Returns
Returns
Returns
Returns
Returns
Returns
Returns
Returns
Returns
Returns
Returns
Parameters
forceBooleanReturns
Parameters
output\_pathStringwith\_parentsBooleanwith\_imageBooleanplain\_tarBooleanReturns
Parameters
commandStringinactivity\_timeoutNumericReturns
Result fields
"stdout"String"stderr"String"exit\_code"Integer"success"BooleanParameters
nameStringReturns
Parameters
nameStringReturns
Returns
Parameters
nameStringReturns
Returns
Returns
Parameters
mibIntegerReturns
Parameters
mibIntegerReturns
Parameters
keyStringvalueStringReturns
Returns
Returns
Returns
Returns
Returns
Returns
Returns
Returns
Returns
Parameters
host\_pathStringportIntegerReturns
Parameters
host\_pathStringportIntegerReturns
Parameters
name\&strReturns
Parameters
name\&strtimeoutDurationReturns
Returned by agent::connect\_sandbox(), AgentClient::connect() · wrapped by AgentBridge
Low-level client for raw agent frames. #### AgentClient::connect()Parameters
sock\_pathimpl AsRef\Returns
Parameters
sock\_pathimpl AsRef\timeoutDurationReturns
Parameters
sock\_pathimpl AsRef\deadlineInstantReturns
Parameters
name\&strReturns
Parameters
name\&strtimeoutDurationReturns
Parameters
name\&strReturns
Parameters
tMessageTypenegotiatedu8Instance methods
#### client.request() ```rust theme={null} async fn requestParameters
tMessageTypepayload\&T: SerializeReturns
Parameters
tMessageTypepayload\&T: SerializeReturns
Parameters
idu32tMessageTypepayload\&T: SerializeParameters
flagsu8bodyVec\Returns
Parameters
flagsu8bodyVec\Returns
Parameters
idu32flagsu8body&\[u8]Returns
Returns
Returns
Current or LegacyV1.Returns
true if the relay speaks the pre-0.5 protocol.Returns
Returns
Parameters
tMessageTypeReturns
true if the runtime can handle the type.Parameters
tMessageTypeParameters
name\&strReturns
Parameters
name\&strtimeoutDurationReturns
Parameters
path\&strReturns
Parameters
path\&strtimeoutDurationReturns
Parameters
flagsu8bodyVec\Returns
Parameters
idu32flagsu8bodyVec\Parameters
flagsu8bodyVec\Returns