Skip to documentation
API + guides

01Documentation

Sandbox

A sandbox gives a user's AI agent an isolated cloud computer where it can run code, install software, manage files, and control network access. Preserve the whole writable root filesystem across successful checkpoints, pause compute between tasks, and resume the same sandbox when work returns. System configuration, installed tools, dependencies, and user files share the same durable RootFS, including paths outside the project directory.

Each sandbox is created from a Template. On growth-enabled templates, the RootFS expands automatically online as it fills, within the configured device ceiling, while the agent keeps running. Existing images and snapshots retain their captured geometry. Incremental checkpoints and demand reads avoid copying the entire growing filesystem during pause/resume. See Template Configuration for growth configuration and runtime-only mounts excluded from RootFS persistence.

On Sandbox0 Cloud, paused sandboxes incur no compute charges. Default pause/resume preserves files and starts fresh processes. Configure auto_resume for supported access paths, or resume explicitly; wake-up takes time and requires available capacity. See Pause And Resume.

Retained storage is billed separately from compute. Shared base images and platform recovery retention are excluded. Billing counts effective changed RootFS blocks and retained memory checkpoint data, with shared Snapshot and Fork references counted once within a team. Pausing stops compute charges; retained data continues to accrue storage charges. See Cloud pricing.

For shell access and file copy over standard SSH clients, see SSH.

ℹ

Sandbox0 Cloud clients should use https://api.sandbox0.ai. The SDKs and CLI use this endpoint by default. See Deployment Options for service availability.

Built with Sandbox0#

Cloud Browser is a cloud browser built on the Sandbox0 chrome template. See the Chrome Shared Desktop guide to build your own browser workflow.

Sandbox Model#

Key Identifiers#

FieldDescription
idUnique sandbox identifier (e.g., sb_abc123)
template_idTemplate used to create this sandbox
team_idTeam that owns this sandbox
runtime_idOpaque identifier of the current physical runtime allocation. Empty while paused.
runtime_generationMonotonically increasing logical runtime generation. Resume and successful system migration commit a new generation.
cluster_idCluster where sandbox runs in multi-cluster deployments. Optional on claim and list responses; absent from sandbox detail responses.

Lifecycle States#

StatusDescription
startingSandbox is being initialized
runningA runtime is committed as active; query health for current execution and terminal availability
pausedSandbox has no runtime; identity and latest rootfs checkpoint are preserved
terminatingSandbox identity and durable state are being deleted
failedSandbox encountered an error
ℹ

PostgreSQL stores durable lifecycle intent, the committed runtime generation, the exact Nomad allocation, and its resource/RootFS writer leases. running is published only after ctld and the task driver prove network, RootFS, runsc, and procd command readiness for that generation. During recovery, status returns to starting until a replacement generation commits.

ℹ

Pause and resume use internal lifecycle transactions, but pausing and resuming are not caller-visible statuses. Inspect both status and paused: a physically resolved memory checkpoint failure can report status: "failed" with paused: true, preserving the RootFS for explicit recovery. That state does not prove a successful memory pause or restore. Default filesystem-only pause does not preserve running processes, memory, sockets, PID state, or live REPL sessions. Experimental memory pause/resume requires an explicit memory: true request.

Independent health observations (unreleased)#

GET /api/v1/sandboxes/{id}/rootfs/identity reads durable storage provenance and runtime coordinates from one regional database snapshot without contacting or resuming the guest. Its optional runtime_compatibility_digest identifies the immutable scheduling class of the current active slot, with a matching external launch proof, unexpired node heartbeat and active resource lease. The field is omitted during a lifecycle transition or when this evidence is unavailable; independent storage provenance remains readable. It binds admitted runtime version/configuration, not binary contents, Sentry liveness or credential safety. Later mutations still require their own exact runtime-generation condition.

GET /api/v1/sandboxes/{id}/health requires sandbox:read and returns separate observations for runtime launch authority and current liveness, execution, terminal, storage identity, writer authority, and storage I/O. Each check carries state (available, unavailable, or unknown), a fixed reason, evidence source, and its original observed_at (null when unobserved).

