Skip to main content
See Overview for configuration examples and Lifecycle for state management. See Snapshots for live fork methods.

Functions

allSandboxMetrics()

Return one SandboxMetrics snapshot for every running sandbox, keyed by sandbox name. See Metrics for a complete example.

Sandbox

Live inspection

info() returns identity, status, optional failure message, and creation/update timestamps. Timestamps are RFC3339 strings or null. id and name require no I/O; mutable state is fetched on each inspection call. See inspection and lifecycle.

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.getRunning()

Get an existing sandbox and connect to its run, starting it when stopped. A missing sandbox is an error; this never creates one. Unlike explicit start, an already-running sandbox succeeds. If the name is replaced during preparation, the operation fails instead of targeting the replacement. A newly started local run is owned by the returned Sandbox. Connecting to an existing run acquires no shutdown ownership. Remote runtime lifetime remains independent of the client.

Sandbox.get()

Look up an existing sandbox without starting it or connecting to its guest. The result is the same Sandbox type returned by creation. Guest execution prepares it automatically, while inspection remains non-starting. A missing or replaced resource is an error.

sb.ensureRunning()

Connect to the sandbox if running, or start it if stopped. The object and its clones own any attached local run they start. Ordinary shell and exec calls do this automatically. See lifecycle.

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 by name. See Destroy or remove for the exact local deletion scope and the external resources that are preserved. 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. A local handle enters attached mode and stops when its await using binding goes out of scope. A cloud handle does not own the service-managed VM, so stop or remove it explicitly.

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 exposes name (string), id (string), and ownsLifecycle (boolean) as read-only properties. The stable opaque id changes when a removed name is recreated. Local attached handles own lifecycle. Attached remote creations, including creation with progress, own their TypeScript scope cleanup. Fetched, detached, and remotely started or restarted handles are non-owning. Calling await sandbox.detach() releases scope cleanup. Command execution (exec, execWith, execStream, execStreamWith, shell, shellStream) and foreground attachment (attach, attachWith, attachShell) live on the Execution page. Lifecycle calls do not wait for unrelated guest operations on the same handle to finish. For example, you can pause and resume while an exec() promise is pending. Await operations explicitly when their order matters; stopping a sandbox may interrupt pending commands or filesystem requests.

sandbox.config()

Fetch the latest persisted configuration from the backend. Lookup errors are returned without a cached fallback; saved settings may still require restart to apply. The result is an inspection observation, not the creation input returned by SandboxBuilder.build().

Returns

Sandbox configuration.
The result distinguishes local persisted specifications from remote inspection projections. Remote source details may be unavailable and secret material is redacted; these are explicit paths in unavailable and redacted, not fabricated defaults. See inspection migration.

sandbox.detach()

Disarm automatic shutdown without consuming the sandbox. Repeated calls succeed; the sandbox and its existing filesystem helpers remain usable. ownsLifecycle becomes false after successful detach, and explicit stop/destroy remain available. If detach fails, it rejects without consuming the object or clearing its cleanup authority. Detach does not cancel work or scoped shutdown that has already begun.

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 confirmation that the sandbox stopped.

Parameters

timeoutMsnumber
Milliseconds to wait for the stopped state to be observed. Must be an integer from 0 to 4294967295, inclusive; other values reject with RangeError before calling native.

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. Reading logs does not start the sandbox. 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 maxDurationSeconds.

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". cpus and memory resize live within the maxCpus / maxMemory ceilings; raising a ceiling requires a restart. rootDiskSize grows owned managed and flat ext4 roots live, including checkpoint-backed roots. Tmpfs root disks can change in either direction on the next boot. User-supplied disk images are rejected. Env and workdir changes affect future execs only. Stopped roots grow before the new size is saved. Explicit restart and next-start policies remain available. Secret specs are keyed by stable secret name. Each SecretModifySpec selects at most one source (env, value, or store) and may also set placeholder, allowedHosts, and the settings listed under SecretModifySpec; omitting a source updates only the other supplied fields. Unknown keys are rejected. Plans expose only safe references and metadata; raw secret values never appear in a plan. Removal is explicit through secretsRemove. Changing a secret’s substitution rules, violation action, TLS identity requirement, or placeholder passthrough hosts requires a restart if the sandbox is running. Use policy: "restart" to apply now, or policy: "next_start" to save for the next start. A live CPU or memory resize can take a moment to settle. The immediate result’s resizeStatus reports "accepted" after the runtime accepts each target; it does not confirm guest completion. The plan’s applied field describes applying the modification request, not usable guest capacity. See SandboxModificationPlan.

