[BUG] Sub-agents can't create sub-sub-agents, even with Task tool access
Preflight Checklist
- [x] I have searched existing issues and this hasn't been reported yet
- [x] This is a single bug report (please file separate reports for different bugs)
- [x] I am using the latest version of Claude Code
What's Wrong?
Problem description:
- A custom slash command creates a sub-agent of type A. The definition of sub-agent A gives it access to the
Tasktool. - The sub-agent definition for A tells it to create a sub-sub-agent of type B.
- Sub-sub-agent B does some trivial work, such as writing to a file.
One of two things will happen:
- Sub-agent A incorrectly reports that it lacks access to the
Tasktool. In those cases, if it hasBashaccess, sometimes it will cleverly try to work around this by invoking theclaude --agentcommand via theBashtool. - Sub-agent A sort-of creates sub-sub-agent B, but before sub-agent B can do any useful work, the entire claude code process crashes with an out-of-memory exception.
- (Later addition based on a comment added below): Sub-agent A silently fails and instead directly performs the tasks it would delegate to Sub-agent B.
I mustn't lie; this issue is actually a duplicate of #4182 and #5528, which are both very well-written and thorough. But then a bot closed both of them as duplicates of each other, then locked the issues. Alas, the original reporters, who put so much quality work into creating the issues, apparently didn't take the necessary action to prevent their auto-closure.
Hopefully this issue will stay open and get some attention. I will follow it closely, and I won't allow a bot to auto-close it.
I have also attached a minimal reproduction consisting of just a few very small files.
What Should Happen?
The slash command should create sub-agent A, which should create sub-sub-agent B, which performs the trivial work.
Error Messages/Logs
Steps to Reproduce
- Unzip the attached file.
- Run
claudefrom the resulting directory. - Execute the command `/test-nested-task
File contents:
settings.json:
{
"permissions": {
"allow": [
"Read",
"Write",
"Task"
],
"deny": [],
"ask": []
}
}
.claude/commands/test-nested-task.md:
---
allowed-tools: Task, Write, Read
argument-hint:
---
# Test Nested Task
Minimal test to reproduce sub-sub-agent creation issue.
## Expected Behavior
1. Command creates parent sub-agent
2. Parent creates child sub-sub-agent using Task tool
3. Child writes output to /tmp/child-output.txt
4. Success!
## Actual Behavior
Parent agent reports Task tool is not available, despite:
- Agent definition includes `tools: Write, Task`
- settings.json includes `Task` in allow list
- Command includes `Task` in allowed-tools
## Process
Create a parent sub-agent:
- `subagent_type: "parent"`
- `model: "opus"` (or "sonnet")
- `prompt: "Create a child sub-agent that writes 'Hello from child' to /tmp/child-output.txt"`
The parent should create the child using the Task tool.
## Expected Result
`/tmp/child-output.txt` should contain "Hello from child"
## Actual Result
Parent agent reports: "Error: Task tool not available"
.claude/agents/parent.md
```---
name: parent
description: Parent agent that attempts to create a child sub-agent
model: opus
color: blue
tools: Write, Task
---
You are a parent agent testing whether sub-agents can create their own sub-agents.
Your Task
Create a child sub-agent using the Task tool.
Your prompt will tell you where the child should write its output.
Use the Task tool with these parameters:
Task tool parameters:
subagent_type: "child"
model: "sonnet"
description: "Write test output"
prompt: "Write 'Hello from child' to <output-path-from-your-prompt>"
CRITICAL CONSTRAINTS
DO NOT write the output file yourself.
DO NOT use any workarounds if the Task tool is unavailable.
DO NOT attempt to accomplish the task through any means other than creating a child sub-agent.
Your ONLY job is to create the child sub-agent using the Task tool. If the Task tool is not available, report the error and stop immediately.
Expected Behavior
The Task tool should be available in your tool set, allowing you to create the child sub-agent.
Response
Return one of:
- "Success: Child agent created and completed"
- "Error: Task tool not available"
- Any other error message
Do NOT proceed with any alternative approaches.
.claude/agents/child.md:
---
name: child
description: Child agent created by parent agent
color: green
tools: Write
---
You are a child agent testing sub-sub-agent creation.
Your Task
Your prompt will tell you where to write output. Write "Hello from child" to that file using the Write tool.
Response
Return "Success: Output written" or an error message.
### Claude Model
Not sure / Multiple models
### Is this a regression?
I don't know
### Last Working Version
_No response_
### Claude Code Version
2.1.12 (Claude Code)
### Platform
Anthropic API
### Operating System
Ubuntu/Debian Linux
### Terminal/Shell
IntelliJ IDEA terminal
### Additional Information
_No response_
19 Comments
Found 3 possible duplicate issues:
This issue will be automatically closed as a duplicate in 3 days.
🤖 Generated with Claude Code
This issue isn't a duplicate of any open issue. Two previous issues were closed as duplicates of each other, but the issue they describe remains.
I've definitely mentioned this in issue comments before. Being able to call just one more layer of subagents would improve my workflow a lot, because I could avoid a ton of compaction and do far more before the subagents themselves run out of context.
This seems intentional.
From the docs:
https://code.claude.com/docs/en/sub-agents#choose-between-subagents-and-main-conversation
Sure enough! I'm pretty sure that's a recent addition to the documentation.
That is a huge limitation. The consequence is that agents aren't composable.
The documentation's advice to use Skills isn't very helpful for me. Skills and custom agents are very different things.
We should just be able to define an agent depth. This is a huge limitation
Target Issues:
---
Confirming This Issue + Critical Blocker for Orchestration Frameworks
I'm hitting this exact issue while building a multi-agent orchestration project, and it's a critical blocker that breaks the entire framework.
Setup:
.claude/agents/conductor/agent.mdsettings.jsonwith"agent": "conductor"Task()toolCritical Issue - Custom Agents Lose Task() Even As Main Instance:
❌ Custom agent loaded via
settings.jsondoes NOT have Task() tool, even though it's the main instanceWhat Works:
✅ Default main Claude instance (no
"agent"in settings.json) → Has Task()✅ Default main instance wearing a SKILL → Has Task()
What Doesn't Work:
❌ Custom agent as main (via
settings.json) → No Task() tool❌ Worker subagents → No Task() tool (expected, documented)
Impact: This Blocks All Orchestration Frameworks
Any framework that needs custom agents to orchestrate workers is broken:
settings.jsonConfusing Developer Experience:
Taskto worker agent'sallowed-toolssucceeds without any error or warning that it won't actually workTask():``
`Error: Task tool not available
Task() is only available to the main Claude instance, not spawned sub-agents`Should say:
Why This Is Confusing:
The architectural decision to prevent nested spawning makes sense (prevents infinite recursion, reduces complexity). But the lack of clear communication makes it feel like a bug rather than intentional design.
Suggested Improvements:
Taskis added to custom agent'sallowed-tools:``
``Warning: Task tool in allowed-tools will have no effect.
Task() is only available to the main Claude instance.
Task():``
``Error: Task() tool is only available to the main Claude instance.
Sub-agents cannot spawn nested agents to prevent infinite recursion.
See: https://code.claude.com/docs/en/sub-agents#nesting-limitation
``
``Note: This tool is only available to the main Claude Code instance.
Spawned sub-agents cannot use Task() to prevent nested orchestration.
Workaround (Forced Architecture Regression):
Had to revert from custom agent to skill-based architecture:
Result: Had to abandon custom agent architecture entirely. Main instance must be default Claude, orchestrator must be a SKILL, not an AGENT.
Impact:
CRITICAL BLOCKER for any orchestration framework using custom agents:
This is not just a "nested agent" issue - it's "custom agents as main instance lose Task()" (Issue #13533).
The architectural restriction makes sense (prevent infinite nesting), but custom agents losing Task() even as main instance is a critical limitation that should be:
This limitation forces all orchestration frameworks to use the default main instance + skills, blocking custom agent-based architectures entirely.
---
This is made more confusing by the documentation specifying that:
my subagents can't delegate to explore subagent and need to grep-ing manually, filling up their precious context windows
We ran into this limitation too when trying to build deep agent delegation chains.
Our workaround was to move coordination outside the sub-agent tree entirely. Instead of nesting agents inside agents, we run each agent as an independent session and they coordinate through a shared message bus. Any agent can kick off work for any other agent through the room, regardless of nesting level.
It is a different architecture than the built-in sub-agent model, but it sidesteps the nesting restriction completely. Works across different models too.
https://github.com/ThinkOffApp/ide-agent-kit
Real-world use case: Coordinator → Worker swarm pattern
I'm hitting this limitation in a production workflow that has shipped 40+ features using a coordinator-subagent architecture. The pattern:
The Scrum Master is a lean coordinator agent (~190 lines). It reads a protocol file, spawns specialist workers in the sequence the protocol defines, manages gates, and routes results. It never generates content itself — it only orchestrates.
This worked until recently (likely broken by the v2.1.69 fix for "teammates accidentally spawning nested teammates"). The SM now reports the Agent tool is unavailable.
Why the primary agent can't fill the coordinator role
This isn't just a convenience issue. The primary agent degrades at protocol compliance when it has broad context. We've documented this empirically:
The subagent boundary isn't just delegation — it's context isolation that enforces compliance. A coordinator subagent can't skip steps it doesn't know how to do. A primary agent with full context can and will.
What would fix this
maxDepth: 2— allowing one level of nested spawning — solves the coordinator pattern completely. The hierarchy is:No infinite recursion risk. Workers at depth 2 don't need to spawn further. The coordinator at depth 1 just needs the Agent tool to delegate.
Scale of impact
This pattern has produced: 42 features, ~1,600 tests, 12 MCP tools, full design-through-delivery lifecycle with gates, vision alignment checks, and risk strategies — all orchestrated by a coordinator subagent spawning specialist workers. It's not a toy example; it's the core development workflow for a production system.
The workaround (
claude --agent) loses the human-in-the-loop conversational flow that makes the primary → coordinator → workers hierarchy work. Agent Teams don't solve it either — the lead IS the primary agent, with the same compliance issues.Strong real-world case. The 42-feature run is probably the best evidence anyone has posted for why the coordinator pattern needs native support.
Your observation about context isolation enforcing compliance is important. We hit the same thing: when the primary agent has full context it starts "helping" instead of delegating, and the specialist boundaries collapse.
For anyone hitting this now: we ended up moving coordination outside the sub-agent tree entirely. Independent Claude sessions communicate through a shared message bus (IDE Agent Kit). Each session has its own context and can only see what gets sent to its inbox.
The downside is more infrastructure. maxDepth:2 as a native feature would be cleaner for the coordinator-worker pattern.
Use case: Orchestrator-only pattern for large projects
I run Claude Code in a strict orchestrator-only mode — the main session never writes code directly. It only plans, decomposes, delegates, and summarizes. This keeps the main context clean and ensures consistent attention quality across long sessions.
The bottleneck: Without nested delegation, the main orchestrator becomes a single point of failure for task decomposition. For a large feature touching backend, frontend, and tests:
Specific pain points:
Even allowing just one additional level (depth 2) would be transformative. A configurable
max_agent_depthparameter would be ideal.+1 for this feature — it's the biggest architectural limitation I've hit with Claude Code's agent system.
I'm butting into this limitation. A couple relevant points:
--agentflag. Soclaude --agent projectlaunches the project orchestrator as the main agent, and it can and does spawn sub-agents to get work done.maxDepthmakes architectural sense over "prohibited", even if the default functionally means the same thing -- it lets folks say "I want to try one layer of nesting"So we showed via tool call counts and via introspection that the orchestrating agent simply did the tasks itself because it couldn't launch the sub-agents.
Adding empirical evidence of the silent failure mode @ozydingo described, with a new
angle: the combination with
run_in_background: truemakes detection significantlyharder.
I have a custom skill (
/review-pipeline) that spawns a wrapper agent in background andinstructs it to orchestrate a convergence loop calling
superpowers:code-reviewer→superpowers:receiving-code-review→code-simplifier:code-simplifierper iteration.I inspected the subagent trace files for 9 invocations across 3 different feature
branches over 3 days and found that the wrapper made 0
Agent/Taskcalls in everysingle run, while 8 of those 9 wrappers produced final reports phrased as if a
multi-iteration convergence loop with specialized sub-agents had been exercised as
designed.
Full data + table + JSONL summary:
<https://gist.github.com/Etilem/6365100d3ca55ebfc10987c9542050a4>
What the wrappers said vs what they did
The orchestrator prompt explicitly instructs the wrapper to spawn three named sub-agents
per iteration. Across the 9 runs:
Agent(run_in_background=true)(the orchestrator's outer call).general-purposefor the wrapper (explicit in 2 runs, default in 7).Agent/Tasktool calls (verified by reading~/.claude/projects/.../subagents/agent-*.jsonl).Read/Bash/Edit/Grep/Glob— 40Editoperations total,all performed in-place by the wrapper itself.
Iterations: 2 / 5,Applied: 4 corrections across 1 iteration,Minor applied (final pass): N suggestions)that strongly implies the dispatch happened.
available. I'll need to perform the review work directly within this agent."* That same
wrapper also made 3
ToolSearchcalls trying to locate a dispatch tool — the only onein the set to do so. The other 8 silently adapted with no acknowledgment.
Why background-mode amplifies the problem
In foreground execution you can watch the orchestrator's tool calls stream in real time,
so a missing
Agent(superpowers:code-reviewer, ...)is visible immediately. Withrun_in_background=truethe wrapper operates out of sight until it returns its finalreport. By the time the user reads the report, they have:
The combination is essentially a plausibility engine: the wrapper produces a report that
looks exactly like what the skill promised, while the actual execution followed a
different code path. In my case the gap went unnoticed for days across multiple branches
before I bothered to read the trace files.
What I think would help
Either of these two would resolve it for my use case:
Agent/Tasktool from the orchestrator's tool set whenspawned with
run_in_background=true, allowing actual nested dispatch.prompt and either (a) refuses to spawn the wrapper in background, or (b) downgrades
the wrapper to foreground, or (c) emits a clear warning in the final report saying
"this wrapper had no
Agent/Tasktool, so all dispatch instructions were executedin-place by the wrapper itself".
Even (c) alone would prevent the silent failure — the user would at least know the
architecture collapsed and could adjust.
---
In case it's useful: I'm happy to share the orchestrator session JSONL files and the
wrapper trace files privately if that would help reproduce. The skill itself is a
single-file Markdown skill; the orchestrator prompt to the wrapper is about 200 lines
of plain instructions, no special dependencies beyond the two
superpowersandcode-simplifierplugin agent names referenced in the prompt.Since the issue was created, the
Tasktool was renamed toAgent.I came across this Issue while hunting down a problem with Claude failing to delegate agents in parallel, instead delegating each agent in sequence.
I solved subagent tasking in OpenCode months ago (https://github.com/anomalyco/opencode/pull/7756#issuecomment-4042978112).
Subagents can delegate to subagents to whatever depth you define in config. You can persist subagent sessions. You have a tree based view of subagent sessions, and other features.
The irony is, this feature users want in Claude Code has been available in OpenCode for months, because after I found it wasn't in Claude Code and wouldn't be unless Anthropic decided to add it, I decided to develop it for OpenCode. But OpenCode maintainers haven't yet merged my PR, and probably won't. I've watched PR after PR languish in the OpenCode github, and unresolved issues get automatically closed, despite continuing to be problems that need fixing.
I think harness development is just plain broken due to failures in leadership and organization. It seems like no one is truly on top of things. You want a harness that works for your use cases, it has to be code you can change.
Evidence from a 9-hour autonomous run: compaction tax as the limiting cost
Adding a use case the thread hasn't seen yet: a single 9-hour
/goalsession that ran a 10-phase autonomous workflow end-to-end (PRD → dual-review → plan → review-loop → orchestrated implementation → review-loop → real-data integration testing → ensemble code review → fix-and-verify → final report).The pattern works today. The orchestrator successfully sequenced all 10 phases and produced the intended artifacts. But it hit a specific failure mode that the existing comments touch on individually and that depth-2 would resolve cleanly:
Every phase's intermediate state lives in the orchestrator's Opus context until the end of the run. PRD drafts, dual-review findings, fix-loop iterations, per-stage orchestrate outputs, test runs — all of it accumulates in one context because each phase is a slash command (
/quick-dual-review,/review-fix-loop,/orchestrate,/adamsreview:review,/ar:fix-and-verify) executing inline rather than as a sub-agent. The result is repeated compaction across a 9-hour window, which is both a real $$ cost at Opus rates and a quality cost — post-compaction the orchestrator loses fidelity on early-phase decisions exactly when it needs to integrate them into later phases.Why depth-2 specifically fixes this
The orchestrator's actual job in this pattern is sequencing, not doing. Its context only ever needs to hold ~10 pointers ("phase 3 complete, kicking off phase 4"). With depth-2:
/goal(depth 0) holds phase verdicts only/orchestrate,/review-fix-loop, etc., at depth 1) holds its own working stateToday the entire stack collapses into depth 0, because the phase commands at "depth 1" are really still executing in the orchestrator's context. The compaction tax scales with
session_length × intermediate_output_size. Depth-2 turns that into a flat per-phase cost because intermediate outputs die with the sub-agent that produced them.This complements the existing arguments rather than restating them
Endorsing the converged API
Three independent issues (#58005, #32340, #21982) landed on essentially the same shape: opt-in depth cap, default 0/1 for backwards compat, decremented per spawn, hard-reject at zero.
remaining_depth: 2from #58005 covers the pattern above with no surface-area expansion beyond a single parameter. +1.<details>
<summary>The actual /goal prompt (for reference — this is what ran for 9 hours)</summary>
Note the explicit acknowledgment in the prompt that compaction will happen repeatedly and the orchestrator has to defend against losing state across it. With depth-2, that defensive build-journal scaffolding becomes much less load-bearing — each phase's sub-agent holds its own state, and the orchestrator just reads verdicts.
</details>
Two recent additions to this cluster sharpen the contract framing in ways worth pulling up here:
Task/Agentis stateless-per-invocation,TeamCreate/SendMessageis state-accumulating across calls. The two are not substitutable for fan-out worker patterns where each item must not see sibling state. xblabs's batch-executor halt log shows this concretely — the run halted at the cohort-spawn gate, not because the orchestrator was "trying to recurse," but becauseTeamCreatewould have silently broken the stateless-per-item guarantee the executor was designed around.Together these two suggest a remediation that is more surgical than "expose
Agentto sub-agents": an opt-in frontmatter field (e.g.nested_spawn: enabledwith optionaldepth_limit) that gives the documentation a place to articulate the ephemeral-vs-persistent distinction the current "subagents cannot spawn other subagents" sentence collapses.The cumulative cluster as of today: this issue + #46424 + #59523 + #60763 + #61993, spanning January → May, with the most recent three filed in the last nine days.