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 / language-binding-adapters

Language binding adapters

Language binding adapters make Microsandbox usable from Node.js and TypeScript, Python, Go, and Ruby without asking application code to speak Rust. Each binding keeps the same sandbox, snapshot, Service, error, and guest-agent ideas while presenting them in the language's normal async, type, resource, and package model. This page complements the SDK bindings overview, the Rust SDK page, and the service management APIs page.

Binding architecture

The bindings form a language-facing layer over the Rust SDK and its guest-agent protocol. A binding turns local language values into shared requests, runs work through a native or protocol boundary, and turns results into language-native resources and errors.

The diagram shows the main paths from application code to sandbox and guest-agent services.

flowchart LR
    A[Node.js / TypeScript] --> B[N-API adapter]
    C[Python] --> D[Python extension]
    E[Go] --> F[C ABI and native provider]
    G[Ruby] --> H[Rust extension]
    B --> I[Rust SDK]
    D --> I
    F --> I
    H --> I
    I --> J[Local or cloud backend]
    K[Shared agent client] --> L[Guest agent]
    M[Generated domain types] --> A
    M --> C
    M --> E
    M --> G

The public adapters cover one product model: create or find a sandbox, run commands, use files and volumes, apply network policy, capture or restore state, inspect output and metrics, and control lifecycle. They also expose cloud Service resources that publish one sandbox port through a public URL. Lower-level agent clients serve integrations that need direct guest messages rather than sandbox management.

References: sdk/…/index.ts• L1-20 sdk/…/lib.rs• L35-116 sdk/…/lib.rs• L1-54 sdk/…/lib.rs• L26-39

Node.js and TypeScript binding

The Node.js and TypeScript binding joins a Rust N-API add-on to a TypeScript public layer. The add-on performs native sandbox work. The TypeScript layer supplies builders, async iterables, stable wrapper objects, context selection, and mapped errors.

N-API surface

The N-API surface supports sandbox creation and lookup, command execution, attach, guest files, SSH, volumes, images, logs, metrics, snapshots, and lifecycle control. The TypeScript exports group these actions around live sandboxes, retained snapshots, named resources, local or remote contexts, and cloud Services.

Creation, connection, and restore are distinct paths. connectOrCreate converges on one persisted name. Restore selects saved state and destination settings instead of reusing fresh-boot meaning. Contexts retain the selected local or remote destination so later lookups do not silently move to a changed ambient configuration.

Snapshot groups now model a named history of immutable checkpoints. The API can inspect a group's source association, select or clear its head, capture more checkpoints, import archives, remove members or groups, and return verification findings. A checkpoint can spawn a sandbox while preserving the checkpoint's identity and backend.

References: sdk/…/index.ts• L18-70 sdk/…/index.ts• L105-121 sdk/…/context.ts• L25-42 sdk/…/context.ts• L112-208 sdk/…/sandbox.ts• L97-114 sdk/…/sandbox.ts• L384-491 sdk/…/snapshot-group.ts• L67-180 sdk/…/snapshot.ts• L181-238

Native error and capability boundary

Native failures cross the boundary as typed Microsandbox errors. The TypeScript layer maps known native tags to error classes and keeps structured data for cases such as snapshot recovery, verification, removal recovery, Service changes, and unsupported operations.

The TypeScript layer also refuses options that an older native add-on cannot honor. This protects explicit restore policies, snapshot import limits, resize tracking, and other capability-sensitive requests from being silently dropped.

References: sdk/…/errors.ts• L1-170 sdk/…/error-mapping.ts• L1-160 sdk/…/sandbox.ts• L316-341 sdk/…/snapshot.ts• L686-692 sdk/…/context.ts• L175-178

Native package delivery

The npm package presents one entry point and selects a platform package for the native add-on. That platform package also carries the local msb runtime and matching libkrunfw file. A configured runtime home has precedence over package files, while an explicit runtime path is still a direct override.

Runtime setup treats msb and libkrunfw as one required pair. A partial home installation is an error rather than a fallback. The package can resolve or install a pair, but loading the JavaScript binding and resolving the host runtime remain separate concerns.

References: sdk/…/README.md• L13-14 sdk/…/README.md• L43-70 sdk/…/resolve-binary.ts• L21-58 sdk/…/setup.ts• L4-20 sdk/…/setup.ts• L68-103 sdk/…/package.json• L23-36 sdk/…/package.json• L8-17

