Claude Code có nhiều cách để chạy nhiều task song song. Chương này bao quát bốn cách đó — subagents, agent view, agent teams, và fork — với trọng tâm là subagents và agent teams: định nghĩa, frontmatter, cách delegate và cách phối hợp workers.
8.1 So sánh các cách chạy song song
Bốn cách parallelize khác nhau ở chỗ: ai coordinate, workers có cần nói chuyện với nhau không, và có edit cùng file không.
| Approach | Cho bạn gì | Dùng khi |
|---|---|---|
| Subagents | Delegated workers trong 1 session, làm side task trong context riêng rồi trả về summary | Side task sẽ làm ngập main conversation bằng search results, logs, file contents bạn không tham chiếu lại |
Agent view (claude agents) | 1 màn hình để dispatch và monitor các session chạy background. Research preview | Bạn có nhiều task độc lập, muốn hand off và chỉ vào khi cần |
| Agent teams | Nhiều session phối hợp, chung task list + inter-agent messaging, do một lead quản lý. Experimental, tắt mặc định | Muốn Claude chia project thành pieces, assign, và giữ workers đồng bộ |
| Dynamic workflows | Một script chạy nhiều subagents và cross-check kết quả | Job vượt quá vài subagents, hoặc cần verify chéo: audit toàn codebase, migration 500 file |
Trong mọi cách, workers đều là Claude sessions. Muốn dùng tool khác thì expose nó cho Claude qua MCP server.
Ba câu hỏi để chọn:
- Ai coordinate? Claude trong 1 conversation → subagents. Bạn hand off rồi check sau → agent view. Claude plan/assign/supervise → agent teams. Script giữ plan → workflows.
- Workers có cần nói chuyện với nhau? Subagents chỉ report về caller; agent view sessions chỉ report cho bạn. Teammates trong agent team share task list và message trực tiếp nhau.
- Task có đụng cùng file? Isolate bằng worktrees. Subagents và session tự chạy có thể dùng worktree riêng; agent teams KHÔNG isolate teammates nên phải partition file theo owner.
Chạy nhiều session/subagent cùng lúc nhân token usage lên. Xem Costs để biết chi tiết rate-limit.
8.2 Subagents
Subagent là AI assistant chuyên biệt chạy trong context window riêng, với system prompt riêng, tool access riêng, permissions độc lập. Khi Claude gặp task khớp description của subagent, nó delegate; subagent làm việc độc lập rồi trả về kết quả. Chỉ summary quay lại main conversation — verbose output ở lại trong context của subagent.
Subagents giúp:
- Preserve context: giữ exploration/implementation ra khỏi main conversation
- Enforce constraints: giới hạn tools một subagent dùng được
- Reuse configurations: subagents user-level dùng lại được khắp project
- Specialize behavior: system prompt tập trung cho domain cụ thể
- Control costs: route task tới model rẻ/nhanh hơn như Haiku
Built-in subagents
Claude Code có sẵn subagents dùng tự động. Mỗi cái kế thừa permissions của parent + thêm tool restrictions.
| Subagent | Model | Tools | Mục đích |
|---|---|---|---|
| Explore | Inherit, cap ở Opus trên Claude API | Read-only (deny Write/Edit) | File discovery, code search, codebase exploration |
| Plan | Inherit | Read-only (deny Write/Edit) | Codebase research trong plan mode |
| general-purpose | Inherit | Tất cả tools | Task phức tạp, nhiều bước, có cả explore lẫn modify |
| statusline-setup | Sonnet | — | Khi chạy /statusline |
| claude-code-guide | Haiku | — | Khi hỏi về feature Claude Code |
- Explore và Plan bỏ qua CLAUDE.md và git status để research nhanh/rẻ; mọi subagent khác load cả hai.
- Từ v2.1.198, Explore inherit model của main conversation thay vì luôn chạy Haiku. Định nghĩa một subagent tên
Explorevớimodel: haikuđể override và giữ exploration ở model rẻ. - Chặn built-in: thêm vào
permissions.deny(ví dụAgent(Explore)), hoặc deny nguyênAgenttool để cấm mọi delegation. ĐặtCLAUDE_CODE_DISABLE_EXPLORE_PLAN_AGENTS=1để bỏ riêng Explore/Plan.
Định nghĩa một subagent
Subagent là file Markdown có YAML frontmatter, phần body là system prompt. Đặt trong .claude/agents/ (project) hoặc ~/.claude/agents/ (user).
---
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.
Subagent chỉ nhận system prompt này + environment details cơ bản (working directory), KHÔNG nhận full Claude Code system prompt. Từ v2.1.198, có thể nhờ Claude viết file cho bạn hoặc tự sửa .claude/agents/; command /agents không còn mở wizard nữa.
Claude Code watch ~/.claude/agents/ và .claude/agents/ — thêm/sửa file được detect trong vài giây, không cần restart. Ngoại lệ cần restart: tạo file đầu tiên trong một agents directory mới; và session chạy với --disable-slash-commands.
Scope và priority
Cùng một name ở nhiều nơi thì nơi priority cao thắng.
| Location | Scope | Priority |
|---|---|---|
| Managed settings | Organization-wide | 1 (cao nhất) |
--agents CLI flag | Session hiện tại | 2 |
.claude/agents/ | Project | 3 |
~/.claude/agents/ | Mọi project của bạn | 4 |
Plugin's agents/ | Nơi plugin bật | 5 (thấp nhất) |
- Project subagents (
.claude/agents/): check vào version control để team cùng dùng. Được discover bằng cách đi ngược lên từ cwd; khi nested trùngname, cái gần cwd nhất thắng. - User subagents (
~/.claude/agents/): cá nhân, dùng ở mọi project. - Cả hai directory được scan đệ quy, nên tổ chức subfolder (
agents/review/) được — nhưng identity chỉ đến từ fieldname, không phải path. Giữnameunique toàn tree. - CLI-defined (
--agents '<json>'): chỉ tồn tại trong session đó, không lưu disk. Dùng JSON với cùng các frontmatter field (dùngpromptcho system prompt). - Plugin subagents: KHÔNG hỗ trợ
hooks,mcpServers,permissionMode(bị ignore vì lý do bảo mật).
Frontmatter fields
Chỉ name và description là bắt buộc.
| Field | Mô tả |
|---|---|
name | Định danh unique (lowercase + hyphen). Hooks nhận value này làm agent_type. Filename không cần khớp |
description | Khi nào Claude nên delegate tới subagent này |
tools | Tools subagent dùng được (allowlist). Bỏ trống = inherit tất cả. Chấp nhận pattern MCP như mcp__<server> |
disallowedTools | Tools bị deny, gỡ khỏi list inherited/specified |
model | sonnet, opus, haiku, fable, full model ID (vd claude-opus-4-8), hoặc inherit. Mặc định inherit |
permissionMode | default, acceptEdits, auto, dontAsk, bypassPermissions, plan, hoặc manual (alias của default) |
maxTurns | Số agentic turns tối đa trước khi subagent dừng |
skills | Skills preload vào context lúc startup (inject full content, không chỉ description) |
mcpServers | MCP servers cấp cho subagent này (inline definition hoặc reference tên) |
hooks | Lifecycle hooks scoped riêng subagent này |
memory | Persistent memory scope: user, project, hoặc local. Bật cross-session learning |
background | true = luôn chạy background. Từ v2.1.198 subagents mặc định chạy background |
effort | Effort level: low, medium, high, xhigh, max (tùy model) |
isolation | worktree = chạy trong git worktree tạm, copy repo riêng, branch từ default branch |
color | Màu hiển thị: red, blue, green, yellow, purple, orange, pink, cyan |
initialPrompt | Auto-submit làm user turn đầu khi agent chạy như main session (--agent) |
Control tools và permissions
tools là allowlist, disallowedTools là denylist. Nếu set cả hai: disallowedTools áp dụng trước, rồi tools resolve trên phần còn lại.
# Chỉ cho Read, Grep, Glob, Bash — không edit/write, không MCP
---
name: safe-researcher
description: Research agent with restricted capabilities
tools: Read, Grep, Glob, Bash
---
# Inherit tất cả trừ Write và Edit
---
name: no-writes
description: Inherits every tool except file writes
disallowedTools: Write, Edit
---
Một số tool không bao giờ cấp cho subagent dù có liệt kê: AskUserQuestion, EnterPlanMode, ExitPlanMode (trừ khi permissionMode: plan), ScheduleWakeup, WaitForMcpServers. Agent tool được inherit → subagent có thể spawn nested subagents.
permissionMode kiểm soát cách xử lý prompt permission. Nếu parent dùng bypassPermissions/acceptEdits thì nó thắng, subagent không override được. Nếu parent ở auto mode, subagent inherit auto và bỏ qua permissionMode trong frontmatter.
⚠ Dùng
bypassPermissionscẩn thận: bỏ qua prompt, cho phép ghi vào.git,.claude,.vscode... mà không cần approve.
Chọn model
Thứ tự resolve model của subagent:
- Env var
CLAUDE_CODE_SUBAGENT_MODEL(nếu set thành alias/ID) - Per-invocation
modelparameter Claude truyền lúc gọi - Field
modeltrong frontmatter - Model của main conversation
Từ v2.1.198, subagents cũng inherit cấu hình extended thinking của main conversation (không có setting per-subagent).
Persistent memory
Field memory cho subagent một directory tồn tại qua các conversation, để tích lũy kiến thức (codebase patterns, debugging insights).
| Scope | Location | Dùng khi |
|---|---|---|
user | ~/.claude/agent-memory/<name>/ | nhớ qua mọi project |
project | .claude/agent-memory/<name>/ | project-specific, share qua git (khuyến nghị) |
local | .claude/agent-memory-local/<name>/ | project-specific, không check vào git |
Khi bật memory: system prompt của subagent thêm hướng dẫn đọc/ghi memory + 200 dòng đầu (hoặc 25KB) của MEMORY.md; Read/Write/Edit tự động được bật.
Conditional rules với hooks
Dùng PreToolUse hook để validate operation trước khi chạy — hữu ích khi cần cho phép một số op và chặn số khác (ví dụ chỉ cho SELECT query):
---
name: db-reader
description: Execute read-only database queries
tools: Bash
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate-readonly-query.sh"
---
Script đọc JSON qua stdin, extract command, exit 2 để chặn write operation. Ngoài ra có SubagentStart/SubagentStop trong settings.json để chạy hook ở main session khi subagent bắt đầu/kết thúc.
Delegate: automatic vs explicit
Claude tự delegate dựa trên request của bạn + field description. Để khuyến khích delegate chủ động, thêm cụm như "use proactively" vào description.
Ba pattern gọi subagent tường minh, tăng dần mức độ ràng buộc:
- Natural language: nêu tên subagent trong prompt; Claude tự quyết định
Use the test-runner subagent to fix failing tests - @-mention: đảm bảo subagent đó chạy cho 1 task
@"code-reviewer (agent)" look at the auth changes - Session-wide: cả session dùng system prompt/tools/model của subagent qua
--agent
Hoặc set default cho project trongclaude --agent code-reviewer.claude/settings.json:{ "agent": "code-reviewer" }
Foreground vs background
- Foreground: block main conversation tới khi xong; permission prompt truyền thẳng cho bạn.
- Background: chạy đồng thời trong khi bạn tiếp tục. Từ v2.1.186, prompt permission của background subagent surface ở main session và nêu tên subagent đang hỏi.
Từ v2.1.198 subagents chạy background mặc định; Claude chỉ chạy foreground khi cần kết quả ngay. Bạn có thể nhờ Claude chạy background/foreground, hoặc nhấn Ctrl+B để background task đang chạy. /tasks liệt kê các item đang chạy nền (kể cả subagents đã xong). Đặt CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1 để tắt hẳn.
Chạy parallel research
Với các điều tra độc lập, spawn nhiều subagent làm cùng lúc:
Research the authentication, database, and API modules in parallel using separate subagents
Mỗi subagent explore vùng của mình độc lập, rồi Claude tổng hợp findings. Hiệu quả nhất khi các research path không phụ thuộc nhau.
⚠ Khi subagents xong, kết quả trả về main conversation. Nhiều subagent mỗi cái trả về kết quả chi tiết có thể ngốn nhiều context. Với parallelism kéo dài hoặc vượt context window, dùng agent teams.
Nested subagents, depth và limit
Từ v2.1.172, một subagent có thể spawn subagents của chính nó — chỉ summary top-level trả về bạn. Depth = số level dưới main conversation; subagent ở depth 5 không nhận Agent tool và không spawn tiếp (fixed, không configurable). Mặc định tối đa 200 subagents/session (chỉnh qua CLAUDE_CODE_MAX_SUBAGENTS_PER_SESSION). Để cấm một subagent spawn con, bỏ Agent khỏi tools hoặc thêm vào disallowedTools.
Resume subagents
Mỗi lần invoke tạo instance mới với context fresh. Để tiếp tục subagent cũ (giữ full history), nhờ Claude resume — nó dùng tool SendMessage với agent ID/name làm field to. Explore và Plan là one-shot, không có agent ID, không resume được; dùng general-purpose hoặc custom subagent khi cần tiếp tục.
Fork the current conversation
Fork là một subagent kế thừa toàn bộ conversation thay vì bắt đầu fresh — thấy cùng system prompt, tools, model, message history như main session. Dùng khi một named subagent cần quá nhiều background để hữu ích, hoặc muốn thử nhiều approach song song từ cùng điểm xuất phát. Tool calls của fork vẫn ở ngoài conversation, chỉ final result quay lại.
Khởi động fork bằng /subtask (v2.1.212+; trước đó là /fork):
/subtask draft unit tests for the parser changes so far
Fork so với named subagent:
| Fork | Named subagent | |
|---|---|---|
| Context | Full conversation history | Fresh + prompt bạn truyền |
| System prompt & tools | Giống main session | Từ definition file |
| Model | Giống main session | Từ field model |
| Prompt cache | Share với main session (rẻ hơn) | Cache riêng |
Fork không spawn được fork khác. Set CLAUDE_CODE_FORK_SUBAGENT=1/0 để bật/tắt fork mode tường minh.
Subagents vs main conversation
Dùng main conversation khi: task cần qua lại/tinh chỉnh liên tục; nhiều phase share context lớn; thay đổi nhỏ/nhanh; latency quan trọng.
Dùng subagents khi: task tạo verbose output không cần trong main context; muốn enforce tool restrictions; công việc self-contained trả về summary.
8.3 Agent Teams
Agent teams cho nhiều Claude Code instance làm việc như một team. Một session là team lead (coordinate, assign, synthesize); các teammates làm độc lập, mỗi cái context window riêng, và message trực tiếp lẫn nhau. Khác subagents (chỉ report về main agent), bạn có thể tương tác trực tiếp với từng teammate mà không qua lead.
⚠ Agent teams là experimental, tắt mặc định. Bật bằng
CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1trongsettings.jsonhoặc environment.
{
"env": {
"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"
}
}
Subagents vs agent teams
| Subagents | Agent teams | |
|---|---|---|
| Context | Context riêng; result trả về caller | Context riêng; fully independent |
| Communication | Chỉ report về main agent | Teammates message trực tiếp nhau |
| Coordination | Main agent quản mọi việc | Shared task list + self-coordination |
| Best for | Task tập trung, chỉ cần result | Việc phức tạp cần thảo luận, phối hợp |
| Token cost | Thấp hơn (summary về main) | Cao hơn (mỗi teammate là 1 Claude instance) |
Dùng agent teams khi teammates cần share findings, challenge nhau, và tự coordinate. Use case mạnh: research/review song song, module/feature mới (mỗi teammate own một phần), debugging với competing hypotheses, cross-layer coordination (FE/BE/tests).
Bắt đầu một team
Sau khi bật, mô tả task và teammates bằng natural language — Claude spawn và coordinate:
I'm designing a CLI tool that helps developers track TODO comments across
their codebase. Spawn three teammates to explore this from different angles:
one on UX, one on technical architecture, one playing devil's advocate.
Claude tạo shared task list, spawn teammates, cho họ explore, và tổng hợp. Lưu ý: đôi khi Claude dùng subagents thay vì team; nếu vậy hỏi lại và yêu cầu tường minh agent team.
Panel dưới prompt liệt kê teammates. Điều khiển: ↑/↓ chọn teammate, Enter mở transcript và message trực tiếp, Esc interrupt turn hiện tại.
Display mode
- In-process (mặc định): tất cả teammates chạy trong terminal chính. Không cần setup thêm.
- Split panes: mỗi teammate một pane riêng, thấy output tất cả cùng lúc. Cần tmux hoặc iTerm2 (với
it2CLI).
Set qua teammateMode trong ~/.claude/settings.json ("in-process", "auto", "tmux", "iterm2") hoặc flag --teammate-mode.
Specify teammates và models
Claude tự quyết số teammates, hoặc bạn chỉ định:
Spawn 4 teammates to refactor these modules in parallel. Use Sonnet for
each teammate.
Teammates KHÔNG inherit /model của lead theo mặc định. Đổi qua Default teammate model trong /config (chọn Default (leader's model) để theo lead). Teammates inherit effort level của lead. Model và fast mode của teammate fixed lúc spawn.
Require plan approval
Với task rủi ro, yêu cầu teammate plan trước khi implement — teammate ở read-only plan mode tới khi lead approve:
Spawn an architect teammate to refactor the authentication module.
Require plan approval before they make any changes.
Lead tự quyết approve/reject autonomously. Ảnh hưởng phán đoán của lead bằng cách cho tiêu chí trong prompt ("only approve plans that include test coverage").
Assign và claim tasks
Shared task list có 3 state: pending, in progress, completed. Task có thể depend nhau — task pending có unresolved dependency không claim được tới khi dependency xong.
- Lead assigns: bảo lead giao task nào cho teammate nào
- Self-claim: xong task, teammate tự lấy task kế tiếp chưa assign, chưa block
Task claiming dùng file locking để tránh race condition. Dependency tự động unblock khi task tiền đề hoàn thành.
Reuse subagent definitions cho teammates
Khi spawn teammate, có thể reference một subagent type từ bất kỳ scope nào — định nghĩa role một lần, dùng cả như subagent lẫn teammate:
Spawn a teammate using the security-reviewer agent type to audit the auth module.
Teammate honor tools allowlist và model của definition; body được append vào system prompt (không thay thế). Coordination tools (SendMessage, task management) luôn có. Lưu ý: skills và mcpServers trong definition KHÔNG áp dụng khi chạy làm teammate — teammates load skills/MCP từ project/user settings như session thường.
Permissions và communication
- Teammates start với permission settings của lead. Đổi mode từng teammate sau spawn được, nhưng không set per-teammate lúc spawn.
- Prompt permission của teammate bubble lên lead session — approve ở đó. Plan approval là ngoại lệ được thiết kế: lead grant không cần prompt riêng cho bạn.
- Một teammate KHÔNG thể approve permission thay bạn; approval claim relay từ agent khác bị coi là untrusted input.
- Mỗi teammate context window riêng, load CLAUDE.md/MCP/skills như session thường, KHÔNG inherit conversation history của lead — đưa chi tiết task vào spawn prompt.
- Message delivery tự động; idle notification tự báo lead khi teammate xong. Message theo tên; để gửi mọi người phải gửi từng recipient.
Quality gates với hooks
TeammateIdle: chạy khi teammate sắp idle.exit 2để gửi feedback và giữ teammate làm tiếp.TaskCreated:exit 2để chặn tạo task và gửi feedback.TaskCompleted:exit 2để chặn đánh dấu complete và gửi feedback.
Best practices
- Team size: bắt đầu 3-5 teammates cho hầu hết workflow. Ba teammate tập trung thường thắng năm cái tản mạn.
- Task size: đơn vị self-contained tạo deliverable rõ ràng (một function, một test file, một review). ~5-6 task/teammate.
- Avoid file conflicts: hai teammate edit cùng file gây overwrite — chia việc để mỗi teammate own một set file khác nhau.
- Give context: đưa chi tiết task-specific vào spawn prompt vì teammate không inherit history của lead.
- Wait for teammates: nếu lead tự implement thay vì đợi, bảo "Wait for your teammates to complete their tasks before proceeding".
- Start with research/review: task có ranh giới rõ, không cần viết code, cho người mới.
Limitations chính
- Không resume in-process teammates qua
/resume//rewind. - Task status có thể lag (teammate quên mark complete → block dependency).
- Một team/session; không nested teams (teammate không spawn teammate).
- In-process teammate không spawn được background subagent.
- Lead cố định suốt lifetime; không promote teammate lên lead.
- Split panes cần tmux/iTerm2 (không hỗ trợ VS Code integrated terminal, Windows Terminal, Ghostty).
8.4 Agent View
Agent view (claude agents) là một màn hình cho mọi background session: cái gì đang chạy, cái gì cần input, cái gì xong. Mỗi background session là một full Claude Code conversation chạy tiếp mà không cần terminal attach. Research preview, cần v2.1.139+.
Vòng lặp cốt lõi:
- Dispatch: gõ prompt + Enter → session mới chạy background, hiện thành một row. Mỗi prompt tạo session riêng (chạy nhiều cái song song).
- Peek & reply: chọn row, nhấn Space mở peek panel xem output/câu hỏi gần nhất; gõ reply + Enter mà không rời agent view.
- Attach & detach: Enter/→ attach vào full conversation; ← trên prompt trống để detach về table.
- Bring in:
/bg(hoặc←) trong một session đang chạy để đẩy nó vào agent view.
Đọc state qua icon (màu + shape): Working (animated), Needs input (yellow), Idle (dimmed), Completed (green), Failed (red), Stopped (grey). Shape cho biết process còn sống (✻/✽) hay đã exit (∙, vẫn peek/reply/attach được).
Dispatch nâng cao (từ input agent view):
| Input | Effect |
|---|---|
<agent-name> <prompt> | Nếu từ đầu khớp custom subagent, subagent đó chạy như main agent của session |
@<agent-name> | Mention subagent ở bất kỳ đâu để chạy làm main agent |
@<repo> | Chạy session ở repository đó |
/<command> | Gợi ý skills/commands để dispatch làm prompt |
! <command> | Chạy shell command làm background job thay vì Claude session |
Shift+Enter | Dispatch và attach ngay |
Từ shell: claude --bg "<prompt>" (kết hợp --agent <name>, --name <label>). Chạy shell command background: claude --bg --exec 'pytest -x'.
File isolation: trước khi edit file, background session tự chuyển vào git worktree riêng dưới .claude/worktrees/, nên các session song song đọc cùng checkout nhưng mỗi cái ghi riêng. Tắt qua worktree.bgIsolation: "none". Session đã isolate còn tự commit, push branch riêng, và mở draft PR mà không hỏi — nhưng không bao giờ push vào main/master, không force-push/merge.
Xem thêm
content/en/docs/claude-code/sub-agents.md— Create custom subagents (reference đầy đủ)content/en/docs/claude-code/agents.md— Run agents in parallel (so sánh các approach)content/en/docs/claude-code/agent-teams.md— Orchestrate teams of Claude Code sessionscontent/en/docs/claude-code/agent-view.md— Manage multiple agents with agent viewcontent/en/docs/claude-code/worktrees.md— Run parallel sessions with worktreescontent/en/docs/claude-code/workflows.md— Dynamic workflowscontent/en/docs/claude-code/hooks.md— Hooks reference (SubagentStart,TeammateIdle,TaskCreated,TaskCompleted)content/en/docs/claude-code/plugins.md— Distribute subagents với plugins