Parameters

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

Returns

The modification plan, applied unless dryRun: true.

sandbox.modifyWithResizeTracking()

Accepts the same options as modify() and returns { plan, resizeOperations }. The records identify this call’s accepted live requests. Tracking is null for dry runs, non-live changes and supported changes through older runtimes; it must not be replaced with a later current operation. Existing modify() output is unchanged. A missing native method refuses before mutation, and a dispatched mutation is never retried through another API.

sandbox.resizeOperations()

Read the latest recorded operation per resource without changing targets. Reads return retained evidence and request a background refresh; they do not wait for a new guest sample. Use an operation-specific wait to await confirmed completion. An empty list means no recorded request. Records contain id, runtimeBootId, generation, requestedTarget, acceptedTarget, status, outcome and observation. Generation is a bigint; memory targets use { resource: "memory", totalMib: bigint }, and CPU targets use { resource: "cpus", online: number }. Status preserves requested, actual, enforced and convergence quantities. Outcome is pending, applied or superseded; observation is available, unsupported, paused or unavailable. Keep bigint fields intact when storing records for reconnection; ordinary JSON.stringify cannot serialize bigint. Use a bigint-aware serializer that restores those fields as bigint, not JavaScript numbers.

sandbox.waitForResizeOperations()

Wait on the supplied one or two records, rechecking their identities against the runtime. Reconnection to the same runtime is supported. Runtime replacement, expired history or supersession fails instead of following a new request; caller-supplied applied status is not proof. An omitted timeout waits indefinitely and zero performs one bounded check. Expiry raises ResizeTimeoutError with completed per-resource reads and does not undo the resize. Unsupported observation is an error, never successful completion. The runtime retains at most 256 operation records, protecting the latest CPU and memory records from eviction. Older records can expire; restarting the runtime clears its history. Resident pause preserves the history. An expired identity cannot establish completion. ResizeWaitError exposes reason, sandbox, operationId, verified status and the native error as cause. Reasons distinguish superseded, interrupted, history_unavailable, invalid_response and observation_unavailable. None implies rollback or final failure of the resize. Timeout and unsupported-feature errors remain separate; unknown future peer errors retain their ordinary mapping.

sandbox.resizeStatus()

Read current resource status without operation identities. Use resizeOperations() when a later wait must remain tied to those records.

sandbox.waitUntilResized()

Select the operations present at the first read and wait for those identities. This does not establish which caller submitted them; use the result of modifyWithResizeTracking() for a wait tied to your modification.

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 you need to wait for the sandbox to stop. 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()

Wait indefinitely for graceful shutdown and release of the targeted runtime’s ownership. Success allows immediate removal without racing teardown. No implicit kill is requested. Paused or unreachable sandboxes return errors; resume or kill explicitly. Ignoring a Promise does not cancel its operation.

sandbox.waitForStatus()

Returns completion only and never starts the sandbox. The existing resource remains usable; call info() for a fresh observation afterward. The observed status may change after this wait completes. Wait without a built-in timeout until this exact persisted sandbox reaches status. Throws SandboxReplacedError rather than following a reused name. Use Promise.race when the caller needs its own deadline; the underlying wait is not cancellable yet.

sandbox.restart()

Restart this exact sandbox. Defaults to graceful shutdown, a 10_000 ms timeout, and attached local start. A stopped, crashed, or created sandbox starts directly; Starting is observed until it settles. Set force to kill, timeoutMs to change how long shutdown can take, or detached for a local background start.

sandbox.destroy()

Stop and remove this exact sandbox. Defaults to graceful shutdown with a 10_000 ms timeout. Identity checks throw SandboxReplacedError instead of deleting a replacement that reused the name.

sandbox.stopWithTimeout()

Apply one total budget to graceful dispatch and completion. Expiry throws StopTimeoutError without killing; 0 expires before dispatch. A delivered request can complete later. Only explicit kill() requests force termination.

Parameters

timeoutMsnumber
Total graceful-completion budget, as an integer from 0 to 4294967295 milliseconds. Zero expires before dispatch.

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

