This commit is contained in:
2026-04-12 01:06:31 +07:00
commit 10d660cbcb
1066 changed files with 228596 additions and 0 deletions

View File

@@ -0,0 +1,129 @@
# Agent Teams -- Controls, Display Modes & Task Management
> **Source:** https://code.claude.com/docs/en/agent-teams
> **Version captured:** Claude Code v2.1.80 (March 2026)
## Display Modes
- **In-process** (default fallback): all teammates in one terminal. `Shift+Up/Down` to navigate. Works in any terminal.
- **Split panes**: each teammate gets own pane. Requires tmux or iTerm2.
Default is `"auto"` -- uses split panes if already inside a tmux session, otherwise in-process. The `"tmux"` setting enables split-pane mode and auto-detects tmux vs iTerm2.
```json
{ "teammateMode": "in-process" }
```
Per-session override: `claude --teammate-mode in-process`
Split panes NOT supported in: VS Code terminal, Windows Terminal, Ghostty.
**tmux setup:** install via system package manager.
**iTerm2 setup:** install `it2` CLI, enable Python API in iTerm2 > Settings > General > Magic.
## Model Requirements
All Agent Team teammates must run **Opus 4.6** -- this is a hard constraint. Mixed-model teams (e.g., Sonnet for devs, Haiku for testers) are NOT supported within Agent Teams.
For mixed-model workflows, use **subagents** instead (the `Agent` tool supports `model: "haiku" | "sonnet" | "opus"` per spawn).
## Plan Approval
Require teammates to plan before implementing:
```
Spawn an architect teammate to refactor the auth module.
Require plan approval before they make any changes.
```
**Flow:**
1. Teammate works in read-only plan mode
2. Teammate finishes planning -> sends `plan_approval_request` to lead
3. Lead reviews -> approves via `SendMessage(type: "plan_approval_response", approve: true)`
4. If rejected: teammate stays in plan mode, revises based on feedback, resubmits
5. Once approved: teammate exits plan mode, begins implementation
**Influence criteria:** "only approve plans that include test coverage" or "reject plans that modify the database schema"
## Delegate Mode
Restricts lead to coordination-only tools: spawning, messaging, shutting down teammates, and managing tasks. No code editing.
Useful when lead should focus entirely on orchestration -- breaking down work, assigning tasks, synthesizing results.
**Enable:** Press `Shift+Tab` after team creation to cycle into delegate mode.
## Direct Teammate Interaction
- **In-process**: `Shift+Up/Down` select teammate, type to message. `Enter` view session. `Escape` interrupt current turn. `Ctrl+T` toggle task list.
- **Split panes**: click into pane to interact directly. Each teammate has full terminal view.
## Task Assignment & Claiming
Three states: **pending** -> **in_progress** -> **completed**. Tasks can have dependencies -- blocked until dependencies resolve.
- **Lead assigns**: tell lead which task -> which teammate
- **Self-claim**: after finishing, teammate picks next unassigned, unblocked task automatically
- **Auto-unblock**: completing a blocking task automatically unblocks dependents
File locking prevents race conditions on simultaneous claiming.
## Worktree Isolation for Implementation
When spawning developer teammates, use `isolation: "worktree"` on the Agent tool:
```
Agent(
subagent_type: "fullstack-developer",
model: "opus",
isolation: "worktree",
run_in_background: true,
prompt: "Implement auth module..."
)
```
Each dev gets own worktree + branch. No file conflicts during parallel work. Lead merges branches after all devs complete.
**When to use:** Always for cook/implementation templates. Not needed for research/review (read-only).
## Background Spawning
Use `run_in_background: true` on the Agent tool to spawn teammates non-blocking:
- Lead continues orchestration while teammates work
- Automatic notification when teammate completes
- No polling needed -- TaskCompleted hook fires on completion
- Use TaskList as fallback if no events in 60s
## Shutdown
```
Ask the researcher teammate to shut down
```
Teammate can approve (exit) or reject with explanation. Teammates finish current request/tool call before shutting down -- can be slow.
## Cleanup
After all teammates shut down, call `TeamDelete` (no parameters). Fails if active teammates still exist.
Removes shared team resources (`~/.opencode/teams/` and `~/.opencode/tasks/` entries).
## Hook-Based Orchestration
### Event-Driven Monitoring
Instead of polling TaskList, lead receives automatic context injection:
- **TaskCompleted** -- fires when any teammate completes a task. Lead gets progress counts.
- **TeammateIdle** -- fires when teammate turn ends. Lead gets available task info.
### Recommended Pattern
1. Lead creates tasks and spawns teammates (with `run_in_background: true`)
2. TaskCompleted hook notifies lead as tasks finish (progress: N/M)
3. TeammateIdle hook suggests reassignment or shutdown
4. Lead acts on suggestions (spawn tester, shut down, reassign)
5. Fallback: Check TaskList manually if no events received in 60s
This replaces the "poll TaskList every 30s" pattern with reactive orchestration.

