Learn-Claude-Code 深度调研报告
Learn-Claude-Code 深度调研报告
基于 GitHub 开源项目 shareAI-lab/learn-claude-code 的深度技术调研
调研日期:2026-03-27
一、项目概述
1.1 基本信息
| 属性 | 信息 |
|---|---|
| 项目名称 | Learn Claude Code |
| GitHub | https://github.com/shareAI-lab/learn-claude-code |
| 官网 | https://learn.shareai.run |
| 开发者 | shareAI-lab (CrazyBoyM) |
| 核心定位 | 从零到一学习 Agent Harness 工程的教程 |
| 开源状态 | MIT License |
| Stars | 40,658 |
| Forks | 6,328 |
| 主要语言 | TypeScript (59.9%), Python (38.9%) |
| 创建时间 | 2025-06-29 |
| 活跃状态 | 持续更新中 |
1.2 一句话介绍
"Bash is all you need" - 一个从零到一构建 Claude Code 风格 Agent Harness 的渐进式教程,包含 12 个学习会话。
1.3 核心理念
┌─────────────────────────────────────────────────────────────────────┐
│ Learn Claude Code 核心理念 │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ "The model IS the agent, the code is the harness" │
│ │
│ 模型就是 Agent,代码是 Harness(驾驭器) │
│ │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ Agent │ │
│ │ ┌─────────────────────────────────────────────────────┐ │ │
│ │ │ LLM Model │ │ │
│ │ │ • 推理能力 │ │ │
│ │ │ • 决策能力 │ │ │
│ │ │ • 工具调用 │ │ │
│ │ └─────────────────────────────────────────────────────┘ │ │
│ │ │ │ │
│ │ ▼ │ │
│ │ ┌─────────────────────────────────────────────────────┐ │ │
│ │ │ Harness │ │ │
│ │ │ • 感知层:收集上下文 │ │ │
│ │ │ • 工具层:执行操作 │ │ │
│ │ │ • 记忆层:管理状态 │ │ │
│ │ │ • 协调层:任务调度 │ │ │
│ │ └─────────────────────────────────────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │
│ Bash 是基础:所有工具都可以通过 Bash 命令实现 │
│ │
└─────────────────────────────────────────────────────────────────────┘
1.4 项目特色
- 渐进式学习:12 个会话,每个添加一个机制
- 逆向工程:解析 Claude Code 的架构模式
- 实践导向:每个会话都有可运行的代码
- 多语言支持:英文、中文、日文文档
二、12 个渐进式会话
2.1 会话概览
| # | 文件 | 主题 | 格言 |
|---|---|---|---|
| s01 | s01_agent_loop.py |
Agent 循环 | "One loop & Bash is all you need" |
| s02 | s02_tool_use.py |
工具使用 | "Adding a tool means adding one handler" |
| s03 | s03_todo_write.py |
计划能力 | "An agent without a plan drifts" |
| s04 | s04_subagent.py |
子 Agent | "Break big tasks down; each subtask gets a clean context" |
| s05 | s05_skill_loading.py |
技能加载 | "Load knowledge when you need it, not upfront" |
| s06 | s06_context_compact.py |
上下文压缩 | "Context will fill up; you need a way to make room" |
| s07 | s07_task_system.py |
任务系统 | "Break big goals into small tasks, order them, persist to disk" |
| s08 | s08_background_tasks.py |
后台任务 | "Run slow operations in the background; the agent keeps thinking" |
| s09 | s09_agent_teams.py |
Agent 团队 | "When the task is too big for one, delegate to teammates" |
| s10 | s10_team_protocols.py |
团队协议 | "Teammates need shared communication rules" |
| s11 | s11_autonomous_agents.py |
自主 Agent | "Teammates scan the board and claim tasks themselves" |
| s12 | s12_worktree_task_isolation.py |
Worktree 隔离 | "Each works in its own directory, no interference" |
2.2 学习路径图
┌─────────────────────────────────────────────────────────────────────────┐
│ 12 Sessions Learning Path │
├─────────────────────────────────────────────────────────────────────────┤
│ │
│ Phase 1: 基础架构 (s01-s03) │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ s01: Agent Loop │ │
│ │ └── 理解基本循环:调用 API → 处理响应 → 工具调用 → 循环 │ │
│ │ │ │ │
│ │ ▼ │ │
│ │ s02: Tool Use │ │
│ │ └── 添加工具:每个工具一个处理器 │ │
│ │ │ │ │
│ │ ▼ │ │
│ │ s03: Todo/Planning │ │
│ │ └── 计划能力:Agent 没有计划就会漂移 │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ │
│ Phase 2: 上下文管理 (s04-s06) │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ s04: Subagent │ │
│ │ └── 分解任务:每个子任务获得干净的上下文 │ │
│ │ │ │ │
│ │ ▼ │ │
│ │ s05: Skill Loading │ │
│ │ └── 按需加载:需要时加载知识,而不是预先加载 │ │
│ │ │ │ │
│ │ ▼ │ │
│ │ s06: Context Compact │ │
│ │ └── 上下文压缩:上下文会满,需要腾出空间 │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ │
│ Phase 3: 高级功能 (s07-s09) │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ s07: Task System │ │
│ │ └── 任务系统:分解目标、排序、持久化 │ │
│ │ │ │ │
│ │ ▼ │ │
│ │ s08: Background Tasks │ │
│ │ └── 后台任务:慢操作后台运行,Agent 继续思考 │ │
│ │ │ │ │
│ │ ▼ │ │
│ │ s09: Agent Teams │ │
│ │ └── Agent 团队:任务太大时,委托给队友 │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ │
│ Phase 4: 自主协作 (s10-s12) │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ s10: Team Protocols │ │
│ │ └── 团队协议:队友需要共享的通信规则 │ │
│ │ │ │ │
│ │ ▼ │ │
│ │ s11: Autonomous Agents │ │
│ │ └── 自主 Agent:队友扫描看板并自行认领任务 │ │
│ │ │ │ │
│ │ ▼ │ │
│ │ s12: Worktree Isolation │ │
│ │ └── Worktree 隔离:每个在自己的目录工作,互不干扰 │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────┘
三、核心架构模式
3.1 Agent Loop(会话 1)
最基础的 Agent 循环:
def agent_loop(messages):
"""核心 Agent 循环:一个循环 + Bash 就足够"""
while True:
# 1. 调用 LLM
response = client.messages.create(
model=MODEL,
system=SYSTEM,
messages=messages,
tools=TOOLS,
)
# 2. 添加助手响应到历史
messages.append({"role": "assistant", "content": response.content})
# 3. 检查是否有工具调用
if response.stop_reason == "tool_use":
# 4. 执行工具
tool_results = execute_tools(response.content)
# 5. 添加工具结果
messages.append({"role": "user", "content": tool_results})
# 6. 循环继续
continue
else:
# 7. 没有工具调用,返回文本
return response.content
核心概念: - One Loop:一个循环处理所有交互 - Bash is All You Need:所有工具都可以用 Bash 命令实现
3.2 Tool Use(会话 2)
工具系统的核心模式:
@dataclass
class Tool:
"""工具基类"""
name: str # 工具名称
description: str # 工具描述
input_schema: dict # JSON Schema 输入定义
def to_dict(self) -> dict:
"""转换为 Claude API 格式"""
return {
"name": self.name,
"description": self.description,
"input_schema": self.input_schema,
}
async def execute(self, **kwargs) -> str:
"""执行工具"""
raise NotImplementedError
格言:"Adding a tool means adding one handler"(添加一个工具就是添加一个处理器)
3.3 Todo/Planning(会话 3)
计划系统的实现:
class TodoWrite(Tool):
"""Todo 写入工具"""
name = "TodoWrite"
description = "Write todos to track progress"
input_schema = {
"type": "object",
"properties": {
"todos": {
"type": "array",
"items": {
"type": "object",
"properties": {
"content": {"type": "string"},
"status": {"type": "string", "enum": ["pending", "in_progress", "completed"]},
}
}
}
}
}
async def execute(self, todos: list) -> str:
self.agent.todos = todos
return f"Updated {len(todos)} todos"
格言:"An agent without a plan drifts"(没有计划的 Agent 会漂移)
3.4 Subagent(会话 4)
子 Agent 模式:
async def dispatch_subagent(task: str, context: dict) -> str:
"""派发子 Agent 处理任务"""
# 1. 构建干净的上下文
subagent_messages = [
{"role": "user", "content": f"Task: {task}\nContext: {context}"}
]
# 2. 创建新的 Agent 实例
subagent = Agent(
model=MODEL,
system=SUBAGENT_SYSTEM,
tools=SUBAGENT_TOOLS,
)
# 3. 执行子任务
result = await subagent.run(subagent_messages)
# 4. 返回结果
return result
格言:"Break big tasks down; each subtask gets a clean context"(分解大任务;每个子任务获得干净的上下文)
3.5 Skill Loading(会话 5)
技能系统结构:
skills/
├── agent-builder/
│ └── SKILL.md # Agent 构建技能
├── code-review/
│ └── SKILL.md # 代码审查技能
├── mcp-builder/
│ └── SKILL.md # MCP 构建技能
└── pdf/
└── SKILL.md # PDF 处理技能
SKILL.md 格式:
---
name: skill-name
description: When to trigger, what it does
---
# Skill Instructions
## Purpose
What this skill does...
## Instructions
How to use this skill...
格言:"Load knowledge when you need it, not upfront"(需要时加载知识,而不是预先加载)
3.6 Context Compact(会话 6)
上下文压缩机制:
class MessageHistory:
"""消息历史管理"""
def __init__(self, context_window_tokens: int):
self.messages = []
self.total_tokens = 0
self.context_window_tokens = context_window_tokens
def truncate(self) -> None:
"""当上下文超限时压缩"""
while self.total_tokens > self.context_window_tokens:
# 1. 移除最旧的消息
removed = self.messages.pop(0)
# 2. 更新 token 计数
self.total_tokens -= count_tokens(removed)
# 3. 添加压缩通知
self.messages.insert(0, {
"role": "user",
"content": "[Earlier messages truncated for context limit]"
})
# 4. 只保留一条压缩通知
break
格言:"Context will fill up; you need a way to make room"(上下文会满,需要腾出空间)
3.7 Task System(会话 7)
任务系统实现:
class TaskManager:
"""任务管理器"""
def __init__(self, storage_path: Path):
self.storage_path = storage_path
self.tasks = self._load_tasks()
def add_task(self, task: Task) -> None:
"""添加任务"""
self.tasks.append(task)
self._save_tasks()
def get_next_task(self) -> Optional[Task]:
"""获取下一个待执行任务"""
pending = [t for t in self.tasks if t.status == "pending"]
if pending:
return pending[0]
return None
def update_task(self, task_id: str, status: str) -> None:
"""更新任务状态"""
for task in self.tasks:
if task.id == task_id:
task.status = status
self._save_tasks()
格言:"Break big goals into small tasks, order them, persist to disk"(分解目标、排序、持久化)
3.8 Background Tasks(会话 8)
后台任务执行:
import asyncio
class BackgroundTaskManager:
"""后台任务管理器"""
def __init__(self):
self.background_tasks: dict[str, asyncio.Task] = {}
async def start_background_task(self, task_id: str, coro) -> str:
"""启动后台任务"""
task = asyncio.create_task(coro)
self.background_tasks[task_id] = task
return f"Background task {task_id} started"
async def check_task_status(self, task_id: str) -> str:
"""检查任务状态"""
task = self.background_tasks.get(task_id)
if task is None:
return f"Task {task_id} not found"
if task.done():
return f"Task {task_id} completed: {task.result()}"
return f"Task {task_id} still running"
格言:"Run slow operations in the background; the agent keeps thinking"(后台运行慢操作;Agent 继续思考)
3.9 Agent Teams(会话 9)
Agent 团队协作:
class AgentTeam:
"""Agent 团队"""
def __init__(self, lead_agent: Agent, specialist_agents: dict[str, Agent]):
self.lead = lead_agent
self.specialists = specialist_agents
async def delegate(self, task_type: str, task: str) -> str:
"""委托任务给专家 Agent"""
specialist = self.specialists.get(task_type)
if specialist:
return await specialist.run(task)
return await self.lead.run(task)
# 创建团队
team = AgentTeam(
lead_agent=Agent(role="lead"),
specialist_agents={
"code": Agent(role="coder"),
"review": Agent(role="reviewer"),
"test": Agent(role="tester"),
}
)
格言:"When the task is too big for one, delegate to teammates"(任务太大时,委托给队友)
3.10 Team Protocols(会话 10)
团队通信协议:
class TeamProtocol:
"""团队协议"""
# 消息类型
TASK_ASSIGNMENT = "task_assignment"
STATUS_UPDATE = "status_update"
RESULT_REPORT = "result_report"
@staticmethod
def create_message(msg_type: str, sender: str, receiver: str, content: dict) -> dict:
"""创建标准消息"""
return {
"type": msg_type,
"sender": sender,
"receiver": receiver,
"content": content,
"timestamp": datetime.now().isoformat(),
}
@staticmethod
def parse_message(message: dict) -> tuple[str, str, dict]:
"""解析消息"""
return message["type"], message["sender"], message["content"]
格言:"Teammates need shared communication rules"(队友需要共享的通信规则)
3.11 Autonomous Agents(会话 11)
自主 Agent 模式:
class AutonomousAgent:
"""自主 Agent"""
def __init__(self, name: str, skills: list[str]):
self.name = name
self.skills = skills
self.claimed_tasks: list[str] = []
async def scan_task_board(self, board: TaskBoard) -> Optional[Task]:
"""扫描任务看板,寻找可认领的任务"""
for task in board.get_available_tasks():
if self._can_handle(task):
return task
return None
async def claim_task(self, task: Task) -> bool:
"""认领任务"""
if self._can_handle(task):
self.claimed_tasks.append(task.id)
task.assignee = self.name
return True
return False
def _can_handle(self, task: Task) -> bool:
"""检查是否能处理该任务"""
return any(skill in task.required_skills for skill in self.skills)
格言:"Teammates scan the board and claim tasks themselves"(队友扫描看板并自行认领任务)
3.12 Worktree Isolation(会话 12)
Worktree 隔离机制:
class WorktreeManager:
"""Worktree 管理器"""
def __init__(self, repo_path: Path):
self.repo_path = repo_path
self.worktrees: dict[str, Path] = {}
async def create_worktree(self, agent_name: str, branch: str) -> Path:
"""为 Agent 创建独立的 worktree"""
worktree_path = self.repo_path / f".worktrees/{agent_name}"
# 创建 git worktree
await run_command(
f"git worktree add {worktree_path} -b {branch}"
)
self.worktrees[agent_name] = worktree_path
return worktree_path
async def remove_worktree(self, agent_name: str) -> None:
"""移除 Agent 的 worktree"""
worktree_path = self.worktrees.get(agent_name)
if worktree_path:
await run_command(f"git worktree remove {worktree_path}")
del self.worktrees[agent_name]
格言:"Each works in its own directory, no interference"(每个在自己的目录工作,互不干扰)
四、项目结构
learn-claude-code/
├── agents/ # 12 个会话代码
│ ├── s01_agent_loop.py
│ ├── s02_tool_use.py
│ ├── s03_todo_write.py
│ ├── s04_subagent.py
│ ├── s05_skill_loading.py
│ ├── s06_context_compact.py
│ ├── s07_task_system.py
│ ├── s08_background_tasks.py
│ ├── s09_agent_teams.py
│ ├── s10_team_protocols.py
│ ├── s11_autonomous_agents.py
│ └── s12_worktree_task_isolation.py
├── skills/ # 技能目录
│ ├── agent-builder/
│ ├── code-review/
│ ├── mcp-builder/
│ └── pdf/
├── docs/ # 文档
│ ├── en/ # 英文
│ ├── zh/ # 中文
│ └── ja/ # 日文
├── README.md # 英文 README
├── README-zh.md # 中文 README
├── README-ja.md # 日文 README
├── requirements.txt # Python 依赖
└── package.json # Node.js 依赖
五、依赖与技术栈
5.1 Python 依赖
anthropic>=0.25.0
python-dotenv>=1.0.0
5.2 语言分布
| 语言 | 比例 | 用途 |
|---|---|---|
| TypeScript | 59.9% | Web 界面、工具 |
| Python | 38.9% | Agent 实现 |
| CSS | 1.8% | 样式 |
| JavaScript | 0.02% | 脚本 |
六、与 Claude Code 的对比
6.1 架构相似性
| 特性 | Learn-Claude-Code | Claude Code |
|---|---|---|
| Agent Loop | ✅ 教授核心模式 | ✅ 内部实现 |
| Tool System | ✅ 自定义实现 | ✅ MCP 工具 |
| Context Management | ✅ 手动压缩 | ✅ 自动压缩 |
| Skills | ✅ 简化版 | ✅ 完整 SKILL.md |
| Subagents | ✅ 教授概念 | ✅ Agent 工具 |
| Task System | ✅ 基础实现 | ✅ Todo 工具 |
| Background Tasks | ✅ 教授概念 | ✅ 后台运行 |
6.2 学习价值
| 学习点 | 说明 |
|---|---|
| 理解原理 | 理解 Claude Code 如何工作 |
| 自定义 Agent | 构建自己的 Agent 框架 |
| 最佳实践 | 学习 Harness 工程模式 |
| 调试能力 | 更好地理解 Agent 行为 |
七、快速开始
7.1 安装
# 克隆仓库
git clone https://github.com/shareAI-lab/learn-claude-code.git
cd learn-claude-code
# 安装 Python 依赖
pip install -r requirements.txt
# 配置 API Key
export ANTHROPIC_API_KEY=your_api_key
7.2 运行示例
# 运行第一个会话
python agents/s01_agent_loop.py
# 运行第二个会话
python agents/s02_tool_use.py
# 依次运行所有会话...
参考资源
- GitHub: https://github.com/shareAI-lab/learn-claude-code
- 官网: https://learn.shareai.run
- 作者: https://github.com/CrazyBoyM
- 组织: https://github.com/shareAI-lab
报告生成时间:2026-03-27