Skip to content

Instantly share code, notes, and snippets.

@justinyanme
Created March 31, 2026 09:39
Show Gist options
  • Select an option

  • Save justinyanme/dac13b9ceeccfa74a268291955679f1f to your computer and use it in GitHub Desktop.

Select an option

Save justinyanme/dac13b9ceeccfa74a268291955679f1f to your computer and use it in GitHub Desktop.

Claude Code 源码仓库分析报告

这是 Claude Code 的源代码 —— Anthropic 官方的 Claude CLI 工具。以下是五个并行探索代理的发现汇总:

项目结构

  • 单体 TypeScript 应用(非 monorepo)—— 无 package.json 或构建配置,属于从更大构建系统中提取的源码
  • 约 800KB 的 main.tsx 入口文件,entrypoints/cli.tsx 作为 CLI 启动引导
  • 146 个 React 组件87+ 个 hooks40+ 个工具50+ 个命令

架构设计

  • UI 层:基于 Ink(终端 React 渲染器)构建,包含自定义布局引擎、Yoga、ANSI 输出、鼠标追踪和 vim 模式支持
  • 核心循环QueryEngine.ts 运行智能体循环 —— 通过 @anthropic-ai/sdk 向 Claude API 发送消息,接收 tool_use 块,执行工具,将 tool_result 回传,循环往复
  • 状态管理:基于 React Context 的 AppStateProvider,集中式 store 配合订阅模型
  • 启动优化:并行初始化、懒加载模块、启动性能分析器、基于特性标志的死代码消除

工具系统

  • 工具定义在 /tools/ 目录下(BashTool、FileReadTool、FileEditTool、GlobTool、GrepTool、AgentTool、MCPTool 等)
  • assembleToolPool() 合并内置工具和 MCP 工具,去重并排序以确保 prompt 缓存稳定性
  • MCP 集成:完整的模型上下文协议支持(SSE、WebSocket、stdio 传输方式、OAuth 认证)
  • 并发策略:只读工具并行执行;有状态变更的工具串行执行

权限与安全

  • 5 种权限模式default(默认)、plan(计划)、acceptEdits(接受编辑)、bypassPermissions(绕过权限)、dontAsk(免询问),另有内部模式 autobubble
  • 设置层级:用户级 → 项目级 → 本地级 → CLI 参数 → 策略级(远程管理,最高优先级)
  • 钩子系统PreToolUse(工具使用前)、PostToolUse(工具使用后)、SessionStart(会话开始)等 —— 支持 shell 命令、提示词、webhook 和子代理
  • 沙箱机制:网络隔离(域名白名单)、文件系统控制(读写允许/拒绝路径)、平台特定的 seccomp 安全策略

智能体/多智能体系统

  • AgentTool:按类型特化派生子代理
  • 协调器模式:多智能体编排(特性门控)
  • SendMessage:基于邮箱模式的代理间消息传递
  • InProcessTeammate:异步协作执行,配合任务列表协调

会话与 UI

  • sessionHistory.ts 管理分页消息历史(每页 100 条)
  • 流式响应通过 React 组件层级逐步渲染
  • 斜杠命令、输入预测建议、方向键历史导航
  • Bridge 模式支持通过传输层远程执行

这是一个规模庞大且架构精密的代码库 —— 包含了 Claude Code 的完整运行时:终端 UI、工具执行引擎、API 客户端、权限系统和多智能体协调机制。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment