Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.microsandbox.dev/llms.txt

Use this file to discover all available pages before exploring further.

See Overview for configuration examples and Lifecycle for state management.

Setup


EnsureInstalled()

func EnsureInstalled(ctx context.Context, opts ...SetupOption) error
Optional. Ensure msb + libkrunfw are present at ~/.microsandbox/, downloading them from the matching GitHub release if not. Call at startup to surface install errors up front; otherwise the first sandbox call handles it. The FFI library is embedded in the Go binary and loads automatically — EnsureInstalled does not govern it. Idempotent. Parameters
NameTypeDescription
ctxcontext.ContextCancels an in-flight msb + libkrunfw download
opts...SetupOptionSee SetupOption for the available knobs

IsInstalled()

func IsInstalled() bool
Report whether msb + libkrunfw are present on disk at the SDK’s pinned version. Does not dlopen the FFI library (which ships embedded).

SDKVersion()

func SDKVersion() string
Return the microsandbox release version this SDK was compiled against.

RuntimeVersion()

func RuntimeVersion() (string, error)
Return the version reported by the loaded FFI library. Auto-loads the library on first use; returns ErrLibraryNotLoaded only if loading fails (e.g. unsupported platform or GLIBC mismatch).

SetupOption

Configures EnsureInstalled. Pass any of the options below as variadic arguments. Options apply only to the first call; subsequent calls are no-ops.
OptionEffect
WithSkipDownload()Refuse to download msb + libkrunfw — require them to be pre-installed

WithSkipDownload()

func WithSkipDownload() SetupOption
Prevent EnsureInstalled from fetching the msb + libkrunfw bundle from GitHub. Use when the runtime is already on disk at the install path (e.g. air-gapped CI). The embedded FFI library is unaffected — it ships with the SDK.

Top-level functions


CreateSandbox()

func CreateSandbox(
    ctx context.Context,
    name string,
    opts ...SandboxOption,
) (*Sandbox, error)
Create and boot a new sandbox. Pulls the image if needed, boots the VM, starts the guest agent, and waits until it is ready to accept commands. The returned *Sandbox owns the VM process — call Close (or StopAndWait + Close) when done. Parameters
NameTypeDescription
ctxcontext.ContextCancels the boot operation. Cancelling after this function returns has no effect on the running sandbox
namestringSandbox name
opts...SandboxOptionFunctional options — see Options
Returns
TypeDescription
*SandboxRunning sandbox
errorTyped *Error — see Error Handling
sb, err := m.CreateSandbox(ctx, "my-sandbox",
    m.WithImage("python:3.12"),
    m.WithMemory(512),
    m.WithCPUs(2),
    m.WithEnv(map[string]string{"PYTHONDONTWRITEBYTECODE": "1"}),
)
if err != nil {
    return err
}
defer func() {
    _, _ = sb.StopAndWait(context.Background())
    _ = sb.Close()
}()

CreateSandboxDetached()

func CreateSandboxDetached(
    ctx context.Context,
    name string,
    opts ...SandboxOption,
) (*Sandbox, error)
Same as CreateSandbox with WithDetached automatically applied. The VM continues running after the returned handle is released or the Go process exits. Reattach via GetSandbox.

StartSandbox()

func StartSandbox(ctx context.Context, name string) (*Sandbox, error)
Restart a previously stopped sandbox. The VM reboots using the persisted configuration. Parameters
NameTypeDescription
ctxcontext.ContextCancels the boot operation
namestringName of a stopped sandbox
Returns
TypeDescription
*SandboxRunning sandbox

StartSandboxDetached()

func StartSandboxDetached(ctx context.Context, name string) (*Sandbox, error)
Boot a stopped sandbox in detached mode.

GetSandbox()

func GetSandbox(ctx context.Context, name string) (*SandboxHandle, error)
Look up a sandbox by name and return a metadata handle without connecting to it. Returns ErrSandboxNotFound if no such sandbox exists. The returned *SandboxHandle exposes Connect, Start, Stop, Kill, Remove, Metrics, and Logs.

ListSandboxes()

func ListSandboxes(ctx context.Context) ([]*SandboxHandle, error)
Return metadata for every known sandbox (running, stopped, draining, crashed) ordered by creation time, newest first.

RemoveSandbox()