Python extension and package layer

The Python binding has one public package with a PyO3 extension below it. The extension connects Python calls to the Rust SDK. The Python layer exposes async classes, frozen data values, string enums, typed exceptions, inspections, and runtime helpers.

Python resource model

Python callers create, find, restore, execute, attach to, inspect, snapshot, and remove sandboxes. The same package covers guest files, volumes, network policy, logs, metrics, images, SSH, lifecycle, jobs, and cloud Services.

Explicit LocalContext and RemoteContext objects retain a destination for resource collections. A remote context captures its endpoint and credentials when it is built. A derived context can change selected remote settings without changing the destination retained by existing resources.

Python snapshot groups separate a mutable history from its immutable checkpoints. Group operations expose head selection, capture, import, inspection, removal, and verification. Restore accepts a snapshot reference and destination choices, so creation-only settings do not become restore inputs.

References: sdk/…/__init__.py• L3-65 sdk/…/__init__.py• L132-166 sdk/…/contexts.py• L11-132 sdk/…/context.rs• L20-95 sdk/…/context.rs• L98-293 sdk/…/lib.rs• L35-116

Python async operation model

The extension runs asynchronous SDK work on an owned multi-thread runtime and returns awaitable Python values. Streams expose Python async iteration for command output, logs, metrics, pull progress, and guest files. At interpreter shutdown, the package closes that runtime and waits for native work instead of leaving callbacks behind.

Operations that use process standard input or output take an exclusive lease. Cancellation releases the lease and wakes blocked reads or writes. This keeps image import and SSH stdio from competing with other SDK operations or hanging at shutdown.

References: sdk/…/runtime.rs• L1-12 sdk/…/runtime.rs• L83-125 sdk/…/runtime.rs• L127-146 sdk/…/stdio.rs• L24-38 sdk/…/stdio.rs• L56-97 sdk/…/README.md• L66-70

Python package delivery

Python wheels bundle the native package's local runtime files. The package still exposes resolve, install, and ensure helpers for source checkouts or shared runtime homes. Runtime resolution returns the executable, matching firmware library, and source that supplied the pair.

The package registers its wheel executable as a candidate after the configured runtime home. It does not treat the extension itself as the host runtime. This separation lets cloud-only use avoid local runtime setup while local use can fail clearly when the pair is missing or incomplete.

References: sdk/…/README.md• L32-41 sdk/…/README.md• L358-367 sdk/…/__init__.py• L278-285 sdk/…/setup.py• L11-43 sdk/…/setup.py• L54-79 sdk/…/setup.rs• L9-24 sdk/…/setup.rs• L68-105

Go FFI and bundled-native delivery

The Go binding presents an idiomatic Go API over a Rust C ABI. Go callers use context.Context, options, channels, typed errors, and explicit Close calls while the boundary carries structured JSON and raw guest-agent bytes.

FFI contract

The Go loader admits a native provider and resolves the C ABI at run time. Sandboxes, contexts, streams, jobs, snapshots, and Services use opaque native handles. Each resource retains the provider that created it, which keeps calls, cancellation, and cleanup on one native library.

The ABI distinguishes normal results, typed error payloads, and raw agent or snapshot bytes. Go owns the converted result values and releases native allocations through the matching boundary. Context cancellation stops waiting or native work when possible, but it does not undo an effect that already completed.

Optional ABI symbols represent capabilities rather than global load requirements. A newer Go package can load an older provider for unrelated work, while a request that needs a missing capability returns an explicit unsupported error.

References: sdk/…/ffi.go• L1-47 sdk/…/provider.go• L16-29 sdk/…/provider.go• L56-97 sdk/…/lib.rs• L1-30 sdk/…/lib.rs• L740-769 sdk/…/microsandbox_go_ffi.h• L56-71

Go context and provider model

Go separates a resource destination from the per-operation context.Context. A local or remote Context owns the selected backend and exposes sandbox, volume, snapshot, and checkpoint collections. A resource keeps that destination even when process-wide selection or environment settings later change.

The provider model supports full, local, and remote distributions. An explicitly loaded provider must match the expected ABI, SDK version, backend kind, and advertised capability. A derived remote context uses the original provider, so credentials and endpoint changes do not redirect existing resources.

