Containing where an agent runs — study guide
The concept's fragments, read in order.
A room you built, with one door you watch
An agent that can run commands runs real ones. It builds, runs tests, installs packages and executes scripts it wrote a minute before, and every one of those processes is untrusted: the model choosing them can be wrong or steered by something it read, and the code it runs is no more trustworthy than the model that wrote it. The sandbox is the contained environment those commands run in. The controller, the program that starts the agent and holds the credentials, builds the sandbox before the run and watches it from outside, so its limits hold whatever the commands inside attempt.
Four walls do the work. The agent sees a filesystem view built for this run, not the host's. Its outbound traffic has one way out, through a proxy the controller owns that admits only listed destinations. It runs under caps on what it can use, with a deadline on everything that waits. And the run is over only when the controller has closed the sandbox and observed it empty, not when the agent says it is done or its first process exits. Behind all four, the controller's own store, token and API sit where nothing inside can reach them. None of this is new machinery: namespaces decide what a process can see and control groups decide how much it can use, here pointed at a tenant you do not trust.
That last word matters, because namespaces and control groups share one kernel. NIST's guide to container security says a shared kernel gives a larger attack surface between workloads than a hypervisor does, so it suits programs of similar trust, and an agent's commands and the controller that holds your credentials are not of similar trust. A namespace sandbox built without administrator privilege, granting no capabilities and checked on each host can still be the right wall, but say out loud what it leaves out: a flaw in the kernel itself. Where that matters, the same four walls can sit inside a virtual machine, or the sandbox can run on a host that holds nothing else worth taking, which is NIST's advice to group workloads by sensitivity.
The walls also have to be the controller's own. Many agent tools ship a sandbox or permission settings of their own, and in one real system a tool's headless mode silently did not apply the permission profiles its integration assumed. OWASP's guidance on agent security puts it bluntly: "Permission prompts are not a security boundary against a manipulated agent; isolation is." Settings inside the tool sit on the agent's side of the boundary, so the controller does not count on them, and whether they govern anything at all is a question for qualifying an agent.
The controller's keys are not in the room
The first thing a sandbox keeps out is the controller itself. No process inside, in any mode and at any autonomy setting, should be able to read or change the controller's store, its records and logs, its API token or its API, or pass itself off as the operator. If one could, the other walls would be decoration: an agent that can write the store can record its own work as approved, and one that holds the controller's token can ask the controller for anything the operator could.
It is easy to let slip while a system is young.
Field recordIn one real system, during an early phase when only tests ran, a scripted stand-in for an agent could read the controller's API token. The project accepted that temporarily and withdrew the acceptance once the sandbox existed.
The mechanism is absence, not refusal. The controller's home directory is not part of the agent's view, so there is no file to guard with permissions and no permission to get wrong. The sandbox's network has no route to the controller's API, so there is no port to guard with a password. Because the sandbox has its own network namespace, it even has its own loopback device, which starts out down: 127.0.0.1 inside it is not the host's 127.0.0.1, where a local API might be listening. A backend that cannot be isolated this way is refused, not run with a warning.
Each protection is paired with a probe that shows it holds. One is a sentinel file seeded at the real token path, which must come back as not found when opened by its host path and by any alias for it. Building probes like that, so that a pass actually means the wall held, belongs to qualifying an agent; what matters here is that every wall in the sandbox has some check that would fail if the wall did not exist.
A filesystem view built for the run
The agent does not get the host's filesystem with a few parts hidden. It gets a root filesystem the controller assembled for this run from a mount plan, like a workbench stocked from a list for one job, instead of letting the worker loose in the whole building to use whatever is lying around. In one real system's design, system directories are mounted read-only and only enumerated configuration files are bound in. The project checkout is read-only, with an overlay on top so that the agent's edits land in a separate layer, and every write goes to one in-memory filesystem with a size cap. The protected test files are bound read-only, so the code being tested cannot rewrite the tests that judge it.
Before each launch the plan is resolved, every path followed to where it really leads, and checked against a forbidden set: the controller's home, other workspaces, credential directories (SSH, GPG, cloud command-line tools, package-manager credentials and the agent tools' own configuration), runtime sockets, devices and host mounts. Any hit refuses the launch. Checking where a path resolves, rather than what it is called, matters because a harmless name can be a link into one of those places.
Nothing inside gets the privileges to rearrange the view. The sandbox is built from user, mount, network, process, IPC, hostname and control-group namespaces without administrator privilege, its processes hold no capabilities, and the no-new-privileges flag is set: once set it cannot be unset, every child inherits it, and running a set-user-ID program or one with file capabilities no longer grants anything extra. The same design rejected a container daemon. OWASP's container guidance says access to a daemon socket running as root is equivalent to unrestricted root access to the host, so reaching one would have made the controller equivalent to an administrator.
Three limits are worth saying plainly. The agent runs as the same operating-system user as the controller, so isolation rests entirely on what the namespaces make visible, and anything mounted in by mistake is readable. The plan is checked before launch, so a socket or credential that the operator's own software creates in an approved directory afterwards is not caught. And the agent can read every object in the repository's history, so anything ever committed there is within its reach.
What a process brings along without asking
A new process starts with more than its arguments. It inherits its parent's open file descriptors, its environment and its working directory, and the tools it runs read whatever configuration sits in the home directory they are given. For a sandbox each of those is a channel nobody decided to open, so the rule is to build every one of them for the run rather than pass along whatever the parent happened to have.
File descriptors show how quietly this goes wrong. A child gets a copy of every descriptor its parent had open at fork, and by default they stay open across exec unless something closes them or marks them close-on-exec, so one can pass through any number of processes that never use it. Linux's close_range call closes a whole range of them in one step.
Field recordIn one real system, a sandboxed role on a second test machine was found holding two open terminal descriptors inherited from the remote shell session that had started the controller. What changed: every inherited descriptor above standard input, output and error (0, 1 and 2) is now closed in the controller, again in the launcher, and again in the sandbox's first process.
Configuration goes wrong the same way, in the other direction.
Field recordIn the same system, a reviewer reproduced a defect in a containment check that tries to change the repository's version-control configuration and expects to be refused. The check ran with a home directory the agent could write. A planted personal config file there made the version-control tool fail, and the failure was read as denied. The fix had three parts: the check writes the controller's own config by path, with no global or system config consulted; denied is recorded only when the filesystem itself refuses; and any other error is recorded as not run, never as denied.
The general lesson outlasts both examples. Anything the agent could write is the agent's to plant, and any tool the controller runs near the sandbox reads that plant unless it is told exactly what to read. Pass paths and settings explicitly, close what you did not mean to hand over, and treat an error you did not expect as unknown rather than as the answer you were hoping for.
One way out, through a door the controller owns
An agent that can reach any address can send what it has read to anyone, which makes outbound traffic the way out in the familiar trio of private data, untrusted content and a channel to the outside. Most host firewalls allow outbound traffic by default; a sandbox turns that around. Its own network namespace has no route out at all, and the one exit is a proxy the controller runs, which works like an office where every outside call goes through the front desk, which dials only numbers on an approved list and writes down every call it places or refuses. It is default-deny pointed outward, and it is what both NIST's container guidance (control the outbound traffic containers send) and OWASP's agent guidance (restrict egress to an allowlist of required domains) ask for.
The proxy's checks are few and strict. It parses the host the agent asked for and accepts it only on an exact match with its list, and only on the secure web port, 443. It resolves the name once, and refuses the whole answer if any address in it is loopback, private, link-local, an IPv4-mapped form of one of those, or the host's own. Then it connects to the address it just checked and to nothing else, so a second lookup that comes back different is never used. Tunnel count, lifetime, buffers and timeouts are bounded, and every connection, accepted or refused, is logged. A host the backend needs that is not on the list fails visibly and is never added automatically.
The answer gets checked, not just the name, because a name can be made to point anywhere, including at the machine itself. That trick is DNS rebinding, and OWASP's guidance on server-side request forgery notes that a domain allowlist alone does not stop it: the resolved address must be checked, with no second, unchecked lookup between the check and the connection. And a service is not safe just because it listens on loopback: in one real system, a local control panel for the agent controller that relied on exactly that was found by a later audit to be open to a full bypass through DNS rebinding, and the page on the threat model for an agent tells that story in full.
The limits are real. Allowlisting restricts destinations; it does not inspect content, and the proxy does not decrypt traffic. Whatever the agent holds can still travel to an allowed host, and the proxy cannot account for extra calls to the model provider made through a destination it allows. Keep the list as short as the job permits, and know that what remains on it is a way out you chose.
Caps on what it uses, a deadline on every wait
A sandbox that keeps the agent in but lets it take the whole machine has only moved the problem. So each sandbox gets caps: on memory, with no swap to spill into, on the number of processes, on bytes written and on files created. On Linux the first two are control-group limits (memory.max with memory.swap.max at 0, and pids.max), and the last two can be set on the in-memory filesystem that takes the agent's writes, since a tmpfs mount accepts both a limit on the bytes it holds (size=) and a limit on how many files and directories it may hold (nr_inodes=). What happens at each edge is ordinary control-group behavior: at memory.max the out-of-memory killer picks a victim inside the group, and at pids.max the next attempt to start a process fails. Before any run is admitted, admission control checks that the host keeps a memory and disk reserve, so the controller is not the one left short.
Caps bound what a run can take; deadlines bound how long anything can wait.
Field recordIn one real system, during a heavy benchmark, a local network outage stalled a run for about 110 minutes. The worker was alive with nothing to show, and the exact call it was stuck in could not be identified because the scheduler's output had not been kept. Reading the source found version-control and host command-line calls with no timeout at all; the model timeouts and the budget checks between roles did not bound them. What changed: a deadline on every external call, scheduler logs kept, and an explicit offline wait instead of spending scheduler ticks.
The rule that came out of it is wide: every run, external call, scheduler step and recovery loop has a deadline. Reaching any cap or deadline cancels the run and records its evidence as incomplete, never as complete. A write that timed out is not blindly retried, because a timeout means you stopped waiting, not that the work failed; it may have landed. And the controller keeps room for its own work, so stopping, refusing and accounting stay possible while another sandbox is pinned at its limits. Step limits and token budgets bound the agent's loop; these caps sit under them, on the machine the loop's commands actually use.
Finished means observed empty
When is an agent's run over? The tempting answer is when its process exits, and that proves nothing. Processes it started may still be running: a server left in the background, a build moved into its own session, a child nobody waited for. Some of them may still be writing to the workspace the controller is about to collect. A parent's exit never establishes that the work stopped, even when the run finished normally and reported success.
So the boundary is not the process tree but a control group the controller has been delegated, which every process the agent starts lands in. A child is born into its parent's group, and starting a new session, clearing the environment or forking again and again does not change that. A process moves only when its number is written into another group's cgroup.procs file, which takes write access to the common ancestor of both groups, and the kernel documentation is explicit that whoever a subtree is delegated to cannot move processes into or out of it. Because the agent runs as the same user as the controller, the sandbox must also give it no writable view of the control-group filesystem; its own cgroup namespace and mount view see to that. That gives the controller a question to put to the kernel rather than to the agent: is anything still in here? On cgroup v2 the group's cgroup.events file answers it, with populated 0 once no live process remains in the group or below it, and writing 1 to cgroup.kill sends SIGKILL to every process in the group and its descendants. Process markers and process groups can answer that question only as diagnostics, because a process can leave its process group and a marker can be dropped. Neither proves that no writer remains.
Asking once is not enough.
Field recordA reviewer probing one real system's boundary design observed a race: a launcher process waiting outside a sandbox's control group entered it after the controller had read the group as empty and issued the command to kill everything in it. What changed: each sandbox now has a launch state (authorizable, authorized, closed) that only controller transactions change, and a launcher runs nothing until it holds an authorization bound to that sandbox, that invocation, that controller lifetime and that lease generation.
Termination is five steps in order: close the sandbox to launches; establish that no launcher can still enter; ask politely, then wait; kill the whole group, then wait; observe it empty. It works like a caretaker who locks the doors first and then walks every room before calling the building empty, instead of taking the last person's goodbye as proof.
After a controller crash, every earlier sandbox is closed before anything else runs. And when closure or emptiness cannot be established, the controller does not guess or take the agent's word for it: the sandbox is quarantined and nothing is collected from it, which is where stopping an agent takes over.
Read what it left as if it were booby-trapped
Everything the agent wrote is something the agent controlled, including the file that is supposed to tell the controller how the run went. So the controller reads it the way you would open a parcel from a stranger. Only after the sandbox has terminated and been observed empty, so that no writer remains to change a file between the check and the read. From outside the sandbox. Without following links, opening regular files only, and within limits on both bytes and time.
Each of those rules answers a real trap.
Field recordIn one real system, a review found that the controller judged one test run by reading, on the host, through a link the agent had made. A link to a named pipe would have blocked the controller, because opening a pipe for reading waits for a writer that may never come. A link to an endless zero device would have made it allocate without bound, because that device never runs out of bytes to return. What changed: every host-side read of an agent-controlled path is no-follow, regular-file-only and size-bounded. A result that is a link, a pipe, a device or an oversize file is invalid, and nothing it points to is opened.
One detail matters for anyone building this: the standard O_NOFOLLOW open flag refuses a link only in the last part of the path, so the directories leading to the file need the same distrust.
The content gets the same suspicion as the container. A result is accepted only when the run exited cleanly, and a well-formed result next to a failure exit is recorded as an invalid result, not a partial success. The controller also does not lean on the agent runtime's own structured-output feature to produce the result; in one real system such a feature broke every run.
Hostile bytes also turn up where nobody thinks of them as files: in anything the controller stores that was derived from agent-controlled text. In one real system, a secret the agent held could reach the controller's database inside the text of a refused proxy connection; the page on secrets an agent never holds tells that story in full. The point here is that a log line can be a payload.
A second witness, never the judge
Every wall so far is judged by the controller's own reading: what it mounted, what its proxy logged, what the control group reports. An optional observer in the kernel can add an independent record. Built with eBPF, the kernel's facility for running small verified programs on kernel events, it can record each process start, file open and connection attempt together with the kernel's answer to each, and that record strengthens the evidence a sandbox is judged on. It works like a camera in the corridor: its footage can back up what the guard reports, but it does not decide who gets in, and a stretch of blank tape does not prove the corridor was empty.
Its role is kept narrow on purpose. It never authorizes a launch, never establishes termination, never passes a check and never measures tokens; those stay with the controller's own mechanisms. Events are attributed to a run through identity the controller established, never through markers the agent supplies, so a reused process or group number cannot carry one run's events into another run's record. Loading such programs takes kernel privilege (CAP_BPF with CAP_PERFMON, split out in Linux 5.8, or the older catch-all CAP_SYS_ADMIN), and neither the controller nor the agent holds it. The observer does not collect credentials, file contents or environment values, so it does not become a new place for secrets to pile up.
Its limits are stated as rules. A missing event is never evidence of absence: an observer that saw no connection attempt has not shown that none happened. Events can be lost, since a kernel buffer that fills up drops new records rather than waiting, and lost events or a collector that stopped make any evidence that depends on them incomplete. An observer cannot turn a probe aimed at the wrong target, or a control that did not work, into a valid test. And if the observer is unavailable, the host is not disqualified, but any test that depends on its evidence is recorded as not established rather than quietly passed.
Containment you can check, not hope for
Running a coding agent you don't have to trust means the limits on it cannot depend on the agent. Instructions ask a model to behave; a sandbox decides what misbehaving can reach. With a built view, an agent told by a poisoned file to read your SSH keys finds no keys to read. With one way out through an allowlist, an agent told to send your repository somewhere finds no route to any host not on the list. With caps and deadlines, a runaway build hits its own group's memory and process limits, not the host's, and a hung call ends on a clock. With an observed shutdown, nothing it started is still writing when you read what it made.
Each wall also leaves something the controller can check: a refused launch, a proxy log line, a counter in the control group, a group read as empty after it was closed. That is the difference between containment and a hope. A wall you cannot observe might be there, and an agent that says it stayed inside is making a claim, not giving evidence.
The walls stop where the agent's legitimate reach begins. An agent holding a key can read that key, and a destination on the allowlist is still a way out, so what goes into the sandbox matters as much as what the sandbox keeps out; keeping secrets out of it, proving with probes that could fail that the walls hold, and stopping or quarantining a run that will not end are each a subject of their own. The same shape fits any tool-using agent, not only coding agents. An assistant on a homelab box that may run shell commands deserves the same four things: a view of only what it needs, an outbound allowlist, a control group with limits, and a shutdown you watched happen.
Sources
The published studies, standards and guidance this page cites. Links open on other sites. Field records come from the author's own records and have no public source.
- Application Container Security Guide, SP 800-190 (NIST, 2017) csrc.nist.gov
- AI Agent and MCP Security, OWASP DevSecOps Guideline (OWASP) owasp.github.io
- Docker Security Cheat Sheet (OWASP Cheat Sheet Series) cheatsheetseries.owasp.org
- Server-Side Request Forgery Prevention Cheat Sheet (OWASP Cheat Sheet Series) cheatsheetseries.owasp.org
- Control Group v2, The Linux Kernel documentation (kernel.org) docs.kernel.org