Sandbox
Factory steps (and CodeCrucible test runs) execute model-driven or repository-driven code inside a per-job Docker
container. The design premise ("Principle 1") is that with Bash available, nothing inside the container can confine
the agent, so the runner installs no hook and every control sits outside: the container contract, the per-job network,
the gateway, and host-side validation of everything that comes back.
| Component | Path | Role |
|---|---|---|
SandboxRuntime | apps/worker/src/sandbox/sandbox-runtime.ts | worker-side AgentRuntime: registers the job token, creates network, volume, keeper and job container, reads events, tears down |
| Argv contract | apps/worker/src/sandbox/contract.ts | exact docker argv builders and assertSafeArgv |
| Docker CLI | apps/worker/src/sandbox/docker.ts | execFile/spawn with shell: false, argv arrays only |
| Extractor | apps/worker/src/sandbox/extract.ts | host-side tar parsing of untrusted workspace output |
| Test container | apps/worker/src/sandbox/test-run.ts | model-less test run with --network none |
| Runner | apps/sandbox-runner/src/runner.ts, main.ts | runs inside the container: one JSON job spec on stdin, NDJSON events on stdout |
Topology of one attempt
Per-attempt Docker names derive from a validated JobId and an 8-hex nonce (jobNames): network and container
afsbx-<jobId>-<nonce>, volume afsbx-<jobId>-<nonce>-ws, keeper afsbx-<jobId>-<nonce>-keeper. Every object carries
the labels agentforge.job, agentforge.owner, agentforge.instance (<host>-<pid>-<random>, one per process) and
agentforge.started.
Run sequence
Before anything starts, run() refuses: an unknown profile, a factory profile with no role in policyIdsByProfile
(never registered with no policy), a missing jobId, or timeoutMs + ttlMarginMs above MAX_TTL_MS (900 000 ms).
Pre-existing volume or container names refuse the attempt (docker volume create of an existing name would silently
adopt a planted volume, M2).
The job container argv
runArgs builds the exact docker run (plan 4.3, asserted from docker inspect by SB-RUN1):
| Flag | Value | Purpose |
|---|---|---|
-i, --name | afsbx-<jobId>-<nonce> | stdin carries the job spec (never argv) |
--network | the per-job internal network | gateway is the only peer |
--dns | 127.0.0.1 | no resolver path out |
--ipc | private | |
--user | 10001:10001 | non-root |
--read-only | read-only root filesystem | |
--cap-drop | ALL | no capabilities (no CAP_NET_RAW) |
--security-opt | no-new-privileges:true | no setuid escalation |
--pids-limit | 512 | fork bombs |
--memory, --memory-swap | 2g, 2g | no swap beyond memory |
--cpus | 2 | |
--ulimit | nofile=1024:1024 | |
--init, --stop-timeout | 5 | docker-init as PID 1 |
--log-driver | none | job output never lands in Docker logs |
--runtime | runc (default) or runsc | see runtimes below |
--tmpfs | /home/agent:rw,nosuid,nodev,size=256m,uid=10001,gid=10001 | writable HOME |
--tmpfs | /tmp:rw,nosuid,nodev,size=512m | |
--mount | type=volume,src=afsbx-…-ws,dst=/workspace | the per-job tmpfs workspace |
--env-file | a path ending in /env | the only channel for the token |
| command | timeout --signal=KILL <ceil(timeoutMs/1000)+30> node dist/main.js | convenience only, not a control |
The keeper (keeperRunArgs) uses --network none, --read-only, --cap-drop ALL, no-new-privileges, uid 10001,
--pids-limit 64, --memory 256m, --cpus 0.5, --init, --log-driver none, the same runtime and volume, command
sleep infinity. The volume (volumeCreateArgs) is a local tmpfs volume o=size=1g,uid=10001,gid=10001. The network
(networkCreateArgs) is --internal -o com.docker.network.bridge.gateway_mode_ipv4=isolated (no host bridge IPv4
address, so published host ports are not reachable from the job).
KILL_MARGIN_S = 30: the in-container timeout runs as uid 10001 and the job can kill it. The host timer
(timeoutMs, then kill and rm) is the bound and the sweep age is the backstop.
Network: none or one link
| Container | Network | Can reach |
|---|---|---|
| Job container (model run) | per-job --internal network | the gateway's data port only |
| Keeper | none | nothing |
Test container (testRunArgs) | none | nothing; no env file, no token, --workdir /workspace, the repo policy's fixed test argv |
The gateway's control listener is not on the job network, and the control tokens never enter a sandbox, an argv or a log line. Gateway-side network setup for the local shape lives in Sandbox roles.
assertSafeArgv
Every docker call goes through assertSafeArgv(args, testCommand?) before execution. It is defence in depth for T9
("not a boundary": the worker's docker access is host-root-equivalent, OQ-1), and it replaced an earlier denylist (N4)
with an allowlist:
Rules:
- Exact element match.
--flag=value, attached short values (-p8080:80), combined shorthands,--and anything unlisted (--privileged,-v,-p,--entrypoint,--group-add,--cgroup-parent,--add-host,--device,--sysctl,-e, …) are refused. - Verbs and their flags:
run(24 flags: the ones in the table above plus-dand--workdir),exec(-i),inspect(--format),stop(-t),kill,rm(-f),ps(-a,--filter,--format),container inspect,network create(--internal,-o,--label),network connect,network disconnect(-f),network rm,network ls,volume create(--driver,--opt,--label),volume inspect,volume rm(-f),volume ls. - Value checks (
ALLOWED_FLAGS), for example:--useronly10001:10001;--cap-droponlyALL;--runtimeonlyruncorrunsc;--networkonlynoneor anafsbx-name;--nameonlyafsbx-<…>-<8 hex>(optionally-keeper);--labelonlyagentforge.(job|owner|instance|started)=<safe chars>;--mountonly the per-job volume at/workspace;--env-fileonly an absolute path ending in/envwithout..;--tmpfsonly the two exact values;--pids-limit,--memory,--cpusbounded by regex. - Image by digest only. The
runtarget must matchSandboxImageRef(^[a-z0-9][a-z0-9._/-]{0,127}@sha256:[0-9a-f]{64}$); a tag refuses to start (SB-IMG1, checked when the config is parsed). - Commands.
sleep infinity;timeout --signal=KILL <1-4 digits> node dist/main.js;tar -x --no-same-owner -C /workspace -f -;tar -c -C /workspace .; andtar -c -C /workspace/.agentforge/out --no-recursion -- <name>forplan.md,patch.diff,review.json,analysis.json,mutation.json,tests.json. No command element may contain whitespace.
Inside the container: the runner
runJob (apps/sandbox-runner/src/runner.ts) validates input before anything else; on failure it writes one
invalid_request result without detail (the spec and env may hold the prompt or the token) and exits 2.
| Input | Schema |
|---|---|
JobSpec (stdin, strict) | jobId, requestId (1 to 256), prompt (1 to 1 000 000 chars), model (^claude-[a-z0-9.-]{1,64}$), profile, limits.maxTurns (1 to 100), limits.maxBudgetUsd (above 0, at most 10), limits.timeoutMs (1000 to 840 000) |
RunnerEnv (env file) | PATH, ANTHROPIC_BASE_URL (http or https URL), ANTHROPIC_API_KEY (must match the afj_ regex), CLAUDE_CODE_MAX_OUTPUT_TOKENS (1 to 6 digits) |
The SDK env option replaces the process env for the CLI: PATH, HOME=/home/agent, the base URL, the job token,
the output cap, CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1, DISABLE_TELEMETRY=1, DISABLE_ERROR_REPORTING=1,
DISABLE_AUTOUPDATER=1, and the offline pnpm settings. Other SDK options: permissionMode: 'dontAsk',
settingSources: [], persistSession: false, Task always disallowed, maxBudgetUsd advisory only (the gateway
ledger row is the ceiling).
| Profile | Tools | Out file |
|---|---|---|
sandbox-spike | Bash, Read, Glob, Grep, Edit, Write | whole workspace |
factory-planner | Read, Glob, Grep | plan.md |
factory-coder | Bash, Read, Glob, Grep, Edit, Write | patch.diff |
factory-reviewer | Read, Glob, Grep | review.json |
For factory profiles the SDK deadline is timeoutMs - OUT_MARGIN_MS (30 000 ms, minimum 1000) so the runner can still
write the out file. The out directory /workspace/.agentforge/out is deleted and recreated before the model runs (only
what this run writes may leave). The coder commits the base tree first and writes the patch with hardened git: hooks
path /dev/null, fsmonitor off, no system or global config, .git/config replaced and .git/info removed before the
diff (a model-written config could add filters or an external diff), --no-ext-diff --no-textconv. The exit code is 0
only for an SDK success result.
Untrusted output handling
Every byte on the container's stdout is attacker-authored. readEvents enforces:
| Limit | Value | On violation |
|---|---|---|
| total stdout | STDOUT_CAP = 16 MiB | agent_failed "invalid sandbox output" |
| one line | LINE_CAP = 1 MiB | same |
| JSON nesting | MAX_EVENT_DEPTH = 64 | same |
| shape | RuntimeEvent Zod schema, serializable | same |
| stderr | drained up to STDERR_CAP = 1 MiB, never logged | stream destroyed |
The first result line is a claim. The host revokes the token, waits up to EXIT_WAIT_MS (10 000 ms) for the
container to exit, and accepts success only if the claim is success and the exit code is 0. Usage and cost from
the sandbox are always replaced with zero: the gateway's debits are the cost authority. Completion is a host fact:
revoke, container removed, workspace-out awaited, then the terminal result.
Workspace extraction (extract.ts)
The tar stream comes from a volume the job controlled (T14). Two readers:
extractTar(stream, dest, caps): default capsmaxBytes64 MiB andmaxEntries10 000. The whole archive is parsed before anything is written, so a refused archive creates nothing. Only regular files (0,\0) and directories (5) are created; links, FIFOs, devices and unknown types are skipped and reported; absolute paths, backslashes, NUL and..segments are skipped; GNU long names (L) and paxpath=(x) are honoured and then pass the same path check. A truncated entry or a missing two-block end-of-archive marker refuses the archive.destmust not exist (mkdirthrowsEEXIST); files are written with flagwx(fails if anything, including a symlink, exists) and mode0644(no setuid, setgid or exec bits); directories0755.extractOutFile(stream, name, maxBytes)for the single out file of a quality run: exactly one regular-file entry namedname, no prefix field, no pax or GNU long-name headers, at mostQUALITY_OUT_MAX_BYTES(8 MiB), followed by the end marker; anything else is refused. Nothing is written to disk.
tar without -h records a symlink as a link, never its target; the out-file argv uses --no-recursion.
Runtimes: runc and runsc
| Runtime | Isolation | Status |
|---|---|---|
runc (default) | Linux namespaces and cgroups on the host kernel | used locally; shares the kernel with the gateway (real key, DB credential) and the worker (GitHub App key) |
runsc (gVisor) | user-space kernel | accepted by config and argv contract; not available on the local OrbStack VM (probe 0m); VPS probe UNVERIFIED |
The factory config refuses runc unless FACTORY_ALLOW_RUNC=throwaway-repo-only (exact value, M-B); runsc needs no
opt-in. Gate G2-VPS requires a dedicated sandbox host or runsc proven on the VPS before untrusted repositories run.
Kill switch, timeouts and cleanup
| Mechanism | Value |
|---|---|
| Kill-switch poll | killSwitchPollMs, default 2000 (100 to 60 000); a read slower than the interval counts as an error |
| Consecutive read errors that end the job | KILL_SWITCH_MAX_ERRORS = 3 (fail closed) |
| Stop bound | STOP_TIMEOUT_MS = 15 000 |
| Workspace-out bound | workspaceOutTimeoutMs, default 60 000 |
| Env-file dirs | prefix afsbx-env-, deleted once the container runs; leftovers older than ENV_DIR_MAX_AGE_MS (120 000) swept |
| Sweep age | SWEEP_AGE_MS = MAX_TTL_MS + 120 000 = 1 020 000 ms; labelled objects older than this are removed whatever their owner |
The config refine guarantees the longest job plus exit wait, stop bound and workspace-out ends before the sweep age, so a
sweep never removes a keeper still being read. Teardown removes exactly the objects this attempt created, and only a
container confirmed (by inspect of the agentforge.instance label) as this attempt's.
Sources
apps/worker/src/sandbox/contract.ts(SandboxImageRef,SandboxConfig,jobNames,runArgs,keeperRunArgs,networkCreateArgs,volumeCreateArgs,testRunArgs,ALLOWED_FLAGS,VERBS,COMMANDS,assertSafeArgv,KILL_MARGIN_S,SWEEP_AGE_MS)apps/worker/src/sandbox/sandbox-runtime.ts(SandboxRuntime.run,readEvents,LINE_CAP,STDOUT_CAP,STDERR_CAP,KILL_SWITCH_MAX_ERRORS,ENV_DIR_PREFIX)apps/worker/src/sandbox/extract.ts(extractTar,extractOutFile,DEFAULT_CAPS,QUALITY_OUT_MAX_BYTES)apps/worker/src/sandbox/docker.ts(dockerCli),apps/worker/src/sandbox/control.tsapps/sandbox-runner/src/runner.ts(JobSpec,RunnerEnv,sandboxOptions,ROLE_TOOLS,commitBase,writePatch,runJob),apps/sandbox-runner/src/main.tsapps/worker/src/factory/config.ts(FACTORY_ALLOW_RUNC)docs/deploy-sandbox.md,docs/deploy-factory.md,docs/p2-findings.md("0m gVisor runsc", "P3-3 security conditions" M-B).omc/plans/p25-sandbox-spike.mdsections 4.3 to 4.6 and 9