References: sdk/…/context.go• L9-25 sdk/…/context.go• L35-69 sdk/…/context.go• L88-122 sdk/…/context.go• L184-210 sdk/…/context_remote.go• L64-80 sdk/…/context.go• L23-53 sdk/…/context.go• L157-201 sdk/…/provider.go• L9-29

Go lifecycle and state model

The Go API distinguishes a live sandbox from a persisted resource record. Stable IDs prevent a stale receiver from acting on a replacement that reused the same name. The same identity rule applies to volumes, snapshots, and other retained resources.

Snapshot groups provide mutable history over immutable checkpoints. Captures and imports return the exact operation result, including head changes and warnings. Resize tracking returns request identities and observed convergence, so waiting for a resize never switches to a newer request by accident.

References: sdk/…/resource.go• L10-69 sdk/…/restore.go• L20-108 sdk/…/snapshot_group.go• L15-24 sdk/…/snapshot_group.go• L51-110 sdk/…/snapshot_group.go• L113-148 sdk/…/resize_operations.go• L12-19 sdk/…/resize_operations.go• L39-99

Bundled-native delivery

The full Go module embeds the FFI library and extracts it lazily before the first native call. This removes the need for a Rust toolchain during a normal Go build. Lean core, local, and remote modules can instead use an explicitly provisioned provider.

The embedded FFI library is only the binding bridge. EnsureRuntime separately resolves or installs the matching msb and libkrunfw runtime pair. Provider installation verifies a trusted digest and target before loading the library. It never installs the host runtime on its own.

References: sdk/…/README.md• L43-73 sdk/…/setup.go• L19-59 sdk/…/setup.go• L87-107 sdk/…/provider_setup.go• L18-27 sdk/…/provider_setup.go• L74-155 sdk/…/provider_setup.go• L189-225

Ruby extension

The Ruby binding uses a Magnus Rust extension with a small Ruby layer. The extension maps Ruby hashes, symbols, strings, arrays, and keywords to shared SDK requests. The Ruby layer adds chainable builders, scoped cleanup, filesystem helpers, context selectors, and typed exception classes.

Ruby native extension

Ruby supports sandbox creation and lookup, command execution, files, volumes, network settings, images, snapshots, logs, metrics, SSH, and lifecycle actions. Native waits release Ruby's global VM lock, so other Ruby threads can run while an operation waits.

The extension maps core failures to Ruby exception subclasses with stable codes. Service failures report whether the change was unchanged or unknown. Snapshot import, verification, removal, and source-recovery failures keep structured results or recovery locators instead of requiring message parsing.

References: sdk/…/lib.rs• L186-245 sdk/…/lib.rs• L410-509 sdk/…/core_error.rs• L17-137 sdk/…/errors.rb• L17-44 sdk/…/errors.rb• L105-224

Ruby contexts and lifecycle

Ruby resource class methods use the configured backend by default. LocalContext and RemoteContext let callers capture a destination before creating or finding a resource. Collections and returned resources retain that context, including after a remote context is derived or environment settings change.

Sandbox.with gives block-scoped ownership and awaits cleanup for the run it created. Detached, remote, and independently connected runs are not stopped by that scope. After a process fork, the extension creates child-safe runtime state before native work resumes.

References: sdk/…/context.rb• L5-47 sdk/…/context.rb• L61-65 sdk/…/context.rs• L15-100 sdk/…/lib.rs• L133-184 sdk/…/lifetime.rb• L3-18 sdk/…/README.md• L122-131

Ruby snapshot groups

Ruby exposes Snapshot as a source-bound checkpoint history and Checkpoint as one immutable artifact. A group can capture later checkpoints, select or clear its head, inspect its source association, import archives, remove members or the group, and verify its selected artifacts.

Groups and checkpoints can spawn a sandbox with destination-only restore settings. The receiver supplies the source and backend, while the caller chooses the new name, resources, mounts, network limits, and progress handling. This keeps a restore from smuggling fresh image or workload settings into saved state.

References: sdk/…/snapshot_group.rs• L86-180 sdk/…/snapshot_group.rs• L197-315 sdk/…/snapshot_spawn.rs• L106-164 sdk/…/snapshot_spawn.rs• L192-240 sdk/…/README.md• L178-197

Ruby package delivery

The gem loads an ABI-specific native extension first and then tries the source-build path. Platform gems are prepared for common Linux, macOS, and Windows targets, but the current release still falls back to a source build when a platform gem is not published or does not match the host.