A running instance can have unavailable execution or terminals. Guest diagnostics are workload-controlled and advisory. A present RootFS identity and a valid writer lease do not establish current storage I/O; the I/O check currently reports unknown/storage_io_unobserved. No aggregate “healthy” flag hides these differences.

The manager combines regional records with bounded node and guest observations, then checks the runtime identity again before returning them. The query may run short fixed shell and PTY probes, but never resumes or restarts a sandbox and skips guest probes during pause or an active lifecycle transition. Guest failure is returned as diagnostic evidence; failure to read regional authority returns 503. Responses are not cached by HTTP intermediaries. Cached guest observations retain their original timestamp.

Use s0 sandbox health <id> -o json, Go GetSandboxHealth, JavaScript client.sandboxes.getHealth, or Python client.sandboxes.get_health with matching SDK/server versions. These additions are not yet deployed by this change.

System Maintenance Migration#

Experimental system migration can move an eligible running sandbox to another compatible node during planned maintenance. The system selects the destination; there is no user migration API, SDK option, CLI command, or template setting. When enabled by the operator, the same mechanism can consolidate lightly loaded elastic workers onto a compatible fixed worker before a safe scale-in. A worker is removed only after its sandbox leases and runtime slots have been cleared.

A successful migration keeps the sandbox ID and preserves supported process state, memory, guest PIDs, open files, and runtime tmpfs data. The physical runtime_id changes and runtime_generation advances. Execution pauses during the move, and requests or existing connections may fail temporarily. Existing SSH, streaming, and external TCP connections are not guaranteed to survive. A failed restore is never reported as a successful migration by restarting the entrypoint. Recovery after an unrecoverable failure follows the existing filesystem checkpoint policy; it cannot reconstruct lost volatile memory.

This capability is still undergoing failure and capacity validation. It does not change user pause/resume semantics or recover live memory from a dead host.

Persistent Root Filesystem#

Sandbox0 persists the sandbox writable root filesystem as part of checkpointed pause/resume:

  • when ttl expires or pause is requested, Sandbox0 publishes a block-COW rootfs checkpoint before releasing the runtime allocation
  • when the sandbox resumes, Sandbox0 claims a fresh carrier and restores the latest rootfs generation before starting sandbox processes
  • files written to the writable rootfs survive pause/resume for the same sandbox identity after a checkpoint succeeds
  • rootfs checkpoints for the sandbox identity are deleted when the sandbox is deleted or hard_ttl expires

Use the root filesystem for transparent same-sandbox continuity. Use Snapshot And Restore for named rootfs snapshots, restore, and fork operations across sandbox identities.

As an agent keeps working, dependencies, repositories, and outputs accumulate in its RootFS. Pause publishes the writable branch's changes and reuses unchanged blocks. Resume attaches the committed generation and reads blocks on demand rather than downloading the complete filesystem before starting work. This avoids full-RootFS copies on the lifecycle path; latency still depends on unpublished writes, metadata, cache state, object-store access, and the workload's read working set. See Pause And Resume for filesystem and optional memory checkpoint behavior.


Claim a Sandbox#

Claim a sandbox from a template. Manager atomically selects a compatible resource-neutral carrier and leases exact CPU and memory from dedicated node capacity. A claim fails closed when carrier, physical capacity, RootFS device, or node authority is unavailable.

POST

/api/v1/sandboxes

Request Body#

FieldTypeDescription
templatestringTemplate ID to use
snapshot_idstringOptional rootfs snapshot ID used to initialize the writable root filesystem
configobjectOptional sandbox configuration

Sandbox Configuration#

FieldTypeDescription
env_varsobjectSandbox-level default environment variables for new procd-managed processes
ttlintegerTime to live in seconds (soft limit, triggers auto-pause; default: 0, disabled)
hard_ttlintegerHard sandbox lifetime in seconds (deletes identity and durable state; default: 0, disabled)
resourcesobjectOptional per-sandbox resource override. resources.memory sets base memory; optional resources.memory_burst_percent authorizes additional memory where enabled. CPU is derived from the platform memory-per-CPU ratio with a 500m minimum limit.
networkobjectSandboxNetworkPolicy. Controls traffic rules, protocol controls, credential bindings, and destination-scoped egress auth
webhookobjectWebhook configuration
auto_resumebooleanAuto-resume on supported runtime API, SSH, and service access paths (default: true). Persistent Files API access while paused does not wake compute.
servicesarraySandbox Services for public HTTP routes, including Sandbox Functions