func RemoveSandbox(ctx context.Context, name string) error
Delete a stopped sandbox and all its persisted state from disk. Fails with ErrSandboxStillRunning if the sandbox is still running.

AllSandboxMetrics()

func AllSandboxMetrics(ctx context.Context) (map[string]*Metrics, error)
Return a point-in-time metrics snapshot for every running sandbox, keyed by sandbox name. Only running and draining sandboxes appear.

Instance methods

The *Sandbox returned by CreateSandbox and friends has the following methods. *Sandbox is safe for concurrent use from multiple goroutines.

Name()

func (s *Sandbox) Name() string
Return the sandbox’s name.

FS()

func (s *Sandbox) FS() *SandboxFs
Return a filesystem accessor for reading and writing files inside the running sandbox. See Filesystem for the full API.

Exec()

func (s *Sandbox) Exec(
    ctx context.Context,
    cmd string,
    args []string,
    opts ...ExecOption,
) (*ExecOutput, error)
Run a command inside the sandbox and wait for it to complete. Collects all stdout and stderr into memory and returns them along with the exit code. For long-running processes or large output, use ExecStream. A non-zero exit code is not a Go error — inspect ExecOutput.Success or ExecOutput.ExitCode instead. Transport, timeout, and spawn failures are returned as errors.
out, err := sb.Exec(ctx, "python3", []string{"-c", "print(1 + 1)"})
if err != nil {
    return err
}
fmt.Println(out.Stdout())    // "2\n"
fmt.Println(out.ExitCode())  // 0
See Execution for ExecOption details.

ExecStream()

func (s *Sandbox) ExecStream(
    ctx context.Context,
    cmd string,
    args []string,
    opts ...ExecOption,
) (*ExecHandle, error)
Run a command with streaming output. Returns a handle that emits Started, Stdout, Stderr, Exited, and Done events as they happen. The handle MUST be closed with Close when done. See ExecHandle for the event loop.

Shell()

func (s *Sandbox) Shell(
    ctx context.Context,
    command string,
    opts ...ExecOption,
) (*ExecOutput, error)
Run a command through /bin/sh -c. Shell syntax like pipes, redirects, and && chains works.
out, err := sb.Shell(ctx, "ls -la /app && echo done")

ShellStream()

func (s *Sandbox) ShellStream(
    ctx context.Context,
    command string,
    opts ...ExecOption,
) (*ExecHandle, error)
Shell command with streaming output.

Attach()

func (s *Sandbox) Attach(ctx context.Context, cmd string, args ...string) (int, error)
Bridge the caller’s terminal directly to a process inside the sandbox for a fully interactive PTY session. The caller’s terminal must be a real TTY; primarily useful for CLI tools, not library code. Returns
TypeDescription
intExit code of the process

AttachShell()

func (s *Sandbox) AttachShell(ctx context.Context) (int, error)
Attach to the sandbox’s default shell (configured via WithShell, defaults to /bin/sh).

Drain()

func (s *Sandbox) Drain(ctx context.Context) error
Send a graceful drain signal (SIGUSR1) to the sandbox. Existing commands run to completion, new exec calls are rejected. Errors if this handle does not own the lifecycle.

Stop()

func (s *Sandbox) Stop(ctx context.Context) error
Gracefully shut down the sandbox (SIGTERM). Does not wait for the VM process to exit — use StopAndWait for that.

StopAndWait()

func (s *Sandbox) StopAndWait(ctx context.Context) (int, error)
Stop the sandbox and wait for the VM process to exit. Returns the guest exit code, or -1 if the guest did not report one.

Kill()

func (s *Sandbox) Kill(ctx context.Context) error
Force-terminate the sandbox immediately (SIGKILL). No graceful shutdown.

Wait()

func (s *Sandbox) Wait(ctx context.Context) (int, error)
Block until the sandbox process exits on its own and return the exit code (-1 if the guest did not report one). Errors if this handle does not own the lifecycle.

Detach()

func (s *Sandbox) Detach(ctx context.Context) error
Release the Rust-side handle without stopping the VM. Use on sandboxes created with WithDetached once the caller is done with the handle but the sandbox should keep running. After Detach, the handle is invalid; a subsequent Close returns ErrInvalidHandle.

Close()

