Running agents safely
The sandbox limits what agent code can reach. These patterns limit what it can do with what it can reach, and make sure you can tell afterwards what happened. None of them needs anything beyond the API and the SDKs; each one takes a few lines.
The examples assume a client vv created as in the tutorial.
Give the agent a key of its own
Section titled “Give the agent a key of its own”Create a key for each agent, or each deployment of one, with only sandboxes:read and sandboxes:write. Keep
audit:read for a reviewer key and org:admin for a key only people use.
- The audit trail’s
actorthen tells you which agent did what. - The agent cannot read or export its own record, and cannot create, change or delete egress policies, so it cannot loosen the rules it runs under.
- If a key leaks, revoke that one. It stops working on its next request and nothing else breaks.
Rate limits apply per key and per organization: 60 write requests and 600 read requests a minute each. Each command and each file write is a write.
An allow-list per task
Section titled “An allow-list per task”Most tasks need a few known destinations: a package index, one API, your own service. Give each kind of task an
allow-list with exactly those, and nothing else leaves the sandbox. Create the policies once, with a key that has
org:admin, and give the agent only their ids.
import { Vivarium } from "@vivarium/sdk";
// Run once, with a key that has the org:admin scope. The agent's own key never needs it.const admin = new Vivarium({ apiKey: process.env.ORG_ADMIN_API_KEY, baseUrl: "https://api.wardcase.com" });
type Rule = { host?: string; cidr?: string; ports?: number[] };async function createPolicy(name: string, rules: Rule[]) { const { data, error } = await admin.raw.POST("/v1/egress-policies", { body: { name, mode: "allowlist", rules }, }); if (error) throw new Error(JSON.stringify(error)); return data;}
const pip = await createPolicy("pip-install", [ { host: "pypi.org", ports: [443] }, { host: "files.pythonhosted.org", ports: [443] },]);const offline = await createPolicy("no-network", []);console.log(pip.id, offline.id); // keep both ids in your agent's configurationimport os
import httpx
API = "https://api.wardcase.com"# Run once, with a key that has the org:admin scope. The agent's own key never needs it.ADMIN = {"Authorization": f"Bearer {os.environ['ORG_ADMIN_API_KEY']}"}
def create_policy(name: str, rules: list[dict[str, object]]) -> dict[str, object]: # The Python SDK has no egress policy helper; this is the REST call. r = httpx.post(f"{API}/v1/egress-policies", headers=ADMIN, json={"name": name, "mode": "allowlist", "rules": rules}) r.raise_for_status() return r.json()
pip = create_policy("pip-install", [ {"host": "pypi.org", "ports": [443]}, {"host": "files.pythonhosted.org", "ports": [443]},])offline = create_policy("no-network", [])print(pip["id"], offline["id"]) # keep both ids in your agent's configuration- List exact hostnames. Hosts refuse a policy with a wildcard rule such as
*.pypi.org; see How host rules match. - An allow-list with no rules leaves name lookups and nothing else, which suits code that needs no network at all.
- If something you listed is blocked, the
egress.connectionevent shows the address the sandbox tried; services behind CDNs can answer with addresses the host did not see. Add acidrrule for them.
Set up with the network, run without it
Section titled “Set up with the network, run without it”A sandbox’s policy is fixed when it is created, but a snapshot carries no policy. So install what the task needs with the package index reachable, snapshot, and run the agent’s code in a new sandbox from that snapshot with no network at all. Whatever the code then tries to reach is blocked and recorded.
// The ids printed when you created the policies.const PIP_POLICY_ID = "pol_...";const NO_NETWORK_POLICY_ID = "pol_...";
// 1. Setup: only the package index is reachable.const setup = await vv.sandboxes.create({ image: "python", region: "eu-west", egressPolicyId: PIP_POLICY_ID });const install = await setup.run("pip install pandas", { timeoutS: 600 });if (install.exitCode !== 0) throw new Error(install.stderr);const deps = await setup.snapshot({ name: "pandas" });await setup.kill();
// 2. The task: the same files, and nothing reachable. Region and image come from the snapshot.const sbx = await vv.sandboxes.create({ snapshotId: deps.id, egressPolicyId: NO_NETWORK_POLICY_ID });const check = await sbx.run("python -c 'import pandas; print(pandas.__name__)'");console.log(check.stdout.trim());pandas# The ids printed when you created the policies.PIP_POLICY_ID = "pol_..."NO_NETWORK_POLICY_ID = "pol_..."
# 1. Setup: only the package index is reachable.setup = vv.sandboxes.create(image="python", region="eu-west", egress_policy_id=PIP_POLICY_ID)install = setup.run("pip install pandas", timeout_s=600)if install.exit_code != 0: raise RuntimeError(install.stderr)deps = setup.snapshot(name="pandas")setup.kill()
# 2. The task: the same files, and nothing reachable. Region and image come from the snapshot.sbx = vv.sandboxes.create(snapshot_id=deps.id, egress_policy_id=NO_NETWORK_POLICY_ID)check = sbx.run("python -c 'import pandas; print(pandas.__name__)'")print(check.stdout.strip())pandasKeep the snapshot and start every later run of the same task from it: the setup cost is paid once.
Snapshot before risky steps
Section titled “Snapshot before risky steps”Before a step that can damage the sandbox’s state, a migration, a mass rename, a command the model is unsure about,
save /work. If the step fails, times out or leaves things in a state you do not trust, destroy the sandbox and
continue in a new one from the checkpoint. Here sbx was created with let in TypeScript so it can be replaced.
// Before a step the model is unsure about, save /work.const checkpoint = await sbx.snapshot({ name: "before-migration" });
const step = await sbx.run("python migrate.py", { timeoutS: 300 });if (step.exitCode !== 0 || step.timedOut) { // Throw the damaged sandbox away and carry on from the checkpoint. await sbx.kill(); sbx = await vv.sandboxes.create({ snapshotId: checkpoint.id, egressPolicyId: NO_NETWORK_POLICY_ID });}# Before a step the model is unsure about, save /work.checkpoint = sbx.snapshot(name="before-migration")
step = sbx.run("python migrate.py", timeout_s=300)if step.exit_code != 0 or step.timed_out: # Throw the damaged sandbox away and carry on from the checkpoint. sbx.kill() sbx = vv.sandboxes.create(snapshot_id=checkpoint.id, egress_policy_id=NO_NETWORK_POLICY_ID)The snapshot saves files, not processes. Take it between steps, when nothing is writing to /work.
Kill on timeout
Section titled “Kill on timeout”Three limits, each for a different failure:
timeoutSon each command (timeout_sin Python) stops one runaway command. The host kills it and the result saystimedOut.idleTimeoutSdestroys the sandbox when your process dies or forgets it. Set it a little longer than the slowest step.hardTimeoutSis the task’s whole budget, enforced by the platform even if nothing else works.
And destroy the sandbox in finally, so a normal end, an error and a timeout all end the same way.
const steps = ["python fetch_data.py", "python analyse.py", "python report.py"];
const sbx = await vv.sandboxes.create({ image: "python", region: "eu-west", idleTimeoutS: 180, // no step leaves it idle this long hardTimeoutS: 1800, // the whole task's budget, enforced even if this process dies});try { for (const command of steps) { const r = await sbx.run(command, { timeoutS: 120 }); if (r.timedOut) { // The host killed the command at 120 s. Stop, rather than let the agent retry blindly. throw new Error(`timed out: ${command}`); } }} finally { await sbx.kill();}steps = ["python fetch_data.py", "python analyse.py", "python report.py"]
sbx = vv.sandboxes.create( image="python", region="eu-west", idle_timeout_s=180, # no step leaves it idle this long hard_timeout_s=1800, # the whole task's budget, enforced even if this process dies)try: for command in steps: r = sbx.run(command, timeout_s=120) if r.timed_out: # The host killed the command at 120 s. Stop, rather than let the agent retry blindly. raise RuntimeError(f"timed out: {command}")finally: sbx.kill()When a command times out, treat what it left behind as suspect. Stopping the task, or continuing from a checkpoint, is usually better than letting the model try the same thing again.
Keep secrets out of command lines
Section titled “Keep secrets out of command lines”The audit trail records the argument list of each command, exactly as it was sent. Environment values passed with env, on
create or on run, reach the sandbox but are never recorded, and the control plane does not store them.
// Recorded in the audit trail as part of the command line. Avoid.await sbx.run(`curl -H "Authorization: Bearer ${token}" https://api.github.com/user`);
// Not recorded: the value travels as an environment variable.await sbx.run('curl -H "Authorization: Bearer $GITHUB_TOKEN" https://api.github.com/user', { env: { GITHUB_TOKEN: token },});# Recorded in the audit trail as part of the command line. Avoid.sbx.run(f'curl -H "Authorization: Bearer {token}" https://api.github.com/user')
# Not recorded: the value travels as an environment variable.sbx.run( 'curl -H "Authorization: Bearer $GITHUB_TOKEN" https://api.github.com/user', env={"GITHUB_TOKEN": token},)Pass a sandbox only the secrets its task needs. Anything inside the sandbox can be read by the agent’s code, and sent to any destination its policy allows; an allow-list is what stops a token from leaving for somewhere else.
Read the audit trail after the task
Section titled “Read the audit trail after the task”Make reading the record part of the task, not something you do after an incident. With a reviewer key, list what the agent ran and what it tried to reach, and keep the JSONL export next to the task’s result.
import { Vivarium } from "@vivarium/sdk";
// A reviewer key with audit:read, separate from the key the agent runs with.const reviewer = new Vivarium({ apiKey: process.env.REVIEWER_API_KEY, baseUrl: "https://api.wardcase.com" });const sandboxId = process.argv[2]; // the sandbox the task ran in
const commands: unknown[] = [];const blocked: Record<string, unknown>[] = [];let cursor: string | undefined;do { const page = await reviewer.audit.list({ sandboxId, cursor }); for (const event of page.data) { if (event.type === "exec.started") commands.push(event.payload.cmd); if (event.type === "egress.connection" && event.payload.action === "block") blocked.push(event.payload); } cursor = page.nextCursor ?? undefined;} while (cursor);
console.log(`${commands.length} commands, ${blocked.length} blocked connections`);for (const b of blocked) console.log("blocked", b.dst_ip, b.dst_port, b.sni ?? b.host ?? "-", b.rule);
// Keep the whole record next to the task's result.const record = await reviewer.audit.export({ sandboxId });console.log(record.eventCount, record.url);import osimport sys
from vivarium import Vivarium
# A reviewer key with audit:read, separate from the key the agent runs with.reviewer = Vivarium(api_key=os.environ["REVIEWER_API_KEY"], base_url="https://api.wardcase.com")sandbox_id = sys.argv[1] # the sandbox the task ran in
commands: list[object] = []blocked: list[dict[str, object]] = []cursor = Nonewhile True: page = reviewer.audit.list(sandbox_id=sandbox_id, cursor=cursor) for event in page.data: if event.type == "exec.started": commands.append(event.payload["cmd"]) if event.type == "egress.connection" and event.payload.get("action") == "block": blocked.append(event.payload) cursor = page.next_cursor if cursor is None: break
print(f"{len(commands)} commands, {len(blocked)} blocked connections")for b in blocked: print("blocked", b["dst_ip"], b["dst_port"], b.get("sni") or b.get("host") or "-", b["rule"])
# Keep the whole record next to the task's result.record = reviewer.audit.export(sandbox_id=sandbox_id)print(record.event_count, record.url)Things worth a flag in the output:
- Any blocked connection. The agent tried to reach something the task did not need. With rule
builtin, it was a private address, the metadata endpoint or a mining pool. - Commands you did not expect, such as network tools in a task that should not need the network.
- Files moved out (
file.get) that the task had no reason to return.
Expose ports only as long as needed
Section titled “Expose ports only as long as needed”expose defaults to token access: only requests that carry the token reach the port. Use public only for
something meant for anyone, and call unexpose when the port is no longer needed. Requests to an exposed port do
not count as activity, so a sandbox that only serves a port is still destroyed at its idle timeout.
When something goes wrong
Section titled “When something goes wrong”- Destroy the sandbox with
kill. - Revoke the agent’s key if it may have leaked, and create a new one.
- Export the sandbox’s audit trail, so the record is fixed in a file.
- Read it as described in Using it after an incident.