Team quota failures return 429 with error.code set to quota_exceeded. The sandbox_claims policy controls sustained claim rate and immediate burst and includes a Retry-After header when exhausted; active_sandboxes controls the team's running sandbox capacity.

See Network and Protocol Controls for outbound control, Sandbox Services for public HTTP controls, Sandbox Functions for inline public handlers, and Credential for outbound auth and secret handling.

Sandbox env_vars override template/image environment variables for new contexts, supervised session attempts, command services, and function executions. Per-context, per-session, per-command, service runtime, and function env_vars override sandbox env_vars for that narrower scope. The resource-neutral carrier has no prestarted guest process; claim-time variables are available when procd starts.

Sandbox Resources#

Set config.resources.memory at claim time when one sandbox needs a different memory limit from its template. The minimum is 128Mi. The platform maximum defaults to 16Gi and is configured with manager's sandbox_max_memory. Sandbox0 enforces that maximum on template defaults and on sandbox claim, resume, and fork operations. Use the Update Sandbox API with config.resources.memory to change an existing sandbox.

Resource requests specify base memory and an optional burst percentage. Manager derives CPU from team_template_memory_per_cpu and applies the platform minimum. PostgreSQL records the exact resource lease and ctld enforces it in the sandbox cgroup; Nomad carrier resources are overhead only.

Send a standalone resource update using PUT /api/v1/sandboxes/{id}:

json
{"config":{"resources":{"memory":"4Gi"}}}

Changing resources preserves the sandbox ID and durable files but restarts processes and terminal sessions. A running sandbox first completes filesystem pause and physical cleanup, then starts with a fresh resource lease. A paused sandbox stays paused and uses the new limits on its next start. Retained memory checkpoints are discarded; resize does not restore the old processes.

Submit resources separately from lifecycle and service updates. The operation survives request timeout and manager restart. A 503 can mean the change is still in progress; retry the same limit. Repeating an applied limit is a no-op. A conflicting resize or lifecycle operation returns 409. If fresh capacity is unavailable, files remain preserved in the paused sandbox while retries continue.

The CPU limit is the memory-derived amount rounded up to a whole millicore, with a minimum of 500m (0.5 CPU). The minimum also applies when a stored template predates this rule. Claim, resume and fork allocate a new resource lease; resource updates also replace the lease after completing pause. CPU admission and compute metering use the full amount recorded in that lease.

Claim-time helpers expose this as WithSandboxMemory in Go, memory in Python, memory in TypeScript, and --memory in the s0 CLI.

Optional memory burst#

ℹ

Dynamic memory burst is available in the ali-ue1 region as an optional per-sandbox setting. It remains disabled by default for each sandbox and in other regions. Regional enablement and compatible workers are required.

At sandbox creation, config.resources.memory_burst_percent can authorize up to 50% additional memory. For example:

json
{"config":{"resources":{"memory":"4Gi","memory_burst_percent":50}}}

The sandbox starts with a 4 GiB hard limit. As usage approaches that limit, Sandbox0 can raise it to 6 GiB without restarting processes or changing CPU. Once memory usage remains low and a final safety check succeeds, the limit returns to 4 GiB. A workload still using 5 GiB keeps the higher limit. There is no forced expiry that kills processes to fit the base allocation.

The percentage defaults to 0. Base plus burst must fit the platform maximum. The allowance authorizes a higher limit without reserving that amount of physical RAM. Expansion depends on available worker memory and timely observations; an allocation spike can still reach the current hard limit before expansion occurs.

Compute usage is billed at the effective memory limit: 4 GiB before expansion, 6 GiB while expanded, and 4 GiB after shrinking. CPU remains based on the original 4 GiB specification. Lost acknowledgements are reconciled against durable node state; an unreconstructable interval uses the lower limit. A retained-memory resume starts at the authorized ceiling so that captured pages fit, is billed at that ceiling, and can shrink when safe.

Automatic transitions preserve running processes. Explicitly changing the base memory or burst percentage uses the resource-update behavior above, including its process restart and retained-checkpoint disposal semantics.

