Skip to main content
Create and control a microVM sandbox: boot it from an image, run commands, stream logs and metrics, then shut it down. See Overview for configuration examples and Lifecycle for state management. The TypeScript SDK uses a builder-only entry point. Start every new sandbox from Sandbox.builder(name) and chain configuration calls before terminating with .create(). Use .detached(true) before .create() for detached/background mode. Sandbox names must be non-empty and no longer than 128 UTF-8 bytes. libkrunfw selection is process-level, not per sandbox. To use a custom library, call setRuntimeLibkrunfwPath(path) before creating local sandboxes, set MSB_LIBKRUNFW_PATH, or configure paths.libkrunfw.

Typical flow

Static methods

Sandbox.builder()

Begin building a new sandbox. Configure it with chainable setters, then call .create() to boot it. Sandbox names must be non-empty and no longer than 128 UTF-8 bytes. See SandboxBuilder for all available options.

Parameters

namestring
Sandbox name, up to 128 UTF-8 bytes.

Returns

Fluent builder for configuring the sandbox.

Sandbox.get()

Get a live handle to an existing sandbox (running or stopped). The handle provides status, configuration, and lifecycle control without requiring a full connection to the guest agent.

Parameters

namestring
Sandbox name, up to 128 UTF-8 bytes.

Returns

Live handle with status and lifecycle control.

Sandbox.list()

Return the first page of sandboxes (running, stopped, and crashed), ordered newest first. The default page size is 20. Handles are read-only - call Sandbox.get(name) to get a live handle for lifecycle calls.

Returns

Promise<SandboxPage>
Read-only handles in this page and an optional cursor for the next page.

Sandbox.listWith()

Return a configured page of sandboxes. Label filters are applied before pagination and are AND-matched. Like list(), returned handles are read-only.

Parameters

configure(list: SandboxListBuilder) => SandboxListBuilder
Configure a limit (1-100), next-page cursor, and/or AND-matched labels.

Returns

Promise<SandboxPage>
Matching read-only handles and an optional cursor for the next page.

Sandbox.remove()

Delete a stopped sandbox and all its state from disk (configuration, logs, runtime directory). Fails if the sandbox is still running - stop it first.

Parameters

namestring
Sandbox name, up to 128 UTF-8 bytes.

Sandbox.start()

Restart a previously stopped sandbox. The VM reboots using the persisted configuration. The sandbox enters attached mode - it stops when the binding goes out of scope (via await using) or when stop() is called.

Parameters

namestring
Name of a stopped sandbox, up to 128 UTF-8 bytes.

Returns

Running sandbox.

Sandbox.startDetached()

Restart a stopped sandbox in detached mode. The sandbox survives after your process exits.

Parameters

namestring
Name of a stopped sandbox, up to 128 UTF-8 bytes.

Returns

Running sandbox.

Instance methods

A running Sandbox also exposes two read-only properties: name (string, the sandbox name) and ownsLifecycle (boolean, true in attached mode where the auto-disposer stops the sandbox, false in detached mode). Command execution (exec, execWith, execStream, execStreamWith, shell, shellStream) and foreground attachment (attach, attachWith, attachShell) live on the Execution page.

sandbox.config()

Get the full configuration the sandbox was created with - image, cpus, memory, env, mounts, and the rest. The shape mirrors SandboxBuilder.build().

Returns

Sandbox configuration.

sandbox.detach()

Release the handle without stopping the sandbox. The sandbox continues running as a background process. Reconnect later with Sandbox.get().

sandbox.fs()

Get a filesystem handle for reading and writing files inside the running sandbox. See Filesystem for API details.

Returns

Filesystem handle.

sandbox.kill()

Force-terminate the sandbox and wait until stopped state is observed. No graceful shutdown - use when the sandbox is unresponsive. Pending writes that the workload hasn’t fsync’d may be lost, same durability semantics as a sudden power loss on a physical machine. Prefer stop() for graceful shutdown that gives the workload a chance to flush.

sandbox.killWithTimeout()

