Skip to main content
See Overview for configuration examples and Lifecycle for state management. See Error handling for cross-SDK behavior.

Sandbox

Class methods

Microsandbox::Sandbox.create()

Create and start a sandbox. An existing name is an error unless replacement is requested. See Networking for network, proxy, and secret options.

Parameters

nameString
Sandbox name.
imageString
OCI image reference.
cpusInteger
Initial virtual CPU count.
max_cpusInteger
Maximum virtual CPU count.
memoryInteger
Initial memory in MiB.
max_memoryInteger
Maximum memory in MiB.
envHash
Environment variables with string keys and values.
labelsHash
Labels with string keys and values.
workdirString
Guest working directory.
shellString
Shell used for shell commands.
hostnameString
Guest hostname.
userString
Guest user.
detachedBoolean
Start locally in the background.
ephemeralBoolean
Remove sandbox state when its lifecycle ends.
max_durationInteger
Maximum lifetime in seconds.
idle_timeoutInteger
Idle timeout in seconds.
replaceBoolean
Replace an existing sandbox with this name.
replace_timeoutNumeric
Finite, non-negative replacement timeout in seconds.
root_diskInteger
Managed root disk size in MiB.
disable_networkBoolean
Disable sandbox networking.
networkSymbol | Hash
Use :none or the allowlist hash documented in the Networking reference.
proxyOutboundProxy
SOCKS proxy configuration; see the Networking reference.
secretsArray<Hash>
Secret injection entries; see the Networking reference.
quiet_logsBoolean
Suppress sandbox log output.
entrypointArray<String>
Override the image entrypoint; creation does not execute it.
initString
Guest init program.
pull_policyString
Image pull policy: if_missing (or if-missing), always, or never.
scriptsHash
Named scripts with string keys and values.
slugString
Human-readable sandbox slug.

Returns

Sandbox
Live sandbox connection.

Microsandbox::Sandbox.builder()

Create a chainable sandbox builder.

Parameters

nameString
Sandbox name.

Returns

SandboxBuilder
Configuration builder.

Microsandbox::Sandbox.start()

Start an existing sandbox.

Parameters

nameString
Sandbox name.
detachedBoolean
Start locally in the background; defaults to false.

Returns

Sandbox
Live sandbox connection.

Microsandbox::Sandbox.get()

Obtain persisted metadata without connecting to the guest agent.

Parameters

nameString
Sandbox name.

Returns

SandboxHandle
Metadata handle bound to this sandbox identity.

Microsandbox::Sandbox.list()

List sandboxes with optional pagination and label filtering.

Parameters

cursorString
Optional cursor from the previous page.
limitInteger
Optional maximum page size.
labelsHash
Optional label filter with string keys and values.

Returns

Hash
String keys: sandboxes (Array<SandboxHandle>) and next_cursor (String or nil).

Microsandbox::Sandbox.remove()

Remove a stopped sandbox and its local state. Use destroy to stop and remove a sandbox.

Parameters

nameString
Sandbox name.

Returns

nil
No return value.

Microsandbox::Sandbox.with()

Create a sandbox and yield it to the block. Gracefully stop it when the block exits, including on an exception. This does not remove persisted sandbox state. Without a block, return the created sandbox.

Parameters

nameString
Sandbox name.
optionsHash
The same creation options as create().

Returns

Object
The block result, or a Sandbox when no block is supplied.

Microsandbox::Sandbox.connect_or_create()

Reuse or create the sandbox with this name. The method connects when it is running, waits while it is starting, starts it when it is created, stopped, or crashed, and creates it only when the name is unused. Options apply only to a new sandbox, and concurrent callers reuse the same sandbox. Replace options are rejected because they request a different sandbox.
Use Sandbox.create when name conflicts must remain an error, or explicit replace options when the old identity should be discarded.

Parameters

nameString
Sandbox name.
optionsHash
Creation options, applied only when creating a new sandbox.

Returns

Sandbox
Live sandbox connection.

Instance methods

sandbox.name

Returns

String
Sandbox name.

sandbox.owns_lifecycle?

Returns

Boolean
Whether this connection owns the sandbox lifecycle.

sandbox.backend

Returns

String
Selected backend: local or cloud.

sandbox.status

Returns

String
Current lifecycle status, fetched from the backend.

sandbox.last_failure_message

Returns

String | nil
Most recent recorded failure, if available.

sandbox.kill()

Force termination and wait for shutdown. Omit timeout for an unbounded wait. Force termination is local-only.

