01 | Claude Code 源码执行流程 - 从用户输入到结果输出
01 | Claude Code 源码执行流程 - 从用户输入到结果输出声明:📝 作者:甜城瑞庄的核桃(ZMJ)原创学习笔记,欢迎分享,但请保留作者信息及原文链接哦~📍 完整调用链路图用户输入命令: claude "帮我分析代码" ↓ ┌──────────────────────────────────────────────────────────┐ │ 1️⃣ CLI 启动阶段 │ └──────────────────────────────────────────────────────────┘ 📄 cli.js (打包后的入口) ↓ 📄 src/entrypoints/cli.tsx : 302行 void main() ← 自执行函数 ↓ 📄 src/entrypoints/cli.tsx : 33-43行 async function main() ├─ 第34行: const args = process.argv.slice(2) // 获取命令行参数 ├─ 第36-42行: 快速路径检查(--version, --help等) └─ 第288-297行: 无特殊标志,进入完整CLI流程 ↓ const { main: cliMain } = await import('../main.js') await cliMain() // 调用主逻辑 ┌──────────────────────────────────────────────────────────┐ │ 2️⃣ 主应用初始化 │ └──────────────────────────────────────────────────────────┘ 📄 src/main.tsx : 12行 profileCheckpoint('main_tsx_entry') // 性能检查点 ↓ 📄 src/main.tsx : 16行 startMdmRawRead() // 并行启动MDM读取 ↓ 📄 src/main.tsx : 20行 startKeychainPrefetch() // 并行启动钥匙串预取 ↓ 📄 src/main.tsx : (中间省略大量import和初始化) ├─ 加载配置 (enableConfigs) ├─ 初始化遥测 (init, initializeTelemetryAfterTrust) ├─ 处理命令行参数 (CommanderCommand解析) ├─ 加载工具 (getTools) ├─ 加载命令 (getCommands) └─ 构建应用状态 (AppState) ┌──────────────────────────────────────────────────────────┐ │ 3️⃣ REPL 交互界面启动 │ └──────────────────────────────────────────────────────────┘ 📄 src/replLauncher.tsx : 12行 async function launchRepl(root, appProps, replProps, renderAndRun) ↓ 📄 src/replLauncher.tsx : 13-18行 const { App } = await import('./components/App.js') const { REPL } = await import('./screens/REPL.js') ↓ 📄 src/replLauncher.tsx : 19-21行 await renderAndRun(root, App {...appProps} REPL {...replProps} / /App ) // 渲染React组件到终端 ┌──────────────────────────────────────────────────────────┐ │ 4️⃣ REPL 主循环 - 等待用户输入 │ └──────────────────────────────────────────────────────────┘ 📄 src/screens/REPL.tsx : (超大文件,关键部分) ├─ 第12行: useInput() // 监听键盘输入 ├─ 第58行: PromptInput / // 提示符组件 └─ 用户输入后触发提交 ↓ 📄 src/utils/handlePromptSubmit.ts handlePromptSubmit(userInput) ├─ 解析用户输入 ├─ 处理命令引用 (expandPastedTextRefs) ├─ 解析斜杠命令 (isSlashCommand) └─ 构建用户消息 (createUserMessage) ↓ 调用查询引擎 ┌──────────────────────────────────────────────────────────┐ │ 5️⃣ QueryEngine - 核心查询引擎 │ └──────