How to Stop a Deep Agent's Shell From Harming Your Host

11 min read

Give a deep agent an execute tool and it can do real work. It can run tests, install packages and crunch data. It can also run cat ~/.ssh/id_ed25519, rm -rf ~, or curl your .env to a stranger's server. The model does not need to be evil for this to happen. One prompt injection in a web page it read is enough, and so is one confused plan.

This part shows how to put the agent's shell inside gVisor, the sandbox Google uses for millions of sandboxes a day. You will build a small deepagents backend that runs every command in a fresh gVisor sandbox. Then you will watch an agent try to read a host file and fail. Last, you will measure what the safety costs.

If you have not built a deep agent yet, start with Part 3. Backends were covered in Part 5.

The problem: a container is not a wall

Most people reach for Docker first. A normal container is a process on the host with namespaces and cgroups around it. Every system call it makes goes straight to the host Linux kernel. That kernel has hundreds of system calls and millions of lines of code. If one of them has a bug, code in the container can use it to get out.

For your own code, that risk is often fine. For code an LLM wrote a second ago, after reading a web page you have never seen, it is a lot of trust.

There are two common ways to shrink that trust:

  1. A microVM, like Firecracker. The code gets its own guest kernel behind hardware virtualization.
  2. An application kernel, like gVisor. The code talks to a kernel written in Go that runs in user space. Only that kernel talks to the host.

Where an agent's syscall goes in a container, gVisor and a microVM

Drag to rotate. Syscalls hit the gVisor Sentry, and only some go on through the Gofer.

What gVisor is

gVisor is an open source project from Google (Apache 2.0, on GitHub at google/gvisor). Its runtime is a single binary called runsc. It is an OCI runtime, so Docker, containerd and Kubernetes can use it in place of runc.

It has two main parts:

  • The Sentry. This is the application kernel. It implements the Linux system call API itself: processes, memory, signals, pipes, sockets, and a virtual file system. When the sandboxed program makes a system call, the Sentry handles it. The call does not pass through to the host.
  • The Gofer. File access outside the sandbox goes through a separate process. The Sentry asks the Gofer to open files over a file protocol, and the Gofer hands back file descriptors. So the Sentry never needs to open host files on its own.

The gVisor security docs explain the goal. The host kernel should only ever see a small, fixed set of system calls from the Sentry. That set is locked down with seccomp. The Sentry is written in Go to avoid whole classes of memory bugs, and it avoids CGo. A bug in the Linux kernel is much harder to reach, because the program never touches that kernel directly. An attacker would have to break the Sentry first, then get past the seccomp filter around it.

Platforms: how syscalls get trapped

The Sentry needs some way to catch the program's system calls. gVisor calls this the platform:

  • systrap is the default (since mid 2023). It uses seccomp to trap system calls and send them to the Sentry. It works almost everywhere, including inside VMs.
  • KVM uses hardware virtualization. The docs say it is the fastest choice on bare metal. It needs /dev/kvm, which the VM used for this article did not have.
  • ptrace is the old platform. It still works, but the docs mark it as unsupported and slated for removal.
sequenceDiagram
    participant App as agent code
    participant S as Sentry
    participant G as Gofer
    participant K as host kernel
    App->>S: syscall, trapped by systrap
    S->>S: handle it in Go
    S->>G: open a file
    G->>K: open on the host
    K-->>G: fd
    G-->>S: fd
    S->>K: small allowed set only
    S-->>App: result

gVisor vs containers vs microVMs

Here is how the three compare, using each project's own docs.

Plain containers (runc) share the host kernel. They start the fastest and have the best compatibility. Isolation is only as good as the host kernel and its config.

Firecracker runs each workload in a tiny VM. The Firecracker design doc lists KVM, a minimal device model, a seccomp filter on the VMM process, and a "jailer" that drops privileges. It says a host can create up to 5 microVMs per core per second. You need KVM, so it fits bare metal or hosts with nested virtualization.

gVisor sits in between. It needs no KVM, starts like a container, and has a much smaller host attack surface. The cost is that it emulates Linux rather than running it, so some system calls and features are missing. It also adds overhead to system calls and file I/O.

