Functions
allSandboxMetrics()
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()
Example
Example
.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
namestringReturns
Sandbox.getRunning()
Example
Example
Sandbox.get()
Example
Example
sb.ensureRunning()
Example
Example
Sandbox.list()
Example
Example
Sandbox.get(name) to get a live handle for lifecycle calls.
Returns
Sandbox.listWith()
Example
Example
list(), returned handles are read-only.
Parameters
configure(list: SandboxListBuilder) => SandboxListBuilderReturns
Sandbox.remove()
Example
Example
Parameters
namestringSandbox.start()
Example
Example
await using binding goes out of scope. A cloud handle does not own the service-managed VM, so stop or remove it explicitly.
Parameters
namestringReturns
Sandbox.startDetached()
Example
Example
Parameters
namestringReturns
Instance methods
A runningSandbox 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()
Example
Example
SandboxBuilder.build().
Returns
unavailable and redacted, not fabricated defaults. See inspection migration.
sandbox.detach()
Example
Example
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()
Example
Example
Returns
sandbox.kill()
Example
Example
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()
Example
Example
timeoutMs for confirmation that the sandbox stopped.
Parameters
timeoutMsnumberRangeError before calling native.sandbox.logs()
Example
Example
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
optsLogReadOptions?tail, since, until, sources. Omit for the default user-program sources.Returns
sandbox.logStream()
Example
Example
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
follow and resume controls (since, fromCursor).Returns
sandbox.ping()
Example
Example
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.touch()
Example
Example
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.modify()
Example
Example
"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
optsModifyOptionspolicy and dryRun. Omitted fields are left unchanged.Returns
dryRun: true.sandbox.modifyWithResizeTracking()
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.
Example
Example
sandbox.resizeOperations()
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()
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()
resizeOperations() when a later wait must remain tied to those records.
sandbox.waitUntilResized()
modifyWithResizeTracking() for a wait tied to your modification.
sandbox.metrics()
Example
Example
Returns
sandbox.metricsStream()
Example
Example
MetricsStream supports both recv() and for await...of.
Parameters
intervalMsnumberReturns
sandbox.requestDrain()
Example
Example
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()
Example
Example
sandbox.requestStop()
Example
Example
sandbox.ssh()
Returns
sandbox.stop()
Example
Example
sandbox.waitForStatus()
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()
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()
SandboxReplacedError instead of deleting a replacement that reused the name.
sandbox.stopWithTimeout()
Example
Example
StopTimeoutError without killing; 0 expires before dispatch. A delivered request can complete later. Only explicit kill() requests force termination.
Parameters
timeoutMsnumbersandbox.waitUntilStopped()
Example
Example
Returns
sandbox.Symbol.asyncDispose
Example
Example
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()
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()
Returns
Promise<Snapshot>
SandboxBuilder
Fluent builder for configuring a sandbox before creation. Obtained viaSandbox.builder(name). Every setter returns the same builder so calls chain. Examples are shown on the methods where usage is non-obvious.
sandboxBuilder.build()
SandboxConfig without booting the sandbox. Validates the configuration and consumes the builder. For booting, use create instead - it builds internally.
Returns
sandboxBuilder.cpus()
Parameters
nnumbersandboxBuilder.maxCpus()
Parameters
nnumbersandboxBuilder.create()
Example
Example
await using, scope exit awaits local shutdown or a best-effort remote stop. Use detached(true) to keep it running after scope exit.
Returns
sandboxBuilder.connectOrCreate()
replace() or replaceWithTimeout() on this builder is invalid.
Returns
Promise<Sandbox>
sandboxBuilder.createWithPullProgress()
Example
Example
PullProgressCreate that yields PullProgress events as the image is resolved, downloaded, and materialized; call awaitSandbox() after iteration to obtain the live sandbox.
Returns
sandboxBuilder.detached()
true. A detached sandbox survives after your process exits and does not auto-stop on await using scope exit.
Parameters
enabledbooleansandboxBuilder.disableMetricsSample()
sandboxBuilder.disableNetwork()
sandboxBuilder.entrypoint()
sandbox.execDefault combines it with the effective CMD. Literal sandbox.exec, sandbox.attach, and sandbox.shell calls ignore it.
Parameters
cmdstring[]sandboxBuilder.env()
execWith) are merged on top.
Parameters
keystringvaluestringsandboxBuilder.envs()
Parameters
varsRecord<string, string>sandboxBuilder.ephemeral()
true, the sandbox and all its persisted state are removed automatically once it stops, rather than left on disk for restart.
Parameters
enabledbooleansandboxBuilder.hostname()
Parameters
namestringsandboxBuilder.libkrunfwPath()
setRuntimeLibkrunfwPath(path) and returns the builder; it is not a per-sandbox setting.
Parameters
pathstringsandboxBuilder.idleTimeoutSeconds()
Parameters
secsnumbersandboxBuilder.image()
"alpine"), local directory paths, or disk image paths. The format is auto-detected. Required for creation; use Sandbox.restore() for snapshots.
Parameters
srcstringsandboxBuilder.imageWith()
Example
Example
Parameters
configure(b: ImageBuilder) => ImageBuildersandboxBuilder.cmd()
create().
sandboxBuilder.init()
Example
Example
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“auto”.argsstring[]?sandboxBuilder.initWith()
Example
Example
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
cmdstringconfigure(b: InitOptionsBuilder) => InitOptionsBuildersandboxBuilder.label()
Sandbox.listWith().
Parameters
keystringvaluestringsandboxBuilder.labels()
Parameters
labelsRecord<string, string>sandboxBuilder.logLevel()
Parameters
levelLogLevelsandboxBuilder.maxDurationSeconds()
Parameters
secsnumbersandboxBuilder.memory()
Parameters
mibnumbersandboxBuilder.maxMemory()
Parameters
mibnumbersandboxBuilder.thp()
"madvise".
Parameters
policy”always” | “madvise” | “never”sandboxBuilder.metricsSampleIntervalMs()
Parameters
msnumbersandboxBuilder.interceptTls()
network() callbacks preserve settings unless explicitly changed. Calling tls() inside the callback replaces the TLS settings.
sandboxBuilder.network()
Parameters
sandboxBuilder.proxy()
Parameters
configurefunctionsandboxBuilder.patch()
Example
Example
PatchBuilder for the operations.
Parameters
configure(b: PatchBuilder) => PatchBuildersandboxBuilder.port()
127.0.0.1. For an explicit bind address, use portBind.
Parameters
hostnumberguestnumbersandboxBuilder.portBind()
"0.0.0.0".
Parameters
bindstringhostnumberguestnumbersandboxBuilder.portUdp()
127.0.0.1.
Parameters
hostnumberguestnumbersandboxBuilder.portUdpBind()
Parameters
bindstringhostnumberguestnumbersandboxBuilder.pullPolicy()
Parameters
policyPullPolicysandboxBuilder.quietLogs()
sandboxBuilder.registry()
Example
Example
Parameters
sandboxBuilder.replace()
sandboxBuilder.replaceWithTimeout()
replace() with a custom SIGTERM timeout in milliseconds. 0 skips SIGTERM and force-kills immediately. Implies replace().
Parameters
timeoutMsnumbersandboxBuilder.rlimit()
rlimitRange.
Parameters
resourcestring“nofile”.limitnumbersandboxBuilder.rlimitRange()
Parameters
resourcestring“nofile”.softnumberhardnumbersandboxBuilder.script()
/.msb/scripts/ inside the guest. Scripts are added to PATH and can be called by name via exec() or shell().
Parameters
namestringcontentstringsandboxBuilder.scripts()
Parameters
scriptsRecord<string, string>sandboxBuilder.security()
Parameters
profile”default” | “restricted”sandboxBuilder.secret()
Parameters
configure(b: SecretBuilder) => SecretBuildersandboxBuilder.secretEnv()
$MSB_<env_var> placeholder usable in headers.
Parameters
envVarstring= or NUL).valuestringallowedHoststringsandboxBuilder.shell()
sandbox.shell().
Parameters
shellstring“/bin/bash”).sandboxBuilder.user()
Parameters
userstringsandboxBuilder.volume()
Parameters
gueststringconfigure(b: MountBuilder) => MountBuildersandboxBuilder.workdir()
Parameters
pathstringPatchBuilder
Builder for pre-boot root filesystem patches.patch.append()
content to an existing file at path. If the file lives in a lower image layer, it’s copied up first.
Parameters
pathstringcontentstringpatch.copyDir()
src into the guest rootfs at dst.
Parameters
srcstringdststringopts.replacebooleantrue, overwrite an existing path at dst.patch.copyFile()
src into the guest rootfs at dst.
Parameters
srcstringdststringopts.modenumber0o644. Omit to keep the source mode.opts.replacebooleantrue, overwrite an existing path at dst.patch.file()
path.
Parameters
pathstringcontentBufferopts.modenumber0o644.opts.replacebooleantrue, overwrite an existing path.patch.mkdir()
path. Idempotent: a no-op if the directory already exists.
Parameters
pathstringopts.modenumber0o755.patch.remove()
path. Idempotent: a no-op if the path doesn’t exist.
Parameters
pathstringpatch.symlink()
link pointing to target.
Parameters
targetstringlinkstringopts.replacebooleantrue, overwrite an existing path at link.patch.text()
path.
Parameters
pathstringcontentstringopts.modenumber0o644.opts.replacebooleantrue, overwrite an existing path.LogEntry
Returned by logs() · logStream()
A class wrapping one captured log entry fromexec.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()
data (lossy - invalid bytes are replaced)
Returns
string
LogStream
Returned by logStream()
An async iterable ofLogEntry values. Drain it with for await...of or call recv() directly. Implements AsyncDisposable, so it works with await using.
logStream.recv()
null when the stream ends.
Returns
Promise<LogEntry \| null>
stream.Symbol.asyncIterator
for await...of
Returns
AsyncIterator<LogEntry>
stream.Symbol.asyncDispose
await using
Returns
Promise<void>
MetricsStream
Returned by metricsStream()
Async stream for receiving periodic metrics snapshots. ImplementsAsyncDisposable, so it works with await using.
metricsStream.recv()
null when the stream ends.
Returns
Promise<SandboxMetrics \| null>
stream.Symbol.asyncIterator
for await...of
Returns
AsyncIterator<SandboxMetrics>
stream.Symbol.asyncDispose
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 bycreateWithPullProgress(). 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()
Returns
Promise<Sandbox>
pull.Symbol.asyncIterator
for await...of
Returns
AsyncIterator<PullProgress>
SandboxListBuilder
Fluent configuration passed toSandbox.listWith(). Keep the labels and limit unchanged when continuing with a cursor.
list.limit()
list.cursor()
nextCursor
list.label()
list.labels()
RegistryConfigBuilder
Fluent builder for OCI registry connection settings. Obtain it throughSandboxBuilder.registry(); the callback’s returned builder is stored in the sandbox configuration.
registry.auth()
Returns
this
registry.insecure()
Returns
this
registry.caCerts()
Returns
this
registry.caCertsPath()
Returns
this
registry.build()
Returns
RegistryConfig
Types
LogLevel
Used by logLevel()
Sandbox process log verbosity. String literal type.LogReadOptions
Used by logs()
Filters passed tologs(). All fields optional. Omit the argument entirely for the default sources (stdout + stderr + output).
LogStreamOptions
Used by logStream()
Options passed tologStream(). 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
envstringvaluestringstorestringplaceholderstring$MSB_<NAME>.allowedHostsstring[]substitutionSecretSubstitutionheaderFields to keep a narrowed list. Omission keeps the stored rule; new secrets default to headers only.violationActionViolationActionrequireTlsIdentitybooleantrue. Explicit false disables this requirement.allowPlaceholderForstring[]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 byPullProgressCreate. 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 byRegistryConfigBuilder.build().
SandboxConfig
Returned by config() · build()
Configuration object produced bybuild() and returned by config(). You generally should not construct this by hand; use the builder.
SandboxPage
One stable, newest-first page returned bySandbox.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 onkind. 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 bywaitUntilStopped().
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()
Options
selectionsreadonly StorageRecoverySelection[]diskId and candidateId strings. Omit or leave empty to import or resume the validated current view.acceptSelectedViewbooleanfalse. Required for explicit selections, which may omit writes from other disk branches.legacyWritersStoppedbooleanfalse. On macOS, confirm that legacy VMs across all homes are stopped and new writers are prevented during recovery.Returns
StorageRecoveryname (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.