Introduction
Subagents allow one agent to delegate part of its work to another agent that runs in complete isolation. Each child agent has its own state, system prompt, tool set, resource budget, and LLM configuration. The parent agent decides when to delegate by calling thespawn_subagent tool, and the child’s final output is returned to the parent as a tool result.
This delegation model is useful when different parts of a task require different expertise, tool access, or resource limits. A code review agent might spawn a “security reviewer” subagent with read-only file access and a tight step budget, while also spawning a “style checker” subagent with different instructions. The parent orchestrates the overall workflow without needing to know the implementation details of each child.
Quick Start
The following example sets up a parent agent with file tools and a “reviewer” subagent that can only read files:spawn_subagent. The tool schema includes a description of all available subagents and their purposes, giving the LLM the information it needs to choose the right one.
How Delegation Works
When the parent agent callsspawn_subagent(subagent: 'reviewer', prompt: 'Review this file...'), the following sequence occurs:
- Depth check — the system verifies that the current nesting depth has not exceeded the configured maximum. If it has, a
SubagentDepthExceededExceptionis thrown and returned to the parent as a tool error. - Definition lookup — the
AgentDefinitionRegistryresolves the namedAgentDefinition. If the name is not found, aSubagentNotFoundExceptionis thrown. - Tool filtering — the child’s tool set is determined by applying the definition’s
toolsallow-list andtoolsDenydeny-list against the parent’s available tools. - Driver resolution — the child inherits the parent’s tool-use driver. If the definition specifies an
llmConfigand the driver supportsCanAcceptLLMConfig, the child’s driver is reconfigured with the specified model/provider. - Budget application — if the definition declares an
ExecutionBudget,UseGuardsis applied to the child’s builder with the budget’s limits. - Loop construction — an
AgentBuilderassembles the childAgentLoopfrom the filtered tools, configured driver, and guards. - State initialization — a fresh
AgentStateis created with the definition’s system prompt and the caller’s prompt as the user message. If the definition has skills, they are injected as additional system messages. - Execution — the child loop runs to completion. If the child fails (
ExecutionStatus::Failed), aSubagentExecutionExceptionis thrown. - Result return — the child’s final
AgentStateis returned to the parent as the tool call result. The parent continues its execution with this information.
Defining Subagents
Subagents are defined using the sameAgentDefinition class used by agent templates. You can register them programmatically or load them from files.
Programmatic Registration
File-Based Registration
Definitions can be loaded from.md, .yaml, or .json files:
Tool Visibility
Tool visibility is one of the most important aspects of subagent design. It determines what a child agent can do, and more importantly, what it cannot.Inheriting All Parent Tools
By default (whentools is null), the child inherits every tool the parent has, including spawn_subagent itself:
Allow-List
Settingtools to a NameList creates a strict allow-list. Only the named tools are available to the child:
Deny-List
ThetoolsDeny field removes specific tools from whatever set the child would otherwise have. This is useful when you want to inherit most tools but block a few dangerous ones:
spawn_subagent in Children
If the child inheritsspawn_subagent, the tool is automatically replaced with a nested version that tracks depth. This means children can spawn their own subagents, subject to the depth policy. If you want to prevent this, add spawn_subagent to the deny list:
Depth Control
Subagents can spawn their own subagents, creating a recursive hierarchy. TheSubagentPolicy controls the maximum nesting depth to prevent unbounded recursion.
Using SubagentPolicy
maxDepth is 3. A depth of 0 means the parent itself; a depth of 2 means the parent can spawn children, and those children can spawn grandchildren, but no further.
Convenience Factory
For simple depth configuration, use the staticforDepth() factory:
Depth Exceeded Behavior
When a subagent attempts to spawn at a depth that exceeds the policy, aSubagentDepthExceededException is thrown. This exception is returned to the calling agent as a tool error, allowing it to handle the situation gracefully (typically by performing the work itself).
Child Budgets and Models
Each child agent can declare its own resource budget and LLM configuration independently from the parent.Custom Budget
Custom Model
Children can use a different model or provider than the parent. This is useful for cost optimization — simple tasks can use a cheaper model while complex analysis uses a more capable one.llmConfig is specified, the child inherits the parent’s LLM configuration. You can also pass just a driver name as a string:
Skill Injection
Subagents can reference named skills from aSkillLibrary. When skills are specified in the definition, their rendered content is injected as additional system messages before the user prompt.
Events
The subagent lifecycle emits two events through the parent’s event dispatcher, providing visibility into delegation activity.SubagentSpawning
Dispatched when a parent agent is about to spawn a child. Contains context for tracing the delegation hierarchy.parentAgentId— the parent’s agent IDsubagentName— the name of the subagent being spawnedprompt— the task/question sent to the childdepth/maxDepth— current and maximum nesting depthparentExecutionId,parentStepNumber,toolCallId— correlation IDs for tracing
SubagentCompleted
Dispatched when a child agent finishes execution, regardless of success or failure.parentAgentId— the parent’s agent IDsubagentName— the name of the completed subagentsubagentId— the child’s unique agent IDstatus— theExecutionStatus(completed, failed, etc.)steps— total steps the child tookusage— token usage data (nullable)startedAt/completedAt— timestamps for duration calculationparentExecutionId,parentStepNumber,toolCallId— correlation IDs for tracing
Error Handling
The subagent system defines three specific exception types:| Exception | When |
|---|---|
SubagentNotFoundException | The named subagent does not exist in the registry |
SubagentDepthExceededException | The spawn would exceed the configured maxDepth |
SubagentExecutionException | The child agent finished with ExecutionStatus::Failed |
The Tool Schema
Thespawn_subagent tool automatically generates its schema from the registry. The schema includes:
- A
subagentparameter as an enum of all available agent names - A
promptparameter for the task or question - A description that lists all available subagents with their descriptions and tool access