Introducing a new way to review your PRs.

Read the announcement

superradcompany / microsandbox

🧱 easy, fast, programmable and local-first microVM runtime and library

View on GitHub

27 documents · Updated Nov 23, 2026

docs / sdk-bindings

SDKs and language bindings

Microsandbox gives Rust, Node.js/TypeScript, Python, Go, and Ruby applications one public model for creating isolated sandboxes, using guest resources, and controlling lifecycle state. Each SDK follows its host language while keeping destination choice, resource identity, runtime setup, errors, and cleanup consistent.

Product boundary

The SDK is the application boundary to the microsandbox service. An application chooses a destination, describes or finds a sandbox, uses guest services, and then keeps, detaches, stops, or removes the sandbox.

The shared product surface includes:

  • Sandbox creation, lookup, connection, execution, and lifecycle control.
  • Guest file access, volumes, images, snapshots, logs, metrics, SSH, and services where supported.
  • Resource, mount, network, DNS, TLS, secret, proxy, and port settings.
  • Local microVM execution and remote control-plane execution.
  • Post-create changes through a plan and apply flow.

This diagram shows how a host-language call reaches the chosen destination.

flowchart LR
    App[Application] --> SDK[Language SDK]
    SDK --> Adapter[Native adapter]
    Adapter --> Core[Shared Rust model]
    Core --> Local[Local context]
    Core --> Remote[Remote context]
    Local --> Guest[Local sandbox]
    Remote --> Service[Remote service]

References: sdk/…/lib.rs• L18-35 sdk/…/index.ts• L18-70 sdk/…/__init__.py• L3-64 sdk/…/context.go• L17-25 sdk/…/context.rs• L15-38

Public resource model

The SDK separates a destination, a live sandbox, and saved resource records. A destination retains the local or remote service used by its collections and returned resources, so later changes to ambient configuration do not move an existing resource.

ResourcePurposeMain use
SandboxLive access to a guestExecute commands, use files, inspect state, and control lifecycle
Sandbox handleReference to persisted sandbox stateFind, start, wait, stop, restart, or remove a sandbox
Managed jobRuntime-owned command identityInspect, wait, stream output, send input, or stop a command
VolumePersistent guest storageCreate, mount, inspect, or remove storage
Snapshot or checkpointSaved disk or execution stateCapture, open, verify, restore, export, import, or remove state
ServicePublic route to a sandbox portCreate, inspect, retarget, enable, disable, or remove a cloud route

Sandbox lifecycle

The lifecycle begins with a named sandbox configuration and ends when the live instance and its saved record are no longer needed. A connect-or-create operation lets several callers converge on one persisted identity instead of creating separate sandboxes.

The common flow is:

  1. Choose a local or remote context.
  2. Create a sandbox or connect to the named sandbox.
  3. Use the live sandbox for commands, files, logs, metrics, and guest resources.
  4. Request a graceful stop or force a kill, then wait when confirmation is needed.
  5. Restart, detach, destroy, or remove the saved identity as required.

Graceful stop and forceful kill are different actions. Detach releases automatic cleanup responsibility without stopping the sandbox. A later lookup or connection can regain control.

References: sdk/…/handle.rs• L44-62 sdk/…/lifetime.rs• L26-74 sdk/…/sandbox.ts• L97-108 sdk/…/sandbox.go• L104-120 sdk/…/context.rs• L173-209 sdk/…/lifetime.rb• L3-18

Managed jobs

A managed job is a sandbox-scoped command identity owned by the runtime. The start result gives the application a durable identity that it can inspect after the original call ends.

The common job flow is:

  1. Start a command and retain its job identity.
  2. Inspect it or wait for a confirmed exit result.
  3. Read retained output or follow new output.
  4. Send input, resize a terminal, signal, or kill the command when needed.
  5. Close observation handles. Closing an observation handle does not terminate the job.

Admission, transport, and process exit remain separate outcomes. If admission succeeds but the final response is uncertain, the caller must recover the job before retrying the command.

References: sdk/…/mod.rs• L1-20 sdk/…/jobs.go• L16-80 sdk/…/index.d.ts• L358-383 sdk/…/_microsandbox.pyi• L1422-1477 sdk/…/jobs.rb• L5-105

Public services

A public Service gives one sandbox port a stable public URL. Services use the remote destination only; local destinations reject Service operations as unsupported before changing state. See Service management APIs for the full Service contract.

