Docs

Sandbox API reference

The Sandbox API is the set of methods your app calls on a linked Sandbox resource to create sandboxes, run commands, and move files, with its types and errors. Your app reaches it through its binding: the connection details Alien injects into each workload linked to the resource, which the SDK client reads.

The SDK client is the same Rust core in every language. TypeScript and Python wrap it, so behavior, errors, and limits match across SDKs.

Get the binding

import { sandbox } from "@alienplatform/sdk"

const box = sandbox("agent") // the Sandbox id from alien.ts

The workload must link the Sandbox. Creating and terminating needs sandbox/management. Running commands and moving files needs sandbox/execute.

Methods

Capabilities differ per platform. An unsupported operation raises OPERATION_NOT_SUPPORTED. It never silently does nothing.

See Operations by platform.

capabilities

capabilities(sandboxId?: string): Promise<string[]>

Without an id, returns the operations new sandboxes support. With an id, returns what that existing sandbox supports. Call it with the id after reconnecting across image upgrades, because an existing session's transport can differ from the one new sandboxes use.

The names are: files, reconnect, jobs, preview, pauseResume, snapshot, domainEgressRules, egressDeny, enforcedLimits, processLimit, sandboxLifetime, supervisorPidNamespace, supervisorIsolation. No platform reports snapshot today.

create

create(options?: CreateSandboxOptions): Promise<SandboxInstance>

Creates a sandbox and waits until it can run commands, so the first command never races its start. On AWS the wait is part of the call and can take seconds. A sandbox that never becomes reachable rejects with SANDBOX_UNREACHABLE.

A retry after SANDBOX_UNREACHABLE can create a second sandbox. Backends try to clean up when readiness fails, but a failed create can still leave a sandbox without returning its id.

get

get(sandboxId: string): Promise<SandboxInstance | null>

Fetches a sandbox, or null if it doesn't exist. Requires reconnect. A backend that can't answer raises an error instead, so an absent sandbox and an unreachable one never look the same.

On Kubernetes, only the process that created a sandbox can reconnect to it.

getOrCreate

getOrCreate(options?: CreateSandboxOptions): Promise<ResolvedSandbox>
getOrCreate(
  sandboxId: string,
  options?: Omit<CreateSandboxOptions, "sandboxId">,
): Promise<ResolvedSandbox>

Fetches a sandbox, creating it if absent, and reports which it did in created.

  • A terminated sandbox counts as absent. The replacement can have a different id, so store the id you get back.
  • An explicit egress updates a sandbox that already exists. Omitting it keeps the existing policy.
  • timeoutMs bounds only a sandbox this call creates. A found sandbox keeps its lifetime.
  • No backend has an atomic create-if-absent. Two callers naming one id can both get created: true.

list

list(): Promise<SandboxInstance[]>

Lists this Sandbox resource's sandboxes. Supported on Google Cloud and Local, and on Kubernetes for sandboxes the current process claimed.

AWS and Azure raise OPERATION_NOT_SUPPORTED, because enumerating there needs an account-wide grant the sandbox role withholds. Use get with an id you saved.

runCommand

runCommand(
  sandboxId: string,
  command: string,
  options: RunCommandOptions,
): AsyncIterable<CommandFrame>

Runs command with options.args and yields stdout and stderr frames as the command produces them, then exactly one exit frame. The iterator is pull-based: nothing is read from the sandbox until you ask for the next frame, so a slow consumer slows the command's output instead of buffering it.

timeoutMs is required. It bounds the command, not the call. A timeout stops the command's process group and the sandbox stays usable.

A child that detaches with setsid can keep running until the sandbox ends. A timeout is reported only after the command has verifiably stopped.

Output beyond 4 MiB per stream is dropped, and the exit frame reports truncated: true.

startJob, pollJob, cancelJob

startJob(sandboxId: string, command: string, options: RunCommandOptions): Promise<string>
pollJob(sandboxId: string, jobId: string, sinceSeq?: number): Promise<JobPoll>
cancelJob(sandboxId: string, jobId: string): Promise<void>

A job is a command that outlives the call that started it. Nothing holds a stream open, and a caller that goes away can reach the job again by its id. All three require jobs.

  • startJob resolves with the job id. If the start goes unanswered, it raises SANDBOX_OUTCOME_UNKNOWN. Don't repeat it: the sandbox may have taken the command.
  • pollJob returns frames after sinceSeq. Omit it to read from the first frame, then pass the highest seq you've received. Repeating a poll changes nothing, so SANDBOX_UNREACHABLE here is safe to retry.
  • cancelJob stops the command. Repeating it is safe.