Parameters

timeoutNumeric
Optional finite, non-negative timeout in seconds. May also be passed positionally, but not both ways.

Returns

nil
No return value.

sandbox.wait_until_stopped()

Wait for termination without a built-in timeout.

Returns

Hash
Stop result with string keys; see Stop result below.

sandbox.ping()

Check sandbox responsiveness.

Returns

Hash
String keys: name (String) and latency_ms (Integer).

sandbox.touch()

Record activity to refresh the sandbox idle timer.

Returns

Hash
String keys: name (String) and activity_seq (Integer).

sandbox.metrics()

Read a metrics sample.

Returns

SandboxMetrics
Metrics sample; call to_h for its fields.

sandbox.request_kill()

Request forced termination without waiting for shutdown. Local-only.

Returns

nil
No return value.

sandbox.detach()

Detach from the local runtime. This consumes the live connection; subsequent operations on it fail.

Returns

nil
No return value.

sandbox.stop()

Request graceful shutdown and wait for this exact sandbox run to finish, including local runtime ownership release. There is no built-in deadline or automatic force-kill. A supplied timeout: bounds the wait without changing graceful shutdown into forced termination. These semantics require the matching updated native extension and runtime.

Parameters

timeoutNumeric
Optional finite, non-negative deadline in seconds; no deadline when omitted.

Returns

nil
No return value.

sandbox.stop_with_timeout()

Bound graceful shutdown with an explicit finite, non-negative timeout. The deadline covers local transition ownership, request dispatch, and termination observation. Expiry raises Microsandbox::Error without force-killing; zero expires before sending a request. Call kill separately when forced termination is intended.

Parameters

secondsNumeric
Finite, non-negative timeout in seconds.

Returns

nil
No return value.

sandbox.request_stop()

Send the graceful shutdown request without waiting for termination or scheduling a force-kill. Pair with wait_until_stopped to observe completion.

Returns

nil
No return value.

sandbox.id

Opaque stable identity of the persisted sandbox. It remains unchanged across stop and restart and changes when a removed name is recreated. Use it for equality, logging, and correlation; do not parse it.

Returns

String
Stable sandbox identity.

sandbox.wait_for_status()

Wait without a built-in timeout until this exact sandbox reaches one of created, starting, running, draining, paused, stopped, or crashed. Returns a refreshed metadata handle. Ruby’s Timeout.timeout does not reliably interrupt the native wait. Use an SDK operation with an explicit timeout when you need a bounded shutdown.

Parameters

statusString
Target lifecycle status.

Returns

SandboxHandle
Refreshed metadata handle.

sandbox.restart()

Restart this exact sandbox. Defaults to graceful shutdown, the SDK’s ten-second timeout, and attached local start. A created, stopped, or crashed sandbox starts directly; a starting sandbox is observed until it settles. Set force: true to kill, timeout: in seconds to change how long shutdown can take, or detached: true for a local background start. On microsandbox cloud, graceful restart is supported, but timeout expiry cannot escalate to force kill. force: true is local-only, and detached: affects only local process ownership.

Parameters

forceBoolean
Use forced termination; defaults to false and is local-only.
timeoutNumeric | nil
Shutdown timeout in seconds; nil uses the SDK default of ten seconds.
detachedBoolean
Start locally in the background; defaults to false.

Returns

Sandbox
Live connection to the restarted sandbox.

sandbox.destroy()

Stop and remove this exact sandbox. Defaults to graceful shutdown with the SDK’s ten-second timeout. Identity checks refuse to delete a same-name replacement.

Parameters

forceBoolean
Use forced termination; defaults to false.
timeoutNumeric | nil
Shutdown timeout in seconds; nil uses the SDK default of ten seconds.

Returns

nil
No return value.

SandboxBuilder

builder.image()

OCI image reference.

Parameters

valueString
OCI image reference.

Returns

SandboxBuilder
The builder, for chaining.

builder.cpus()

Initial virtual CPU count.

Parameters

valueInteger
Initial virtual CPU count.

Returns

SandboxBuilder
The builder, for chaining.

builder.max_cpus()

Maximum virtual CPU count.

Parameters

valueInteger
Maximum virtual CPU count.

Returns

SandboxBuilder
The builder, for chaining.

builder.memory()

Initial memory in MiB.

Parameters

valueInteger
Initial memory in MiB.

Returns

SandboxBuilder
The builder, for chaining.

builder.max_memory()

Maximum memory in MiB.

Parameters

valueInteger
Maximum memory in MiB.

