A coding agent is only useful when it can run code. It needs to execute the tests, reproduce the bug, install a dependency, and check its own fix. The moment it can do that, it also runs whatever the repository contains: a conftest.py, a build script, a package's install hook, and every command the model decides to type.
Most local setups run that code with your user account, your environment variables, your network, and your files. A prompt injection hidden in a README or an issue comment then has the same reach as you. Better prompts do not fix this. The fix is to decide where code runs, what that place can reach, and who decides when the work is finished.
In Issue #52, the harness ran candidate code in a temporary directory and said plainly that it was not a security sandbox. This issue builds that sandbox. We take a Python coding agent driven by Microsoft Agent Framework and a Foundry model, give it a real shell, and run every command it chooses inside a disposable Docker container. Then we attack it with nine scripted cases and fix what they find.
What You Are Building
The companion repository is a small background coding agent. You give it a repository and a ticket. It works without supervision and hands back a patch, or a clear reason why it could not produce one.
The system has five parts:
- A host process that runs the Agent Framework loop and holds the Foundry credential.
- A harness that validates every tool call, applies path rules and budgets, and records evidence.
- A task sandbox: a hardened container per run where every command executes.
- An egress proxy: the sandbox network's only exit, allowing PyPI and nothing else.
- A verifier: a fresh container with no network that applies the patch to a clean copy and runs the original tests.
The sample ticket is real and small. A shop charges £4.99 delivery on an order of exactly £50, although free delivery starts at £50 inclusive. Amounts are integer pence. The bug is one comparison operator, which keeps attention on the execution boundary rather than on the fix.
Where Should the Agent Live?
The first design question is what goes inside the container. The intuitive answer is "the whole agent". That is what you do with tools you cannot split, such as a vendor CLI agent, and products like Docker Sandboxes exist for that case. When you own the agent, there is a stronger option.
Separate the agent into its three pieces. The model runs in Foundry and never executes anything; it only returns text. The loop sends context, receives tool calls, counts budgets, writes the log, and decides when the run is done. Tool execution runs commands and the repository's code. Only the third piece runs untrusted code, so only it needs to be inside the box.
The diagram follows one malicious conftest.py, which pytest imports automatically. With the agent inside, that file shares a process space and environment with the model key, the trace, and the code that reports success. With the loop on the host, it finds no credentials and no route out, and the worst it can do is damage a container we delete anyway. The rule that follows: the agent's work runs in the container; its keys, its records, and its verdict stay outside.
System Structure
The trusted side is a Python process on the host. The untrusted side is two kinds of container: one task sandbox per run, and one verifier per finish attempt. The proxy and the networks are long-lived and started once with Docker Compose.
Every arrow into a container goes through the policy gate. The model never talks to Docker directly; it proposes an action, and the harness decides whether and how that action runs.
Runtime Configuration First
All settings live in config/agent.json, with SBXA_SECTION__KEY environment overrides. The model section points at a Foundry deployment of gpt-5.1-codex-mini, which is tuned for coding agents, supports function calling, and is served through the Responses API. Authentication uses az login by default. Key authentication reads the key from an environment variable, and the config refuses anything that looks like a key in the field that should hold the variable's name.
{
"foundry": {
"endpoint": "https://YOUR-RESOURCE.services.ai.azure.com/",
"deployment": "gpt-5.1-codex-mini",
"auth": "entra",
"api_key_env": "SBXA_FOUNDRY_API_KEY"
},
"budgets": {
"max_steps": 30,
"max_seconds": 600,
"command_timeout_seconds": 120,
"max_output_bytes": 16000,
"max_finish_attempts": 2
},
"sandbox": {
"image": "sbxa-sandbox:1",
"isolation": "container",
"network": "sbxa-internal",
"memory": "1g",
"cpus": 1,
"pids_limit": 256
}
}The endpoint accepts a resource root, an /openai/v1 base URL, or a full /responses URL, and normalizes all three. That small detail matters, because the portal shows several formats and a wrong one fails only at the first model call. The whole config is also copied into each run's manifest, which is one more reason the key must never be in it.
Start the infrastructure, check it, and run the agent:
docker compose --profile build build
docker compose up -d
.venv/Scripts/sandboxed-agent doctor
.venv/Scripts/sandboxed-agent run --task fixtures/tasks/free-delivery.jsonThe doctor command checks the Docker engine, the sandbox image, the proxy, the Foundry settings, and one property that is easy to get wrong silently: that the sandbox network is actually marked internal.
Building the Sandbox Container
The image is python:3.13-slim with git, ripgrep, and pytest, and a non-root user with UID 10001. Its main process is sleep infinity: the container idles, and every agent command is added to it with docker exec. The hardening lives in the run options, where it is visible in one place:
container = client.containers.run(
image=cfg.image,
detach=True,
init=True, # docker-init reaps zombies as PID 1
user="10001:10001",
working_dir="/workspace",
volumes={volume.name: {"bind": "/workspace", "mode": "rw"}},
read_only=True, # root filesystem cannot be modified
tmpfs={"/tmp": "size=256m,mode=1777"},
cap_drop=["ALL"],
security_opt=["no-new-privileges:true"],
mem_limit="1g", memswap_limit="1g",
nano_cpus=1_000_000_000,
pids_limit=256,
network="sbxa-internal",
environment={"HTTPS_PROXY": "http://proxy:3128", "HTTP_PROXY": "http://proxy:3128"},
)Each line closes a specific path. A read-only root with writable /workspace and /tmp means the agent can change the repository but cannot install anything into the system. Dropping all capabilities and forbidding new privileges stops setuid escalation. Memory, CPU, and PID limits turn resource attacks into failed commands instead of a frozen machine. The environment contains the proxy address and nothing else: no model key, no token, and no host variables.
The repository enters the container as a tar archive owned by UID 10001, and the container commits a git baseline on its side. The host never runs git on files the agent has touched. A repository can carry hooks and config that execute code whenever git runs, so git stays inside the box and only the diff text comes out.
One Way Out of the Network
A coding agent usually needs packages, so "no network" is too strict for the task sandbox. The sandbox joins a Docker network marked internal: true, which has no default route. The only other member is a Squid proxy, which is also attached to a normal network.
networks:
internal:
name: sbxa-internal
internal: true # no default route: containers here can reach only the proxy
egress:
name: sbxa-egressacl allowed_hosts dstdomain pypi.org files.pythonhosted.org
acl SSL_ports port 443
acl CONNECT method CONNECT
http_access deny CONNECT !SSL_ports
http_access allow allowed_hosts
http_access deny allCode that respects HTTPS_PROXY reaches PyPI and receives a 403 for everything else. Code that ignores the proxy and opens a socket directly gets "Network is unreachable", because the route does not exist. Every proxy decision is logged, and the host stores the lines that belong to each run as egress.log. An allowlist this broad is still a supply-chain surface; for repositories that need no installs, remove PyPI and run with no exit at all.
Every Command Through One Door
Everything the agent does reaches the container through one method, which calls the Docker exec API. Each command is wrapped in timeout, runs in bash, merges stderr into stdout, and is cut off by head inside the container, so a flood of output never reaches host memory:
_SHELL_WRAPPER = 'bash -c "$0" 2>&1 | head -c "$1"; exit "${PIPESTATUS[0]}"'
wrapped = ["timeout", "-k", "5", str(timeout), "bash", "-c", _SHELL_WRAPPER, command, str(max_bytes + 1)]
exec_id = api.exec_create(container.id, cmd=wrapped, user="10001:10001", workdir="/workspace")["Id"]
for chunk in api.exec_start(exec_id, stream=True):
... # keep at most max_bytes
exit_code = api.exec_inspect(exec_id)["ExitCode"]The exit code is reported honestly. 124 means the command timed out. 137 means SIGKILL, most often from the out-of-memory killer, so the model is told "out of memory or time limit" instead of a misleading timeout.
The first test run exposed a gap that a timeout does not close. A fork bomb is a command that keeps copying itself, and ours started its copies in the background. The command returned immediately, so the timeout saw nothing wrong, but the copies kept running. They used up the container's 256 process slots, and every later command failed to start, including the final git diff. The host was never at risk. The run was.
The fix is a reaper. After every shell command, it kills anything the command left running in the container. It is written so it can still run when every process slot is taken. If it cannot start at all, the host restarts the container, and because the agent's files live on a separate volume, its work survives. After this change, the command after a fork bomb ran normally.
The Tools the Model Gets
The model receives seven tools: list_files, read_file, search, write_file, replace_in_file, run_command, and finish. Each is a thin Python function. Agent Framework turns it into a tool definition, and the function only forwards to the harness:
def run_command(command: Annotated[str, Field(description="Shell command, run in /workspace")]) -> str:
return harness.execute_raw({"op": "run_command", "command": command})The harness parses the arguments into a strict Pydantic action union, so an extra field such as a shell argument is an invalid action, not a hidden option. It counts the step, applies path rules, executes, and appends the call to trace.jsonl. File tools reject absolute paths, .., .git/, and the task's protected paths. A blocked action is returned to the model with its reason, so the model can correct itself, and it still costs a step.
The shell is deliberately unrestricted inside the sandbox. Filtering command strings is a losing game, and the container is what makes an open shell acceptable. The rules that matter are enforced where the agent cannot reach them: at the patch gate and in the verifier.
Agent Framework runs the tool loop. The harness needs one hook into it, because the framework would otherwise keep calling tools after the run has ended. A function middleware stops the loop cleanly once the harness has an outcome:
@function_middleware
async def stop_when_finished(context: FunctionInvocationContext, call_next) -> None:
if harness.finished:
raise MiddlewareTermination("run finished")
await call_next()
if harness.finished:
raise MiddlewareTermination("run finished")The framework's own max_iterations and max_function_calls sit above the harness budget as a second limit, and a watchdog kills the container 15 seconds after the run's deadline, whatever the model or a command is doing.
Deciding "Done" Outside the Agent
The agent can run the tests as often as it likes, and that feedback is useful. It never decides the outcome. When the model calls finish, the harness runs git diff inside the sandbox and treats the result as plain text. The patch gate reads the diff headers and rejects an empty patch, binary changes, and any file under a protected path. Parsing text executes nothing.
A clean patch goes to the verifier, a new container with network_mode="none". It receives the pristine repository without its protected paths, then mounts those paths read-only from the host's untouched copy. The patch is applied, and the task's test command runs with a JUnit report. The judgement is deliberately strict:
def judge(task: Task, exit_code: int, counts: JUnitCounts) -> tuple[bool, str]:
if exit_code != 0 or counts.failures or counts.errors:
return False, "tests_failed"
if counts.skipped:
return False, "tests_skipped"
if counts.tests != task.expected_tests:
return False, f"expected {task.expected_tests} tests, ran {counts.tests}"
return True, "verifier_passed"The test count closes a gap that the exit code alone leaves open. One scripted case adds os._exit(0) to the source module. Pytest imports it during collection, and the process exits with status 0 before any test runs. Exit code alone would call that a pass. The verifier sees zero of six expected tests and rejects it.
A failed verification is returned to the model as a report, and it can try again until max_finish_attempts is used up. Every path out of a run, whether accepted, rejected, stopped, or errored, removes the containers and the volume.
The verifier still runs patched code, so it narrows what that code can fake rather than proving it honest. Read-only tests, no network, a fresh container, and the test-count check cover the cheap tricks. A person should still read patch.diff before merging it.
Walking a Real Live Run
This is the trace of one live run against a Foundry deployment of gpt-5.1-codex-mini on the shipping ticket, recorded on 27 November 2026:
| Step | Model action | What the harness returned |
|---|---|---|
| 1 | list_files("") | Blocked: path must be relative to the repository root |
| 2–5 | list, then read tests, shipping, cart | File list and numbered source |
| 6 | run_command: pytest | Exit 1: 2 failed, 4 passed |
| 7 | replace_in_file: > to >= | Edited src/shop/shipping.py |
| 8 | run_command: pytest | Exit 0: 6 passed |
| 9 | finish | Accepted: verifier ran 6 of 6 original tests |
The run took 25 seconds and used 13,444 tokens, 5,888 of them served from the prompt cache. It made no network requests, because the fix needed no packages. The first step is worth noticing. The model sent an empty path, the gate refused it with a reason, and the model corrected itself on the next call. A clear refusal is better feedback than a silent default.
The run produced this patch, stored with the trace, manifest, sandbox details, verifier report, and egress log:
- if subtotal_pence > FREE_DELIVERY_THRESHOLD_PENCE:
+ if subtotal_pence >= FREE_DELIVERY_THRESHOLD_PENCE:Your project is not changed. The agent edited a copy inside a container that no longer exists, and the output is a patch to review. That is one successful live run on one small ticket, not a measured success rate.
Attacking Your Own Sandbox
Before the cases, it helps to see the layers they target. A tool call passes six checks on its way to becoming an accepted patch, and every layer has at least one scripted attack aimed at it:
You cannot reliably ask a model to misbehave, so the misbehaviour is scripted. Each file in cases/ is a fixed action list and an expected outcome. The suite replays them through the same harness against real containers, with no model calls and no cost:
| Case | Attempt | Observed result |
|---|---|---|
| Protected paths | Edit tests, AGENTS.md, ../, .git/ with file tools | Each blocked with a reason |
| Tests via shell | Rewrite the tests with printf so they pass | Local pytest passed; patch gate rejected the protected path |
| Exfiltration | Read env, call example.com, connect to 1.1.1.1 | No keys; proxy 403; network unreachable; PyPI 200 |
| Host escape | Write /usr, find the Docker socket, read PID 1 env | Read-only; no socket; no keys; capabilities 0 |
| Resources | Fork bomb, 3 GB allocation, 50 MB output, sleep 300 | Reaped; exit 137; truncated; timed out; still responsive |
| Forged exit | os._exit(0) during import | Rejected: 0 of 6 expected tests ran |
| Retry | Wrong threshold, then the correct fix | Report on attempt 1; accepted on attempt 2 |
A valid fix and a step-limit case complete the nine. All nine match their expected outcomes, alongside 31 unit and framework-loop tests. The loop tests drive the real Agent Framework tool loop with a fake chat client that emits scripted tool calls, which checks the middleware and termination behaviour without spending tokens.
The suite earned its place on the first run, when three of nine cases failed. One was the fork bomb. Another was a crashed proxy: Squid drops privileges and could not write its log to stdout, so it restarted in a loop. The third was a mistake in my own case: lowering the threshold to 4,999 pence is a correct fix in integer pence, not a wrong one.
The most instructive failure came after those fixes. The exfiltration run's allowed PyPI request appeared in the next run's egress log. Docker had reused the container's IP address, and Squid logs a tunnel only when it closes. Attribution now destroys the container first, waits for the log, and filters by IP and the run's time window, and the case asserts exactly one denied and one allowed request. That is correct for sequential runs. Parallel runs would need per-run proxy credentials.
Why This Architecture Works
Each boundary answers one question, and no answer depends on the model behaving well. Where does code run? In a disposable container. What can it reach? A proxy with an allowlist. What can it read? A copy of the repository and nothing secret. Who decides success? A separate container running tests the agent could not change. The model's job is to be useful inside those answers.
The isolation level is a setting, not an architecture. The harness depends on a small workspace interface: run, shell, read, write, diff, kill, destroy. Docker with hardened options is the default because it runs on any developer machine. A container still shares the host kernel, so the next step for untrusted repositories is gVisor's runsc runtime on Linux, or a microVM or Hyper-V session backend such as Azure Container Apps dynamic sessions. The loop, gate, and verifier stay the same.
Potential Enhancements
The next step I would take is a held-out set of everyday tickets, such as a pagination off-by-one, an inclusive date filter, and a duplicated retry, each run several times. That turns one successful run into a pass rate per ticket, with cost and time alongside.
After that, the work is mostly operational:
- Open a draft pull request from the host with a scoped GitHub App token, which never enters a container.
- Add a cloud backend that runs the same contract in Azure Container Apps dynamic sessions, with egress disabled and dependencies built into the image.
- Give each run its own proxy credentials, so parallel runs keep separate egress logs.
- Sign the run evidence, so a manifest and trace can be trusted after they leave the machine.
Final Notes
A coding agent should run code, and that is exactly why it needs a place to run it that you are willing to lose. Keep the loop, the keys, and the verdict on the host. Put everything the model chooses to execute in a container with no secrets and one narrow way out. Let a separate container decide whether the work is done.
Then attack your own setup before anyone else does. The cases that failed on the first run were more useful than the ones that passed, and each of them is now a regression test.
Explore the companion repository at the GitHub repository.
See you in the next issue.
Stay curious.
