Sub topic 14
Planning and sub-agents
This chapter assumes you have read the earlier chapters on the agent loop, stop conditions, and context management. You should be comfortable with the loop in which the model asks for tools, the harness runs them, and the results go back into the messages. Here you will see how a harness handles tasks too large for one pass, either by writing down a plan or by handing part of the work to a second agent.
Why long tasks need structure
A single loop works well for small jobs such as "rename this function" or "why does this test fail". Large jobs strain it in two ways.
- Drift. After dozens of steps the original goal is far back in the history. The model may chase a side issue or forget a requirement.
- Context cost. Exploring a large codebase means reading many files and search results. Every one of them stays in the context window for the rest of the run, whether or not it is still useful.
Planning addresses drift. Delegation addresses context cost. Both are built from the pieces you already know: messages, tools, and the loop.
Planning inside the loop
A plan is text. The model writes a list of steps, the list sits in the message history, and later steps can see it. Nothing special happens inside the model. The plan helps because the model conditions on everything in its context, and a short, explicit list of steps is easy to follow.
Plain text plans have a weakness. They scroll back in the history and may be summarized away during compaction. A common fix is a plan tool that stores the list outside the conversation and returns it on request.
PLAN = []
def update_plan(steps):
# steps: list of {"title": str, "status": "todo" | "doing" | "done"}
PLAN.clear()
PLAN.extend(steps)
return "\n".join(f"[{s['status']}] {s['title']}" for s in PLAN)
TOOLS = {"update_plan": update_plan}Each call returns the whole plan as a tool result. That puts a fresh copy near the end of the context, where the model attends to it most reliably. The harness can also re-inject the plan after it compacts the history, so the goal survives summarization.
Some harnesses add a plan-then-act mode. In the planning phase the model gets only read-only tools and produces a plan. A person reviews it, and only then does the harness enable edit and command tools. This is a permissions control as much as a planning technique, because the person approves the intent before any file changes.
Delegating to a sub-agent
A sub-agent is a second run of the same agent loop, started by the first. The parent calls it through an ordinary tool. The harness handles that call by starting a new loop with a new, nearly empty message list. When the sub-agent finishes, only its final text goes back to the parent as the tool result.
This isolates context. A sub-agent might read 40 files and run 15 searches, using tens of thousands of tokens. The parent sees a report of a few hundred tokens. The exploration cost is paid in the sub-agent's context window, which is thrown away afterward.
A minimal implementation
The loop from earlier chapters used a global TOOLS registry. To give each agent its own toolset, pass the registry as a parameter. The delegate tool then calls the same loop with a smaller registry.
from pathlib import Path
def read_file(path):
return Path(path).read_text()[:20000]
def run_agent(task, call_model, tools, max_steps=20):
messages = [{"role": "user", "content": task}]
for _ in range(max_steps):
reply = call_model(messages)
messages.append({"role": "assistant", "content": reply["text"],
"tool_calls": reply["tool_calls"]})
if not reply["tool_calls"]:
return reply["text"]
for call in reply["tool_calls"]:
try:
result = tools[call["name"]](**call["arguments"])
except Exception as e:
result = f"error: {e}"
messages.append({"role": "tool", "tool_call_id": call["id"],
"content": str(result)})
return "stopped: step limit reached"
def make_delegate(call_model, sub_tools, max_steps=10):
def delegate(task):
report = run_agent(task, call_model, sub_tools, max_steps)
return report[:4000] # cap what flows back into the parent
return delegate
def fake_model(messages):
# Scripted stand-in for a real model API so the example runs offline.
first, last = messages[0]["content"], messages[-1]
if first.startswith("Find"): # sub-agent behavior
if last["role"] == "user":
return {"text": "", "tool_calls": [{"id": "s1", "name": "read_file",
"arguments": {"path": "notes.txt"}}]}
return {"text": "Report: " + last["content"].strip(), "tool_calls": []}
if last["role"] == "user": # parent behavior
return {"text": "", "tool_calls": [{"id": "p1", "name": "delegate",
"arguments": {"task": "Find the retry setting in notes.txt"}}]}
return {"text": "Done. " + last["content"], "tool_calls": []}
Path("notes.txt").write_text("retry=3\n")
read_only = {"read_file": read_file}
parent_tools = {"read_file": read_file,
"delegate": make_delegate(fake_model, read_only)}
print(run_agent("Fix the retry bug", fake_model, parent_tools))Running it prints Done. Report: retry=3. With a real model, fake_model would be replaced by your provider's API call. The structure stays the same.
Three details in this code matter.
- The sub-agent gets its own
max_steps, so a stuck sub-agent cannot consume the parent's budget indefinitely. - The sub-agent's registry has no
delegateentry. It cannot spawn further agents, which prevents unbounded recursion. - The report is truncated before it returns, for the same reason tool outputs are truncated elsewhere: one result should not fill the parent's window.
Designing the delegation
Write the task as if to a stranger
The sub-agent starts with no history. It does not know what the user asked, what the parent already tried, or which files matter. Whatever the parent writes in task is everything it has. A task such as "look into the failing test" produces wandering. A better one names the goal, the starting point, and the expected output:
- Goal: find where the retry count is read from configuration.
- Starting point: the
client/directory. - Output: file paths and line numbers, no code excerpts longer than five lines.
Restrict tools to the job
Give each sub-agent only the tools its job needs. A research sub-agent gets read and search. A test-running sub-agent gets a command tool, ideally one that is sandboxed. Narrow toolsets reduce both the damage from mistakes and the number of choices the model must weigh. Permissions and approvals still apply inside the sub-agent. Decide explicitly whether an approval the user gave the parent carries over. The safer default is that it does not.
Choose what comes back
The report is the only channel from sub-agent to parent. Ask for a specific shape, such as a list of findings with evidence, because anything left out of the report is lost when the sub-agent's context is discarded.
When to delegate
| Situation | Delegate? | Reason |
|---|---|---|
| Search across many files for one answer | Yes | Output is large, the answer is small |
| Run a long test suite and summarize failures | Yes | Raw logs stay out of the parent's context |
| Independent investigations, such as three modules | Yes, possibly in parallel | Results do not depend on each other |
| Small edit to a file the parent already read | No | The overhead exceeds the savings |
| Steps that depend on detailed intermediate state | No | A summary would drop details the next step needs |
| Parallel edits to the same files | Avoid | Writes can conflict and overwrite each other |
Costs and failure modes
- Lossy reports. A summary is a compression. If the report omits a detail that matters later, the parent cannot recover it without delegating again or reading the files itself.
- Wrong or invented findings. The parent usually trusts the report. A sub-agent that guesses can mislead the parent. Asking for file paths and line numbers lets the parent spot-check claims cheaply.
- Cost and latency. Each sub-agent is a full loop with its own model calls. Total tokens used across all agents can exceed what a single agent would have spent, even though each context stays small.
- Compounding limits. Step limits apply per agent. A parent allowed 20 steps and sub-agents allowed 10 steps each can perform far more than 20 steps of work in total. Track the combined budget if cost matters.
- Injection passes through. Text a sub-agent reads from a web page or a file can shape its report. Treat the report as data from an untrusted source, not as instructions, just like any other tool result.
Reading delegation in a trace
In a message trace, delegation appears as one tool call and one tool result in the parent's history. The sub-agent's own messages may be logged separately. When debugging, check these in order:
- Was the task text specific enough for a reader with no context?
- Did the sub-agent stop because it finished, or because it hit its step limit? The string
stopped: step limit reachedin a report means the answer may be incomplete. - Does the report contain evidence, such as paths and line numbers, that the parent can verify?
Exercise
A parent agent delegates "check why the build is slow" to a sub-agent. The report comes back as "The build is slow because of large dependencies." The parent then makes a wrong change. Name two problems in how the delegation was set up, and say how you would fix each.
Show answer
First, the task was vague and gave the sub-agent no starting point, goal, or required output, so it had to guess. Fix it by naming the build command, the directory, and the output format. Second, the report had no evidence, so the parent could not verify the claim. Fix it by requiring measurements, such as timings per build step, with file paths or log lines. Adding a step limit check also helps, in case the report came from a sub-agent that ran out of steps.
Exercise
In the code above, why does the sub-agent registry read_only not include the delegate tool, and what could go wrong if it did?
Show answer
Leaving out delegate stops sub-agents from starting their own sub-agents. If it were included, a sub-agent could delegate to another one, which could delegate again, and so on. Each level adds model calls and cost, and per-agent step limits would not cap the total. A depth limit or a shared budget would be needed to keep it bounded.