Prerequisites
Export your Archil API key, a region where sandboxes are available (aws-us-east-1, aws-us-west-2, or aws-eu-west-1), and an Anthropic API key, then install the SDK:
Run OpenCode in a sandbox
This script creates a disk, starts a sandbox with the disk mounted at/workspace, installs OpenCode, and gives it a task with opencode run, which works until the task is done, prints the result, and exits. Then it deletes the sandbox; everything the agent made is on the disk.
npx tsx start.ts or python start.py. The agent’s wording varies from run to run. One run printed:
Pick up where you left off
OpenCode’s project and session history are on the disk, so any sandbox that mounts it can continue the session. This script starts a new sandbox on the same disk and runsopencode run --continue, which continues the most recent session.
Going further
- Stream output. Pass
onOutput: ({ data }) => process.stdout.write(data)toexec(in Python,on_output=lambda out: sys.stdout.buffer.write(out.data)) to watch the agent as it works. Add--format jsontoopencode runto get one JSON event per line. - Work interactively. Start
opencodein a pseudo-terminal withsandbox.run; see Opening interactive shells. - Run the OpenCode server.
opencode serveruns OpenCode as an HTTP server that the OpenCode terminal UI (opencode attach) and the OpenCode SDK connect to. Run it as a sandbox service so it keeps running and restarts with the sandbox. SetOPENCODE_SERVER_PASSWORDon the server, and reach it with a port token, or with a public port if you useopencode attach, which can’t send the token header.
Use Vercel AI Gateway instead of an Anthropic key
Use Vercel AI Gateway instead of an Anthropic key
OpenCode has a built-in Vercel AI Gateway provider,
vercel, that reads AI_GATEWAY_API_KEY. Export AI_GATEWAY_API_KEY instead of ANTHROPIC_API_KEY, replace the ANTHROPIC_API_KEY line in env with this one, and change --model anthropic/claude-sonnet-5 to --model vercel/anthropic/claude-sonnet-5 in both scripts. On the Developer plan, sandboxes can’t reach the gateway, because it isn’t on the managed allowlist; use your provider key instead.Clean up
Each script deletes its sandbox when it finishes, so only the disk is left. Delete it:Next steps
Claude Code
Run Claude Code headlessly in a sandbox.
OpenAI Codex
Run the Codex CLI headlessly in a sandbox.
Coding agent in a sandbox
Build your own coding agent with the AI SDK instead.
Persistent sandboxes
Lifecycle, services, network access, and forking in detail.