Delegate to another agent (subagents)
weft.Subagent(name, description, child, opts...) returns a tool whose handler runs another agent. The parent model calls it with one argument, prompt; the child runs on a fresh transcript holding only that prompt, and the tool’s result is the child’s final text. Use it when an orchestrator should hand a self-contained task to a specialist and read its answer.
subagents/main.go gives an orchestrator a researcher:
researcher := weft.New(childModel, weft.Name("researcher"), weft.Instructions("You research one question and answer briefly."), deepSearch,)orchestrator := weft.New(parentModel, weft.Name("orchestrator"), weft.Subagent("research", "Research a topic in depth.", researcher, weft.Timeout(2*time.Minute), // bounds the child run ),)The tool’s description is all the parent model knows about the child, so write it as you would any tool’s. The package example is ExampleSubagent.
How it works
Section titled “How it works”A subagent is an ordinary tool (ADR 0014). Its handler runs the child through the same loop Generate and Stream use, on the parent call’s context. There is no second loop and no graph: it is the orchestrator-worker pattern built from the tool contract.
The child sees nothing of the parent’s conversation, only the prompt the parent model wrote and its own instructions. The prompt argument’s schema says so to the parent model: The task, stated in full: the agent sees only this prompt, not the conversation.
The child’s run is observable from the parent. Its events arrive in the parent’s stream, its usage is added to the parent’s, and Studio draws the delegation as an edge:


Delegate
Section titled “Delegate”Every tool option applies to the delegation:
weft.Timeoutbounds the child run. At the deadline the result is the ordinarytool "research" timed out after 2m0s, and the child stops at its next context check.weft.MaxResultBytescaps the child’s answer.weft.RequireApprovalgates the act of delegating: the call parks, andApproveruns the child.weft.Sequentialmakes the delegation a barrier, and the parent’sweft.Parallelismbounds concurrent delegations: with the defaultParallelism(4), four research calls in one step run their four children at once, and a fifth waits for a slot.- The parent’s
weft.WrapToolswraps the delegation once; the child’s own seams govern inside it.
A child built with weft.Output returns its last valid submit_output arguments, byte for byte, instead of its text. If it never made a valid submission, the tool’s result is its final text, and no error is raised. Canceling the parent’s context cancels the child.
What reaches the child run
Section titled “What reaches the child run”The child runs on its own agent’s configuration. Its run is built from the delegating call alone: the call’s context, a run id derived from the call, and the prompt argument. A parent’s run options reach the child only when they ride that context:
| Parent run option | Reaches the child? | What the child does |
|---|---|---|
weft.Metadata, and weft.WithMetadata on the context | Yes | Reads the merged pairs with weft.MetadataFromContext. |
weft.ParkAllExcept | Yes | Applies the rule to its own tools; a call it parks ends the delegation SUBAGENT_PENDING. |
Cancellation and deadline, weft.Timeout on the delegation included | Yes | Stops at its next context check. |
weft.Thinking, weft.Instructions, weft.Params, weft.ToolChoice | No | Sends its own agent’s defaults. |
weft.UseModel | No | Calls its own agent’s model. |
weft.OnlyTools | No | Is offered all of its own tools. |
weft.MaxSteps, weft.Parallelism (lowered) | No | Keeps its own agent’s limits. |
weft.ParkOn | No | Runs the named tools unasked. |
weft.Approve, weft.Deny, weft.Resolve, weft.ResolveError, weft.ResumeOf | No | Decides nothing of the parent’s. A child that parks ends SUBAGENT_PENDING. |
weft.Steering, weft.OnMessages | No | Gets no steering source and no transcript observer. |
weft.RunID, weft.Prompt, weft.Messages | No | Gets the id <parent>/<step>/<callID> and a transcript holding only the prompt argument. |
No error is raised. A parent run with Thinking(ThinkHigh), Instructions("run sys"), Params{Temperature: 0.9}, UseModel(alt), OnlyTools, MaxSteps(2) and ParkOn sent all of these on its own two model calls. Its child’s three requests, one more than the parent’s MaxSteps(2), carried the child’s system prompt, no thinking level, no temperature and both of the child’s tools; the parked tool ran (gotcha).
See the child’s events
Section titled “See the child’s events”Each event of the child run arrives in the parent’s stream wrapped in a weft.Nested: CallID is the parent call that owns the child, Event is the child’s event. Switch on the inner event as you would on the parent’s:
run := orchestrator.Stream(ctx, weft.Prompt("What is new in tool-use evaluation?"), weft.RunID("run-1"))for ev, err := range run.Events() { if err != nil { return err } switch ev := ev.(type) { case weft.ToolStart: fmt.Fprintf(w, "parent tool %s: %s\n", ev.CallID, ev.Name) case weft.Nested: // one event of the child run, owned by parent call ev.CallID switch inner := ev.Event.(type) { case weft.RunStart: fmt.Fprintf(w, " child %s started: %s\n", inner.ID, inner.Agent) case weft.ToolFinish: fmt.Fprintf(w, " child tool %s → %s\n", inner.Name, inner.Content) case weft.RunFinish: fmt.Fprintf(w, " child %s finished in %d steps\n", inner.RunID, inner.Steps) } case weft.ToolFinish: fmt.Fprintf(w, "parent tool %s → %s\n", ev.CallID, ev.Content) }}parent tool c1: research child run-1/0/c1 started: researcher child tool deep_search → 3 papers on tool-use evaluation child run-1/0/c1 finished in 2 stepsparent tool c1 → I found 3 papers on tool-use evaluation.The child’s whole run, RunStart through RunFinish, sits inside the delegating call’s ToolStart and ToolFinish. No Nested event for a call is delivered after that call’s ToolFinish, even when a timeout abandoned the child (the late-event rule, an amendment to ADR 0004).
A Nested event’s Seq comes from the parent’s counter, so the parent stream stays totally ordered with the child’s events in place. The inner event keeps its own RunID and Seq. A grandchild’s event is a Nested inside a Nested. wefttest.Flatten unwraps them all for a test.
A child run’s id is <parent>/<step>/<callID>: run-1/0/c1 is call c1 of step 0 of run run-1. A call executed under Approve gets <parent>/resume/<callID>. The id is on the nested RunStart (ID) and RunFinish (RunID), and on weft.CallFromContext inside the child’s tools; the parent’s tool result does not carry it.
Count the child’s usage
Section titled “Count the child’s usage”The child’s total usage is added to the parent’s RunResult.Usage and recorded per call on StepRecord.SubagentUsage. The step’s own Usage stays the model call’s numbers:
res, err := orchestrator.Generate(ctx, weft.Prompt("What is new in tool-use evaluation?"))if err != nil { return err}step := res.Steps[0]fmt.Fprintf(w, "step 0 model call: %d in, %d out\n", step.Usage.InputTokens, step.Usage.OutputTokens)for callID, u := range step.SubagentUsage { // the child's total, keyed by the delegating call fmt.Fprintf(w, "subagent %s: %d in, %d out\n", callID, u.InputTokens, u.OutputTokens)}fmt.Fprintf(w, "run total: %d in, %d out\n", res.Usage.InputTokens, res.Usage.OutputTokens)step 0 model call: 10 in, 5 outsubagent c1: 20 in, 10 outrun total: 40 in, 20 outA failed child’s partial usage counts too, as long as the child returns before its call finishes. A child abandoned by weft.Timeout is the exception: its usage is recorded only when the child run returns, after the timed-out call has finished, so none of it reaches RunResult.Usage, SubagentUsage or the parent’s UsageLimit, including the steps it ran before the deadline.
Because the child’s usage is otherwise the parent’s, weft.UsageLimit on the parent counts delegated work (rule 13). It counts it once the delegating call returns: the parent checks its limit only between its own steps, so it cannot stop a child that is running (How does a run stop?). A weft/thread pool child is the exception: it is a session, its usage is on its receipt, never on the parent run’s Usage (Run bounded child sessions with a pool).
Read the failure codes
Section titled “Read the failure codes”A child that fails never fails the parent run. Its failure is a coded tool error the parent model reads and reacts to:
res, err := orchestrator.Generate(ctx, weft.Prompt("What is new in tool-use evaluation?"))if err != nil { return err // the child's failure is not a parent run error}r := res.Steps[0].Results[0]fmt.Fprintf(w, "error result: %t\n%s\n", r.IsError, r.Content)error result: trueSUBAGENT_FAILED: agent "research" failed at step 0: model stream: provider downThe three codes are exported constants, so policy middleware can branch on them without parsing text:
| Constant | Result text | When |
|---|---|---|
weft.CodeSubagentFailed | SUBAGENT_FAILED: agent "<tool>" failed at step N: <cause> | The child run returned an error. Its *RunError is on ToolError.Err, reachable with errors.As in middleware. |
weft.CodeSubagentPending | SUBAGENT_PENDING: agent "<tool>" ended awaiting approval of N call(s) | The child parked a call. The parent’s transcript has nowhere to carry it. |
weft.CodeSubagentCycle | SUBAGENT_CYCLE: agent "<tool>" is already running in this call chain | The child is already running above this call; refused before any model call. |
The messages name the tool, not the child agent’s Name: the tool name is what the parent model called. The child’s own name is on the nested RunStart.Agent. Agents are immutable, so a cycle cannot be built at construction; a weft.ToolSource can close one at run time, and the guard compares *Agent pointers.
Complete example
Section titled “Complete example”subagents/main.go streams a delegation, reads its usage, and fails a child:
// Command subagents runs the examples of the guide "Delegate to another// agent (subagents)": go run ./subagents. Every model is scripted with// wefttest, so it runs offline; swap in a provider adapter for a real one.package main
import ( "context" "errors" "fmt" "io" "os" "time"
"github.com/weftgo/weft" "github.com/weftgo/weft/wefttest")
type SearchInput struct { Query string `json:"query" jsonschema:"what to search for"`}
// newOrchestrator builds a researcher child and an orchestrator that// delegates to it. childModel scripts the child; the parent calls the// research tool once and then answers.func newOrchestrator(childModel weft.Model) *weft.Agent { deepSearch := weft.Tool("deep_search", "Search the paper index.", func(_ context.Context, in SearchInput) (string, error) { return "3 papers on " + in.Query, nil }) parentModel := wefttest.Script( wefttest.ToolCalls(wefttest.Call{ID: "c1", Name: "research", Args: `{"prompt":"Find recent work on tool-use evaluation."}`}), wefttest.Say("Research found three papers."), ) researcher := weft.New(childModel, weft.Name("researcher"), weft.Instructions("You research one question and answer briefly."), deepSearch, ) orchestrator := weft.New(parentModel, weft.Name("orchestrator"), weft.Subagent("research", "Research a topic in depth.", researcher, weft.Timeout(2*time.Minute), // bounds the child run ), ) return orchestrator}
func researchScript() weft.Model { return wefttest.Script( wefttest.ToolCalls(wefttest.Call{ID: "c1", Name: "deep_search", Args: `{"query":"tool-use evaluation"}`}), wefttest.Say("I found 3 papers on tool-use evaluation."), )}
// nested streams the orchestrator and prints the child's events.func nested(ctx context.Context, w io.Writer) error { orchestrator := newOrchestrator(researchScript()) run := orchestrator.Stream(ctx, weft.Prompt("What is new in tool-use evaluation?"), weft.RunID("run-1")) for ev, err := range run.Events() { if err != nil { return err } switch ev := ev.(type) { case weft.ToolStart: fmt.Fprintf(w, "parent tool %s: %s\n", ev.CallID, ev.Name) case weft.Nested: // one event of the child run, owned by parent call ev.CallID switch inner := ev.Event.(type) { case weft.RunStart: fmt.Fprintf(w, " child %s started: %s\n", inner.ID, inner.Agent) case weft.ToolFinish: fmt.Fprintf(w, " child tool %s → %s\n", inner.Name, inner.Content) case weft.RunFinish: fmt.Fprintf(w, " child %s finished in %d steps\n", inner.RunID, inner.Steps) } case weft.ToolFinish: fmt.Fprintf(w, "parent tool %s → %s\n", ev.CallID, ev.Content) } } return nil}
// usage shows the child's usage rolled into the parent's result.func usage(ctx context.Context, w io.Writer) error { orchestrator := newOrchestrator(researchScript()) res, err := orchestrator.Generate(ctx, weft.Prompt("What is new in tool-use evaluation?")) if err != nil { return err } step := res.Steps[0] fmt.Fprintf(w, "step 0 model call: %d in, %d out\n", step.Usage.InputTokens, step.Usage.OutputTokens) for callID, u := range step.SubagentUsage { // the child's total, keyed by the delegating call fmt.Fprintf(w, "subagent %s: %d in, %d out\n", callID, u.InputTokens, u.OutputTokens) } fmt.Fprintf(w, "run total: %d in, %d out\n", res.Usage.InputTokens, res.Usage.OutputTokens) return nil}
// failure: the child's model fails; the parent model reads it as data.func failure(ctx context.Context, w io.Writer) error { orchestrator := newOrchestrator(wefttest.Script(wefttest.Fail(errors.New("provider down")))) res, err := orchestrator.Generate(ctx, weft.Prompt("What is new in tool-use evaluation?")) if err != nil { return err // the child's failure is not a parent run error } r := res.Steps[0].Results[0] fmt.Fprintf(w, "error result: %t\n%s\n", r.IsError, r.Content) fmt.Fprintln(w, "answer:", res.Text()) return nil}
func run(ctx context.Context, w io.Writer) error { steps := []struct { title string fn func(context.Context, io.Writer) error }{ {"nested events", nested}, {"usage", usage}, {"failure", failure}, } for _, s := range steps { fmt.Fprintf(w, "== %s\n", s.title) if err := s.fn(ctx, w); err != nil { return fmt.Errorf("%s: %w", s.title, err) } } return nil}
func main() { if err := run(context.Background(), os.Stdout); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) }}View on GitHub · run it from docs-site/examples:
go run ./subagentsgo test ./subagents== nested eventsparent tool c1: research child run-1/0/c1 started: researcher child tool deep_search → 3 papers on tool-use evaluation child run-1/0/c1 finished in 2 stepsparent tool c1 → I found 3 papers on tool-use evaluation.== usagestep 0 model call: 10 in, 5 outsubagent c1: 20 in, 10 outrun total: 40 in, 20 out== failureerror result: trueSUBAGENT_FAILED: agent "research" failed at step 0: model stream: provider downanswer: Research found three papers.Best practices & gotchas
Section titled “Best practices & gotchas”- Keep approval-gated tools in the orchestrator. A child that parks returns
SUBAGENT_PENDINGand its call cannot be decided from the parent; putRequireApprovalon the subagent tool instead. (Source: ADR 0014,weft/core/subagent.go:23-28) - Pass a built agent.
weft.Subagentpanics whenchildis nil, withweft: Subagent "research" called with a nil agentfor a tool namedresearch, at construction rather than on the first call. (Source:weft/core/subagent.go:304-308) - Do not count on an
Outputchild failing when it never submits. Without a validsubmit_outputcall the result falls back to the child’s final text, with no error and no code, so the parent model reads prose where it expected JSON. (Source:weft/core/subagent.go:264-270, 331-336;weft/core/output.go:135-153) - Write the delegation’s description for the parent model. It is the parent’s entire routing surface for the child. (Source:
weft/core/subagent.go:279-282) - Set a
Timeouton long children, and bound what it leaves uncounted. The child runs on the call’s deadline context, so at the deadline its in-flight model request is cancelled and it calls the model no more. The steps it ran before the deadline are not counted: none of their usage reaches the parent, so the parent’sUsageLimitcannot cover them. Bound the child itself with its ownMaxStepsorUsageLimit. (Source: ADR 0014, “Cancellation and timeouts” and the late-event rule;weft/core/subagent.go:318-319;weft/core/loop.go:1265-1272, 1381, 2156) - Configure the child agent, not the parent’s run. A per-run
Thinking,UseModel,Params,Instructions,ToolChoice,OnlyToolsor loweredMaxStepschanges the parent’s model calls only. Build the child with the setting it needs, or build a second child agent for the variant. To vary a child per run, give it aweft.PrepareStepthat reads the inheritedweft.MetadataFromContext(ctx): a child whosePrepareStepsetThinkHighonthink=highsent level 4 under a parent run withMetadata{"think": "high"}. (Source:weft/core/subagent.go:316;weft/core/loop.go:63;weft/core/agent.go:176) - Budget with
UsageLimiton the parent, and bound each child itself. Delegated usage counts toward the parent’s limit, and there is no depth cap. The parent checks the limit only before its next model call, so every child of the step runs to its own end first. Give each child agent its ownUsageLimitandMaxStepsto bound one delegation. (Source: ADR 0014, “The cycle guard”; AGENTS.md rule 13;weft/core/loop.go:849, 1102-1116) - Read
SubagentUsagefor attribution, notStepRecord.Usage. The step’s usage is its own model call only. (Source: ADR 0014, “Usage”)
See also
Section titled “See also”- How do tools work?: a subagent is one
- Stream a run’s events
- Run bounded child sessions with a pool
- The agent loop, from first principles
Symbols used: weft.Subagent · weft.Nested · weft.CodeSubagentFailed · weft.CodeSubagentPending · weft.CodeSubagentCycle · weft.StepRecord · weft.RunResult · weft.ToolError · weft.Timeout · weft.MaxResultBytes · weft.Parallelism · weft.UsageLimit · weft.Output · weft.RunID · weft.Name · weft.Instructions · weft.Tool · weft.New · ExampleSubagent · wefttest.Flatten · wefttest.Script