# Nested Subagents > Genera subagentes anidados (agentes que lanzan subagentes) hasta 5 niveles vía la herramienta Task nativa, para delegación con gestión de contexto. Fuente: https://skillsagentes.com/skills/ruvnet/ruflo/nested-subagents Markdown: https://skillsagentes.com/skills/ruvnet/ruflo/nested-subagents.md Repositorio: https://github.com/ruvnet/ruflo Autor: ruvnet Licencia: MIT Actualizado: hace 2 meses Coste de contexto: 36 tok instalada, 1k tok al activarse, 1k tok con todos los archivos del bundle Bundle: 1 archivo, 4 KB Permisos que pide: task todowrite read grep glob bash ## Instalación Un skill son archivos markdown: los mismos archivos valen para cualquier agente y lo único que cambia es el directorio de destino, es decir la bandera `--agent`. Añade `-g` para instalarlo en todos los proyectos de la máquina. ```bash # Claude Code npx -y skills add ruvnet/ruflo --skill nested-subagents --agent claude-code # Cursor npx -y skills add ruvnet/ruflo --skill nested-subagents --agent cursor # Codex npx -y skills add ruvnet/ruflo --skill nested-subagents --agent codex # Gemini CLI npx -y skills add ruvnet/ruflo --skill nested-subagents --agent gemini # Windsurf npx -y skills add ruvnet/ruflo --skill nested-subagents --agent windsurf # Cline npx -y skills add ruvnet/ruflo --skill nested-subagents --agent cline ``` ## Qué hace - Genera un árbol de subagentes anidados (agentes que a su vez lanzan subagentes) hasta 5 niveles de profundidad usando la herramienta Task nativa. - Cada nivel obtiene una ventana de contexto limpia, así el trabajo profundo no agota el presupuesto de contexto del agente superior. - El coordinador descompone el problema con TodoWrite antes de lanzar ningún Task, y cada hijo devuelve un resumen de ~200 tokens en vez del transcript completo. ## Cuándo usarla - El problema se descompone en capas anidadas (investigar → ampliar → verificar → sintetizar) que ensuciarían el contexto del padre. - Los nodos hoja necesitan subagent_type distintos con prompts especializados. ## Cuándo no - Cuando basta un fan-out plano (varios Task en un mismo mensaje), porque anidar añade latencia. ## Qué la activa - "Lanza un coordinador anidado para investigar y verificar este problema en profundidad" ## Archivos - SKILL.md — 4 KB ## SKILL.md Reproducido tal cual desde ruvnet/ruflo bajo MIT. Esta sección es el documento original y está en inglés. # 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 ", prompt: "" }) ``` 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 ## Dónde encaja - Categoría: [Automatización](https://skillsagentes.com/categorias/automatizacion.md) — Flujos de varios pasos que se ejecutan sin supervisión. - Creador: [ruvnet](https://skillsagentes.com/creators/ruvnet.md) — 275 skills en el directorio - [Todas las skills](https://skillsagentes.com/skills.md) - [Ranking de instalaciones](https://skillsagentes.com/ranking.md) ## Otras skills del mismo repositorio - [Harness Gepa](https://skillsagentes.com/skills/ruvnet/ruflo/harness-gepa.md): Inspecciona y audita genomas GEPA: carga y valida un genoma, renderiza el system prompt que compila, o clasifica los modos de fallo de una transcripción de ejecución. - [Deepseek Reason](https://skillsagentes.com/skills/ruvnet/ruflo/deepseek-reason.md): Completion en modo razonamiento contra deepseek-reasoner (R1) de DeepSeek. Devuelve el chain-of-thought por separado de la respuesta final. Lee DEEPSEEK_API_KEY y degrada si falta o la API no responde. - [Deepseek Chat](https://skillsagentes.com/skills/ruvnet/ruflo/deepseek-chat.md): Completion de un solo turno contra el modelo deepseek-chat de DeepSeek vía /v1/chat/completions. Lee DEEPSEEK_API_KEY y degrada con status:degraded si falta o la API no responde. Para tareas sin razonamiento. - [Adr Index](https://skillsagentes.com/skills/ruvnet/ruflo/adr-index.md): Construye o reconstruye el índice de ADRs y su grafo de dependencias ejecutando scripts/import.mjs, en vez de cientos de llamadas MCP. - [Agntcy Status](https://skillsagentes.com/skills/ruvnet/ruflo/agntcy-status.md): Muestra el estado de la integración AGNTCY/SLIM/CASA: si los paquetes están instalados, qué transporte está activo y si el enforcement de CASA está habilitado. --- Skills Agentes · [Índice de páginas en markdown](https://skillsagentes.com/sitemap.md) · [Inicio](https://skillsagentes.com/index.md)