Subagents
Let an agent delegate self-contained tasks to named child agents, each in its own run with its own message history.
While Pydantic AI Harness is on 0.x releases, the API may change between minor releases; when it does, deprecation warnings and release-note migration guidance tell you (or your agent) exactly how to upgrade. See the version policy.
flowchart TB
accTitle: Subagents: hand a task to another agent run
accDescr: The parent model calls delegate_task and gets a result. The SubAgents capability passes the task to researcher, writer or self, a new run with its own message history, and gets str(result.output) back. It does not run the child on an unknown agent name, max_calls used up or max_depth reached, and a child stops early if timeout_seconds or usage_limits is reached or it failed.
model(["parent model"])
subagents["SubAgents()<br/>delegate_task"]:::capability
child["researcher, writer or self<br/>a new run with its<br/>own message history"]
refused["unknown agent name,<br/>max_calls used up,<br/>or max_depth reached"]:::blocked
stopped["timeout_seconds or<br/>usage_limits reached,<br/>or the child failed"]:::blocked
model <-->|"tool call, result"| subagents
subagents <-->|"task, str(result.output)"| child
subagents -.-x|"does not run the child"| refused
child -.-x|"stopped early"| stopped
classDef capability stroke:#E520E9,stroke-width:2px
classDef blocked stroke:#E5533D,stroke-width:2px,stroke-dasharray:4 3
One agent that does everything accumulates many tools and a long context. Specialized sub-agents keep each context focused, but hand-wired delegation needs a tool per agent, forwarded deps, threaded usage limits, and a prompt listing the delegates.
SubAgents takes a sequence of SubAgent entries and exposes one delegate_task(agent_name, task) tool. Each delegation runs the chosen sub-agent in its own run, which never sees the parent conversation, and returns its output to the parent. The system prompt lists the sub-agents by name and description (the agent’s own, or SubAgent(description=...); one without a description is listed by name alone), so the listing stays in the cached prefix; a change between runs of the same conversation is appended instead of rewriting the prefix.
from pydantic_ai import Agent
from pydantic_ai_harness import SubAgent, SubAgents
researcher = Agent('anthropic:claude-opus-5-5', name='researcher', description='Researches a topic')
writer = Agent('anthropic:claude-opus-5-5', name='writer', description='Turns notes into polished prose')
orchestrator = Agent(
'anthropic:claude-opus-5-5',
capabilities=[SubAgents(agents=[SubAgent(researcher), SubAgent(writer)])],
)
result = orchestrator.run_sync('Research the history of TLS and write a one-paragraph summary.')
print(result.output)
A delegate’s name, used by the parent model and in the prompt listing, is the agent’s own name or a SubAgent(name=...) override. An agent with neither is rejected, and two delegates with the same name are an error.
| Tool | Purpose |
|---|---|
delegate_task(agent_name, task) | Run the named sub-agent on a self-contained task and return its output. |
taskmust be self-contained, since the sub-agent does not see the parent conversation.- An unknown
agent_nameraisesModelRetry, so the model can correct itself. - The parent gets
str(result.output). - With a
modelsmenu, the tool takes an extramodelargument (see below).
- Deps are forwarded. Each sub-agent gets the parent run’s
deps, so it shares the parent’sAgentDepsT(every sub-agent is anAbstractAgent[AgentDepsT, Any]). - The workspace is inherited, unless
workspace_resolverselects another directory. Parent read-only restrictions still apply. - Usage is shared by default. Each sub-agent run gets the parent’s
usage, so token usage aggregates and a parentusage_limitsapplies across the whole agent tree. Setforward_usage=Falseto give each sub-agent run its own accounting. - The parent’s tools are not passed on. A sub-agent runs with its own tools. To delegate to an agent with all of the parent’s tools and capabilities, use
include_self=True(see below). - Capabilities can be shared.
shared_capabilitiesapply to every sub-agent run, for example a common guardrail, memory, or planning capability, without rebuilding eachAgent. - Sub-agent events can be streamed. An
event_stream_handleris forwarded to each sub-agent run, so its model-streaming and tool events reach the caller. The handler receives the sub-agent’s ownRunContext.
inherit_tools=True is deprecated and emits a HarnessDeprecationWarning. It adds the parent agent’s own tools (from tools= or toolsets=, minus the delegate tool) to each sub-agent run, but not the tools from the parent’s capabilities. Instead, bind the tools an explicit sub-agent needs to its Agent, use include_self=True, or give disk-loaded agents tools with a tool_resolver.
With include_self=True, the roster also lists the running agent as self. A delegation to self starts a fresh run of that agent (RunContext.agent) on the parent run’s model (or the models option the parent picks), with no parent conversation. The child is the same Agent, so every capability, toolset, and instruction bound to it registers again in the child run: a guardrail, approval gate, or audit hook bound next to SubAgents sees the delegate’s tool calls, not only the delegate_task call. Coder uses this by default.
from pydantic_ai import Agent
from pydantic_ai_harness import SubAgents
agent = Agent(
'anthropic:claude-opus-5-5',
capabilities=[SubAgents(include_self=True)],
)
- Only what is bound to the
Agentcarries over. Capabilities, toolsets, instructions, and model settings passed to the parent’srun()do not reach the delegate. PassingSubAgents(include_self=True)itself torun()raises aUserErrorwhen the run starts, since the delegate would come up without it. - Delegation depth is capped. The delegate has
delegate_tasktoo, somax_depth(default3, counting the top-level run) bounds the tree: the top-level run delegates, its delegates delegate once more, and a run at the limit gets neitherdelegate_tasknor the sub-agent listing. The limit applies to every delegation throughSubAgents, including explicit rosters. - Delegates inherit everything, including what may not suit a sub-task. An
AskUsercapability bound to the agent can prompt the user from inside a delegation. The delegate returns the agent’s ownoutput_type, rendered withstr(); a run that ends withDeferredToolRequestsorPendingModelResponsereturns a steering message instead (see Failure handling), unlessforward_deferred_calls=Truepasses its deferred tool calls to the caller (see Approving a delegate’s tool calls). - The deprecated
inherit_toolsdoes not apply toself, whose tools are already the parent’s. The nameselfis reserved: an explicit delegate with that name is an error, and a disk definition with that name is skipped with a warning. - On Temporal,
agent_foldersis not supported. Disk-loaded sub-agents add a toolset at run time, which Temporal refuses, so passagent_folders=None. Whenselfis the only delegate, it runs in the workflow, so register aModelinstance frommodelswithTemporalDurability(models=...). Otherwise delegations run in an activity, or in a child workflow when you opt in (see Delegates as child workflows). Neither has the parent run’s model, so a delegate needs a model of its own (or, in an activity, amodelsoption); see delegation on Temporal.
Each SubAgent carries its own budgets; one with none set runs with the SubAgents defaults.
from pydantic_ai import Agent
from pydantic_ai.usage import UsageLimits
from pydantic_ai_harness import SubAgent, SubAgents
reproducer = Agent('anthropic:claude-opus-5-5', instructions='Reproduce the reported bug from a minimal script.')
librarian = Agent('anthropic:claude-opus-5-5', instructions='Find relevant docs, issues, and prior art.')
orchestrator = Agent(
'anthropic:claude-opus-5-5',
capabilities=[
SubAgents(
agents=[
SubAgent(reproducer, usage_limits=UsageLimits(request_limit=35), timeout_seconds=600, max_calls=1),
SubAgent(librarian, usage_limits=UsageLimits(request_limit=18), timeout_seconds=300, max_calls=2),
]
)
],
)
| Field | Effect |
|---|---|
models | The SubAgents menu keys this delegate may run on. The first key is its default. See Per-delegation model selection. |
usage_limits | A request/token budget for one delegation. The child gets its own usage accounting, so the budget counts only that child’s requests and tokens. With forward_usage=True, the child’s usage is added to the parent’s after the delegation. Reaching the budget is a soft outcome (see below), not a run-stopping UsageLimitExceeded. |
timeout_seconds | A wall-clock budget for one delegation. A child that exceeds it is cancelled and the parent gets a steering message. The cancelled child’s event_stream_handler stops receiving events without a terminal event. |
max_calls | The maximum delegations to this sub-agent per parent run. After that, delegations return a budget-exhausted steering message without running the child. Counts are per Agent.run (a run_id) and cleared when it ends, so each parent run and each level of a nested tree has its own budget. A delegation refused before it starts, by max_running_tasks or a listener’s veto, doesn’t count. |
on_failure | A steering message that replaces the built-in default for any soft outcome of this delegate. While on_model_error is unset, it also makes child failures soft (see below). |
on_model_error | What the parent gets when the child fails with a soft model error: 'retry' raises a parent ModelRetry, 'return' returns the error and the steering message as a normal tool result. Unset means 'return', with the on_failure message alone, when on_failure is set, and 'retry' otherwise. |
contain_errors | Whether an unexpected crash in this delegate returns to the parent as a bounded ModelRetry instead of aborting the parent run. Unset inherits SubAgents(contain_errors=...) (off). |
keep_partial_output | Whether a child stopped by timeout_seconds or its own usage_limits passes its last text response to the parent. Off by default. |
read_only | Wrap the child’s workspace in ReadOnlyWorkspace, which refuses commands and file changes through the workspace API. Off by default. |
Let the orchestrator pick a model per task: with a models menu, the delegate tool gains a model argument naming one of its keys.
from pydantic_ai import Agent
from pydantic_ai.settings import ModelSettings
from pydantic_ai_harness import SubAgent, SubAgents
from pydantic_ai_harness.sub_agents import ModelOption
reviewer = Agent('anthropic:claude-opus-5-5', name='reviewer', description='Reviews a diff')
linter = Agent('anthropic:claude-opus-5-5', name='linter', description='Runs the linter and reports failures')
orchestrator = Agent(
'anthropic:claude-opus-5-5',
capabilities=[
SubAgents(
agents=[SubAgent(reviewer), SubAgent(linter, models=['fast'])],
models={
'fast': 'anthropic:claude-haiku-5-5',
'standard': 'anthropic:claude-sonnet-5-5',
'deep': ModelOption(
'anthropic:claude-opus-5-5',
description='hard reasoning, multi-file changes',
settings=ModelSettings(thinking='xhigh'),
),
},
)
],
)
- Off by default. Without a
modelsmenu, the tool schema has nomodelargument. - The keys are the interface. The system prompt lists them with each entry’s model and description, and the tool schema offers them as an enum, so the model picks from the menu instead of inventing a model name. Name them for the job (
'fast','deep'), not the vendor. - An entry is a model or a
ModelOption.ModelOption(model, description=..., settings=...)adds a routing hint and per-optionModelSettings, so one key can mean “same model, more thinking”. The settings merge over the sub-agent’s ownmodel_settings, keeping the parts the option does not set. - Resolution order. The key the parent passed, else the delegate’s first allowed key, else the delegate’s own model, else the parent run’s model.
- A delegate can be restricted.
SubAgent(linter, models=['fast'])pins that delegate tofast: it runs on the first listed key when the parent passes nomodel, and other keys are refused with aModelRetry. The prompt listing shows the restriction (- linter: Runs the linter (models: fast)). A key the menu does not define is aValueErrorat construction. - A rejected key costs nothing. An unknown or unavailable key returns a
ModelRetrylisting the valid options, before the delegate’smax_callsbudget is charged.
Set workspace_resolver to offer delegate_task(working_directory=...). The async callback receives the parent RunContext and a DelegationWorkspaceRequest with the delegate name and requested directory, and returns a Workspace. It validates the request and decides which delegates may use another workspace. Without it, the tool has no working_directory and children inherit the parent’s workspace.
from pydantic_ai import Agent, RunContext
from pydantic_ai.exceptions import ModelRetry
from pydantic_ai.workspaces import LocalWorkspaceBackend, Workspace
from pydantic_ai_harness.file_system import FileSystem
from pydantic_ai_harness.sub_agents import DelegationWorkspaceRequest, SubAgent, SubAgents
workspaces: dict[str, Workspace] = {'/repos/policy': Workspace(LocalWorkspaceBackend('/repos/policy'))}
async def resolve_workspace(ctx: RunContext[object], request: DelegationWorkspaceRequest) -> Workspace:
if request.agent_name != 'reviewer' or request.directory not in workspaces:
raise ModelRetry('Choose the reviewer and a configured directory.')
return workspaces[request.directory]
reviewer = Agent(name='reviewer', deps_type=object, capabilities=[FileSystem(read_only=True)])
delegation = SubAgents(
agents=[SubAgent(reviewer, read_only=True)],
workspace_resolver=resolve_workspace,
)
- The child’s relative file paths and repository instructions use the returned workspace. Read-only restrictions from the parent or
SubAgent(read_only=True)still apply. Limit the delegate to trusted read-only tools too, since arbitrary Python tools can bypass the workspace API. The resolver must keep any other backend restrictions the application requires. - The child’s whole workspace gets the lowest
authoritythe parent gives anything in or above that directory,path_authorityentries included, so no file gets more authority in the child than the parent gives it. A directory outside the parent’s working directory is at'none', as the parent gives it, unless one of the parent’spath_authorityentries contains it: name it there, such as{'/srv/checkouts': 'operator'}, to let the delegate’s repository instructions, skills and agent definitions reach it as instructions. - The caller owns the returned workspace and keeps its resources alive until background children finish.
- Managed tasks record the resolved directory in
DelegationTask.working_directory. A resume without the argument resolves that saved directory again, so the resolver must accept its own resolved spelling; changing it is rejected. Older tasks without this field inherit the parent workspace. - Remote and durable delegations reject directory overrides.
- This does not change where disk agent definitions are found:
SubAgents.workspacecontrols that.
A soft outcome returns a steering message to the parent as a normal tool result, so its model reads it and decides what to do next, instead of re-delegating straight away as a ModelRetry invites. A timeout, a reached usage_limits budget, and an exhausted max_calls budget are always soft. on_failure replaces the built-in message for these outcomes.
With keep_partial_output=True, a delegation stopped by its timeout or its own usage budget also passes the child’s last text response to the parent. It follows the steering message (or on_failure) as <partial_output>...</partial_output>, and the outcome stays timeout or budget. DelegationFinishedEvent.output carries the same text, bounded like any other output. The text has not passed the child’s output validation: it can be text the child’s output validator or OutputGuardrail rejected, so leave this off for a child whose guardrails keep content from its parent. Text from a response the child answered with a retry is skipped, as is a final response the run stopped before acting on, or one whose output tool call the stop cut off before its verdict. A child with no such text returns the steering message alone.
A sub-agent run that ends with DeferredToolRequests (its output_type includes it and a tool needed approval or was deferred) is soft too by default. The parent’s model cannot approve the child’s tool calls or resume its run, and the same task would likely stop the same way again, so the delegation returns a steering message naming the sub-agent and why it stopped, or the on_failure message. With forward_deferred_calls=True, the calls go to the parent run’s caller instead, and the child resumes once they are answered (see Approving a delegate’s tool calls). A sub-agent that resolves its own deferred calls, for example with HandleDeferredToolCalls, never ends this way. A run that ends with PendingModelResponse (a model request left waiting on the provider, for example in a batch) returns a steering message the same way, including on a remote worker, and the request is cancelled, since nobody will check on it later. Cancelling is best effort, and a batch is cancelled only once no other request in it is still waiting.
A sub-agent run that fails with a soft model error (ModelRetry, or UnexpectedModelBehavior such as exhausted retries) becomes a ModelRetry for the parent by default: the parent’s model sees Sub-agent '<name>' failed: ... and can re-delegate. The delegate tool defaults to tool_retries=2, so the parent aborts only after that many consecutive delegate failures; a successful delegation resets the count. Raise tool_retries for a flakier sub-agent, or set None to inherit the parent agent’s default. on_model_error='return' makes a delegate’s failures soft: the parent gets Sub-agent '<name>' failed: ... as a normal tool result, followed by the on_failure message or a default steering message. on_model_error='retry' keeps the parent ModelRetry even with on_failure set, so on_failure then customizes only the other soft outcomes. With on_model_error unset, on_failure makes failures soft and returns its message alone, without the error.
Hard errors stop the whole run. A UsageLimitExceeded from a child with no per-delegate usage_limits (sharing the parent’s accounting) means the whole tree is out of budget, and propagates; a child reaching its own usage_limits is soft, as above.
An unexpected crash, any other exception the child raises (a provider ModelAPIError or FallbackExceptionGroup, a ValueError from a bad tool argument), propagates by default and aborts the parent run. contain_errors=True (per delegate, or as the SubAgents default) returns it to the parent as a bounded ModelRetry instead, so one crash cannot kill the whole run. The exception is in the retry message (Sub-agent '<name>' crashed: ...) and logged through logging, and tool_retries still turns consecutive crashes into an abort. A contained crash always raises this retry, never the on_failure return. These bypass containment: cancellation, a shared UsageLimitExceeded, Pydantic AI control-flow signals (CallDeferred, ApprovalRequired, the Skip* signals), and UserError. External cancellation (asyncio.CancelledError) propagates as-is. A child’s own cancellation (RunContext.cancel() in the child, raising RunCancelled) leaves the delegate tool uncontained; Pydantic AI then isolates it as a failed delegate_task return the parent model can react to, not a crash retry that invites re-delegation.
With SubAgents(forward_deferred_calls=True), a sub-agent run that ends with DeferredToolRequests doesn’t return a steering message. The delegate call raises ApprovalRequired instead, so the parent run ends with DeferredToolRequests too, and its caller answers the sub-agent’s calls the way it answers the parent’s own. The parent’s output_type must include DeferredToolRequests, or a HandleDeferredToolCalls handler on the parent must answer them through the same two functions below. Whatever approves the delegate_task call itself, such as a handler that doesn’t use them or a UI adapter like AG-UI, which shows the user only that call, approves none of the sub-agent’s calls.
delegated_requests() lists the sub-agent’s calls in place of the delegate call that stopped on them, each under the delegate call’s ID and its own joined by : ('c1:e1'), with an agent_path metadata entry naming the delegates it was made under, outermost first. delegated_results() routes the answers back. Both only look at calls of the delegate tool, delegate_task: if SubAgents(tool_name=...) renames it anywhere in the delegation tree, pass every name to both as tool_names=.
from pydantic_ai import Agent, DeferredToolRequests
from pydantic_ai_harness import SubAgent, SubAgents
from pydantic_ai_harness.sub_agents import delegated_requests, delegated_results
mailer = Agent('anthropic:claude-opus-5-5', name='mailer', output_type=[str, DeferredToolRequests])
@mailer.tool_plain(requires_approval=True)
def send_email(to: str, body: str) -> str:
return f'Sent to {to}'
orchestrator = Agent(
'anthropic:claude-opus-5-5',
output_type=[str, DeferredToolRequests],
capabilities=[SubAgents(agents=[SubAgent(mailer)], forward_deferred_calls=True)],
)
async def run_with_approvals(prompt: str) -> str:
result = await orchestrator.run(prompt)
while isinstance(result.output, DeferredToolRequests):
requests = delegated_requests(result.output)
approvals: dict[str, bool] = {}
for call in requests.approvals:
path = ' > '.join(requests.metadata.get(call.tool_call_id, {}).get('agent_path', ['agent']))
approvals[call.tool_call_id] = input(f'{path} wants {call.tool_name}({call.args}). Approve? ') == 'y'
result = await orchestrator.run(
message_history=result.all_messages(),
deferred_tool_results=delegated_results(result.output, requests.build_results(approvals=approvals)),
)
return result.output
The next run resumes the sub-agent from its own history with those answers, so the calls it already ran don’t run again, and the delegation then ends like any other. A delegate that sets forward_deferred_calls too passes its own delegates’ calls up the same way.
- Every call the sub-agent waits on needs an answer:
delegated_results()raisesValueErrorotherwise. Deny a call withFalseorToolDenied. - Only the sub-agent decides which of its calls need approval. Approving the delegate call itself, for example with
build_results(approve_all=True)on the parent’s requests or through an approval gate on the delegate tool, approves none of them: the delegation runs the task again, and passes on the calls it stops on. - Waiting sub-agent history is stored server-side in
deferred_state_store. By default,InMemoryDeferredStateStorekeeps up to 1000 states for 24 hours in-process, so resume through the sameSubAgentsinstance; pass a customDeferredStateStore(such as a database-backed one) to resume in another process. - Resuming removes the saved state before the sub-agent runs, so the same answers resume it at most once: if the resumed delegation fails, resubmitting them raises
UserErrorinstead of running approved calls again. Missing or mismatched states, or answers to calls the sub-agent didn’t ask about, also raiseUserError. Approving the delegate call itself runs the task afresh. - Resuming runs whichever sub-agent and tools are registered under the same names at resume time, not the implementations that deferred the calls, so a deployment that replaces them in between runs the approved calls with the new ones.
- The delegation that stops emits a
DelegationFinishedEventwith outcomefailed, whoseoutputsays the sub-agent is waiting for answers, and the sub-agent’s usage up to that point counts like any delegation’s. The resumed run is a new delegation, with its own events. - Durable execution and
task_controldon’t support it:forward_deferred_calls=Truewith either raises an error.
SubAgents emits typed capability events in the sub_agents namespace, so a host can show a delegation as it runs and how it ended without parsing the delegate tool’s arguments and result:
| Event | Dispatch | When | Payload |
|---|---|---|---|
DelegationStartedEvent | stream | a delegation passed every check and the child run is about to start | agent_name, task, truncated, model (the menu key, or None), inherits_tools |
DelegationFinishedEvent | stream | the delegation settled into what the parent receives | agent_name, outcome, output, truncated, usage, duration_ms |
Both are notifications. A start and its end share the tool_call_id core stamps on every event, which pairs them when the model delegates in parallel. duration_seconds is the deprecated name of duration_ms: it still reads, in seconds and with a warning, and a payload saved under it still loads.
outcome follows Failure handling:
ok: the child’s output went back to the parent.timeoutorbudget: the child hit itstimeout_secondsor its ownusage_limits.failed: a soft model error, returned or raised peron_model_error, or a run that ended withDeferredToolRequestsorPendingModelResponse, including one whose deferred tool callsforward_deferred_callspassed to the caller.contained: a crashcontain_errorscaught.
output is what the delegate tool returns to the parent: the child’s output, the steering message, or the retry text. It is emitted inside the tool, before any ToolGuardrail result guard screens it; for the screened text, read the ToolReturnPart in core’s FunctionToolResultEvent. usage is the child’s own RunUsage when it has separate accounting (usage_limits set, or forward_usage=False), and None when its usage goes into the parent’s.
A delegation refused before the child runs (an unknown sub-agent, a model key off the menu, an exhausted max_calls budget) emits nothing; the tool result says why. An exception out of the delegate tool (a shared usage limit, an uncontained crash, a cancellation) ends without an end event. A SubAgentToolset registered directly in Agent(toolsets=[...]) has no owning capability and emits nothing. As with any capability event, a listener that raises aborts the parent run.
task and output are cut at MAX_EVENT_TEXT_CHARS (4096) with a truncated flag, so one verbose delegation cannot flood a persisted or forwarded event stream. The task events and AgentCreatedEvent are not cut.
from pydantic_ai import Agent
from pydantic_ai.capabilities import AbstractCapability, on_event
from pydantic_ai_harness.sub_agents import DelegationFinishedEvent, SubAgent, SubAgents
class ReportDelegations(AbstractCapability):
@on_event(DelegationFinishedEvent)
async def on_delegation_end(self, ctx, event: DelegationFinishedEvent) -> None:
print(f'{event.agent_name}: {event.outcome} in {event.duration_ms / 1000:.1f}s')
researcher = Agent('anthropic:claude-opus-5-5', name='researcher')
agent = Agent(
'anthropic:claude-opus-5-5',
capabilities=[SubAgents(agents=[SubAgent(researcher)]), ReportDelegations()],
)
For the child run’s model streaming, pass an event_stream_handler. See capability events for how @on_event works.
Plain delegation adds no OpenTelemetry spans: the child run’s own spans nest under the parent’s tool-call span.
A child run has its own conversation_id, so adding up cost by gen_ai.conversation.id leaves it out of the conversation it was started for. Its spans also carry pydantic_ai.root_conversation_id, the conversation_id of the top-level run (the run that isn’t inside any other run), even for a child started by another child; see correlating runs for how to use it and where it’s missing.
Task control records its own decisions, which core’s spans don’t show, as zero-duration spans on the delegating run’s tracer. Their attributes have the sub_agents. prefix and include sub_agents.agent_name (for a created agent, whose name the model chose, only as content) and, for a task, sub_agents.task_id:
| Span | When | Attributes |
|---|---|---|
sub_agents vetoed | a listener vetoed a task, message, answer, cancellation, or created agent | sub_agents.event (the vetoed event’s kind), sub_agents.veto_reason |
sub_agents task backgrounded | a task moved to the background | sub_agents.reason: requested, auto, or question |
sub_agents question answered | a listener, not the model, answered a task’s question | sub_agents.question, sub_agents.answer |
sub_agents task refused | max_running_tasks refused a delegation | sub_agents.running_tasks, sub_agents.max_running_tasks |
sub_agents task not accepted | no worker picked a remote task up within accept_timeout | sub_agents.accept_timeout |
sub_agents remote task stopped | a remote task ended without its worker’s report, and its worker was told to stop it |
A veto reason, question, or answer, and the name a vetoed create_agent call asked for, are attached only when the run’s instrumentation includes content. While a top-level run waits for its background tasks, a sub_agents wait for tasks span with sub_agents.running_tasks covers the wait.
By default a delegation finishes inside the delegate_task call that started it. With task_control=TaskControl(), delegations become tasks the model manages: they can run in the background, ask questions, be steered or cancelled, and be resumed.
from pydantic_ai import Agent
from pydantic_ai_harness import SubAgent, SubAgents
from pydantic_ai_harness.sub_agents import TaskControl
researcher = Agent('anthropic:claude-opus-5-5', name='researcher', description='Researches a topic')
orchestrator = Agent(
'anthropic:claude-opus-5-5',
capabilities=[SubAgents(agents=[SubAgent(researcher)], task_control=TaskControl(auto_background_after=60))],
)
| Tool | Purpose |
|---|---|
delegate_task(agent_name, task, background=False, resume=None) | Start a task, or resume a finished one by its task ID. background=True returns a receipt right away. |
list_tasks() | The tasks this run started and the tasks they started, with status and IDs (the 50 most relevant). |
check_task(task_id) | What one of those tasks is doing now, without waiting for it: elapsed time, the model requests, last five tool calls and latest text of its current run, and any question it waits on. A finished task shows only its outcome. |
message_task(task_id, message) | Steer a running task; it reads the message, as sent, at its next model request. Its instructions tell it its delegating agent may send it messages. A finished task resumes with the message as its prompt, in the background if it ran there, through a delegate_task(resume=...) call that the delegate tool’s hooks and approvals see and that counts as a second tool call. |
answer_task(task_id, answer) | Answer the question a task is waiting on. |
cancel_task(task_id, force=False) | Stop a task, and the tasks it started, before its next model request, or right away with force=True. |
- Reports and questions arrive as messages. A background task’s report is
<task_output>data, and its question<task_question>data, on the user channel; the task-control instructions tell the model both are untrusted task data. A top-level run whose model ends while background tasks still run waits for them, so their reports become its next request. - Questions. Each sub-agent gets an
ask_parent(question)tool. A question moves its task to the background, since the delegating model can answer only oncedelegate_taskreturns, and reaches that model as a message. Turn it off per delegate withSubAgent(can_ask_questions=False). A task that can’t run in the background (a run-owned workspace that isn’t local) gets noask_parent. - Limits.
TaskControl(auto_background_after=...)moves a task still running after that many seconds to the background.TaskControl(max_running_tasks=...)caps how many tasks a conversation runs at once, across its whole delegation tree.SubAgent(resumable=False)makes a delegate one-shot (see Managed delegation sessions forone_shot). All are off by default. - Who controls a task. Only the run that started a task can message, answer, or resume it. Any run above it can cancel it.
- Each run gets an owner. With no
DelegationTasksbound,SubAgentsopens one for the run and cancels the tasks still running when the run ends. Delegations then follow the owner’s rules in Managed delegation sessions, including how a delegate’susage_limitsapply. Another agent’s run that one of the run’s tools starts is not a task and doesn’t share the owner. Bind your own owner to keep tasks across runs, persist them, and observe them. - Task IDs derive from the run’s
run_idand the tool call that started the task, so a rerun with the samerun_idand tool calls gets the same task IDs, and runs that share an owner or aSubAgentWorkerneed distinctrun_ids, asrun_idalready requires. - Only one
SubAgentson an agent can settask_control. The deprecated wrapper agents, such asTemporalAgent, give a run no durability capability, so the checks below can’t catch them; don’t use task control ordynamic_agentswith them. - On Temporal and DBOS, task control keeps the tasks in the workflow and runs each in its own durable unit, so recovery replays a background task’s events and reuses its result. On replay, a task sent to the background on request can get its
TaskBackgroundedEventafter it settles. A durable task can’t ask questions, take messages, or be resumed,cancel_taskstops it right away, and its report reaches the model when the run would otherwise end, not at its next request. On DBOS, a replayedlist_taskscan show a task’s status as of a different moment. A durable task’s history is not updated while it runs, socheck_taskshows only its status and elapsed time. Under durable execution, these raise aUserError:- task control with
include_self,remote_agentsorforward_events - task control with
auto_background_afterormax_running_tasksoutside Temporal - task control or
dynamic_agentson another durable engine, or within a boundDelegationTasksowner
- task control with
- On Temporal and DBOS,
dynamic_agentskeeps the roster in the workflow and runs each delegation other than toselfin its own durable unit, on the parent run’s model unless the created agent has one, so recovery rebuilds the created agents and reuses each delegation’s result. Thefactoryruns again on replay, so keep it deterministic. Engines that record each tool call in its own unit would lose the roster on replay, so they raise aUserError. Under any durability capability,SubAgentsneeds anid, which it has by default;id=Noneraises aUserError. - Task control and
DelegationTasksrun tasks as asyncio tasks, so AnyIO’s Trio backend is not supported.
With task control, every step of a task is a typed capability event in the sub_agents namespace. A task’s events go into the event stream of the run that started it, so a nested task’s events reach its own parent’s run. A bound DelegationTasks observer also receives them as DelegationTaskEvent(event=...), including those of a task that settles after its delegating run ended; in place of TaskProgressEvent, it receives the task run’s own events.
| Event | When | A listener can |
|---|---|---|
TaskAssignedEvent, TaskResumedEvent (TaskRequestEvent matches both) | a task is about to start, or to resume | rewrite prompt, or veto() it |
TaskStartedEvent | the task’s run is starting, locally or on a worker | |
TaskBackgroundedEvent | the task moved to the background; reason is requested, auto, or question | |
TaskProgressEvent | an event of the task’s own run, with TaskControl(forward_events=True) | |
TaskQuestionAskedEvent | the task asked a question | set answer, so the model is not asked |
TaskAnsweredEvent | an answer is about to reach the task | rewrite answer, or veto() it |
TaskSteeredEvent | a steering message is about to reach the task | rewrite message, or veto() it |
TaskCancelRequestedEvent, TaskForceCancelRequestedEvent | a cancellation is about to reach the task | veto() it |
TaskRetriedEvent | a worker is running a failed remote task again | |
TaskCompletedEvent, TaskFailedEvent, TaskCancelledEvent | the task settled | rewrite output of a completed task |
These events and AgentCreatedEvent are not cut at MAX_EVENT_TEXT_CHARS: each is the message a transport carries, so a prompt, question, answer, or output arrives whole. A listener that persists or forwards them bounds them itself.
Events a listener can change are dispatched immediately, so its decisions take effect. A vetoed message is not sent, and the model is told why. With a bound DelegationTasks, DelegationStartedEvent and DelegationFinishedEvent go to its observer only (see Managed delegation sessions); with the run’s own owner, they go to the run.
Earlier releases used different class and attribute names. The old names still import from the deprecated pydantic_ai_harness.subagents path (or read as properties) with a HarnessDeprecationWarning, and each event’s kind is unchanged:
| Old name | Current name |
|---|---|
SubAgentMessage, ParentMessage, ChildMessage | SubAgentMessageEvent, ParentMessageEvent, ChildMessageEvent |
TaskFollowUpEvent | TaskResumedEvent |
TaskMessageEvent | TaskSteeredEvent |
TaskAnswerEvent | TaskAnsweredEvent |
TaskCancelRequestEvent | TaskCancelRequestedEvent |
TaskForceCancelEvent | TaskForceCancelRequestedEvent |
TaskQuestionEvent | TaskQuestionAskedEvent |
TaskRetryEvent | TaskRetriedEvent |
AgentCreatedEvent.name | AgentCreatedEvent.agent_name |
DelegationStartedEvent.parent_id, DelegationFinishedEvent.parent_id | parent_task_id |
Constructors accept only the current keyword names, and events serialize under the current keys (old serialized keys still load). Update code that reads serialized events by key and upgrade readers before writing new events.
from pydantic_ai.capabilities import AbstractCapability, on_event
from pydantic_ai_harness.sub_agents import TaskAssignedEvent, TaskQuestionAskedEvent
class DelegationPolicy(AbstractCapability):
@on_event(TaskAssignedEvent)
async def check_task(self, ctx, event: TaskAssignedEvent) -> None:
if 'production' in event.prompt:
event.veto('ask the user before touching production')
@on_event(TaskQuestionAskedEvent)
async def answer_known(self, ctx, event: TaskQuestionAskedEvent) -> None:
if event.question == 'Which branch?':
event.answer = 'main'
A SubAgentWorker serves agents to delegating agents in other processes. The delegating side lists them as RemoteSubAgents, by name, and reaches them through a SubAgentTransport:
from pydantic_ai import Agent
from pydantic_ai_harness.sub_agents import RemoteSubAgent, SubAgents, SubAgentWorker, TaskControl
transport = ... # a SubAgentTransport both processes reach
# In the process that hosts the agent:
async def serve():
researcher = Agent('anthropic:claude-opus-5-5', name='researcher')
await SubAgentWorker(agents={'researcher': researcher}, transport=transport, deps=None).serve()
# In the delegating process:
orchestrator = Agent(
'anthropic:claude-opus-5-5',
capabilities=[
SubAgents(
task_control=TaskControl(
remote_agents=[RemoteSubAgent(name='researcher', description='Researches a topic')],
transport=transport,
)
)
],
)
- A transport is a set of mailboxes. Implement
send,receive, and optionallyreleaseover a WebSocket, a Redis list, or anything else that moves bytes, withserialize_messageanddeserialize_messageat the boundary. Every message is one of theSubAgentMessageEvents above.InMemoryTransportserves a worker in the same process. - The transport is the trust boundary. Anyone who can send to it can run the served agents, with their tools and
deps, and read what they return. Put authentication, authorization, and network binding in your transport. A worker’s output and errors reach the delegating model like a local delegate’s: as tool results in the foreground, as framed reports in the background. - A transport reports a lost worker. A worker that stops sends
TaskFailedEventfor its running tasks. If one dies without doing so, the delegating run waits for its report until the run is cancelled, unlessreceiveraises when the worker is gone. The protocol has no heartbeats. - The worker runs the agent with its own model, tools, and
deps, which never cross the transport. It takes the agents it serves by name, without per-delegate run controls, which belong to the delegating side’sSubAgents. It applies the delegating run’s usage limits to the task’s own usage and continues the delegating run’s trace. The usage it reports with the settled event is added to the delegating run’s usage, unlessforward_usage=False. - A task nobody picks up fails. The worker sends
TaskStartedEventwhen it starts a task. A remote task no worker picks up withinTaskControl.accept_timeoutseconds (default30) fails. A remote task that stops without its worker’s report, for example because its delegating run ended, is force-cancelled on the worker. SubAgentWorker(retries=...)runs a failed task again from its prompt, with aTaskRetriedEvent. The worker keeps up tomax_conversationstask conversations (default1000) for resuming. A conversation stays in its worker, so serve each remote agent name from one worker: a follow-up that reaches another worker fails.- A remote agent runs on its worker’s model, so
delegate_taskrefuses amodelfor it, and its delegations emit noDelegationStartedEventorDelegationFinishedEvent.
With dynamic_agents, the model gets a create_agent(name, description, instructions, model=None) tool and can delegate to the agents it creates until the run ends, with or without task control.
from pydantic_ai_harness.sub_agents import DynamicAgents, SubAgents
SubAgents(models={'fast': 'anthropic:claude-haiku-5-5'}, dynamic_agents=DynamicAgents(models=['fast'], max_agents=3))
- A created agent is an
Agentwith the model-written instructions and no tools, on themodelskey it was created with, or on the delegating run’s model whenDynamicAgents.modelsis empty. The model delegates to it by the name it gave increate_agent. The agent has nonameordescriptionof its own, since tracing records those even without content. The description goes only to a custom factory, asDynamicAgentSpec.description, and the model never sees it: created agents aren’t added to the cache-stable roster. PassDynamicAgents(factory=...)to build the agent yourself from theDynamicAgentSpec. - An
AgentCreatedEventis dispatched immediately before the agent is created: a listener can rewrite itsinstructions(and itsdescription, which only a custom factory reads), orveto()it. max_agents(default5) caps how many agents one run creates. Only oneSubAgentson an agent can setdynamic_agents.
Task control, remote agents, and created agents are a port of subagents-pydantic-ai, a community package by Vstorm (MIT licensed).
SubAgents delegates in the foreground only, unless a caller opens and binds a DelegationTasks owner. The owner adds background and resume to the delegate tool’s schema, gives every child a stable conversation ID, and owns every worker (an asyncio task) until shutdown. It adds no agent loop of its own.
Use DelegationReports on the parent run to deliver settled background reports through core’s queued-message API. Each report is a TaskOutputPart holding the child’s output as <task_output task_id="..." agent_name="..."> data on the user channel, with outcome="..." added when the task didn’t succeed, like a background tool’s <tool_result>. A model wrote the output, so it never enters system voice: a note in the application’s voice says the sub-agent wrote it, not the user or the application. The output goes out as the child wrote it; text in it that looks like the frame’s own tag or an application frame such as <system> gets a further note naming the sub-agent as its author, so it can’t end the frame early or speak as the application. Nothing else precedes the frame: the receipt the parent got at launch already said a report would follow.
Reports default to priority='when_idle', so active parents finish their current work first. A host that starts an idle continuation should use DelegationReports(..., priority='asap') and agent.run(None, ...): pending reports then enter the first model request, with no synthetic user prompt. The host schedules wake-ups between runs. A report or question that arrives after a run has read its last queued messages is kept for the conversation’s next run.
A task’s question arrives the same way, as a TaskQuestionPart framed as <task_question task_id="..." agent_name="...">. Find reports and questions in history by these types, or with is_task_report(part), which also recognizes the user text earlier versions delivered them as, for example to keep them out of a transcript of what the user typed. The Vercel AI and AG-UI message conversions leave capability parts out, so reports and questions stay in server-side history.
from pathlib import Path
from pydantic_ai import Agent
from pydantic_ai_harness.sub_agents import DelegationReports, DelegationTasks, SubAgents
agent = Agent('anthropic:claude-sonnet-5-5', capabilities=[SubAgents(include_self=True)])
tasks = DelegationTasks(directory=Path('.task-history'))
async def converse():
async with tasks.opened():
with tasks.bind():
result = await agent.run(
'Delegate an independent investigation in the background.',
conversation_id='review',
capabilities=[DelegationReports(tasks, conversation_id='review')],
)
print(result.output)
# Keep this owner open across subsequent parent turns.
opened()cancels and drains workers on exit. If a child hasn’t released its resources within ten seconds,opened()raisesRuntimeError, or only logs it when an error is already closing the owner, so that error isn’t masked. Keep workspace and plugin resources alive outside that scope.- A task still running when its process exited loads as cancelled when the owner next opens; if it was waiting for an answer, its output names the question, so the parent can resume it with the answer.
- A running task records the process running it. An owner opening the same
directoryin another process while that process still runs leaves the task out ofrecordsand never saves over it; once that process is gone, the next owner to open loads it as cancelled. As with saved sessions, this is a check on the local machine, not a lock: don’t sharedirectorybetween hosts. - Detached execution is refused for run-owned non-local workspaces; foreground delegation still works.
- The owner’s
max_depth=4counts the main run and allows three child layers. An explicitly set non-defaultSubAgents.max_depthtakes precedence; plainSubAgentskeeps its own default. restore(task)adds a finishedDelegationTaskmade elsewhere, such as one imported from another agent’s session, so the parent can resume it by ID. It works beforeopened()too; the owner loads the task when it opens. A task with the same ID that has run since, under a differentrun_id, is kept rather than replaced, andrestorereturnsFalse.
background(task_id)releases a foreground waiter without restarting the child.await cancel(task_id)stops and drains that child and its descendants.- A user stop blocks model-requested resume until the application calls
await allow_resume(task_id). one_shotnames never resume.SubAgent(resumable=False)does the same for one delegate, also with the ownerSubAgents(task_control=...)opens: useone_shotwhen the application binds the owner and decides by agent name, andresumablewhere the delegate is declared. Either makes the task one-shot.- A resume uses the same child ID and its own history, a new run ID, and the current direct parent.
- A child waits for its own descendants and consumes their reports before its final output settles. Reports go to the direct parent; an idle parent receives pending reports on its next explicitly started run. Delivery is acknowledged only when core emits
EnqueuedMessagesEvent, and acknowledgements are persisted. - With task control, a child’s
ask_parentquestion is routed the same way:questions(conversation_id=...)lists the children whose question awaits delivery, and the observer is notified when one starts waiting, so an application can start its idle parent’s next run to answer it. steer(task_id, text)sends a running child a user message on its own run’s queue withpriority='asap': the child reads it at its next model request, and one about to finish goes on with it instead. It returnsFalsewhen the child is not running, so an application can offer to resume it. A message sent before the child’s run starts waits for it; one sent as the child’s final response settles may arrive too late.
- An observer receives
DelegationTaskEvent, with the task identity and an optional correlated child stream event. Events from the child’s own stream also carry themodel_nameandcontext_windowof the model streaming that request, so a UI can show the child’s context usage. Managed start and end events carrytask_idandparent_task_id. Managed cancellation and uncontained exceptions produce terminal outcomes; unmanaged events and exception propagation are unchanged. - Metadata and final or interrupted histories are saved atomically under
directory. Once a task settles and is saved, the owner keeps its history only in that file, so long-finished tasks don’t fill memory: an observer is told a task settled with its history, and after that the task inrecordshas emptymessages.history(task_id)reads the history from the file (from async code, call it in a worker thread:anyio.to_thread.run_sync(owner.history, task_id)), and a resume loads it back. To copy a settled task with its history, usereplace(task, messages=owner.history(task.id)). snapshot(task_id)returns aDelegationSnapshotof a running task from its live history, without waiting on it: status,elapsed_seconds, theusageof its current run’s model responses, itsrecent_tool_callsasDelegationToolCalls, and itslatest_textandpending_question, both cut atMAX_EVENT_TEXT_CHARS. It leaves out the child’s final result, so a snapshot doesn’t show a result beforeTaskCompletedEventlisteners process it. A host can render a task list or status line from it, for example on eachDelegationTaskEvent.usageisNone, with no tool calls or text, when the owner doesn’t see the run’s history as it streams: before the child’s first model request, for a remote task (its history stays on its worker) or a durable one, and once the task settles (its history is in its file).check_taskgives the model the same view.- Pass
step_storeto checkpoint throughStepPersistenceand recover a process-killed child’s latest frontier. Loading an interrupted record never executes its tools; inspect possible partial effects before an explicit resume. A resume answers tool calls the interruption left unanswered with aninterruptedtool return, so the child sees they did not complete. - Each saved file loads on its own. A file that can’t be read or validated, whose name doesn’t match its task ID, or whose saved ancestry loops is skipped and left on disk:
opened()logs a warning and lists it inproblemsas aSavedTaskProblem(its path and the reason), and the other tasks still load.
To list a saved task tree without opening an owner or resuming anything, for example from a dashboard or another process, call DelegationTasks.discover(directory). It returns SavedTasks, with the loaded tasks by ID (follow parent_id for the tree) and the same problems. discover() writes nothing and returns a task saved as running unchanged, since the process that owns it may still be running it.
from pathlib import Path
from pydantic_ai_harness.sub_agents import DelegationTasks
async def show_saved_tasks():
saved = await DelegationTasks.discover(Path('.task-history'))
for task in saved.tasks.values():
print(task.id, task.parent_id, task.agent_name, task.status, task.outcome)
for problem in saved.problems:
print(f'Skipped {problem.path}: {problem.reason}')
- Managed children with
forward_usage=Trueshare live usage accounting and inherit parent ceilings. A per-child budget becomes an absolute ceiling at launch: concurrent sibling spend may reach it earlier, but cannot bypass the parent’s budget. Unmanaged per-child accounting is unchanged. - A locally run child that inherits
count_tokens_before_request=Trueand raisesNotImplementedErrorbefore its first request is started once more without the up-front count, so ceilings are checked against response usage instead. It isn’t restarted once a request has been counted into itsusage(including a sibling’s underforward_usage=True), so no tool runs twice; a resumed child fromforward_deferred_callsdrops inherited counting up front for the same reason. A child whose ownusage_limitssetscount_tokens_before_request=True, a remote task, or a durable delegation toselfwhose count runs through the engine (on every engine whenselfis the only delegate, on DBOS and Prefect always, and on Temporal also whendynamic_agentsortask_controlis set) on a provider that serves no token counting (such asopenai-codex:oropenai-chatgpt:) fails instead, as a top-level run would. agents,aliases, andinstructionsextend the roster and guidance only inside the bound scope; they do not add delegation to an agent withoutSubAgents.- For a
SubAgent(read_only=True)delegate, give the agent only trusted read-only capabilities, since arbitrary Python tools can bypass the workspace API. Pax’s Explore and Plan specialists use filesystem readers and expose no shell, code execution, or parent plugin tools. - Core’s agent, model, and tool spans provide execution telemetry; task IDs, parent IDs, and child run IDs provide correlation. The owner adds no logging exporter.
When self is the only delegate, delegate_task runs outside a durable unit on every engine, so the delegated run’s model requests and tool calls are recorded as the parent’s own durable units, and recovery reuses them. With other delegates, delegate_task runs in a durable unit on engines that wrap function tools, and a delegation to self from it works on DBOS, Prefect and Render Workflows, and on Temporal with a models option. On AWS Lambda and Azure Durable Task it raises an error, and on Absurd and pgtask a retry replays the wrong results, so list self alone there (#13204).
By default, on Temporal a delegation to an agent other than self runs in an activity, and on DBOS it runs inline in the parent workflow, so a delegate’s own durability does nothing. To keep it, run the delegate tool as a child workflow (Temporal, DBOS) with SetToolMetadata:
from pydantic_ai import Agent
from pydantic_ai.capabilities import SetToolMetadata
from pydantic_ai.durable_exec.temporal import TemporalDurability
from pydantic_ai_harness.sub_agents import SubAgent, SubAgents
worker = Agent('anthropic:claude-opus-5-5', name='worker', capabilities=[TemporalDurability()])
lead = Agent(
'anthropic:claude-opus-5-5',
name='lead',
capabilities=[
SubAgents(agents=[SubAgent(worker)]),
SetToolMetadata(tools=['delegate_task'], temporal={'child_workflow': {}}),
TemporalDurability(),
],
)
On DBOS, use DBOSDurability() and SetToolMetadata(tools=['delegate_task'], dbos={'child_workflow': {}}). The delegate’s model requests and tool calls are then recorded in the child’s history, not the parent’s.
- Every delegate must be durable on the parent’s engine: the tool body runs as workflow code.
- On Temporal, register each delegate with the worker too, for example with an
AgentPlugin. include_self,inherit_tools,models,shared_capabilities,event_stream_handler,dynamic_agents,task_control, and a delegate’smax_callsrely on parent-run state the child workflow doesn’t receive, so a delegation with any of them raises aUserError.- The delegate’s usage isn’t reliably counted in the parent run’s usage, and the parent’s usage limits don’t bound it.
- The delegation depth isn’t carried into the child workflow, so if a delegate’s own
SubAgentsalso opts in,max_depthcounts again from each child workflow and no longer bounds the tree.
With agent_folders set, every Claude-style *.md and Codex-style *.toml file in those folders is loaded as a sub-agent, alongside the explicit agents. Files are read in sorted filename order.
from pydantic_ai import Agent
from pydantic_ai_harness import SubAgents
orchestrator = Agent(
'anthropic:claude-opus-5-5',
capabilities=[SubAgents(agent_folders='agents')], # loads .agents/agents/ from the run's workspace
)
Definitions are read at the start of every run from the run’s workspace, so a sandbox’s agent files are found and nothing is read from your home directory. To read them from elsewhere, such as definitions that ship with your application, pass workspace=LocalWorkspaceBackend('/app').
A definition file below 'operator' authority in the workspace it’s read from, such as one in a repository the operator doesn’t control, is not loaded, and the run warns naming it: a definition’s body becomes a delegate’s instructions, and its description is listed in the parent’s. It’s left out before names are compared, so it can’t shadow an operator’s definition of the same name. Read the folders from a workspace the operator controls with workspace= instead.
agent_folders controls which folders are read:
- A folder-name
str('agents'is the conventional layout) loads from.agents/<name>/,.claude/<name>/, and.codex/<name>/under the workspace’s working directory, in that order, so a workspace that uses.agents/for something else (such as skills) still loads agents from the others. A run without a workspace skips them. - A sequence of workspace paths, absolute or relative to the working directory, loads from exactly those folders, in order. A run without a workspace fails at its start.
None, the default, disables disk loading.
Convention discovery warns once when it skips a .agents/ or .claude/ folder in the current or home directory that the workspace does not reach, naming the folder and the workspace= that reads it.
A definition is a Claude-style markdown file with optional frontmatter, or a Codex-style TOML file. Markdown:
---
name: researcher
description: Researches a topic and reports findings
tools: Read, Grep
---
You research topics. Report your findings, each with a source.
nameis the delegate name. It falls back to the filename stem.descriptiondrives the prompt listing.- The markdown body becomes the agent’s instructions.
tools(orallowed-tools) is a comma-separated string or a YAML block list. See Tools.modelandcolorare ignored: the model is inherited from the parent (see below), andcolorhas no Pydantic AI equivalent.
A small, dependency-free parser reads only those keys (pyyaml is not a harness dependency); full YAML frontmatter is not supported.
A Codex-style standalone TOML file:
name = "reviewer"
description = "Reviews code for bugs"
developer_instructions = "Inspect the code and report findings. Do not edit files."
tools = ["Read", "Grep"]
name,description, anddeveloper_instructionsare required nonempty strings.tools(orallowed-tools) is optional: a list of strings or a comma-separated string, not both keys.model,effort,model_reasoning_effort, andcolorare ignored with a warning; useagent_overridesfor models and effort.- Any other key, including sandbox or permission settings, skips that file with a warning instead of granting broader tools. The older
[agents.<name>] config_filelayout is not supported. - TOML files are parsed with the standard-library
tomllib.
Nothing in a definition file is executed. A malformed or invalid file is skipped with a warning without blocking the others.
Disk agents inherit the parent run’s model by default. agent_overrides, keyed by agent name, sets a model and a thinking/effort level per agent:
from pydantic_ai_harness import SubAgents
from pydantic_ai_harness.sub_agents import AgentOverride
SubAgents(
agent_folders='agents',
agent_overrides={'researcher': AgentOverride(model='anthropic:claude-opus-5-5', effort='high')},
)
With effort unset, the disk agent adds no thinking setting, so the inherited model’s defaults apply. An explicit value, including False or 'minimal', is passed unchanged through Pydantic AI’s ModelSettings.thinking.
MINIMUM_EFFORT_FLOOR and clamp_effort(level, floor=...) still import from the deprecated pydantic_ai_harness.subagents path, with a HarnessDeprecationWarning, but SubAgents no longer uses them. Pass AgentOverride(effort=...) for an explicit level, or apply an application-specific floor outside the capability.
Without a tool_resolver, a disk agent gets no tools and its tools frontmatter is ignored. A tool_resolver receives each tool name (so it can honor entries like Bash(git:*)) and returns the toolsets that provide it, or None for an unknown name, which is skipped with a warning.
from collections.abc import Sequence
from pydantic_ai.toolsets import AgentToolset
from pydantic_ai_harness import SubAgents
TOOLSETS: dict[str, Sequence[AgentToolset[object]]] = {} # your tool name -> toolsets mapping
def resolve(tool_name: str) -> Sequence[AgentToolset[object]] | None:
return TOOLSETS.get(tool_name)
SubAgents(agent_folders='agents', tool_resolver=resolve)
When a name appears in more than one source, the higher-precedence one wins and the others are skipped with a warning: explicit agents first; then, for convention discovery, the workspace’s .agents/, .claude/, and .codex/ folders in that order, or, for a path sequence, earlier folders first. A duplicate name within the explicit agents is an error.
SubAgentsis not serializable through the agent spec, since it holds liveAgentinstances, soget_serialization_name()returnsNone.- Sub-agents can have their own
SubAgents, forming a tree. EachSubAgentsstops offering delegation at its ownmax_depth, so a delegate with a higher limit can go deeper than its parent’s. Shareusage(the default) and setusage_limitson the top-level run to bound the whole tree. - Delegations the model issues in parallel run as independent sub-agent runs.
Bases: AbstractCapability[AgentDepsT]
Let an agent delegate self-contained tasks to named sub-agents.
Exposes a single delegate_task(agent_name, task) tool. Each delegation runs the chosen
sub-agent in a fresh run that does not see the parent conversation. The available sub-agents
are listed in the system prompt; a change to the listing between runs of a conversation is
appended rather than rewritten.
Delegates come from agents, from Markdown or TOML definitions under agent_folders, and,
with include_self=True, from the running agent itself. With a models menu, delegate_task
also takes a model argument naming one of its keys. The parent’s deps are forwarded to
each sub-agent, and delegations nest at most max_depth levels.
from pydantic_ai import Agent
from pydantic_ai_harness.sub_agents import SubAgent, SubAgents
researcher = Agent('anthropic:claude-sonnet-4-6', name='researcher', description='Researches topics')
writer = Agent('anthropic:claude-sonnet-4-6', name='writer', description='Writes prose')
orchestrator = Agent(
'anthropic:claude-opus-4-7',
capabilities=[SubAgents(agents=[SubAgent(researcher), SubAgent(writer)])],
)
The sub-agents to expose, each a SubAgent pairing an agent with its
per-delegate run controls. See SubAgent. These take precedence over any
disk-loaded agents of the same name.
Type: Sequence[SubAgent[AgentDepsT]] Default: ()
A menu of models the parent can route an individual delegation to, keyed by
the name the parent uses to pick one. Off by default: with no menu the delegate
tool has no model argument and every delegation runs the way it always did.
Each value is a model reference, or a ModelOption carrying a routing hint and
its own ModelSettings (so one key can mean “same model, more thinking”). The
keys and their descriptions are listed in the system prompt, so name them for
the job — 'fast', 'deep' — rather than for the vendor. SubAgent.models
restricts which of them a given delegate accepts.
from pydantic_ai_harness.sub_agents import SubAgents
SubAgents(models={'fast': 'anthropic:claude-haiku-4-5', 'deep': 'anthropic:claude-opus-4-7'})
Type: Mapping[str, Model | KnownModelName | str | ModelOption] Default: field(default_factory=(dict[str, 'Model | KnownModelName | str | ModelOption']))
Where to load Markdown and standalone Codex TOML definitions from, in addition to agents.
Off by default: only agents are exposed unless this is set. Every folder is
read at the start of each run through the run’s workspace (ctx.workspace),
or through workspace when set. A definition file below 'operator'
authority in that workspace is skipped with a warning.
- a folder-name
str('agents'is the conventional layout): load from.agents/<name>/,.claude/<name>/, and.codex/<name>/under the workspace’s working directory, in that order. Skipped when the run has no workspace. - a sequence of paths in the workspace, absolute or relative to its working
directory: load from exactly those folders, in order. A run with no workspace
fails at its start; pass
workspace=LocalWorkspaceBackend('.')to read them from this machine. None: no disk loading (the default).
Missing folders are skipped. Within a folder every *.md and *.toml file is a candidate.
Type: str | Sequence[str | Path] | None Default: None
Per-disk-agent overrides keyed by the agent’s name. An entry can set the
agent’s model (otherwise the parent’s model is inherited) and its effort
(otherwise no thinking setting is added). Has no effect on explicitly-passed agents.
Type: Mapping[str, AgentOverride] Default: field(default_factory=(dict[str, AgentOverride]))
Optional override for how a disk agent gets its tools. When set, each tool
name in a definition’s tools/allowed-tools frontmatter is passed to this
resolver and the returned toolsets are attached to that agent; an unknown name
(resolver returns None) is skipped with a warning. When unset, the
frontmatter tool list is ignored and disk agents have no tools of their own.
Type: ToolResolver | None Default: None
If True, the parent run’s usage is shared with each sub-agent run, so
token usage aggregates and usage limits apply across the whole agent tree.
Type: bool Default: True
Deprecated: setting it to True emits a HarnessDeprecationWarning.
If True, the parent agent’s own tools (registered via tools= or toolsets=,
not those contributed by capabilities) are exposed to each sub-agent run, minus
the delegate tool. Bind required tools directly to explicit sub-agents, use
include_self=True to delegate to an agent with all of the parent’s tools and
capabilities, or use tool_resolver to give disk agents tools.
Type: bool Default: False
Capabilities applied to every sub-agent run, in addition to whatever each sub-agent already has.
Type: Sequence[AgentCapability[AgentDepsT]] Default: ()
If set, this handler is passed to each sub-agent run, so the sub-agent’s
model-streaming and tool events surface to the caller. The handler receives
the sub-agent’s own RunContext and event stream.
Type: EventStreamHandler[AgentDepsT] | None Default: None
Name of the delegate tool exposed to the model.
Type: str Default: 'delegate_task'
Fixed, since an agent exposes a single delegate tool. Durable execution requires one.
Two SubAgents capabilities would register the same tool_name and collide. The shared id
makes them merge instead, unioning their rosters, so a packaged harness that delegates can
compose with another that does the same.
Type: str | None Default: field(default='sub_agents', kw_only=True)
Retries for the delegate tool — how many extra attempts it gets after a
sub-agent error before the parent run aborts. A sub-agent failure (e.g. it
exhausts its own output retries) surfaces to the parent as a tool retry it
can react to by re-delegating with a corrected task. The retry counter
resets after any successful delegation, so this bounds consecutive failures,
not total ones. Defaults to 2 (pydantic-ai’s per-tool default is 1) so a
repeated flaky sub-agent does not abort the parent run on its first repeat;
set None to inherit the parent agent’s default tool retries instead.
Default for SubAgent.contain_errors: whether an unexpected sub-agent crash
is caught and returned to the parent as a bounded ModelRetry instead of
aborting the parent run. Off by default, so a crash propagates. Any SubAgent
can override this per delegate. See SubAgent.contain_errors for the
containment contract and what always propagates regardless.
Type: bool Default: False
A workspace to read agent_folders from instead of the run’s, such as
LocalWorkspaceBackend('/app') for definitions that ship with the application.
A backend, not the LocalWorkspace capability. It is used in-process only: a durable engine
does not route it through its workflow machinery.
Type: WorkspaceBackend | None Default: field(default=None, kw_only=True)
Opt into delegate_task(working_directory=...) with an async callback receiving the parent
context and a DelegationWorkspaceRequest with the delegate name and requested directory.
Return the child’s Workspace; the caller owns
its resources, including keeping it alive for background tasks. Omission keeps the parent workspace.
The callback validates paths and decides which delegates and backends may change directory.
Parent and delegate read-only restrictions still apply, and the child’s workspace gets the lowest
authority the parent gives anything in or above its directory: 'none' for a directory outside the parent’s
working directory, unless one of the parent’s path_authority entries contains it. Tools that bypass the
workspace API need their own restrictions. Remote and durable delegations cannot request another directory.
Resuming a task keeps its saved directory; the resolver is called again for that directory.
This does not change where agent_folders are discovered (see workspace).
Type: WorkspaceResolver[AgentDepsT] | None Default: field(default=None, kw_only=True)
Pass a sub-agent’s deferred tool calls to the caller of the parent run, and resume the sub-agent once they
are answered. Off by default: a sub-agent run that ends with DeferredToolRequests returns a steering message.
When on, such a run makes the delegate call raise ApprovalRequired, so the parent run ends with
DeferredToolRequests too (its output_type must include it, or a HandleDeferredToolCalls handler must answer
it through these two functions).
delegated_requests() lists the sub-agent’s calls under IDs prefixed by the delegate call’s, and
delegated_results() routes the answers back, so the next run resumes the sub-agent from its history rather than
running the task again. Approving the delegate call itself, such as through an approval gate on the delegate
tool, approves none of the sub-agent’s calls: the delegation runs the task, and passes on the calls it stops on.
Not supported under durable execution or with task_control, which raise an error.
Type: bool Default: field(default=False, kw_only=True)
Where a sub-agent’s history waits while the caller answers the calls forward_deferred_calls passed on.
It stays on the server, and the caller only gets its ID. Unset, each SubAgents keeps it in memory, so the run
that resumes must use the same instance, in the same process. Pass the same DeferredStateStore to every
process that may resume a run another one started.
Type: DeferredStateStore | None Default: field(default=None, kw_only=True)
If True, the roster also lists the running agent itself, as self.
A delegation to self starts a fresh run of RunContext.agent on the parent run’s model
(or the models option the parent picks), so the delegate has every capability, toolset, and instruction bound to that Agent —
guardrails, approval gates, and audit hooks included, since they are registered again in
the child run. What was passed to the parent’s run() rather than bound to the Agent
(run-level capabilities, toolsets, instructions, model_settings) does not carry
over, so this capability has to be bound to the Agent itself; passing it to run()
raises a UserError when the run starts.
inherit_tools does not apply to self, whose tools are already the parent’s. The
delegate can delegate in turn, up to max_depth.
Type: bool Default: False
How many levels a delegation tree may have, counting the top-level run as the first.
The default of 3 lets the top-level run delegate, and its delegates delegate once more.
A run at the limit gets neither the delegate tool nor the sub-agent listing. The level
is tracked per task tree, across every SubAgents capability, and each capability enforces
its own limit. This bounds include_self, whose delegate carries the delegate tool again,
and a roster that reaches the same agent through another path.
Type: int Default: DEFAULT_MAX_DEPTH
Let delegations outlive the tool call, and give the model tools to manage them. Off by default.
See TaskControl. Only one SubAgents on an agent can set it. On Temporal and DBOS, each task runs in a durable
unit of its own, which can’t ask questions, take messages, or be resumed. Under durable execution, include_self,
remote_agents, forward_events, auto_background_after or max_running_tasks outside Temporal, other durable
engines, and a bound DelegationTasks owner raise a UserError.
Type: TaskControl | None Default: field(default=None, kw_only=True)
Let the model create sub-agents during a run, with a create_agent tool. Off by default.
Only one SubAgents on an agent can set it. On Temporal and DBOS, every delegation other than to self runs in a
durable unit of its own, so recovery rebuilds the created agents and reuses the delegations’ results. Other durable
engines, and a bound DelegationTasks owner under any of them, raise a UserError.
Type: DynamicAgents[AgentDepsT] | None Default: field(default=None, kw_only=True)
@async
def for_run(ctx: RunContext[AgentDepsT]) -> SubAgents[AgentDepsT]
A per-run copy when agent folders are read; otherwise self.
A run at max_depth gets a copy without the delegate tool and listing instead. The per-run
copy starts from the explicit roster; before_run adds the folders’ definitions. Its
instructions and toolset are read after that, so they list the delegates this run has.
SubAgents[AgentDepsT]
@async
def before_run(ctx: RunContext[AgentDepsT]) -> None
Read the agent folders’ definitions through the workspace and rebuild this run’s roster.
@async
def wrap_run(
ctx: RunContext[AgentDepsT],
*,
handler: WrapRunHandler,
) -> AgentRunResult[Any]
Run the parent agent, then drop this run’s delegation counts so they don’t accumulate.
With task_control set, the run gets a DelegationTasks owner unless the application bound one, and
the task events of its children are published into its event stream.
@async
def after_output_process(
ctx: RunContext[AgentDepsT],
*,
output_context: OutputContext,
output: Any,
) -> Any
Keep a top-level run with its own owner going while its background tasks work.
The run waits until they settle, or one asks a question, and their reports become its next request.
def get_instructions() -> AgentInstructions[AgentDepsT] | None
Cache-stable listing of the available sub-agents and models.
A per-run copy returns it as a function, rendered after before_run has read the
workspace’s definitions; it is the same text on every step of the run.
AgentInstructions[AgentDepsT] | None
def get_toolset() -> AgentToolset[AgentDepsT] | None
Toolset providing the delegate tool, or None when no sub-agents are configured.
A per-run copy returns a function yielding the toolset before_run settled on, the same
instance for every step of the run.
AgentToolset[AgentDepsT] | None
@classmethod
def get_serialization_name(cls) -> str | None
Not spec-serializable — the capability holds live Agent instances.
@classmethod
def combine(
cls,
capabilities: Sequence[AbstractCapability[AgentDepsT]],
) -> AbstractCapability[AgentDepsT]
Compose the rosters, and require everything else to already agree.
Two packaged harnesses on one agent each bring their delegates, and composing them is what
the shared id is for. Only agents, models, and include_self are composed. Every other
field decides how the delegates run — what capabilities they are handed, whether they see the parent’s
tools, what the delegate tool is called, where delegates are loaded from — so merging it
would apply one harness’s policy to the other’s sub-agents, which neither author asked for.
Those must agree, and say so when they do not.
Disk definitions are not part of the merge: the per-run copy reads them in before_run,
after run-level capabilities are combined.
AbstractCapability[AgentDepsT]
Bases: Generic[AgentDepsT]
One delegate: a child agent plus its per-delegate run controls.
Pass a sequence of these as SubAgents(agents=[...]). The delegate’s name —
how the parent model refers to it, and how it is listed in the system prompt —
is name when set, otherwise the agent’s own name. An agent with neither is
rejected by SubAgents.
Every control below is optional; an unset field leaves the corresponding
behaviour at the SubAgents default.
The agent that runs when this delegate is invoked.
Type: AbstractAgent[AgentDepsT, Any]
Name the parent model uses to delegate to this agent. Defaults to the
agent’s own name when unset.
Type: str | None Default: None
Description for the system-prompt listing. Defaults to the agent’s own
description when unset; a delegate with neither is listed by name alone.
Type: str | None Default: None
Which of SubAgents.models this delegate may run on, as menu keys, and
which one it runs on by default: the first key listed. Leave it unset to let
the parent pick any configured option and to fall back to the delegate’s own
model when it picks none. Set it to pin a delegate to one option
(models=['fast']) or to bound an expensive delegate to a subset. Naming a key
the menu does not define is an error.
Type: Sequence[str] | None Default: None
Request/token budget for one delegation. When set, the child runs with
its own usage accounting so the budget counts only the child’s own requests
and tokens (not the parent’s or siblings’). When forward_usage=True, that
usage is added to the parent’s usage after the delegation. Hitting this budget
is a soft outcome (steering message), not a run-stopping UsageLimitExceeded.
Type: UsageLimits | None Default: None
Wall-clock budget for one delegation. When the child exceeds it, the run is cancelled and the parent gets a soft steering message instead of hanging on the child.
Type: float | None Default: None
Maximum number of delegations to this sub-agent per parent run. Once reached, further delegations return a soft budget-exhausted message without running the child.
Type: int | None Default: None
Steering message returned to the parent for any soft degradation of this
delegate (timeout, child failure, a child run ending with DeferredToolRequests or PendingModelResponse,
usage budget reached, call budget exhausted), in place of the built-in default. While on_model_error is unset,
setting it also makes child failures soft: a child error returns this message as a normal tool result
instead of raising a parent ModelRetry.
Type: str | None Default: None
Whether an unexpected sub-agent crash is contained instead of aborting the
parent run. When True, an exception the child raises that is not an expected
soft degradation (a provider ModelAPIError/FallbackExceptionGroup, a plain
ValueError from a bad tool argument, etc.) is caught and returned to the parent
as a bounded ModelRetry, so one delegate crash cannot kill the whole run. It
stays loud: the exception rides the retry message and is logged, and
tool_retries still bounds consecutive crashes into an abort. Cancellation, a
shared usage-limit, pydantic-ai control-flow signals, and UserError always
propagate regardless. Unset inherits SubAgents.contain_errors (default off).
Orthogonal to on_failure, which only sets the message for expected soft
degradations; a contained crash always raises the loud ModelRetry.
Type: bool | None Default: None
What the parent gets when the child fails with ModelRetry or UnexpectedModelBehavior.
'retry' raises a parent ModelRetry naming the error, bounded by SubAgents.tool_retries. 'return' returns
the error followed by the on_failure message, or a default steering message, as a normal tool result. Either
way on_failure only sets message text. Unset keeps the earlier coupling: 'return' with the on_failure
message alone when on_failure is set, 'retry' otherwise.
Type: Literal[‘retry’, ‘return’] | None Default: dataclass_field(default=None, kw_only=True)
Run in a ReadOnlyWorkspace; supply only trusted read-only tools as well.
Type: bool Default: dataclass_field(default=False, kw_only=True)
Whether a finished task can be resumed, within a DelegationTasks owner or with SubAgents.task_control set.
Set this to False for a one-shot agent. DelegationTasks(one_shot=...) does the same by name, for an owner
the application binds.
Type: bool Default: dataclass_field(default=True, kw_only=True)
Whether the sub-agent gets an ask_parent tool to ask the delegating agent a question, with
SubAgents.task_control set. Not offered when the task can’t run in the background.
Type: bool Default: dataclass_field(default=True, kw_only=True)
Whether a child stopped by timeout_seconds or its own usage_limits passes on its last text response.
The parent gets it after the steering message, in a <partial_output> frame. It has not passed the child’s
output validation and can be text the child rejected, so leave this off for a child whose guardrails keep content
from its parent.
Type: bool Default: dataclass_field(default=False, kw_only=True)
The delegate’s name: name if set, else the agent’s own name.
One entry on the model menu, as a model plus how it should run.
Pass bare model references when the menu keys speak for themselves, and a
ModelOption when an entry needs a routing hint or its own settings:
from pydantic_ai.settings import ModelSettings
from pydantic_ai_harness.sub_agents import ModelOption, SubAgents
SubAgents(
models={
'fast': 'anthropic:claude-haiku-4-5',
'deep': ModelOption(
'anthropic:claude-opus-4-7',
description='hard reasoning, multi-file changes',
settings=ModelSettings(thinking='xhigh'),
),
},
)
The model a delegation routed to this option runs on.
Type: Model | KnownModelName | str
What this option is for, listed in the prompt next to the key so the parent can route on task difficulty rather than on model names alone.
Type: str | None Default: None
Settings for a delegation routed to this option — thinking effort,
temperature, and so on. They merge over the sub-agent’s own model_settings,
which keeps whatever the sub-agent set and is not overridden here.
Type: ModelSettings | None Default: None
Per-agent override for a disk-loaded sub-agent, keyed by the agent’s name.
Both fields are optional. An unset model inherits the parent run’s model; an
unset effort leaves the inherited model’s thinking setting unchanged.
Model to run this disk agent with, in place of inheriting the parent’s.
Type: Model | KnownModelName | str | None Default: None
Thinking/reasoning level for this disk agent, passed through unchanged.
Type: ThinkingLevel | None Default: None
Bases: CapabilityEvent
A sub-agent run is about to start for one delegation.
Emitted once the delegation has passed every check that could refuse it (an
unknown sub-agent, a model key off the menu, an exhausted max_calls
budget), immediately before the child run starts.
The menu key the delegation runs on, or None when no option was selected: there is
no menu, or the delegate allows the whole menu and the parent named no key.
The task whose run started this one, or None when the top-level run did.
Type: _ParentTaskId Default: None
Whether the parent’s own tools were passed to the child run (SubAgents.inherit_tools).
Type: bool
Bases: CapabilityEvent
A delegation settled into what the parent receives.
output is what the delegate tool hands back to the parent: the child’s
output on ok, otherwise the steering message it returns or the
ModelRetry it raises. An exception that propagates out of the delegate
tool (a shared usage limit, an uncontained crash, a cancellation) ends
without this event for ordinary SubAgents users. An opt-in DelegationTasks
owner emits terminal cancelled or error outcomes with stable task identity.
The child’s own usage when it has separate accounting (SubAgent.usage_limits
set, or forward_usage off); None when it accrues into the parent’s usage.
The task whose run started this one, or None when the top-level run did.
Type: _ParentTaskId Default: None
Wall-clock milliseconds from just after the start event was emitted until the delegation settled.
Type: float
Deprecated: duration_ms in seconds.
Type: float
Lets delegations outlive the tool call, and gives the model tools to manage them.
Every run gets a DelegationTasks owner unless the application bound one, so delegate_task takes
background and resume, and the model gets list_tasks, message_task, answer_task and
cancel_task. A sub-agent gets an ask_parent tool (SubAgent.can_ask_questions). Each step of a
task is a SubAgentMessageEvent that listeners can rewrite or veto, and the reports of background
tasks arrive as messages: a top-level run that would end while its own background tasks work waits
for them.
Sub-agents a SubAgentWorker in another process serves, reached through transport.
Type: Sequence[RemoteSubAgent] Default: ()
How messages reach the SubAgentWorker serving remote_agents. Required with remote_agents.
Type: SubAgentTransport | None Default: None
How many seconds a remote task waits for a worker to pick it up before it fails, or None to wait
indefinitely.
Type: float | None Default: 30.0
How many seconds delegate_task waits for a task before it returns a receipt and lets the task
continue in the background. None waits until the task settles.
Type: float | None Default: None
The most tasks a conversation may have running when it starts another, across its whole delegation
tree, or None for no limit.
Type: int | None Default: None
Forward the events of every task’s run into the delegating run’s event stream, as
TaskProgressEvents.
Type: bool Default: False
A sub-agent that a SubAgentWorker in another process serves, reached through TaskControl.transport.
The worker runs the agent with its own model, tools and deps; this side only knows its name and what it is for.
The name the model delegates to, and the worker serves it under. 1 to 64 letters, digits, _ or -.
Type: str
What the agent is good at, for the system-prompt listing.
Type: str | None Default: None
Whether a finished task can be resumed, continuing the conversation the worker keeps.
The conversation lives in the worker that ran the task, so serve each remote agent name from one worker: another worker that picks up the follow-up fails the task, having no conversation to resume.
Type: bool Default: True
Whether the agent gets an ask_parent tool to ask the delegating agent a question.
Type: bool Default: True
Bases: Generic[AgentDepsT]
Serves sub-agents to delegating agents in other processes, over a transport.
Run serve in the process that hosts the agents. The delegating agent’s SubAgents lists them as
RemoteSubAgents with the same names, and reaches them through the same transport.
The worker keeps the conversations of tasks, up to max_conversations, so a delegating run can
resume them.
The agents this worker serves, by the name delegating agents reach them by.
Run controls such as usage limits or timeouts belong to the agent, or to the delegating run’s
SubAgents, which applies its own to the task.
Type: Mapping[str, AbstractAgent[AgentDepsT, object]]
The transport the delegating agents send tasks over.
Type: SubAgentTransport
The deps every task’s run gets. Deps never cross the transport.
Type: AgentDepsT
How many times to run a task again when its run raises an error, starting over from its prompt.
Cancellation, usage limits, and UserError are not retried.
Type: int Default: 0
How many task conversations to keep for resuming; the least recently used is forgotten first.
Type: int Default: 1000
@async
def serve() -> None
Receive and run tasks for every agent, until cancelled.
Bases: ABC
Carries SubAgentMessageEvents between a delegating run and the SubAgentWorker serving its remote agents.
A transport is a set of mailboxes. send delivers a message to the mailbox named by its mailbox
property, and receive waits for the next message in a mailbox. Messages a mailbox receives before
anyone waits on it are kept, in order.
The delegating run relays a task’s messages until the task settles, so the worker must end every task it
picks up with one TaskSettledEvent (TaskCompletedEvent, TaskFailedEvent or TaskCancelledEvent) to
its parent mailbox. SubAgentWorker does, including when it stops.
Implement this class to reach agents in other processes or machines, over a WebSocket, gRPC, a Redis
list, or anything else that can move bytes: use serialize_message and deserialize_message at the
boundary. InMemoryTransport serves a worker in the same process.
The transport is the trust boundary: anyone who can send to it can run the served agents, with their tools and dependencies. Authenticate and authorize senders in the transport.
@abstractmethod
@async
def send(message: SubAgentMessageEvent) -> None
Deliver message to message.mailbox, without waiting for anyone to receive it.
@abstractmethod
@async
def receive(mailbox: str) -> SubAgentMessageEvent
Wait for the next message delivered to mailbox and return it, in the order they were sent.
A stopping worker reports its running tasks as failed. Raise once a worker is gone without doing so, if the transport can tell: otherwise its delegating run waits for the task until it is cancelled.
SubAgentMessageEvent
@async
def release(mailbox: str) -> None
Discard mailbox and any messages left in it, once no one will receive from it again.
Called when a task settles, for its two task mailboxes. The default does nothing.
A message sent after the release, such as the late reply of a worker to a task that timed out, starts the mailbox again, and nobody may receive it. A transport that serves many tasks should expire such messages, for example with a time to live.
Bases: SubAgentTransport
A transport whose mailboxes are in-process queues, for a worker in the same process.
Messages are passed by reference, not serialized.
def __init__() -> None
Create a transport with no mailboxes; each is created when first sent to or received from.
@async
def send(message: SubAgentMessageEvent) -> None
Append message to its mailbox’s queue and wake whoever waits on that mailbox.
@async
def receive(mailbox: str) -> SubAgentMessageEvent
Take the oldest message in mailbox, waiting until one arrives.
SubAgentMessageEvent
@async
def release(mailbox: str) -> None
Drop mailbox and any messages still queued in it.
def serialize_message(message: SubAgentMessageEvent) -> bytes
Serialize a sub-agent message to JSON, for a transport that crosses a process boundary.
def deserialize_message(data: str | bytes) -> SubAgentMessageEvent
Deserialize a sub-agent message serialized by serialize_message.
SubAgentMessageEvent
ValueError— Ifdatais not a sub-agent message.
Bases: Generic[AgentDepsT]
Lets the model create sub-agents during a run, with a create_agent tool.
A created sub-agent is delegated to like any other, by the run that created it, until that run ends.
The SubAgents.models keys the model may run a created sub-agent on; the first is the default.
Empty: created sub-agents run on the delegating run’s model.
Type: Sequence[str] Default: ()
How many sub-agents one run may create.
Type: int Default: 5
Builds the agent. The default is an Agent with the requested instructions and no tools, on the
model SubAgents routes the delegation to.
The model wrote the spec’s name and description. Tracing records an agent’s own name and description
even without content, so the default agent has neither.
Type: DynamicAgentFactory[AgentDepsT] | None Default: None
What the model asked for when it called create_agent.
The new sub-agent’s name.
Type: str
What the sub-agent is for.
Type: str
The sub-agent’s instructions, written by the model.
Type: str
The SubAgents.models key the sub-agent runs on, or None for the delegating run’s model.
Builds the agent for a sub-agent the model created with create_agent.
Type: TypeAlias Default: 'Callable[[DynamicAgentSpec], AbstractAgent[AgentDepsT, Any]]'
Bases: CapabilityEvent
A message between a delegating run and one of its tasks, with SubAgents(task_control=...).
Messages are dispatched immediately: listeners run before the message takes effect, so they can
rewrite its fields or, for a ParentMessageEvent, veto it. A SubAgentTransport carries them to and
from a SubAgentWorker in another process.
Which side of the task receives this message.
Type: Recipient
The task this message belongs to.
Type: str
The name of the sub-agent running the task.
Type: str
The address a transport delivers this message to.
agent:<agent_name> for a message that starts a run, task:<task_id>:worker for one the running
task receives, and task:<task_id>:parent for one its parent receives.
Type: str
Bases: _Vetoable, SubAgentMessageEvent
A message from a delegating run to its task. A listener can veto it, and then it has no effect.
Bases: SubAgentMessageEvent
A message from a task to its delegating run.
Which side of a task a message is for: the worker serving the agent, the running task, or its parent.
Type: TypeAlias Default: Literal['worker', 'task', 'parent']
Bases: ChildMessageEvent
The task’s run ended. This is the task’s report to its delegating run.
The sub-agent’s usage when a worker in another process counted it separately.
None for a sub-agent that ran in the delegating run’s process: its usage was counted the way
SubAgents.forward_usage and SubAgent.usage_limits decide.
Type: RunUsage | None Default: None
Why a task moved to the background.
requested: the model delegated withbackground=True.auto: the task ran longer thanTaskControl.auto_background_after.question: the task asked a question, which the delegating model can only answer once the delegation tool returns.
Type: TypeAlias Default: Literal['requested', 'auto', 'question']
Bases: ParentMessageEvent
A request to a worker to start a run of the sub-agent: a new task or a follow-up.
Not to be confused with TaskStartedEvent, the worker’s reply once the run started.
Whether a listener vetoed it.
Type: bool Default: False
Why it was vetoed, reported to the model that asked for it.
Type: str | None Default: None
The task this message belongs to.
Type: str
The name of the sub-agent running the task.
Type: str
The address a transport delivers this message to.
agent:<agent_name> for a message that starts a run, task:<task_id>:worker for one the running
task receives, and task:<task_id>:parent for one its parent receives.
Type: str
What the sub-agent is asked to do. A listener can rewrite it.
Type: str
The task whose run started this one, or None when the top-level run did.
Type: str | None Default: None
The delegation level the task runs at, counting the top-level run as 1, like SubAgents.max_depth.
Type: int Default: 2
Whether the sub-agent gets an ask_parent tool.
Type: bool Default: True
Whether the sub-agent’s stream events are forwarded as TaskProgressEvents.
Type: bool Default: False
The delegating run’s usage limits, which a worker in another process applies to the sub-agent’s own usage.
Type: UsageLimits | None Default: None
W3C trace context of the delegation, so a worker in another process continues the delegating run’s trace.
Type: dict[str, str] Default: field(default_factory=(dict[str, str]))
When capability and application listeners receive the event.
Type: Literal[‘stream’, ‘immediate’] Default: 'stream'
The namespaced event kind, injected as the default on registered subclasses.
Type: str Default: ''
The run id of the capability that emitted this event.
Stamped at emission when unset; a pre-set value is preserved, so a capability re-emitting an event on behalf of another instance can keep the original attribution.
Type: str | None Default: None
The associated tool call id, when emitted by a capability-contributed tool.
Type: str | None Default: None
The associated tool name, when emitted by a capability-contributed tool.
Type: str | None Default: None
Event type identifier, used as a discriminator.
Type: Literal[‘capability’] Default: 'capability'
def veto(reason: str | None = None) -> None
Stop it from taking effect.
@classmethod
def __get_pydantic_core_schema__(
cls,
source: Any,
handler: pydantic.GetCoreSchemaHandler,
) -> pydantic_core.core_schema.CoreSchema
Build this family’s tagged union, instead of the plain dataclass schema pydantic would infer.
The set of event classes isn’t known when this module is imported — applications and
capabilities register their own by defining them — so the union can’t be written down as a
static Annotated[... , Field(discriminator=...)] the way the closed event types are. This
override builds it from the registry each time a schema is generated, and routes a tag no
class has registered to UnknownCapabilityEvent, so an event from a process that
imported a module this one didn’t still round-trips instead of failing validation.
Only the family base builds the union; a subclass gets its own dataclass schema, so annotating a concrete event type validates just that event.
pydantic_core.core_schema.CoreSchema
Bases: TaskRequestEvent
The delegating run assigns a new task to a sub-agent.
Whether a listener vetoed it.
Type: bool Default: False
Why it was vetoed, reported to the model that asked for it.
Type: str | None Default: None
The task this message belongs to.
Type: str
The name of the sub-agent running the task.
Type: str
The address a transport delivers this message to.
agent:<agent_name> for a message that starts a run, task:<task_id>:worker for one the running
task receives, and task:<task_id>:parent for one its parent receives.
Type: str
What the sub-agent is asked to do. A listener can rewrite it.
Type: str
The task whose run started this one, or None when the top-level run did.
Type: str | None Default: None
The delegation level the task runs at, counting the top-level run as 1, like SubAgents.max_depth.
Type: int Default: 2
Whether the sub-agent gets an ask_parent tool.
Type: bool Default: True
Whether the sub-agent’s stream events are forwarded as TaskProgressEvents.
Type: bool Default: False
The delegating run’s usage limits, which a worker in another process applies to the sub-agent’s own usage.
Type: UsageLimits | None Default: None
W3C trace context of the delegation, so a worker in another process continues the delegating run’s trace.
Type: dict[str, str] Default: field(default_factory=(dict[str, str]))
When capability and application listeners receive the event.
Type: Literal[‘stream’, ‘immediate’] Default: 'stream'
The namespaced event kind, injected as the default on registered subclasses.
Type: str Default: ''
The run id of the capability that emitted this event.
Stamped at emission when unset; a pre-set value is preserved, so a capability re-emitting an event on behalf of another instance can keep the original attribution.
Type: str | None Default: None
The associated tool call id, when emitted by a capability-contributed tool.
Type: str | None Default: None
The associated tool name, when emitted by a capability-contributed tool.
Type: str | None Default: None
Event type identifier, used as a discriminator.
Type: Literal[‘capability’] Default: 'capability'
def veto(reason: str | None = None) -> None
Stop it from taking effect.
@classmethod
def __get_pydantic_core_schema__(
cls,
source: Any,
handler: pydantic.GetCoreSchemaHandler,
) -> pydantic_core.core_schema.CoreSchema
Build this family’s tagged union, instead of the plain dataclass schema pydantic would infer.
The set of event classes isn’t known when this module is imported — applications and
capabilities register their own by defining them — so the union can’t be written down as a
static Annotated[... , Field(discriminator=...)] the way the closed event types are. This
override builds it from the registry each time a schema is generated, and routes a tag no
class has registered to UnknownCapabilityEvent, so an event from a process that
imported a module this one didn’t still round-trips instead of failing validation.
Only the family base builds the union; a subclass gets its own dataclass schema, so annotating a concrete event type validates just that event.
pydantic_core.core_schema.CoreSchema
Bases: TaskRequestEvent
The delegating run resumes a finished task’s conversation with a new prompt.
Whether a listener vetoed it.
Type: bool Default: False
Why it was vetoed, reported to the model that asked for it.
Type: str | None Default: None
The task this message belongs to.
Type: str
The name of the sub-agent running the task.
Type: str
The address a transport delivers this message to.
agent:<agent_name> for a message that starts a run, task:<task_id>:worker for one the running
task receives, and task:<task_id>:parent for one its parent receives.
Type: str
What the sub-agent is asked to do. A listener can rewrite it.
Type: str
The task whose run started this one, or None when the top-level run did.
Type: str | None Default: None
The delegation level the task runs at, counting the top-level run as 1, like SubAgents.max_depth.
Type: int Default: 2
Whether the sub-agent gets an ask_parent tool.
Type: bool Default: True
Whether the sub-agent’s stream events are forwarded as TaskProgressEvents.
Type: bool Default: False
The delegating run’s usage limits, which a worker in another process applies to the sub-agent’s own usage.
Type: UsageLimits | None Default: None
W3C trace context of the delegation, so a worker in another process continues the delegating run’s trace.
Type: dict[str, str] Default: field(default_factory=(dict[str, str]))
When capability and application listeners receive the event.
Type: Literal[‘stream’, ‘immediate’] Default: 'stream'
The namespaced event kind, injected as the default on registered subclasses.
Type: str Default: ''
The run id of the capability that emitted this event.
Stamped at emission when unset; a pre-set value is preserved, so a capability re-emitting an event on behalf of another instance can keep the original attribution.
Type: str | None Default: None
The associated tool call id, when emitted by a capability-contributed tool.
Type: str | None Default: None
The associated tool name, when emitted by a capability-contributed tool.
Type: str | None Default: None
Event type identifier, used as a discriminator.
Type: Literal[‘capability’] Default: 'capability'
def veto(reason: str | None = None) -> None
Stop it from taking effect.
@classmethod
def __get_pydantic_core_schema__(
cls,
source: Any,
handler: pydantic.GetCoreSchemaHandler,
) -> pydantic_core.core_schema.CoreSchema
Build this family’s tagged union, instead of the plain dataclass schema pydantic would infer.
The set of event classes isn’t known when this module is imported — applications and
capabilities register their own by defining them — so the union can’t be written down as a
static Annotated[... , Field(discriminator=...)] the way the closed event types are. This
override builds it from the registry each time a schema is generated, and routes a tag no
class has registered to UnknownCapabilityEvent, so an event from a process that
imported a module this one didn’t still round-trips instead of failing validation.
Only the family base builds the union; a subclass gets its own dataclass schema, so annotating a concrete event type validates just that event.
pydantic_core.core_schema.CoreSchema
Bases: ChildMessageEvent
A worker picked the task up and its run is starting.
A remote task that no worker picks up within TaskControl.accept_timeout fails.
Bases: CapabilityEvent
A task now runs in the background: the delegation tool returned a receipt, and its report arrives later.
A requested task still running when the delegation tool gets its receipt, but settled before this event is
announced, as one replayed under durable execution can be, gets this event after its settle event.
The task now running in the background.
Type: str
The name of the sub-agent running the task.
Type: str
Why it moved to the background.
Type: BackgroundReason
Bases: ChildMessageEvent
An event from the sub-agent’s own run, forwarded while the task runs, with TaskControl.forward_events.
Dispatched at its stream position, like the event it carries.
The sub-agent’s stream event.
Type: AgentStreamEvent
Bases: ChildMessageEvent
The task asks its delegating run a question and waits for a TaskAnsweredEvent.
A listener can answer it by setting answer, and then the delegating model is not asked.
Identifies the question, so the answer can name it.
Type: str
The question.
Type: str
An answer a listener supplies, sent to the task without involving the delegating model.
Type: str | None Default: None
Bases: ParentMessageEvent
The delegating run answers the question a task is waiting on.
Whether a listener vetoed it.
Type: bool Default: False
Why it was vetoed, reported to the model that asked for it.
Type: str | None Default: None
The task this message belongs to.
Type: str
The name of the sub-agent running the task.
Type: str
The address a transport delivers this message to.
agent:<agent_name> for a message that starts a run, task:<task_id>:worker for one the running
task receives, and task:<task_id>:parent for one its parent receives.
Type: str
The TaskQuestionAskedEvent.question_id this answers.
Type: str
The answer. A listener can rewrite it.
Type: str
When capability and application listeners receive the event.
Type: Literal[‘stream’, ‘immediate’] Default: 'stream'
The namespaced event kind, injected as the default on registered subclasses.
Type: str Default: ''
The run id of the capability that emitted this event.
Stamped at emission when unset; a pre-set value is preserved, so a capability re-emitting an event on behalf of another instance can keep the original attribution.
Type: str | None Default: None
The associated tool call id, when emitted by a capability-contributed tool.
Type: str | None Default: None
The associated tool name, when emitted by a capability-contributed tool.
Type: str | None Default: None
Event type identifier, used as a discriminator.
Type: Literal[‘capability’] Default: 'capability'
def veto(reason: str | None = None) -> None
Stop it from taking effect.
@classmethod
def __get_pydantic_core_schema__(
cls,
source: Any,
handler: pydantic.GetCoreSchemaHandler,
) -> pydantic_core.core_schema.CoreSchema
Build this family’s tagged union, instead of the plain dataclass schema pydantic would infer.
The set of event classes isn’t known when this module is imported — applications and
capabilities register their own by defining them — so the union can’t be written down as a
static Annotated[... , Field(discriminator=...)] the way the closed event types are. This
override builds it from the registry each time a schema is generated, and routes a tag no
class has registered to UnknownCapabilityEvent, so an event from a process that
imported a module this one didn’t still round-trips instead of failing validation.
Only the family base builds the union; a subclass gets its own dataclass schema, so annotating a concrete event type validates just that event.
pydantic_core.core_schema.CoreSchema
Bases: ParentMessageEvent
The delegating run steers a running task, which sees the message at its next model request.
Whether a listener vetoed it.
Type: bool Default: False
Why it was vetoed, reported to the model that asked for it.
Type: str | None Default: None
The task this message belongs to.
Type: str
The name of the sub-agent running the task.
Type: str
The address a transport delivers this message to.
agent:<agent_name> for a message that starts a run, task:<task_id>:worker for one the running
task receives, and task:<task_id>:parent for one its parent receives.
Type: str
The steering message. A listener can rewrite it.
Type: str
When capability and application listeners receive the event.
Type: Literal[‘stream’, ‘immediate’] Default: 'stream'
The namespaced event kind, injected as the default on registered subclasses.
Type: str Default: ''
The run id of the capability that emitted this event.
Stamped at emission when unset; a pre-set value is preserved, so a capability re-emitting an event on behalf of another instance can keep the original attribution.
Type: str | None Default: None
The associated tool call id, when emitted by a capability-contributed tool.
Type: str | None Default: None
The associated tool name, when emitted by a capability-contributed tool.
Type: str | None Default: None
Event type identifier, used as a discriminator.
Type: Literal[‘capability’] Default: 'capability'
def veto(reason: str | None = None) -> None
Stop it from taking effect.
@classmethod
def __get_pydantic_core_schema__(
cls,
source: Any,
handler: pydantic.GetCoreSchemaHandler,
) -> pydantic_core.core_schema.CoreSchema
Build this family’s tagged union, instead of the plain dataclass schema pydantic would infer.
The set of event classes isn’t known when this module is imported — applications and
capabilities register their own by defining them — so the union can’t be written down as a
static Annotated[... , Field(discriminator=...)] the way the closed event types are. This
override builds it from the registry each time a schema is generated, and routes a tag no
class has registered to UnknownCapabilityEvent, so an event from a process that
imported a module this one didn’t still round-trips instead of failing validation.
Only the family base builds the union; a subclass gets its own dataclass schema, so annotating a concrete event type validates just that event.
pydantic_core.core_schema.CoreSchema
Bases: ParentMessageEvent
The delegating run asks a running task to stop before its next model request.
Whether a listener vetoed it.
Type: bool Default: False
Why it was vetoed, reported to the model that asked for it.
Type: str | None Default: None
The task this message belongs to.
Type: str
The name of the sub-agent running the task.
Type: str
The address a transport delivers this message to.
agent:<agent_name> for a message that starts a run, task:<task_id>:worker for one the running
task receives, and task:<task_id>:parent for one its parent receives.
Type: str
When capability and application listeners receive the event.
Type: Literal[‘stream’, ‘immediate’] Default: 'stream'
The namespaced event kind, injected as the default on registered subclasses.
Type: str Default: ''
The run id of the capability that emitted this event.
Stamped at emission when unset; a pre-set value is preserved, so a capability re-emitting an event on behalf of another instance can keep the original attribution.
Type: str | None Default: None
The associated tool call id, when emitted by a capability-contributed tool.
Type: str | None Default: None
The associated tool name, when emitted by a capability-contributed tool.
Type: str | None Default: None
Event type identifier, used as a discriminator.
Type: Literal[‘capability’] Default: 'capability'
def veto(reason: str | None = None) -> None
Stop it from taking effect.
@classmethod
def __get_pydantic_core_schema__(
cls,
source: Any,
handler: pydantic.GetCoreSchemaHandler,
) -> pydantic_core.core_schema.CoreSchema
Build this family’s tagged union, instead of the plain dataclass schema pydantic would infer.
The set of event classes isn’t known when this module is imported — applications and
capabilities register their own by defining them — so the union can’t be written down as a
static Annotated[... , Field(discriminator=...)] the way the closed event types are. This
override builds it from the registry each time a schema is generated, and routes a tag no
class has registered to UnknownCapabilityEvent, so an event from a process that
imported a module this one didn’t still round-trips instead of failing validation.
Only the family base builds the union; a subclass gets its own dataclass schema, so annotating a concrete event type validates just that event.
pydantic_core.core_schema.CoreSchema
Bases: ParentMessageEvent
The delegating run stops a running task immediately, interrupting its current model request or tool calls.
Whether a listener vetoed it.
Type: bool Default: False
Why it was vetoed, reported to the model that asked for it.
Type: str | None Default: None
The task this message belongs to.
Type: str
The name of the sub-agent running the task.
Type: str
The address a transport delivers this message to.
agent:<agent_name> for a message that starts a run, task:<task_id>:worker for one the running
task receives, and task:<task_id>:parent for one its parent receives.
Type: str
When capability and application listeners receive the event.
Type: Literal[‘stream’, ‘immediate’] Default: 'stream'
The namespaced event kind, injected as the default on registered subclasses.
Type: str Default: ''
The run id of the capability that emitted this event.
Stamped at emission when unset; a pre-set value is preserved, so a capability re-emitting an event on behalf of another instance can keep the original attribution.
Type: str | None Default: None
The associated tool call id, when emitted by a capability-contributed tool.
Type: str | None Default: None
The associated tool name, when emitted by a capability-contributed tool.
Type: str | None Default: None
Event type identifier, used as a discriminator.
Type: Literal[‘capability’] Default: 'capability'
def veto(reason: str | None = None) -> None
Stop it from taking effect.
@classmethod
def __get_pydantic_core_schema__(
cls,
source: Any,
handler: pydantic.GetCoreSchemaHandler,
) -> pydantic_core.core_schema.CoreSchema
Build this family’s tagged union, instead of the plain dataclass schema pydantic would infer.
The set of event classes isn’t known when this module is imported — applications and
capabilities register their own by defining them — so the union can’t be written down as a
static Annotated[... , Field(discriminator=...)] the way the closed event types are. This
override builds it from the registry each time a schema is generated, and routes a tag no
class has registered to UnknownCapabilityEvent, so an event from a process that
imported a module this one didn’t still round-trips instead of failing validation.
Only the family base builds the union; a subclass gets its own dataclass schema, so annotating a concrete event type validates just that event.
pydantic_core.core_schema.CoreSchema
Bases: ChildMessageEvent
A remote task’s run failed and its worker is running it again, as SubAgentWorker.retries allows.
The attempt about to start; the first retry is attempt 2.
Type: int
The error the previous attempt failed with.
Type: str
Bases: TaskSettledEvent
The task finished with an output.
The task this message belongs to.
Type: str
The name of the sub-agent running the task.
Type: str
The address a transport delivers this message to.
agent:<agent_name> for a message that starts a run, task:<task_id>:worker for one the running
task receives, and task:<task_id>:parent for one its parent receives.
Type: str
The sub-agent’s usage when a worker in another process counted it separately.
None for a sub-agent that ran in the delegating run’s process: its usage was counted the way
SubAgents.forward_usage and SubAgent.usage_limits decide.
Type: RunUsage | None Default: None
The sub-agent’s output, as text. A listener can rewrite it before the delegating model reads it.
Type: str
When capability and application listeners receive the event.
Type: Literal[‘stream’, ‘immediate’] Default: 'stream'
The namespaced event kind, injected as the default on registered subclasses.
Type: str Default: ''
The run id of the capability that emitted this event.
Stamped at emission when unset; a pre-set value is preserved, so a capability re-emitting an event on behalf of another instance can keep the original attribution.
Type: str | None Default: None
The associated tool call id, when emitted by a capability-contributed tool.
Type: str | None Default: None
The associated tool name, when emitted by a capability-contributed tool.
Type: str | None Default: None
Event type identifier, used as a discriminator.
Type: Literal[‘capability’] Default: 'capability'
@classmethod
def __get_pydantic_core_schema__(
cls,
source: Any,
handler: pydantic.GetCoreSchemaHandler,
) -> pydantic_core.core_schema.CoreSchema
Build this family’s tagged union, instead of the plain dataclass schema pydantic would infer.
The set of event classes isn’t known when this module is imported — applications and
capabilities register their own by defining them — so the union can’t be written down as a
static Annotated[... , Field(discriminator=...)] the way the closed event types are. This
override builds it from the registry each time a schema is generated, and routes a tag no
class has registered to UnknownCapabilityEvent, so an event from a process that
imported a module this one didn’t still round-trips instead of failing validation.
Only the family base builds the union; a subclass gets its own dataclass schema, so annotating a concrete event type validates just that event.
pydantic_core.core_schema.CoreSchema
Bases: TaskSettledEvent
The task’s run failed, or ended in a way that delivered no output.
The task this message belongs to.
Type: str
The name of the sub-agent running the task.
Type: str
The address a transport delivers this message to.
agent:<agent_name> for a message that starts a run, task:<task_id>:worker for one the running
task receives, and task:<task_id>:parent for one its parent receives.
Type: str
The sub-agent’s usage when a worker in another process counted it separately.
None for a sub-agent that ran in the delegating run’s process: its usage was counted the way
SubAgents.forward_usage and SubAgent.usage_limits decide.
Type: RunUsage | None Default: None
What went wrong, as reported to the delegating model.
Type: str
When capability and application listeners receive the event.
Type: Literal[‘stream’, ‘immediate’] Default: 'stream'
The namespaced event kind, injected as the default on registered subclasses.
Type: str Default: ''
The run id of the capability that emitted this event.
Stamped at emission when unset; a pre-set value is preserved, so a capability re-emitting an event on behalf of another instance can keep the original attribution.
Type: str | None Default: None
The associated tool call id, when emitted by a capability-contributed tool.
Type: str | None Default: None
The associated tool name, when emitted by a capability-contributed tool.
Type: str | None Default: None
Event type identifier, used as a discriminator.
Type: Literal[‘capability’] Default: 'capability'
@classmethod
def __get_pydantic_core_schema__(
cls,
source: Any,
handler: pydantic.GetCoreSchemaHandler,
) -> pydantic_core.core_schema.CoreSchema
Build this family’s tagged union, instead of the plain dataclass schema pydantic would infer.
The set of event classes isn’t known when this module is imported — applications and
capabilities register their own by defining them — so the union can’t be written down as a
static Annotated[... , Field(discriminator=...)] the way the closed event types are. This
override builds it from the registry each time a schema is generated, and routes a tag no
class has registered to UnknownCapabilityEvent, so an event from a process that
imported a module this one didn’t still round-trips instead of failing validation.
Only the family base builds the union; a subclass gets its own dataclass schema, so annotating a concrete event type validates just that event.
pydantic_core.core_schema.CoreSchema
Bases: TaskSettledEvent
The task stopped because it was cancelled. A resumable task can be followed up on.
The task this message belongs to.
Type: str
The name of the sub-agent running the task.
Type: str
The address a transport delivers this message to.
agent:<agent_name> for a message that starts a run, task:<task_id>:worker for one the running
task receives, and task:<task_id>:parent for one its parent receives.
Type: str
The sub-agent’s usage when a worker in another process counted it separately.
None for a sub-agent that ran in the delegating run’s process: its usage was counted the way
SubAgents.forward_usage and SubAgent.usage_limits decide.
Type: RunUsage | None Default: None
Whether the task was stopped immediately rather than before its next model request.
Type: bool
When capability and application listeners receive the event.
Type: Literal[‘stream’, ‘immediate’] Default: 'stream'
The namespaced event kind, injected as the default on registered subclasses.
Type: str Default: ''
The run id of the capability that emitted this event.
Stamped at emission when unset; a pre-set value is preserved, so a capability re-emitting an event on behalf of another instance can keep the original attribution.
Type: str | None Default: None
The associated tool call id, when emitted by a capability-contributed tool.
Type: str | None Default: None
The associated tool name, when emitted by a capability-contributed tool.
Type: str | None Default: None
Event type identifier, used as a discriminator.
Type: Literal[‘capability’] Default: 'capability'
@classmethod
def __get_pydantic_core_schema__(
cls,
source: Any,
handler: pydantic.GetCoreSchemaHandler,
) -> pydantic_core.core_schema.CoreSchema
Build this family’s tagged union, instead of the plain dataclass schema pydantic would infer.
The set of event classes isn’t known when this module is imported — applications and
capabilities register their own by defining them — so the union can’t be written down as a
static Annotated[... , Field(discriminator=...)] the way the closed event types are. This
override builds it from the registry each time a schema is generated, and routes a tag no
class has registered to UnknownCapabilityEvent, so an event from a process that
imported a module this one didn’t still round-trips instead of failing validation.
Only the family base builds the union; a subclass gets its own dataclass schema, so annotating a concrete event type validates just that event.
pydantic_core.core_schema.CoreSchema
Bases: _Vetoable, CapabilityEvent
The model is creating a sub-agent with create_agent (SubAgents.dynamic_agents).
Dispatched immediately, so a listener can rewrite description and instructions, or veto the
creation.
Whether a listener vetoed it.
Type: bool Default: False
Why it was vetoed, reported to the model that asked for it.
Type: str | None Default: None
The name the model gave the sub-agent, which it delegates to.
Also loads from name, the key it was serialized under before the rename.
Type: Annotated[str, Field(validation_alias=(AliasChoices(‘agent_name’, ‘name’)))]
What the sub-agent is for. It reaches only a custom DynamicAgents.factory, as DynamicAgentSpec.description;
the model is never shown it. A listener can rewrite it.
Type: str
The sub-agent’s instructions. A listener can rewrite them.
Type: str
The SubAgents.models key the sub-agent runs on, or None for the delegating run’s model.
When capability and application listeners receive the event.
Type: Literal[‘stream’, ‘immediate’] Default: 'stream'
The namespaced event kind, injected as the default on registered subclasses.
Type: str Default: ''
The run id of the capability that emitted this event.
Stamped at emission when unset; a pre-set value is preserved, so a capability re-emitting an event on behalf of another instance can keep the original attribution.
Type: str | None Default: None
The associated tool call id, when emitted by a capability-contributed tool.
Type: str | None Default: None
The associated tool name, when emitted by a capability-contributed tool.
Type: str | None Default: None
Event type identifier, used as a discriminator.
Type: Literal[‘capability’] Default: 'capability'
def veto(reason: str | None = None) -> None
Stop it from taking effect.
@classmethod
def __get_pydantic_core_schema__(
cls,
source: Any,
handler: pydantic.GetCoreSchemaHandler,
) -> pydantic_core.core_schema.CoreSchema
Build this family’s tagged union, instead of the plain dataclass schema pydantic would infer.
The set of event classes isn’t known when this module is imported — applications and
capabilities register their own by defining them — so the union can’t be written down as a
static Annotated[... , Field(discriminator=...)] the way the closed event types are. This
override builds it from the registry each time a schema is generated, and routes a tag no
class has registered to UnknownCapabilityEvent, so an event from a process that
imported a module this one didn’t still round-trips instead of failing validation.
Only the family base builds the union; a subclass gets its own dataclass schema, so annotating a concrete event type validates just that event.
pydantic_core.core_schema.CoreSchema