Coding Agent:Claude Code 深度剖析 + 开源生态¶
更新日期:2026-04-15
本文目标:深入理解 Claude Code 的完整内部架构(tool loop、subagents、hooks、skills、MCP、memory、permission、compaction),对比主流开源 Coding Agent(Cline/Roo Code/OpenHands/Aider/Continue/OpenCode/Codex CLI),能据此选型或自建。
四、Subagents(Task 工具)深度剖析¶
4.1 什么是 Subagent¶
Subagent 是 Claude Code 最强大的抽象:隔离上下文中运行的专用 Agent。每个 subagent 有独立的 system prompt、工具集、模型选择、记忆。主会话只看到 subagent 的总结返回,不污染主 context。参考 Claude Code Subagents Docs。
flowchart LR
main["主会话<br/>context"]
task["Task tool"]
sub["Subagent<br/>(独立 context +<br/>system prompt + tools)"]
work["多轮工具调用<br/>(隔离)"]
summary["总结回主"]
main --> task --> sub --> work --> summary --> main
classDef stage fill:#fff,stroke:#cc785c,color:#1a1a1a;
class main,task,sub,work,summary stage
4.2 Subagent 的五大价值¶
| 价值 | 说明 |
|---|---|
| Context 隔离 | 长任务不污染主 context;可在主限额耗尽前 fork 一个子运行 |
| 专用 prompt | 各 subagent 有独立 system prompt(code-reviewer / security-auditor / 等) |
| 工具白名单 | 限制 subagent 只能用某些工具(safety / 性能) |
| 模型路由 | 简单 subagent 用 Haiku(便宜),关键 subagent 用 Opus |
| 并行 + 协调 | 主会话可同时 spawn 多个 subagent(搜索 / 检查并行) |
4.3 内置 Subagents¶
Claude Code 默认提供:
Explore— 通用代码库探索(grep / glob / read 优化),用 Haiku 较快较便宜Plan— 软件架构师,输出实现计划general-purpose— 通用 agent,全工具可用statusline-setup— 配置 status line 的特化 agent
用户可在 ~/.claude/agents/*.md 自定义。
4.4 自定义 Subagent(.md 文件)¶
---
# ~/.claude/agents/code-reviewer.md
name: code-reviewer
description: Reviews code for bugs, style issues, and improvements
model: sonnet # 用较便宜的模型
tools: # 白名单
- Read
- Glob
- Grep
- Bash # 用于运行 linter
color: purple
---
You are a senior code reviewer. Focus on:
- Bug risk (null checks, race conditions)
- Style consistency with project
- Performance
Don't suggest changes that are personal taste only.
4.5 Task 工具调用¶
# 在主会话中调用 subagent
Task({
"description": "Review recent git changes",
"prompt": "Review the diff in the last 3 commits. Report any issues.",
"subagent_type": "code-reviewer"
})
调用流程:
-
主会话暂停
-
启动一个全新的 Claude API 会话
-
System prompt = subagent 的专用 prompt + 传入的 prompt
-
Tools = 只有 subagent 允许的工具
-
Model = 按 subagent 配置选择
-
Subagent 完整运行(可能多轮工具调用)
-
Subagent 的最终文本返回给主会话,作为 Task tool 的 result
-
主会话继续
4.6 Task 进化:Tasks v2(2026)¶
Tasks v2(2026.04 发布)引入了跨会话、跨 subagent 的任务协调层,支持 DAG 依赖。参考 Tasks update (VentureBeat)。
关键新能力:
- 任务持久化到 ~/.claude/tasks (UNIX 哲学, 文件即状态)
- DAG 依赖: Task 3 (Run Tests) blockedBy [Task 1 (Build API), Task 2 (Configure Auth)]
- 跨会话恢复: 关闭终端, 明天继续
- Subagent 之间通过 tasks 协调工作
4.7 Subagent 生态(社区 100+ 预制)¶
例子:
-
security-auditor: 代码安全审计 -
performance-profiler: 性能分析 -
test-generator: 为现有代码生成测试 -
db-migration-reviewer: 数据库迁移 SQL 审查
五、Hooks 系统¶
5.1 Hook 生命周期事件¶
| 事件 | 触发时机 | 典型用途 |
|---|---|---|
UserPromptSubmit |
用户输入提交 | 审计 / inject 上下文 |
PreToolUse |
工具执行前 | 安全检查 / 修改参数 / 拦截 |
PostToolUse |
工具执行后 | 格式化 / lint / log |
Stop |
会话结束 | 写日志 / 通知 |
SubagentStop |
subagent 完成 | 收集结果 |
SessionStart |
新会话启动 | 加载工作区 / 检查 git |
Notification |
系统通知 | 自定义 chime |
5.2 Hook 实现类型¶
| 类型 | 怎么写 | 适合 |
|---|---|---|
command |
shell 命令 / 脚本 | 一次性检查(lint / format) |
inline |
直接 JS(待核实) | 极简逻辑 |
matcher |
正则 match tool name | 选择性绑定 |
Hook 可以是 同步 阻断或 async 后台跑(不阻塞 LLM)。
5.3 Hook 配置示例¶
// ~/.claude/settings.json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [{
"type": "command",
"command": "~/.claude/hooks/check-dangerous-bash.sh"
}]
},
{
"matcher": "Write|Edit",
"hooks": [{
"type": "command",
"command": "~/.claude/hooks/format-and-lint.sh",
"async": true
}]
}
],
"UserPromptSubmit": [{
"hooks": [{
"type": "command",
"command": "echo 'User typed: $USER_PROMPT' >> ~/.claude/audit.log"
}]
}]
}
}
5.4 Hook 返回值(控制流)¶
# PreToolUse hook 可以返回的控制结构
hook_response = {
"decision": "allow", # allow | deny | ask | defer
"reason": "Safe operation",
"updatedInput": {...}, # 修改后的参数
"context": "..." # 注入到 Claude 的额外上下文
}
六、Skills 系统¶
6.1 Skill vs Slash Command¶
| 维度 | Slash Command (/foo) |
Skill |
|---|---|---|
| 触发方式 | 显式输入 /name [args] |
自动(描述匹配)+ 显式 |
| 状态 | 无(一次执行) | 可在 subagent fork 中跑 |
| 工具限制 | 跟当前会话同 | 可单独白名单 |
| 参数化 | YAML 参数 | 同样支持 |
| 适合 | 用户主动操作 | LLM 自主决定 |
Skill 是 Slash Command 的"超集" —— 多了自动触发能力。Anthropic 鼓励 skill 优先。
6.2 SKILL.md 结构¶
---
name: code-review
description: Review git diff for bugs, style, performance issues
# 触发行为
disable-model-invocation: false # 允许模型自动触发
# 执行上下文
context: fork # 在 subagent 中运行(隔离); 或 inline
# 工具限制
allowed-tools: [Read, Grep, Bash]
# 参数
arguments:
- name: target_branch
default: main
---
# Code Review Skill
When reviewing code, check:
1. Logical correctness
2. Edge cases
3. Performance
...
Run: git diff $target_branch...HEAD
Report findings as:
- CRITICAL / WARNING / SUGGESTION
6.3 Skill 的两种触发¶
flowchart LR
subgraph auto["自动触发"]
u1["用户:<br/>'帮我 review 一下最近的 commit'"] --> m1["匹配 description"]
m1 --> l1["加载 SKILL.md"]
l1 --> s1["在 subagent (fork context)<br/>中执行"]
s1 --> r1["返回结果"]
end
subgraph exp["显式触发"]
u2["用户:/code-review main"] --> l2["直接加载 skill"]
l2 --> a2["$target_branch = main"]
a2 --> e2["执行"]
end
classDef io fill:#f5f3eb,stroke:#bdb9ab,color:#1a1a1a;
classDef op fill:#fff,stroke:#cc785c,color:#1a1a1a;
class u1,u2,r1,e2 io
class m1,l1,s1,l2,a2 op
七、MCP 集成¶
7.1 MCP 架构回顾¶
flowchart LR
cc["Claude Code"]
mcp["MCP Client"]
fs["filesystem<br/>server"]
git["git<br/>server"]
db["postgres<br/>server"]
custom["自家业务<br/>server"]
cc --> mcp
mcp --> fs
mcp --> git
mcp --> db
mcp --> custom
classDef stage fill:#fff,stroke:#cc785c,color:#1a1a1a;
class cc,mcp,fs,git,db,custom stage
7.2 配置 MCP Server¶
// ~/.claude.json 或 .mcp.json
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/data"]
},
"slack": {
"url": "https://slack-mcp.example.com/sse",
"transport": "sse",
"headers": {"Authorization": "Bearer xxx"}
}
}
}
7.3 MCP 工具命名与权限¶
MCP 工具名: mcp__<server_name>__<tool_name>
例: mcp__slack__send_message, mcp__filesystem__read_file
权限控制:
~/.claude/settings.json 里的 permissions 字段
{
"permissions": {
"allow": ["Read", "Grep", "Bash(ls *)"],
"deny": ["Bash(rm*)", "mcp__slack__send_message"],
"ask": ["Write", "Edit"]
}
}
八、Memory 与 Context 管理¶
8.1 三类记忆¶
flowchart LR
short["Working memory<br/>(当前 context window)"]
mid["Session memory<br/>(本次对话历史)"]
long["Long-term memory<br/>(CLAUDE.md / memory/<br/> Skills / MCP resources)"]
short --- mid --- long
classDef stage fill:#fff,stroke:#cc785c,color:#1a1a1a;
class short,mid,long stage
| 类型 | 容量 | 持久化 | 跨 session |
|---|---|---|---|
| Working | 受 context window 限制(200k-1M) | 否 | 否 |
| Session | 当前对话所有消息 | 否(关终端就丢) | 否 |
| Long-term | 文件系统 | 是 | 是 |
Long-term memory 通过 ~/.claude/projects/<slug>/memory/MEMORY.md + 单独 memory 文件组织,详见 auto memory 系统。
8.2 Context Compaction¶
当 context 即将溢出,Claude Code 触发 compaction:先清理旧 tool outputs(保留 tool calls 和用户消息);不够就总结整个对话。
def compact(session):
# 阶段 1: 清理 tool_result (最吃 token 的部分)
for msg in session.messages[:-20]: # 保留最近 20 条
for block in msg.content:
if block.type == "tool_result" and len(block.content) > 500:
block.content = f"[{len(block.content)} chars, compacted]"
# 阶段 2: 还不够 → LLM summarize 整个历史
if session.token_count > THRESHOLD:
summary = claude.summarize(session.messages)
session.messages = [
{"role": "user", "content": "<Previous conversation summary>: " + summary},
*session.messages[-5:] # 保留最近 5 条
]
# 阶段 3: 重新加载启动内容(CLAUDE.md、环境等)
session.reload_startup()
# 注意: skills 不会重新加载 (太贵)
8.3 Auto-Compact¶
用户可以在 CLAUDE.md 中指定哪些内容要在 compaction 中保留:
<!-- CLAUDE.md -->
## Compact Instructions
In any compaction, always preserve:
- The current task and remaining subtasks
- Files currently being edited
- The branch name and recent git history
九、Permission Modes¶
| Mode | 描述 | 场景 |
|---|---|---|
| default | 只读,写操作要确认 | 日常,敏感工作 |
| acceptEdits | 文件编辑自动批准,但不执行命令 | 已 review plan |
| plan | 只探索和规划,不做任何改动 | 需求分析 |
| auto | 分类器决定哪些自动做 | 受信任的环境 |
| bypassPermissions | 完全自主 | 沙箱环境 |
十、Plan Mode 深入¶
Plan Mode 是 Claude Code 的安全护栏:强制模型先规划后执行。
10.1 Plan Mode 流程¶
flowchart LR
enter["进入 Plan Mode<br/>(--plan 或对话触发)"]
explore["只读探索<br/>(Read/Grep/Glob)"]
plan["生成 plan<br/>(步骤列表)"]
review{"用户审批"}
exec["切回普通 mode<br/>执行"]
revise["修改 plan"]
enter --> explore --> plan --> review
review -->|批准| exec
review -->|要改| revise --> plan
classDef stage fill:#fff,stroke:#cc785c,color:#1a1a1a;
classDef decision fill:#f5f3eb,stroke:#bdb9ab,color:#1a1a1a;
class enter,explore,plan,exec,revise stage
class review decision
进入 Plan Mode 后:
- 所有 Write / Edit / NotebookEdit / 非 read-only Bash 都被禁用
- 模型必须输出完整 plan 后等用户批准(
ExitPlanModetool) - 用户可以让 Claude 修订 plan 多轮
- 批准后切回普通 mode 执行原计划
10.2 强制 Plan 的触发¶
用户可以强制进入 Plan Mode:
-
CLI:
claude --plan -
对话中:输入 "请先做一个 plan 然后等我批准"
Plan Mode 下禁用的工具:
十一、泄露事件揭示的内部细节¶
2026.03.31 Anthropic 的 source map 意外发布。512K+ 行 TypeScript 代码暴露。参考 Claude Code Source Leak Analysis。
11.1 Anti-Distillation 机制¶
Claude Code API 请求中附加:
服务器会在 system prompt 中注入虚假工具定义(真实 Claude Code 不会调用)。如果竞对抓取流量用于蒸馏,就会学到这些假工具,从而污染竞对的训练数据,同时不影响真实用户。
11.2 Undercover Mode¶
在非 Anthropic 仓库工作时自动开启。功能:
-
隐藏所有内部代号(Tengu、KAIROS 等)
-
不提及内部 Slack / email
-
用通用名称(Claude 而非 Fennec)
目的:防止员工贡献开源代码时意外泄露内部信息。
11.3 KAIROS / autoDream¶
KAIROS: 持续运行的后台 agent - 空闲时触发 autoDream - 整合本会话学到的东西到长期记忆 - 类似人脑的"梦"阶段
(未公开启用, 仅在代码中存在)
↑ 上级 · H4. Coding Agent:Claude Code / Cursor / Devin / OpenClaw