The extension and the local msb runtime are separate concerns. The gem and its Rust core use one release version so the Ruby API and native contract stay paired. Local use still needs the runtime and firmware pair installed.

References: sdk/…/README.md• L14-46 sdk/…/README.md• L80-88 sdk/…/microsandbox.rb• L9-22 sdk/…/version.rb• L1-5 sdk/…/Cargo.toml• L1-26

Shared agent clients

The shared agent client is the low-level path to the guest agent service. It does not create sandboxes or manage images, storage, metrics, or lifecycle. It owns the transport session, handshake, frame routing, and one-response or streaming request behavior.

Agent transport and message model

The client can use a local socket, a Windows named pipe, or a caller-owned byte stream. A session reads a ready frame, assigns request IDs, matches responses by correlation ID, and keeps a stream open until its terminal frame. Follow-up messages can carry input, signals, resize data, or more bytes.

Language adapters expose raw agent access for specialized integrations. Typed helpers may encode and decode messages, but the raw frame path remains available when an integration needs direct protocol control.

References: sdk/…/index.d.ts• L4-57 sdk/…/napi.ts• L114-143 sdk/…/ffi.go• L262-271 sdk/…/lib.rs• L240-274 sdk/…/_microsandbox.pyi• L65-91

Agent compatibility

The client uses the peer's ready frame to learn the protocol generation. It can reject an unsupported typed action before sending a message, which protects older guest agents while allowing other operations to continue.

References: sdk/…/index.d.ts• L29-56 sdk/…/ffi.go• L262-271

Generated domain types

Generated domain types give the adapters one shared meaning for sandbox requests and results. They describe backend-neutral intent such as resources, root filesystems, mounts, networking, lifecycle, execution, snapshots, restore policy, secrets, storage, modification plans, and cloud Service targets.

The Rust shared types are the source of truth. Generated TypeScript types carry the same domain and cloud shapes to JavaScript consumers. The types describe data and intent; they do not create sandboxes, manage Services, or run native work.

Cross-language configuration contracts

Each adapter changes names and value forms for its language, but it must preserve the meaning of the shared contract. Sparse changes distinguish an omitted field from an explicit clear. Nested collections can merge or replace. Known fields and enum values remain validated at the boundary.

Network configuration is one visible example of this contract. Node.js uses fluent builders and camelCase output. Python uses frozen data classes and typed enums. Go uses functional options and explicit pointer fields. These forms still describe the same policy, DNS, TLS, secret, proxy, port, and rate-limit intent.

Modification is another shared contract. Node.js, Python, and Go expose language-native option forms but send the same policy choices, secret source rules, sparse removals, and plan dispositions. This lets callers reason about live changes and restart needs in the same way across SDKs.

Cloud Service data follows the same rule. Go, Python, and Ruby expose slugs, URLs, status, targets, timestamps, and paged results in language-native forms, while the cloud contract keeps the resource identity and target meaning stable.

References: sdk/…/network-config.ts• L44-159 sdk/…/types.py• L1280-1491 sdk/…/options.go• L1164-1243 sdk/…/sandbox.go• L433-523 sdk/…/modify.ts• L1-180 sdk/…/sandbox.rs• L948-1027 sdk/…/modify.go• L265-391 sdk/…/service.go• L29-80 sdk/…/service.rs• L14-25 sdk/…/services.rs• L19-27 sdk/…/builders.test.ts• L652-708 sdk/…/network_test.go• L14-92 sdk/…/test_http_deny.py• L8-51

Domain and cloud contracts

Domain types describe backend-neutral requests. Cloud types wrap that intent in service request and response shapes. This keeps host-only state out of public tenant data and lets local and cloud backends share user intent without sharing private runtime handles. Cloud Service types add a public resource identity and a sandbox-port target without exposing the native handle used by an adapter.

References: sdk/…/lib.rs• L20-38 sdk/…/lib.rs• L61-74 sdk/…/service.rs• L32-56 sdk/…/helpers.rs• L172-249

Contract generation flow

Shared Rust type changes must pass through the type-generation step before language-facing generated contracts are current. Adapter mappings then consume the generated shape rather than maintaining independent copies.

The diagram shows how one shared type change reaches language APIs.

flowchart LR
    A[Rust shared domain types] --> B[Type generator]
    B --> C[Generated TypeScript types]
    B --> D[Cloud data shapes]
    C --> E[Language adapter mappings]
    D --> E
    E --> F[SDK callers]

