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.tsThe 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.
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
egressupdates a sandbox that already exists. Omitting it keeps the existing policy. timeoutMsbounds 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.
startJobresolves with the job id. If the start goes unanswered, it raisesSANDBOX_OUTCOME_UNKNOWN. Don't repeat it: the sandbox may have taken the command.pollJobreturns frames aftersinceSeq. Omit it to read from the first frame, then pass the highestseqyou've received. Repeating a poll changes nothing, soSANDBOX_UNREACHABLEhere is safe to retry.cancelJobstops 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:
| Method | Signature |
|---|---|
capabilities | async capabilities(sandbox_id: str | None = None) -> frozenset[str] |
create | async create(*, sandbox_id=None, tenant_key=None, env=None, timeout_ms=None, egress=None) -> SandboxInfo |
get | async get(sandbox_id: str) -> SandboxInfo | None |
get_or_create | async get_or_create(*, sandbox_id=None, tenant_key=None, env=None, timeout_ms=None, egress=None) -> tuple[SandboxInfo, bool] |
list | async list() -> list[SandboxInfo] |
run_command | async run_command(sandbox_id, command, args, *, timeout_ms, cwd=None, env=None) -> CommandStream |
start_job | async start_job(sandbox_id, command, args, *, timeout_ms, cwd=None, env=None) -> str |
poll_job | async poll_job(sandbox_id, job_id, *, since_seq=None) -> JobResult |
cancel_job | async cancel_job(sandbox_id, job_id) -> None |
read_file | async read_file(sandbox_id, path) -> bytes |
write_file | async write_file(sandbox_id, path, contents: bytes) -> None |
update_egress | async update_egress(sandbox_id, egress: EgressPolicy) -> None |
preview | async preview(sandbox_id, port) -> SandboxPreview |
pause, resume, terminate | async pause(sandbox_id) -> None |
argsis positional and required onrun_commandandstart_job. Pass[]for none.- Await
run_commandto get the stream, then iterate it withasync for. Callawait stream.close()to stop reading early. write_filewrites one file per call.SandboxInfohassandbox_id,state, andgeneration.CommandFramehaskind,seq,data,exit_code, andtruncated.JobResulthasrunning,frames,exit_code,truncated,error_code, anderror_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
| Error | Meaning | Action |
|---|---|---|
SANDBOX_OUTCOME_UNKNOWN | The command, job, or create may have happened. | Check its effects before repeating it. |
SANDBOX_COMMAND_FAILED | Command timeout, refused path, or provider failure. | Don't assume the command had no effects. |
SANDBOX_UNREACHABLE | Create readiness failed, or the image is still building. | Retryable, but a retried create can make a second sandbox. |
SANDBOX_NOT_AS_DECLARED | Azure's effective egress differs from the declaration. | Creation fails. Investigate the policy. |
OPERATION_NOT_SUPPORTED | Operation or option not available on this platform. | Check capabilities(). |
INVALID_INPUT | Bad request, such as a zero lifetime. | Correct the request. |
SANDBOX_EGRESS_REQUIRES_INTERNET | A runtime policy without .egress("internet"). | Change the declaration. |
SANDBOX_EGRESS_INVALID | Malformed target, or one in a refused range. | Correct the target. |
SANDBOX_EGRESS_POLICY_TOO_LARGE | More than 4,096 targets or 256 KiB. | Shorten the policy. |
SANDBOX_EGRESS_GATEWAY_UNAVAILABLE | The gateway can't apply the policy, or the platform has no gateway. | Check gateway health. |
SANDBOX_EGRESS_VERSION_IN_FUTURE | The SDK clock is more than 60 seconds ahead of the gateway. | Fix clock skew. |
SANDBOX_EGRESS_POLICY_STORE_FULL | The gateway has no room for another policy. | Terminate unused sandboxes. |
See Errors and retries for per-platform cases.