Force-terminate the sandbox and wait up to timeoutMs for stopped-state observation.

Parameters

timeoutMsnumber
Milliseconds to wait for the stopped state to be observed.

sandbox.logs()

Read captured output from the sandbox’s exec.log. Backed by an on-disk JSON Lines file the runtime writes via the relay tap. Works on running and stopped sandboxes alike - there is no protocol traffic. The same method is available on SandboxHandle for callers that don’t want to start the sandbox first. The default sources are "stdout", "stderr", and "output" (PTY-merged). Pass "system" to also include synthetic lifecycle markers and runtime/kernel diagnostic lines, or "all" for every source.

Parameters

Filters: tail, since, until, sources. Omit for the default user-program sources.

Returns

Matching entries in chronological order.

sandbox.logStream()

Stream captured output as it appears, with optional follow. Backed by the same on-disk exec.log as logs(), but yields entries lazily. Pass { follow: true } to keep the stream open past current EOF and pick up new entries as they are written; otherwise the stream drains the current contents and ends. Each yielded LogEntry carries an opaque cursor that can be passed back via LogStreamOptions.fromCursor to resume.

Parameters

Filters plus follow and resume controls (since, fromCursor).

Returns

Async iterable of log entries.

sandbox.ping()

Check that the running sandbox’s guest agent is reachable without refreshing idle activity. This sends core.ping and waits for core.pong; it does not start stopped sandboxes and returns an error if the sandbox is not running or agentd cannot respond. After upgrading from a runtime that predates protocol generation 6, restart already-running sandboxes so the guest agent understands the message.

Returns

Sandbox name and agent round-trip latency.

sandbox.touch()

Explicitly refresh the running sandbox’s idle activity. This sends core.touch, receives core.touched, and advances the guest activity sequence used by the runtime idle-timeout monitor. It does not start stopped sandboxes and it does not bypass maxDuration.

Returns

Sandbox name and updated activity sequence.

sandbox.modify()

Plan or apply a configuration change. The returned plan labels each change "live", "next start", "requires restart", or "unsupported", and apply is all-or-nothing. cpus and memory resize live within the maxCpus / maxMemory ceilings; raising a ceiling requires a restart. Env and workdir changes affect future execs only. On a stopped sandbox, changes are saved for the next boot. Secret changes are Rust-SDK and CLI only for now. The CLI equivalent is msb modify. A live CPU or memory resize can take a moment to settle. The new limits are enforced immediately, and the returned plan’s resizeStatus reports when the sandbox has finished adjusting. See SandboxModificationPlan.

Parameters

Requested changes plus policy and dryRun. Omitted fields are left unchanged.

Returns

The modification plan, applied unless dryRun: true.

sandbox.metrics()

Get a point-in-time snapshot of the sandbox’s resource usage: CPU, memory, disk I/O, network I/O, optional upper disk usage, and uptime.

Returns

Resource metrics.

sandbox.metricsStream()

Stream resource metrics at a regular interval. The returned MetricsStream supports both recv() and for await...of.

Parameters

intervalMsnumber
Milliseconds between metric snapshots.

Returns

Async stream yielding a snapshot each interval.

sandbox.requestDrain()

Request a graceful drain and return once the request is sent. Existing commands run to completion, but new exec calls are rejected. The sandbox transitions to stopped when all in-flight commands finish. Use waitUntilStopped() when the caller needs stopped-state observation. Useful for zero-downtime rotation of worker sandboxes.

sandbox.requestKill()

Request force termination and return once the signal is sent, without waiting for the stopped state to be observed.

sandbox.requestStop()

Request graceful shutdown and return once the request is sent, without waiting for the stopped state to be observed.

sandbox.ssh()

Get an SSH handle for opening interactive sessions and port forwards into the running guest. See SSH for API details.

Returns

SSH handle.

sandbox.stop()

Gracefully shut down the sandbox and wait until stopped state is observed. Lets the sandbox finish writing any pending data to disk before it exits, so files written inside the sandbox aren’t lost across a later restart. Waits up to 10_000 ms for a clean exit; if the sandbox is still running after that, it is force-killed.

