Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

40.9 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2024 BoxLite AI (originally Daytona Platforms Inc.
// Modified and rebranded for BoxLite

// Package boxlite provides a BoxLite-backed implementation of the box runtime,
// replacing Docker with VM-based isolation via the BoxLite Go SDK.
package boxlite

import (
	"context"
	"fmt"
	"io"
	"log/slog"
	"os"
	"os/exec"
	"os/user"
	"path/filepath"
	"slices"
	"strings"
	"sync"
	"time"

	boxlite "github.com/boxlite-ai/boxlite/sdks/go"
	"github.com/boxlite-ai/runner/pkg/api/dto"
	"github.com/boxlite-ai/runner/pkg/models"
	"github.com/boxlite-ai/runner/pkg/models/enums"
	"github.com/containerd/errdefs"
	"go.opentelemetry.io/otel/propagation"
)

// PulledImage is what a box's image reference resolved to on this runner: the
// registry's own digest and the size the manifest declared.
type PulledImage struct {
	Digest    string
	SizeBytes int64
}

// Client wraps the BoxLite Go SDK to provide the same interface as the Docker client.
// It manages VMs instead of containers, providing hardware-level isolation.
type Client struct {
	runtime    *boxlite.Runtime
	logger     *slog.Logger
	homeDir    string
	kernelPath string
	mu         sync.RWMutex
	boxes      map[string]*boxlite.Box
	// What each freshly created box's image resolved to, until it has been
	// reported once. Held in memory only: an entry lost to a runner restart is
	// simply gone, and the control plane re-resolves on the next create.
	pendingImageReports map[string]PulledImage
	awsRegion           string
	awsEndpointUrl      string
	awsAccessKeyId      string
	awsSecretAccessKey  string
	volumeBackend       string
	// testMountRunner and testProbeRunner are the test seams for the NFS mount path:
	// the concurrency test counts mount commands without a real server, and
	// the readiness probe reads a host binary (mountpoint) a dev machine may
	// not have. nil means the real exec runs — every production path lands
	// there because NewClient sets neither.
	testMountRunner func(*exec.Cmd) error
	testProbeRunner func(context.Context, string) (bool, error)
	// writeRecordSeam replaces the box volume mount record write when set —
	// the same posture as testMountRunner replacing the mount exec: a test uses
	// it to fail one specific record write without touching the filesystem.
	// nil means the real write runs — every production path lands there
	// because NewClient sets none of the seams.
	writeRecordSeam      func(ctx context.Context, boxID string, record boxVolumeMountRecord) error
	prepareRunner        func(dataDir string) error
	clearPublishedRunner func() error
	volumeMutexes        map[string]*sync.Mutex
	volumePending        map[string]int
	volumeMutexesMutex   sync.Mutex
	volumeCleanupMutex   sync.Mutex
	lastVolumeCleanup    time.Time
	volumeCleanup        volumeCleanupConfig

	nestedVirtualizationAllowed bool

	// afterGuestStateCheck runs right after DialGuestPort's persisted-state
	// check, before it fetches a handle. Tests use it to land a stop in that
	// window; nil in production.
	afterGuestStateCheck func(boxID string)
}

// ClientConfig holds configuration for the BoxLite client.
type ClientConfig struct {
	Logger                       *slog.Logger
	HomeDir                      string
	KernelPath                   string
	ExperimentalFeatures         string
	InsecureRegistries           []string
	RegistryProxy                RegistryProxy
	AWSRegion                    string
	AWSEndpointUrl               string
	AWSAccessKeyId               string
	AWSSecretAccessKey           string
	VolumeStorageBackend         string
	VolumeCleanupInterval        time.Duration
	VolumeCleanupDryRun          bool
	VolumeCleanupExclusionPeriod time.Duration
}

// errMissingOutboundPolicy rejects a create or recover request that carries no
// outbound policy. Guessing one would either open egress the caller meant to
// block or cut egress it meant to allow, and the box would start silently wrong.
var errMissingOutboundPolicy = errdefs.ErrInvalidArgument.WithMessage("outboundEnabled is required")

// networkSpec maps the create request's outbound policy onto the SDK spec.
func networkSpec(boxDto dto.CreateBoxDTO) (boxlite.NetworkSpec, error) {
	if boxDto.OutboundEnabled == nil {
		return boxlite.NetworkSpec{}, errMissingOutboundPolicy
	}
	policy := dto.OutboundNetworkPolicy{Mode: boxlite.NetworkModeEnabled, AllowNet: boxDto.OutboundAllowNet}
	if !*boxDto.OutboundEnabled {
		policy.Mode = boxlite.NetworkModeDisabled
	}
	if err := policy.Validate(); err != nil {
		return boxlite.NetworkSpec{}, err
	}
	return boxlite.NetworkSpec{Mode: policy.Mode, AllowNet: allowNetEntries(policy.AllowNet)}, nil
}

// allowNetEntries trims entries and drops blanks; nil when nothing is left.
func allowNetEntries(entries []string) []string {
	var allowNet []string
	for _, entry := range entries {
		if entry = strings.TrimSpace(entry); entry != "" {
			allowNet = append(allowNet, entry)
		}
	}
	return allowNet
}

func boxRuntimeEnv(ctx context.Context, boxDto dto.CreateBoxDTO) map[string]string {
	env := map[string]string{
		"BOXLITE_BOX_ID": boxDto.Id,
	}
	if boxDto.OtelEndpoint != nil && *boxDto.OtelEndpoint != "" {
		env["BOXLITE_OTEL_ENDPOINT"] = *boxDto.OtelEndpoint
	}
	if boxDto.OrganizationId != nil && *boxDto.OrganizationId != "" {
		env["BOXLITE_ORGANIZATION_ID"] = *boxDto.OrganizationId
	}
	if boxDto.RegionId != nil && *boxDto.RegionId != "" {
		env["BOXLITE_REGION_ID"] = *boxDto.RegionId
	}
	// Propagate the active W3C trace context into the box so in-box processes can
	// join the SAME traceId as the api->runner spans, instead of rooting a fresh
	// disjoint trace. With no active span the carrier is empty.
	carrier := propagation.MapCarrier{}
	propagation.TraceContext{}.Inject(ctx, carrier)
	if traceParent := carrier.Get("traceparent"); traceParent != "" {
		env["BOXLITE_TRACEPARENT"] = traceParent
		if traceState := carrier.Get("tracestate"); traceState != "" {
			env["BOXLITE_TRACESTATE"] = traceState
		}
	}
	return env
}

// secretSpecs maps control-plane SecretDTOs onto the boxlite SDK's Secret
// values. Extracted as a pure function so the mapping is unit-testable without
// a live runtime (see secret_options_test.go). The SDK applies the
// `<BOXLITE_SECRET:{name}>` placeholder default when Placeholder is empty, so an
// omitted placeholder is passed through as-is rather than synthesized here.
func secretSpecs(secrets []dto.SecretDTO) []boxlite.Secret {
	specs := make([]boxlite.Secret, 0, len(secrets))
	for _, secret := range secrets {
		specs = append(specs, boxlite.Secret{
			Name:        secret.Name,
			Value:       secret.Value,
			Hosts:       secret.Hosts,
			Placeholder: secret.Placeholder,
			Headers:     secret.Headers,
		})
	}
	return specs
}

// RegistryProxy is where the runner sends a pull for an image whose registry
// credentials only the platform holds, and the runner's own credential for it.
// The password is the runner's API key: the proxy authenticates a caller by
// asking the control plane whose key it is.
type RegistryProxy struct {
	Host     string
	Username string
	Password string
}

// complete reports whether all three were given, which is the only state in
// which the proxy is used at all.
//
// The host is judged after it is reduced to one, not as written: a value that
// reduces to nothing — a bare scheme, whitespace — is as unusable as one left
// out, and treating it as given would drop the proxy without a word.
func (p RegistryProxy) complete() bool {
	return registryHost(p.Host) != "" && p.Username != "" && p.Password != ""
}

// missing names the variables a partly configured proxy lacks or cannot use.
// Empty for a proxy that is complete or not configured at all.
func (p RegistryProxy) missing() []string {
	given := map[string]bool{
		"REGISTRY_PROXY_HOST":     registryHost(p.Host) != "",
		"REGISTRY_PROXY_USERNAME": p.Username != "",
		"REGISTRY_PROXY_PASSWORD": p.Password != "",
	}
	var absent []string
	for _, name := range []string{"REGISTRY_PROXY_HOST", "REGISTRY_PROXY_USERNAME", "REGISTRY_PROXY_PASSWORD"} {
		if !given[name] {
			absent = append(absent, name)
		}
	}
	if len(absent) == len(given) {
		return nil
	}
	return absent
}

// warnOnPartialRegistryProxy says so when a stage configured some of the proxy
// and not the rest. That is almost always an unfinished setting rather than an
// intent, and without a word it would look like the proxy being ignored.
func warnOnPartialRegistryProxy(logger *slog.Logger, proxy RegistryProxy) {
	if absent := proxy.missing(); len(absent) > 0 {
		logger.Warn("Registry proxy is partly configured and will not be used", "missing", strings.Join(absent, ", "))
	}
}

// buildImageRegistries assembles the runtime-scoped OCI registry list handed
// to boxlite-core: the insecure (HTTP) registries, and — when the registry
// proxy is fully configured — one entry for it. A registry's credential is
// never here.
//
// Core matches credentials by host, and this runtime pulls the operator's
// curated images and references tenants named from the same hosts. A
// credential here would be spent on any tenant reference to its host, so the
// runtime holds none: a public image pulls anonymously — which is why the
// curated images must be public — and a private one goes to the proxy. The
// proxy's entry is the exception that proves it: it carries the runner's own
// key, not a registry's, and only the API writes a ref under the proxy host,
// so no reference a tenant wrote reaches it.
// With no proxy configured this is byte-for-byte the anonymous list, so the
// proxy is safe to ship dark. Kept as a pure function so that is testable
// without constructing a real runtime.
//
// No host is named twice. The runtime matches a host to the first entry naming it and ignores
// the rest, for transport and credential alike, so a registry proxy that is also listed as
// insecure — the local stack's, served over plain HTTP — is one entry carrying both: HTTP from
// the insecure list, the credential from the proxy. Two entries would let the credential-less
// one win.
//
// The proxy is never searched. Search makes an unqualified reference like `alpine:3.20` try
// this host, and nothing about an image a caller names without a registry should route it here.
func buildImageRegistries(insecureRegistries []string, proxy RegistryProxy) []boxlite.ImageRegistry {
	proxyHost := ""
	if proxy.complete() {
		proxyHost = registryHost(proxy.Host)
	}

	registries := make([]boxlite.ImageRegistry, 0, len(insecureRegistries)+1)
	proxyIsInsecure := false
	for _, host := range insecureRegistries {
		if host == proxyHost {
			proxyIsInsecure = true
			continue
		}
		registries = append(registries, boxlite.ImageRegistry{
			Host:       host,
			Transport:  boxlite.RegistryTransportHTTP,
			SkipVerify: true,
		})
	}
	if proxyHost != "" {
		entry := boxlite.ImageRegistry{
			Host:      proxyHost,
			Transport: boxlite.RegistryTransportHTTPS,
			Search:    false,
			Auth: boxlite.ImageRegistryAuth{
				Username: proxy.Username,
				Password: proxy.Password,
			},
		}
		if proxyIsInsecure {
			entry.Transport = boxlite.RegistryTransportHTTP
			entry.SkipVerify = true
		}
		registries = append(registries, entry)
	}
	return registries
}

// resolveHomeDir picks the BoxLite home the way boxlite-core does when it is
// given none: the configured directory, then $BOXLITE_HOME, then .boxlite under
// the user's home — $HOME, or the passwd entry when $HOME is unset. The runner
// hands the result to core, so the runtime and everything here that reads the
// home (migration staging) agree on one directory. Two cases differ from core:
// an empty $BOXLITE_HOME counts as unset, and with neither $HOME nor a passwd
// entry this returns an error instead of falling back to ./.boxlite.
func resolveHomeDir(configured string) (string, error) {
	if configured != "" {
		return configured, nil
	}
	if home := os.Getenv("BOXLITE_HOME"); home != "" {
		return home, nil
	}
	userHome := os.Getenv("HOME")
	if userHome == "" {
		current, err := currentUser()
		if err != nil {
			return "", fmt.Errorf("cannot locate the BoxLite home directory; set BOXLITE_HOME_DIR: %w", err)
		}
		// A passwd entry without a home would turn into the relative path
		// ".boxlite", which core rejects with a less helpful error.
		if current.HomeDir == "" {
			return "", fmt.Errorf("cannot locate the BoxLite home directory; set BOXLITE_HOME_DIR: user %q has no home directory", current.Username)
		}
		userHome = current.HomeDir
	}
	return filepath.Join(userHome, ".boxlite"), nil
}

// currentUser is the passwd lookup behind the last fallback; tests replace it.
var currentUser = user.Current

// NewClient creates a new BoxLite client backed by the BoxLite VM runtime.
func NewClient(ctx context.Context, config ClientConfig) (*Client, error) {
	if config.KernelPath != "" {
		if !filepath.IsAbs(config.KernelPath) {
			return nil, fmt.Errorf("BOXLITE_KERNEL_PATH must be absolute")
		}
		info, err := os.Stat(config.KernelPath)
		if err != nil {
			return nil, fmt.Errorf("stat BOXLITE_KERNEL_PATH: %w", err)
		}
		if !info.Mode().IsRegular() {
			return nil, fmt.Errorf("BOXLITE_KERNEL_PATH must be a readable regular file")
		}
		file, err := os.Open(config.KernelPath)
		if err != nil {
			return nil, fmt.Errorf("open BOXLITE_KERNEL_PATH: %w", err)
		}
		file.Close()
	}
	homeDir, err := resolveHomeDir(config.HomeDir)
	if err != nil {
		return nil, err
	}
	var features []string
	if raw := strings.TrimSpace(config.ExperimentalFeatures); raw != "" {
		features = strings.Split(raw, ",")
		for i := range features {
			features[i] = strings.TrimSpace(features[i])
		}
	}
	if config.KernelPath != "" && !slices.Contains(features, "custom-kernel") {
		features = append(features, "custom-kernel")
	}
	opts := []boxlite.RuntimeOption{boxlite.WithHomeDir(homeDir), boxlite.WithExperimentalFeatures(features...)}
	logger := config.Logger
	if logger == nil {
		logger = slog.Default()
	}
	warnOnPartialRegistryProxy(logger, config.RegistryProxy)

	insecureRegistries := normalizeRegistryHosts(config.InsecureRegistries)
	registries := buildImageRegistries(insecureRegistries, config.RegistryProxy)
	if len(registries) > 0 {
		opts = append(opts, boxlite.WithImageRegistries(registries...))
	}

	rt, err := boxlite.NewRuntime(opts...)
	if err != nil {
		return nil, fmt.Errorf("failed to create boxlite runtime: %w", err)
	}

	return &Client{
		nestedVirtualizationAllowed: slices.Contains(features, "nested-virtualization"),

		runtime:             rt,
		logger:              logger,
		homeDir:             homeDir,
		kernelPath:          config.KernelPath,
		boxes:               make(map[string]*boxlite.Box),
		pendingImageReports: make(map[string]PulledImage),
		awsRegion:           config.AWSRegion,
		awsEndpointUrl:      config.AWSEndpointUrl,
		awsAccessKeyId:      config.AWSAccessKeyId,
		awsSecretAccessKey:  config.AWSSecretAccessKey,
		volumeBackend:       config.VolumeStorageBackend,
		volumeMutexes:       make(map[string]*sync.Mutex),
		volumeCleanup: volumeCleanupConfig{
			interval:        config.VolumeCleanupInterval,
			dryRun:          config.VolumeCleanupDryRun,
			exclusionPeriod: config.VolumeCleanupExclusionPeriod,
		},
	}, nil
}

// PendingImageReport returns what a box's image resolved to, when this runner
// created that box and has not yet reported it.
func (c *Client) PendingImageReport(boxId string) (PulledImage, bool) {
	c.mu.RLock()
	defer c.mu.RUnlock()
	pulled, ok := c.pendingImageReports[boxId]
	return pulled, ok
}

// ClearPendingImageReport drops a report that has been delivered. Separate from
// reading it so a report the control plane refused is retried rather than lost.
func (c *Client) ClearPendingImageReport(boxId string) {
	c.mu.Lock()
	defer c.mu.Unlock()
	delete(c.pendingImageReports, boxId)
}

// HomeDir is the directory the runtime keeps boxes, images and its database in.
func (c *Client) HomeDir() string {
	return c.homeDir
}

// Shutdown gracefully stops all running boxes in the underlying BoxLite
// runtime. Blocks until shutdown completes or `timeout` elapses. Call this
// BEFORE Close so VMs aren't killed mid-write on systemd SIGTERM.
//
// Without this, restart attempts for the killed boxes hit a 30s
// `guest_connect` timeout because the guest agent inside never re-establishes
// vsock after an unclean shutdown — and (until the matching Rust-side fix
// landed) that timeout would auto-delete the box record.
//
// `timeout=0` means "use the runtime default (10s)". Negative values are
// clamped by the SDK.
func (c *Client) Shutdown(ctx context.Context, timeout time.Duration) error {
	return c.runtime.Shutdown(ctx, timeout)
}

// Close releases the BoxLite runtime handle. Prefer calling `Shutdown` first
// so boxes get a graceful stop before the C handle is freed.
func (c *Client) Close() error {
	c.mu.Lock()
	boxes := make([]*boxlite.Box, 0, len(c.boxes))
	for id, bx := range c.boxes {
		boxes = append(boxes, bx)
		delete(c.boxes, id)
	}
	c.mu.Unlock()

	// Close outside the cache lock: each Close waits for in-flight native
	// calls on its box, and one box's drain must not block the others.
	for _, bx := range boxes {
		bx.Close()
	}
	return c.runtime.Close()
}

// NestedVirtualizationEnabled combines startup ENV authorization and current host support.
func (c *Client) NestedVirtualizationEnabled() bool {
	return c.nestedVirtualizationAllowed && nestedVirtualizationAvailable()
}

// Create creates a new box (VM) from the given image and configuration.
// Returns the box ID and runtime version.
func (c *Client) Create(ctx context.Context, boxDto dto.CreateBoxDTO) (string, string, error) {
	cpus, err := dto.CPUAllocation(boxDto.CpuQuota)
	if err != nil {
		return "", "", errdefs.ErrInvalidArgument.WithMessage(err.Error())
	}
	memoryMiB, err := dto.MemoryMiB(boxDto.MemoryQuota)
	if err != nil {
		return "", "", errdefs.ErrInvalidArgument.WithMessage(err.Error())
	}
	// Before any side effect: a request without a policy must not leave
	// volume mounts or a box behind.
	network, err := networkSpec(boxDto)
	if err != nil {
		return "", "", err
	}
	if err := validateRecreatableSecrets(boxDto.Secrets); err != nil {
		return "", "", err
	}

	// Also before any side effect: the box id becomes part of filesystem
	// paths — volume mount records ({id}.json) and the runtime's own box
	// name. The control plane mints ids from
	// [0-9A-Za-z]{12}, which cannot carry separators or '..', but this
	// boundary must not lean on that: a traversal-shaped id is rejected
	// before any mount or record work runs. The literal Contains checks stay
	// inline so static analysis sees the validation on every path.
	if strings.ContainsAny(boxDto.Id, "/\\") || strings.Contains(boxDto.Id, "..") {
		return "", "", fmt.Errorf("invalid box id %q: must not contain path separators or '..'", boxDto.Id)
	}

	operation, err := c.checkpointOperations().Lock(ctx, boxDto.Id)
	if err != nil {
		return "", "", err
	}
	defer operation.Close()
	if err := operation.CheckIdle(); err != nil {
		return "", "", err
	}
	candidate, err := operation.UnpublishedCandidate()
	if err != nil {
		return "", "", err
	}
	if candidate != "" {
		if err := c.runtime.ForceRemove(ctx, candidate); err != nil && !boxlite.IsNotFound(err) {
			return "", "", err
		}
	}
	if err := operation.Invalidate(); err != nil {
		return "", "", err
	}

	opts := []boxlite.BoxOption{
		boxlite.WithName(boxDto.Id),
		boxlite.WithCPUs(cpus),
		boxlite.WithMemory(memoryMiB),
		boxlite.WithAutoRemove(false),
		boxlite.WithDetach(true),
	}
	if boxDto.StorageQuota > 0 {
		opts = append(opts, boxlite.WithDiskSize(int(boxDto.StorageQuota)))
	}

	for k, v := range boxDto.Env {
		opts = append(opts, boxlite.WithEnv(k, v))
	}
	for k, v := range boxRuntimeEnv(ctx, boxDto) {
		opts = append(opts, boxlite.WithEnv(k, v))
	}
	for _, secret := range secretSpecs(boxDto.Secrets) {
		opts = append(opts, boxlite.WithSecret(secret))
	}

	if len(boxDto.Entrypoint) > 0 {
		opts = append(opts, boxlite.WithEntrypoint(boxDto.Entrypoint...))
	}

	if len(boxDto.Cmd) > 0 {
		opts = append(opts, boxlite.WithCmd(boxDto.Cmd...))
	}

	if boxDto.WorkingDir != "" {
		opts = append(opts, boxlite.WithWorkDir(boxDto.WorkingDir))
	}

	// Only when the caller asked. 16d9248bb removed the unconditional
	// WithUser(OsUser) because the default landed a USER override on images
	// that never defined that account; an explicit RunAsUser is the caller's
	// own choice and their image's problem if it is wrong.
	if boxDto.RunAsUser != "" {
		opts = append(opts, boxlite.WithUser(boxDto.RunAsUser))
	}

	nested := boxDto.NestedVirtualization && c.NestedVirtualizationEnabled()
	if nested {
		// Replay must adopt the saved choice rather than request an upgrade.
		if _, lookupErr := c.runtime.GetInfo(ctx, boxDto.Id); lookupErr == nil {
			nested = false
		} else if !boxlite.IsNotFound(lookupErr) {
			return "", "", lookupErr
		}
	}
	if nested || boxDto.Privileged || c.kernelPath != "" {
		advanced, advancedErr := boxlite.NewAdvancedBoxOptions()
		if advancedErr != nil {
			return "", "", advancedErr
		}
		defer advanced.Close()
		if advancedErr = advanced.SetNestedVirtualization(nested); advancedErr != nil {
			return "", "", advancedErr
		}
		if advancedErr = advanced.SetPrivileged(boxDto.Privileged); advancedErr != nil {
			return "", "", advancedErr
		}
		if c.kernelPath != "" {
			if advancedErr = advanced.SetKernelPath(c.kernelPath); advancedErr != nil {
				return "", "", advancedErr
			}
		}
		opts = append(opts, boxlite.WithAdvancedOptions(advanced))
	}

	var priorVolumeRecord *boxVolumeMountRecord
	if hasFilestoreRef(boxDto.Volumes) {
		priorVolumeRecord, err = c.readBoxVolumeMountRecord(boxDto.Id)
		if err != nil {
			return "", "", fmt.Errorf("failed to read existing volume mount record: %w", err)
		}
	}

	volumeMounts, err := c.getVolumeMounts(ctx, boxDto.Id, boxDto.Volumes)
	if err != nil {
		// A filestore volume earlier in the list may already have written its
		// record entry inside the instance critical section. The failed create
		// must not leave it behind: no box ever exists to destroy, so the
		// dangling entry would count a reference forever and keep the NFS
		// mount from reclaiming.
		if hasFilestoreRef(boxDto.Volumes) {
			c.rollbackVolumeMountRecord(ctx, boxDto.Id, boxDto.Volumes, priorVolumeRecord)
		}
		return "", "", err
	}
	for _, vol := range volumeMounts {
		// The bucket is already FUSE-mounted on this host, so the runner is a
		// host-bind consumer even though the box is mounting a managed volume.
		opts = append(opts, boxlite.WithBindMount(vol.hostPath, vol.mountPath))
	}

	if len(volumeMounts) > 0 {
		if err := c.recordBoxVolumeMounts(ctx, boxDto.Id, volumeMounts); err != nil {
			// The final write failed after earlier volumes already published
			// their entries in-lock. Same rule as the getVolumeMounts path:
			// no box will exist to destroy, so the dangling entries must not
			// survive.
			if hasFilestoreRef(boxDto.Volumes) {
				c.rollbackVolumeMountRecord(ctx, boxDto.Id, boxDto.Volumes, priorVolumeRecord)
			}
			return "", "", err
		}
	}

	opts = append(opts, boxlite.WithNetwork(network))
	if err := ctx.Err(); err != nil {
		if len(volumeMounts) > 0 {
			cleanupCtx, cancel := cleanupContext(ctx)
			defer cancel()
			c.rollbackVolumeMountRecord(cleanupCtx, boxDto.Id, boxDto.Volumes, priorVolumeRecord)
		}
		return "", "", err
	}
	// Native creation cannot be cancelled after admission. Keep the target
	// lease until it finishes; preparation above still obeys caller cancellation.
	ctx = context.WithoutCancel(ctx)

	// GetOrCreate (not Create) so a CREATE_BOX replay is idempotent. The local
	// box name is boxDto.Id — the control plane's globally-unique box id — so if
	// the box was already persisted by a prior CREATE_BOX for the SAME box (e.g.
	// the host rebooted before the job was marked COMPLETED and the poller is
	// replaying the still-IN_PROGRESS job), the core adopts it instead of
	// failing with "already exists", which the API would surface as a 400.
	// The created flag (new vs adopted) is irrelevant here: either way the box
	// now exists locally and the job can proceed, so it is discarded.
	id, err := c.nativeBoxID(boxDto.Id)
	if err != nil {
		if len(volumeMounts) > 0 && hasFilestoreRef(boxDto.Volumes) {
			c.rollbackVolumeMountRecord(ctx, boxDto.Id, boxDto.Volumes, priorVolumeRecord)
		}
		return "", "", err
	}
	var bx *boxlite.Box
	if boxDto.RequireExisting || id != boxDto.Id {
		bx, err = c.runtime.Get(ctx, id)
	}
	// The target lease excludes HTTP destruction until adoption/start finishes.
	// Never recreate a replay target whose single-use credential was skipped.
	if boxDto.RequireExisting && bx == nil {
		if len(volumeMounts) > 0 && boxlite.IsNotFound(err) {
			// Absence is confirmed. Drop this box's record and rescan
			// shared Filestore references under the instance lock.
			c.rollbackVolumeMountRecord(ctx, boxDto.Id, boxDto.Volumes, nil)
		}
		return "", "", fmt.Errorf("existing box unavailable: %w", err)
	}
	if bx == nil && (err == nil || boxlite.IsNotFound(err)) {
		clearPublished := operation.ClearPublished
		if c.clearPublishedRunner != nil {
			clearPublished = c.clearPublishedRunner
		}
		if err := clearPublished(); err != nil {
			if len(volumeMounts) > 0 && hasFilestoreRef(boxDto.Volumes) {
				c.rollbackVolumeMountRecord(ctx, boxDto.Id, boxDto.Volumes, priorVolumeRecord)
			}
			return "", "", err
		}
		bx, _, err = c.runtime.GetOrCreate(ctx, boxDto.Image, opts...)
	}
	if err != nil {
		if len(volumeMounts) > 0 {
			c.rollbackVolumeMountRecord(ctx, boxDto.Id, boxDto.Volumes, priorVolumeRecord)
		}
		return "", "", fmt.Errorf("failed to create box: %w", err)
	}

	c.mu.Lock()
	c.boxes[boxDto.Id] = bx
	c.mu.Unlock()

	c.logger.Info(
		"created box",
		"id",
		bx.ID(),
		"boxId",
		boxDto.Id,
		"name",
		bx.Name(),
		"image",
		boxDto.Image,
	)

	// bx.Start must stay the last step of Create that can fail.
	//
	// A successful Start publishes StartedAt when BoxLite moves the box to Running,
	// and BoxSync reads it as evidence this job body succeeded — it is what
	// lets a lost job-completion callback be repaired later. A fallible step
	// added below would publish that evidence for a Create that then returns
	// an error, and the two would disagree with no way to tell which is right.
	// TestCreateHasNoFallibleStepAfterStart enforces this.
	skipStart := boxDto.SkipStart != nil && *boxDto.SkipStart
	if !skipStart {
		if err := bx.Start(ctx); err != nil {
			return bx.ID(), "", fmt.Errorf("failed to start box: %w", err)
		}
		c.recordPulledImage(ctx, boxDto.Id, bx)
	}

	return bx.ID(), "boxlite", nil
}

// boxInfoReader is the one thing recordPulledImage needs from a box. A
// *boxlite.Box satisfies it; a test stubs it, since a real box's Info crosses
// the FFI.
type boxInfoReader interface {
	Info(ctx context.Context) (*boxlite.BoxInfo, error)
}

// recordPulledImage notes what a box's image reference resolved to, so the
// control plane can be told once.
//
// Only a started box has an answer: GetOrCreate allocates a handle and
// persists the box, and the image is not pulled until the first start
// (rt_impl.rs — "The VM is not started until start() or exec() is called").
// Asking any earlier reads an answer that does not exist yet. It never fails
// its caller, so it can sit after Start without breaking the rule that Start
// is Create's last fallible step: info that cannot be read is logged and the
// report dropped, which costs one re-resolution on the next create.
func (c *Client) recordPulledImage(ctx context.Context, boxId string, bx boxInfoReader) {
	// Not cancelled with the request: the box has started either way, and a
	// report dropped for that reason is one the control plane pays for later.
	info, err := bx.Info(context.WithoutCancel(ctx))
	if err != nil {
		c.logger.WarnContext(ctx, "cannot read what the box's image resolved to; dropping the report",
			"box", boxId, "error", err)
		return
	}
	if info.ResolvedImage == nil {
		return
	}
	c.mu.Lock()
	defer c.mu.Unlock()
	c.pendingImageReports[boxId] = PulledImage{
		Digest:    info.ResolvedImage.ManifestDigest,
		SizeBytes: info.ResolvedImage.TotalLayerSize,
	}
}

// Start starts a stopped box and returns the runtime version.
func (c *Client) Start(ctx context.Context, boxId string, authToken *string, metadata map[string]string) (string, error) {
	// Same boundary check as Create: Start replays the volume mount record
	// write from metadata and looks the box up by name, so a
	// traversal-shaped id is rejected before any of that runs.
	if strings.ContainsAny(boxId, "/\\") || strings.Contains(boxId, "..") {
		return "", fmt.Errorf("invalid box id %q: must not contain path separators or '..'", boxId)
	}

	operation, err := c.lockCheckpointTarget(ctx, boxId)
	if err != nil {
		return "", err
	}
	defer operation.Close()
	ctx = context.WithoutCancel(ctx)
	if err := c.ensureVolumeMountsFromMetadata(ctx, boxId, metadata); err != nil {
		if isFilestoreVolumePreparationError(err) {
			return "", err
		}
		c.logger.ErrorContext(ctx, "failed to ensure volume mounts", "box", boxId, "error", err)
	}

	bx, err := c.getOrFetchBox(ctx, boxId)
	if err != nil {
		return "", err
	}
	if err := bx.Start(ctx); err != nil {
		return "", err
	}
	// The other place a box is first started: one created with SkipStart has
	// pulled nothing until now.
	c.recordPulledImage(ctx, boxId, bx)
	return "boxlite", nil
}

// Stop stops a running box.
func (c *Client) Stop(ctx context.Context, boxId string, force bool) error {
	operation, err := c.lockCheckpointTarget(ctx, boxId)
	if err != nil {
		return err
	}
	defer operation.Close()
	ctx = context.WithoutCancel(ctx)
	bx, err := c.getOrFetchBox(ctx, boxId)
	if err != nil {
		return err
	}
	err = bx.Stop(ctx)

	// The stopped box's handle is spent either way, so drop it from the cache.
	c.evictBox(boxId, bx)

	return err
}

// Destroy removes a box entirely.
func (c *Client) Destroy(ctx context.Context, boxId string) error {
	// Same boundary check as Create/Start: the runtime removal and the
	// volume mount record paths below all key off boxId, so a
	// traversal-shaped id is rejected before any of them runs.
	if strings.ContainsAny(boxId, "/\\") || strings.Contains(boxId, "..") {
		return fmt.Errorf("invalid box id %q: must not contain path separators or '..'", boxId)
	}

	operation, err := c.checkpointOperations().Lock(ctx, boxId)
	if err != nil {
		return err
	}
	defer operation.Close()
	if err := operation.Invalidate(); err != nil {
		return err
	}
	ctx = context.WithoutCancel(ctx)
	c.forgetBox(boxId)

	ids, err := operation.NativeTargets()
	if err != nil {
		return err
	}
	for _, id := range ids {
		if err := c.runtime.ForceRemove(ctx, id); err != nil && !boxlite.IsNotFound(err) {
			return err
		}
	}

	// The record deletion takes each referenced instance's mutex so it cannot
	// interleave with an in-flight reclaim decision for those instances
	// (design §4.5.3); the orphan cleanup that follows reclaims their mounts.
	instances, readErr := c.readFilestoreInstancesFromRecord(boxId)
	if readErr != nil {
		c.logger.WarnContext(ctx, "failed to read box volume mount record", "box", boxId, "error", readErr)
	}
	if cleanupErr := c.removeBoxVolumeMountRecordLocked(ctx, boxId, instances); cleanupErr != nil {
		c.logger.WarnContext(ctx, "failed to remove box volume mount record", "box", boxId, "error", cleanupErr)
	}
	c.CleanupOrphanedVolumeMounts(ctx)

	return nil
}

// ToBoxState maps a box's local lifecycle state onto the control plane's
// vocabulary, one arm per state the runtime can report. Unknown is not a
// neutral default: the API counts it as compute-consuming while Error is not,
// so Failed must map explicitly to Error.
//
// Exported apart from GetBoxInfo because a caller that already holds a
// BoxInfo must not fetch a second one: BoxSync pairs the state with the box's
// StartedAt, and reading the two at different moments is what lets a stale
// timestamp meet a fresh state.
func ToBoxState(state boxlite.State) enums.BoxState {
	switch state {
	case boxlite.StateRunning:
		return enums.BoxStateStarted
	case boxlite.StatePaused:
		// vCPUs frozen for a snapshot's point-in-time consistency. The VM is up,
		// so the control plane should keep seeing the box as started.
		return enums.BoxStateStarted
	case boxlite.StateStopping:
		return enums.BoxStateStopping
	case boxlite.StateStopped:
		return enums.BoxStateStopped
	case boxlite.StateConfigured:
		// Persisted but never booted. The control plane has no "configured" of
		// its own, so this stays folded into Creating.
		return enums.BoxStateCreating
	case boxlite.StateFailed:
		return enums.BoxStateError
	default:
		return enums.BoxStateUnknown
	}
}

// BoxExists distinguishes absence from runtime lookup failures without fetching
// a bootable handle. GetBoxInfo intentionally maps absence to an unknown state.
func (c *Client) BoxExists(ctx context.Context, boxId string) (bool, error) {
	_, err := c.nativeBoxInfo(ctx, boxId)
	if boxlite.IsNotFound(err) {
		return false, nil
	}
	return err == nil, err
}

// GetBoxInfo returns a box's current state together with the main command's
// exit code, when the runtime recorded one.
//
// Both come from a single GetInfo snapshot on purpose. Read apart, a state
// from one moment could meet an exit code from another, and the pair would
// describe two different lifecycles — the same trap ToBoxState's comment
// describes for StartedAt.
//
// It reads through the runtime rather than the handle cache: a state read
// needs no bootable handle, only the persisted record. Routing it through
// getOrFetchBox would evict, close and re-fetch a handle for every
// non-running box, paying a full handle round-trip per read.
func (c *Client) GetBoxInfo(ctx context.Context, boxId string) (models.BoxInfo, error) {
	info, err := c.nativeBoxInfo(ctx, boxId)
	if err != nil {
		if boxlite.IsNotFound(err) {
			return models.BoxInfo{BoxState: enums.BoxStateUnknown}, nil
		}
		return models.BoxInfo{BoxState: enums.BoxStateUnknown}, err
	}

	return models.BoxInfo{
		BoxState: ToBoxState(info.State),
		ExitCode: info.ExitCode,
	}, nil
}

// StartExecution starts an interactive execution in a box.
func (c *Client) StartExecution(ctx context.Context, boxId string, command string, args []string, stdout, stderr io.Writer, tty bool) (*boxlite.Execution, error) {
	bx, err := c.getOrFetchBox(ctx, boxId)
	if err != nil {
		return nil, err
	}
	return bx.StartExecution(ctx, command, args, &boxlite.ExecutionOptions{
		TTY:    tty,
		Stdout: stdout,
		Stderr: stderr,
	})
}

// Exec executes a command in a running box and returns the result.
func (c *Client) Exec(ctx context.Context, boxId string, command string, args ...string) (*ExecResult, error) {
	bx, err := c.getOrFetchBox(ctx, boxId)
	if err != nil {
		return nil, err
	}

	result, err := bx.Exec(ctx, command, args...)
	if err != nil {
		return nil, err
	}

	return &ExecResult{
		StdOut:   result.Stdout,
		StdErr:   result.Stderr,
		ExitCode: result.ExitCode,
	}, nil
}

// CopyInto copies a file from host into a box.
func (c *Client) CopyInto(ctx context.Context, boxId string, hostSrc, guestDst string) error {
	bx, err := c.getOrFetchBox(ctx, boxId)
	if err != nil {
		return err
	}
	return bx.CopyInto(ctx, hostSrc, guestDst)
}

// CopyOut copies a file from a box to the host.
func (c *Client) CopyOut(ctx context.Context, boxId string, guestSrc, hostDst string) error {
	bx, err := c.getOrFetchBox(ctx, boxId)
	if err != nil {
		return err
	}
	return bx.CopyOut(ctx, guestSrc, hostDst)
}

// CopyInStream streams raw tar bytes from r into guestDst without staging.
func (c *Client) CopyInStream(ctx context.Context, boxId, guestDst string, r io.Reader, options ...boxlite.CopyInOption) error {
	bx, err := c.getOrFetchBox(ctx, boxId)
	if err != nil {
		return err
	}
	return bx.CopyInStream(ctx, guestDst, r, options...)
}

// CopyOutStream streams a tar of guestSrc to w without staging.
func (c *Client) CopyOutStream(ctx context.Context, boxId, guestSrc string, w io.Writer) error {
	bx, err := c.getOrFetchBox(ctx, boxId)
	if err != nil {
		return err
	}
	return bx.CopyOutStream(ctx, guestSrc, w)
}

// ListImages returns all locally cached images.
func (c *Client) ListImages(ctx context.Context) ([]boxlite.ImageInfo, error) {
	images, err := c.runtime.Images()
	if err != nil {
		return nil, err
	}
	defer images.Close()
	return images.List(ctx)
}

// Ping checks if the BoxLite runtime is healthy.
func (c *Client) Ping(ctx context.Context) error {
	_, err := c.runtime.Metrics(ctx)
	return err
}

// Metrics returns runtime-level metrics.
func (c *Client) Metrics(ctx context.Context) (*boxlite.RuntimeMetrics, error) {
	return c.runtime.Metrics(ctx)
}

// BoxMetrics returns metrics for a specific box.
func (c *Client) BoxMetrics(ctx context.Context, boxId string) (*boxlite.BoxMetrics, error) {
	bx, err := c.getOrFetchBox(ctx, boxId)
	if err != nil {
		return nil, err
	}
	return bx.Metrics(ctx)
}

// ListInfo returns info for all boxes managed by this runtime.
func (c *Client) ListInfo(ctx context.Context) ([]boxlite.BoxInfo, error) {
	return c.listPublicBoxes(ctx)
}

// TakeSSHUsage borrows its own native handle, so telemetry cannot evict or
// close a business operation's cached handle. This read never boots the box.
func (c *Client) TakeSSHUsage(ctx context.Context, nativeID string) (*boxlite.SSHUsageBatch, error) {
	box, err := c.runtime.Get(ctx, nativeID)
	if err != nil {
		return nil, err
	}
	defer box.Close()
	return box.SSH().RunnerTakeUsage(ctx)
}

// GetBox retrieves a box handle from cache or fetches it from the runtime.
func (c *Client) GetBox(ctx context.Context, boxId string) (*boxlite.Box, error) {
	return c.getOrFetchBox(ctx, boxId)
}

// getOrFetchBox retrieves a box handle from cache or fetches it from the runtime.
//
// A cached handle is only good while its box is up. A box can stop *itself* —
// its main command exits and the guest powers the VM off — and such a handle is
// spent: it holds the dead VM and can never boot another. Stop evicts its own
// handle, but nothing was clearing this entry on a self-stop, so every later
// Start, exec, copy or metrics call on that box was answered with the corpse,
// forever. The core invalidates its own cache from the exit watcher; this one
// is ours.
//
// So a box that is no longer running gets a fresh handle, which *can* boot it.
// That is the auto-restart the control plane depends on: its reaper stops idle
// boxes and the next call is expected to bring them back.
func (c *Client) getOrFetchBox(ctx context.Context, boxId string) (*boxlite.Box, error) {
	c.mu.RLock()
	cached, ok := c.boxes[boxId]
	c.mu.RUnlock()

	if ok {
		// Info reads persisted state — it never boots the box, so it is safe to
		// ask a spent handle.
		info, err := cached.Info(ctx)
		if err != nil {
			return nil, err
		}
		// Paused counts as up: the VM is frozen for a snapshot's point-in-time
		// consistency, not stopped, and its handle still drives a live machine.
		// The Rust sibling gates on the same pair via BoxStatus::is_active.
		if info.State == boxlite.StateRunning || info.State == boxlite.StatePaused {
			return cached, nil
		}
		c.evictBox(boxId, cached)
	}

	id, err := c.nativeBoxID(boxId)
	if err != nil {
		return nil, err
	}
	bx, err := c.runtime.Get(ctx, id)
	if err != nil {
		return nil, fmt.Errorf("box %s not found: %w", boxId, err)
	}

	c.mu.Lock()
	c.boxes[boxId] = bx
	c.mu.Unlock()

	return bx, nil
}

// forgetBox drops everything this client still holds for a box that is being
// destroyed: the cached handle, and any image report the box never got to
// deliver. The report has to go with it — the control plane records an image
// only on the push that says the box started, so one still owed for a box that
// no longer exists can never be delivered, and left behind it would accumulate
// one entry per box this runner ever destroyed.
// forgetBox drops everything this client still holds for a box that is being
// destroyed: the cached handle, and any image report the box never got to
// deliver. The report has to go with it — the control plane records an image
// only on the push that says the box started, so one still owed for a box that
// no longer exists can never be delivered, and left behind it would accumulate
// one entry per box this runner ever destroyed.
//
// The close runs outside the cache lock: it waits for in-flight native calls
// on that one box, and no other box's lookup should queue behind the wait.
func (c *Client) forgetBox(boxId string) {
	c.mu.Lock()
	bx := c.boxes[boxId]
	delete(c.boxes, boxId)
	delete(c.pendingImageReports, boxId)
	c.mu.Unlock()

	if bx != nil {
		bx.Close()
	}
}

// evictBox unmaps a handle so the next lookup fetches a fresh one, and only
// while it is still the cached one — a concurrent Create or fetch may already
// have replaced it, and unmapping the winner would drop a live entry.
//
// It deliberately does not Close the handle: an evicted handle may still be
// referenced by callers that have not finished their requests, and closing it
// here would turn those calls into ErrInvalidState. That ownership hand-off
// is its own change, tracked in Linear BUI-1747 — until it lands, the
// unmapped handle is leaked for the process lifetime, bounded by the request
// volume that finds its box down.
func (c *Client) evictBox(boxId string, stale *boxlite.Box) {
	c.mu.Lock()
	defer c.mu.Unlock()

	if current, ok := c.boxes[boxId]; ok && current == stale {
		delete(c.boxes, boxId)
	}
}

// ExecResult holds the output of a command execution.
type ExecResult struct {
	StdOut   string
	StdErr   string
	ExitCode int
}