The common Service flow is:

  1. Select a remote context and create a Service for a running sandbox port.
  2. Get or list Services to read their current target and status.
  3. Retarget, enable, or disable routing as the sandbox changes.
  4. Refresh or get the Service before retrying an uncertain change.
  5. Remove the Service when the public route is no longer needed.

Create and change calls do not retry automatically. A detached Service has no target. Setting a target reattaches it, while disabling it keeps the target.

This diagram shows the public route from an external client to a guest application.

flowchart LR
    Client[External client] --> URL[Service URL]
    URL --> Route[Cloud Service]
    Route --> Target[Sandbox port]
    Target --> App[Guest application]

References: sdk/…/api.rs• L18-24 sdk/…/api.rs• L47-73 sdk/…/service.ts• L88-199 sdk/…/service.rs• L14-203 sdk/…/service.go• L12-204 sdk/…/services.rs• L19-234

Sandbox modification

Sandbox modification uses a plan-first contract for changes after creation. The plan tells the caller whether each change is live, applies at the next start, needs a restart, or is unsupported.

The contract is shared by Rust, Go, Node.js/TypeScript, and Python where modification is exposed. Local destinations support a wider set of changes. Remote destinations accept only the fields supported by the remote service, and reject other fields instead of ignoring them.

Planning does not send secret values. Apply resolves secret sources and sends values only for the apply request. An uncertain remote result requires inspection before retry.

References: sdk/…/mod.rs• L1-21 sdk/…/builder.rs• L222-310 sdk/…/modify.go• L19-35 sdk/…/modify.ts• L1-80 sdk/…/types.py• L190-245

Execution results

Command execution has three public forms. A collected result returns output and an exit status. A stream returns ordered output and exit events. A managed job adds runtime ownership and retained history.

The result contract separates a process exit from a launch or transport failure. Binary output remains available when text decoding is not possible. Interactive streams can accept input, allocate or resize a terminal, send signals, and wait for a confirmed exit.

References: sdk/…/mod.rs• L1-13 sdk/…/session.rs• L27-169 sdk/…/exec.ts• L1-120 sdk/…/_microsandbox.pyi• L317-401 sdk/…/ffi.go• L150-184

Destination contexts

A context is a retained destination: local execution on the host or a remote control plane. Collections and builders created from a context keep that destination and its captured configuration. Context construction does not need to start a sandbox.

The explicit context model is now the main cross-language way to keep backend choice clear:

SDKLocal destinationRemote destination
RustLocalContextRemoteContext
Node.js/TypeScriptLocalContextRemoteContext
PythonLocalContextRemoteContext
GoNewLocalContextNewRemoteContext or a remote provider
RubyLocalContextRemoteContext

Resources returned by a context retain the context that created or found them. This prevents a later provider registration, profile change, or environment change from redirecting an existing resource.

References: sdk/…/dispatch.rs• L22-63 sdk/…/context.ts• L25-42 sdk/…/context.rs• L20-95 sdk/…/context.go• L9-25 sdk/…/context.rs• L15-100

Backend selection

Backend selection chooses the service that receives resource operations. The local backend starts microVMs on the calling host. The remote backend sends control requests to a remote service and keeps its endpoint and credentials with the context.

The ambient selection path resolves explicit program settings, profiles, environment settings, and the local fallback. An API key does not select the remote backend by itself. Select the destination before creating or finding resources.

The selection scope differs by language:

SDKSelection modelResource behavior
RustExplicit contexts plus configured defaultContext objects retain shared transport and backend state.
Node.js/TypeScriptExplicit contexts plus configured providerNative objects retain the provider that created them.
PythonExplicit contexts plus configured defaultContext and resource wrappers retain native destination state.
GoExplicit contexts and registered native providersContexts, streams, cancellation, and cleanup retain the creating library.
RubyExplicit contexts plus local and remote convenience methodsCollections retain their context; convenience selection is process-wide.

Remote connections use an endpoint and API key. The hosted endpoint is the default when no endpoint is supplied. Profiles and explicit settings can target other compatible services. Public Services require a remote context.

References: sdk/…/profile.rs• L1-9 sdk/…/profile.rs• L112-167 sdk/…/context.ts• L44-82 sdk/…/provider.ts• L18-24 sdk/…/context_remote.go• L64-80 sdk/…/context.rb• L61-65

Runtime setup

Local sandboxes need a matching msb runtime and libkrunfw firmware library. Runtime setup is separate from the SDK binding library and separate from destination selection.

