Cap 3: Sub-Agents

Por: Artiko
claude-codesub-agentsagentsagent-tool

Qué son los Sub-Agents

Los subagents son asistentes especializados que manejan tipos específicos de tareas. Usá uno cuando una tarea secundaria inundaría tu conversación principal con resultados de búsqueda, logs, o archivos que no vas a referenciar de nuevo: el subagente hace ese trabajo en su propio contexto y devuelve solo el resumen.

Cada subagente corre en su propia ventana de contexto, con system prompt custom, acceso a tools específico y permisos independientes.

Los subagents te ayudan a:

Versión 2.1.63: el Task tool fue renombrado a Agent. Las referencias Task(...) aún funcionan como alias.

Subagents built-in

AgenteModeloToolsPropósito
ExploreHaikuRead-onlyFile discovery, code search, exploración rápida
PlanInheritRead-onlyResearch durante plan mode
general-purposeInheritTodosTareas complejas multi-paso con exploración + acción
statusline-setupSonnetCuando corrés /statusline
claude-code-guideHaikuPreguntas sobre features de Claude Code

Al invocar Explore, Claude especifica un nivel de thoroughness: quick, medium o very thorough.

Quickstart: crear con /agents

/agents abre una interfaz tabbed:

Flujo: tab Library → Create new agent → elegí Personal/Project → Generate with Claude describiendo el agente → seleccionar tools, modelo, color, memoria → guardar (s o Enter).

Los subagents creados via /agents están disponibles inmediatamente sin reiniciar.

Scopes de subagents

UbicaciónScopePrioridad
Managed settingsOrganización1 (más alta)
--agents CLI flagSesión actual2
.claude/agents/Proyecto3
~/.claude/agents/Usuario4
Plugin agents/Donde el plugin esté habilitado5 (más baja)

Cuando hay nombres duplicados, gana el de mayor prioridad. La identidad viene SOLO del campo name del frontmatter, no del path. Mantené name únicos en todo el árbol.

Claude Code escanea .claude/agents/ y ~/.claude/agents/ recursivamente. Los plugin agents en subcarpetas reciben identificador scoped: my-plugin:review:security.

Los --add-dir no cargan subagents (a diferencia de skills).

Subagents via CLI flag

claude --agents '{
  "code-reviewer": {
    "description": "Expert code reviewer. Use proactively after code changes.",
    "prompt": "You are a senior code reviewer. Focus on quality, security, and best practices.",
    "tools": ["Read", "Grep", "Glob", "Bash"],
    "model": "sonnet"
  },
  "debugger": {
    "description": "Debugging specialist for errors and test failures.",
    "prompt": "You are an expert debugger. Analyze errors, identify root causes, and provide fixes."
  }
}'

Crear un sub-agent manualmente

---
name: code-reviewer
description: Reviews code for quality and best practices
tools: Read, Glob, Grep
model: sonnet
---

You are a code reviewer. When invoked, analyze the code and provide
specific, actionable feedback on quality, security, and best practices.

El cuerpo se vuelve el system prompt. Los subagents reciben SOLO ese system prompt (más detalles básicos del entorno como CWD), no el system prompt completo de Claude Code.

Si editás el archivo directamente en disco, reiniciá la sesión. Los creados via /agents toman efecto inmediato.

Frontmatter completo

Solo name y description son requeridos.

CampoDescripción
nameIdentificador único en minúsculas con guiones. Los hooks lo reciben como agent_type
descriptionCuándo debe Claude delegar a este subagent
toolsTools permitidos. Hereda todos si se omite. Para precargar Skills usá skills, no Skill aquí
disallowedToolsTools denegados, removidos de la lista heredada o especificada
modelsonnet, opus, haiku, full model ID (ej claude-opus-4-7), o inherit. Default inherit
permissionModedefault, acceptEdits, auto, dontAsk, bypassPermissions, plan
maxTurnsMáximo de turnos agentic
skillsSkills a precargar (contenido completo inyectado al startup)
mcpServersServidores MCP scoped al subagent (inline o por referencia)
hooksHooks lifecycle scoped al subagent
memoryuser, project, o local. Memoria persistente entre conversaciones
backgroundtrue para correr siempre en background
effortlow, medium, high, xhigh, max
isolationworktree para correr en git worktree temporal
colorred, blue, green, yellow, purple, orange, pink, cyan
initialPromptAuto-submitted como primer turno cuando corre como main session via --agent

Plugin subagents NO soportan hooks, mcpServers ni permissionMode (por seguridad).

Selección de modelo