References: sdk/…/index.d.ts• L1-3 sdk/…/napi.ts• L18-21 sdk/…/_microsandbox.pyi• L1-11 sdk/…/lib.rs• L1-15

Change checklist

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

  • Keep each language's context, collection, and retained-resource rules aligned so a resource does not switch backend after creation.
  • Keep native declarations, ABI symbols, provider capability markers, and wrapper methods aligned before exposing a new operation.
  • Keep creation, restore, live fork, and snapshot-group spawn options separate in every binding.
  • Keep snapshot group, checkpoint, head-update, verification, removal, and recovery result shapes aligned across Node.js, Python, Go, and Ruby.
  • Keep runtime discovery aligned with the complete msb and libkrunfw pair. A binding artifact and a host runtime are separate delivery units.
  • Keep native error tags, language exception classes, structured recovery fields, and Service change-state fields aligned.
  • Keep agent ready-frame capability checks and terminal-frame handling aligned with the shared protocol client.
  • Regenerate packages/…/domain.ts, snapshot.ts, and cloud.ts from Rust type changes.
  • Preserve secret placeholders and host-side substitution rules. Do not expose secret values through guest configuration or adapter errors.

Important failure modes

TriggerConsequenceGuard
A platform package or native provider lacks a required binding symbolThe SDK cannot load or one feature reports as unavailableKeep ABI exports, declarations, loaders, provider metadata, and capability checks aligned
A runtime home contains only msb or only libkrunfwLocal startup fails or setup reports an incomplete runtimeResolve and deliver the pair as one unit
A resource is used after its context or provider changesCalls can reach the wrong backend or lose the native ownerRetain context and provider identity on collections and resources
A creation option crosses into restore or snapshot spawnThe saved state request is rejected or gets the wrong meaningKeep source selection and destination restore settings separate
A snapshot group or checkpoint result is rebuilt from a later head lookupThe caller sees a later operation's state instead of the operation it startedReturn operation-owned head updates and recovery data
A generated TypeScript file is edited without changing Rust sourceRegeneration removes the changeUpdate the Rust type and regenerate the checked files
A guest agent does not support a requested messageTyped work is rejected or cannot be decodedRead ready-frame capabilities before dispatch
A Service change reports an unknown outcomeRetrying can duplicate or conflict with a change that may have appliedRefresh the Service and inspect its current state before retrying
A secret value crosses into guest configuration or an error messageCredential material can be exposedSend placeholders and keep substitution host-side
Ruby reuses a parent runtime after forkNative work can hang or fail in the childRebuild child runtime state before native use

Key files

FileWhy to read it
sdk/…/index.tsShows the public Node and TypeScript export surface.
sdk/…/context.tsShows retained local and remote destinations and resource collections.
sdk/…/sandbox.tsShows the public sandbox, restore, lifecycle, and progress model.
sdk/…/snapshot-group.tsShows named snapshot histories, checkpoint capture, head updates, and restore.
sdk/…/resolve-binary.tsShows platform package lookup for the local runtime.
sdk/…/__init__.pyShows the Python package's public resources, types, errors, and setup helpers.
sdk/…/contexts.pyShows explicit destination selection and remote context derivation.
sdk/…/context.rsShows Python resource collections and async entry points.
sdk/…/runtime.rsShows the owned async bridge and shutdown contract.
sdk/…/ffi.goShows the Go-to-Rust ABI boundary and result model.
sdk/…/provider.goShows native provider admission and provider retention.
sdk/…/context.goShows Go destination contexts and retained resource routing.
sdk/…/provider_setup.goShows trusted native provider installation and verification.
sdk/…/snapshot_group.goShows Go snapshot histories, operation results, and verification data.
sdk/…/lib.rsShows Ruby native execution, GVL release, and error mapping.
sdk/…/context.rsShows Ruby contexts and resource collections.
sdk/…/snapshot_group.rsShows Ruby group, checkpoint, import, and verification objects.
sdk/…/snapshot_spawn.rsShows destination-only snapshot restore and progress sessions.
packages/…/README.mdExplains the shared guest-agent client boundary and transport model.
packages/…/client.tsShows the TypeScript agent client as a specialization of the shared router.
packages/…/typescript.rsShows the Rust-to-TypeScript generation boundary.
packages/…/cloud.tsShows the generated cloud wire shapes consumed by TypeScript clients.