All SDKs use the same high-level rule: resolve a complete executable-and-firmware pair first, and install only when no complete pair exists. An incomplete pair fails closed. Explicit paths and runtime-home settings must remain distinct from package-provided candidates.

The language-specific setup model is:

  • Rust exposes setup, version, and host-readiness helpers.
  • Node.js/TypeScript exposes runtime resolution and installation helpers through its platform package.
  • Python registers the wheel's packaged msb as a candidate and exposes the same setup actions.
  • Go loads its FFI library lazily. EnsureRuntime separately resolves or installs the local runtime pair.
  • Ruby uses the gem's native extension and runtime helpers.

Remote-only applications may not need local virtualization files. Local applications still need host virtualization support such as KVM, Apple Silicon virtualization, or WHP on Windows.

References: sdk/…/mod.rs• L1-31 sdk/…/setup.ts• L4-23 sdk/…/setup.rs• L9-24 sdk/…/__init__.py• L278-285 sdk/…/setup.go• L19-39 sdk/…/README.md• L43-59 sdk/…/microsandbox.rb• L9-22

Language surfaces

Each SDK presents the shared resource model in the style of its host language. The native layer carries the Rust operations, while the public layer maps names, values, async work, errors, and ownership into that language.

Rust SDK

The Rust SDK is the reference public model for contexts, sandboxes, handles, execution, guest files, volumes, snapshots, storage, logs, metrics, jobs, Services, and modification plans. Its feature set can expose local and remote capabilities separately, while backend limits remain typed unsupported operations. Read Rust SDK implementation for the detailed Rust surface.

References: sdk/…/lib.rs• L18-35 sdk/…/lib.rs• L43-63 sdk/…/lib.rs• L75-128 sdk/…/api_boundary.rs• L1-29

Node.js and TypeScript SDK

The Node.js package exposes promise-based methods, fluent builders, async streams, and typed errors. TypeScript owns the public names and value shapes. The N-API layer carries native builders and operations and maps native error data back to stable JavaScript error classes.

Platform packages select a native binding for the host platform, architecture, and Linux C library. The provider layer checks ABI, version, and capability before use. A full package or a split local or remote provider can supply the native implementation, and returned objects retain their provider.

References: sdk/…/index.ts• L18-46 sdk/…/context.ts• L25-42 sdk/…/provider.ts• L18-24 sdk/…/provider.ts• L63-106 sdk/…/context.rs• L23-69 sdk/…/index.cjs• L263-331

Python SDK

The Python package exposes async methods, context-managed cleanup, async iterators, enums, type stubs, managed jobs, and structured exceptions. PyO3 wraps the Rust resources and converts Rust futures into Python awaitables.

Python contexts retain a local or remote destination. The package can register its bundled runtime as a candidate without replacing explicit user settings. The binding owns an async runtime for bridge work and joins it during interpreter shutdown.

References: sdk/…/__init__.py• L3-64 sdk/…/contexts.py• L11-61 sdk/…/context.rs• L20-95 sdk/…/runtime.rs• L18-25 sdk/…/runtime.rs• L93-138 sdk/…/provider.rs• L15-40

Go SDK

The Go package uses context.Context for operation cancellation and deadlines, option functions for sandbox settings, pointers for live resources, and Go errors for failures. Its public model supports explicit local and remote contexts, resource collections, streaming operations, jobs, snapshots, and retained handles.

The full module embeds its native FFI library and loads it lazily. Lean core, local, and remote distributions can provision a matching native library separately. The FFI returns JSON, bytes, error tags, cancellation IDs, and opaque handles; the Rust side owns the underlying resources. Go context cancellation stops the current SDK operation. It does not stop a runtime-owned job or sandbox.

References: sdk/…/README.md• L14-26 sdk/…/README.md• L61-73 sdk/…/context.go• L17-25 sdk/…/provider.go• L9-29 sdk/…/setup.go• L19-59 sdk/…/ffi.go• L1-47 sdk/…/lib.rs• L17-30

Ruby SDK

The Ruby gem provides blocking methods, keyword options, hashes, blocks, typed exceptions, and scoped cleanup. The Magnus extension wraps the shared Rust context and resource objects. Long operations run outside the Ruby VM lock, and the native runtime is recreated after a process fork when needed.

Ruby offers explicit local and remote contexts as well as convenience methods that select a destination for common resource calls. A block passed to Sandbox.with performs ownership-aware cleanup after the block returns or raises.

