"""05 AGENT IN THE BOX. The payoff. A tiny "agent" writes code for a task, and that code runs ONLY inside a throwaway container, never on your host. No API key needed. The "agent" here is a canned code-writing step, so you can see the full loop with nothing to configure. Swap in a real coding agent later; the box stays the same. Run: python 05_agent_in_the_box.py Needs: Docker installed and running. If Docker is missing, this prints what it WOULD do and exits 0. It never fakes output. """ import shutil import subprocess import sys IMAGE = "python:3.11-slim" TASK = "compute the sum of the first 10 square numbers" def have_docker() -> bool: return shutil.which("docker") is not None def fake_agent_writes_code(task: str) -> str: """Stand-in for a real coding agent. No LLM call, no API key. Just enough to prove the loop: TASK IN -> CODE OUT -> CODE RUNS IN THE BOX, NEVER ON YOUR HOST.""" return ( "total = sum(n * n for n in range(1, 11))\n" f"print('{task}:', total)" ) def run_in_sandbox(code: str) -> str: cmd = [ "docker", "run", "--rm", "--network", "none", "--memory", "256m", "--cpus", "0.5", IMAGE, "python3", "-c", code, ] result = subprocess.run(cmd, capture_output=True, text=True, timeout=60) return result.stdout.strip() or result.stderr.strip() def main(): print(f"== TASK ==\n{TASK}\n") code = fake_agent_writes_code(TASK) print("== AGENT WROTE THIS CODE ==") print(code) if not have_docker(): print("\nDocker not found on this machine.") print("What happens next, if Docker were here: that code runs ONLY inside a") print("throwaway container (--network none, --memory 256m), never on your host.") print("Install Docker Desktop (or the docker CLI) and re-run to see it live.") sys.exit(0) print("\n== RUNNING THE AGENT'S CODE, ONLY INSIDE THE BOX ==") try: output = run_in_sandbox(code) print(output) except subprocess.TimeoutExpired: print("Sandbox timed out after 60s (that's the timeout working as intended).") sys.exit(1) print("\nThe agent wrote code and ran it, and your host never saw a single line execute.") print("That's the pattern you leave with: task in, code out, code runs in the box.") if __name__ == "__main__": main()