Configure subagent invocation, context passing, and spawning
Learning objectives
By the end of this topic, you should be able to:
- Diagnose the difference between a defined worker, an available spawning tool and an authorized invocation.
- Build an explicit context handoff that preserves findings and attribution.
- Select a fresh worker or a fork according to the context needed.
- Dispatch independent work together while keeping dependent work ordered.
Make the spawning mechanism available
A worker definition alone does not allow a coordinator to invoke it. The execution environment must expose the appropriate spawning capability, and its permission policy must allow the requested invocation.
The spawning capability may be named Task or Agent in different interface versions. Treat the name as part of a versioned interface. In a Task-based configuration, the coordinator needs the corresponding capability in its allowed tools. An Agent-based release needs its supported equivalent. Do not assume that renaming a tool in a prompt changes the installed runtime, or that an allowlist is the only permission mechanism in every release.
When delegation fails, inspect the actual tool registry, permission decision, worker name and active definition. Then inspect whether the description explains when that worker should be selected. Naming a worker makes intent clearer, but natural-language naming cannot override a denial or guarantee execution. Confirm the actual invocation event.
Caller-managed subagents return bounded findings to their caller, which owns assignments and final synthesis. In contrast, the source's agent teams use independent sessions with direct peer communication. These are different topology/ownership contracts, not capabilities automatically granted by the word “agent.” Standard fresh-worker histories and explicit fork baselines still differ, and any peer messages require actual permission. A concise final return can reduce copied parent context, but total resources still include worker computation, retained histories, coordination, retries and synthesis; the source's lower-cost comparison is not a universal measured guarantee. Neither central routing nor independent peers alone establishes security or correct completion.
Separate definition fields by responsibility
A reusable definition should distinguish these concerns:
| Concern | What it controls |
|---|---|
| Name and description | Worker identity and the situations in which delegation is appropriate. |
| Worker prompt | Specialist purpose, evidence handling, constraints and output expectations. |
| Tool restrictions and permission policy | Operations the worker can request and operations the harness can authorize. |
| Model and resource settings | The configured release, consumption bounds and execution limits. |
The supplied material describes filesystem definitions under .claude/agents/ and definitions supplied programmatically. Use the schema for the selected surface; a conceptual JSON example is not automatically a valid configuration file. Check which definition wins if the same worker name exists in more than one scope. Inspect the effective definition rather than editing an ignored copy.
Main-agent and nested-agent restrictions may behave differently in a particular release. Do not infer a nested allowlist or a fixed recursion depth from an example intended for the main session. Verify the active limit and failure behavior before designing a worker that must spawn descendants. A limit should produce an explicit blocked or failed task, not a fictitious successful result.
Supply the context a fresh worker needs
A fresh worker should receive a complete task packet: objective, relevant state, approved decisions, source paths or excerpts, constraints, required output and unresolved questions. Do not write "continue the analysis above" when the worker cannot see that analysis.
For a synthesis worker, include the actual findings from earlier workers or references it is authorized and able to read. A statement that "research was completed" does not transfer the research. Keep evidence excerpts and qualifications with their claims. Exclude irrelevant conversation history and unnecessary sensitive material.
Some harnesses can load skills, project context or other resources at worker startup. That is a configured loading behavior, not proof that arbitrary prior findings were passed. Inspect the supported mechanism and confirm the needed content is available. Do not promote untrusted search results into high-priority instructions merely to make them visible.
Preserve attribution in the handoff
A structured record keeps content separate from metadata without separating a claim from its support. The following invented record is an application handoff format, not an Agent SDK configuration schema:
{
"content": "The example deployment requires approval before release.",
"document_name": "release-policy-v2",
"location": "section 3",
"methodological_context": "Applies to the example production environment; staging was not assessed.",
"verification_status": "compared with supplied section"
}
A synthesis worker should retain the production-environment restriction. It must not turn the record into "all deployments everywhere require this approval." If the document cannot be opened or its version is uncertain, keep that limitation visible. Valid JSON does not prove that the policy exists or that the claimed comparison happened; those need evidence in the actual workflow.
Use forks for a shared baseline deliberately
A fork starts from a snapshot of an existing session. It can be useful when two approaches need the same previously checked analysis. A fresh worker is preferable when the task needs only a focused evidence packet or an independent examination without inherited conclusions.
A context fork is not a filesystem worktree. Two branches may still edit the same files unless the environment provides separate checkouts or another isolation mechanism. State which files each branch may modify and how results will be reconciled. Do not assume that a conversational rewind can undo every change performed by a background process.
Before relying on fork, resume or background behavior, check the installed interface and permission policy. The source contains several release-specific names and commands; their presence in course material does not establish that an arbitrary installation supports them. Preserve the shared baseline version so later comparisons do not accidentally use different starting states.
Dispatch independent work in one scheduling step
If the harness supports parallel spawning, submit independent worker requests together rather than waiting for one response before even requesting the next. A coordinator response can contain several tool calls; the execution layer must actually schedule them concurrently for a latency benefit.
Independence is a dependency property. Reviewing formatting and inspecting dependency metadata can be independent read-only tasks. Synthesizing their findings requires the findings first. Two workers modifying the same file require ownership or isolation, not merely parallel tool calls.
Track each invocation and return separately, including a timeout or denied operation. Aggregate only after resolving the needed dependencies. Concurrent execution can reduce waiting, but dispatch overhead, resource contention and final synthesis still contribute to total elapsed time.
Specify goals and quality criteria without over-scripting
A useful worker prompt defines the result and boundaries while allowing investigation to respond to evidence. "Inspect these two modules for missing authorization checks; cite exact locations, distinguish confirmed defects from hypotheses, and do not edit files" is more adaptable than a rigid list of searches that assumes where the defect must be.
Adaptability does not remove prerequisites. Required permissions, approved source versions and prohibited actions remain explicit. Set a stopping point for an unresolved dependency and define how to report it. The coordinator should assess the returned evidence rather than equating fluent prose with a successful invocation.
Worked example: two reviews followed by synthesis
In this teaching workflow, a coordinator has an approved read-only review task for commit R7. It prepares two packets:
| Worker | Required context and scope | Required return |
|---|---|---|
| Convention reviewer | Commit R7, changed-file list and the approved style guide; no edits. | Supported convention findings with file locations, plus unreviewed files. |
| Dependency reviewer | Commit R7, dependency manifest and approved dependency rules; no network or file modifications. | Supported dependency findings, applicable rule and unresolved version questions. |
The coordinator submits both independent requests in the same scheduling step. If the dependency worker lacks a necessary source, its return is blocked for that question; the coordinator does not invent a clean dependency result.
Only afterward does the synthesis worker receive both actual returns, their source metadata and the original review criteria. A supported synthesis might say: "The changed files were reviewed against the supplied convention guide. The dependency review remains incomplete because the approved version record is missing." It must not report the whole review as passed.
This example specifies checkable packets and an honest result. It does not claim that a particular SDK, permission callback or live worker was executed.
Resolve permission and definition details in the supported interface
The supplied local snapshots use both Task and Agent. Their opening claim that a missing Task entry always prevents delegation is qualified by their later SDK discussion: allowedTools can preapprove Agent or the supported legacy equivalent; otherwise a proposed call may reach canUseTool, while dontAsk can reject a call requiring approval. Tool availability, preapproval and the actual permission decision are separate. Inspect the effective registry and decision before reporting a worker as dispatched.
The source describes versions before v2.1.63 as using Task, and a newer interface as using Agent/AgentInput with legacy aliases. It also names ToolInputSchemas, SDKSystemMessage, TaskCreate, TaskCompleted, PreToolUse and PostToolUse. These are supplied interface claims whose exact exported types, payload fields and event support have not been independently checked here. Task-management types such as TaskCreateInput, TaskGetInput, TaskListInput and TaskOutputInput are not themselves proof of a spawning operation. A received initialization message is not an instruction to mutate an SDK's exposed tool list.
For a real migration, identify the installed contract first; adapt only its supported request/tool names, hook inputs and permission fields; then verify the observed worker and request/result correlation. The source's v2.1.212-or-later claim that a payload mode is ignored is not permission expansion. Its claimed inherited parent mode, a supported custom-definition permissionMode, and any enforced permissions.disableBypassPermissionsMode must be interpreted under the real parent and global policy. Renaming a field or removing mode does not grant access.
Likewise, the illustrated prompt, subagent_type and model schema is not a universal installed contract. A meaningful task still needs objective, relevant evidence, constraints and required output. The source's fast-to-Claude-3.5-Haiku alias, omitted-model inheritance and interactive availableModels discussion remain unverified deployment examples. Resolve aliases and defaults through the actual supported account/session/organization contract. A programmatic model parameter never supplies authority to bypass model-access restrictions.
The source says that a programmatic definition takes precedence over a filesystem definition with the same name in its described interface. If a .claude/agents/ edit appears ignored, inspect both definitions and the actual resolved worker before diagnosing a permission problem. Verify this resolution rule for the deployed surface; it is not a universal rule across clients.
The following comparison preserves the supplied main-thread versus nested-worker snapshot. It is distinct from SDK preapproval and remains subject to real permissions and depth:
| Source-described tool policy | Intended scope and effect |
|---|---|
Agent(worker) and Agent(researcher) |
A type allowlist for the described main thread started with claude --agent; an unlisted type is rejected. |
Plain Agent |
Makes the spawning capability available without that type filter; other policy and depth controls still apply. |
Omitted Agent |
Removes that spawning capability in the described tools configuration. |
permissions.deny for a selected type |
A targeted deny when the intention is to block that type while otherwise permitting supported work. |
| Parenthesized types in a nested worker | The snapshot says these type filters are ignored there. This does not remove actual tool availability, depth or effective permission restrictions. |
The detailed source depth rule counts three layers below the main conversation by default and names CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH as an override. These are version-scoped claims, not a verified current universal limit. At the described boundary an ordinary worker has Agent withheld; a fork can retain the inherited tool, but its attempted further spawn returns an error. Neither condition produces another successful child. The source's shorter exam-tip wording must not collapse withheld capability and a retained-but-failing tool into an identical event, or present a fork as a bypass. Keep the task and its remaining work explicit after the boundary is reached.
Distinguish a configured role from a complete spawn lifecycle
The source's conceptual filesystem YAML and programmatic object use fields such as permissions, tool_access, context_window, model_routing, load_claude_md and load_git_status. They express design intentions rather than an independently verified accepted file/SDK schema. Indentation must be reconstructed if such YAML is displayed. Implement name/description, focused prompt, actual model choice and effective tools through a supported definition mechanism; prompt text does not enforce permissions. MCP means Model Context Protocol and can integrate external tools, but a named registry endpoint or tool string does not prove installation, access or a valid worker definition.
The snapshot also says built-in Explore/Plan skip CLAUDE.md and parent git status while custom workers load them. Keep this worker-type/release claim separate from full conversational inheritance and verify actual startup behavior. CLAUDE.md is a persistent project-instruction file, not the model named Claude. A file definition, loaded instruction file and executed worker are different facts.
A predefined workflow follows code-controlled paths; an adaptive agent chooses task-relevant next actions within its real tools and authority. The source's Task budgets beta, Fast mode research preview, Managed Agents, Admin API and Claude API skill mentions remain optional, source-scoped integration claims. They do not establish a required working stack, infinite context or guaranteed reliability. Actual authentication, accepted request, permitted execution, supported stop/error handling, observed output and aggregation remain necessary.
A complete application lifecycle can be specified without claiming that the source's undefined executeBackgroundAgent helper implements it:
accept an actual supported delegation request and retain its request ID
validate task meaning, effective worker definition, permission and resources
if denied or unavailable: retain that specific non-dispatch outcome
otherwise start the implemented worker and record its real worker identity
monitor supported completion, failure, cancellation and interruption outcomes
record the actual result or explicit error under the initiating request ID
return the matched outcome to the coordinator through its supported interface
inspect the continuation and its acceptance evidence before final synthesis
For example, this invented application exchange preserves a failed startup rather than reporting a completed review. It illustrates correlation, not a universally valid SDK event schema or a live invocation:
{"request":{"request_id":"delegate-review-27","worker":"convention-reviewer","task":"Review commit R7 against the supplied style guide; do not edit files."},"outcome":{"request_id":"delegate-review-27","worker_id":null,"status":"blocked","stage":"input-resolution","error":"Required skill review-findings has no accessible SKILL.md.","findings":null},"coordinator_next":"Keep the convention review unresolved; repair the authorized input and retry only when the supported launch prerequisites are satisfied."}
Preserve observability without confusing it with authorization
The local source describes parent_tool_use_id and a coordinator tool_decision correlation, plus claude_code.tool, gen_ai.tool.call.id, parent_agent_id, result_tokens and a workflow.run_id with a wf_ prefix. It names OTEL_LOG_TOOL_DETAILS=1 for detail and OTEL_LOG_TOOL_CONTENT=1 for a tool.output content event, with a stated 60 KB per-attribute truncation limit. These exact options, names, units and payload relationships remain source-snapshot claims requiring actual implementation support. A migration must inspect its real supported hook/trace fields rather than infer compatibility from similar names.
Keep the real request, worker and parent identities linked. A truncated log is incomplete evidence of bodies, and an absent field may require interface/configuration diagnosis. Correlation proves neither permission nor the truth of a result. Log only material permitted by the actual data/access policy; enabling content telemetry is not authorization to disclose source data. This lesson neither enables telemetry nor verifies the source's exact logging contract.
Use the actual fork surface and baseline
A supported conversation fork captures the parent history and the actual prompt, tools and model baseline at its creation point. Its later intermediate calls stay outside the parent transcript and its final result returns through the supported caller path. Copying a baseline is different from loading project instructions, continuously merging later work or starting fresh. Prompt-cache reuse additionally depends on the actual matching/eligibility rules; a fork does not guarantee a cache hit, lower total cost or new authority.
The supplied snapshot names /subtask as a manual fork command and /fork for v2.1.161 through v2.1.211. It describes autonomous fork selection as enabled by default in the source interactive snapshot, subject to actual version/rollout support. It names CLAUDE_CODE_FORK_SUBAGENT=1 and =0 for enabling/disabling autonomous fork selection, while describing the supported manual command independently of that autonomous mode. Check exact deployed command/version/default support rather than run these names merely because they appear here. The source's OAuth2 refactor command is an unexecuted example, not permission to change an authentication module.
Forked skills are another surface. The source context: fork description combines the configured agent prompt and SKILL.md content with inherited conversation. The skill file's frontmatter/body does not by itself prove that inheritance or content loading happened. The source distinguishes foreground fork permission prompts from background non-fork routing and says a skill needing tools outside the background-safe set may need supported background: false. That setting supplies no new tool authority, and a general fork exception does not automatically expand a skill's tools.
For the source's background forked-skill case, edits can sit outside session checkpoints, so /rewind may not undo them. Inspect the actual edited files and supported recovery; use version-control recovery only for the intended authorized changes, preserving unrelated work and recognizing that external effects may need separate handling. A context fork remains distinct from a Git worktree, which can isolate filesystem checkouts.
The source also qualifies automatic named-agent-list injection to supported non-fork startup with the relevant SendMessage capability and v2.1.206-or-later behavior; forks inherit context differently and do not receive that same injection. Visibility of names is discovery, not permission to message peers. Missing metadata calls for actual version/mode/capability diagnosis.
Deliver previous findings as evidence through a working input path
The prior findings needed for synthesis must actually arrive with their provenance and quality-critical limitations. The source contrasts ordinary tool schema/description exposure with full skill-Markdown preloading through a supported skills array. Its example references web-search-findings and doc-analysis-findings, with model: claude-opus-5, permissionMode: auto, maxTurns: 15 and effort: high in that illustrative definition. Actual skill directory/SKILL.md resolution, accepted fields, scope and loaded content need verification; model names or settings printed in the example do not establish support. Turning retrieved material into a skill file does not give it new instruction authority.
Another source-only route uses noninteractive -p with --append-subagent-system-prompt to append findings to nested worker prompts. Its described reach is every nested subagent in that execution, rather than just one selected synthesis worker. Verify actual flag/mode support, payload size, safe argument handling and intended recipients. Avoid promoting untrusted findings to operating instructions or passing unrelated secrets through a broadly applied prompt. This lesson does not execute the displayed shell route or establish that any worker loaded it.
The source's SubagentStart input names hook_event_name, agent_id and agent_type. A supported start hook can be a setup integration point, but a TypedDict or notification does not implement injection. A cache fetch, file write and model ingestion are separate facts. The real handler must make the intended relevant data available through the actual worker input mechanism before processing, and the workflow must check delivery/read evidence before claiming the finding was supplied.
These static teaching cases show the distinctions under an illustrative application contract. They are expected outcomes, not measured SDK runs:
| Setup observation | Expected honest result |
|---|---|
| Start hook fired; no delivery path implemented | Spawn observation only; prior findings have not been established as supplied. |
| Handler wrote a cache file; no supported read/load occurred | File-write evidence only; keep worker ingestion unconfirmed. |
Required skill name does not resolve to an accessible SKILL.md |
Explicit input-resolution failure; no invented analysis. The source's later API termination/StopFailure claim is interface-specific even if the start hook already fired. |
| Correct versioned findings are supplied through the supported input path and their required context is available | The worker can proceed to the authorized task; actual useful output still requires its own validation. |
Manage capacity and acceptance together
For long data-rich tasks, the source recommends longform findings before the specific synthesis query. Evaluate that ordering for the actual task/model; its 20,000-token wording is not a universal hard threshold or mandatory order for every input. The claimed 1,000,000-token Claude Opus 5 default, model identity and PreCompact/PostCompact hooks are likewise source-only details until actual support is established. Monitor the real input/output/aggregate capacity contract and preserve needed facts, decisions, source identities, limitations and unfinished work through accessible artifacts or summaries before compaction or replacement. Confirm what the next worker actually receives.
The source's suggestion to remove verification instructions because a newer named model self-verifies is not a general acceptance rule. Reduce only redundancy supported by actual observed behavior, while retaining required task, safety and quality checks. A fluent summary or a model's statement that it checked itself is not external verification. Inspectable plans, decisions and results suffice; private intermediate reasoning is not required.
A summary length of 1,000–2,000 tokens, the analyst's under-2,000 criterion, or the illustrative 1,500-token description is a source/example output target rather than proof of completeness. The source's 3–5 workers, 3+ parallel tools and up-to-90% research-time example is scenario guidance, not a universal setting or a measurement here. Slowest-worker timing applies to an ideal concurrent independent worker phase. Real end-to-end elapsed includes dispatch, scheduling, waiting, contention, synthesis and retries; total cost includes workers as well as coordinator work and is distinct from active human time.
Before a fresh continuation, save a versioned artifact with the essential findings, decisions, source locations, limitations and unresolved work, return a usable authorized reference, and supply an explicit next task. Open the intended relevant details before relying on them. This mitigates telephone-effect loss; a path or proposed memory mechanism alone neither preserves every fact nor restores an absent one.
If an artifact is inaccessible during a cross-worker continuation, stop the dependent step and retain its locator with the non-secret workspace/project and account identity needed to select the correct authorized context. Include a credential identity or an approved secret reference only when relevant. Keep the intended receiving worker and actual access failure identifiable, but never copy API keys, tokens, passwords or other secret values into prompts, logs or handoffs. Knowing a path, account name or secret reference does not grant permission to read or use it. Resolve access through the authorized mechanism, or return the specific blocked state instead of silently switching accounts or broadening access.
Retain both sides of an attributed conflict
The original structured record keeps content, document identity, location and methodological context together. A citation check needs actual examination of the document/report and its available exact location; naming a CitationAgent does not prove that check happened. If records conflict, preserve both before resolution. For example, these invented inputs disagree about the same example environment and reporting period:
{"records":[{"content":"Release approval is required.","document_name":"release-policy-v2","location":"section 3","methodological_context":"Example production environment, period R7."},{"content":"Release approval is not required.","document_name":"release-exception-R7","location":"paragraph 2","methodological_context":"Same example production environment and period R7; authority/version not yet checked."}],"status":"unresolved-conflict","next_action":"Inspect both authorized originals, their effective versions and exception authority before choosing a conclusion."}
The correct static synthesis exposes the unresolved disagreement with both identities and locations. It does not silently overwrite the policy, invent exception authority or treat syntactically valid JSON as proof that either document exists. External artifact references can carry large records, provided their actual relevant content remains available and attributed. All examples and exact product/version/interface claims here are based on supplied local material; original cited attachments, current external behavior and live worker/API/website execution have not been verified.
Summary
Reliable spawning depends on a supported tool, an effective definition and actual permission. Fresh contexts need explicit evidence packets; forks preserve a baseline but do not automatically isolate files. Preserve provenance, dispatch only independent work together, and verify worker returns before treating the overall task as complete.
