按下回车键之后After You Press Enter
从按键到回答 —— Claude Code 内部的一场接力赛From keypress to answer — the relay race inside Claude Code
什么是 Claude Code?What is Claude Code?
Claude Code 是一个命令行工具command-line tool,让你可以和一个能读写、运行代码的 AI 对话。你输入消息,Claude 来完成工作。Claude Code is a 命令行工具command-line tool that lets you talk to an AI that can read, write, and run code on your computer. You type a message, and Claude does the work.
它不只是聊天机器人。它可以真正做事情 —— 打开文件、运行程序、编辑代码、搜索整个项目。把它想象成一个坐在你终端terminal里的技术助手。It is not just a chatbot. It can actually do things — open files, run programs, edit your code, and search across your entire project. Think of it as a skilled assistant sitting inside your 终端terminal.
自然语言交流Talk Naturally
像说话一样输入"修复登录 bug"或"添加暗色模式开关",不需要任何特殊语法。Type plain English like "fix the login bug" or "add a dark mode toggle." No special syntax needed.
读取你的文件Read Your Files
Claude 可以打开和读取项目中的任何文件,在修改之前先理解你的代码。Claude can open and read any file in your project to understand your code before making changes.
编辑你的代码Edit Your Code
它直接在你的文件中编写和修改代码,而不只是在聊天窗口里。真实的改动,真实的代码。It writes and edits code directly in your files, not just in a chat window. Real changes, real code.
运行命令Run Commands
它可以运行测试、安装依赖包,以及执行你电脑能处理的任何Shell 命令shell command。It can run tests, install packages, and execute any Shell 命令shell command your computer can handle.
从你按下回车键到看到回复的那一刻,Claude Code 内部已经跑完了一整场接力赛。每个选手接过接力棒,完成自己的任务,然后传给下一个人。让我们用慢镜头来观看这场比赛。Between the moment you press Enter and the moment you see a response, an entire relay race happens inside Claude Code. Each runner grabs the baton, does their job, and passes it on. Let's watch that race in slow motion.
消息的旅程The Journey of a Message
逐步了解你的消息是如何从键盘传递到最终回答的。点击"下一步"来推进。Walk through each step to see exactly how your message travels from your keyboard to the final answer. Click "Next Step" to advance.
代码解读:程序入口Code Translation: The Entry Point
这是你输入 claude 时最先运行的代码 —— 来自入口文件entry point的真实源码。左边是代码,右边是通俗解释。Here is the very first thing that runs when you type claude — real code from the 入口文件entry point file. Read the code on the left, and the plain English translation on the right.
async function main(): Promise<void> {
const args = process.argv.slice(2);
if (args[0] === '--version') {
console.log(MACRO.VERSION);
return;
}
// For all other paths, load the
// startup profiler and continue...
await launchRepl(config);
}
第 1 行:定义主函数function —— 一切从这里开始。Line 1: Define the main 函数function — this is where everything starts.
第 2 行:获取你在 claude 后面输入的内容。这些就是你的参数arguments。Line 2: Grab whatever you typed after claude. These are your 参数arguments.
第 4-7 行:快捷通道:如果你只输入了 claude --version,打印版本号然后立即退出。不需要加载整个应用。Lines 4-7: Quick shortcut: if you only typed claude --version, print the version number and stop immediately. No need to load the whole app.
第 10-11 行:其他所有情况,加载完整应用并启动交互式 REPLREPL —— 也就是来回对话的循环。Lines 10-11: For everything else, load the full application and launch the interactive REPLREPL — the back-and-forth conversation loop.
这种"先检查快捷出口再加载全部"的模式,就是为什么 claude --version 能瞬间响应,而 claude 需要花一点时间来加载 45 个工具tools、103 个命令和完整的用户界面UI。This pattern — checking for quick exits before loading everything — is why claude --version responds instantly, while claude takes a moment to load 45 工具tools, 103 commands, and the full 用户界面UI.
查询循环The Query Loop
应用加载完成后,一切都围绕一个核心概念运转:QueryEngineQueryEngine在一个循环中工作。它不断在 Claude 和你的电脑之间来回协调,直到任务完成。Once the app is loaded, everything revolves around one core idea: the QueryEngineQueryEngine works in a loop. It keeps going back and forth between Claude and your computer until the job is done.
你的消息加上一大堆隐藏指令(系统提示词system prompt)会一起发送给 Claude 的 APIAPI。Your message, plus a huge set of hidden instructions (the 系统提示词system prompt), are sent to Claude's APIAPI.
Claude 不一定直接回答,它可能会说:"我需要先读取一个文件"或"让我运行这个命令"。这就叫工具调用tool call。Instead of answering directly, Claude might say: "I need to read a file first" or "Let me run this command." This is called a 工具调用tool call.
Claude Code 找到合适的工具(比如 FileReadTool 或 BashTool),运行它,然后收集结果。Claude Code finds the right tool (like FileReadTool or BashTool), runs it, and collects the result.
工具的执行结果被发回给 Claude。现在 Claude 有了更多信息,可以继续思考了。The tool result is sent back to Claude. Now Claude has more information and can think again.
Claude 可能需要 2 次、5 次甚至 20 轮工具调用。每一轮叫做一次智能体轮次agentic turn。循环会一直持续,直到 Claude 给出最终答案。Claude might need 2, 5, or even 20 rounds of tool use. Each round is called an 智能体轮次agentic turn. The loop continues until Claude has a final answer.
复杂的任务需要多个步骤。让 Claude "修一个 bug"可能需要读取文件、理解错误、编辑代码、运行测试。每个步骤都是循环中的一次往返。Complex tasks need multiple steps. Asking Claude to "fix a bug" might require reading the file, understanding the error, editing the code, and running the tests. Each step is one trip through the loop.
检验你的理解Check Your Understanding
1. 你输入 claude --version,背后发生了什么?1. You type claude --version. What happens behind the scenes?
2. 你让 Claude "读取 3 个文件并总结它们"。QueryEngine 可能调用 Claude API 多少次?2. You ask Claude to "read 3 files and summarize them." How many times might the QueryEngine call the Claude API?
3. 朋友说"QueryEngine 只是把消息发给 API"。为什么这个说法不完整?3. A friend says "the QueryEngine just sends messages to the API." Why is that incomplete?
认识演员阵容Meet the Cast
让 Claude Code 运转的五大部门 —— 就像一个电影制作团队The five departments that make Claude Code work — like a movie production crew
制作团队The Production Crew
Claude Code 不是一个庞大的单体程序。它更像一个完整的电影制片厂,每个专业部门各负责制作的不同环节。以下是五个主要角色。Claude Code is not one giant program. It is an entire movie studio with specialized departments, each handling a different part of the production. Here are the five main players.
掌控全局。决定如何处理你的消息,组装系统提示词system prompt,调用 APIAPI,并分配工具tool调用。Runs the show. Decides what to do with your message, assembles the 系统提示词system prompt, calls the APIAPI, and dispatches 工具tool calls.
每个工具专精一件事。BashTool 运行命令,FileReadTool 打开文件,FileEditTool 修改代码。它们就是执行导演安排的场景的演员。Each tool does one thing well. BashTool runs commands. FileReadTool opens files. FileEditTool modifies code. They are the actors who perform the scenes the director calls for.
与 Anthropic 服务器通信的 API 客户端、MCPMCP 连接、数据分析、OAuthOAuth 身份认证。它们处理繁琐的底层工作,让导演可以专注于导演。The API client that talks to Anthropic servers, MCPMCP connections, analytics, OAuthOAuth authentication. They handle the messy plumbing so the director can focus on directing.
一个跟踪所有内容的共享空间:你的设置、权限、加载了哪些工具、哪些插件plugins处于活跃状态。使用一个叫 ZustandZustand 的库library来构建。One shared place where everything is tracked: your settings, permissions, which tools are loaded, which 插件plugins are active. Built with a 库library called ZustandZustand.
将纯文本变成漂亮的界面,包含进度条、加载动画、权限对话框和格式化代码。用 ReactReact 在终端terminal中运行 —— 共 146 个组件components。Turns plain text into a beautiful interface with progress bars, spinners, permission dialogs, and formatted code. Built with ReactReact running inside a 终端terminal — 146 组件components in total.
制片厂地图The Studio Map
每个部门都有自己的办公区。这是 Claude Code 源代码source code的目录directory结构 —— 每个文件夹就是一个部门。Every department has its own wing of the building. Here is the 目录directory structure of Claude Code's 源代码source code — each folder is a department.
整个代码库有超过 500 个 TypeScriptTypeScript 文件。但得益于良好的组织,一个开发工具的人永远不需要碰 UI 代码,修 UI bug 的人也不需要去读 API 客户端代码。The full codebase has over 500 TypeScriptTypeScript files. But thanks to good organization, a developer working on a tool never needs to touch the UI code, and someone fixing a display bug never needs to read the API client.
片场的一天A Day on Set
看看各部门在处理一个真实请求时是如何互相交流的。点击"下一条消息"来逐步推进对话。Watch the departments talk to each other as they handle a real request. Click "Next Message" to step through the conversation.
代码解读:共享剧本Code Translation: The Shared Script
还记得状态部门 —— 那个共享的信息源吗?这是它在源代码source code中的简化版。这段代码来自一个叫 AppStateStore.tsAppStateStore.ts 的文件。Remember the State department — the shared source of truth? Here is a simplified version of what it actually looks like in the 源代码source code. This is from a file called AppStateStore.tsAppStateStore.ts.
type AppState = {
settings: SettingsJson
verbose: boolean
mainLoopModel: ModelSetting
toolPermissionContext:
ToolPermissionContext
mcp: {
clients: MCPServerConnection[]
tools: Tool[]
commands: Command[]
}
plugins: {
enabled: LoadedPlugin[]
disabled: LoadedPlugin[]
}
tasks: { [taskId]: TaskState }
}
settings:你的个人配置 —— 主题、快捷键、允许的目录。所有你在设置文件settings file中配置的内容。settings: Your personal configuration — themes, keybindings, allowed directories. Everything you set in your 设置文件settings file.
verbose:一个简单的开关。开启后,Claude Code 会显示关于它在幕后做了什么的额外细节。verbose: A simple on/off flag. When on, Claude Code shows extra detail about what it is doing behind the scenes.
mainLoopModel:当前正在使用哪个 AI 模型model(比如 Sonnet 或 Opus)。mainLoopModel: Which AI 模型model is being used right now (like Sonnet or Opus).
toolPermissionContext:跟踪 Claude 被允许做什么。它能编辑文件吗?能运行命令吗?这就是权限系统。toolPermissionContext: Tracks what Claude is allowed to do. Can it edit files? Run commands? This is the permission system.
mcp:通过 MCPMCP 连接的所有外部服务 —— 连接了哪些服务器、它们提供什么工具、添加了什么命令。mcp: All external connections via MCPMCP — which servers are connected, what tools they provide, and what commands they add.
plugins:所有插件plugins的列表 —— 包括已启用的和已关闭的。plugins: A list of all 插件plugins — both the ones that are active and the ones that are turned off.
tasks:当前正在运行的所有后台任务 —— 比如一个子代理正在处理你请求的某个部分。tasks: Every background task currently running — like a sub-agent working on a separate piece of your request.
把所有信息放在一个地方,Claude Code 就避免了一个常见问题:应用的不同部分拥有不同版本的"真相"。当你授予一项权限时,工具、界面和 QueryEngineQueryEngine 都能立即看到。By keeping everything in one place, Claude Code avoids a common problem: different parts of the app having different versions of the truth. When you grant a permission, the tools, the UI, and the QueryEngineQueryEngine all see it instantly.
核心思想:关注点分离The Big Idea: Separation of Concerns
这个原则是说系统的每个部分都应该专精一件事。工具负责读取文件,服务管理连接,UI 渲染文本。谁也不会踩到别人的脚。这就是为什么 Claude Code 可以有 45 个工具、146 个 UI 组件components和 103 个命令而不会变成一团乱麻。The principle that each piece of a system should do one thing well. Tools read files. Services manage connections. The UI renders text. Nobody steps on anyone else's toes. This is why Claude Code can have 45 tools, 146 UI 组件components, and 103 commands without becoming a tangled mess.
1. 你想让 Claude Code 生成图片。哪个部门会增加新成员?1. You want Claude Code to generate images. Which department would get a new team member?
2. 有用户反馈权限对话框显示异常。开发者应该先看哪里?2. A user reports that the permission dialog looks glitchy. Where would a developer look first?
3. 为什么 Claude Code 把所有数据放在一个共享的状态存储中,而不是让每个部门自己管理?3. Why does Claude Code keep all its data in one shared State store instead of letting each department track its own?
工具系统:AI 的瑞士军刀The Tool System: AI's Swiss Army Knife
Claude 如何从"想"到"做"——以及为什么每个动作都要过一道机场安检How Claude goes from thinking to doing — and why every action passes through airport security first
什么是工具?What Are Tools?
当 Claude 说"我需要读取一个文件"或"让我来运行这条命令"时,它就是在使用工具。工具就是 Claude 从思考转向行动的桥梁。When Claude says "I need to read a file" or "Let me run this command," it is using a tool. Tools are how Claude goes from thinking to doing.
Claude Code 内置了 45 个工具,以下是主要分类:Claude Code ships with 45 tools. Here are the main categories:
BashTool
在你的电脑上运行终端命令。相当于Shell 的遥控器。Run terminal commands on your computer. Like a remote control for your shell.
文件工具File Tools
FileReadTool、FileEditTool 和 FileWriteTool 让 Claude 能读取、修改和创建你电脑上的文件。FileReadTool, FileEditTool, and FileWriteTool let Claude read, modify, and create files on your machine.
搜索工具Search Tools
GrepTool 和 GlobTool 用来搜索你的代码。可以把它想象成整个项目的 Ctrl+F。GrepTool and GlobTool search through your code. Think of it as Ctrl+F for your entire project.
网络工具Web Tools
WebFetchTool 和 WebSearchTool 让 Claude 能访问互联网,查阅文档或搜索答案。WebFetchTool and WebSearchTool let Claude access the internet to look up documentation or search for answers.
AgentTool
生成子代理——创建迷你版 Claude 并行处理任务,完成后汇报结果。Spawn sub-agents — create mini-Claudes that work on tasks in parallel, then report back.
MCPTool
通过 MCP 协议连接外部服务。就像安装插件获得额外超能力。Connect to external services through the MCP protocol. Like installing plugins for extra superpowers.
工具的设计蓝图The Tool Blueprint
每个工具都遵循完全相同的模式。这是 FileReadTool 的简化版构建方式——来自源码的真实代码:Every tool follows the exact same pattern. Here is a simplified version of how the FileReadTool is built — this is real code from the source:
export const FileReadTool = buildTool({
name: 'Read',
async description() {
return 'Reads a file from the filesystem'
},
inputSchema: () => z.object({
file_path: z.string(),
offset: z.number().optional(),
limit: z.number().optional(),
}),
async validateInput(input, context) {
// Check if file exists, validate path
},
async checkPermissions(input, context) {
// Does the user allow reading this?
},
async execute(input, context) {
// Actually read and return the file
},
})
buildTool() 是一个工厂函数——它按照严格的模板来创建工具。buildTool() is a factory function — it creates a tool following a strict template.
name 和 description 告诉 Claude 这个工具是做什么的,这样它才知道什么时候该用它。name and description tell Claude what this tool does, so it knows when to use it.
inputSchema 精确定义了工具接受哪些输入——使用一个叫 Zod 的库来拒绝无效数据。inputSchema defines exactly what inputs the tool accepts — using a library called Zod to reject bad data.
validateInput 检查输入是否合理——文件到底存不存在?validateInput checks if the inputs make sense — does the file actually exist?
checkPermissions 会问:用户允许执行这个操作吗?checkPermissions asks: is the user okay with this action?
execute 执行实际工作——但只有在验证和权限检查都通过之后才会运行。execute does the actual work — but only if validation and permissions both pass.
这套统一蓝图意味着添加新工具非常简单。你只需要填好模板——名称、描述、模式定义、验证、权限、执行——系统会处理剩下的一切。全部 45 个工具都遵循这同一结构。This shared blueprint means adding a new tool is straightforward. You fill in the template — name, description, schema, validation, permissions, execute — and the system handles the rest. All 45 tools follow this exact structure.
权限检查站The Permission Checkpoint
把它想象成机场安检。每一次工具使用——每一次文件读取、每一条命令、每一次网页搜索——都必须通过多步检查站才能运行。点击动画来看看具体过程:Think of this like airport security. Every single tool use — every file read, every command, every web search — must pass through a multi-step checkpoint before it can run. Walk through the animation to see what happens:
即使是"无害"的操作(比如读取一个文件)也要通过这个检查站。系统从不假设某个操作是安全的——它始终会检查。这就是所谓的纵深防御策略。Even "harmless" actions like reading a file go through this checkpoint. The system never assumes an action is safe — it always checks. This is called a defense-in-depth approach.
三层防护Three Layers of Protection
权限系统不只是一个简单的"是/否"门禁。它有三个独立的防护层,各自捕获不同类型的风险:The permission system is not just a single yes/no gate. It has three independent layers, each catching different kinds of risk:
在你的设置文件中预先设定的规则。例如:"始终允许读取文件"或"绝不允许删除文件的命令"。这些规则最先运行,静默执行,不会弹出对话框。Pre-set rules in your settings file. Example: "Always allow file reads" or "Never allow commands that delete files." These run first, silently, with no popup.
一个 AI 分类器,判断一条 bash 命令是否安全到可以自动运行。这个功能是受功能开关控制的,只有启用时才会激活。An AI classifier that judges whether a bash command is safe enough to run automatically. This is feature-gated, meaning it only activates when enabled.
弹出对话框,直接问你是否同意或拒绝。这是最后的安全网——如果配置规则没有覆盖,分类器也不确定,就会直接问你。The dialog box that asks YOU to approve or deny. This is the final safety net — if the config rules do not cover it and the classifier is unsure, you get asked directly.
如果没有权限系统,一个拥有 Shell 访问权限的 AI 可能会删除你的文件、发送电子邮件或修改你的系统。权限系统正是让 Claude Code 可以安全使用的关键。Without permissions, an AI with shell access could delete your files, send emails, or modify your system. The permission system is what makes Claude Code safe to use.
检验你的理解Check Your Understanding
Claude 想用 BashTool 执行命令 rm test-output.tmp 来删除一个测试文件。Claude wants to delete a test file using BashTool with the command rm test-output.tmp.
1. 接下来会发生什么?1. What happens next?
你在配置中设置了文件读取"始终允许"。Claude 尝试读取 /etc/hosts。You set "always allow" for file reads in your config. Claude tries to read /etc/hosts.
2. 会发生什么?2. What happens?
Claude 不断运行同一条 npm install 命令,每次都报相同的错误。Claude keeps running the same npm install command and it keeps failing with the same error.
3. 最好的做法是什么?3. What is the best thing to do?
4. Claude Code 的 45 个工具有什么共同点?4. What do all 45 tools in Claude Code have in common?
记忆的艺术:对抗遗忘The Art of Memory: Fighting Forgetfulness
白板不断被写满——什么会被擦掉、什么会被保留、由谁来决定The whiteboard keeps filling up — what gets erased, what gets kept, and who decides
白板难题The Whiteboard Problem
Claude 一次只能"看到"有限的文本量。这就是上下文窗口。把它想象成会议室里的一块白板:Claude 需要知道的一切都必须写在那块白板上。Claude can only "see" a limited amount of text at once. This is the context window. Think of it as a whiteboard in a meeting room: everything Claude needs to know has to fit on that whiteboard.
Claude 的白板大约能容纳 200,000 个 token(大约 15 万个英文单词)。听起来很多,但填满的速度比你想象的要快。Claude's whiteboard fits roughly 200,000 tokens (about 150,000 words). That sounds like a lot, but it fills up faster than you think.
你发的每条消息、每个工具结果、每条系统指令——它们都占用白板上的空间。单次文件读取就可能消耗数千个 token。Every message you send, every tool result, every system instruction — they all take up room on the whiteboard. A single file read can use thousands of tokens.
运行 10 条命令就能轻松消耗 50% 的空间。一个复杂的调试会话,涉及大量文件读取和工具结果,可能几分钟就把白板写满了。Running 10 commands can easily eat 50% of the space. A complex debugging session with many file reads and tool results can fill the whiteboard in minutes.
当白板快满时,Claude 就无法处理新信息了。它会开始忘记之前的上下文,难以遵循指令,并且容易犯错。When the whiteboard is nearly full, Claude cannot process new information. It starts forgetting earlier context, struggling to follow instructions, and making mistakes.
仅系统提示词就可能占用 10,000-15,000 个 token。一次大文件读取可能再增加 5,000-10,000 个。经过 10-15 轮带工具使用的来回对话后,你可能已经用掉了 80% 的容量。The system prompt alone can use 10,000-15,000 tokens. A large file read might add 5,000-10,000 more. After 10-15 back-and-forth exchanges with tool use, you could easily be at 80% capacity.
四种清理策略Four Cleanup Strategies
白板写满时,Claude Code 不会直接崩溃。它有四种释放空间的策略,按从温和到激进的顺序递进使用:Claude Code does not just crash when the whiteboard fills up. It has four strategies for freeing space, used in escalating order — from gentle to aggressive:
1. 裁剪(Snip)1. Snip
直接删除旧消息。就像从记事本上撕掉几页——信息没了,但释放了最多的空间。用于最旧的、最不相关的消息。Delete old messages entirely. Like ripping pages off a notepad — the information is gone, but you free up the most space. Used for the oldest, least relevant messages.
2. 微压缩(Microcompact)2. Microcompact
压缩大型工具结果。就像在笔记里用缩写——关键信息保留,但多余的废话被删掉了。Compress large tool results. Like using abbreviations in your notes — the key info stays, but the filler words are removed.
3. 上下文折叠(Context Collapse)3. Context Collapse
在不实际改变已存储消息的情况下,创建对话的摘要视图。就像在白板上面贴一张"太长不看"的便签。Create a summary view of the conversation without actually changing the stored messages. Like writing a TL;DR sticky note on top of the whiteboard.
4. 自动压缩(Autocompact)4. Autocompact
调用一个独立的 AI 来总结整个对话。就像请同事从头写一份会议纪要——原始讨论被浓缩版替代。Call a separate AI to summarize the entire conversation. Like asking a colleague to write meeting notes from scratch — the original discussion is replaced with a condensed version.
这些策略按顺序尝试。裁剪和微压缩快速且低成本。上下文折叠更加激进。自动压缩是核武器选项——它会重写整个对话历史。系统总是先尝试最轻量的方式。These strategies are tried in order. Snip and microcompact are quick and cheap. Context collapse is more aggressive. Autocompact is the nuclear option — it rewrites the entire conversation history. The system always tries the lightest touch first.
自动压缩何时触发?When Does Autocompact Kick In?
系统会监控白板的填充程度,当你接近上限时触发自动压缩。以下是真实的逻辑:The system monitors how full the whiteboard is and triggers autocompact when you get dangerously close to the limit. Here is the real logic:
const AUTOCOMPACT_BUFFER = 13000
const WARNING_BUFFER = 20000
function getAutoCompactThreshold(model) {
const window = getEffectiveContextWindowSize(
model
)
return window - AUTOCOMPACT_BUFFER
}
定义了两个安全余量。自动压缩缓冲区是 13,000 个 token——当你距离上限还剩 13,000 个 token 时,自动压缩就会触发。Two safety margins are defined. The autocompact buffer is 13,000 tokens — when you are within 13,000 tokens of the limit, autocompact fires.
警告缓冲区是 20,000 个 token——当你越过这个阈值时,系统开始显示空间不足的警告。The warning buffer is 20,000 tokens — when you cross this threshold, the system starts showing warnings that you are running low on space.
阈值的计算方式是:用白板总容量减去缓冲区。对于 200K token 的窗口,自动压缩在大约使用 187,000 个 token 时触发。The threshold is calculated by taking the total whiteboard size and subtracting the buffer. For a 200K-token window, autocompact fires at around 187,000 tokens used.
白板上已经写了什么?What Is Already on the Whiteboard?
在你输入第一条消息之前,白板上就已经有内容了。系统提示词像一层层蛋糕一样从六个不同的来源组装而成。点击动画来看每一层:Before you even type your first message, the whiteboard is already partially filled. The system prompt is assembled like a layer cake from six different sources. Walk through to see each layer:
CLAUDE.md——你的控制面板CLAUDE.md — Your Control Panel
CLAUDE.md 文件是你定制 Claude Code 行为的方式。它们在启动时被加载到系统提示词中,所以 Claude 每次都会遵循你的规则,不需要你重复说明。CLAUDE.md files are how YOU customize Claude Code's behavior. They are loaded into the system prompt at startup, so Claude follows your rules without you repeating them every time.
Claude Code 会在三个位置搜索 CLAUDE.md 文件:全局 ~/.claude/ 目录、项目根目录以及任何父级目录。来自所有层级的规则会合并成一套完整的指令集。Claude Code searches for CLAUDE.md files in three places: the global ~/.claude/ directory, the project root, and any parent directories. Rules from all levels are combined into a single instruction set.
CLAUDE.md 是最强大的功能之一。它让你告诉 AI 你的项目需要什么——编码风格、测试规则、部署步骤——而不需要每次会话都重复。写一次,Claude 永远遵循。CLAUDE.md is one of the most powerful features available. It lets you tell the AI what YOUR project needs — coding style, testing rules, deployment steps — without repeating yourself every session. Write it once, and Claude follows it forever.
~/.claude/ 中的规则适用于你打开的所有项目Rules in ~/.claude/ apply to every project you open
/memory 命令保存 Claude 应该跨会话记住的信息The /memory command saves facts Claude should remember across sessions
检验你的理解Check Your Understanding
你和 Claude 一起工作了一个小时。它不断忘记你之前给的指令,对项目结构也显得困惑。You have been working with Claude for an hour. It keeps forgetting instructions you gave earlier and seems confused about the project structure.
1. 很可能发生了什么?1. What is likely happening?
2. 你想让 Claude 在你的项目中始终使用 TypeScript。这条指令该放在哪里?2. You want Claude to always use TypeScript in your project. Where do you put this instruction?
Claude 说它空间不足,无法处理你的完整请求。Claude says it is running low on space and cannot process your full request.
3. 哪种恢复策略会启动?3. Which recovery strategy kicks in?
与外部世界对话Talking to the Outside World
MCP 与插件 —— 让 Claude Code 连接万物的 USB 接口MCP and Plugins — the USB ports that let Claude Code connect to anything
扩展难题The Extension Problem
Claude Code 内置了 45 个工具。但如果你还需要它操作 Notion?或者 Figma?或者公司的数据库呢?你可以等 Anthropic 为每一个服务都做适配…… 或者,你可以用插件系统。Claude Code ships with 45 built-in tools. But what if you need it to work with Notion? Or Figma? Or your company database? You could wait for Anthropic to build support for every service... or you could use a plug-in system.
可以把它想象成 USB 接口。不用为每种设备都做一个不同的插头,只需要一个标准接口。任何遵循这个标准的设备都能直接接入。Think of it like USB ports. Instead of building a different connector for every device, you create one standard port. Anything that speaks the standard can plug right in.
预装的 45 个工具 —— 文件操作、bash 命令、网页搜索、代码编辑等等。45 tools that come pre-installed — file operations, bash commands, web search, code editing, and more.
添加新工具的外部程序 —— Notion、GitHub、数据库、设计工具。每个 MCP 服务器就像插上一个新的 USB 设备。External programs that add NEW tools — Notion, GitHub, databases, design tools. Each MCP server is like plugging in a new USB device.
将工具、命令和技能打包在一起的扩展,一键安装。Packaged extensions that bundle tools, commands, and skills together into one installable package.
Markdown 文件,教会 Claude 新的工作流程 —— 就像给它一张特定任务的操作手册。Markdown files that teach Claude new workflows — like giving it a recipe card for a specific task.
MCP 是什么?实际运行演示What is MCP? Watching It in Action
让我们看看,当你让 Claude 做一件它独力完成不了的事情时,幕后究竟发生了什么。逐条点击查看对话过程。Let us watch what happens behind the scenes when you ask Claude to do something it cannot do alone. Click through to see the conversation unfold.
就像你不需要理解 USB 键盘内部是怎么工作的 —— 插上就能用 —— 你也不需要理解 Notion 的 API。MCP 服务器会处理所有这些。你只需要告诉 Claude 你想做什么。Just like you do not need to understand how a USB keyboard works internally — you just plug it in — you do not need to understand the Notion API. The MCP server handles all that. You just tell Claude what you want done.
MCP 服务器如何连接How MCP Servers Connect
MCP 服务器可以通过不同的方式连接到 Claude Code,这些方式叫做传输(Transport)。每种方式适用于不同的场景。MCP servers can connect to Claude Code in different ways, called transports. Each is suited to different situations.
stdio(最常用)stdio (Most Common)
服务器作为本地程序运行在你的电脑上。Claude Code 通过标准输入/输出与它对话 —— 就像两个人传纸条。快速、简单,而且可以离线工作。The server runs as a local program on your computer. Claude Code talks to it through standard input/output — like two people passing notes. Fast, simple, and works offline.
SSE / HTTP
服务器运行在远程 Web 服务器上。Claude Code 通过网络使用 Web 请求进行连接。适合多人共享的云托管服务。The server runs on a remote web server. Claude Code connects over the network using web requests. Good for cloud-hosted services that many people share.
WebSocket
实时的双向连接。双方可以随时发送消息,就像打电话而不是发邮件。用于流式传输数据。A real-time two-way connection. Both sides can send messages at any time, like a phone call instead of email. Used for streaming data.
进程内(In-Process)In-Process
服务器直接运行在 Claude Code 内部 —— 不需要单独的程序。用于随工具一起发布的内置插件。由于没有网络延迟,这是最快的选项。The server runs inside Claude Code itself — no separate program needed. Used for built-in plugins that ship with the tool. The fastest option since there is zero network delay.
深入内部:连接 MCP 服务器Under the Hood: Connecting to an MCP Server
下面是 MCP 客户端代码中的真实模式。它展示了 Claude Code 是如何接入外部服务的。Here is the real pattern from the MCP client code. It shows exactly how Claude Code plugs into an external service.
// From src/services/mcp/client.ts
async function ensureConnectedClient(
serverName, config
) {
const transport = new StdioClientTransport({
command: config.command,
args: config.args,
env: config.env,
});
const client = new Client();
await client.connect(transport);
const tools = await client.listTools();
const resources = await client.listResources();
return { client, tools, resources };
}
第 1-3 行:这个函数用于连接 MCP 服务器。它需要服务器名称和配置信息(如何启动服务器)。Line 1-3: This is a function that connects to an MCP server. It needs the server name and its config (how to start it).
第 4-7 行:创建一个"传输通道"—— 即通信管道。这里使用 stdio 方式,所以它会将服务器作为本地程序启动,通过文本输入/输出进行对话。Line 4-7: Create a "transport" — the communication channel. This one uses stdio, so it launches the server as a local program and talks via text input/output.
第 8-9 行:创建一个新的 MCP 客户端并连接到传输通道。就像插上 USB 线。Line 8-9: Create a new MCP client and connect it to the transport. Like plugging in a USB cable.
第 10-11 行:询问服务器"你提供哪些工具和资源?"服务器会返回它的能力菜单。Line 10-11: Ask the server "What tools and resources do you offer?" The server responds with its menu of capabilities.
第 12 行:返回所有东西 —— 连接、工具列表和资源列表 —— 这样 Claude 就可以开始使用它们了。Line 12: Return everything — the connection, the tools list, and the resources list — so Claude can start using them.
MCP 服务器从哪里来Where MCP Servers Come From
MCP 服务器并不是硬编码的。它们来自多个配置来源,按优先级逐级检查。这意味着你、你的团队和你的组织可以各自提供不同的服务器。MCP servers are not hardcoded. They come from multiple configuration sources, checked in order. This means you, your team, and your organization can all contribute different servers.
想象一个团队,每个人都需要访问公司的 Jira 看板,但有一位开发者还额外使用个人的时间追踪工具。项目设置负责共享的 Jira 服务器,用户设置负责个人工具,互不干扰。Imagine a team where everyone needs access to the company Jira board but one developer also uses a personal time-tracking tool. Project settings handle the shared Jira server. User settings handle the personal tool. Neither interferes with the other.
检验你的理解Check Your Understanding
1. 你想让 Claude Code 与你的 Jira 看板交互,你需要什么?1. You want Claude Code to interact with your Jira board. What do you need?
2. 一个 MCP 服务器不断断开连接。你会先检查哪里?2. An MCP server keeps disconnecting. Where would you look first?
3. 你的团队希望每个人都能使用相同的自定义工具。MCP 配置应该放在哪里?3. Your team wants everyone to have access to the same custom tools. Where should the MCP config go?
当事情出错时When Things Break
错误处理与恢复 —— 让 Claude Code 持续飞行的应急预案Error handling and recovery — the emergency procedures that keep Claude Code flying
七条恢复路径The Seven Recovery Paths
就像飞行员为每种故障都准备了应急预案 —— 引擎、电气、导航 —— Claude Code 中的查询循环有七个不同的地方可以从错误中恢复。其中大多数都是静默发生的,你甚至都不会注意到。Like a pilot who has emergency procedures for every type of failure — engine, electrical, navigation — the query loop in Claude Code has SEVEN different places where it can recover from errors. Most of these happen silently, without you ever knowing.
回复太长,在句子中间被截断了。Claude Code 检测到截断,会让 Claude 从停下的地方继续生成。The response was too long and got cut off mid-sentence. Claude Code detects the truncation and asks Claude to continue from where it stopped.
上下文窗口快要满了。Claude Code 自动压缩对话历史以释放空间,然后重试。The context window is nearly full. Claude Code automatically compresses the conversation history to free up space, then retries.
即使压缩之后,上下文仍然太大。Claude Code 会为旧消息创建一个高层摘要视图,只保留最关键的信息。Even after compacting, context is still too large. Claude Code creates a high-level summary view of old messages, keeping only the essentials.
某些数据与当前模型不兼容。Claude Code 剥离有问题的数据并重试,可能还会切换到后备模型。Some data is incompatible with the current model. Claude Code strips the problematic data and retries, possibly with a fallback model.
图片或文件对 API 来说太大了。Claude Code 会压缩或缩小媒体文件,然后用较小的版本重试。An image or file is too large for the API. Claude Code compresses or resizes the media and tries again with the smaller version.
你的登录令牌(Token)过期了。Claude Code 自动刷新令牌并重试请求。你永远不会看到登录提示。Your login token expired. Claude Code automatically refreshes it and retries the request. You never see a login prompt.
服务器过载(错误码 429 或 529)。Claude Code 使用指数退避策略等待后重试。The server is overloaded (error 429 or 529). Claude Code waits with exponential backoff and retries.
重试引擎运行演示The Retry Engine in Motion
withRetry() 函数就是驾驶舱里的飞行员。逐步点击动画,看看它是如何处理每种故障的。The withRetry() function is the pilot at the controls. Walk through the animation to see how it handles each type of failure.
深入内部:重试循环Under the Hood: The Retry Loop
下面是简化后的真实 withRetry() 函数。这段代码决定是重试、等待还是放弃。Here is the real withRetry() function, simplified. This is the code that decides whether to retry, wait, or give up.
// From src/services/api/withRetry.ts
async function* withRetry(
getClient, operation, options
) {
for (let attempt = 1;
attempt <= maxRetries + 1;
attempt++) {
try {
return await operation(client, attempt);
} catch (error) {
if (isTransientCapacityError(error)) {
const delay = BASE_DELAY
* Math.pow(2, attempt - 1);
await sleep(delay);
continue;
}
throw error;
}
}
}
第 1-3 行:一个用自动重试逻辑包装任意 API 操作的函数。它接收操作本身和一些选项(比如允许重试多少次)。Line 1-3: A function that wraps any API operation with automatic retry logic. It takes the operation and some options (like how many retries to allow).
第 4-6 行:一个循环,最多尝试 maxRetries + 1 次。默认是 10 次重试,共 11 次尝试。每次都会记录当前是第几次尝试。Line 4-6: A loop that tries up to maxRetries + 1 times. The default is 10 retries, so 11 total attempts. Each time it keeps track of which attempt number it is on.
第 7-8 行:尝试执行操作。如果成功了,立即返回结果,搞定!Line 7-8: TRY to run the operation. If it succeeds, return the result immediately. Done!
第 9-10 行:如果失败了,检查:这是临时性问题吗?(服务器过载、限流等)Line 9-10: If it FAILS, check: was this a temporary problem? (Server overloaded, rate limited, etc.)
第 11-14 行:如果是临时性问题:使用指数退避计算等待时间。第 1 次等 500ms,第 2 次等 1 秒,第 3 次等 2 秒,第 4 次等 4 秒。每次等待时间翻倍。Line 11-14: If temporary: calculate the wait time using exponential backoff. Attempt 1 waits 500ms. Attempt 2 waits 1 second. Attempt 3 waits 2 seconds. Attempt 4 waits 4 seconds. Each time, the wait doubles.
第 16 行:如果错误不是临时性的(请求无效、输入错误),立即放弃并将错误反馈给用户。Line 16: If the error is NOT temporary (bad request, invalid input), give up immediately and surface the error.
如果服务器已经过载,疯狂地快速重试只会让情况更糟 —— 就像所有人同时给一家繁忙的餐厅打电话。通过每次翻倍等待时间(500ms、1秒、2秒、4秒、8秒……),你给了服务器喘息的空间来恢复。这就是所谓的指数退避。If the server is overloaded, hammering it with rapid retries makes things worse — like everyone calling a busy restaurant at the same time. By doubling the wait each time (500ms, 1s, 2s, 4s, 8s...), you give the server breathing room to recover. This is called exponential backoff.
功能开关:构建系统的闸门Feature Flags: The Build System Gates
Claude Code 使用功能开关(Feature Flags)来控制特定版本中包含哪些能力。下面是它们在代码中的样子:Claude Code uses feature flags to control which capabilities exist in a given version. Here is what they look like in the code:
// Feature-gated code pattern
if (feature('REACTIVE_COMPACT')) {
// This code only exists in
// certain builds
const mod =
require('./reactiveCompact.js');
}
第 1 行:检查:这个构建版本是否开启了"REACTIVE_COMPACT"功能?Line 1: Check: is the "REACTIVE_COMPACT" feature turned on for this build?
第 2-4 行:如果是,加载响应式压缩模块 —— 即在内存快满时自动压缩对话的代码。Line 2-4: If YES, load the reactive compaction module — the code that automatically compresses conversations when memory gets full.
关键洞察:feature() 在构建时就被求值了,而不是在你运行程序时。被禁用的功能的代码会从最终的二进制文件中被完全移除。Key insight: feature() is evaluated at build time, not when you run the program. Code for disabled features is completely removed from the final binary.
Claude Code 的反编译源码中有 108 个缺失的模块藏在功能开关后面。公开版本构建时,这些开关被设为 false,对应的代码被完全剥离。它不仅仅是被关掉了 —— 在你下载的文件中根本就不存在。The decompiled source of Claude Code has 108 missing modules behind feature flags. When the public version was built, those flags were set to false, and the code was stripped out entirely. It is not just turned off — it does not exist in the file you downloaded.
氛围编程者的调试技巧Debugging Tips for Vibe Coders
当 Claude Code 表现异常时,下面是最常见的问题和排查方法。不需要计算机科学学位。When Claude Code behaves unexpectedly, here are the most common issues and what to check. No computer science degree required.
同一个失败命令反复执行Same failing command over and over
权限系统可能在自动批准错误的命令。检查你的 allowedTools 设置,考虑退出自动批准模式。The permission system may be auto-approving bad commands. Check your allowedTools settings and consider switching out of auto-accept mode.
响应变慢,开始遗忘Responses are slow and forgetful
上下文窗口快满了。使用 /compact 压缩对话,或者开启一个新的聊天会话。The context window is filling up. Use /compact to compress the conversation, or start a new chat session.
Claude 找不到我的文件Claude cannot find my files
检查你的工作目录。Claude 在你启动它时所在的文件夹中工作。用 pwd 检查,必要时导航到正确位置。Check your working directory. Claude operates from the folder where you launched it. Use pwd to check, and navigate if needed.
MCP 工具没有出现MCP tools are not showing up
MCP 服务器可能已崩溃或启动失败。检查 /mcp 状态,必要时重启服务器。The MCP server may have crashed or failed to start. Check /mcp status and restart the server if needed.
Claude 使用了错误的模型Claude is using the wrong model
检查 /model 和你的设置。会话级覆盖(通过 /model 命令设置)优先于配置文件。后备模型也可能已被静默触发。Check /model and your settings. Session overrides (from /model command) take priority over config files. A fallback may also have been triggered silently.