View File

@@ -0,0 +1,220 @@
# Agent Teams -- Examples, Best Practices & Troubleshooting
> **Source:** https://code.claude.com/docs/en/agent-teams
> **Version captured:** Claude Code v2.1.80 (March 2026)
## Use Case Examples
### Parallel Code Review
```
Create an agent team to review PR #142. Spawn three reviewers:
- One focused on security implications
- One checking performance impact
- One validating test coverage
Have them each review and report findings.
```
Each reviewer applies different filter to same PR. Lead synthesizes across all three.
### Competing Hypotheses Investigation
```
Users report the app exits after one message instead of staying connected.
Spawn 5 agent teammates to investigate different hypotheses. Have them talk to
each other to try to disprove each other's theories, like a scientific
debate. Update the findings doc with whatever consensus emerges.
```
Adversarial debate structure fights anchoring bias -- surviving theory is most likely correct.
### Parallel Feature Implementation (with Worktree Isolation)
```
Create a team to implement the new dashboard feature.
Developer A owns src/api/* and src/models/*.
Developer B owns src/components/* and src/pages/*.
Tester writes tests after both devs finish.
Require plan approval for developers.
Use worktree isolation for each developer.
```
Each developer works in isolated worktree -- own branch, own working directory. No file conflicts even if ownership boundaries overlap accidentally. Tester blocked until both complete.
## Best Practices
### Give Enough Context
Teammates don't inherit lead's conversation. Include details in spawn prompt:
```
Spawn a security reviewer with prompt: "Review src/auth/ for vulnerabilities.
Focus on token handling, session management, input validation.
App uses JWT in httpOnly cookies. Report with severity ratings."
```
### Size Tasks Right
- **Too small**: coordination overhead exceeds benefit
- **Too large**: teammates work too long without check-ins
- **Right**: self-contained units with clear deliverable (function, test file, review)
### Start with Research/Review
If new to agent teams, start with read-only tasks (reviewing PRs, researching libraries, investigating bugs). Shows parallel value without coordination challenges of parallel implementation.
### Use Worktree Isolation for Code Changes
For any template where teammates edit code (cook, fix), always use `isolation: "worktree"`:
```
Agent(
subagent_type: "fullstack-developer",
model: "opus",
isolation: "worktree",
run_in_background: true,
prompt: "..."
)
```
**Benefits:**
- Each dev gets own git worktree + branch
- No file conflicts -- devs can edit same files independently
- `.git` dir shared (common config), everything else isolated
- Lead merges branches after all devs complete
**When NOT to use:** Research and review templates (read-only, no file edits).
### Spawn with run_in_background
Always use `run_in_background: true` when spawning multiple teammates:
```
# Spawn all 3 researchers concurrently (non-blocking)
Agent(subagent_type: "researcher", run_in_background: true, ...)
Agent(subagent_type: "researcher", run_in_background: true, ...)
Agent(subagent_type: "researcher", run_in_background: true, ...)
```
Lead continues orchestration immediately. TaskCompleted events notify when each finishes.
### Wait for Teammates
If lead starts implementing instead of delegating:
```
Wait for your teammates to complete their tasks before proceeding
```
### Avoid File Conflicts
Two teammates editing same file = overwrites. Mitigate with:
1. **Worktree isolation** (recommended) -- each dev in own worktree
2. **File ownership boundaries** -- define glob patterns per task
3. **Lead handles shared files** -- restructure tasks if overlap unavoidable
### Monitor & Steer
Check progress regularly. Redirect bad approaches. Synthesize findings as they arrive. Letting a team run unattended too long increases wasted effort risk.
### File Ownership Enforcement
- Define explicit file boundaries in each task description
- Include glob patterns: `File ownership: src/api/*, src/models/*`
- If two tasks need same file: use worktree isolation OR escalate to lead
- Tester owns test files only; reads implementation files but never edits them
### Leverage Event-Driven Hooks
With `TaskCompleted` and `TeammateIdle` hooks enabled:
- Lead is automatically notified when tasks complete -- no manual polling needed
- Progress is tracked via hook-injected context: "3/5 tasks done, 2 pending"
- Idle teammates trigger suggestions: "worker-2 idle, 1 unblocked task available"
- All tasks done triggers: "Consider shutting down teammates and synthesizing"
**Cook workflow example:**
```
1. Lead spawns 3 devs (run_in_background: true, isolation: "worktree")
2. TaskCompleted(dev-1, task #1) -> "1/4 done"
3. TaskCompleted(dev-2, task #2) -> "2/4 done"
4. TaskCompleted(dev-3, task #3) -> "3/4 done"
5. TaskCompleted(dev-1, task #4) -> "4/4 done. All tasks completed."
6. Lead merges worktree branches, then spawns tester
```
### Use Agent Memory for Long-Running Projects
For projects with recurring team sessions:
- Code reviewer learns project conventions, stops flagging known patterns
- Debugger remembers past failures, faster root-cause identification
- Tester tracks flaky tests, avoids re-investigating known issues
- Researcher accumulates domain knowledge across projects (user scope)
Memory persists after team cleanup -- it's in `.opencode/agent-memory/`, not `~/.opencode/teams/`.
### Restrict Sub-Agent Spawning
Use `Task(agent_type)` in agent definitions to prevent:
- Recursive agent chains (agent spawns agent spawns agent)
- Cost escalation (teammate spawning expensive sub-agents)
- Scope creep (tester spawning developer to "fix" issues)
Recommended: Most agents get `Task(Explore)` only. Planner gets `Task(Explore), Task(researcher)`.
## Token Budget Guidance
| Template | Estimated Tokens | Notes |
|----------|-----------------|-------|
| Research (3 teammates) | ~150K-300K | Read-only, all Opus |
| Cook (4 teammates) | ~400K-800K | Highest -- code generation |
| Review (3 teammates) | ~100K-200K | Read-only, all Opus |
| Debug (3 teammates) | ~200K-400K | Mixed read/execute |
Agent Teams use significantly more tokens than subagents (all teammates run Opus 4.6). Use only when parallel exploration + discussion adds clear value. For routine tasks, single session with subagents is more cost-effective.
## Troubleshooting
### Teammates Not Appearing
- In-process: press `Shift+Down` to cycle through active teammates
- Task may not be complex enough -- Claude decides based on task
- Split panes: verify tmux installed and in PATH
- iTerm2: verify `it2` CLI installed and Python API enabled
### Too Many Permission Prompts
Pre-approve common operations in permission settings before spawning.
### Teammates Stopping on Errors
Check output via `Shift+Up/Down` or clicking pane. Give additional instructions or spawn replacement.
### Lead Shuts Down Early
Tell lead to keep going or wait for teammates.
### Orphaned tmux Sessions
```
tmux ls
tmux kill-session -t <session-name>
```
### TeamCreate Fails
- Verify `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` is set in settings.json env
- Agent Teams requires CLI terminal -- NOT supported in VSCode extension
- Only one team per session -- call TeamDelete before creating another
## Limitations
- **Model lock**: All teammates must run Opus 4.6 (no mixed-model teams)
- **No session resumption**: `/resume` and `/rewind` don't restore in-process teammates
- **Task status can lag**: teammates may not mark tasks completed; check manually
- **Shutdown can be slow**: finishes current request first
- **One team per session**: clean up before starting new one
- **No nested teams**: only lead manages team
- **Lead is fixed**: can't promote teammate or transfer leadership
- **Permissions at spawn**: all inherit lead's mode; changeable after but not at spawn time
- **Split panes**: require tmux or iTerm2 only
- **VSCode unsupported**: Agent Teams requires CLI terminal