sandbox.stopWithTimeout()

Gracefully shut down the sandbox with an explicit observation timeout before force-kill escalation. 0 force-kills immediately. Resolves successfully either way - it does not throw on timeout expiry.

Parameters

timeoutMsnumber
Milliseconds to wait for a clean exit before force-killing. 0 skips the grace period.

sandbox.waitUntilStopped()

Block until the sandbox is observed in a terminal non-running state, without triggering a stop or kill request.

Returns

Terminal status, exit code, and signal that were observed.

sandbox.Symbol.asyncDispose

Implements AsyncDisposable so the sandbox can be used with await using. When the binding goes out of scope, the sandbox is stopped (best-effort) - but only if ownsLifecycle is true.

SandboxBuilder

Fluent builder for configuring a sandbox before creation. Obtained via Sandbox.builder(name). Every setter returns the same builder so calls chain. Examples are shown on the methods where usage is non-obvious; simple setters are demonstrated by the Typical flow above.

.build()

Materialize the SandboxConfig without booting the sandbox. Validates the configuration and consumes the builder. For booting, use create instead - it builds internally.

Returns

Validated, ready-to-boot configuration.

.cpus()

Set the number of virtual CPUs. This is a limit, not a reservation.

Parameters

nnumber
Number of vCPUs.

.maxCpus()

Set the boot-time maximum possible virtual CPU capacity. This reserves the envelope a sandbox can use after restart-backed changes and future live CPU activation; it does not increase the effective vCPU count by itself.

Parameters

nnumber
Maximum possible vCPUs.

.create()

Build and boot the sandbox. By default the sandbox is attached - it stops when the await using binding goes out of scope. Call detached(true) first for background mode.

Returns

Running sandbox.

.createWithPullProgress()

Build and boot while streaming image pull progress. Returns a PullProgressCreate that yields PullProgress events as the image is resolved, downloaded, and materialized; call awaitSandbox() after iteration to obtain the live sandbox.

Returns

Async iterable creation handle.

.detached()

Create in detached/background mode when true. A detached sandbox survives after your process exits and does not auto-stop on await using scope exit.

Parameters

enabledboolean
Whether to boot in detached mode.

.disableMetricsSample()

Disable periodic background metrics sampling for this sandbox.

.disableNetwork()

Fully disable networking. No network interface is created.

.entrypoint()

Override the OCI image’s stored ENTRYPOINT. Consulted by msb exec / msb run (CLI command resolution), not by sandbox.exec / sandbox.shell - those pass cmd literally to the guest agent. Use this when configuring a sandbox via the SDK for later CLI attachment.

Parameters

cmdstring[]
Entrypoint command and arguments.

.env()

Set an environment variable visible to all commands. Can be called multiple times. Per-command env vars (via execWith) are merged on top.

Parameters

keystring
Variable name.
valuestring
Variable value.

.envs()

Add many environment variables at once.

Parameters

varsRecord<string, string>
Map of variable names to values.

.ephemeral()

When true, the sandbox and all its persisted state are removed automatically once it stops, rather than left on disk for restart.

Parameters

enabledboolean
Whether the sandbox is ephemeral.

.fromSnapshot()

Boot from a previously captured snapshot instead of a fresh image. The image reference and upper-layer source are pinned from the snapshot manifest. See Snapshots.

Parameters

pathOrNamestring
Snapshot name or filesystem path.

.hostname()

Set the guest hostname.

Parameters

namestring
Hostname.

.libkrunfwPath()

Deprecated compatibility alias for older builder chains. This sets the same process-level override as setRuntimeLibkrunfwPath(path) and returns the builder; it is not a per-sandbox setting.

Parameters

pathstring
Path to the libkrunfw shared library.

.idleTimeout()

Auto-drain the sandbox after this many seconds of inactivity (no active exec sessions). Enforced on the host side.

Parameters

secsnumber
Idle timeout in seconds.