TTL vs Hard TTL#

Sandbox0 uses two-tier TTL to balance resource efficiency and flexibility:

FieldBehaviorUse Case
ttlRuntime soft pause: When expired, Sandbox0 checkpoints the writable root filesystem, releases the runtime allocation, and marks the sandbox paused.Keep sandboxes alive during active use while freeing compute resources during idle periods.
hard_ttlSandbox hard delete: When expired, Sandbox0 deletes the sandbox identity and durable state, including paused rootfs checkpoints.Enforce a maximum lifetime for compute and storage resources.
ℹ

When both limits are positive, ttl <= hard_ttl is required. Either limit can independently be disabled with 0. When ttl expires first, sandbox pauses but can be resumed. When hard_ttl expires, the sandbox is deleted and later access returns not found. Resume starts a new runtime generation from the latest rootfs checkpoint only while the sandbox is paused and still within its hard TTL.

When an expiration path is disabled or unset, Sandbox responses return null for the corresponding expires_at or hard_expires_at field. A disabled expiration is never represented as a sentinel date.

Example timeline (sandbox created with ttl=300 and hard_ttl=3600):

  • t=0: Sandbox created
  • t=300: TTL expires → sandbox auto-pauses
  • t=310: User calls refresh → soft deadline becomes t=610, hard deadline becomes t=3910; the sandbox stays paused
  • t=610: The soft deadline passes; the sandbox is already paused and remains paused
  • t=3910: Hard TTL expires → sandbox identity and durable state are deleted
go
ctx := context.Background() client, err := sandbox0.NewClient( sandbox0.WithToken(os.Getenv("SANDBOX0_TOKEN")), sandbox0.WithBaseURL(os.Getenv("SANDBOX0_BASE_URL")), ) if err != nil { log.Fatal(err) } // Claim a sandbox from the "default" template sandbox, err := client.ClaimSandbox(ctx, "default", sandbox0.WithSandboxTTL(300), sandbox0.WithSandboxHardTTL(3600), sandbox0.WithSandboxMemory("512Mi"), sandbox0.WithSandboxEnvVars(map[string]string{ "APP_ENV": "development", }), ) if err != nil { log.Fatal(err) } fmt.Printf("Sandbox ID: %s\n", sandbox.ID) defer client.DeleteSandbox(ctx, sandbox.ID)

Get Sandbox Details#

Retrieve full details about an existing sandbox. The snippets below reuse the client and sandbox from the claim example; delete it after finishing. In Go, keep the snippets in the same function, before the deferred cleanup runs.

GET

/api/v1/sandboxes/{id}

go
sb, err := client.GetSandbox(ctx, sandbox.ID) if err != nil { log.Fatal(err) } fmt.Printf("Status: %s\n", sb.Status) fmt.Printf("Template: %s\n", sb.TemplateID) if expiresAt, ok := sb.ExpiresAt.Get(); ok { fmt.Println("Expires at:", expiresAt) } else { fmt.Println("Soft TTL disabled") }

Get Sandbox Status#

Get the current status of a sandbox (lighter weight than full details).

GET

/api/v1/sandboxes/{id}/status

go
status, err := client.StatusSandbox(ctx, sandbox.ID) if err != nil { log.Fatal(err) } fmt.Printf("Status: %s\n", status.Status.Value)

Observability#

Sandbox0 exposes runtime metrics, historical logs, and signed audit events without waking a paused sandbox.

DataUse it forEndpoint
Runtime metricsChart-ready CPU, memory, network, process, and rootfs seriesGET /api/v1/sandboxes/{id}/metrics
Historical logsRetained stdout, stderr, and PTY outputGET /api/v1/sandboxes/{id}/observability/logs
Audit eventsCanonical signed activity recordsGET /api/v1/sandboxes/{id}/observability/events

Audit ingestion and audit queries require the enterprise sandbox_audit feature. Logs, runtime metrics, and the metric catalog do not.

See Observability for metric names, query filters, watch streams, audit integrity, delivery modes, and coverage limits.


List Sandboxes#

List all sandboxes with optional filters.

GET

/api/v1/sandboxes

Query Parameters#