For an attached remote creation, scope exit awaits a best-effort stop by sandbox ID, including when the block throws. Call stop() explicitly to observe remote stop errors. Detached and fetched remote sandboxes keep running. For an owned local run, disposal awaits graceful shutdown of the captured run. Local cleanup errors reject. If the block also throws, SuppressedError preserves both failures.

sandbox.restoreWarnings()

Return warnings for unavailable external filesystems and accepted restore mismatches. See External mounts for restore options. Each ExternalMountWarning contains:

guestPath

string Guest-visible mount path.

reason

string Why the resource could not be reconstructed.

staleInodes

readonly bigint[] Permanently invalid captured node IDs; empty when the whole export is unavailable.

handle.snapshot()

Capture a disk snapshot. Locally, the name selects a member within the sandbox’s snapshot group. See Snapshots.

Returns

Promise<Snapshot>

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.

sandboxBuilder.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.

sandboxBuilder.cpus()

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

Parameters

nnumber
Number of vCPUs.

sandboxBuilder.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.

sandboxBuilder.create()

Build and boot an attached sandbox. With await using, scope exit awaits local shutdown or a best-effort remote stop. Use detached(true) to keep it running after scope exit.

Returns

Running sandbox.

sandboxBuilder.connectOrCreate()

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. Builder settings apply only to a new sandbox. Concurrent callers reuse the same sandbox. Calling replace() or replaceWithTimeout() on this builder is invalid.

Returns

Promise<Sandbox>

sandboxBuilder.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.

sandboxBuilder.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.

sandboxBuilder.disableMetricsSample()

Disable periodic background metrics sampling for this sandbox.

sandboxBuilder.disableNetwork()

Fully disable networking. No network interface is created.

sandboxBuilder.entrypoint()

Override the image ENTRYPOINT used by default-workload execution. sandbox.execDefault combines it with the effective CMD. Literal sandbox.exec, sandbox.attach, and sandbox.shell calls ignore it.

Parameters

cmdstring[]
Entrypoint command and arguments.

sandboxBuilder.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.

sandboxBuilder.envs()

Add many environment variables at once.

Parameters

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

sandboxBuilder.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.

sandboxBuilder.hostname()

Set the guest hostname.

Parameters

namestring
Hostname.

sandboxBuilder.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.

sandboxBuilder.idleTimeoutSeconds()

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.

sandboxBuilder.image()

On our managed cloud, these paths refer to files in your organization’s host volume, rather than files on your computer.
Set the root filesystem source. Accepts OCI image names ("alpine"), local directory paths, or disk image paths. The format is auto-detected. Required for creation; use Sandbox.restore() for snapshots.

Parameters

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

sandboxBuilder.imageWith()

On our managed cloud, these paths refer to files in your organization’s host volume, rather than files on your computer.
Configure an explicit rootfs source. Use this for OCI-only settings such as the writable root disk, or for disk images when the filesystem type can’t be auto-detected.

Parameters

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

sandboxBuilder.cmd()

Override the image CMD used by default-workload execution. An empty array explicitly clears the image CMD. This describes durable configuration and does not execute anything during create().

sandboxBuilder.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.

sandboxBuilder.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.

sandboxBuilder.label()

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

Parameters

keystring
Label key.
valuestring
Label value.

sandboxBuilder.labels()

Attach many labels at once.

Parameters

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

sandboxBuilder.logLevel()

Override the sandbox process’s log verbosity.

Parameters

Log level.

sandboxBuilder.maxDurationSeconds()

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.

sandboxBuilder.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.

sandboxBuilder.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.

sandboxBuilder.thp()

Select the guest transparent huge-page policy applied through the kernel command line at boot. Default: "madvise".

Parameters

policy”always” | “madvise” | “never”
The THP policy persisted for the sandbox.

sandboxBuilder.metricsSampleIntervalMs()

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

Parameters

msnumber
Sampling interval in milliseconds.

sandboxBuilder.interceptTls()

Enable TLS interception for a local sandbox. Existing network and TLS settings are preserved. Later network() callbacks preserve settings unless explicitly changed. Calling tls() inside the callback replaces the TLS settings.

sandboxBuilder.network()

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

Parameters

Configure the network.

sandboxBuilder.proxy()

Configure the single proxy used for outbound sandbox connections. See Proxies for the protocol builders and examples.

Parameters

configurefunction
Callback that selects and configures one proxy protocol.

sandboxBuilder.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.

sandboxBuilder.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.