Returns

SandboxBuilder
The builder, for chaining.

builder.env()

Environment variables with string keys and values.

Parameters

keyString
Environment variable name.
valueString
Environment variable value.

Returns

SandboxBuilder
The builder, for chaining.

builder.workdir()

Guest working directory.

Parameters

valueString
Guest working directory.

Returns

SandboxBuilder
The builder, for chaining.

builder.shell()

Shell used for shell commands.

Parameters

valueString
Shell used for shell commands.

Returns

SandboxBuilder
The builder, for chaining.

builder.hostname()

Guest hostname.

Parameters

valueString
Guest hostname.

Returns

SandboxBuilder
The builder, for chaining.

builder.user()

Guest user.

Parameters

valueString
Guest user.

Returns

SandboxBuilder
The builder, for chaining.

builder.detached()

Start locally in the background.

Parameters

valueBoolean
Start locally in the background.

Returns

SandboxBuilder
The builder, for chaining.

builder.ephemeral()

Remove sandbox state when its lifecycle ends.

Parameters

valueBoolean
Remove sandbox state when its lifecycle ends.

Returns

SandboxBuilder
The builder, for chaining.

builder.max_duration()

Maximum lifetime in seconds.

Parameters

valueInteger
Maximum lifetime in seconds.

Returns

SandboxBuilder
The builder, for chaining.

builder.idle_timeout()

Idle timeout in seconds.

Parameters

valueInteger
Idle timeout in seconds.

Returns

SandboxBuilder
The builder, for chaining.

builder.replace()

Replace an existing sandbox with this name.

Returns

SandboxBuilder
The builder, for chaining.

builder.root_disk()

Managed root disk size in MiB.

Parameters

valueInteger
Managed root disk size in MiB.

Returns

SandboxBuilder
The builder, for chaining.

builder.disable_network()

Disable sandbox networking.

Returns

SandboxBuilder
The builder, for chaining.

builder.proxy()

SOCKS proxy configuration; see the Networking reference.

Parameters

valueOutboundProxy
SOCKS proxy configuration; see the Networking reference.

Returns

SandboxBuilder
The builder, for chaining.

builder.quiet_logs()

Suppress sandbox log output.

Returns

SandboxBuilder
The builder, for chaining.

builder.entrypoint()

Override the image entrypoint; creation does not execute it.

Parameters

valueArray<String>
Override the image entrypoint; creation does not execute it.

Returns

SandboxBuilder
The builder, for chaining.

builder.init()

Guest init program.

Parameters

valueString
Guest init program.

Returns

SandboxBuilder
The builder, for chaining.

builder.label()

Add a label.

Parameters

keyString
Label key.
valueString
Label value.

Returns

SandboxBuilder
The builder, for chaining.

builder.replace_with_timeout()

Replace an existing sandbox with a bounded wait.

Parameters

secondsNumeric
Finite, non-negative timeout in seconds.

Returns

SandboxBuilder
The builder, for chaining.

builder.create()

Create and start the configured sandbox. This consumes the builder; it cannot be reused.

Returns

Sandbox
Live sandbox connection.
The chainable setters above also have bang forms, such as image!, which mutate the builder and return nil. See VSock for vsock and vsock_dgram. Network allowlists, secret entries, pull policy, scripts, and slug are creation keywords, not Ruby builder methods.

builder.connect_or_create()

Create or reuse the configured sandbox, with the same behavior as Microsandbox::Sandbox.connect_or_create. This consumes the builder.

Returns

Sandbox
Live sandbox connection.

builder.http()

Denial responses are disabled by default. Call h.deny_response(true) to enable readable 403 responses. Optionally set deny_message to customize the body; {host} names the blocked hostname. Setting a message alone does not enable responses. Enabling requires a supporting local runtime; cloud rejects it. See HTTP denial responses for which requests receive a response.
The same option is available when creating a sandbox:

SandboxHandle

handle.name

Returns

String
Sandbox name.

handle.status

Returns

String
Status captured by this metadata handle. Call refresh for current metadata.

handle.config_json

Returns

String
Saved desired configuration as JSON.

handle.active_config_json

Returns

String | nil
Configuration used for the active run, when available.

handle.last_failure_message

Returns

String | nil
Failure message captured by this handle, if available.

handle.kill()

Force termination and wait for shutdown. Omit timeout for an unbounded wait. Force termination is local-only.

Parameters

timeoutNumeric
Optional finite, non-negative timeout in seconds. May also be passed positionally, but not both ways.