ParameterTypeDescription
statusstringFilter by status (starting, running, paused, terminating, failed)
template_idstringFilter by template ID
pausedbooleanFilter by paused state independently of status
limitintegerMax results per page (default: 50, max: 200)
offsetintegerPagination offset (default: 0)
go
limit := 10 sandboxes, err := client.ListSandboxes(ctx, &sandbox0.ListSandboxesOptions{ Status: "running", TemplateID: "default", Limit: &limit, }) if err != nil { log.Fatal(err) } for _, sb := range sandboxes.Sandboxes { fmt.Printf("- %s (status: %s)\n", sb.ID, sb.Status) }

Update Sandbox#

Update durable lifecycle or service configuration without replacing the runtime allocation, or submit a separate memory resource update that replaces compute as described in Sandbox Resources.

PUT

/api/v1/sandboxes/{id}

Updatable Fields#

Only the following fields can be updated at runtime:

FieldTypeDescription
ttlintegerTime to live in seconds (soft limit)
hard_ttlintegerHard sandbox lifetime in seconds
auto_resumebooleanAuto-resume when accessed
servicesarraySandbox Services for public HTTP routes, including Sandbox Functions
resources.memorystringStandalone memory resize; replaces running compute and discards retained process state. Do not combine with the other fields.
ℹ

Use PUT /api/v1/sandboxes/{'{id}'}/network for network policy changes. Environment and webhook changes are not accepted by this endpoint. Resource changes are accepted only as a standalone memory resize.

bash
curl -X PUT "$SANDBOX0_BASE_URL/api/v1/sandboxes/$SANDBOX_ID" \ -H "Authorization: Bearer $SANDBOX0_TOKEN" \ -H "Content-Type: application/json" \ -d '{"config":{"ttl":600,"hard_ttl":3600,"auto_resume":true}}'

Pause And Resume#

Pause and resume is covered in a dedicated page because it affects TTL, auto_resume, service routes, SSH, and webhook behavior.

See Pause And Resume for explicit pause, state inspection, resume, and auto-resume behavior.

See Snapshot And Restore for named rootfs snapshots, restore, and fork operations. Snapshot and fork accept a running or paused source sandbox; the storage-only restore requires a paused target sandbox. The separate snapshot recovery operation can retire running compute, restore a snapshot, and start a fresh runtime.


Refresh Sandbox TTL#

Extend the sandbox time-to-live. This resets both ttl and hard_ttl (if configured) from the current time. It also works while paused, without resuming compute.

POST

/api/v1/sandboxes/{id}/refresh

Request Body#

FieldTypeDescription
durationintegerDuration to extend TTL in seconds (optional, defaults to original TTL)
ℹ

If duration is not specified, both ttl and hard_ttl are reset to their original configured values. Use this to keep a sandbox alive as long as the user is actively using it.

go
// Also import apispec "github.com/sandbox0-ai/sdk-go/pkg/apispec" // Refresh with default duration (original TTL) resp, err := client.RefreshSandbox(ctx, sandbox.ID, nil) if err != nil { log.Fatal(err) } if expiresAt, ok := resp.ExpiresAt.Get(); ok { fmt.Println("New expires at:", expiresAt) } else { fmt.Println("Soft TTL disabled") } // Refresh with custom duration (e.g., 1 minute) resp, err = client.RefreshSandbox(ctx, sandbox.ID, &apispec.SandboxRefreshRequest{ Duration: apispec.NewOptInt32(60), }) if err != nil { log.Fatal(err) } if expiresAt, ok := resp.ExpiresAt.Get(); ok { fmt.Println("New expires at:", expiresAt) } else { fmt.Println("Soft TTL disabled") }

Delete Sandbox#

Terminate and delete a sandbox. This action is irreversible.

DELETE

/api/v1/sandboxes/{id}

A successful response means the deletion intent is durable. Runtime teardown and persistent RootFS cleanup finish asynchronously. For Nomad-backed Sandboxes, the manager fences the exact allocation and its writer authority before deleting the logical record; it does not depend on the Nomad task-driver process remaining available.

go
_, err = client.DeleteSandbox(ctx, sandbox.ID) if err != nil { log.Fatal(err) } fmt.Println("Sandbox deleted")

Next Steps#