sandboxBuilder.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.

sandboxBuilder.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.

sandboxBuilder.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.

sandboxBuilder.pullPolicy()

Control when the OCI image is pulled from the registry.

Parameters

Pull behavior.

sandboxBuilder.quietLogs()

Suppress sandbox process log output.

sandboxBuilder.registry()

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

Parameters

Configure registry authentication, transport, and CA certificates.

sandboxBuilder.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.

sandboxBuilder.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.

sandboxBuilder.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.

sandboxBuilder.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.

sandboxBuilder.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.

sandboxBuilder.scripts()

Add many named scripts at once.

Parameters

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

sandboxBuilder.security()

Set the in-guest security profile.

Parameters

profile”default” | “restricted”
Security profile.

sandboxBuilder.secret()

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

Parameters

Configure the secret.

sandboxBuilder.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.

sandboxBuilder.shell()

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

Parameters

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

sandboxBuilder.user()

Set the default guest user for all commands.

Parameters

userstring
User name or UID.

sandboxBuilder.volume()

Add a volume mount. See Volumes for mount types.

Parameters

gueststring
Mount point inside the sandbox.
Configure the mount.

sandboxBuilder.workdir()

Set the default working directory for all commands.

Parameters

pathstring
Absolute path inside the guest.

PatchBuilder

Builder for pre-boot root filesystem patches.

patch.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.

patch.copyDir()

On our managed cloud, these paths refer to files in your organization’s host volume, rather than files on your computer.
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.

patch.copyFile()

On our managed cloud, these paths refer to files in your organization’s host volume, rather than files on your computer.
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.

patch.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.

patch.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.

patch.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.

patch.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.

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.

entry.timestamp

Date Wall-clock capture time on the host

entry.source

LogSource Where the chunk came from

entry.sessionId

number \| null Relay-monotonic session id; null for "system" entries

entry.data

Uint8Array The captured chunk’s bytes (UTF-8 lossy decoded by default)

entry.cursor

string Opaque resume token; pass to LogStreamOptions.fromCursor to resume

entry.text()

Convenience: UTF-8 decode of data (lossy - invalid bytes are replaced)

Returns

string

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.

logStream.recv()

Receive the next entry. Returns null when the stream ends.

Returns

Promise<LogEntry \| null>

stream.Symbol.asyncIterator

Use with for await...of

Returns

AsyncIterator<LogEntry>

stream.Symbol.asyncDispose

Stop iterating; safe to use with await using

Returns

Promise<void>

MetricsStream

Returned by metricsStream()

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

metricsStream.recv()

Receive the next snapshot. Returns null when the stream ends.

Returns

Promise<SandboxMetrics \| null>

stream.Symbol.asyncIterator

Use with for await...of

Returns

AsyncIterator<SandboxMetrics>

stream.Symbol.asyncDispose

Stop yielding metrics through both recv() and iteration; safe to use with await using. A sample arriving from an in-flight read after disposal is suppressed. Disposal does not interrupt that native read, and a pending read error still rejects its caller.

Returns

Promise<void>

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.

pull.progress

NapiPullProgressStream The underlying progress event stream

pull.awaitSandbox()

Resolve the underlying creation task and return the running sandbox

Returns

Promise<Sandbox>

pull.Symbol.asyncIterator

Use with for await...of

Returns

AsyncIterator<PullProgress>

SandboxListBuilder

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

list.limit()

Set a page size from 1 through 100

list.cursor()

Continue after a previous page’s nextCursor

list.label()

Require one label; repeated calls are AND-matched

list.labels()

Add several AND-matched labels

RegistryConfigBuilder

Fluent builder for OCI registry connection settings. Obtain it through SandboxBuilder.registry(); the callback’s returned builder is stored in the sandbox configuration.

registry.auth()

Set registry authentication credentials.

Returns

this

registry.insecure()

Use plain HTTP instead of TLS.

Returns

this

registry.caCerts()

Add a PEM-encoded CA certificate. May be called repeatedly.

Returns

this

registry.caCertsPath()

Read and add a PEM-encoded CA certificate from a filesystem path.

Returns

this

registry.build()

Snapshot the accumulated registry configuration.

Returns

RegistryConfig

Types

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).

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:

ModifyOptions

Used by modify()

A requested sandbox modification. Omitted fields are left unchanged.

cpus

number Desired effective vCPU count. Live when within the booted maxCpus

