Your AI agent just wrote some Python and wants to run it. Where does that code actually execute?
For a lot of agent products the honest answer is "on the same server as everything else, with the same environment variables". That means the same API keys, the same database URL and the same network access as your app. One bad generation, or one prompt injection hidden in a document the agent read, and the code can print your secrets, fill your disk or loop forever.
The industry has noticed. LangChain made LangSmith Sandboxes generally available this year, and its announcement is blunt about the design: every sandbox is a "hardware-virtualized microVM, fully kernel-isolated" from your services, with its own filesystem, shell and network boundary. Its reasoning is that containers share a kernel with the host, which is not enough for untrusted code. monday.com uses it so its Sidekick assistant can write and run code.
You may not need a microVM on day one. But you do need a runner that assumes the code is hostile. Here is a small one I use as the first layer, in under 50 lines of Python, with a test for each way agent code goes wrong.
The threat list
Agent-generated code fails in boring, predictable ways. Each one gets a test:
- Secrets: it reads
OPENAI_API_KEYor your database URL from the environment. - CPU: it writes
while Trueby accident. - Wall clock: it sleeps, or starts a child process that sleeps, and holds the worker forever.
- Memory: it loads a 2 GB file into RAM.
- Disk: it writes a 50 MB file into your working directory.
- Network: it sends data somewhere you never approved.
The code
import os, signal, resource, shutil, subprocess, sys, tempfile LIMITS = {"cpu_s": 2, "mem_mb": 256, "file_mb": 1, "wall_s": 5, "out_kb": 8} SAFE_ENV = {"PATH": "/usr/bin:/bin", "LANG": "C.UTF-8", "HOME": "/tmp"} def _limit(): # runs inside the child, just before the agent's code starts mb = 1024 * 1024 resource.setrlimit(resource.RLIMIT_CPU, (LIMITS["cpu_s"],) * 2) resource.setrlimit(resource.RLIMIT_AS, (LIMITS["mem_mb"] * mb,) * 2) resource.setrlimit(resource.RLIMIT_FSIZE, (LIMITS["file_mb"] * mb,) * 2) os.setsid() # own process group, so a timeout can kill everything it spawned def run(code: str) -> dict: work = tempfile.mkdtemp(prefix="agent-") cmd = [sys.executable, "-I", "-c", code] # -I: ignore env vars and user site if shutil.which("unshare"): cmd = ["unshare", "-rn"] + cmd # empty network namespace: no internet p = subprocess.Popen(cmd, cwd=work, env=SAFE_ENV, preexec_fn=_limit, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) try: out, err = p.communicate(timeout=LIMITS["wall_s"]) status = {0: "ok", -9: "killed"}.get(p.returncode, f"exit {p.returncode}") except subprocess.TimeoutExpired: os.killpg(p.pid, signal.SIGKILL) # kill the whole group, not just one pid out, err = p.communicate() status, err = "timeout", "killed after wall clock limit" finally: shutil.rmtree(work, ignore_errors=True) # nothing survives between runs cap = LIMITS["out_kb"] * 1024 return {"status": status, "stdout": str(out)[:cap], "stderr": str(err)[-cap:]} TESTS = { "normal": "print(sum(range(10)))", "secrets": "import os; print(os.environ.get('OPENAI_API_KEY', 'no key visible'))", "cpu_loop": "while True: pass", "sleeper": "import subprocess; subprocess.Popen(['sleep', '60']); import time; time.sleep(60)", "memory": "x = bytearray(2 * 1024**3)", "disk": "open('big.bin','wb').write(b'0' * 50 * 1024**2)", "network": "import urllib.request; urllib.request.urlopen('https://example.com', timeout=3)", } if __name__ == "__main__": os.environ["OPENAI_API_KEY"] = "sk-live-secret" # pretend the host has a real key for name, code in TESTS.items(): r = run(code) lines = (r["stdout"] or r["stderr"]).strip().splitlines() or [""] print(f"{name:<9} {r['status']:<10} {lines[-1][:60]}") Running it
On a Linux box:
$ python sandbox.py normal ok 45 secrets ok no key visible cpu_loop killed sleeper timeout killed after wall clock limit memory exit 1 MemoryError disk exit 1 OSError: [Errno 27] File too large network exit 1 urllib.error.URLError: <urlopen error [Errno -3] Temporary f Every failure is contained, and the normal case still works. The host process had a "live" key in its environment, and the agent's code could not see it. I also checked after the run: the sleep 60 that the sleeper started was gone, because the runner kills the whole process group, not just the parent.
What each line is doing
A clean environment, not a filtered one. env=SAFE_ENV passes three variables and nothing else. Do not try to strip "sensitive" names from os.environ. You will miss one. Allow-list instead.
-I isolated mode. Python ignores PYTHON* variables and the user's site-packages, so the agent cannot be steered by something left in the host environment.
Resource limits set in the child. preexec_fn runs after the fork and before the agent's code, so RLIMIT_CPU, RLIMIT_AS and RLIMIT_FSIZE apply only to the child. The kernel enforces them. The code cannot catch its way out of a CPU kill.
CPU time and wall time are different. A CPU limit does nothing to code that sleeps or waits on a socket. You need both, and the wall clock limit has to kill the process group (os.setsid() plus os.killpg), or a child process outlives the run.
No network by default. unshare -rn starts the code in an empty network namespace, with no interfaces except loopback. If your distribution blocks unprivileged user namespaces, the runner falls back to running with network, so check that unshare -rn true works on your hosts.
A fresh directory every time. Each run gets a temp directory that is deleted afterwards. Nothing leaks from one user's run into the next.
Capped output. An agent that prints 200 MB will otherwise blow up your logs and your model's context window on the next turn.
What this does not protect
Be honest about the limits. This runner shares the host kernel and can still read world-readable files on the machine. A kernel exploit escapes it. That is fine for code your own agent writes from trusted instructions in an internal tool. It is not fine for a product where any user can make your agent run anything.
That is exactly the line LangChain draws in its announcement. When untrusted users can influence the code, move execution into a microVM (Firecracker style, or a managed service like LangSmith Sandboxes, E2B or Modal) and keep this runner's ideas on top: allow-listed environment, resource limits, wall clock kills, no network unless a specific domain is approved, and credentials injected by a proxy at the network layer instead of handed to the code.
A checklist for your agent's code tool
- Allow-list environment variables. Never pass the host environment.
- Set CPU, memory and file size limits, and a separate wall clock timeout that kills the process group.
- Deny network by default; allow specific domains only when a task needs them.
- Give every run a fresh, throwaway working directory.
- Cap stdout and stderr before they go back into the model.
- Log every execution with its code, limits and result, so you can replay incidents.
- Move to microVMs the day untrusted users can trigger code execution.
The model writing the code is the impressive part. The runner is the part that decides whether your agent is safe to put in front of customers.
If you are building an agent that writes or runs code and want it production-ready, that is what we do at Axionry, an AI product development studio. We ship in weeks.