.image()

Set the root filesystem source. Accepts OCI image names ("alpine"), local directory paths, or disk image paths. The format is auto-detected. Required unless fromSnapshot is used.

Parameters

srcstring
OCI image name, local directory path, or disk image path.

.imageWith()

Configure an explicit rootfs source. Use this for OCI-only settings such as the writable overlay upper size, or for disk images when the filesystem type can’t be auto-detected.

Parameters

configure(b: ImageBuilder) => ImageBuilder
Configure the rootfs source.

.init()

Hand off PID 1 inside the guest to cmd after agentd finishes its boot-time setup. cmd is either an absolute path inside the guest rootfs or the literal "auto", which honors a known image ENTRYPOINT init then falls back to probing common init paths. See Custom init system. For init binaries that need extra env, use initWith.

Parameters

cmdstring
Absolute path inside the guest, or “auto”.
argsstring[]?
Optional argv for the init binary.

.initWith()

Like init, but with a closure-builder for argv and env vars. The builder exposes .arg, .args, .env, and .envs. Calling init or initWith more than once overwrites.

Parameters

cmdstring
Absolute path to the init binary inside the guest.
configure(b: InitOptionsBuilder) => InitOptionsBuilder
Closure populating argv and env.

.label()

Attach a single label to the sandbox. Labels can be matched later with Sandbox.listWith().

Parameters

keystring
Label key.
valuestring
Label value.

.labels()

Attach many labels at once.

Parameters

labelsRecord<string, string>
Map of label keys to values.

.logLevel()

Override the sandbox process’s log verbosity.

Parameters

Log level.

.maxDuration()

Set the maximum sandbox lifetime in seconds. When exceeded, the sandbox is drained and stopped. Enforced on the host side - the guest cannot override it.

Parameters

secsnumber
Maximum lifetime in seconds.

.memory()

Set the guest memory size in MiB. Physical pages are only allocated as the guest touches them, so this is a limit, not an upfront reservation.

Parameters

mibnumber
Memory in MiB.

.maxMemory()

Set the boot-time maximum hotpluggable guest memory in MiB. This reserves the envelope a sandbox can use after restart-backed changes and future live memory activation; it does not increase the effective memory by itself.

Parameters

mibnumber
Maximum memory in MiB.

.metricsSampleIntervalMs()

Set the interval, in milliseconds, at which the host samples background metrics for this sandbox.

Parameters

msnumber
Sampling interval in milliseconds.

.network()

Configure DNS, TLS, policy, and secrets. See Networking for the full builder API.

Parameters

Configure the network.

.patch()

Modify the rootfs before the VM boots. Patches go into the writable layer - the base image is untouched. See PatchBuilder for the operations.

Parameters

Configure rootfs patches.

.port()

Publish a TCP port from the sandbox to the host. The default host bind address is 127.0.0.1. For an explicit bind address, use portBind.

Parameters

hostnumber
Port on the host.
guestnumber
Port inside the sandbox.

.portBind()

Publish a TCP port on a specific host bind address, such as "0.0.0.0".

Parameters

bindstring
Host bind address.
hostnumber
Port on the host.
guestnumber
Port inside the sandbox.

.portUdp()

Publish a UDP port. The default host bind address is 127.0.0.1.

Parameters

hostnumber
Port on the host.
guestnumber
Port inside the sandbox.

.portUdpBind()

Publish a UDP port on a specific host bind address.

Parameters

bindstring
Host bind address.
hostnumber
Port on the host.
guestnumber
Port inside the sandbox.

.pullPolicy()

Control when the OCI image is pulled from the registry.

Parameters

Pull behavior.

.quietLogs()

Suppress sandbox process log output.

.registry()

Configure the OCI registry connection: authentication, insecure transport, and CA certificates.

Parameters

configure(b: RegistryBuilder) => RegistryBuilder
Configure the registry.

.replace()

If a sandbox with the same name already exists, stop it (10s SIGTERM grace, then SIGKILL), remove it, and create a fresh one. Without this, creation fails on name conflict.

