Subagents
A subagent is a real HPD agent exposed to a parent agent as a tool. The parent model sees one generated function with an input argument. By default, when the model calls it, the runtime builds the child agent from its definition (or reuses the one it already built), creates an agent-owned child thread using the configured context policy, streams child events through the parent event path, and returns the child answer as the tool result.
Use subagents when the parent should delegate to a specialist during normal tool calling. Use multi-agent workflows when the whole task should follow an explicit graph of roles and routes.
Smallest Setup
Create a tool harness method marked with [SubAgent] and return a SubAgent definition:
using HPD.Agent;
public sealed class SpecialistTools
{
[SubAgent]
public SubAgent Summarizer() =>
SubAgent.FromConfig(
"specialist.summarizer",
"summarizer",
"Summarizes a request before the parent answers.",
new AgentConfig
{
Name = "Summarizer",
SystemInstructions = "Summarize the user's request in three concise bullets.",
});
}Register the harness like any other tool harness:
var assistant = new AgentConfig()
.WithChatClient(chatClient)
.WithToolHarness<SpecialistTools>();
await using var runtime = await new AgentRuntimeBuilder()
.AddAgent("assistant", assistant)
.BuildAsync();The first argument is the durable child AgentId; the second is the model-facing tool name. SubAgent.FromConfig(...) defaults to SubAgentContextPolicy.Handoff. Each call creates a child thread and passes the parent conversation as handoff context unless the author selects a different context policy.
The runtime uses an in-memory session store by default. Use AgentRuntimeBuilder.WithSessionStore(...) when subagent threads should survive process restarts or be visible to another host.
Tool Shape
By default, the generated tool takes one model-facing argument:
{
"input": "Summarize this request."
}The subagent name becomes the tool name. The description becomes the tool description, so write it as guidance for the parent model. Subagent tools require permission by default.
Control Nested Availability
Each subagent capability controls the agent depths from which that particular tool may be invoked. The default is root-only, so registering the same harness on a child does not accidentally make a subagent recursively call itself:
root (depth 0) sees researcher
└─ researcher (depth 1) does not see researcherNo configuration is required for this safe default. Permit intentional nesting with WithAvailability(...):
return SubAgent.FromConfig(
"research/coordinator",
"coordinator",
"Coordinates specialized research agents.",
coordinatorConfig)
.WithAvailability(SubAgentAvailability.ThroughDepth(2));ThroughDepth(2) lets agents at depths zero and one invoke the capability, creating children at depths one and two. The tool is hidden at depth two. Use SubAgentAvailability.AnyAllowedDepth when the capability should remain available until the agent-wide AgentConfig.MaxSubAgentDepth ceiling is reached.
Availability is enforced both in the model-facing tool projection and again during invocation. A stale or manually constructed call therefore cannot bypass the policy. The per-capability policy may be stricter than MaxSubAgentDepth, but never less restrictive.
Configure Direct Child Runs
SubAgentRunConfig entries are supplied as one per-input collection. Use SubAgentTarget.All for a shared direct-child baseline and an exact target when only one declaration should receive the overlay:
var childRun = new SubAgentRunConfig
{
Target = SubAgentTarget.All,
SystemInstructions = new SystemInstructionsRunConfig
{
Append = "Report concrete review findings first."
},
Security = new AgentSecurityRunConfig
{
Approval = AgentApprovalPolicy.ReviewProtectedActions
}
};
await parentAgent.RunAsync(
"Review the current change.",
subAgentRunConfigs: [childRun]);Target one source declaration by its owning harness type and declaration member:
var sharedSecurity = new AgentSecurityRunConfig
{
Approval = AgentApprovalPolicy.ReviewProtectedActions
};
var reviewerSecurity = new AgentSecurityRunConfig
{
Approval = AgentApprovalPolicy.ReviewProtectedActions,
Sandbox = new AgentSandboxRunConfig
{
Escape = AgentSandboxEscapePolicy.Deny
}
};
await parentAgent.RunAsync(
"Review the current change.",
subAgentRunConfigs:
[
new SubAgentRunConfig
{
Target = SubAgentTarget.All,
Security = sharedSecurity
},
new SubAgentRunConfig
{
Target = SubAgentTarget.Declared<CodingToolHarness>(
nameof(CodingToolHarness.Reviewer)),
Security = reviewerSecurity
}
]);An exact entry overlays the shared baseline only for that declaration. Use SubAgentTarget.Agent("coding/worker") only when that AgentId identifies one direct-child declaration; ambiguous identifiers fail and require the declaration target. Model-facing action names are not target identities.
Target Identity
The public targeting surface is deliberately limited to:
SubAgentTarget.AllSubAgentTarget.Agent(agentId)SubAgentTarget.Declared<T>(nameof(Member))
Declaration identity combines the owning ToolHarness activation identity with the [SubAgent] source member. Changing the model-facing action or description does not change that identity. Renaming or moving the declaration member does. Capability IDs are internal and are not accepted by the authoring API.
The complete declaration catalog is validated before parent input admission. Unknown, duplicate, malformed, and ambiguous targets fail before a child creation reservation or dispatch. Important codes include:
subagent_target_not_foundsubagent_target_ambiguoussubagent_target_duplicatesubagent_target_catalog_required
The child still owns its complete AgentConfig. Parent and child security authority is intersected so a child cannot silently broaden the controller's permissions.
Direct children inherit every configured parent client family through ordinary immediate-parent fallback, including families the parent has not constructed yet. To exclude one inherited family, opt out explicitly for that target:
var reviewerRun = new SubAgentRunConfig
{
Target = SubAgentTarget.Declared<CodingToolHarness>(
nameof(CodingToolHarness.Reviewer)),
ClientInheritance = new AgentClientInheritance
{
ImageGeneration = ClientFamilyInheritanceMode.UseOwn
},
Clients = new AgentClientsConfig
{
Chat = reviewerChat
}
};UseOwn removes only the named family's parent fallback. An explicit selection for that family still applies. Provider payloads and operation options are snapshotted through the generated provider contract and restored before the child executes.
Inheritance applies to all client families, not only Chat: realtime, image generation, embeddings, speech, hosted files, voice activity, and end-of-turn detection follow the same immediate-parent rule. A configured parent family is visible to the child even if no client has been constructed yet.
A provider profile by itself is a baseline, not a selection. A profile is used when the family has an explicit provider or a matching provider default. An unselected profile-only family remains absent instead of guessing a provider.
A child's configuration is resolved in memory every time it runs, so client selections, provider payloads, and credentials, including a literal API key the runtime was built with, reach the child without being written to the journal.
There is no implicit inheritance of the parent's full AgentRunConfig. Pass only the portable non-client child behavior the invocation should receive.
AgentRunConfig.Harnesses is not inherited implicitly. Configure direct child harness settings explicitly through SubAgentRunConfig.Harnesses:
var childRun = new SubAgentRunConfig
{
Target = SubAgentTarget.All
};
childRun.Harnesses
.For<SearchHarness>()
.Override(new SearchConfigOverrides
{
MaxResults = 5
});
await parentAgent.RunAsync(
"Research this question",
subAgentRunConfigs: [childRun]);The override is resolved against the child's registered harness owner. It does not copy the parent's harness identity or configuration handle. The child keeps its own dependencies, middleware, construction settings, and configuration baseline.
Use SubAgentRunDefaults.Harnesses when a child should intentionally pass a harness setting to its own descendants:
var descendantDefaults = new SubAgentRunDefaults();
descendantDefaults.Harnesses
.For<SearchHarness>()
.Override(new SearchConfigOverrides
{
MaxResults = 3
});
var childRun = new SubAgentRunConfig
{
DescendantDefaults = descendantDefaults
};The equivalent serialized direct-child setting is:
subAgentRunConfigs:
- target:
kind: all
harnesses:
- name: SearchHarness
config:
maxResults: 5Descendant Overrides
DescendantDefaults carries explicit behavior to further descendants. Exact target settings overlay the shared All descendant settings field by field, so an exact target can change one descendant policy without erasing unrelated shared defaults.
Chat propagation is a separate, Chat-only control:
var forcedChat = new SubAgentRunConfig
{
Target = SubAgentTarget.All,
Clients = new AgentClientsConfig { Chat = coordinatedChat },
ClientPropagation = SubAgentClientPropagation.ThroughDepth(3)
};Depth counts from the override origin:
DirectChildrenThroughDepth(n)EntireTree
An explicit propagated Chat selection wins over stored child defaults while the scope is active. When several authorized overrides overlap, the nearer override wins for its admitted depth. Its scope can then expire while an outer scope resumes. Scopes come from the parent's current subagent run configuration each time a child runs.
Other client families are never forced through this Chat-only control. They continue to use ordinary immediate-parent fallback.
The child must register the named harness. Missing or ambiguous owners fail with a child-specific configuration path before a child harness tool executes.
For synchronous calls, the tool result is the child agent's text response. HPD also records subagent metadata on the tool result, including subAgentStatus, subAgentSessionId, subAgentThreadId, subAgentName, and invocationId.
Execution And Definition Updates
The targeted collection is normalized and snapshotted when the parent input is admitted. Mutating, clearing, or reordering the caller's collection afterward does not alter the admitted run.
A child's settings are not frozen. Each run of a child, including a later continue, resolves them from three layers, highest last: the runtime's composition, the child's own AgentConfig, and the parent's current subagent run configuration. A middleware the child's definition declares replaces the runtime's middleware of the same type for that child. Input sent directly to a child's thread uses its definition and the runtime only. After a restart or a configuration change, a continued child runs with the current settings.
Stored definitions change through runtime.Agents:
await runtime.Agents.UpdateAsync("specialist.reviewer", updatedConfig);- An execution already running keeps the agent it started with and finishes consistently.
- The next execution builds from the updated definition.
CreateAsync,UpdateAsync, andDeleteAsyncthrowAgentDefinitionReadOnlyExceptionfor an id that code owns; itsOwnernames what declares it.CreateAsyncthrowsAgentDefinitionExistsExceptionwhen the store already has the id. The check and the write are one atomic store operation.CreateAsyncandUpdateAsyncvalidate the definition, including against the runtime's composition, and throwValidationExceptionwith itsErrors.runtime.Agents.Validate(config)returns the same errors without writing.
Code-owned definitions (FromConfig, FromParent) are never written to the agent store. Change them in code; a new runtime uses the new definition.
Invocation Mode
Subagents are synchronous by default: the parent model calls the tool, HPD waits for the child agent, and the tool result is the child text.
For long-running delegation, set an invocation mode policy on the SubAgent definition:
[SubAgent]
public SubAgent Reviewer() =>
SubAgent.FromConfig(
"specialist.reviewer",
"reviewer",
"Reviews a draft and reports actionable issues.",
reviewerConfig,
contextPolicy: SubAgentContextPolicy.Handoff,
invocationModePolicy: AgentInvocationModePolicy.ModelChoice,
operationNotification: null);Policies:
| Policy | Tool Shape | Tool Result |
|---|---|---|
SynchronousOnly | input | Final child text |
BackgroundOnly | input | Background launch receipt |
ModelChoice | arguments.input, invocation.mode | Final child text or background launch receipt |
For ModelChoice, the model can pass:
{
"arguments": { "input": "Review this draft." },
"invocation": { "mode": "background" }
}Background subagent calls return immediately with a structured receipt that includes the background taskId. The child result is delivered later through the background task notification system, using the child text as the completion summary.
See Background Tasks And Notifications.
Choose The Source
A subagent has three configuration sources. Every source still requires a stable AgentId:
| Source | Use When | What Happens |
|---|---|---|
SubAgent.FromConfig(...) | The specialist is defined next to the parent harness. | HPD builds a child agent from the inline AgentConfig. Missing client families use ordinary immediate-parent inheritance, including configured families not yet constructed. |
SubAgent.FromParent(...) | The specialist should use the effective parent configuration. | HPD takes an immutable snapshot of the parent configuration as the child definition. Child harnesses can still extend it. |
SubAgent.FromAgentId(...) | The specialist is an agent the runtime already runs, or is stored and managed outside this harness. | Names a code agent registered on the runtime or a stored agent in its agent store. The runtime builds and caches it like any other agent it runs, then runs it with the selected context, availability, and run-configuration policies. |
FromConfig and FromParent definitions are code-owned. When the runtime builds the parent agent, it registers each harness subagent's definition under its AgentId, owned by the harness capability that declares it, and builds the child from it the first time it is needed. Nothing is written to the agent store, and the ids are reserved. runtime.Agents.ListAsync() shows them with Source = Code, IsEditable = false, and Owner naming the declaring capability, next to stored definitions.
A FromAgentId subagent is checked when the parent agent is built: if the id names neither a code agent of the runtime nor a stored agent, building the parent fails. Register the agent with AddAgent, or create the stored definition first with runtime.Agents.CreateAsync(...).
Inline config is best for local specialists that belong to one product surface. Stored agents are better when specialists are user-created, versioned, administered, or shared across parent agents.
What A Child Agent Gets
The runtime builds every child from two parts:
| From | What |
|---|---|
| The child's own definition | instructions, model, harnesses, definition middleware (AgentConfig.Middlewares), plan mode, goals |
| The runtime | stores, providers and secrets, host services, events, and every middleware registered on AgentRuntimeBuilder |
Middleware registered on the runtime builder, including WithPermissions() and WithSandbox(...), is one instance shared by every agent the runtime runs. A subagent in a plain console app is checked by the same permission middleware and runs in the same sandbox as its parent. Shared middleware starts and stops once with the runtime, however many agents use it. Policies such as retry or PII protection come from each agent's own definition, so a parent's policies do not run for its children.
Built children are cached by the runtime and reused across sessions and threads, and disposed with the runtime. Their events reach runtime.Subscribe(...). See The Runtime And Its Agents for code and stored agents and when the runtime builds them.
Add Child Tools
Pass tool harness types after the context policy:
[SubAgent]
public SubAgent Researcher() =>
SubAgent.FromConfig(
"specialist.researcher",
"researcher",
"Researches a question using the approved search tools.",
new AgentConfig
{
Name = "Researcher",
SystemInstructions = "Research the request and return cited notes.",
},
contextPolicy: SubAgentContextPolicy.Handoff,
toolharnessTypes: [typeof(SearchTools), typeof(CitationTools)]);Those harnesses are registered on the child agent, not exposed directly to the parent. The parent sees only the researcher tool.
Choose The Context Policy
The context policy directly decides how the child conversation begins.
| Policy | Session | History | Use When |
|---|---|---|---|
SubAgentContextPolicy.Handoff | Parent session | Parent conversation rendered as text | Default. The child needs the current conversation. |
SubAgentContextPolicy.Fresh | Parent session | Starts empty | The delegated input is self-contained. |
SubAgentContextPolicy.ModelChoice | Parent session | Model chooses handoff or fresh | Different calls need different amounts of context. |
The child's thread is always created in the parent's session. When ModelChoice is enabled, the tool schema exposes context: "handoff" | "fresh". Omitting it defaults to fresh. Fixed policies do not expose the argument.
Continue A Child Conversation
Completing a delegation does not destroy the child conversation. A child is addressed like any other conversation, by sessionId + threadId, and each run on it names the agent that answers. The parent's registry records which agent the delegation used, as ChildAgentId. Pass it as the agentId to continue with the same subagent, or name another agent; a run without an agentId uses the runtime's default agent. Subagent tool invocations always create a new child thread; invocationId identifies one parent-to-child delegation and is not a reusable routing identity.
To find a thread's subagents, list them from the session store:
var parent = new ThreadKey(sessionId, "main");
var children = await runtime.SessionStore.GetSubAgentsAsync(parent) ?? [];
foreach (var child in children)
{
var activity = await runtime.Executions.GetActivityAsync(child.ChildThread);
Console.WriteLine($"{child.LocalId} {child.ChildAgentId} {child.ChildThread.ThreadId}: {activity.Status}");
}GetSubAgentsAsync returns the subagents the thread's history names, in order of their parent-local id, or null when the parent thread does not exist. Each carries its ChildThread and ChildAgentId. A fork of the parent copies that history, so the fork names the same children created before the fork point.
A subagent's thread is an ordinary thread. Send it a message with any agent, or run the subagent's agent on any other thread:
await runtime.RunAsync(new UserMessagesInputEvent
{
AgentId = child.ChildAgentId, SessionId = child.ChildThread.SessionId, ThreadId = child.ChildThread.ThreadId,
Messages = [new ChatMessage(ChatRole.User, "Check the tests too.")]
});The parent is not notified of direct input; it reads its children with its own tools. The child's Parent tool works on every run of its thread: it reports results to, and asks questions of, the parent thread recorded when the thread was created.
Child Threads
A child thread records one thing about how it was made: the thread that created it. Thread.ParentSessionId and Thread.ParentThreadId, and ThreadDescriptor.Parent, name the parent thread; ThreadDto carries parentSessionId and parentThreadId. A thread with no parent has none.
Everything else about the delegation belongs to the parent, not the child thread: its local id, role, ChildAgentId, invocation, tool call, and context policy are in the parent's registry (GetSubAgentsAsync) and in its SubAgentInvocation* events. The child thread has no kind, no subagent name, and no visibility of its own, and HPD writes nothing into its metadata. Thread metadata belongs to the application.
To show a session's child threads, list its threads and keep those whose parent is the thread you are showing. To label them, join each child's thread id with the parent's registry entries.
Events And Hierarchy
Subagent runs are event-native. The parent journal records SubAgentInvocationStartedEvent followed by SubAgentInvocationCompletedEvent, SubAgentInvocationFailedEvent, or SubAgentInvocationCancelledEvent. These events correlate through invocationId and identify the child agent, session, thread, resolved context policy, and invocation mode. The parent also emits normal tool-call events, while the child owns its normal run and message lifecycle in the child journal.
AddCodingHarnessTui() projects coding subagent tools such as explore, worker, and reviewer into one semantic parent-transcript entry. The entry moves from preparing to running and then to completed, failed, or cancelled as the durable lifecycle events arrive. Prompt, result, and error text is bounded in the parent transcript; use /subagents to open the complete child conversation. Replaying the same parent events reconstructs the same presentation after hydration.
That lets a host render:
- the parent model deciding to call
researcher ToolCallStart,ToolCallArgs,ToolCallEnd, andToolCallResultfor the subagent tool- child text, tool calls, permissions, custom events, and turn events
- the parent model continuing after the child result
The parent runtime state includes answerable requests originating from descendant child threads. Post the response through the active parent coordinator route while preserving the request id and child sessionId and threadId on the response event. To continue a child with the agent that ran it, read ChildAgentId from the parent's registry, or name another agent.
For rendering patterns, see Event Streams And Hierarchies, Workflow Events, and Render An Event Stream.
Handoff Compaction
For Handoff subagents, configure the optional textual handoff compaction on the direct child run:
var childRun = new SubAgentRunConfig
{
Target = SubAgentTarget.All,
HandoffCompaction = new CompactionSpecification
{
Point = new CompactAtCurrentHead(),
Preservation = new PreservePreviousTurns(3),
Strategy = new SummarizingCompaction()
}
};The compaction runs before the child receives the parent text handoff. Set SubAgentRunDefaults.HandoffCompaction when descendants should receive the same policy. The handoff compaction is recorded when the child is admitted, so creating its thread can resume after a crash.
See Compaction.
Security And Permissions
AgentSecurityRunConfig controls approval and host isolation. It does not select a provider account; provider authentication remains under Clients.<Family>.Provider.Authentication.
var security = new AgentSecurityRunConfig
{
Approval = AgentApprovalPolicy.ReviewProtectedActions,
Sandbox = new AgentSandboxRunConfig
{
Mode = AgentSandboxPolicy.Enforced,
Escape = AgentSandboxEscapePolicy.Deny,
Capabilities = new AgentSandboxConfiguration
{
Filesystem =
[
new AgentSandboxPathGrant
{
Path = "src",
Access = AgentSandboxPathAccess.Read
}
],
Network = NetworkEgressPolicy.Blocked
}
}
};The security fields are:
Approval: prompt for protected operations or auto-approve them.Sandbox.Mode: enforce host isolation or disable it.Sandbox.Escape: ask for a narrow capability or deny anything outside the active grants.Sandbox.Capabilities: filesystem, network, and interactive process grants.PermissionOverrides: per-function/action/authority decisions.CapabilityCeiling: trusted runtime-only host authority; it cannot be provided by serialized configuration.
Subagent authority is intersected, not replaced:
- A review requirement in any applicable layer remains required.
- An enforced sandbox remains enforced.
- A
Denyescape policy remains denied. - Filesystem and interactive capabilities can only become narrower.
- A target cannot use an exact override to broaden controller authority.
Subagent tools also require permission by default because they can run another agent, call child tools, and write durable history. Treat prompts as a parent-level decision, while retaining the child’s own tool permission gate.
If you build custom permission middleware, it may approve at the subagent tool, generated input, child tool, or a higher-level signed command boundary. It must not bypass the common function permission gate or expand admitted security.
See Permissions and Bidirectional Events.
Subagents Vs Workflows
Use subagents when:
- the parent model should decide when to delegate
- each specialist is naturally a tool
- the parent should receive a single tool result and continue
- thread policy is more important than graph topology
Use multi-agent workflows when:
- the app should control the graph
- routing, fan-out, review gates, or fixed stages matter
- node outputs need explicit keys
- you want to run the workflow directly from app code or expose the whole graph through
[MultiAgent]
See Multi-Agent Overview and Multi-Agent Capabilities.
Pre-1.0 Contract
There is one current subagent configuration format:
- Inputs use
subAgentRunConfigs; the previous singular broadcast parameter is not retained. - Target values use
All,Agent(...), orDeclared<T>(...); raw capability IDs are not public authoring inputs. - A child's configuration is never stored; only its identity is: agent id, child thread, parent link, and local name.
- There are no legacy readers, compatibility revisions, migrations, or retrofit paths.
A new contract replaces the current one in a pre-1.0 cutover. Existing durable records from an incompatible earlier contract fail explicitly rather than being silently translated.
Boundaries
[SubAgent] is the normal authoring path. The containing harness must use generated registration; harness registration no longer falls back to runtime reflection.
Generated and reflection-created subagent wrappers freeze the same declaration and register the same code-owned definition. Both run the child through the agent's runtime, session store, event coordination, and hierarchical metadata. Treat low-level runtime helpers as implementation details unless you are extending HPD Agent itself.