Google Cloud uses both styles. The GKE Sandbox docs compare them: a microVM boots in about 1 to 2 seconds with a fixed cost of about 250 mCPU and 130 MiB, while a gVisor sandbox starts in under 100 ms. The same page lists running AI agent code as a use case. Cloud Run tells the same story. Its first generation runtime is based on gVisor, with fast cold starts and "emulation of most, but not all" system calls. Its second generation runtime is a microVM with full Linux compatibility.

Who runs it

The gvisor.dev users page names many companies. A few that matter for agents: Anthropic (code execution on claude.ai), OpenAI (for "some higher-risk tasks" such as code execution), Modal, Cloudflare (Pages builds), Snowflake (Snowpark), Beam, Tines and Deductive AI. Google uses it in GKE Sandbox, Cloud Run and App Engine, and says it runs millions of sandboxes every day.

The trap with runsc do

The easiest way to try gVisor is runsc do. It runs one command in a sandbox, with no image and no Docker:

bash
sudo runsc --platform=systrap --network=none --ignore-cgroups do uname -r

That printed 4.19.0-gvisor on our VM, whose real kernel is 7.0.0-44-generic. So the command really ran on the Sentry.

But look at what else it can do. We put a decoy file at /tmp/host-secret.txt on the host, then ran cat on it three ways. Here is the real log:

text
1) LocalShellBackend (no isolation)
decoy: a host-only file the agent should never see
7.0.0-44-generic

2) runsc do with defaults (host / mounted read-only + tmpfs overlay)
decoy: a host-only file the agent should never see
4.19.0-gvisor

3) GVisorSandbox (own read-only rootfs, only /workspace shared)
cat: /tmp/host-secret.txt: No such file or directory
4.19.0-gvisor

runsc do keeps your host safe from writes: it puts a temporary overlay over a read-only view of the host root. But it still shows the program your whole host file system. An agent could read ~/.ssh, .env files and your shell history. gVisor stops kernel escapes. It does not decide what files you share. You still have to do that part.

So the backend below gives the sandbox its own small root file system, and shares exactly one host folder.

Building a gVisor backend for deepagents

The deepagents sandbox docs make this easy. A sandbox backend subclasses BaseSandbox and implements execute(). Every other file tool (ls, read_file, write_file, edit_file, glob, grep) is built on top of execute(). When create_deep_agent sees a sandbox backend, it gives the model the execute tool.

How GVisorSandbox wires a deep agent to a fresh gVisor sandbox

flowchart LR
    A[LLM] -->|tool call| B[FilesystemMiddleware]
    B -->|execute cmd| C[GVisorSandbox]
    C -->|config.json| D[runsc run]
    D --> E[Sentry]
    E --> F[Gofer]
    F --> G[/workspace only/]

Each execute() call writes a tiny OCI bundle and runs runsc run. The spec is the core of the security:

python
def _spec(self, command: str) -> dict:
    return {
        "ociVersion": "1.0.0",
        "process": {
            "user": {"uid": 0, "gid": 0},
            "args": ["/bin/sh", "-c", command],
            "cwd": "/workspace",
            "capabilities": {k: ["CAP_AUDIT_WRITE", "CAP_KILL"]
                             for k in ("bounding", "effective", "inheritable", "permitted")},
            "noNewPrivileges": True,
            # env and rlimits trimmed here, see the repo
        },
        "root": {"path": self.rootfs, "readonly": True},
        "hostname": "agent-sandbox",
        "mounts": [
            {"destination": "/proc", "type": "proc", "source": "proc"},
            {"destination": "/tmp", "type": "tmpfs", "source": "tmpfs"},
            {"destination": "/workspace", "type": "bind",
             "source": str(self.workspace), "options": ["rbind", "rw"]},
            # /dev (tmpfs) and /sys (ro) trimmed here
        ],
        "linux": {"namespaces": [{"type": t} for t in
                                 ("pid", "network", "ipc", "uts", "mount")]},
    }

The root file system is read-only. Only /workspace is writable, and it maps to one host folder. And --network=none is on the command line. Then execute() runs it with a timeout and an output cap:

python
def execute(self, command, *, timeout=None):
    timeout = timeout or self.default_timeout
    bundle = Path(tempfile.mkdtemp(prefix="gvisor-bundle-"))
    state = bundle / "state"          # fresh runsc state dir per call
    state.mkdir()
    cid = f"{self._id}-{uuid.uuid4().hex[:6]}"
    try:
        (bundle / "config.json").write_text(json.dumps(self._spec(command)))
        cmd = [self.runsc, f"--root={state}", f"--platform={self.platform}",
               "--network=none", *self.extra, "run", f"--bundle={bundle}", cid]
        try:
            p = subprocess.run(cmd, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
                               stderr=subprocess.STDOUT, timeout=timeout)
        except subprocess.TimeoutExpired as e:
            subprocess.run([self.runsc, f"--root={state}", "delete", "--force", cid],
                           capture_output=True)
            out = (e.output or b"").decode(errors="replace")
            return ExecuteResponse(output=out + f"\n[timed out after {timeout}s]", exit_code=124)
        out = p.stdout.decode(errors="replace")
        return ExecuteResponse(output=out[:MAX_OUTPUT], exit_code=p.returncode,
                               truncated=len(out) > MAX_OUTPUT)
    finally:
        shutil.rmtree(bundle, ignore_errors=True)

One quirk we hit: reusing a single --root state folder made the second runsc run fail with a "gofer: error setting namespace" error. A fresh state folder per call fixed it.

upload_files and download_files work on the host folder directly. They refuse any path outside /workspace, including ../ tricks. The full file, gvisor_backend.py, is about 180 lines.

The root file system is a small Ubuntu tree with python3. The script make_rootfs.sh builds one with debootstrap --download-only and dpkg-deb. That took 3 minutes and made a 112 MB tree on our VM. python3 is needed because read_file and edit_file run small Python scripts inside the sandbox.

What the sandbox allows and blocks

Here is the smoke test log, calling the backend directly:

text
$ uname -a
Linux agent-sandbox 4.19.0-gvisor #1 SMP Sun Jan 10 15:06:54 PST 2016 x86_64 x86_64 x86_64 GNU/Linux
[exit_code=0]

$ cat /tmp/host-secret.txt
cat: /tmp/host-secret.txt: No such file or directory
[exit_code=1]

$ touch /usr/bin/evil
touch: cannot touch '/usr/bin/evil': Read-only file system
[exit_code=1]

$ python3 -c 'import socket; socket.create_connection(("1.1.1.1", 80), timeout=3)'
...
OSError: [Errno 101] Network is unreachable
[exit_code=1]

upload outside /workspace: permission_denied

A file written to /workspace/hello.txt showed up in the host folder. Everything else stayed sealed.

The agent, end to end

Plug the backend into create_deep_agent like any other backend:

python
from deepagents import create_deep_agent
from gvisor_backend import GVisorSandbox

backend = GVisorSandbox("gvisor/rootfs", "/tmp/agent-ws", runsc="runsc")
agent = create_deep_agent(model="anthropic:claude-sonnet-4-6", backend=backend)

agent.invoke({"messages": [{"role": "user", "content":
    "Run uname -a, then try to cat /tmp/host-secret.txt, "
    "then write and run a script that sums squares below one million."}]})

The model now sees these tools:

text
tools the model sees: ['delete', 'edit_file', 'execute', 'glob', 'grep', 'ls', 'read_file', 'task', 'write_file']

Here are the tool results from that run, with a scripted model making the calls:

text
--- tool execute (status=success, artifact={'truncated': False, 'exit_code': 0})
Linux agent-sandbox 4.19.0-gvisor #1 SMP Sun Jan 10 15:06:54 PST 2016 x86_64 x86_64 x86_64 GNU/Linux

[Command succeeded with exit code 0]
--- tool execute (status=success, artifact={'truncated': False, 'exit_code': 1})
cat: /tmp/host-secret.txt: No such file or directory

[Command failed with exit code 1]
--- tool write_file (status=success, artifact=None)
Updated file /workspace/squares.py
--- tool execute (status=success, artifact={'truncated': False, 'exit_code': 0})
333332833333500000

[Command succeeded with exit code 0]
files on the host side of /workspace: ['squares.py']

The model gets a normal shell error. It learns the file is not there, not that a guard blocked it. The script it wrote survives in the shared folder, so you can collect results after the run.

Animation: syscalls from the sandboxed program land in the gVisor Sentry, file opens go through the Gofer, and only a small allowed set reaches the host kernel.

What it costs

gVisor's performance guide is honest about this. Code that only uses the CPU runs at about native speed. System calls, file I/O and networking cost more, because the Sentry does the work. (The guide also notes its own benchmarks used the ptrace platform.)

