Skip to content

Claude Code From Scratch

Build your own Claude Code from scratch. Claude Code 开源了 50 万行代码,读不动?用 ~5000 行 TypeScript / Python 从零复现核心架构,11 章分步教程带你理解 coding agent 精髓

Install

$git clone https://github.com/Windy3f3f3f3f/claude-code-from-scratch

Install command taken from the project's README or registry entry. Always review code before running it.

Claude Code From Scratch

一步步,从零手写一个 Claude Code

📘 在线阅读教程 →   |   📘 Read Tutorial (English) →   |   English

📖 想深入了解原理? 姊妹项目 How Claude Code Works — 12 篇专题,33 万字,从源码级别深度解析 Claude Code 架构


⚖️ 声明 / Disclaimer:这是一个从零手写 Claude Code 的学习项目,照着 Claude Code 的公开可观察行为和通用 Agent 写法来做,不保证和 Claude Code 真实内部实现一致。"Claude Code" 是 Anthropic 的商标,本项目和 Anthropic 没有关联。

Claude Code 有几十万行代码,读不动?

本项目用 约 5000 行代码(TypeScript 和 Python 两个版本分别写),从零手写 Claude Code 的核心:Agent Loop、13 个工具(含并行执行 + 流式早期启动)、4 层上下文压缩、语义记忆召回、技能系统、多 Agent、MCP 集成。参照的是 Claude Code 的公开可观察行为,每一步都对着它讲清差异在哪。

这不是 demo,是一份分步教程——13 章内容,跟着动手写几千行代码,从零理解一个 Coding Agent 的工作原理。而且每个代码章都能一条命令跑起来、不用 API key(见下方「每章代码都能跑」一节)。读完你就理解了 coding agent 的核心运作机制,无需啃那几十万行代码。

📖 分步教程

13 章内容,分两个阶段——先构建一个可用的 Coding Agent,再逐步添加进阶能力。每章都贴能跑的真实代码 + 与 Claude Code 的架构对照:

章节 内容 架构对照视角
Phase 1: 构建一个可用的 Coding Agent
1. Agent Loop 核心循环:调用 LLM → 执行工具 → 重复 agent.ts ↔ query.ts
2. 工具系统 13 个工具 + mtime 防护 + 延迟加载 tools.ts ↔ Tool.ts + 66 工具
3. System Prompt 提示词工程 + @include 语法 prompt.ts ↔ prompts.ts
4. CLI 与会话 REPL、Ctrl+C、会话持久化 cli.ts ↔ cli.tsx
5. 流式输出 双后端 + 流式工具执行 + 并行执行 agent.ts ↔ api/claude.ts
6. 权限与安全 5 模式 + 声明式规则 + 危险检测 tools.ts ↔ permissions/ (52KB)
7. 上下文管理 4 层压缩 + 大结果持久化 agent.ts ↔ compact/
Phase 2: 进阶能力
8. 记忆系统 4 类型记忆 + 语义召回 + 异步预取 memory.ts ↔ memory.ts
9. 技能系统 技能发现 + inline/fork 双模式 skills.ts ↔ SkillTool/
10. Plan Mode 只读规划 + 4 选项审批工作流 agent.ts ↔ EnterPlanMode
11. 多 Agent Sub-Agent fork-return 多 Agent 架构 subagent.ts ↔ AgentTool/
12. MCP 集成 JSON-RPC over stdio 连接外部工具 mcp.ts ↔ mcpClient.ts
13. 架构对比 完整对比 + 扩展方向 全局
14. 功能测试 22 项手动测试覆盖全部功能 test/

▶ 每章代码都能跑(无需 API key)

读代码最怕读不懂又跑不起来,改一行也不知道对不对。所以每个代码章都配了一份能单独跑的最小实现:一条命令、不用 API key,就能看它真的转起来。

Similar plugs

Orca is the ADE for working with a fleet of parallel agents. Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.

CLI proxy that reduces LLM token consumption by 60-90% on common dev commands. Single Rust binary, zero dependencies

Documented system prompts from Anthropic - Claude Fable 5.1, Opus 5.5, Claude Design, Claude Code. OpenAI - ChatGPT GPT-6-Astra, Codex. Google - Gemini 3.8 Flash, 3.1 Pro,…

Wrap Antigravity, ChatGPT Codex, Claude Code, Grok Build, Muse Code, Devin as an OpenAI/Gemini/Claude/Codex compatible API service, allowing you to enjoy the free Gemini…