本教程基于 shareAI-lab/learn-claude-code 演变而来。
https://github.com/YYHDBL/MyCodeAgent 项目Trace 追踪给了我很大启发。
核心特色:Agent 运行可视化日志追踪
本教程通过完整的日志追踪系统,帮助读者深入理解 Agent 的每个执行步骤:
- 📤 发送消息:发送给大模型的消息列表内容。
- 📥 接收响应:大模型的响应内容和结构。
- 🔧 工具调用:调用了哪些工具?工具执行结果如何?
- 📚 技能使用:使用了哪些技能?何时加载的?
- 🤖 子 Agent 协作:subAgent 如何运行?返回了什么结果?
- 🗜️ 上下文压缩:何时进行消息压缩?压缩了哪些数据?
- 📨 团队协作:不同子 Agent 之间传递了哪些数据?
所有这些信息都通过HTML 追踪报告清晰呈现,让 Agent 的"黑盒"变得透明可观测!!!
快速预览HTML追踪报告: all_logs/01_agent_loop/Agent loop log.pdf
新功能 | 调试利器
每个 agent 会话自动生成浏览器可读的 HTML 追踪报告,实时记录:
- 完整执行链路 - 每步的模型调用、工具使用、token 消耗
- 子 agent 调用栈 - 嵌套 subagent 的完整上下文和返回值
- 上下文压缩追踪 - Compact 操作的触发时机和压缩效果
- 会话统计面板 - 总步骤、工具调用次数、总 token 使用量
参考日志: all_logs/01_agent_loop/Agent loop log.pdf
日志保存至 logs/traces/trace-{session-id}.html,浏览器打开即可查看完整运行过程。
Scan with Wechat to fellow us,
or fellow on X: shareAI-Lab
THE AGENT PATTERN
=================
User --> messages[] --> LLM --> response
|
stop_reason == "tool_use"?
/ \
yes no
| |
execute tools return text
append results
loop back -----------------> messages[]
That's the minimal loop. Every AI coding agent needs this loop.
Production agents add policy, permissions, and lifecycle layers.
12 progressive sessions, from a simple loop to isolated autonomous execution. Each session adds one mechanism. Each mechanism has one motto.
s01 "One loop & Bash is all you need" — one tool + one loop = an agent
s02 "Adding a tool means adding one handler" — the loop stays the same; new tools register into the dispatch map
s03 "An agent without a plan drifts" — list the steps first, then execute; completion doubles
s04 "Break big tasks down; each subtask gets a clean context" — subagents use independent messages[], keeping the main conversation clean
s05 "Load knowledge when you need it, not upfront" — inject via tool_result, not the system prompt
s06 "Context will fill up; you need a way to make room" — three-layer compression strategy for infinite sessions
s07 "Break big goals into small tasks, order them, persist to disk" — a file-based task graph with dependencies, laying the foundation for multi-agent collaboration
s08 "Run slow operations in the background; the agent keeps thinking" — daemon threads run commands, inject notifications on completion
s09 "When the task is too big for one, delegate to teammates" — persistent teammates + async mailboxes
s10 "Teammates need shared communication rules" — one request-response pattern drives all negotiation
s11 "Teammates scan the board and claim tasks themselves" — no need for the lead to assign each one
s12 "Each works in its own directory, no interference" — tasks manage goals, worktrees manage directories, bound by ID
def agent_loop(messages):
while True:
response = client.messages.create(
model=MODEL, system=SYSTEM,
messages=messages, tools=TOOLS,
)
messages.append({"role": "assistant",
"content": response.content})
if response.stop_reason != "tool_use":
return
results = []
for block in response.content:
if block.type == "tool_use":
output = TOOL_HANDLERS[block.name](**block.input)
results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": output,
})
messages.append({"role": "user", "content": results})Every session layers one mechanism on top of this loop -- without changing the loop itself.
This repository is a 0->1 learning project for building a nano Claude Code-like agent. It intentionally simplifies or omits several production mechanisms:
- Full event/hook buses (for example PreToolUse, SessionStart/End, ConfigChange).
s12 includes only a minimal append-only lifecycle event stream for teaching. - Rule-based permission governance and trust workflows
- Session lifecycle controls (resume/fork) and advanced worktree lifecycle controls
- Full MCP runtime details (transport/OAuth/resource subscribe/polling)
Treat the team JSONL mailbox protocol in this repo as a teaching implementation, not a claim about any specific production internals.
git clone https://github.com/shareAI-lab/learn-claude-code
cd learn-claude-code
pip install -r requirements.txt
cp .env.example .env # Edit .env with your ANTHROPIC_API_KEY
python agents/s01_agent_loop.py # Start here
python agents/s12_worktree_task_isolation.py # Full progression endpoint
python agents/s_full.py # Capstone: all mechanisms combinedInteractive visualizations, step-through diagrams, source viewer, and documentation.
cd web && npm install && npm run dev # http://localhost:3000Phase 1: THE LOOP Phase 2: PLANNING & KNOWLEDGE
================== ==============================
s01 The Agent Loop [1] s03 TodoWrite [5]
while + stop_reason TodoManager + nag reminder
| |
+-> s02 Tool Use [4] s04 Subagents [5]
dispatch map: name->handler fresh messages[] per child
|
s05 Skills [5]
SKILL.md via tool_result
|
s06 Context Compact [5]
3-layer compression
Phase 3: PERSISTENCE Phase 4: TEAMS
================== =====================
s07 Tasks [8] s09 Agent Teams [9]
file-based CRUD + deps graph teammates + JSONL mailboxes
| |
s08 Background Tasks [6] s10 Team Protocols [12]
daemon threads + notify queue shutdown + plan approval FSM
|
s11 Autonomous Agents [14]
idle cycle + auto-claim
|
s12 Worktree Isolation [16]
task coordination + optional isolated execution lanes
[N] = number of tools
learn-claude-code/
|
|-- agents/ # Python reference implementations (s01-s12 + s_full capstone)
|-- docs/{en,zh,ja}/ # Mental-model-first documentation (3 languages)
|-- web/ # Interactive learning platform (Next.js)
|-- skills/ # Skill files for s05
+-- .github/workflows/ci.yml # CI: typecheck + build
Mental-model-first: problem, solution, ASCII diagram, minimal code. Available in English | 中文 | 日本語.
| Session | Topic | Motto |
|---|---|---|
| s01 | The Agent Loop | One loop & Bash is all you need |
| s02 | Tool Use | Adding a tool means adding one handler |
| s03 | TodoWrite | An agent without a plan drifts |
| s04 | Subagents | Break big tasks down; each subtask gets a clean context |
| s05 | Skills | Load knowledge when you need it, not upfront |
| s06 | Context Compact | Context will fill up; you need a way to make room |
| s07 | Tasks | Break big goals into small tasks, order them, persist to disk |
| s08 | Background Tasks | Run slow operations in the background; the agent keeps thinking |
| s09 | Agent Teams | When the task is too big for one, delegate to teammates |
| s10 | Team Protocols | Teammates need shared communication rules |
| s11 | Autonomous Agents | Teammates scan the board and claim tasks themselves |
| s12 | Worktree + Task Isolation | Each works in its own directory, no interference |
After the 12 sessions you understand how an agent works inside out. Two ways to put that knowledge to work:
npm i -g @shareai-lab/kode
Skill & LSP support, Windows-ready, pluggable with GLM / MiniMax / DeepSeek and other open models. Install and go.
GitHub: shareAI-lab/Kode-cli
The official Claude Code Agent SDK communicates with a full CLI process under the hood -- each concurrent user means a separate terminal process. Kode SDK is a standalone library with no per-user process overhead, embeddable in backends, browser extensions, embedded devices, or any runtime.
GitHub: shareAI-lab/Kode-agent-sdk
The agent this repo teaches is use-and-discard -- open a terminal, give it a task, close when done, next session starts blank. That is the Claude Code model.
OpenClaw proved another possibility: on top of the same agent core, two mechanisms turn the agent from "poke it to make it move" into "it wakes up every 30 seconds to look for work":
- Heartbeat -- every 30s the system sends the agent a message to check if there is anything to do. Nothing? Go back to sleep. Something? Act immediately.
- Cron -- the agent can schedule its own future tasks, executed automatically when the time comes.
Add multi-channel IM routing (WhatsApp / Telegram / Slack / Discord, 13+ platforms), persistent context memory, and a Soul personality system, and the agent goes from a disposable tool to an always-on personal AI assistant.
claw0 is our companion teaching repo that deconstructs these mechanisms from scratch:
claw agent = agent core + heartbeat + cron + IM chat + memory + soul
learn-claude-code claw0
(agent runtime core: (proactive always-on assistant:
loop, tools, planning, heartbeat, cron, IM channels,
teams, worktree isolation) memory, soul personality)
MIT
The model is the agent. Our job is to give it tools and stay out of the way.