.replaceWithTimeout()

Same as replace() with a custom SIGTERM timeout in milliseconds. 0 skips SIGTERM and force-kills immediately. Implies replace().

Parameters

timeoutMsnumber
Milliseconds to wait after SIGTERM before escalating to SIGKILL.

.rlimit()

Set a guest resource limit (a soft and hard limit at the same value). For separate soft/hard values, use rlimitRange.

Parameters

resourcestring
Resource name, e.g. “nofile”.
limitnumber
Limit value applied to both soft and hard.

.rlimitRange()

Set a guest resource limit with explicit soft and hard values.

Parameters

resourcestring
Resource name, e.g. “nofile”.
softnumber
Soft limit.
hardnumber
Hard limit.

.script()

Add a named script at /.msb/scripts/ inside the guest. Scripts are added to PATH and can be called by name via exec() or shell().

Parameters

namestring
Script name (becomes the filename).
contentstring
Script content.

.scripts()

Add many named scripts at once.

Parameters

scriptsRecord<string, string>
Map of script names to contents.

.security()

Set the in-guest security profile.

Parameters

profile”default” | “restricted”
Security profile.

.secret()

Add a secret with full configuration. See Secrets for the builder API. Automatically enables TLS interception.

Parameters

Configure the secret.

.secretEnv()

Auto-placeholder shorthand for adding a header-injected secret. Generates a $MSB_<env_var> placeholder usable in headers.

Parameters

envVarstring
Environment variable name (non-empty, no = or NUL).
valuestring
Secret value.
allowedHoststring
Allowed destination host.

.shell()

Set the shell binary used by sandbox.shell().

Parameters

shellstring
Shell path (e.g. “/bin/bash”).

.user()

Set the default guest user for all commands.

Parameters

userstring
User name or UID.

.volume()

Add a volume mount. See Volumes for mount types.

Parameters

gueststring
Mount point inside the sandbox.
Configure the mount.

.workdir()

Set the default working directory for all commands.

Parameters

pathstring
Absolute path inside the guest.

PatchBuilder

Fluent builder for the ordered list of pre-boot rootfs patches. Used in SandboxBuilder.patch(p => p...). Each method appends one operation; calls are chainable. By default a method that targets a path already present in the image errors at boot; pass { replace: true } on the operation to allow overwriting. mkdir and remove are idempotent. See Patches for conceptual context.

.append()

Append content to an existing file at path. If the file lives in a lower image layer, it’s copied up first.

Parameters

pathstring
Absolute path inside the guest.
contentstring
Text to append.

.copyDir()

Recursively copy a host directory at src into the guest rootfs at dst.

Parameters

srcstring
Host source directory.
dststring
Absolute destination path inside the guest.
opts.replaceboolean
When true, overwrite an existing path at dst.

.copyFile()

Copy a single host file at src into the guest rootfs at dst.

Parameters

srcstring
Host source file.
dststring
Absolute destination path inside the guest.
opts.modenumber
File mode, e.g. 0o644. Omit to keep the source mode.
opts.replaceboolean
When true, overwrite an existing path at dst.

.file()

Write raw bytes at path.

Parameters

pathstring
Absolute path inside the guest.
contentBuffer
Raw byte content.
opts.modenumber
File mode, e.g. 0o644.
opts.replaceboolean
When true, overwrite an existing path.

.mkdir()

Create a directory at path. Idempotent: a no-op if the directory already exists.

Parameters

pathstring
Absolute path inside the guest.
opts.modenumber
Directory mode, e.g. 0o755.

.remove()

Delete a file or directory at path. Idempotent: a no-op if the path doesn’t exist.

Parameters

pathstring
Absolute path inside the guest.
Create a symlink at link pointing to target.

Parameters

targetstring
What the symlink points to (literal symlink target text).
linkstring
Absolute path of the symlink itself.
opts.replaceboolean
When true, overwrite an existing path at link.

.text()

Write UTF-8 text content at path.

Parameters