maxCpus

number Boot-time maximum possible vCPUs (restart-backed)

memory

number Desired effective guest memory in MiB. Live when within the booted maxMemory

maxMemory

number Boot-time maximum hotpluggable memory in MiB (restart-backed)

rootDiskSize

number Desired root disk size in MiB. Managed and flat OCI disks are grow-only; applies on restart or next start

env

Record<string, string> Environment variables to set for future execs

envRemove

string[] Environment variable keys to remove

ports

ModifyPort[] Add/update {hostPort, guestPort, hostBind?, protocol?} mappings; other endpoints stay unchanged

portsRemove

ModifyPortEndpoint[] Remove {hostPort, hostBind?, protocol?} endpoints; loopback TCP by default

labels

Record<string, string> Labels to set

labelsRemove

string[] Label keys to remove

workdir

string Working directory for future execs

secrets

Record<string, SecretModifySpec> Desired secret specs keyed by stable secret name

secretsRemove

string[] Secret names to remove explicitly

policy

"no_restart" \| "next_start" \| "restart" "no_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

dryRun

boolean Compute the plan without applying anything. Defaults to false

SecretModifySpec

Used by modify()

Desired state for one secret. env, value, and store are mutually exclusive sources. Omit all three to update only the other supplied fields.

Fields

envstring
Host environment variable to resolve when applying the modification.
valuestring
Raw secret value. Stored in the durable sandbox config until replaced by a source reference.
storestring
Reserved for a host-side secret store reference; currently unsupported.
placeholderstring
Explicit guest-visible placeholder. New secrets default to $MSB_<NAME>.
allowedHostsstring[]
Desired allowed host patterns. A new secret requires at least one; an empty list leaves existing hosts unchanged.
substitutionSecretSubstitution
Desired substitution locations. A supplied value replaces the stored rule; omitted keys take the defaults (headers on, every header, no query or body), so repeat headerFields to keep a narrowed list. Omission keeps the stored rule; new secrets default to headers only.
violationActionViolationAction
Per-secret blocking action. Omission keeps the existing override.
requireTlsIdentityboolean
Whether substitution requires verified TLS identity. Omission keeps the existing setting; new secrets default to true. Explicit false disables this requirement.
allowPlaceholderForstring[]
Hosts permitted to receive the unchanged placeholder. A non-empty list replaces the existing hosts; an empty list leaves them unchanged.

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.

RegistryAuth

Authentication used when pulling images from an OCI registry.

RegistryConfig

Built by RegistryConfigBuilder · stored in SandboxConfig.registry

OCI registry connection settings produced by RegistryConfigBuilder.build().

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().

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 describes a live resize. The immediate modification result reports "accepted"; equal reported quantities do not establish operation-bound guest completion, and plugged memory may still be offline:

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 Sandbox.status · SandboxStopResult.status

Current lifecycle state of a sandbox. String literal type.

Nested virtualization

nestedVirt(enabled: boolean) controls nested virtualization for a local sandbox. Omit it to inherit configuration (off by default). See nested VM snapshots for requirements.

Storage recovery

Sandbox.recoverStorage()

Import or resume storage for a stopped local sandbox. Inspect it first with storage diagnostics. See sandbox storage repair for maintenance requirements and recovery limits.

Options

selectionsreadonly StorageRecoverySelection[]
Exact IDs from storage diagnosis, with diskId and candidateId strings. Omit or leave empty to import or resume the validated current view.
acceptSelectedViewboolean
Default false. Required for explicit selections, which may omit writes from other disk branches.
legacyWritersStoppedboolean
Default false. On macOS, confirm that legacy VMs across all homes are stopped and new writers are prevented during recovery.

Returns

StorageRecovery
name (string) identifies the sandbox. ready (boolean) confirms protected storage is ready, and originalsRetained (boolean) confirms the original disks were retained.

SandboxConfigInspection

name is the name observed by this lookup. unavailable and redacted contain snake_case paths relative to spec, including in TypeScript. They identify information the backend cannot expose or deliberately withholds. This result cannot be used as creation input. kind discriminates { kind: "local", spec: LocalSandboxInspection } from { kind: "remote", spec: RemoteSandboxInspection }. Runtime settings are at spec.runtime; remote resources use spec.resources.vcpus and local resources use spec.resources.cpus. Remote image: null means the source details are unavailable.