So far every action an agent could take was a function someone wrote in advance and described in a schema. That covers a lot, but it puts a ceiling on the agent: it can do only what the tool list anticipated, one call at a time, with every intermediate result pasted into its context. This module removes the ceiling by giving the agent a computer. The agent writes a program, a sandbox runs it, and the printout comes back as the observation. Three practical questions follow. How do you run code you did not write without risking your machine? Where does the agent keep its files? And how do you give it many specialised procedures without putting all of them in every prompt?

Notebooks

Notebook 8a: CodeAct and a local sandbox answers one shopping question with JSON tool calls and then with a single program, builds a sandbox layer by layer and trips each layer on purpose, and measures how both styles scale. Notebook 8b: Workspaces and skills gives an agent a folder with four file tools, refuses every path that leaves it, then packages a procedure as a skill and measures what loading it on demand saves.

Code as the action

Hur and Song list three limits of the predefined-tool approach. The first is a fixed action space: if nobody wrote a list_files tool, the agent cannot list files, however simple the request. The second is inefficient execution: the unit of work is one model call, one tool run and one observation, so a task that touches ten files takes about ten round trips, and every file’s full contents land in the context even when only a few lines matter. The third is tool proliferation: covering each new need with a new tool makes the tool list longer, and that list is sent with every request. A few MCP servers can add tens of thousands of tokens before the user has typed anything.

All three have the same fix: let the model write code.

Definition 8.1 (Code action).

A code action is a tool call whose argument is a program. The agent’s capabilities are exposed as functions the program may call, an execution environment runs it, and whatever it prints is the observation. CodeAct (Wang et al., 2024) is the agent pattern built on code actions.

With code actions (Definition 8.1), a loop over twelve stores is a for statement, filtering a large result is a list comprehension, and the agent can do anything the language and its libraries allow, not only what the tool list names. Notebook 8a measures the difference on a question that needs a price, a shipping cost and a currency conversion per store. Here “calls” means model calls:

storesJSON, one call per turnJSON, batched callsCodeAct
39 calls, 5,390 tokens4 calls, 2,371 tokens2 calls, 736 tokens
1233 calls, 40,395 tokens4 calls, 4,788 tokens2 calls, 823 tokens

The call counts follow a simple rule. If the task needs tool invocations arranged in dependent rounds (shipping can be asked for at once, but conversion needs the price first), and the program takes attempts to run cleanly, then

model calls, the being the final answer. Tokens grow faster than equation suggests, because each call re-reads the history so far (the quadratic sum of Module 1). Batching removes most of the round trips, but not the conversions or the bulk of each result entering the context; a program does the arithmetic in Python and returns one line per store.

The offline numbers above come from a rule-based model, so they show the mechanics, not the quality. Wang et al. tested real models: across 17 LLMs, code actions gave the best success rate for 12 of them, and on their M3ToolEval benchmark GPT-4 (gpt-4-1106-preview) solved 74.4% of tasks with code against 52.4% with JSON calls, in fewer turns (5.5 against 7.6 on average). CS329Z’s lecture on design patterns puts it in one line: code is a good form factor for actions.

JSON tool calls think model act one tool one call, one result, every result in the context 3 stores: 9 model calls 12 stores: 33 model calls CodeAct think model act sandbox one program: loops and sums run in Python, printout back 3 stores: 2 model calls 12 stores: 2 model calls
Remark 8.1 (When a tool still beats code).

Keep an action as a separate tool when the harness needs to see it. A refund, an email or a deletion should stay a tool call that can be logged, rate-limited and confirmed one at a time; inside a program it becomes one line among many. Small, frequent, well-defined actions are also cheaper as tools, and smaller models write unreliable code.

This trade-off (Remark 8.1) is why real agents mix the two: a code tool for open-ended work next to a handful of plain tools for actions that need oversight.

A sandbox is a stack of limits

Code the model writes is untrusted, even when the model means well. It may loop forever, allocate until the machine swaps, delete the wrong folder, or follow instructions planted in a document it read. Notebook 8a starts with the naive version, subprocess.run on the model’s code, and a probe confirms what that child process gets: the notebook’s environment variables (API keys included), its working directory, and every file you can read.

Definition 8.2 (Sandbox).

A sandbox runs untrusted code with explicit limits on time, CPU, memory, files, network and output, and reports what happened (exit status, output, which limit fired) back as an observation the model can read.

No single mechanism gives a sandbox (Definition 8.2) all of these limits, so agentlab.sandbox.LocalSandbox stacks several, each stopping a different accident:

layerstopsmechanism
fresh folderwrites into your projectthe process starts in its own work directory
clean environmentleaked secretsonly PATH, HOME, locale and Python settings are passed on
wall-clock timeoutwaiting foreverthe whole process group is killed after timeout_s
CPU limitbusy loopsRLIMIT_CPU: the kernel stops the process
memory watchdogrunaway allocationresident memory polled every 50 ms, group killed past the cap
sandbox-exec (macOS)network, writes elsewhere, reading your home foldera kernel policy
output capflooding the contextstdout and stderr cut at a fixed size, with a note

The interface is small, and the result says which layer fired:

box = LocalSandbox(workdir=nb.workdir / "box", timeout_s=10, cpu_s=5,
                   mem_mib=512, network=False)
r = box.run_python("while True:\n    pass")
r.killed_by, r.returncode          # ('cpu', -24): SIGXCPU from the kernel
r.to_text()                        # what the model reads as the observation