pathstring
Absolute path inside the guest.
contentstring
Text content.
opts.modenumber
File mode, e.g. 0o644.
opts.replaceboolean
When true, overwrite an existing path.

Types

LogEntry

Returned by logs() · logStream()

A class wrapping one captured log entry from exec.log. Bytes are exposed via data; use text() for a UTF-8-lossy decode.

LogLevel

Used by logLevel()

Sandbox process log verbosity. String literal type.

LogReadOptions

Used by logs()

Filters passed to logs(). All fields optional. Omit the argument entirely for the default sources (stdout + stderr + output).

LogStream

Returned by logStream()

An async iterable of LogEntry values. Drain it with for await...of or call recv() directly. Implements AsyncDisposable, so it works with await using.

LogStreamOptions

Used by logStream()

Options passed to logStream(). All fields optional. since and fromCursor are mutually exclusive - passing both rejects at the boundary.

LogSource

Used by LogEntry.source · LogReadOptions.sources

Tag indicating where a captured log entry came from. String literal type:

MetricsStream

Returned by metricsStream()

Async stream for receiving periodic metrics snapshots. Implements AsyncDisposable, so it works with await using.

ModifyOptions

Used by modify()

A requested sandbox modification. Omitted fields are left unchanged. Secret changes are Rust-SDK and CLI only for now.

PullPolicy

Used by pullPolicy()

Controls when the SDK fetches an OCI image from the registry. String literal type.

PullProgress

Yielded by PullProgressCreate

Image pull and materialize progress event emitted by PullProgressCreate. A discriminated union. Narrow on kind to access variant-specific fields. totalDownloadBytes and totalBytes on the "resolved" / "layerDownloadProgress" variants may be absent if the manifest omits sizes.

PullProgressCreate

Returned by createWithPullProgress()

Async iterable creation handle returned by createWithPullProgress(). Yields PullProgress events as the image is resolved, downloaded, and materialized. Call awaitSandbox() after iteration to obtain the live sandbox.

SandboxConfig

Returned by config() · build()

Configuration object produced by build() and returned by config(). You generally should not construct this by hand; use the builder.

SandboxPage

One stable, newest-first page returned by Sandbox.list() or Sandbox.listWith().

SandboxListBuilder

Fluent configuration passed to Sandbox.listWith(). Keep the labels and limit unchanged when continuing with a cursor.

SandboxHandle

Returned by Sandbox.get() · Sandbox.list() · Sandbox.listWith()

A lightweight handle to an existing sandbox (running or stopped). Obtained via Sandbox.get(), Sandbox.list(), or Sandbox.listWith(). Provides status, configuration, and lifecycle control without an active connection to the guest agent. Handles from Sandbox.get(name) are live - they expose lifecycle methods (start, stop, kill, connect, etc). Handles in pages returned by Sandbox.list() / Sandbox.listWith() are read-only: calling lifecycle methods on them throws. Use Sandbox.get(name) to upgrade to a live handle.

SandboxModificationPlan

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.

PlannedChange

Used by SandboxModificationPlan.changes

Discriminated union on kind. Both variants carry field, change, disposition, and reason.

ConfigPlannedChange

Variant of PlannedChange

Ordinary configuration change in a modification plan.

SecretPlannedChange

Variant of PlannedChange

Secret change in a modification plan. Values are omitted by construction; beforeRef and afterRef are guest-visible references. ResourceResizeStatus reports runtime convergence for a live resize; enforcement applies immediately, the guest converges asynchronously:

SandboxPingResult

Returned by ping()

Agent reachability result.

SandboxTouchResult

Returned by touch()

Explicit idle-refresh result.

SandboxMetrics

Returned by metrics() · yielded by MetricsStream

Point-in-time resource usage snapshot.

SandboxStopResult

Returned by waitUntilStopped()

Observed terminal sandbox state returned by waitUntilStopped().

SandboxStatus

Used by SandboxHandle.status · SandboxStopResult.status

Current lifecycle state of a sandbox. String literal type.