func (s *Sandbox) Close() error
Release the Rust-side handle. Safe to call multiple times; the second call returns ErrInvalidHandle. For a sandbox created with WithDetached, Close will stop the VM — use Detach instead if the intent is to leave it running.

OwnsLifecycle()

func (s *Sandbox) OwnsLifecycle() (bool, error)
Report whether this handle owns the VM process. When true, closing or stopping the handle terminates the sandbox; when false the sandbox is detached.

OwnsLifecycleOrFalse()

func (s *Sandbox) OwnsLifecycleOrFalse() bool
Convenience that swallows the error and returns false on any failure. Suitable for log lines and best-effort branching.

RemovePersisted()

func (s *Sandbox) RemovePersisted(ctx context.Context) error
Remove the sandbox’s persisted state (filesystem and database record). The sandbox must already be stopped. This handle becomes invalid after the call.

Metrics()

func (s *Sandbox) Metrics(ctx context.Context) (*Metrics, error)
Get a point-in-time snapshot of the sandbox’s resource usage.
metrics, err := sb.Metrics(ctx)
fmt.Printf("CPU: %.1f%% Mem: %d bytes Uptime: %s\n",
    metrics.CPUPercent, metrics.MemoryBytes, metrics.Uptime)

Logs()

func (s *Sandbox) Logs(ctx context.Context, opts LogOptions) ([]LogEntry, error)
Read persisted sandbox output. Works for running and stopped sandboxes.
entries, err := sb.Logs(ctx, m.LogOptions{
    Sources: []m.LogSource{m.LogSourceStdout, m.LogSourceStderr},
})

MetricsStream()

func (s *Sandbox) MetricsStream(
    ctx context.Context,
    interval time.Duration,
) (*MetricsStreamHandle, error)
Start a streaming metrics subscription that delivers a snapshot every interval. Sub-millisecond precision is rounded up. Close the returned handle when done.
stream, err := sb.MetricsStream(ctx, 500*time.Millisecond)
if err != nil {
    return err
}
defer stream.Close()

for {
    metrics, err := stream.Recv(ctx)
    if err != nil || metrics == nil {
        break
    }
    fmt.Printf("CPU: %.1f%%  Mem: %d bytes\n", metrics.CPUPercent, metrics.MemoryBytes)
}

Patch

Helpers that construct rootfs patches for WithPatches. Access via the package-level Patch value. Each method returns a PatchConfig. Mkdir and Remove are idempotent; other operations error at boot when targeting a path already present in the image unless Replace: true is passed in PatchOptions. See Patches for conceptual context.

Patch.Text()

func (patchFactory) Text(path, content string, opts PatchOptions) PatchConfig
Write UTF-8 text content at path.

Patch.Append()

func (patchFactory) Append(path, content string) PatchConfig
Append content to an existing file at path. If the file lives in a lower image layer, it is copied up first.

Patch.Mkdir()

func (patchFactory) Mkdir(path string, opts PatchOptions) PatchConfig
Create a directory. Only opts.Mode is honoured; Replace is ignored (the operation is idempotent).

Patch.Remove()

func (patchFactory) Remove(path string) PatchConfig
Delete a file or directory. Idempotent.
func (patchFactory) Symlink(target, link string, opts PatchOptions) PatchConfig
Create a symlink at link pointing to target. Only opts.Replace is honoured.

Patch.CopyFile()

func (patchFactory) CopyFile(src, dst string, opts PatchOptions) PatchConfig
Copy a single host file at src into the guest rootfs at dst.

Patch.CopyDir()

func (patchFactory) CopyDir(src, dst string, opts PatchOptions) PatchConfig
Recursively copy a host directory at src into the guest rootfs at dst. Only opts.Replace is honoured.

Init

Helpers that construct InitConfig values for WithInit to hand off PID 1 inside the guest after agentd setup. Access via the package-level Init value. See Custom init system for image picks and shutdown semantics.

Init.Auto()

func (initFactory) Auto() InitConfig
Probe common init paths inside the guest (/sbin/init, /lib/systemd/systemd, …).
m.WithInit(m.Init.Auto())

Init.Cmd()