Orden de resolución del modelo:

  1. CLAUDE_CODE_SUBAGENT_MODEL env var
  2. Parámetro model per-invocación
  3. Frontmatter model
  4. Modelo de la conversación principal

Tools disponibles

Por defecto los subagents heredan todos los tools, incluyendo MCP tools.

Allowlist con tools

---
name: safe-researcher
description: Research agent with restricted capabilities
tools: Read, Grep, Glob, Bash
---

Denylist con disallowedTools

---
name: no-writes
description: Inherits every tool except file writes
disallowedTools: Write, Edit
---

Si ambos están seteados, disallowedTools se aplica primero.

Restringir qué subagents pueden spawnearse

Cuando un agente corre como main thread con claude --agent, puede spawnear subagents usando el Agent tool. Sintaxis Agent(agent_type):

tools: Agent(worker, researcher), Read, Bash

Solo worker y researcher pueden spawnearse. Agent sin paréntesis = sin restricciones. Omitir Agent completamente = no puede spawnear ningún subagent.

Permission modes

ModoComportamiento
defaultChequeo estándar con prompts
acceptEditsAuto-acepta edits y comandos comunes en working directory
autoClassifier de background revisa cada comando
dontAskAuto-deny prompts (tools explícitamente allowed siguen funcionando)
bypassPermissionsSkip todos los prompts
planPlan mode (read-only)

Si el padre usa bypassPermissions o acceptEdits, eso tiene precedencia. Si el padre usa auto, el subagente hereda auto y su frontmatter es ignorado.

Preload skills en subagents

skills inyecta contenido completo de skills al startup del subagent. Es lo inverso a context: fork en un skill.

---
name: api-developer
description: Implement API endpoints following team conventions
skills:
  - api-conventions
  - error-handling-patterns
---

Implement API endpoints. Follow the conventions and patterns from the preloaded skills.
ApproachSystem promptTaskTambién carga
Skill con context: forkDel agent typeSKILL.md contentCLAUDE.md
Subagent con skills fieldCuerpo del subagentMensaje de delegación de ClaudeSkills precargados + CLAUDE.md

No podés precargar skills con disable-model-invocation: true. Para impedir invocación de skills, omití Skill de tools o agregalo a disallowedTools.

Memoria persistente

memory da al subagent un directorio que sobrevive entre conversaciones.

ScopeLocationCuándo usar
user~/.claude/agent-memory/<name>/Conocimiento aplica a todos los proyectos
project.claude/agent-memory/<name>/Conocimiento específico del proyecto, shareable via VCS
local.claude/agent-memory-local/<name>/Específico del proyecto, NO checked-in

Cuando memory está enabled:

---
name: code-reviewer
description: Reviews code for quality and best practices
memory: user
---

You are a code reviewer. As you review code, update your agent memory with
patterns, conventions, and recurring issues you discover.

Tip: pedile al subagent que consulte su memoria antes de empezar y que la actualice al terminar.

Hooks en frontmatter

Hooks scoped al subagent que solo corren mientras el subagent está activo.

---
name: code-reviewer
description: Review code changes with automatic linting
hooks:
  PreToolUse:
    - matcher: "Bash"
      hooks:
        - type: command
          command: "./scripts/validate-command.sh"
  PostToolUse:
    - matcher: "Edit|Write"
      hooks:
        - type: command
          command: "./scripts/run-linter.sh"
---

Eventos comunes:

EventoCuándo dispara
PreToolUseAntes de que el subagent use un tool
PostToolUseDespués de usar un tool
StopCuando el subagent termina (convertido a SubagentStop en runtime)

Hooks del proyecto para eventos de subagent

En settings.json:

EventoCuándo dispara
SubagentStartCuando un subagent empieza
SubagentStopCuando un subagent completa
{
  "hooks": {
    "SubagentStart": [
      { "matcher": "db-agent", "hooks": [{ "type": "command", "command": "./scripts/setup-db.sh" }] }
    ],
    "SubagentStop": [
      { "hooks": [{ "type": "command", "command": "./scripts/cleanup-db.sh" }] }
    ]
  }
}

Scope MCP servers a un subagent

---
name: browser-tester
description: Tests features in a real browser using Playwright
mcpServers:
  # Inline: solo para este subagent
  - playwright:
      type: stdio
      command: npx
      args: ["-y", "@playwright/mcp@latest"]
  # Por referencia: reusa servidor configurado
  - github
---

Los inline se conectan al inicio del subagent y desconectan al terminar. Útil para mantener un MCP server fuera de la conversación principal (sus tool descriptions consumen contexto).

