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 OpenAI API key, then install the SDK:
Run Codex in a sandbox
This script creates a disk, starts a sandbox with the disk mounted at/workspace, installs Codex, and gives it a task with codex exec, which works until the task is done, prints the final answer, and exits. Then it deletes the sandbox; everything the agent made is on the disk.
npx tsx start.ts or python start.py. Codex prints its progress to standard error and only the final answer to standard output. The wording varies from run to run. One run printed:
Pick up where you left off
Codex’s project and session history are on the disk, so any sandbox that mounts it can resume the session. This script starts a new sandbox on the same disk and runscodex exec resume --last, which resumes the most recent session in /workspace.
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--jsontocodex execto get one JSON event per line. - Work interactively. Start
codexin a pseudo-terminal withsandbox.runand sign in when it asks; see Opening interactive shells.
Use Vercel AI Gateway instead of an OpenAI key
Use Vercel AI Gateway instead of an OpenAI key
Codex can send its requests through Vercel AI Gateway. Export
AI_GATEWAY_API_KEY instead of OPENAI_API_KEY, replace the CODEX_API_KEY line in env with this one, and change codex exec to codex exec -c openai_base_url=https://ai-gateway.vercel.sh/codex/v1 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.
OpenCode
Run OpenCode 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.