A sandbox holds at most 16 jobs. A finished job counts until a poll reads its result.

readFile, writeFiles

readFile(sandboxId: string, path: string): Promise<Buffer>
writeFiles(sandboxId: string, files: Record<string, Buffer | string>): Promise<void>

Paths resolve under /sandbox. A leading / means /sandbox. Paths can't escape it.

Parent directories are created as needed. Each file can be at most 32 MiB.

writeFiles writes sequentially, so a failed call can leave earlier files written. Requires files. See Files by platform for how each platform resolves paths.

updateEgress

updateEgress(sandboxId: string, egress: EgressPolicy): Promise<void>

Replaces the sandbox's runtime egress policy without replacing the sandbox. Works on running sandboxes, and on paused AWS sandboxes, which receive it on resume.

New connections use the new policy when the call returns. Open connections to removed destinations close within about 30 seconds.

Requires a resource declared with .egress("internet"). Otherwise it raises SANDBOX_EGRESS_REQUIRES_INTERNET. A failed update may already have reached some gateway replicas.

preview

preview(sandboxId: string, port: number): Promise<SandboxPreview>

Returns an endpoint and headers that reach a port inside the sandbox. The port must be in .previewPorts(). Requires preview.

Send every header with every request, and request a new preview before expiresInSeconds runs out.

pause, resume

pause(sandboxId: string): Promise<void>
resume(sandboxId: string): Promise<void>

Requires pauseResume. pause freezes the sandbox with its state.

A running command freezes with it, along with its own deadline. A caller streaming that command's output is rejected within a bound rather than held for the length of the pause.

resume returns once the sandbox can take a command. A sandbox that has ended rejects with a non-retryable error.

On Azure, a command frozen by a pause is ended by terminating the sandbox, so a later resume finds nothing.

terminate

terminate(sandboxId: string): Promise<void>

Deletes the sandbox. Idempotent: terminating an absent sandbox succeeds. A terminate that can't confirm deletion rejects with a retryable error.

AWS reports SANDBOX_UNREACHABLE if it can't confirm termination within 30 seconds. On Kubernetes, terminate deletes only sandboxes the current process claimed, and returns success without deleting another process's sandbox.

Types

CreateSandboxOptions

Prop

Type

Use command-level env for portable code. See Create options by platform.

SandboxInstance

Prop

Type

ResolvedSandbox is { sandbox: SandboxInstance, created: boolean }.

RunCommandOptions

Prop

Type

On AWS and Google Cloud, the platform ends a sandbox at its lifetime whatever is running. A command cut off that way reports SANDBOX_OUTCOME_UNKNOWN, not a timeout. Leave room in the lifetime for the longest command.

CommandFrame

type CommandFrame =
  | { kind: "stdout" | "stderr"; seq: number; data: Buffer }
  | { kind: "exit"; exitCode: number; truncated: boolean }

seq increases across both streams, so you can interleave them in production order. data is raw bytes and isn't necessarily UTF-8.

JobPoll

Prop

Type

SandboxPreview

Prop

Type

EgressPolicy

type EgressPolicy = "internet" | { allow: string[] }

A target is a hostname, a wildcard hostname, an IPv4 address, or an IPv4 CIDR, with an optional :port. A policy holds up to 4,096 targets and 256 KiB. See Allowlists.

Python

Python has the same operations in snake_case. Differences from TypeScript:

