Agent Sandboxes docs · Tasks
Run Claude Code, Codex and OpenCode in a sandbox
Claude Code, Codex and OpenCode are installed in every sandbox. One call gives an agent a prompt, another streams each message and tool call of its turn, and its API key never enters the sandbox: the egress proxy adds it to the agent's requests on the way out.
PromptAgentgives an agent a prompt in a new conversation or an existing one, and waits up to 45 s for its turn: its state and its last message.- Three agents:
CLAUDE_CODE(the default),CODEXandOPENCODE, each driven through its own official SDK, with every permission granted: the sandbox is the boundary. - Signed in by a secret: bind
ANTHROPIC_API_KEYorOPENAI_API_KEYto a workspace secret. OpenCode runs with no key at all. WatchConversationstreams prompts, messages, tool calls with their input and output, and each turn's end.
Step 1: Save the agent's key as a secret
A secret is a value the workspace keeps and no sandbox holds, with the hosts it may be sent to. Set it once, from a program or with the CLI, where the value comes from your own environment, never from a prompt.
import os
sandboxes.set_secret("anthropic", value=os.environ["ANTHROPIC_API_KEY"], hosts=["api.anthropic.com"])
await sandboxes.setSecret({
name: "anthropic",
value: process.env.ANTHROPIC_API_KEY!,
hosts: ["api.anthropic.com"],
});
_, err = client.SetSecret(ctx, &sandboxes.SetSecretRequest{
Name: "anthropic",
Value: os.Getenv("ANTHROPIC_API_KEY"),
Hosts: []string{"api.anthropic.com"},
})
sandboxes
.set_secret(SetSecretRequest {
name: "anthropic".into(),
value: std::env::var("ANTHROPIC_API_KEY")?,
hosts: vec!["api.anthropic.com".into()],
..Default::default()
})
.await?;
$ printf %s "$ANTHROPIC_API_KEY" | pethost sandbox secret set anthropic --host api.anthropic.com
✓ Set the secret anthropic for api.anthropic.com. Bind it: --env <VARIABLE>=secret:anthropic
anthropic
Step 2: Make a sandbox that binds it
Bind the agent's variable to the secret. Inside the sandbox the variable holds a placeholder, phs_…; the egress proxy swaps it for the key in the headers of requests to api.anthropic.com.
from pethost.sandboxes import Environment, EnvVar, SandboxSettings
sandbox = sandboxes.create_sandbox(
"base",
name="agent",
settings=SandboxSettings(
environment=Environment(variables=[EnvVar(name="ANTHROPIC_API_KEY", secret="anthropic")]),
),
)
sandbox_id = sandbox.sandbox_id
const sandbox = await sandboxes.createSandbox({
template: "base",
name: "agent",
settings: { environment: { variables: [{ name: "ANTHROPIC_API_KEY", secret: "anthropic" }] } },
});
const sandboxId = sandbox.sandboxId;
sandbox, err := client.CreateSandbox(ctx, &sandboxes.CreateSandboxRequest{
Template: "base",
Name: "agent",
Settings: &sandboxes.SandboxSettings{Environment: &sandboxes.Environment{Variables: []sandboxes.EnvVar{
{Name: "ANTHROPIC_API_KEY", Source: sandboxes.EnvVarSecret("anthropic")},
}}},
})
if err != nil {
log.Fatal(err)
}
id := sandbox.SandboxID
let key = EnvVar { name: "ANTHROPIC_API_KEY".into(), source: Some(EnvVarSource::Secret("anthropic".into())) };
let sandbox = sandboxes
.create_sandbox(CreateSandboxRequest {
template: "base".into(),
name: "agent".into(),
settings: Some(SandboxSettings {
environment: Some(Environment { variables: vec![key] }),
..Default::default()
}),
..Default::default()
})
.await?;
let id = sandbox.sandbox_id.clone();
$ pethost sandbox new --name agent --env ANTHROPIC_API_KEY=secret:anthropic
✓ Made sandbox agent (kjxa3j9hvg9qmmqe): default, running, from base@17, in <1 s
kjxa3j9hvg9qmmqe
Next: pethost sandbox run kjxa3j9hvg9qmmqe -- <command> · pethost sandbox shell kjxa3j9hvg9qmmqe
CreateSandbox {"name": "agent", "settings": {"environment": {"variables": [{"name": "ANTHROPIC_API_KEY", "secret": "anthropic"}]}}}
Step 3: Give the agent a prompt and follow its turn
PromptAgent with wait_seconds 0 answers once the turn has started. WatchConversation then sends what the agent does as it does it, and the turn as it ended last: its state, its last message (reply, up to 16 KiB) and the tokens it used.
The example asks OpenCode for one of its free models, opencode/big-pickle, so it needs no key; Claude Code and Codex work the same way once their key is bound as a secret: drop model, then also leave out agent for Claude Code, or set it to CODEX for Codex.
from pethost.sandboxes import Agent
turn = sandboxes.prompt_agent(
sandbox_id,
prompt="Write a FizzBuzz in Python in fizz.py, with a test, and run the test.",
agent=Agent.OPENCODE,
model="opencode/big-pickle",
wait_seconds=0,
)
for event in sandboxes.watch_conversation(sandbox_id, conversation_id=turn.conversation_id):
if event.tool_call is not None:
print("tool:", event.tool_call.name)
elif event.message is not None:
print("says:", event.message)
elif event.turn_end is not None and event.turn_id == turn.turn_id:
print(event.turn_end.state.name, event.turn_end.output_tokens, "tokens out")
break
# tool: bash
# tool: write
# tool: write
# tool: bash
# tool: bash
# says: Created `fizz.py` and `test_fizz.py`; `python3 -m unittest test_fizz -v` passes.
# DONE 338 tokens out
const turn = await sandboxes.promptAgent({
sandboxId,
prompt: "Write a FizzBuzz in Python in fizz.py, with a test, and run the test.",
agent: Agent.OPENCODE,
model: "opencode/big-pickle",
waitSeconds: 0,
});
for await (const event of sandboxes.watchConversation({ sandboxId, conversationId: turn.conversationId })) {
if (event.event === "toolCall") console.log("tool:", event.toolCall.name);
if (event.event === "message") console.log("says:", event.message);
if (event.event === "turnEnd" && event.turnId === turn.turnId) {
console.log(event.turnEnd.state, event.turnEnd.outputTokens, "tokens out");
break;
}
}
turn, err := client.PromptAgent(ctx, &sandboxes.PromptAgentRequest{
SandboxID: id,
Prompt: "Write a FizzBuzz in Python in fizz.py, with a test, and run the test.",
Agent: sandboxes.AgentOpencode,
Model: "opencode/big-pickle",
WaitSeconds: new(uint32(0)),
})
if err != nil {
log.Fatal(err)
}
events := client.WatchConversation(ctx, &sandboxes.WatchConversationRequest{SandboxID: id, ConversationID: turn.ConversationID})
watch:
for event, err := range events {
if err != nil {
log.Fatal(err)
}
switch e := event.Event.(type) {
case sandboxes.AgentEventToolCall:
fmt.Println("tool:", e.Name)
case sandboxes.AgentEventMessage:
fmt.Println("says:", string(e))
case sandboxes.AgentEventTurnEnd:
if event.TurnID == turn.TurnID {
fmt.Println(e.State, e.OutputTokens, "tokens out")
break watch
}
}
}
let turn = sandboxes
.prompt_agent(PromptAgentRequest {
sandbox_id: id.clone(),
prompt: "Write a FizzBuzz in Python in fizz.py, with a test, and run the test.".into(),
agent: Agent::Opencode,
model: "opencode/big-pickle".into(),
wait_seconds: Some(0),
..Default::default()
})
.await?;
let mut events = sandboxes.watch_conversation(WatchConversationRequest {
sandbox_id: id.clone(),
conversation_id: turn.conversation_id.clone(),
..Default::default()
});
while let Some(event) = events.next().await {
let event = event?;
match event.event {
Some(AgentEventEvent::ToolCall(call)) => println!("tool: {}", call.name),
Some(AgentEventEvent::Message(text)) => println!("says: {text}"),
Some(AgentEventEvent::TurnEnd(end)) if event.turn_id == turn.turn_id => {
println!("{:?} {} tokens out", end.state, end.output_tokens);
break;
}
_ => {}
}
}
$ pethost sandbox agent agent --agent opencode --model opencode/big-pickle 'Write a FizzBuzz in Python in fizz.py, with a test, and run the test.'
opencode · conversation dk5p1kaxc1mj
› bash: ls -la /home/user
› write: def fizzbuzz(n): if n % 15 == 0: return "FizzBuzz" if n % 3 == 0: return "Fizz" if n % 5 == 0: retur…
› write: import unittest from fizz import fizzbuzz, fizzbuzz_sequence class FizzBuzzTest(unittest.TestCase): …
› bash: python3 -m unittest -v test_fizz.py
Running the test with Python's standard `unittest` runner.
Created `fizz.py` and `test_fizz.py`. Tests passed: 2/2 via `python3 -m unittest -v test_fizz.py`.
done · opencode · conversation dk5p1kaxc1mj · 33k tokens in, 1.1k out
Step 4: Go on in the same conversation
Send the turn's conversation_id with the next prompt, and the agent goes on with what it knows. A conversation runs one turn at a time: a prompt sent while one runs is QUEUED behind it. GetAgentTurn waits for a turn again, up to 45 s a call, and StopAgentTurn ends one now.
from pethost.sandboxes import AgentTurnState
next_turn = sandboxes.prompt_agent(sandbox_id, prompt="Now make it read n from argv.", conversation_id=turn.conversation_id)
while next_turn.state in (AgentTurnState.QUEUED, AgentTurnState.RUNNING):
next_turn = sandboxes.get_agent_turn(sandbox_id, turn_id=next_turn.turn_id)
print(next_turn.state.name, next_turn.reply)
# DONE `fizz.py` now reads `n` from `sys.argv[1]`; tests pass and CLI works (`python3 fizz.py 15` → `FizzBuzz`).
let nextTurn = await sandboxes.promptAgent({
sandboxId,
prompt: "Now make it read n from argv.",
conversationId: turn.conversationId,
});
while (nextTurn.state === AgentTurnState.QUEUED || nextTurn.state === AgentTurnState.RUNNING) {
nextTurn = await sandboxes.getAgentTurn({ sandboxId, turnId: nextTurn.turnId });
}
console.log(nextTurn.state, nextTurn.reply);
next, err := client.PromptAgent(ctx, &sandboxes.PromptAgentRequest{
SandboxID: id,
Prompt: "Now make it read n from argv.",
ConversationID: turn.ConversationID,
})
for err == nil && (next.State == sandboxes.AgentTurnStateQueued || next.State == sandboxes.AgentTurnStateRunning) {
next, err = client.GetAgentTurn(ctx, &sandboxes.GetAgentTurnRequest{SandboxID: id, TurnID: next.TurnID})
}
if err != nil {
log.Fatal(err)
}
fmt.Println(next.State, next.Reply)
let mut next = sandboxes
.prompt_agent(PromptAgentRequest {
sandbox_id: id.clone(),
prompt: "Now make it read n from argv.".into(),
conversation_id: turn.conversation_id.clone(),
..Default::default()
})
.await?;
while matches!(next.state, AgentTurnState::Queued | AgentTurnState::Running) {
let ask = GetAgentTurnRequest { sandbox_id: id.clone(), turn_id: next.turn_id.clone(), ..Default::default() };
next = sandboxes.get_agent_turn(ask).await?;
}
println!("{:?} {}", next.state, next.reply);
$ pethost sandbox agent agent --conversation dk5p1kaxc1mj 'Now make it read n from argv.'
opencode · conversation dk5p1kaxc1mj
› read: /home/user/fizz.py
› read: /home/user/test_fizz.py
› edit: /home/user/fizz.py
› edit: /home/user/fizz.py
› edit: /home/user/test_fizz.py
› edit: /home/user/test_fizz.py
› bash: python3 -m unittest -v test_fizz.py
› bash: python3 fizz.py 5
`fizz.py` now reads `N` from argv via `main()` (fizz.py:19). `python3 fizz.py 5` prints `1, 2, Fizz, 4, Buzz`. Tests: 3/3 passed.
done · opencode · conversation dk5p1kaxc1mj · 61.4k tokens in, 1.6k out
The three agents
| Agent | agent | Signs in with | A model's name |
|---|---|---|---|
| Claude Code | CLAUDE_CODE, the default | ANTHROPIC_API_KEY, or claude auth login | claude-opus-5-5 |
| Codex | CODEX | OPENAI_API_KEY, or codex login --device-auth | gpt-6.1 |
| OpenCode | OPENCODE | Nothing: its own free models, or a provider's key | anthropic/claude-opus-5-5 |
A new conversation takes agent (absent is Claude Code), model as that agent names its models (absent is the agent's default) and cwd, its working directory (absent is /home/user). Each agent runs through its own SDK with every permission granted, Claude Code with bypassPermissions, Codex with full access and no approvals, OpenCode with every tool allowed: nothing asks you to approve a command, because the sandbox, a VM of its own, is the boundary. The CLIs are on the PATH too, as claude, codex and opencode, for a person in a terminal.
Signing an agent in
- A secret bound to its variable, as above: the key stays in the workspace, and the proxy adds it to the agent's requests to the secret's hosts. A new value works at once. Secrets and egress says how the swap works.
- A login in the terminal: a person opens the sandbox's terminal and runs
claude auth loginorcodex login --device-auth. The login is kept on the sandbox's disk, like any file. - No sign-in, with OpenCode: with no provider's key it uses OpenCode's own free models.
A prompt to an agent that cannot reach its model is refused with FAILED_PRECONDITION and AgentSignIn, which names the variable to bind (variable) and the command a person can run instead (sign_in_command).
Turns, and what outlives them
A turn is QUEUED behind the conversation's running turn, RUNNING, then DONE, FAILED (failure_message says why) or STOPPED by StopAgentTurn; LOST when the sandbox lost its memory while it ran. When a turn ends, the agent and its helpers end with it, but what its commands left running in the background, a dev server say, runs on. A turn keeps the sandbox awake while it runs.
A conversation's history is on the sandbox's disk: a pause keeps it, a fork carries it into every copy, so each copy can go on from the same point. A template does not: sandboxes from it start with no conversation. ListConversations lists a sandbox's conversations with the tokens each has used, and the console's Agents tab shows them as they run.
What an agent writes, reads and runs comes from the code and the pages it works on: show its messages and tool output as data, never as instructions to your own model.
When it does not work
FAILED_PRECONDITIONwithAgentSignIn: no key reaches the agent's model. Bindvariableto a secret withUpdateSandbox(the environment applies to processes started after), have a person runsign_in_command, or use OpenCode.- The turn FAILED at once with a 403 from the model's host: the sandbox's egress does not allow that host, or the secret's hosts do not name it. Add
api.anthropic.comorapi.openai.comto both. - The turn stays QUEUED: another turn of the conversation is running. Wait for it, stop it, or start a new conversation.
- The turn is LOST: the sandbox stopped while it ran, or its server ran out of memory. Resume the sandbox and prompt again; the files the agent wrote before are on its disk.
INVALID_ARGUMENToncwd: an existing conversation keeps the directory it began in. Leavecwdout, or start a new conversation.
Questions
Which coding agents can run in a sandbox?
Claude Code, Codex and OpenCode, all three installed in base, each driven through its own official SDK.
Does my API key enter the sandbox?
Not when it is a bound secret: the sandbox holds a placeholder, and the egress proxy puts the key into requests to the secret's hosts only.
Can I run a coding agent without an API key?
Yes, OpenCode: with no provider's key it uses OpenCode's own free models.
Does the agent ask before running commands?
No. Every permission is granted, because the sandbox is a VM of its own with nothing of yours inside but what you put there. Narrow its egress for untrusted work.
Do conversations survive a pause?
Yes, and a fork carries them into every copy. A template does not keep them.
Try Pethost Agent Sandboxes
A 7-day trial with $1 of usage and 4 vCPUs, with a card. Then a plan from $20 a month, which includes as much usage.