nested-subagents — скилл для Claude Code: вложенные субагенты до
Строит дерево субагентов, где каждый ребёнок может породить своих детей. Нужен, когда промежуточное состояние не влезает в контекст одного агента.
npx skills add ruvnet/ruflo --skill nested-subagents -a claude-codeЧто делает nested-subagents
Скилл запускает nested-coordinator как верхнего агента, и тот сначала раскладывает дерево задач через TodoWrite, а уже потом зовёт Task. Дети возвращают сжатые сводки примерно на 200 токенов вместо полных расшифровок, поэтому верхний уровень не видит внутреннюю возню. Смысл здесь не в параллельности, а в управлении контекстом: каждому уровню достаётся свежее окно.
Породить следующий уровень может любой агент, у которого в YAML-фронтматтере объявлен Task. Листовые агенты без Task в списке инструментов детей не создают — им subagent_type подставляют прямо под координатора. Хук post-task на каждом запуске пишет parent_agent_id и depth в AgentDB, так что после прогона видно, сколько стоило всё дерево, а не отдельный агент.
Глубина ограничена: у Anthropic API это 5 уровней, а ruflo по умолчанию держит 4 — запас в один уровень, порог настраивается в claude-flow.config.json. Переменная CLAUDE_FLOW_STRICT_NESTING=true включает строгий режим. На пределе хук отдаёт типизированную ошибку NESTING_DEPTH_EXCEEDED со всей цепочкой в теле, и родитель сам решает: сворачивать, передавать дальше или останавливаться. Вложенность добавляет задержку, поэтому если хватает плоского веера из нескольких Task в одном сообщении, дерево только замедлит работу.
Какие задачи решает
- разложить исследование на слои и не забить контекст родителя
- провести рекурсивное расширение сущностей в досье
- раздать листьям разные
subagent_typeсо своими промптами - посчитать расход по всему дереву агентов, а не по одному
- удержать промежуточное состояние, которое не влезает в одно окно
Примеры запросов агенту
- Разбей задачу на дерево субагентов через nested-subagents: исследование, расширение, проверка, сводка
- Запусти
nested-coordinatorдля разбора этого запроса и покажи дерево задач до старта - Проверь глубину вложенности перед запуском: не больше 4 уровней, иначе хук вернёт
NESTING_DEPTH_EXCEEDED
Как установить nested-subagents
1Через Skills CLI (Vercel)
npx skills add ruvnet/ruflo --skill nested-subagents -a claude-code2Вручную: положить файлы
~/.claude/skills/nested-subagents/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/nested-subagents/
1Через Skills CLI (Vercel)
npx skills add ruvnet/ruflo --skill nested-subagents -a codex2Вручную: положить файлы
.agents/skills/nested-subagents/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add ruvnet/ruflo --skill nested-subagents -a cursor2Вручную: положить файлы
.cursor/skills/nested-subagents/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install ruvnet/ruflo nested-subagents2Вручную: положить файлы
.github/skills/nested-subagents/SKILL.md1Через Skills CLI (Vercel)
npx skills add ruvnet/ruflo --skill nested-subagents -a gemini-cli2Командой платформы
gemini skills install https://github.com/ruvnet/ruflo --path plugins/ruflo-agent/skills/nested-subagentsВручную: положить файлы
.devin/skills/nested-subagents/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add ruvnet/ruflo --skill nested-subagents -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Из того же набора146
Похожие
Рядом в теме «Настройка агента: память, контекст, субагенты»
Все скиллы по теме «Настройка агента: память, контекст, субагенты» →Вопросы о nested-subagents
Как установить nested-subagents в Claude?
Выполните npx skills add ruvnet/ruflo --skill nested-subagents -a claude-code. Файл скилла окажется по пути ~/.claude/skills/nested-subagents/SKILL.md.
Что делает nested-subagents?
Запускает дерево субагентов, где каждый ребёнок может породить своих детей. Каждый уровень получает свежий контекст и возвращает наверх сжатую сводку.
На какую глубину можно вкладывать агентов?
Anthropic API допускает 5 уровней, а ruflo по умолчанию ограничивает 4 — запас в один уровень. Порог меняется в claude-flow.config.json, строгий режим включается переменной CLAUDE_FLOW_STRICT_NESTING=true.
Исходный текст
SKILL.md · MIT
---
name: nested-subagents
description: Spawn nested sub-agents (agents that spawn sub-agents, up to depth=5) via Claude Code's native Task tool — for context-managed deep delegation
argument-hint: "<problem-statement>"
allowed-tools: Task TodoWrite Read Grep Glob Bash
---
# Nested Sub-Agents
Spawn a tree of sub-agents where each child can itself spawn children, up to 5 levels deep. The motivation is **context management**, not parallelism: each level gets a fresh context window so deep work doesn't blow the top-level agent's context budget.
## When to use
- The problem decomposes into nested layers (research → expand → verify → synthesize), each of which would otherwise pollute the parent's context.
- A single agent's context window would not be enough to hold all the intermediate state.
- The leaves of the tree are different `subagent_type`s and need their own specialized prompts (e.g., `pii-detector` at one leaf, `tester` at another).
Skip this skill when flat fan-out (`Task` × N in one message) suffices — nesting adds latency.
## Steps
1. **Invoke the coordinator** — spawn `nested-coordinator` as your top-level agent:
```
Task({
subagent_type: "nested-coordinator",
name: "root-coordinator",
description: "Decompose and delegate <problem>",
prompt: "<problem statement, with constraints and expected output shape>"
})
```
2. **The coordinator decomposes first** — it lays out the spawn tree via `TodoWrite` before any `Task` call. Inspect the tree before approving deep work.
3. **Children spawn children** — any `nested-coordinator` (or any other agent whose YAML frontmatter declares `tools: [..., Task]`) can itself call `Task` to spawn the next level. Leaf agents (without `Task` in their tools list) cannot.
4. **Each level reports a summary** — children return ~200-token structured summaries, not full transcripts. The whole point is to keep the parent's context clean.
5. **Tree shape is persisted** — the `post-task` hook writes `parent_agent_id` and `depth` to AgentDB on every spawn (ADR-147 P2). Query after the run for cost attribution and pattern learning.
## Depth budget
| Source | Limit |
|---|---|
| Anthropic API | 5 levels (announced 2026-06-09) |
| Ruflo default (`pre-task` hook) | 4 levels — one-level guard band, configurable in `claude-flow.config.json` |
| Strict-mode env var | `CLAUDE_FLOW_STRICT_NESTING=true` to enforce the ruflo cap |
The hook returns a typed `NESTING_DEPTH_EXCEEDED` error at the cap, with the full chain in the payload so the parent can decide to summarize, hand off, or abort.
## Benefits
- **Context isolation per level** — top-level coordinator never sees inner chatter; leaf summaries climb back up.
- **Deeper delegation without re-summarization** — eliminates the "summarize at level 1 to fit it all" anti-pattern that flat fan-out forces.
- **Tree-shaped cost attribution** — `parent_agent_id` lineage gives accurate per-tree spend, not just flat per-agent.
- **Maps cleanly onto ruflo's existing orchestrators** — `ruflo-sparc:sparc-orchestrator` (5 phases ≈ 5 levels), `ruflo-goals:dossier-investigator` (recursive entity expansion), `v3-queen-coordinator` (hierarchical-mesh top).
## Anti-patterns (do NOT)
- **Pass `Task` to leaf agents.** Leaves must not spawn. Add the leaf's `subagent_type` directly under the coordinator instead.
- **Wrap a Tier-1 codemod in a coordinator.** Codemods (`hooks_codemod`) are depth-0 deterministic transforms — never put them inside a spawn tree.
- **Nest "for cleanliness".** A premature nesting layer wastes latency and cost without saving context. If one agent can do the work, use one agent.
- **Return full transcripts from a child.** That defeats the entire purpose of nesting. Children return structured summaries.
## Related
- **Agent**: `ruflo-agent:nested-coordinator` — the orchestrator
- **ADR-147** — design rationale and four-phase rollout
- **ADR-144** — authorization propagation shares the depth counter as `AuthScope.delegationDepth`
- **ADR-099** — dossier investigator (recursive parallel research) is the textbook deep use case
© ruvnet · MIT · ruvnet/ruflo