Invocación

Delegación automática

Claude delega basándose en la description. Incluí frases como “use proactively” para fomentar delegación proactiva.

Lenguaje natural

Use the test-runner subagent to fix failing tests
Have the code-reviewer subagent look at my recent changes

@-mention

Garantiza que ese subagent corra. Tipeá @ y elegí del typeahead:

@"code-reviewer (agent)" look at the auth changes

Manual: @agent-<name> para locales, @agent-<plugin>:<agent> para plugin.

Sesión completa como subagent

claude --agent code-reviewer

El system prompt del subagent reemplaza el default. Para plugins: claude --agent <plugin>:<agent>. Para hacerlo default del proyecto:

// .claude/settings.json
{ "agent": "code-reviewer" }

Foreground vs background

Claude decide automáticamente. También podés:

Para deshabilitar background: CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1.

Deshabilitar subagents específicos

{
  "permissions": {
    "deny": ["Agent(Explore)", "Agent(my-custom-agent)"]
  }
}

O via CLI: claude --disallowedTools "Agent(Explore)".

Resume y compactación de subagents

Cada invocación crea una instancia nueva. Para continuar el trabajo previo, pedile a Claude que resume:

Use the code-reviewer subagent to review the authentication module
[Agent completes]

Continue that code review and now analyze the authorization logic
[Claude resume el subagent con full context]

Resume requiere CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1.

Los transcripts persisten en ~/.claude/projects/{project}/{sessionId}/subagents/agent-{agentId}.jsonl. La compactación del main no afecta los transcripts de subagents.

Auto-compaction en subagents trigger a ~95%. Override con CLAUDE_AUTOCOMPACT_PCT_OVERRIDE.

Forked subagents (experimental)

Requiere CLAUDE_CODE_FORK_SUBAGENT=1, Claude Code 2.1.117+.

Un fork es un subagent que hereda toda la conversación en lugar de empezar fresh. Ve el mismo system prompt, tools, modelo e historial. Sus tool calls se mantienen fuera de tu conversación; solo el resultado final vuelve.

Cuándo fork mode está activo:

/fork draft unit tests for the parser changes so far

Panel debajo del prompt con keybindings: ↑↓ mover, Enter abrir transcript, x cerrar/detener, Esc volver al prompt.

ForkNamed subagent
ContextoHistorial completoFresh con prompt pasado
System promptIgual al mainDel definition file
ModeloIgual al mainDel campo model
Prompt cacheCompartido con mainCache separado

Patrones comunes

Aislar operaciones de alto volumen

Use a subagent to run the test suite and report only the failing tests with their error messages

Research en paralelo

Research the authentication, database, and API modules in parallel using separate subagents

Encadenar subagents

Use the code-reviewer subagent to find performance issues, then use the optimizer subagent to fix them

Los subagents NO pueden spawnear otros subagents. Para delegación anidada, usá Skills o encadenalos desde la main conversation.

Cuándo usar subagents vs main conversation

Usá main cuando:

Usá subagents cuando:

Para preguntas rápidas sobre algo ya en tu conversación, usá /btw en vez de un subagent.

Ejemplo: Code Reviewer

---
name: code-reviewer
description: Expert code review specialist. Proactively reviews code for quality, security, and maintainability. Use immediately after writing or modifying code.
tools: Read, Grep, Glob, Bash
model: inherit
---

You are a senior code reviewer ensuring high standards of code quality and security.

When invoked:
1. Run git diff to see recent changes
2. Focus on modified files
3. Begin review immediately

Review checklist:
- Code is clear and readable
- Functions and variables are well-named
- No duplicated code
- Proper error handling
- No exposed secrets or API keys
- Input validation implemented
- Good test coverage
- Performance considerations addressed

Provide feedback organized by priority:
- Critical issues (must fix)
- Warnings (should fix)
- Suggestions (consider improving)

Include specific examples of how to fix issues.

Ejemplo: Debugger

---
name: debugger
description: Debugging specialist for errors, test failures, and unexpected behavior. Use proactively when encountering any issues.
tools: Read, Edit, Bash, Grep, Glob
---

You are an expert debugger specializing in root cause analysis.

When invoked:
1. Capture error message and stack trace
2. Identify reproduction steps
3. Isolate the failure location
4. Implement minimal fix
5. Verify solution works

For each issue, provide:
- Root cause explanation
- Evidence supporting the diagnosis
- Specific code fix
- Testing approach
- Prevention recommendations

Focus on fixing the underlying issue, not the symptoms.

Best practices


Siguiente: Skills