View File

@@ -0,0 +1,221 @@
# Agent Teams -- Overview & Architecture
> **Canonical source:** https://code.claude.com/docs/en/agent-teams
> **Version captured:** Claude Code v2.1.80 (March 2026)
> **Update policy:** Re-fetch canonical URL when Claude Code releases new Agent Teams features.
This is a **self-contained knowledge base** -- AI agents should NOT need to re-fetch the URL.
## Overview
Agent Teams coordinate multiple Claude Code instances working together. One session acts as the team lead, coordinating work, assigning tasks, and synthesizing results. Teammates work independently, each in its own context window, and communicate directly with each other.
Unlike subagents (run within a single session, report back only), teammates are full independent sessions you can interact with directly.
## When to Use
Best for tasks where parallel exploration adds real value:
- **Research and review**: multiple teammates investigate different aspects, share and challenge findings
- **New modules or features**: teammates each own a separate piece without conflicts
- **Debugging with competing hypotheses**: test different theories in parallel
- **Cross-layer coordination**: changes spanning frontend, backend, tests -- each owned by different teammate
**Not suitable for:** sequential tasks, same-file edits, work with many dependencies.
### Subagents vs Agent Teams
| | Subagents | Agent Teams |
|---|---|---|
| **Tool** | `Agent` (formerly `Task`) | `Agent` + `TeamCreate`/`TaskCreate`/`SendMessage` |
| **Context** | Own 200K-token window; results return to caller | Own full Claude Code instance + context |
| **Communication** | Report back to parent only | Message each other directly via SendMessage |
| **Coordination** | Parent manages all work | Shared task list, self-coordination |
| **Isolation** | Optional `isolation: "worktree"` | Each teammate = separate session |
| **Model** | Any (haiku/sonnet/opus per agent) | All teammates must run Opus 4.6 |
| **Max parallel** | ~10 simultaneous | Depends on system resources |
| **Best for** | Focused tasks, result-only | Complex work requiring discussion |
| **Token cost** | Lower | Higher (each teammate = separate instance) |
| **Status** | Production (stable) | Experimental (requires opt-in flag) |
## Enable
Still experimental -- requires opt-in:
```json
{ "env": { "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1" } }
```
Set in shell environment or settings.json.
## How Teams Start
Two paths:
1. **You request**: describe task + ask for agent team. Claude creates based on instructions.
2. **Claude proposes**: suggests team if task benefits from parallel work.
Both require your confirmation. Claude won't create a team without approval.
## Architecture
| Component | Role |
|-----------|------|
| **Team lead** | Main session -- creates team, spawns teammates, coordinates |
| **Teammates** | Separate Claude Code instances with own context windows |
| **Task list** | Shared work items at `~/.opencode/tasks/{team-name}/` |
| **Mailbox** | Messaging system for inter-agent communication |
Storage:
- **Team config**: `~/.opencode/teams/{team-name}/config.json` (members array with name, agent ID, type)
- **Task list**: `~/.opencode/tasks/{team-name}/`
Task dependencies managed automatically -- completing a blocking task unblocks dependents without manual intervention.
## Tools API Surface
### Agent Tool (spawn teammates)
The `Agent` tool (formerly `Task`, renamed v2.1.63) spawns teammates:
```
Agent(
subagent_type: string, # Agent specialization
description: string, # Short task summary (3-5 words)
prompt: string, # Full instructions for teammate
model: "opus", # Required for Agent Teams (Opus 4.6)
run_in_background: true, # Non-blocking spawn
isolation: "worktree" # Optional: git worktree isolation
)
```
**Built-in subagent types:** `general-purpose`, `Explore`, `Plan`, `researcher`, `fullstack-developer`, `code-reviewer`, `debugger`, `tester`, `planner`, `docs-manager`, `brainstormer`, and more.
**Custom subagents:** Define in `.opencode/agents/` with frontmatter (name, description, tools, model).
### TeamCreate
Create team + task list. Params: `team_name`, `description`.
### TeamDelete
Remove team/task dirs. **Takes NO parameters** -- just call `TeamDelete` with empty params. Fails if active teammates still exist.
### SendMessage Types
| Type | Purpose |
|------|---------|
| `message` | DM to one teammate (requires `recipient`) |
| `broadcast` | Send to ALL teammates (use sparingly -- costs scale with N) |
| `shutdown_request` | Ask teammate to gracefully exit |
| `shutdown_response` | Teammate approves/rejects shutdown (requires `request_id`) |
| `plan_approval_response` | Lead approves/rejects teammate plan (requires `request_id`) |
**Resume pattern:** `SendMessage(to: "<agent-name>")` resumes an idle teammate.
### Task System Fields
| Field | Values/Purpose |
|-------|---------------|
| `status` | `pending` -> `in_progress` -> `completed` (or `deleted`) |
| `owner` | Agent name assigned to task |
| `blocks` | Task IDs this task blocks (read via TaskGet) |
| `blockedBy` | Task IDs that must complete first (read via TaskGet) |
| `addBlocks` | Set blocking relations (write via TaskUpdate) |
| `addBlockedBy` | Set dependency relations (write via TaskUpdate) |
| `metadata` | Arbitrary key-value pairs |
| `subject` | Brief imperative title |
| `description` | Full requirements and context |
Task claiming uses file locking to prevent race conditions.
Task dependencies resolve automatically -- completing a blocker unblocks dependents.
## Hook Events
### TaskCompleted
Fires when teammate calls `TaskUpdate` with `status: "completed"`.
| Field | Type | Description |
|-------|------|-------------|
| `task_id` | string | Completed task ID |
| `task_subject` | string | Task title |
| `task_description` | string | Full task description |
| `teammate_name` | string | Who completed it |
| `team_name` | string | Team name |
### TeammateIdle
Fires after `SubagentStop` for team members.
| Field | Type | Description |
|-------|------|-------------|
| `teammate_name` | string | Idle teammate name |
| `team_name` | string | Team name |
### Event Lifecycle
```
SubagentStart(worker) -> TaskCompleted(task) -> SubagentStop(worker) -> TeammateIdle(worker)
```
TaskCompleted fires BEFORE SubagentStop/TeammateIdle.
## Worktree Isolation
For implementation teams, the `isolation: "worktree"` parameter on the Agent tool gives each teammate:
- **Own git worktree** -- isolated working directory, staging area, HEAD
- **Own branch** -- auto-created feature branch
- **No file conflicts** -- multiple devs can edit same files independently
- **Shared .git** -- common config, refs visible to all
After completion, lead merges worktree branches. This is the recommended pattern for parallel code changes.
## Agent Memory
Agents can declare `memory` in frontmatter for persistent cross-session learning.
| Scope | Location | Persists across |
|-------|----------|-----------------|
| `user` | `~/.opencode/agent-memory/<name>/` | All projects |
| `project` | `.opencode/agent-memory/<name>/` | Sessions in same project |
First 200 lines of `MEMORY.md` auto-injected into system prompt.
## Task(agent_type) Restrictions
Limit which sub-agents an agent can spawn:
```yaml
tools: Read, Grep, Bash, Task(Explore)
```
This agent can only spawn `Explore` sub-agents. Restricts recursive spawning and cost escalation.
## Context & Communication
Each teammate loads: CLAUDE.md, MCP servers, skills, agents. Receives spawn prompt from lead. Lead's conversation history does NOT carry over.
- **Automatic message delivery** -- no polling needed
- **Idle notifications** -- teammates notify lead when turn ends
- **Shared task list** -- all agents see status and claim work
## Permissions
Teammates inherit lead's permission settings at spawn. If lead uses `--dangerously-skip-permissions`, all teammates do too. Can change individually after spawning but not at spawn time.
## Token Usage
Scales with active teammates. Worth it for research/review/features. Single session more cost-effective for routine tasks. All teammates run Opus 4.6 -- no mixed-model teams currently supported.
## Limitations
- **Model lock**: All teammates must run Opus 4.6 (no mixed-model teams)
- **No session resumption**: `/resume` and `/rewind` don't restore in-process teammates
- **Task status can lag**: teammates may not mark tasks completed; check manually
- **Shutdown can be slow**: finishes current request first
- **One team per session**: clean up before starting new one
- **No nested teams**: only lead manages team
- **Lead is fixed**: can't promote teammate or transfer leadership
- **Permissions at spawn**: all inherit lead's mode; changeable after but not at spawn time
- **Split panes**: require tmux or iTerm2 only
- **VSCode unsupported**: Agent Teams requires CLI terminal