func (initFactory) Cmd(cmd string, opts InitOptions) InitConfig
Specify the init binary explicitly with optional argv/env. cmd must be an absolute path inside the guest rootfs.
m.WithInit(m.Init.Cmd(
    "/lib/systemd/systemd",
    m.InitOptions{
        Args: []string{"--unit=multi-user.target"},
        Env:  map[string]string{"container": "microsandbox"},
    },
))

Options

Functional options for CreateSandbox. Most options merge across repeated calls; WithImage and similar single-value setters replace.

WithImage()

func WithImage(image string) SandboxOption
OCI image, local path, or disk image (e.g. "python:3.12", "docker.io/library/alpine"). Use WithImageDisk when a disk-image root needs an explicit filesystem type. Required unless WithSnapshot is used.

WithImageDisk()

func WithImageDisk(path string, fstype string) SandboxOption
Use a disk image as the root filesystem and optionally provide the inner filesystem type, for example "ext4". The disk format is inferred from the path extension (.qcow2, .raw, or .vmdk).

WithSnapshot()

func WithSnapshot(pathOrName string) SandboxOption
Boot from a snapshot artifact by bare name or filesystem path. Mutually exclusive with WithImage. See Snapshots.

WithMemory()

func WithMemory(mebibytes uint32) SandboxOption
Guest memory in MiB. This is a limit, not a reservation.

WithCPUs()

func WithCPUs(cpus uint8) SandboxOption
Virtual CPUs.

WithWorkdir()

func WithWorkdir(path string) SandboxOption
Default working directory for commands.

WithShell()

func WithShell(shell string) SandboxOption
Shell binary used by Sandbox.Shell and Sandbox.AttachShell. Defaults to /bin/sh on most images.

WithEnv()

func WithEnv(env map[string]string) SandboxOption
Environment variables visible to all commands. Called repeatedly, the maps merge; later keys overwrite earlier ones.

WithHostname()

func WithHostname(hostname string) SandboxOption
Guest hostname.

WithUser()

func WithUser(user string) SandboxOption
Default user (UID or name) to run sandbox commands as.

WithReplace()

func WithReplace() SandboxOption
Replace any existing sandbox with the same name. Sends SIGTERM, waits up to 10s for graceful exit, then escalates to SIGKILL.

WithReplaceWithGrace()

func WithReplaceWithGrace(grace time.Duration) SandboxOption
Like WithReplace but with a caller-specified grace period between SIGTERM and SIGKILL. Implies WithReplace. A zero duration skips SIGTERM and SIGKILLs immediately.

WithDetached()

func WithDetached() SandboxOption
Create the sandbox in detached mode. The VM continues running after the Go process exits.

WithEntrypoint()

func WithEntrypoint(cmd ...string) SandboxOption
Override the image’s stored ENTRYPOINT. Consulted by msb exec / msb run (CLI command resolution against this sandbox), not by Sandbox.Exec / Sandbox.Shell — those pass cmd literally to the guest agent. Use this when configuring sandboxes via the SDK for later CLI attachment. For PID 1 handoff, use WithInit instead.

WithInit()

func WithInit(cfg InitConfig) SandboxOption
Hand off PID 1 to a guest init binary. Construct cfg via Init.

WithLogLevel()

func WithLogLevel(level LogLevel) SandboxOption
Override the sandbox process log verbosity. See LogLevel.

WithQuietLogs()

func WithQuietLogs() SandboxOption
Suppress sandbox-level log output entirely.

WithScripts()

func WithScripts(scripts map[string]string) SandboxOption
Named scripts mounted at /.msb/scripts/<name>. Called repeatedly, entries merge.

WithPullPolicy()

func WithPullPolicy(p PullPolicy) SandboxOption
Image pull behaviour. See PullPolicy.

WithMaxDuration()

func WithMaxDuration(d time.Duration) SandboxOption
Maximum sandbox lifetime. Zero means unlimited. Sub-second precision is rounded up to whole seconds.

WithIdleTimeout()

func WithIdleTimeout(d time.Duration) SandboxOption
Stop the sandbox after this much wall-clock time without exec activity. Zero means unlimited.

WithRegistryAuth()

func WithRegistryAuth(auth RegistryAuth) SandboxOption
Credentials for pulling from a private OCI registry. See RegistryAuth.

WithPorts()

func WithPorts(ports map[uint16]uint16) SandboxOption
Publish host TCP ports into the sandbox (map key = host port, value = guest port).

