
Sub-agents in Go, and when a fresh context helps
Run your agent loop again inside a tool to answer one question, and when that doesn’t pay off.
On the agent compass Stage 1 of 4 · Build the requestAs an agent investigates, every file and report it opens stays in its history and is resent each turn. A context policy that clears and summarizes old turns is one way to keep that in check. A sub-agent is another. The parent hands a narrow question to a tool, the tool runs a second copy of the loop with an empty conversation, and only the final answer comes back. Whatever the sub-agent read along the way is discarded with its conversation, so the parent’s history grows by one answer.
The rest of this page adds a sub-agent to the crash-triage agent, the companion code’s agent that reads crash reports from the remind practice service and files issues in a tracker, and then tests it on the task it was designed for.
A sub-agent is a tool
From the parent’s point of view the sub-agent is just a tool, explain_package, which takes the name of a package in the service and a question about that package:
// ExplainPackage returns a tool that hands one question about one
// package to a sub-agent: the same loop, started fresh, with only the
// read-only code tools and its own limits. The parent's context grows
// by the answer, not by every file the sub-agent read.
func ExplainPackage(m agent.StreamModel, e *Env,
lim agent.Limits) agent.Tool {
return agent.NewTool("explain_package", explainDesc,
func(ctx context.Context, a explainArgs) (string, error) {
msgs := []agent.Message{
{Role: "system", Content: explainPrompt},
{Role: "user",
Content: "Package " + a.Package +
": " + a.Question},
}
tools := explainTools(e.view())
res, err := agent.RunStream(ctx, m, tools, msgs, lim)
if errors.Is(err, agent.ErrBudget) {
return "", fmt.Errorf("the helper didn't finish (%v) "+
"after %d turns; ask a narrower question, or "+
"read the code yourself", err, turns(res))
}
if err != nil {
return "", fmt.Errorf("the helper failed: %w",
err)
}
answer := res.Messages[len(res.Messages)-1].Content
return short(answer, 4000), nil
})
}
The whole sub-agent is set up inside that function.
It gets a brief system prompt, the question as its task, a tool set and limits of its own, and it runs on the same RunStream loop the parent uses.
Its answer is truncated to 4,000 bytes before being returned to the parent.
Four of its design choices carry over to other agents.
Read-only tools. The sub-agent can only read code. Patching, running tests, and filing issues are off its list; it investigates and reports, and any action is the parent’s call.
Its own bookkeeping.
The parent’s code_patch won’t touch a file unless the parent has read it first.
Sharing that record with the sub-agent would let the parent edit a file it knows only from someone else’s summary.
So the sub-agent works in the same workspace but keeps a separate record of what it has read.
A sub-agent that didn’t finish is an error result, never a budget error.
When the sub-agent hits its turn limit, the parent receives an ordinary tool error, the helper didn't finish (agent: budget exhausted: max turns reached) after 15 turns; ask a narrower question, or read the code yourself, which tells it what to try next.
Returning ErrBudget here would be wrong.
The parent’s loop reads ErrBudget as its own turns or money being used up, so it would halt and report a budget problem that belongs to someone else.
The sub-agent’s error is formatted into the message with %v, which copies its text without wrapping it, so no errors.Is check in the parent can match it.
The one exception is a fatal error, a missing workspace for instance: that is wrapped with %w and stops the parent as well.
One level.
explain_package is left out of the sub-agent’s tool list, so a sub-agent can never start another one.
Without that rule, spending can grow geometrically, as each question spawns three helpers and each helper spawns three more.
With a single level, the worst case for any question is one sub-agent’s turn limit, and since the parent and its sub-agents spend from one shared pool, one cost budget bounds the whole run.
Claude Code makes a different and reasonable choice: its subagents may start their own, down to three levels by default, and the limit is configurable. That fits an assistant a person is watching as it works. A triage run that nobody is supervising benefits more from a fixed limit the model can’t talk its way past.
Did it help? Measured
The longest single task in the crash catalog is a crash in the digest code.
Its cause sits three packages away in schedule, and to understand how the next run time is calculated, the agent ends up reading most of that package.
On the default model, anthropic/claude-haiku-5.5, this task was run three times with explain_package available and three times without it (October 2026):
| Runs | Turns | Parent’s largest request (tokens) | Cost, sub-agent included | Checks passed (of 16) |
|---|---|---|---|---|
| With the sub-agent | 18, 23, 18 | 24,493; 33,809; 33,891 | $0.0122, $0.0161, $0.0147 | 16, 16, 16 |
| Without | 17, 16, 16 | 30,435; 28,968; 37,862 | $0.0113, $0.0095, $0.0121 | 16, 16, 16 |
The sub-agent didn’t help.
Each run that had the tool used it once, for a well-chosen question: can Next in schedule return a time earlier than its input?
The sub-agent settled that in three or four tool calls, costing between $0.0020 and $0.0032.
After that, the parent opened schedule/weekly.go on its own regardless.
The fix belonged in that file, and the patch tool refuses to change a file the parent hasn’t read.
So the two agents read much of the same code, and the runs with the tool needed between one and seven extra turns and cost slightly more.
All six runs located the root cause and passed all 16 checks.
The task also never came close to needing context relief. Its largest request stayed below 38,000 tokens, well under the 60,000 tokens at which the context policy above begins to clear old results.
When a sub-agent pays
The saving comes from questions about files the parent will never open again. Examples: how some other package gets used, what a third-party library does, or which handful of forty call sites actually matter. If the sub-agent’s answer points to a change in the very files it just read, the parent must open those files to make the change, and the sub-agent’s reading was duplicated work.
Research is the stronger case. There the answer is scattered across many sources that have nothing to do with each other. A lead agent breaks the question into parts and starts a sub-agent for each; every sub-agent reads its own sources in a separate context and returns a brief summary. Anthropic’s report on its multi-agent research system covers a design like that. It reports that its multi-agent systems used roughly 15 times as many tokens as chats, and it names the reason coding sees smaller gains: coding tasks have “fewer truly parallelizable tasks than research”. The rules from the triage agent hold there too. Use a single budget for the lead and all sub-agents. Report a sub-agent that ran out of turns as a result the lead can respond to. And give sub-agents read-only tools, because the pages they read are untrusted, and instructions planted in a page, a prompt injection, can travel up to the lead inside a summary.
Sub-agents and fan-out
The model decides when a sub-agent runs, by calling the tool. In fan-out, the harness itself splits the job ahead of time and starts one agent per part. Each is a form of concurrency in Go, and both were measured on the triage agent. On the 99-report batch, fan-out finished no faster than one agent; what it gave instead was steadier cost and smaller requests. When the model itself decides how many agents to start and what each one does, and its replies drive the merging of their results, that is orchestration, and this page deliberately stops short of that.
What was measured, and what wasn’t
Measured, on the default model in October 2026:
- One sub-agent on one task, three runs with it and three without, on the catalog’s longest single task. The result is in the table above: no context saved, a little more cost.
- Fan-out over a batch: 23 group agents run four at once and run one after another, two runs of each, set against three runs of a single agent over the same 99 reports. Four at once beat one after another by about 2.4 times, matched the single agent’s wall time, varied less in cost, and cost 25 to 60 percent more than the single agent.
Not measured:
- A sub-agent on a task where the parent never rereads the files. That is where a sub-agent should pay off, and the one task tested with a sub-agent wasn’t that case.
- A research workload. The research assistant is described from Anthropic’s published report; no research agent was run.
- Orchestration, where a model decides how many agents to start and what each one does. That is left out on purpose.
Three runs a side can show a large effect and can’t rank two close ones. If your agent asks side questions about code it will never edit, or reads many independent sources, the unmeasured cases are the ones that describe it, and a few runs of your own, with and without the sub-agent, will tell you more than this page can.
When to use it
Reach for it
- A side question needs reading the parent will never use again. On the digest task, the sub-agent answered its question in three or four calls for $0.0020 to $0.0032.
- You want a steady bill and small requests across a batch. One agent per crash group cost $0.124 to $0.126 in four runs and never sent a request over 28,275 tokens.
Leave it out
- The answer leads to an edit in the files the sub-agent read. On the digest task, the parent reread those files anyway, and runs with the sub-agent took one to seven more turns and cost slightly more.
- One agent with a context policy can hold the batch. Four agents at a time finished no sooner and cost 25 to 60 percent more.
Try it
From the code directory of a clone of the companion repository:
$ go test ./ch09/triage/ -run TestExplainUnfinished -v
$ go run ./ch09 -task g3-mixed-batch -groups -parallel 4
The -run flag picks the test by name and -v prints its name and result.
In the second command, -groups runs one agent per fingerprint group (reports with the same fingerprint, a short identifier derived from a crash report, are treated as one cause), and -parallel 4 runs four of those agents at a time.
The test confirms that a sub-agent that exhausts its turns reaches the parent as a tool error and that the parent keeps running.
The second command, with no key set, replays a recorded fan-out run on a six-report task with five fingerprint groups.
Each output line names the group whose agent produced it; after the agents finish come the merge of their workspaces (each agent edits its own copy of the service, and the edits are combined at the end), the filed issues, and a grade of 22 of 22 checks.
The service’s tests run many times along the way, so it takes a couple of minutes.
The sub-agent’s prompt and tool list are in ch09/triage/subagent.go.
func ExplainPackage(m agent.StreamModel, e *Env,
lim agent.Limits) agent.Tool
ExplainPackage returns a tool that hands one question about one package to a sub-agent: the same loop, started fresh, with only the read-only code tools and its own limits.
ExplainPackage returns a tool that hands one question about one package to a sub-agent: the same loop, started fresh, with only the read-only code tools and its own limits. func ExplainPackage(m agent.StreamModel, e *Env, lim agent.Limits) agent.Tool. In ch09/triage/subagent.go, line 23.
var m agent.StreamModel
var m agent.StreamModel. In ch09/triage/subagent.go, line 23.
package agent ("github.com/blackwell-systems/go-agents-book/code/ch09/agent")
Package agent is the agent loop and the types it works with.
Package agent is the agent loop and the types it works with. package agent ("github.com/blackwell-systems/go-agents-book/code/ch09/agent"). In ch09/agent.
type StreamModel interface {
Stream(ctx context.Context, req Request) iter.Seq2[Delta, error]
}
A StreamModel produces the next reply as a stream of pieces.
A StreamModel produces the next reply as a stream of pieces. type StreamModel interface { Stream(ctx context.Context, req Request) iter.Seq2[Delta, error] }. In ch09/agent/stream.go, line 44.
type Env struct {
Reports []Report
Issues *tracker.Store
Dir string // the workspace: the agent's copy of remind
Original string // remind as it was before the agent changed it
// TestSlots, if set, limits how many run_tests calls run at once,
// across every Env that shares it: six agents each running the
// whole suite with -race would starve each other (chapter 9).
TestSlots agent.Slots
// ...
}
An Env is everything the triage tools work on: the crash reports, the agent's working copy of remind, an untouched copy to check reproducers against, and the issue tracker.
An Env is everything the triage tools work on: the crash reports, the agent's working copy of remind, an untouched copy to check reproducers against, and the issue tracker. type Env struct { Reports []Report Issues *tracker.Store Dir string // the workspace: the agent's copy of remind Original string // remind as it was before the agent changed it // TestSlots, if set, limits how many run_tests calls run at once, // across every Env that shares it: six agents each running the // whole suite with -race would starve each other (chapter 9). TestSlots agent.Slots // ... }. In ch09/triage/env.go, line 23.
var lim agent.Limits
var lim agent.Limits. In ch09/triage/subagent.go, line 24.
type Limits struct {
MaxTurns int
MaxCost float64 // in dollars; 0 means no cost budget (chapter 5)
// Context, if set, builds each request's messages from the full
// conversation: trimming, clearing, or summarizing old turns. Nil
// sends the whole conversation, as before (chapter 8).
Context ContextPolicy
// Spend, if set, is a spending pool shared with other runs: the run
// ...
}
Limits holds the settings that bound a run.
Limits holds the settings that bound a run. type Limits struct { MaxTurns int MaxCost float64 // in dollars; 0 means no cost budget (chapter 5) // Context, if set, builds each request's messages from the full // conversation: trimming, clearing, or summarizing old turns. Nil // sends the whole conversation, as before (chapter 8). Context ContextPolicy // Spend, if set, is a spending pool shared with other runs: the run // ... }. In ch09/agent/types.go, line 138.
type Tool struct {
Def ToolDef
Run func(ctx context.Context, args jsontext.Value) (string, error)
// Safety flags (chapter 7). A tool with neither flag set may change
// something outside the run.
ReadOnly bool // it only looks things up
Idempotent bool // running it twice has the same effect as once
// Final marks the tool that ends the run: once a call to it
// ...
}
Tool is the harness's side of a tool: the definition the model sees, and the Go function that runs it.
Tool is the harness's side of a tool: the definition the model sees, and the Go function that runs it. type Tool struct { Def ToolDef Run func(ctx context.Context, args jsontext.Value) (string, error) // Safety flags (chapter 7). A tool with neither flag set may change // something outside the run. ReadOnly bool // it only looks things up Idempotent bool // running it twice has the same effect as once // Final marks the tool that ends the run: once a call to it // ... }. In ch09/agent/types.go, line 119.
func NewTool[A any](name, description string,
run func(ctx context.Context, args A) (string, error)) Tool
NewTool makes a Tool from a Go function whose arguments are the fields of a struct, A. The schema the model sees is generated from A, so the two can't drift apart.
NewTool makes a Tool from a Go function whose arguments are the fields of a struct, A. The schema the model sees is generated from A, so the two can't drift apart. func NewTool[A any](name, description string, run func(ctx context.Context, args A) (string, error)) Tool. In ch09/agent/registry.go, line 19.
const explainDesc = "Ask a helper to read one package of remind and " + ...
const explainDesc = "Ask a helper to read one package of remind and " + .... In ch09/triage/subagent.go, line 75.
var ctx context.Context
var ctx context.Context. In ch09/triage/subagent.go, line 26.
package context ("context")
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes. package context ("context"). Documented at pkg.go.dev, context.
type Context interface {
// Deadline returns the time when work done on behalf of this context
// should be canceled. Deadline returns ok==false when no deadline is
// set. Successive calls to Deadline return the same results.
Deadline() (deadline time.Time, ok bool)
// Done returns a channel that's closed when work done on behalf of this
// context should be canceled. Done may return nil if this context can
// never be canceled. Successive calls to Done return the same value.
// The close of the Done channel may happen asynchronously,
// ...
}
A Context carries a deadline, a cancellation signal, and other values across API boundaries.
A Context carries a deadline, a cancellation signal, and other values across API boundaries. type Context interface { // Deadline returns the time when work done on behalf of this context // should be canceled. Deadline returns ok==false when no deadline is // set. Successive calls to Deadline return the same results. Deadline() (deadline time.Time, ok bool) // Done returns a channel that's closed when work done on behalf of this // context should be canceled. Done may return nil if this context can // never be canceled. Successive calls to Done return the same value. // The close of the Done channel may happen asynchronously, // ... }. Documented at pkg.go.dev, context.Context.
type explainArgs struct {
Package string `json:"package" desc:"a package, such as schedule"`
Question string `json:"question" desc:"what to find out"`
}
type explainArgs struct { Package string `json:"package" desc:"a package, such as schedule"` Question string `json:"question" desc:"what to find out"` }. In ch09/triage/subagent.go, line 12.
type string string
string is the set of all strings of 8-bit bytes, conventionally but not necessarily representing UTF-8-encoded text.
string is the set of all strings of 8-bit bytes, conventionally but not necessarily representing UTF-8-encoded text. type string string. Documented at pkg.go.dev, builtin.string.
type error interface {
Error() string
}
The error built-in interface type is the conventional interface for representing an error condition, with the nil value representing no error.
The error built-in interface type is the conventional interface for representing an error condition, with the nil value representing no error. type error interface { Error() string }. Documented at pkg.go.dev, builtin.error.
var msgs []agent.Message
var msgs []agent.Message. In ch09/triage/subagent.go, line 27.
type Message struct {
Role string // "system", "user", "assistant", or "tool"
Content string // empty when the message has tool calls
ToolCalls []ToolCall // set on assistant messages that call tools
ToolCallID string // on tool messages: the call this answers
IsError bool // set on tool messages that report a failure
// ReasoningDetails is a reasoning model's record of its thinking,
// sent back unchanged with the tool calls it led to (chapter 4).
ReasoningDetails jsontext.Value
// ...
}
Message is one entry in the conversation.
Message is one entry in the conversation. type Message struct { Role string // "system", "user", "assistant", or "tool" Content string // empty when the message has tool calls ToolCalls []ToolCall // set on assistant messages that call tools ToolCallID string // on tool messages: the call this answers IsError bool // set on tool messages that report a failure // ReasoningDetails is a reasoning model's record of its thinking, // sent back unchanged with the tool calls it led to (chapter 4). ReasoningDetails jsontext.Value // ... }. In ch09/agent/types.go, line 38.
field Role string
"system", "user", "assistant", or "tool"
"system", "user", "assistant", or "tool" field Role string. In ch09/agent/types.go, line 39.
field Content string
empty when the message has tool calls
empty when the message has tool calls field Content string. In ch09/agent/types.go, line 40.
const explainPrompt = `You answer one question about one package of ` + ...
const explainPrompt = `You answer one question about one package of ` + .... In ch09/triage/subagent.go, line 80.
field Package string `json:"package" desc:"a package, such as schedule"`
field Package string `json:"package" desc:"a package, such as schedule"`. In ch09/triage/subagent.go, line 13.
field Question string `json:"question" desc:"what to find out"`
field Question string `json:"question" desc:"what to find out"`. In ch09/triage/subagent.go, line 14.
var tools []agent.Tool
var tools []agent.Tool. In ch09/triage/subagent.go, line 33.
func explainTools(e *Env) []agent.Tool
explainTools are the sub-agent's tools: reading code, and nothing else.
explainTools are the sub-agent's tools: reading code, and nothing else. func explainTools(e *Env) []agent.Tool. In ch09/triage/subagent.go, line 56.
func (e *Env) view() *Env
view returns an Env on the same workspace with bookkeeping of its own, for a sub-agent: the files it reads don't count as read by the parent, which must still read a file itself before patching it.
view returns an Env on the same workspace with bookkeeping of its own, for a sub-agent: the files it reads don't count as read by the parent, which must still read a file itself before patching it. func (e *Env) view() *Env. In ch09/triage/subagent.go, line 100.
var res agent.Result
var res agent.Result. In ch09/triage/subagent.go, line 34.
func RunStream(ctx context.Context, m StreamModel, tools []Tool,
msgs []Message, lim Limits) (Result, error)
RunStream runs the loop and returns when it ends, for callers that don't need to see the run as it happens.
RunStream runs the loop and returns when it ends, for callers that don't need to see the run as it happens. func RunStream(ctx context.Context, m StreamModel, tools []Tool, msgs []Message, lim Limits) (Result, error). In ch09/agent/loop.go, line 23.
package errors ("errors")
Package errors implements functions to manipulate errors.
Package errors implements functions to manipulate errors. package errors ("errors"). Documented at pkg.go.dev, errors.
func Is(err, target error) bool
Is reports whether any error in err's tree matches target.
Is reports whether any error in err's tree matches target. func Is(err, target error) bool. Documented at pkg.go.dev, errors.Is.
var ErrBudget = errors.New("agent: budget exhausted")
ErrBudget: the run used up a limit the caller set.
ErrBudget: the run used up a limit the caller set. var ErrBudget = errors.New("agent: budget exhausted"). In ch09/agent/errors.go, line 15.
package fmt ("fmt")
Package fmt implements formatted I/O with functions analogous to C's printf and scanf.
Package fmt implements formatted I/O with functions analogous to C's printf and scanf. package fmt ("fmt"). Documented at pkg.go.dev, fmt.
func Errorf(format string, a ...any) (err error)
Errorf formats according to a format specifier and returns the string as a value that satisfies error.
Errorf formats according to a format specifier and returns the string as a value that satisfies error. func Errorf(format string, a ...any) (err error). Documented at pkg.go.dev, fmt.Errorf.
func turns(res agent.Result) int
turns counts the assistant messages in a run.
turns counts the assistant messages in a run. func turns(res agent.Result) int. In ch09/triage/subagent.go, line 87.
var nil Type
nil is a predeclared identifier representing the zero value for a pointer, channel, func, interface, map, or slice type.
nil is a predeclared identifier representing the zero value for a pointer, channel, func, interface, map, or slice type. var nil Type. Documented at pkg.go.dev, builtin.nil.
field Messages []Message
field Messages []Message. In ch09/agent/types.go, line 155.
func len(v Type) int
The len built-in function returns the length of v, according to its type:
The len built-in function returns the length of v, according to its type: func len(v Type) int. Documented at pkg.go.dev, builtin.len.
func short(s string, n int) string
short cuts text to n runes on one line, marking the cut.
short cuts text to n runes on one line, marking the cut. func short(s string, n int) string. In ch09/triage/crashtools.go, line 57.