Two details matter more than they look. A program that sleeps uses no CPU, so only a wall-clock timeout catches it, and a busy loop needs the CPU limit, because a stuck parent process might never fire its timer. And the timeout kills the whole process group, so a background child the program started dies with it.

This sandbox is for code that is probably fine. It shares the kernel with your machine, isolates files and network only on macOS, and its memory cap is a poll, so a fast allocation overshoots before it is caught. Production systems use containers with no network and a read-only root, microVMs such as Firecracker, or hosted sandboxes; the book uses E2B, whose sandboxes keep variables between calls like a notebook kernel. Ours starts a fresh process each time, so only files persist, and the code tool’s description says so.

When code fails, the traceback is the observation. Notebook 8a stages this with a scripted model: its first program uses a wrong dictionary key, the observation shows KeyError: 'cost' with the line number, and the second program fixes the key. Each failed attempt adds one to the in equation .

A workspace of files

A program that runs and forgets is useful; an agent that can also keep files is much more so. Files hold data to analyse, scripts to rerun, notes for later, which is the “write” strategy of context engineering from Module 1: move information out of the context and read it back when needed.

Definition 8.3 (Workspace).

A workspace is a directory that is the agent’s whole file system. Tools list, read and write files and run commands in it; every path the model gives is resolved and checked to lie inside the root; and commands run in a sandbox whose working directory is that root.

Four tools are enough for a great deal: list_files, read_file, write_file and run_command. CS329Z’s case study of the minimal Pi harness makes the same bet: by default it enables only read, bash, edit and write, since everything else is a shell command. Pi also has no permission checks and runs with the rights of the user who started it, which is exactly the gap a sandbox fills. In notebook 8b an agent with these four tools lists the folder, reads a CSV file, writes a seven-line script and runs it to count 24 orders and total EUR 4,929.40.

The path check in a workspace (Definition 8.3) is where most homemade versions go wrong:

def resolve(self, path: str) -> Path:
    p = Path(str(path).strip() or ".")
    real = (p if p.is_absolute() else self.root / p).resolve()  # collapses .., follows links
    if real != self.root and not real.is_relative_to(self.root):
        raise PathEscape(f"{path!r} is outside the workspace; use a path relative to its root")
    return real

resolve() runs before the comparison, so data/../../x and a symbolic link that points out of the folder are both caught. Comparing strings instead would fail twice: ../ is not collapsed, and a sibling folder named root-old starts with the same characters as root. The path check guards only the file tools, though. run_command("cat ../secret.txt") never passes through resolve, which is why the commands also run in the sandbox, where the kernel policy refuses the read.

Skills: instructions loaded when needed

A workspace and a code tool make an agent general. Specialised procedures, such as how this team formats release notes or which script produces the monthly report, still have to come from somewhere. Putting all of them in the system prompt brings back the third limit, a prompt that grows with every capability.

Definition 8.4 (Skill).

A skill is a folder with a SKILL.md file (frontmatter with a name and a description, then instructions in Markdown) plus any scripts, templates or reference files the instructions mention. The agent sees only the names and descriptions until it chooses to load a skill.

Skills (Definition 8.4) disclose information in three levels. Level 1, one line per skill, is in the system prompt on every request. Level 2, the body of SKILL.md, enters the context when the model calls load_skill. Level 3, the bundled files, is read or run only when the instructions say so; a script’s code need never enter the context at all, only its output. With skills whose summary lines cost tokens and whose bodies cost , of which are loaded, one request costs

tokens. Hur and Song’s example: 100 capabilities at 500 tokens each cost 50,000 tokens inline, while 50-token summaries plus two 2,000-token bodies cost about 9,000. Notebook 8b measures its three fixture skills (summary lines of 39 to 46 tokens, bodies of 134 to 188) and extrapolates to 100 skills: 20,367 tokens inline against 4,523 listed. The saving in equation grows with and shrinks as approaches , so skills pay off when there are many of them and each request needs few.

The format has a few rules worth enforcing: the name uses lowercase letters, digits and hyphens, at most 64 characters, and matches the folder; the description is required and at most 1,024 characters. The notebook’s library rejects a skill named Quick_Notes and one with no description, and says why.

Remark 8.2 (The description is the router).

The model decides whether to load a skill from its level-1 line alone. A description should say what the skill does and when to use it (“Use when asked to summarise, total or break down a table of data”). A vague description is never chosen; an overly broad one is loaded for everything and wastes the saving.

Hur and Song arrange an agent’s capabilities in three tiers: core tools that are always present, installable skills loaded on demand, and code the agent generates for itself. A good description (Remark 8.2) is what makes the middle tier work. A skill is also code and instructions written by someone else. Its SKILL.md enters the context with the authority of a system prompt and its scripts run in your sandbox, so install third-party skills with the care you give a dependency (Module 12 returns to this).

Try this

  • In notebook 8a, add a fourth currency to convert and two stores that price in it. Count the model calls for each style, and check your counts against equation .
  • Give the CodeAct agent timeout_s=0.5 and a question whose program sleeps for one second. What exactly does the model read, and what should a good model do next?
  • Find a path that you expect to escape the workspace in notebook 8b (a symbolic link, ~, an absolute path, a URL-encoded ..). Which check stops it?
  • Using equation with and , at what does inlining every skill cost more than 10,000 tokens per request? What would cancel the saving?
  • Write a fourth skill with a deliberately vague description and ask the skilled agent a question it should handle. Does the offline model load it? Re-run with MODEL set.

Readings