References: sdk/…/microsandbox.rb• L9-25 sdk/…/lifetime.rb• L3-18 sdk/…/context.rb• L5-65 sdk/…/context.rs• L15-100 sdk/…/lib.rs• L133-183

Native binding layers

Native binding layers carry the shared Rust operation model into a host runtime. They convert values, run async work in the host's execution model, map errors, and keep resource and stream handles valid until the host releases them. They are adapters, not separate product backends. See Cross-language binding adapters for ownership and conversion rules.

AdapterHost-facing role
Node.js/TypeScript N-APIExposes native builders and classes to JavaScript and TypeScript.
Python PyO3Exposes Rust classes and turns Rust futures into Python awaitables.
Go CGO FFIDefines the C-shaped boundary for JSON, bytes, error tags, cancellation, and opaque handles.
Ruby MagnusExposes Rust objects to Ruby and runs blocking work outside the VM lock.

The common ownership rules are:

  • Host buffers and strings remain host-owned unless the boundary defines a transfer.
  • Native output and error buffers are released through matching boundary operations.
  • Opaque sandbox, execution, agent, SSH, and stream handles stay native-owned until close.
  • Cancellation affects the current operation. It does not imply termination of a runtime-owned resource.

References: sdk/…/ffi.go• L20-47 sdk/…/lib.rs• L5-30 sdk/…/shared_handle.rs• L7-45 sdk/…/runtime.rs• L117-138 sdk/…/lib.rs• L190-239

Sandbox handles

The live sandbox object and the sandbox handle solve different problems. The live object is the session used for guest work. The handle is a retained reference to a persisted identity used to inspect state or regain a live session later.

Live sandbox objects

A live object carries the sandbox identity and retained destination. It can execute commands, use guest services, report health, read logs and metrics, and perform lifecycle actions.

Identity-aware actions reject a same-name replacement instead of acting on a newer sandbox. A live object does not make every operation available on every destination; unsupported local-only operations return a typed error on remote resources.

References: sdk/…/handle.rs• L148-205 sdk/…/handle.rs• L224-233 sdk/…/sandbox.ts• L153-166 sdk/…/resource.go• L20-44 sdk/…/sandbox.rs• L25-36

Metadata handles

A metadata handle comes from lookup or listing and represents a point-in-time view. Refresh or perform a new lookup before a state-sensitive action when the sandbox may have changed.

The handle can start a stopped sandbox, connect to a running one, wait for a state, stop or kill it, and remove it after it stops. This supports detached workflows and control-plane tools that do not need to run commands inside the guest.

Handles remain bound to the identity they observed. If a name is removed and reused, an old handle must not redirect an identity-sensitive action to the replacement.

References: sdk/…/handle.rs• L224-257 sdk/…/context.ts• L123-146 sdk/…/context.go• L124-171 sdk/…/resource.go• L20-35 sdk/…/context.rs• L103-154

Cross-language consistency

The SDKs aim for semantic consistency rather than identical spelling. A lifecycle change in the Rust model should retain the same meaning in each language: create, connect-or-create, execute, inspect, wait, stop, detach, restart, destroy, and remove.

The contracts that matter most are:

  • A name locates a resource, but its stable identity protects actions from same-name replacements.
  • A live resource retains the destination and native provider selected at creation or lookup.
  • A metadata handle is a snapshot until refreshed.
  • Graceful stop, forceful kill, detach, and close are different actions.
  • A managed job keeps a runtime identity after admission. Observation errors are not confirmed process exits.
  • A completed command carries an exit status. Launch and transport failures use the language error model.
  • Stream, native, job, attachment, and opaque handles need explicit or scoped cleanup.
  • Restore is distinct from fresh creation, and unsupported destination settings are rejected rather than ignored.
  • Modification plans preserve live, next-start, restart-required, and unsupported outcomes.
  • Remote Service operations preserve cloud-only support, target state, status, pagination, and no-retry change behavior.