MethodSignature
capabilitiesasync capabilities(sandbox_id: str | None = None) -> frozenset[str]
createasync create(*, sandbox_id=None, tenant_key=None, env=None, timeout_ms=None, egress=None) -> SandboxInfo
getasync get(sandbox_id: str) -> SandboxInfo | None
get_or_createasync get_or_create(*, sandbox_id=None, tenant_key=None, env=None, timeout_ms=None, egress=None) -> tuple[SandboxInfo, bool]
listasync list() -> list[SandboxInfo]
run_commandasync run_command(sandbox_id, command, args, *, timeout_ms, cwd=None, env=None) -> CommandStream
start_jobasync start_job(sandbox_id, command, args, *, timeout_ms, cwd=None, env=None) -> str
poll_jobasync poll_job(sandbox_id, job_id, *, since_seq=None) -> JobResult
cancel_jobasync cancel_job(sandbox_id, job_id) -> None
read_fileasync read_file(sandbox_id, path) -> bytes
write_fileasync write_file(sandbox_id, path, contents: bytes) -> None
update_egressasync update_egress(sandbox_id, egress: EgressPolicy) -> None
previewasync preview(sandbox_id, port) -> SandboxPreview
pause, resume, terminateasync pause(sandbox_id) -> None
  • args is positional and required on run_command and start_job. Pass [] for none.
  • Await run_command to get the stream, then iterate it with async for. Call await stream.close() to stop reading early.
  • write_file writes one file per call.
  • SandboxInfo has sandbox_id, state, and generation. CommandFrame has kind, seq, data, exit_code, and truncated. JobResult has running, frames, exit_code, truncated, error_code, and error_message.

Rust

Arc<dyn Sandbox> from alien_sdk::Bindings::sandbox:

fn capabilities(&self) -> SandboxCapabilities;
async fn session_capabilities(&self, sandbox_id: &str) -> Result<SandboxCapabilities>;
async fn create(&self, request: CreateSandboxRequest) -> Result<SandboxInstance>;
async fn get(&self, sandbox_id: &str) -> Result<Option<SandboxInstance>>;
async fn get_or_create(&self, request: CreateSandboxRequest) -> Result<ResolvedSandbox>;
async fn list(&self) -> Result<Vec<SandboxInstance>>;
async fn update_egress(&self, sandbox_id: &str, egress: EgressPolicy) -> Result<()>;
async fn run_command(&self, sandbox_id: &str, request: RunCommandRequest)
    -> Result<BoxStream<'static, Result<CommandOutput>>>;
async fn start_job(&self, sandbox_id: &str, request: RunCommandRequest) -> Result<JobStart>;
async fn poll_job(&self, sandbox_id: &str, job_id: &str, since_seq: Option<u64>) -> Result<JobPoll>;
async fn cancel_job(&self, sandbox_id: &str, job_id: &str) -> Result<()>;
async fn read_file(&self, sandbox_id: &str, path: &str) -> Result<Vec<u8>>;
async fn write_files(&self, sandbox_id: &str, files: BTreeMap<String, Vec<u8>>) -> Result<()>;
async fn preview(&self, sandbox_id: &str, port: u16) -> Result<PreviewCapability>;
async fn pause(&self, sandbox_id: &str) -> Result<()>;
async fn resume(&self, sandbox_id: &str) -> Result<()>;
async fn terminate(&self, sandbox_id: &str) -> Result<()>;

capabilities() returns a struct of booleans rather than a list of names. RunCommandRequest takes timeout: Duration instead of milliseconds. CommandOutput is Stdout { seq, data }, Stderr { seq, data }, or Exit { code, truncated }.

Errors

ErrorMeaningAction
SANDBOX_OUTCOME_UNKNOWNThe command, job, or create may have happened.Check its effects before repeating it.
SANDBOX_COMMAND_FAILEDCommand timeout, refused path, or provider failure.Don't assume the command had no effects.
SANDBOX_UNREACHABLECreate readiness failed, or the image is still building.Retryable, but a retried create can make a second sandbox.
SANDBOX_NOT_AS_DECLAREDAzure's effective egress differs from the declaration.Creation fails. Investigate the policy.
OPERATION_NOT_SUPPORTEDOperation or option not available on this platform.Check capabilities().
INVALID_INPUTBad request, such as a zero lifetime.Correct the request.
SANDBOX_EGRESS_REQUIRES_INTERNETA runtime policy without .egress("internet").Change the declaration.
SANDBOX_EGRESS_INVALIDMalformed target, or one in a refused range.Correct the target.
SANDBOX_EGRESS_POLICY_TOO_LARGEMore than 4,096 targets or 256 KiB.Shorten the policy.
SANDBOX_EGRESS_GATEWAY_UNAVAILABLEThe gateway can't apply the policy, or the platform has no gateway.Check gateway health.
SANDBOX_EGRESS_VERSION_IN_FUTUREThe SDK clock is more than 60 seconds ahead of the gateway.Fix clock skew.
SANDBOX_EGRESS_POLICY_STORE_FULLThe gateway has no room for another policy.Terminate unused sandboxes.

See Errors and retries for per-platform cases.

On this page