Sandbox
A Sandbox is a resource your app uses to create isolated environments at runtime and run code it doesn't trust inside them: an AI agent's tool calls, a customer's script, a build of a customer's repository. The code inside gets no cloud credentials, so it can't reach other resources in the stack.
import * as alien from "@alienplatform/core"
const agent = new alien.Sandbox("agent")
.code({ type: "image", image: "ubuntu:24.04" })
.limits({ cpu: "1", memory: "2Gi", disk: "8Gi" })
.egress("internet")
.lifecycle({ maxLifetimeSeconds: 3600 })
.build()
const api = new alien.Worker("api")
.code({ type: "source", src: "./api", toolchain: { type: "typescript" } })
.link(agent)
.permissions("execution")
.build()
export default new alien.Stack("acme")
.add(agent, "frozen")
.add(api, "live")
.permissions({
profiles: { execution: { agent: ["sandbox/management", "sandbox/execute"] } },
})
.build()In this stack:
.link(agent)connects the Sandbox resource to theapiWorker, the workload (the running code) that uses it. Alien injects the Sandbox resource's connection details, its binding, into the Worker, read by the SDK client.- The
executionpermission profile, the named set of cloud permissions a workload runs with, grantssandbox/managementandsandbox/execute: creating sandboxes and running commands in them. "frozen"means the customer's admin creates the Sandbox resource during initial setup."live"resources, like the Worker, are created and updated by Alien on every release. See Frozen and live.
| Platform | Provisions | Isolation boundary | "internet" egress |
|---|---|---|---|
| AWS | Lambda MicroVMs, egress gateway | MicroVM. No execution role attached. | Supported. Needs a VPC created by the deployment, or private sandbox subnets supplied through CloudFormation or Terraform. |
| Google Cloud | Agent Platform sandboxes | Provider container boundary | Not supported |
| Azure | Container Apps sandboxes | Container Apps sandbox | Not supported |
| Kubernetes | Warm pool of Pods with a sandboxed RuntimeClass (AWS Nitro Sandboxes on EKS, gVisor, or Kata), egress gateway | Sandboxed runtime, no service account token, NetworkPolicy | Supported. Needs a CNI that enforces NetworkPolicy. |
| Machines | Not supported | ||
| Local | Docker containers | Shares the host kernel. For development only. | Not supported |
A platform that can't deliver a declaration refuses it at plan time. See Behavior and limits for operations, limits, and lifetimes per platform, and Security for the isolation boundary.
The api Worker creates a sandbox, runs a command in it, and deletes it:
import { sandbox } from "@alienplatform/sdk"
const box = sandbox("agent")
const { sandboxId } = await box.create()
const options = { args: ["hello"], timeoutMs: 30_000 }
for await (const frame of box.runCommand(sandboxId, "echo", options)) {
if (frame.kind === "stdout") process.stdout.write(frame.data)
}
await box.terminate(sandboxId)Link the Sandbox to the workload that creates sandboxes, and grant that workload sandbox/management and sandbox/execute.
Lifecycle and ids
The image, limits, and outbound access are fixed in alien.ts. Sandboxes themselves come and go at runtime, created and deleted by your app.
A Sandbox resource is "frozen" on every platform: the customer's admin creates it during initial setup. On AWS it can also be "live", and it must be "live" when it uses a source build or a private base image. See Frozen and live.
Sandbox ids must be DNS-compatible: lowercase letters, digits, and hyphens, starting and ending with a letter or digit, with no consecutive hyphens. On AWS they can be at most 17 characters, or 16 with .egress("none").
For your own services, use a Worker, Container, or Daemon instead.
Use it in code
import { sandbox } from "@alienplatform/sdk"
const box = sandbox("agent")
const { sandboxId } = await box.create({ egress: { allow: ["api.example.com"] } })
try {
await box.writeFiles(sandboxId, { "work/input.txt": "hello\n" })
for await (const frame of box.runCommand(sandboxId, "sh", {
args: ["-c", "cat work/input.txt > work/output.txt"],
timeoutMs: 30_000,
})) {
if (frame.kind === "stdout") process.stdout.write(frame.data)
if (frame.kind === "stderr") process.stderr.write(frame.data)
if (frame.kind === "exit") console.log("exit code", frame.exitCode)
}
const output = await box.readFile(sandboxId, "work/output.txt")
console.log(output.toString())
} finally {
await box.terminate(sandboxId)
}- Keep the returned
sandboxId. A provider can allocate an id different from the one you asked for. Pass it togetto reconnect later. - Every command needs a timeout. A nonzero exit code is a command result, not an error.
- Commands run a program directly. For shell syntax, pass
shwithargs: ["-c", line]. SANDBOX_OUTCOME_UNKNOWNmeans the command may have run. Check its effects before you run it again.- Save results you want to keep in Storage before you terminate the sandbox.
See the API reference for every method and type.
Outbound access
.egress("internet") sends outbound traffic through an egress gateway in the deployment's network:
Architecture diagram. Left: Your app, Worker or Container. Right: Customer environment containing Sandbox; Egress gateway · 2 replicas, per-sandbox policy, public destination checks; NAT · fixed outbound IP; Internet.
The gateway allows only public destinations. Private ranges, cloud metadata, the deployment network, and the container network are always blocked. The enforcement runs outside the sandbox, so code inside it can't widen it.
Each sandbox has its own policy. Pass it to create, or change it later with updateEgress:
| Policy | Allows |
|---|---|
"internet" | Public hostnames. Literal IP addresses need an explicit entry. |
{ allow: ["api.example.com", "*.example.org", "203.0.113.10:443", "198.51.100.0/24"] } | Only these targets. |
{ allow: [] } | No new outbound connections. |
Without egress on create, .defaultPolicy() applies, and without that the policy is "internet".
Mail ports 25, 465, and 587 need an entry that names the port.
.egress("none") blocks outbound connections without a gateway. On AWS and Azure, DNS lookups still work through the cloud's resolver, so data can still leave in a hostname. On Google Cloud, a sandbox with "none" resolves no names.
See Egress for target syntax, policy changes, outbound IPs, and older egress values.
Images
| Platform | Image | Source builds |
|---|---|---|
| AWS | ARM64 Lambda MicroVM bundle | linux/arm64. Source builds and private base images require "live". |
| Google Cloud | Image with the Alien sandbox agent, in Artifact Registry | linux/amd64. The release adds the agent. |
| Azure | Registry image with the Alien agent added, or a native catalog image such as ubuntu | linux/amd64. The release adds the agent. |
| Kubernetes | Image with the Alien sandbox agent | Not supported. Use a prebuilt image. |
| Local | Docker image on your machine | Not supported. Use a prebuilt image. |
To build from a Dockerfile, use a source declaration:
.code({ type: "source", src: "./sandbox", toolchain: { type: "docker" } })Run alien build, then alien release. A Dockerfile shared across clouds needs a base published for both architectures, or one base per architecture. Docker sets TARGETARCH for each build:
FROM public.ecr.aws/lambda/microvms:al2023-minimal AS base-arm64
FROM python:3.14-slim AS base-amd64
FROM base-${TARGETARCH}Add your application and its dependencies after the final FROM.
Per-platform image requirements:
- Google Cloud: the sandbox service agent needs Artifact Registry Reader on the image repository.
- Google Cloud: the image's startup command must keep running in the foreground. If the container exits at start, the deployment fails with a message that names this cause.
- Azure and Local: native Azure images and Local images need
sh,setsid,od,tr,sleep, andkillfor command timeouts. - Azure: give a changed image a new tag or digest, because Azure builds one disk image per reference.
The image's USER decides which identity runs your image's startup command and which runs commands. See Image startup and Users and privileges.
Options
| Method | Type | Default | Notes |
|---|---|---|---|
.code(code) | SandboxCode | required | Prebuilt image or Dockerfile source. See Images. |
.egress(mode) | "none" | "internet" | required | "none" blocks outbound connections. "internet" routes through the egress gateway. |
.lifecycle(policy) | { maxLifetimeSeconds?, idlePauseSeconds? } | required | Pass {} to set neither. maxLifetimeSeconds is refused on Local. |
.limits(limits) | { cpu, memory, disk, maxProcesses? } | platform default | Enforced ceilings, not scheduling hints. A platform that can't enforce one refuses the stack at plan time. |
.defaultPolicy(policy) | "internet" | { allow: string[] } | "internet" | Policy for sandboxes created without one. Requires .egress("internet"). |
.previewPorts(ports) | number[] | [] | Only these ports can be exposed with preview. |
.privateBaseImage(image) | string | none | Private ECR base image for an AWS build. AWS only, and the Sandbox must be "live". |
.enabled(input) | StackInputRef<boolean> | always | Gates the resource on a boolean stack input. See Using resources. |
Sandbox.any() returns the "sandbox" resource type, for permission targets that apply to every Sandbox.
Limits
cpu takes cores or millicores ("1", "500m"). memory and disk take Kubernetes quantities ("2Gi", "512Mi"). maxProcesses must be at least 1 and works only on Local.
Each platform enforces limits differently:
- AWS picks a MicroVM size from your memory and disk ceilings. The smallest accepted declaration is
cpu: "1",memory: "2Gi",disk: "8Gi". See AWS sizes. - Azure takes CPU in steps of
250mfrom250mto 16 cores, with at most 2 GiB of memory and 20 GiB of disk per core. - Google Cloud enforces CPU and memory by terminating a sandbox that exceeds them. It sets
diskas the sandbox's ephemeral storage limit, which can be at most10Gi. - Kubernetes sets Pod resource limits and an ephemeral storage limit.
- Local sets Docker limits and caps the size of
/sandbox.
Common patterns
Reuse a sandbox per task
const { sandbox: reused, created } = await box.getOrCreate("task-42", {
egress: { allow: ["api.example.com"] },
})
await saveSandboxId("task-42", reused.sandboxId)An explicit egress also updates a sandbox that already exists, so set the policy each time you hand a sandbox new work.
Save the returned id: replacing a missing or terminated sandbox can return a new one. getOrCreate isn't atomic, so two concurrent callers can each create a sandbox. Use your own lock if setup must not run twice.
Long-running work
runCommand holds a stream open for the length of the command. For work that outlives a request, start a job and poll it:
const jobId = await box.startJob(sandboxId, "make", { args: ["test"], timeoutMs: 600_000 })
let seq: number | undefined
for (;;) {
const poll = await box.pollJob(sandboxId, jobId, seq)
for (const frame of poll.frames) {
if (frame.kind !== "exit") seq = frame.seq
}
if (!poll.running) break
await new Promise(resolve => setTimeout(resolve, 1000))
}Jobs need the jobs capability. Call capabilities(sandboxId) first if your code runs on more than one platform.
Preview a port
Declare the port with .previewPorts([8080]), then:
const preview = await box.preview(sandboxId, 8080)
await fetch(preview.endpoint, { headers: preview.headers })Preview works on AWS (credentials last 30 minutes), Google Cloud, Azure, Kubernetes, and Local (on 127.0.0.1, no expiry). Credentials last at most 5 minutes on Google Cloud and 15 minutes on Azure and Kubernetes, so call preview again for a fresh one before expiresInSeconds runs out.
On Kubernetes, only callers inside the cluster can reach the endpoint. On Azure, preview needs an image with the Alien agent, so catalog images such as ubuntu are refused at plan time.
On Azure and Kubernetes, the preview headers carry an Alien capability in X-Alien-Preview-Capability, so your own Authorization header reaches the service unchanged, over HTTP and WebSocket.
Preview on Google Cloud
On Google Cloud, preview access equals command access. The credential Google's sandbox ingress accepts covers the whole sandbox, not one port, and it also runs commands. So preview works only for a caller that can already run commands in that sandbox:
- The deployment's own sandbox binding can preview. A remote sandbox can't.
- A permission profile that previews must hold
sandbox/executeon the sandbox. A declaration with preview ports that no profile can run commands in is refused at plan time. - Initial setup creates one signing identity per sandbox resource with preview ports. Only the profiles that hold
sandbox/executeon it can sign as it. - Don't share a Google Cloud preview link with anyone you wouldn't let run commands in the sandbox. For a preview link a third party can open, use AWS, Azure or Kubernetes.
Your own bearer token goes in the header named by preview.callerAuthorizationHeader, because Google's ingress uses Authorization itself. The service still receives it as Authorization:
const preview = await box.preview(sandboxId, 8080)
await fetch(preview.endpoint, {
headers: { ...preview.headers, [preview.callerAuthorizationHeader]: `Bearer ${token}` },
})A WebSocket needs the headers and preview.subprotocols, offered after your own subprotocols. A browser can't set headers on a WebSocket, so open Google Cloud WebSockets from server code.
Google Cloud preview needs the Alien CLI and SDK 3.3.68 or later. Other limits on Google Cloud stay: disk at most 10Gi, no "internet" egress, and no pause.
Run a service inside the sandbox
The image's ENTRYPOINT and CMD start once per boot, before commands are accepted. Alien doesn't wait for the service to be ready or restart it, so use a supervisor. This image starts a root supervisor that gives a directory to UID 2000 and runs a worker under that UID:
FROM python:3.14-slim
COPY supervisor.py /opt/supervisor.py
USER 0:0
ENTRYPOINT ["python3", "/opt/supervisor.py"]import os
import subprocess
import sys
import time
os.makedirs("/tmp/worker", exist_ok=True)
os.chown("/tmp/worker", 2000, 2000)
while True:
subprocess.run(
[sys.executable, "-m", "http.server", "8081", "--directory", "/tmp/worker"],
user=2000, group=2000, extra_groups=[], check=False,
)
time.sleep(1)Build it with a source declaration. On AWS, use .egress("internet") or .egress("none"), because a root image needs the connector that initial setup provides.
On Amazon EKS, an image whose USER is root doesn't start yet. Use a non-root USER there.
Your app must check the worker's readiness before using it. runCommand and startJob still run as the separate command identity.
Remote sandboxes
A remote sandbox is driven from outside the deployment with cloud credentials. It must use the older { mode: "allow" } egress and declare no preview ports.
"internet" can't be combined with remoteAccess, because the gateway's policy endpoint is private to the deployment. See Remote bindings.
A remotely published Sandbox must be the deployment's only remoteAccess resource, and nothing else in the deployment may reach its sandboxes:
- no link to it,
- no permission profile or service account set that covers its sandboxes,
- no resource-scoped management grant on it.
No cloud can scope a remote grant to some sessions only, so the plan refuses these stacks.
The remote caller holds cloud credentials, so its cloud grant bounds it, not the Sandbox declaration. For example, declared preview ports don't limit it on AWS.
Permissions
| Set | Grants |
|---|---|
sandbox/management | Creating and terminating sandboxes and changing gateway policies. No access to sandbox contents. |
sandbox/execute | Running commands and moving files inside an existing sandbox. On Azure, also lifecycle operations. |
sandbox/remote-execute | Direct cloud access for a remote caller to create sandboxes and run code in them. |
sandbox/templates | Creating and replacing the template a sandbox launches from, which sets its image and internet access. Google Cloud. |
sandbox/images | Building, reading, and deleting sandbox disk images. Azure. |
sandbox/protect-setup-roles | Refuses changes to the IAM roles initial setup creates for sandboxes. AWS. |
sandbox/provision, sandbox/heartbeat | Used by initial setup and the management identity. |
Google Cloud grants bind at project scope. Use separate projects where deployments need separate sandbox access. See Permissions.