We measured it ourselves. The script 04_bench.py runs each workload 7 times natively, under runsc do with systrap, and under runsc do with ptrace, and takes the median. "Wall" is the time from the host, including sandbox start. "Inner" is timed inside the workload, so it leaves out start-up.

Start a sandbox and run `true` (median wall time, 7 runs)
native20.9msgVisor systrap1390msgVisor ptrace1014ms
Data from the sources listed below.
Write, stat and delete 500 small files (median inner time)
native108.6msgVisor systrap3694.6msgVisor ptrace4155.9ms
Data from the sources listed below.
Python CPU loop, 3M squares (median inner time)
native1701msgVisor systrap2304.3msgVisor ptrace2274.9ms
Data from the sources listed below.

Three things stand out.

  1. Start-up dominates short commands. Every execute() starts a new sandbox. On our VM that was about 1 to 1.4 seconds, not the "under 100 ms" GKE quotes. Our test box is a small shared VM with no KVM, and an earlier run of the same script gave 484 ms for systrap. Expect your numbers to differ.
  2. Small-file I/O is the worst case. 500 files took about 34 times longer under systrap. Every open, stat and unlink is a system call the Sentry has to handle. An agent that runs npm install or a big pytest suite will feel this.
  3. CPU work was slower than native here too, about 1.35 times. That is more than the guide suggests. We did not dig into why, so treat it as a result for this VM only.

For an agent, a second of start-up per command is often fine. The model call before it usually takes longer. If it is not fine, you could keep one sandbox running and send commands into it with runsc exec. We did not test that here, and it means state lasts between commands.

Running it with Docker

On a machine with Docker, the gVisor docs give this setup. We did not run it here, because our VM has no Docker:

bash
sudo runsc install                 # adds the runsc runtime to /etc/docker/daemon.json
sudo systemctl restart docker
docker run --runtime=runsc --rm hello-world
docker run --runtime=runsc -it ubuntu dmesg   # gVisor prints its own boot log

From there, a sandbox backend can call docker run --runtime=runsc --network=none -v "$WS:/workspace" image sh -c "$CMD" in execute(). On Kubernetes, GKE Sandbox offers the same isolation per pod.

What gVisor does not fix

The deepagents sandbox docs warn about two risks a sandbox cannot solve:

  • Context injection. A file or web page can still tell the model to do something bad. gVisor limits the damage, but the model still obeys inside the box. Pair this with approvals from Part 8.
  • Exfiltration. If you turn the network on, anything in /workspace can leave. Keep --network=none unless the task needs it, and never put secrets in the shared folder.

Also, gVisor is not full Linux. Some system calls are missing, which is why Cloud Run offers a microVM runtime too. Test your tool chain inside it before you trust it.

How this code was tested

Versions: deepagents 0.7.42, langchain 1.5.2, langchain-core 1.8.5, langgraph 1.2.24, and runsc release-20261123.1 with the systrap platform, on a 4 CPU Linux VM with no KVM and no Docker. The backend smoke test, the three-way comparison and the benchmark ran for real, and the logs above are copied from those runs. The agent run used a scripted fake model to make the tool calls, so the tool results are real but the model's choices were fixed in advance. A planned run with Llama 4 Scout on Workers AI stopped at the first model call with a rate limit error (HTTP 429), so no real-model output appears here. The Docker steps come from the gVisor docs and were not run.

Try this

bash
# 1. Check runsc works on your machine (needs root; no Docker needed)
sudo runsc --platform=systrap --network=none --ignore-cgroups do uname -r

# 2. Build a small rootfs with python3 (about 3 minutes, 112 MB here)
cd code/part10
sudo ./make_rootfs.sh ./rootfs

# 3. Smoke test the backend, then run the agent and the benchmark
export RUNSC=$(command -v runsc) ROOTFS=$PWD/rootfs
sudo -E python 01_backend_smoke.py
sudo -E python 02_three_ways.py
sudo -E python 03_agent_fake.py
sudo -E REPS=7 python 04_bench.py

Then put a fake secret in your home folder and ask your own agent to find it. With runsc do defaults it will. With GVisorSandbox it will not.

Next, Part 11 opens up the LangGraph graph under the agent: streaming, checkpoints and how deep agents keep context small.

Sources