Run a coding agent in a sandbox per conversation
This example builds an agent product whose chat UI stays hosted, while the agent itself runs in the customer's AWS account, one Sandbox per conversation. The agent is Claude Code. It works with the customer's internal API, but it never holds a real credential, it reaches nothing except the model and one connector, and every write it asks for waits for a person to approve it.
Architecture diagram. Left: Your cloud containing Control plane, chat UI, thread router, approve / deny. Right: Customer environment containing Alien stack containing runner (Container); agent (Sandbox per thread); connector (Container); model (Container) + AI; Already there, internal API, scanner.
Source: examples/agent-sandboxes. control-plane/ is your SaaS, data-plane/ is the Alien stack, and customer-network/ stands in for what the customer already runs: a VPC, a small orders API, and a scanner, both on private addresses.
What goes where
| Your cloud (control plane) | Customer's environment (data plane) |
|---|---|
| Chat UI and thread router | agent, a Sandbox, one per conversation thread |
| Binds each turn to the user who asked | runner, a Container that holds the sandbox binding |
| Approve and deny buttons | connector, a Container, the only way to private systems |
| Threads in a JSON file | model, a Container that serves the Anthropic Messages API from the deployment's llm AI resource (Bedrock on AWS) |
The control plane talks to the deployment only through commands, so it needs no network path into the customer's cloud. The model runs on Bedrock in the customer's account with the model Container's own identity, so no model key exists anywhere.
The stack
const agent = new alien.Sandbox("agent")
.code(
process.env.SANDBOX_IMAGE
? { type: "image", image: process.env.SANDBOX_IMAGE }
: {
type: "source",
src: "./sandbox",
toolchain: { type: "docker", dockerfile: "Dockerfile" },
},
)
.egress("internet")
// No internet: only the two links. A sandbox the runner creates gets this policy.
.defaultPolicy({ allow: ["link:model", "link:connector"] })
.link(model)
.link(connector)
// A thread's sandbox ends after 8 hours (the AWS ceiling); the router pauses it while idle.
.lifecycle({ maxLifetimeSeconds: 8 * 3600 })
.build()
const runner = new alien.Container("runner")
.code({ type: "source", src: "./runner", toolchain: { type: "typescript" } })
.cpu(0.5)
.memory("512Mi")
.replicas(1)
.commandsEnabled(true)
.environment({ MODEL: process.env.MODEL ?? "claude-sonnet-4-6" })
.link(agent)
.permissions("runner")
.build().egress("internet")puts the sandbox behind the egress gateway, and.defaultPolicy()narrows it to the two links.curl https://example.comfrom inside the sandbox gets a 403 from the gateway.- Only
runnerlinks the Sandbox, so only it can create sandboxes and run commands in them. Its profile grantssandbox/managementandsandbox/execute. - The sandbox image starts Claude Code with
ANTHROPIC_API_KEY=placeholderandCONNECTOR_TOKEN=placeholder. Neither is a real key. - The stack targets
localandaws. On AWS a source-built sandbox must be"live", so release withSANDBOX_LIFECYCLE=live.
Bind each turn to the user
The connector checks a token on every request. Before each turn, the control plane asks the connector for a token for that thread and user, and the runner installs it as a credential rule on the sandbox's connector link:
receiver.command("bind-turn", async input => {
const i = obj(input)
await agent.updateCredentials(str(i, "sandboxId"), [
{ link: "connector", header: "Authorization", valuePrefix: "Bearer ", value: str(i, "token") },
])
return { bound: true }
})The egress gateway now sets Authorization: Bearer <token> on the sandbox's requests to the connector. The call returns once every gateway replica has the rule, so the turn's first request already carries it. The token never enters the sandbox. If the bind fails, the turn doesn't start.
When a different user takes over a thread, the runner first ends every process the previous user's turns left in the sandbox, then binds the new user.
Run a turn
One turn is one Claude Code process, driven over stdin with runInteractive:
const proc = await agent.runInteractive(sandboxId, "claude", {
args,
cwd: WORKSPACE_DIR,
env: await agentEnv(),
timeoutMs: TURN_TIMEOUT_MS,
})
t.stop = () => proc.signal("kill")
const message = { type: "user", message: { role: "user", content: [{ type: "text", text }] } }
await proc.write(`${JSON.stringify(message)}\n`)
// End of input: Claude Code answers the one message, prints its `result` and exits.
await proc.closeStdin()args runs claude -p with stream-json in and out, plus --resume <session id> after the first turn. Claude Code keeps its conversation on disk in the sandbox, so nothing has to stay running between turns. The runner reads the output frames and the control plane long-polls them through a command and streams them to the browser.
When the turn ends, its access ends:
} finally {
// The turn's access ends with the turn, before anything else can start in this thread.
try {
await agent.updateCredentials(sandboxId, [])The connector also revokes the turn's token. A process the agent left running in the background keeps running, but its next call to the connector gets a 401.
Writes wait for approval
The connector lets reads through and holds every write. When the agent runs orders update 1003 --status refunded, the connector holds that HTTP request and lists it in its approvals command, and the UI shows Approve and Deny. The decision goes back through the connector's decide command:
- The approver needs the
orders:approveright indata-plane/connector/src/access.tsand can't be the user who asked. - The write must still belong to a live turn. If the turn ended or another user took over, the approval is refused and the write is never sent.
A key the sandbox never holds
The customer's scanner wants its own API key. The stack declares it as a deployer secret mapped into the connector's environment only:
scannerApiKey: alien.secret({
providedBy: "deployer",
required: true,
label: "Scanner API key",
description: "The key the customer's scanner requires. Read by the connector only.",
env: { name: "SCANNER_API_KEY", targetResources: ["connector"] },
}),The customer writes it into their own secret store. Your control plane, Alien, and the sandbox never see it. The sandbox calls /scanner/findings on its connector link, and the connector adds the key.
For a public API, such as a hosted ticketing service, add the host to the sandbox's egress policy and install a host rule instead. The gateway then adds the key on HTTPS requests to that host. The example doesn't run this path.
Run it locally
You need Docker, Bun, the Alien CLI, and AWS credentials with Bedrock access to the model you use (default claude-sonnet-4-6).
alien init agent-sandboxes agent-sandboxes
cd agent-sandboxes
pnpm install
docker build -t agent-sandboxes-sandbox:dev data-plane/sandbox/Start the data plane in one terminal. alien dev stays in the foreground:
cd data-plane
SANDBOX_IMAGE=agent-sandboxes-sandbox:dev ALIEN_AI_LOCAL_BEDROCK_REGION=us-east-1 \
alien dev --input internalApiUrl=http://internal-api:8080 --input scannerUrl=http://scanner:8081ALIEN_AI_LOCAL_BEDROCK_REGION makes the local llm resource call Bedrock with your own AWS credentials. alien dev prints the deployment id and the values for the control plane.
In a second terminal, store the scanner key, start the stand-in customer services, and start the control plane:
export SCANNER_API_KEY=$(openssl rand -hex 16)
(cd data-plane && printf '%s' "$SCANNER_API_KEY" | \
alien dev vault --deployment <deployment id> set deployer-secrets scanner-api-key --stdin)
docker compose -f customer-network/local/compose.yml up -d --build
ALIEN_MANAGER_URL=<commands url> ALIEN_DEPLOYMENT_ID=<deployment id> ALIEN_TOKEN=<token> \
pnpm control-planeOpen http://localhost:3000 and start a thread. Then try it:
- In the Run in sandbox box, run
env | sort. The only keys are the two placeholders. - Run
curl -m5 https://example.com. The gateway refuses it. - Ask the agent to list the orders. It goes through the connector and works.
- Ask it to refund an order. The write waits until you approve it as
manager. - Switch to
boband ask for a cancellation. The connector answers 403, becausebobcan read orders but not change them.
demo.sh makes the same calls against the control plane's HTTP API, and pnpm test runs the connector, router, and runner tests.
Local sandboxes don't pause, so idle pause and resume show only on AWS. The source's README walks through the AWS deploy: a Terraform network with dedicated sandbox and gateway subnets, then the CloudFormation or Terraform setup into that VPC.
Adapt it to your product
- Your private systems. Replace
customer-network/internal-api/and the routes indata-plane/connector/src/index.ts, and give the agent its own tool in place ofdata-plane/sandbox/orders. - Who may do what.
data-plane/connector/src/access.tsmaps users to actions. Read it from your own user store, and take the approver's identity from your own sign-in. The example has none. - What needs approval. The connector holds every write. Hold only some, or none.
- State. The connector keeps turn tokens and held writes in memory with one replica, and the control plane keeps threads in a JSON file. A connector restart fails the writes that were waiting.
- Users who must share nothing. Ending a previous user's processes is best effort. Give each user their own sandbox instead.
Next
GitHub integration
A full product split into a hosted Next.js dashboard and a small GitHub Worker that runs in each customer's environment, with the GitHub token kept in the customer's vault.
Chat with a private Postgres
A streaming Next.js chat app in the customer's cloud that answers from a private Postgres through a model served by the same cloud. No API keys, no database password in the app.