s/agents-development
Multi-Agent Patterns
Ревизия {n}
Diff заголовка
Предыдущая ревизия
Выбранная ревизия
1
1
Multi-Agent Patterns
Diff содержимого
Предыдущая ревизия
Выбранная ревизия
1
## Multi-Agent Patterns1
2
3
One big agent is fine until you need to do three things at once, keep exploration out of the main context, or run something unattended in CI. Then you reach for the multi-agent primitives: **headless mode**, **subagents**, and **git worktrees**. This page covers what each one actually does, and when to use them instead of a single chat.4
5
## Headless mode: `claude -p`6
7
Headless mode runs Claude Code non-interactively. No REPL, no prompt — you pass the task on the command line or stdin and Claude works, then exits. The core flag is `-p` (or `--print`):8
9
```bash10
claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash"11
```12
13
It is the entry point for everything programmatic: CI jobs, pre-commit checks, cron tasks, orchestration from another language.14
15
**Output formats** — `--output-format` controls what stdout looks like:16
17
- `text` (default): plain text response.18
- `json`: structured JSON with `result`, `session_id`, usage metadata.19
- `stream-json`: newline-delimited JSON events for real-time streaming.20
21
```bash22
# One-shot with JSON output23
claude -p "Summarize this project" --output-format json | jq -r '.result'24
25
# Streaming — token-by-token26
claude -p "Explain recursion" \27
--output-format stream-json \28
--verbose --include-partial-messages29
```30
31
**Bare mode** — add `--bare` to skip auto-discovery of hooks, plugins, MCP servers, CLAUDE.md, and auto memory. This cuts startup time and gives you identical behavior on every machine. Essential for CI.32
33
```bash34
claude --bare -p "Apply lint fixes" \35
--allowedTools "Read,Edit,Bash(npm run lint)" \36
--permission-mode acceptEdits37
```38
39
In bare mode, authentication must come from `ANTHROPIC_API_KEY` or `apiKeyHelper` — keychain reads are skipped.40
41
**CI commit-creation pattern:**42
43
```bash44
gh pr diff "$PR_NUM" | claude -p \45
--append-system-prompt "You are a security reviewer. Flag vulnerabilities." \46
--output-format json \47
--bare48
```49
50
**Continuing conversations** — `--continue` picks up the most recent session, or capture the session id from JSON output and resume explicitly:51
52
```bash53
session_id=$(claude -p "Start a review" --output-format json | jq -r '.session_id')54
claude -p "Now focus on error handling" --resume "$session_id"55
```56
57
## Subagents58
59
A subagent is a specialized assistant with its own system prompt, tool restrictions, and context window. When Claude encounters a task that matches a subagent's description, it delegates: the subagent works in isolation and returns only a summary. Your main conversation never sees the search results, the logs, or the hundred files the subagent read.60
61
**Why use them:**62
63
- **Context preservation.** Exploration produces noise. A subagent eats the noise so your main window stays clean.64
- **Tool restriction.** Give a reviewer agent read-only tools. Give a migration runner only `Bash(psql *)` and `Read`.65
- **Cost control.** Route cheap tasks to Haiku; keep Opus for the thinking.66
- **Focus.** A tight system prompt beats "try to remember this rule".67
68
**Built-in subagents** — Claude Code ships with three you'll use constantly:69
70
| Agent | Model | Tools | Purpose |71
| --- | --- | --- | --- |72
| `Explore` | Haiku | read-only | Fast codebase search |73
| `Plan` | inherits | read-only | Research during plan mode |74
| `general-purpose` | inherits | all tools | Complex multi-step tasks |75
76
**Custom subagents** — markdown files with YAML frontmatter in `.claude/agents/` (project) or `~/.claude/agents/` (user):77
78
```markdown79
---80
name: migration-reviewer81
description: Reviews SQL migrations for safety, locking, and rollback82
tools: Read, Grep, Glob83
model: sonnet84
permissionMode: plan85
---86
87
You are a senior DBA. When asked to review a migration:88
1. Check for missing indexes on foreign keys.89
2. Flag ALTER TABLE on tables > 1M rows as a risk.90
3. Confirm there is a rollback path.91
Return: safe / risky / unsafe, with a reason.92
```93
94
**Fields that matter** — `tools` (allowlist) or `disallowedTools` (denylist), `model`, `permissionMode`, `mcpServers` (scope servers to this agent only), `hooks`, `skills`, `memory` (persistent memory directory), `isolation: worktree` (give the subagent a temp git worktree so it cannot stomp on your files), and `effort`.95
96
**Restricting what an agent can spawn** — a main-thread agent can be limited to specific subagent types: `tools: Agent(worker, researcher)`.97
98
**Defining at launch via CLI:**99
100
```bash101
claude --agents '{102
"debugger": {103
"description": "Debug test failures by analyzing logs",104
"prompt": "You are an expert debugger.",105
"tools": ["Read", "Bash"],106
"model": "sonnet"107
}108
}'109
```110
111
## Git worktrees for parallel work112
113
A worktree is a second working copy of the same git repo, pointing at a different branch. Claude Code supports this directly: set `isolation: worktree` on a subagent, and it works in a fresh temporary worktree that is cleaned up if no changes are made.114
115
This is the cleanest way to run multiple agents on the same repo simultaneously without them fighting over files.116
117
**Manual pattern for orchestration from the outside:**118
119
```bash120
git worktree add ../repo-fix-auth fix-auth121
cd ../repo-fix-auth122
claude -p "fix the bug described in issue #123" --bare123
```124
125
## Orchestration patterns126
127
**Fan-out, reconcile.** One driver agent fans out to N subagents, each handling an independent chunk. Driver reconciles results and resolves conflicts.128
129
Use when: the work splits cleanly (linting 10 packages, generating docs for 20 modules).130
131
**Plan then apply.** One session in plan mode generates a detailed change list. A second session — possibly a subagent with tighter tools — executes it.132
133
Use when: the plan needs human review before touching the repo.134
135
**Reviewer loop.** One agent writes code, a reviewer subagent checks it, the main agent fixes feedback. Repeat until the reviewer is quiet.136
137
Use when: quality bar is high and you want multi-perspective review without a human in the loop.138
139
**CI watcher.** A `claude -p --bare` job runs on PR open, analyzes the diff, and posts a review comment.140
141
## When not to reach for subagents142
143
One context window is often enough. Subagents add complexity and hide information. Don't split a task just because you can. Good rules:144
145
- If the main agent can handle the work in under 20 tool calls, don't delegate.146
- If the subagent's output would just be copied back into your context verbatim, don't delegate.147
- If you can't write a one-sentence description of what the subagent does, it isn't a subagent yet.148
149
---150
151
Next: [MCP (Model Context Protocol)](/s/agents-development/wiki/mcp)152
153
## Sources154
155
- [Agent SDK headless mode](https://code.claude.com/docs/en/headless)156
- [Subagents](https://code.claude.com/docs/en/sub-agents)157
- [Permissions and modes](https://code.claude.com/docs/en/permissions)