Agents¶
@app.agent declares a task whose sandbox
runs a coding agent: its sandbox comes from the kit of the agent, the keys of
the agent found in the environment go to the proxy of that sandbox only, the
hosts the agent needs are allowed by its kit along with the network rules of
the task, and the task drives the agent through ctx.agent. This page covers
the declaration, the agents there are, their keys, and the three ways to run
an agent from a task.
In a hurry?
The quickstart runs an agent in five minutes, and the Agent sandboxes pages answer the questions of a real setup, one page each: its repository, its network, following its work, its tools, several agents at once.
An agent task¶
from pathlib import Path
from typing import Annotated
from pydantic import BaseModel
from fastsandbox import Context, FastSandbox, Network, WorkspaceDir
app = FastSandbox("agents")
class Report(BaseModel):
passed: bool
summary: str
@app.agent("claude", network=Network.deny("example.org"), timeout="20m")
async def fix_bug(
ctx: Context,
repo: Annotated[Path, WorkspaceDir()],
issue: str,
command: str = "make test",
) -> Report:
"""Has Claude Code fix an issue, then checks the fix with the tests."""
await ctx.agent.prompt(f"{issue}\n\nFix it, then run `{command}` to confirm.")
# The agent says the tests pass; the tests decide.
check = await ctx.sandbox.exec(command, working_dir=str(repo.resolve()))
return Report(passed=check.ok, summary=(check.stdout + check.stderr)[-500:])
@app.agent("claude", ...)takes the agent first, then the options of@app.task(see Tasks), with the kit of the agent as the default kit, andmcp, the MCP servers registered in the agent (see Connect MCP tools). It is always called:@app.agent("claude"), never bare. TheTaskit returns has theAgentintask.agent.ctx.agent.prompt(...)runs the agent once on a prompt, without a terminal, and waits for it to end.- The task then checks the work itself, with the tests of the project: what the agent reports is not a result.
Run it as any task, here on the current directory, which the agent edits in
place (WorkspaceDir(); Working with repositories
gives it a clone instead):
export ANTHROPIC_API_KEY=sk-ant-... # not needed with a Claude subscription
fastsandbox run docs_src/agents/fix_bug.py fix_bug --repo . --issue "the parser drops the last line"
With a Claude subscription, leave ANTHROPIC_API_KEY unset: Claude Code uses
the subscription Docker Sandboxes holds (see the
quickstart and Keys).
The agents¶
The agents are those sbx knows, by the name of their kit, an
Agent or its name; another name, or shell, raises
TaskError when the task is declared. Their
profiles are those of docker-sandbox-kit, written once from the documentation
of each agent: the keys each takes (Agent.keys), the
variables it reads in clear (Agent.forwarded_env),
and its unattended run (Agent.headless()).
| Agent | Credentials read from the environment | Output of an unattended run |
|---|---|---|
claude |
ANTHROPIC_API_KEY |
JSON lines |
codex |
OPENAI_API_KEY, else CODEX_API_KEY |
JSON lines |
copilot |
COPILOT_GITHUB_TOKEN, else GH_TOKEN, else GITHUB_TOKEN |
Text |
cursor |
CURSOR_API_KEY |
JSON lines |
devin |
DEVIN_API_KEY |
Text |
docker-agent |
The keys of the model providers, below | Text |
droid |
FACTORY_API_KEY |
JSON lines |
kiro |
None: KIRO_API_KEY is given to the agent process |
Text |
opencode |
The keys of the model providers, below | Text |
The keys of the model providers, each given when it is set, are
ANTHROPIC_API_KEY, OPENAI_API_KEY, GEMINI_API_KEY (else
GOOGLE_API_KEY), OPENROUTER_API_KEY, GROQ_API_KEY, MISTRAL_API_KEY,
NEBIUS_API_KEY and XAI_API_KEY.
What each agent supports¶
What fastsandbox builds and checks for each agent, and what was seen on a real daemon. Yes is verified by the tests of fastsandbox or the audit of the daemon; No is refused by the code; Not verified is neither.
| Agent | Key held by the proxy | Unattended and streamed | Interactive session | MCP servers of the task | Registers the MCP gateway |
|---|---|---|---|---|---|
claude |
Yes; or a Claude subscription held by the daemon | Yes | Yes | Yes | Yes |
codex |
Yes | Yes | Not verified | No | Not verified |
copilot |
Yes, when its kit declares the service of its key | Yes | Not verified | Yes | Yes |
cursor |
Yes | Yes | Not verified | No | Not verified |
devin |
Yes | Yes | Not verified | No | Not verified |
docker-agent |
Yes | Yes | Not verified | No | Not verified |
droid |
Yes | Yes | Not verified | No | Not verified |
kiro |
No: its key is a variable of the sandbox, in clear | Yes | Not verified | No | Not verified |
opencode |
Yes | Yes | Not verified | Yes | Yes |
The unattended command of every agent is built and checked against the fake
daemon; an interactive session takes the same route of the daemon for every
agent, and is tested for claude. No test of fastsandbox runs a real agent:
how each one behaves on a real daemon, its sign-in included, is the work of
its kit and of its maker. The kit of an agent also declares the hosts it
reaches; for claude, the services of Anthropic, its downloads and the
Debian package mirror, as of sbx v0.54.1.
Keys¶
The socket of the daemon never reads the secrets stored with sbx secret set:
the keys of a sandbox are given to it. The sandbox of each run is launched from
a sandbox spec that names the keys its agent
takes, as the profile of the agent says
(Agent.keys), each optional, whatever its kit:
the kit of the agent, an image, a package or a kit the CLI compiled. The
values found in the environment of the calling process go to the proxy of that
sandbox, and of that sandbox only:
- The sandbox holds a placeholder in the variable the agent reads its key from;
the proxy writes the key in its place in the requests to the hosts the kit
declares for its service. The agent never sees the key, though it can use
it through the placeholder while the sandbox lives, and the key goes with
the sandbox when the run ends.
kirois the exception:sbxknows no service for it, so its key is a variable of the sandbox, in clear. - A key given this way does not depend on the daemon authorizing the credential the kit declares: it reaches the agent all the same.
- A key whose service no kit of the sandbox declares has nowhere to go, and is left out; one that is not set is left out too.
- When none is set, the credential the daemon holds for the kit of the agent
applies, a subscription for instance, as it does to every sandbox of that
kit, when the daemon authorizes it: it is your own account, shared by those
sandboxes. A Claude subscription signed in under
sbxis one:claudeneeds noANTHROPIC_API_KEYthen (see the quickstart). One it withholds gets nothing from the proxy (see Withheld credentials): the run logs a warning naming those it withholds, on the logger of the task,fastsandbox.task.<name>, since the agent would fail later without saying why.
The report of the launch, ctx.lease.report, names the keys given and those
left out, with the reason, never their values (see
Tasks).
kiro has no service in sbx: KIRO_API_KEY, when set, is given to the
sandbox as a variable, and to the agent process that prompt and stream
start; its value is visible inside the sandbox.
The network of an agent¶
The kit of an agent declares the hosts it needs, which its sandbox is allowed
from its creation. The rules of network come with them (see
Network rules). The default policy of sbx may allow every
host, depending on how it was set up: an allowance then restricts nothing, and
a refusal is what keeps the agent from a host.
Running the agent¶
The task reaches the agent through ctx.agent, an
AgentRunner; a parameter annotated
AgentRunner receives the same object. In a task declared with @app.task,
ctx.agent raises TaskError. The runner holds the sandbox, the Agent
(agent, Agent.CLAUDE for instance, whose value, "claude", is the name
of the runner) and the
KitAgent its kit declares (kit_agent): the program
and the options its sessions start it with, which the profile builds on. A
program that drives an agent outside a task builds one the same way,
AgentRunner(sandbox, Agent.CLAUDE, kit_agent), with the KitAgent the
package or the lease of its sandbox gives (package.agent, lease.agent).
One prompt, unattended¶
prompt(prompt, *, timeout, working_dir, env)
runs the agent on one prompt, with the command its profile gives for an
unattended run, and returns an AgentRun:
exit_code, andokwhen it is 0;stdoutandstderr, as text;events, the JSON lines ofstdoutparsed, for the agents whose output is JSON lines.
timeout bounds how long the task waits for the agent, and raises
SandboxTimeoutError when it is
over, whose after is that deadline; uncaught, it leaves the task as it is,
not as the timeout of the task (see Timeouts). It does
not stop the agent, which goes on until it ends or its sandbox is removed:
see Timeouts and cancellation.
working_dir defaults to the working directory of the sandbox.
The command is the one the profile builds, as
Agent.headless(kit_agent, prompt) gives it, a
Headless with the command and its output, jsonl or
text. For most agents, it is the program and the run options the kit
declares, followed by the arguments of the profile. codex, droid and
opencode start with a subcommand instead, which takes the options it needs
in place of the run options of the kit: codex exec …, droid exec …,
opencode run --auto …, the program being the one the kit declares, or else
the name of the agent. A kit that declares no program for an agent whose
command starts with the run options makes prompt, stream and command
raise TaskError.
command(prompt) returns the command
without running it:
from fastsandbox import AgentRunner, FastSandbox, Network
app = FastSandbox("agents")
@app.agent("claude", network=Network.allow("pypi.org"))
async def show_command(agent: AgentRunner, prompt: str) -> list[str]:
"""The command `agent.prompt(prompt)` would run, without running it."""
return agent.command(prompt)
For claude, it is claude --dangerously-skip-permissions -p <prompt>
--output-format stream-json --verbose: the run options of the kit let the agent
edit files and run commands without asking. The sandbox contains what it
does, within what the task gives it: a read-write workspace, the hosts the
policy allows, the keys the proxy writes (see the
security model).
Following what it does¶
stream(prompt, *, working_dir) runs the
same command and yields what the agent writes on its standard output as it
comes, a line at a time: parsed JSON values for the agents whose output is JSON
lines, text lines otherwise. Unlike prompt, it has no timeout of its own,
and no env: the timeout of the task bounds it when the task declares one,
none by default, and the agent process gets the variables its profile
forwards, as with prompt. Leaving the loop early stops the reading, not the
agent, which stops when its sandbox is removed.
from pathlib import Path
from typing import Annotated
from fastsandbox import Context, FastSandbox, Network, WorkspaceDir
app = FastSandbox("reviews")
@app.agent("claude", network=Network.deny("example.org"), timeout="30m")
async def review(ctx: Context, repo: Annotated[Path, WorkspaceDir()]) -> str:
"""Has Claude Code review a project, logging each step it reports."""
prompt = "Review this project and list its three main risks."
summary = ""
async for event in ctx.agent.stream(prompt, working_dir=str(repo.resolve())):
if not isinstance(event, dict):
continue
ctx.log(f"agent event: {event.get('type')}")
if event.get("type") == "result" and isinstance(event.get("result"), str):
summary = event["result"]
return summary
The events are those of the agent; the stream of Claude Code ends with an event
of type result, which holds its final answer.
An interactive session¶
session(*args, tty=True, size=None) starts
the agent as sbx run does, in an interactive session: an
Interactive to write to and read from, for a
program that relays a terminal or drives the agent itself. args are passed
to the agent, as after sbx run AGENT --. See
Interactive sessions.
Choosing the kit¶
The kit of an agent task is the kit of the agent. kit= replaces it with a
composition of that kit, for instance with kit arguments, which select what
the kit declares, such as the model of claude:
Each composition is forged once and kept apart (see
Kits), and keeps the keys of the agent; a mixin composed
this way adds install commands or hosts to the kit of the agent. The kit must
describe an agent: one that does not makes the run raise TaskError.