Returns

nil
No return value.

handle.wait_until_stopped()

Wait for termination without a built-in timeout.

Returns

Hash
Stop result with string keys; see Stop result below.

handle.ping()

Check sandbox responsiveness.

Returns

Hash
String keys: name (String) and latency_ms (Integer).

handle.touch()

Record activity to refresh the sandbox idle timer.

Returns

Hash
String keys: name (String) and activity_seq (Integer).

handle.metrics()

Read a metrics sample.

Returns

SandboxMetrics
Metrics sample; call to_h for its fields.

handle.refresh()

Fetch current metadata for this sandbox.

Returns

SandboxHandle
A refreshed handle; assign the returned value.

handle.connect()

Connect to the running sandbox without starting it.

Returns

Sandbox
Live sandbox connection.

handle.start()

Start this existing sandbox.

Parameters

detachedBoolean
Start locally in the background; defaults to false.

Returns

Sandbox
Live sandbox connection.

handle.remove()

Remove this stopped sandbox. The handle remains bound to its original identity.

Returns

nil
No return value.

handle.id

Opaque stable identity captured by this handle. Receiver lifecycle calls remain bound to this value.

Returns

String
Stable sandbox identity.

handle.stop()

Request graceful shutdown for this exact sandbox run and wait for termination and local runtime ownership release. stop has no built-in timeout. Both bounded forms raise Microsandbox::Error on expiry without force-killing; zero expires before sending a request. A stale identity is refused rather than stopping a replacement. On cloud, a timeout limits the SDK wait; an accepted stop may continue server-side.

Parameters

timeoutNumeric
Optional finite, non-negative deadline in seconds; no deadline when omitted.

Returns

nil
No return value.

handle.stop_with_timeout()

Request graceful shutdown and wait up to the supplied deadline. Timeout does not force-kill the sandbox; zero expires before sending a request.

Parameters

secondsNumeric
Finite, non-negative timeout in seconds.

Returns

nil
No return value.

handle.connect_or_start()

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.

Parameters

detachedBoolean
Start locally in the background if needed; defaults to false.

Returns

Sandbox
Live sandbox connection.

handle.wait_for_status()

Wait until this exact sandbox reaches status, returning a refreshed handle. The method does not have a built-in timeout.

Parameters

statusString
Target lifecycle status.

Returns

SandboxHandle
Refreshed metadata handle.

handle.restart()

Restart this exact sandbox with the same state and option semantics as Sandbox#restart.

Parameters

forceBoolean
Use forced termination; defaults to false and is local-only.
timeoutNumeric | nil
Shutdown timeout in seconds; nil uses the SDK default of ten seconds.
detachedBoolean
Start locally in the background; defaults to false.

Returns

Sandbox
Live connection to the restarted sandbox.

handle.destroy()

Stop and remove this exact sandbox. A stale handle refuses to destroy a replacement that reused the name.

Parameters

forceBoolean
Use forced termination; defaults to false.
timeoutNumeric | nil
Shutdown timeout in seconds; nil uses the SDK default of ten seconds.

Returns

nil
No return value.

SandboxMetrics

metrics.to_h()

Return the metrics sample as a hash with string keys.

Returns

Hash
Metrics fields below.

Fields

cpu_percentFloat
CPU utilization percentage.
vcpu_time_nsInteger
Accumulated virtual CPU time in nanoseconds.
memory_bytesInteger
Memory usage in bytes.
memory_limit_bytesInteger
Memory limit in bytes.
disk_read_bytesInteger
Bytes read from disk.
disk_write_bytesInteger
Bytes written to disk.
net_rx_bytesInteger
Network bytes received.
net_tx_bytesInteger
Network bytes sent.
uptime_msInteger
Uptime in milliseconds.
timestampString
RFC 3339 sample timestamp.

Stop result

Fields

nameString
Sandbox name.
statusString
Observed terminal status.
exit_codeInteger | nil
Exit code, if available.
signalInteger | nil
Termination signal, if available.
observed_atString
RFC 3339 observation timestamp.
sourceString | nil
Source of the termination observation.

Identity errors

Stale handles raise Microsandbox::SandboxReplacedError rather than acting on a replacement with the same name. See Error handling.

Installation requirements

Ruby 3.3, 3.4, and 4.0 are supported. When a matching platform gem is available, it carries the native extension; otherwise the source gem requires Rust 1.85 or newer to build it locally. Blocking native calls release Ruby’s global VM lock (GVL), allowing other Ruby threads to run.