Docs

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.

alien.ts
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 the api Worker, 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 execution permission profile, the named set of cloud permissions a workload runs with, grants sandbox/management and sandbox/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.
PlatformProvisionsIsolation boundary"internet" egress
AWSLambda MicroVMs, egress gatewayMicroVM. No execution role attached.Supported. Needs a VPC created by the deployment, or private sandbox subnets supplied through CloudFormation or Terraform.
Google CloudAgent Platform sandboxesProvider container boundaryNot supported
AzureContainer Apps sandboxesContainer Apps sandboxNot supported
KubernetesWarm pool of Pods with a sandboxed RuntimeClass (AWS Nitro Sandboxes on EKS, gVisor, or Kata), egress gatewaySandboxed runtime, no service account token, NetworkPolicySupported. Needs a CNI that enforces NetworkPolicy.
MachinesNot supported
LocalDocker containersShares 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:

api/src/run.ts
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

src/run.ts
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 to get to 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 sh with args: ["-c", line].
  • SANDBOX_OUTCOME_UNKNOWN means 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.

Sandbox traffic leaves only through the egress gateway. Your app pushes a signed policy for each sandbox.

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:

PolicyAllows
"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

PlatformImageSource builds
AWSARM64 Lambda MicroVM bundlelinux/arm64. Source builds and private base images require "live".
Google CloudImage with the Alien sandbox agent, in Artifact Registrylinux/amd64. The release adds the agent.
AzureRegistry image with the Alien agent added, or a native catalog image such as ubuntulinux/amd64. The release adds the agent.
KubernetesImage with the Alien sandbox agentNot supported. Use a prebuilt image.
LocalDocker image on your machineNot supported. Use a prebuilt image.

To build from a Dockerfile, use a source declaration:

alien.ts
.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:

sandbox/Dockerfile
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, and kill for 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

MethodTypeDefaultNotes
.code(code)SandboxCoderequiredPrebuilt 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? }requiredPass {} to set neither. maxLifetimeSeconds is refused on Local.
.limits(limits){ cpu, memory, disk, maxProcesses? }platform defaultEnforced 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)stringnonePrivate ECR base image for an AWS build. AWS only, and the Sandbox must be "live".
.enabled(input)StackInputRef<boolean>alwaysGates 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 250m from 250m to 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 disk as the sandbox's ephemeral storage limit, which can be at most 10Gi.
  • 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

src/run.ts
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:

src/run.ts
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:

src/run.ts
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/execute on 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/execute on 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:

src/run.ts
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:

sandbox/Dockerfile
FROM python:3.14-slim
COPY supervisor.py /opt/supervisor.py
USER 0:0
ENTRYPOINT ["python3", "/opt/supervisor.py"]
sandbox/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

SetGrants
sandbox/managementCreating and terminating sandboxes and changing gateway policies. No access to sandbox contents.
sandbox/executeRunning commands and moving files inside an existing sandbox. On Azure, also lifecycle operations.
sandbox/remote-executeDirect cloud access for a remote caller to create sandboxes and run code in them.
sandbox/templatesCreating and replacing the template a sandbox launches from, which sets its image and internet access. Google Cloud.
sandbox/imagesBuilding, reading, and deleting sandbox disk images. Azure.
sandbox/protect-setup-rolesRefuses changes to the IAM roles initial setup creates for sandboxes. AWS.
sandbox/provision, sandbox/heartbeatUsed 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.

Next

On this page