Skip to content
Wardcase Docs

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.

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 actor then 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.

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.

policies.mts
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 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.connection event shows the address the sandbox tried; services behind CDNs can answer with addresses the host did not see. Add a cidr rule for them.

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.

two-phase.mts
// 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());
Output
pandas

Keep the snapshot and start every later run of the same task from it: the setup cost is paid once.

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 });
}

The snapshot saves files, not processes. Take it between steps, when nothing is writing to /work.

Three limits, each for a different failure:

  • timeoutS on each command (timeout_s in Python) stops one runaway command. The host kills it and the result says timedOut.
  • idleTimeoutS destroys the sandbox when your process dies or forgets it. Set it a little longer than the slowest step.
  • hardTimeoutS is 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.

task.mts
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();
}

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.

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 },
});

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.

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.

review.mts
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);

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 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.

  1. Destroy the sandbox with kill.
  2. Revoke the agent’s key if it may have leaked, and create a new one.
  3. Export the sandbox’s audit trail, so the record is fixed in a file.
  4. Read it as described in Using it after an incident.