References: sdk/…/handle.rs• L184-205 sdk/…/lifetime.rs• L48-90 sdk/…/provider.ts• L86-106 sdk/…/context.go• L184-204 sdk/…/context.rs• L49-95 sdk/…/lifetime.rb• L3-18

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the Rust context, resource identity, and lifecycle model aligned with N-API, PyO3, CGO, and Magnus surfaces.
  • Keep provider ABI, SDK version, capability checks, and split-package loading aligned with the native artifacts.
  • Keep runtime resolution strict about matching msb and libkrunfw pairs. Do not make package candidates override explicit user settings.
  • Keep backend selection separate from credential presence. An API key must not silently select the remote destination.
  • Keep returned resources, streams, cancellation, and cleanup bound to the provider or context that created them.
  • Keep omitted values distinct from explicit zero, clear, or null values at every adapter boundary.
  • Keep native output buffers, error strings, opaque handles, and cancellation IDs released by the matching boundary.
  • Keep stop, kill, detach, close, and context cancellation distinct across lifecycle wrappers.
  • Keep typed error categories and structured recovery data aligned across host languages.
  • Keep Service cloud-only behavior, target state, pagination, and no-retry changes aligned with the related API page.
  • Mark a feature as unsupported in a language surface when its adapter does not expose it. Do not imply full Rust parity.

Important failure modes

TriggerConsequenceGuard
An API key is present without remote selectionThe local fallback can be selectedCreate a remote context or select a remote profile explicitly.
Only one local runtime artifact resolvesLocal setup fails before sandbox creationResolve or install the complete executable-and-firmware pair.
A native provider and host package use different ABI or release versionsLoading or value conversion failsInstall matching core, provider, and SDK versions.
A resource is used after a provider or context changeThe call can target the wrong library or fail provider checksUse the context or resource that captured the intended destination.
A same-name sandbox replaces the one held by an old objectIdentity-sensitive lifecycle actions are rejectedRefresh or look up the replacement as a new resource.
A handle is closed or an operation is cancelled and the caller assumes terminationThe sandbox or job can continue runningUse stop or kill for termination and close only for handle cleanup.
A managed-job admission result is uncertain and the caller retriesTwo commands can runRecover the returned job identity or inspect jobs before retrying.
A remote Service change result is unknown and the caller retriesThe route can change twice or point to an unintended targetRead the Service before retrying the change.
A modification needs a restart but the selected policy forbids itApply is rejected or remains deferredInspect the plan and choose the policy that matches the desired effect.
A stream or native handle is not consumed or closedOutput can stall or native resources can remain liveConsume stream events and close observation handles.
A Go FFI buffer or returned native allocation is not releasedNative memory can leak or later calls can failCopy returned data and release it through the matching FFI operation.
A Python or Ruby async bridge is used after interpreter or process shutdownThe call fails or native work can outlive the host runtimeLet the binding own bridge shutdown and create new work in the current process after fork.

Key files

FileWhy to read it
sdk/…/lib.rsShows the shared Rust public exports and feature-gated surfaces.
sdk/…/dispatch.rsShows retained destinations and resource collection dispatch.
sdk/…/profile.rsShows configured backend and profile resolution.
sdk/…/handle.rsShows sandbox identity, observations, and lifecycle handles.
sdk/…/lifetime.rsShows detach and ownership-aware cleanup.
sdk/…/mod.rsShows the Rust runtime setup boundary.
sdk/…/api.rsShows the shared Service resource contract.
sdk/…/index.tsShows the Node.js/TypeScript public exports.
sdk/…/context.tsShows explicit local and remote contexts and retained collections.
sdk/…/provider.tsShows native provider validation and resource ownership.
sdk/…/context.rsShows the N-API context bridge to Rust collections.
sdk/…/setup.tsShows Node.js runtime resolution and installation.
sdk/…/__init__.pyShows the Python public package surface and runtime registration.
sdk/…/contexts.pyShows Python local and remote context construction.
sdk/…/context.rsShows PyO3 context and collection wrappers.
sdk/…/runtime.rsShows the Python async bridge lifetime.
sdk/…/context.goShows Go contexts, collections, and resource retention.
sdk/…/provider.goShows explicit native provider loading and registration.
sdk/…/setup.goShows lazy FFI loading and its separation from runtime installation.
sdk/…/ffi.goShows the CGO boundary, ownership, and handle contract.
sdk/…/lib.rsShows native handles, the Rust runtime, and thread safety.
sdk/…/README.mdShows Go setup, distribution choices, and lifecycle usage.
sdk/…/context.rbShows Ruby context shortcuts and retained collections.
sdk/…/lifetime.rbShows Ruby scoped sandbox cleanup.
sdk/…/context.rsShows the Magnus context and collection bridge.
sdk/…/lib.rsShows Ruby runtime management and error mapping.
docs/rust-sdk.mdChild page for the detailed Rust SDK model.
docs/language-binding-adapters.mdChild page for adapter conversion and ownership contracts.
docs/service-management-apis.mdRelated page for the Service management API contract.