WithPortsUDP()

func WithPortsUDP(ports map[uint16]uint16) SandboxOption
Publish host UDP ports into the sandbox.

WithNetwork()

func WithNetwork(net *NetworkConfig) SandboxOption
Configure the network stack — preset, custom rules, DNS, TLS interception. See Networking.

WithSecrets()

func WithSecrets(secrets ...SecretEntry) SandboxOption
Append credential secrets to the sandbox. Secrets never enter the VM; the network proxy substitutes them at the transport layer. See Secrets.

WithPatches()

func WithPatches(patches ...PatchConfig) SandboxOption
Append rootfs patches applied before the VM boots. Patches are only compatible with OverlayFS rootfs (not disk images). Construct via Patch.

WithMounts()

func WithMounts(mounts map[string]MountConfig) SandboxOption
Volume mount configurations keyed by guest path. See Volumes.

SandboxHandle

A lightweight metadata reference to a sandbox returned by GetSandbox and ListSandboxes. Holds last-known name, status, config JSON, and timestamps; offers lifecycle methods that operate on the sandbox without an active connection. Call Connect or Start to upgrade to a full *Sandbox.
MethodReturnsDescription
Name()stringSandbox name
Status()SandboxStatusLast-known lifecycle status
ConfigJSON()stringRaw JSON configuration
CreatedAt()time.TimeCreation time, zero value if unknown
UpdatedAt()time.TimeLast-update time, zero value if unknown
Metrics(ctx)(*Metrics, error)Point-in-time resource metrics
Logs(ctx, opts)([]LogEntry, error)Persisted sandbox logs
Connect(ctx)(*Sandbox, error)Reattach to the running sandbox
Start(ctx)(*Sandbox, error)Boot a stopped sandbox in attached mode
StartDetached(ctx)(*Sandbox, error)Boot a stopped sandbox in detached mode
Stop(ctx)errorGraceful shutdown
Kill(ctx)errorForce terminate
Remove(ctx)errorDelete sandbox and persisted state
Snapshot(ctx, name)(*SnapshotArtifact, error)Snapshot this stopped sandbox under a bare name
SnapshotTo(ctx, path)(*SnapshotArtifact, error)Snapshot this stopped sandbox to an explicit path

Types

SandboxConfig

The config struct populated by SandboxOption functions. Most callers build a sandbox via CreateSandbox(ctx, name, ...opts); SandboxConfig is exported for callers that prefer to construct a value directly and pass its fields explicitly.
FieldTypeDescription
ImagestringOCI image, local path, or disk image
ImageFstypestringOptional inner filesystem type for disk-image roots
SnapshotstringSnapshot artifact path or bare name; mutually exclusive with Image
MemoryMiBuint32Guest memory in MiB
CPUsuint8Virtual CPUs
WorkdirstringDefault working directory
ShellstringShell binary used by Shell calls
HostnamestringGuest hostname
UserstringDefault guest user
ReplaceboolReplace existing sandbox with same name
ReplaceWithGrace*time.DurationGrace period between SIGTERM and SIGKILL (implies Replace)
Envmap[string]stringEnvironment variables
DetachedboolIf true, sandbox survives after process exits
Entrypoint[]stringOverride image entrypoint
Init*InitConfigHand PID 1 off to a guest init binary
LogLevelLogLevelSandbox log verbosity override
QuietLogsboolSuppress sandbox-level log output
Scriptsmap[string]stringNamed scripts mounted at /.msb/scripts/
PullPolicyPullPolicyImage pull behaviour
MaxDurationtime.DurationMaximum sandbox lifetime
IdleTimeouttime.DurationIdle timeout
RegistryAuth*RegistryAuthPrivate registry credentials
Portsmap[uint16]uint16Host→guest TCP port mappings
PortsUDPmap[uint16]uint16Host→guest UDP port mappings
Network*NetworkConfigNetwork policy and configuration
Secrets[]SecretEntrySecret injection entries
Patches[]PatchConfigRootfs modifications applied before boot
Volumesmap[string]MountConfigVolume mounts keyed by guest path

SandboxOption

type SandboxOption func(*SandboxConfig)
A functional option for CreateSandbox. All WithX helpers listed above return a SandboxOption.

InitConfig

Custom init specification.
FieldTypeDescription
CmdstringAbsolute path or "auto" to the init binary inside the guest rootfs
Args[]stringSupplemental argv (argv[0] is implicitly Cmd)
Envmap[string]stringExtra env vars merged on top of the inherited env

InitOptions

Tuning struct for Init.Cmd.
FieldTypeDescription
Args[]stringSupplemental argv
Envmap[string]stringExtra env vars

RegistryAuth

Private registry credentials.
FieldTypeDescription
UsernamestringRegistry username
PasswordstringRegistry password

PatchConfig

A single rootfs patch produced by Patch.
FieldTypeDescription
KindPatchKindPatch flavour
PathstringAbsolute guest path (text / file / mkdir / remove / append)
ContentstringText content (text / append)
Mode*uint32File or directory mode, e.g. 0o644
ReplaceboolWhen true, overwrite an existing path at the destination
SrcstringHost source path (copy_file / copy_dir)
DststringGuest destination path (copy_file / copy_dir)
TargetstringSymlink target
LinkstringSymlink path

PatchOptions

Tuning struct passed to Patch methods.
FieldTypeDescription
Mode*uint32File or directory mode
ReplaceboolOverwrite an existing path

PatchKind

type PatchKind string
ConstantValue
PatchKindText"text"
PatchKindAppend"append"
PatchKindMkdir"mkdir"
PatchKindRemove"remove"
PatchKindSymlink"symlink"
PatchKindCopyFile"copy_file"
PatchKindCopyDir"copy_dir"

PullPolicy

type PullPolicy string
Controls when the SDK fetches an OCI image from the registry.
ConstantValueDescription
PullPolicyDefault""Runtime default (currently PullPolicyIfMissing)
PullPolicyAlways"always"Pull every time, even if cached locally
PullPolicyIfMissing"if-missing"Pull only if not already cached
PullPolicyNever"never"Never pull; fail if missing

LogOptions

Filters for Logs.
FieldTypeDescription
Tailuint64Keep only the last N matching entries
Sincetime.TimeInclusive lower timestamp bound
Untiltime.TimeExclusive upper timestamp bound
Sources[]LogSourceSources to include; empty uses the runtime default

LogEntry

One persisted log entry.
FieldTypeDescription
SourceLogSourceOrigin of the captured data
SessionID*uint64Relay session ID, nil for system entries
Timestamptime.TimeCapture timestamp
Data[]byteCaptured bytes
MethodReturnsDescription
Text()stringCaptured bytes as a string

LogSource

type LogSource string
ConstantValue
LogSourceStdout"stdout"
LogSourceStderr"stderr"
LogSourceOutput"output"
LogSourceSystem"system"

LogLevel

type LogLevel string
Sandbox process log verbosity.
ConstantValueDescription
LogLevelDefault""Runtime default
LogLevelTrace"trace"Most verbose — all diagnostic output
LogLevelDebug"debug"Debug and higher
LogLevelInfo"info"Info and higher
LogLevelWarn"warn"Warnings and errors only
LogLevelError"error"Errors only

SandboxStatus

type SandboxStatus string
ConstantValueDescription
SandboxStatusRunning"running"Guest agent is ready
SandboxStatusStopped"stopped"VM shut down; can be restarted
SandboxStatusCrashed"crashed"VM exited unexpectedly
SandboxStatusDraining"draining"Graceful shutdown in progress
SandboxStatusPaused"paused"VM is paused

Metrics

Point-in-time resource usage snapshot returned by Metrics.
FieldTypeDescription
CPUPercentfloat64CPU usage as a percentage
MemoryBytesuint64Current memory usage in bytes
MemoryLimitBytesuint64Memory limit in bytes
DiskReadBytesuint64Total bytes read from disk since boot
DiskWriteBytesuint64Total bytes written to disk since boot
NetRxBytesuint64Total bytes received over the network since boot
NetTxBytesuint64Total bytes sent over the network since boot
Uptimetime.DurationTime since the sandbox was created

MetricsStreamHandle

Live metrics subscription returned by MetricsStream.
MethodReturnsDescription
Recv(ctx)(*Metrics, error)Block until the next snapshot arrives. Returns (nil, nil) when the stream ends
Close()errorStop the stream and release Rust-side resources