Claw Code 代码架构详细解析
项目:Rewriting Project Claw Code (
instructkr/claw-code)GitHub:https://github.com/instructkr/claw-code
作者:@instructkr(被华尔街日报报道的 AI 工程师)
社区:https://instruct.kr/(韩国 LLM 社区)
📋 项目概览
背景
2026年3月31日凌晨4点,Claw Code 源码被泄露。作者 @instructkr 在压力下使用 oh-my-codex (OmX) 和 oh-my-opencode (OmO) 工具链,从零开始用 Python 重写了核心功能,随后启动了 Rust 重写版本以提升性能。
成就
- 发布 2 小时内即突破 50K ⭐
- 从零重写核心功能
- 完整的 MCP (Model Context Protocol) 支持
- 多语言实现(Python + Rust)
🏗️ 整体架构
claude-code-main/
├── src/ # Python 重写版本(已实现基础功能)
│ ├── commands.py # 命令系统
│ ├── main.py # CLI 入口
│ ├── models.py # 数据模型
│ ├── tools.py # 工具系统
│ └── ...
├── rust/ # Rust 重写版本(正在开发)
│ ├── Cargo.toml # Workspace 配置
│ └── crates/ # Rust crates 模块化设计
│ ├── api/ # API 客户端
│ ├── runtime/ # 运行时核心
│ ├── tools/ # 工具系统
│ ├── plugins/ # 插件系统
│ ├── commands/ # 命令系统
│ ├── claw-cli/ # CLI 二进制
│ ├── lsp/ # LSP 支持
│ ├── compat-harness/ # 兼容性测试
│ └── server/ # 服务器模式
├── tests/ # 测试套件
└── assets/ # 资源文件
🦀 Rust 架构详解
Workspace 配置 (rust/Cargo.toml)
toml
[workspace]
members = ["crates/*"]
resolver = "2"
[workspace.package]
version = "0.1.0"
edition = "2021"
license = "MIT"
[workspace.lints.rust]
unsafe_code = "forbid" # 禁止不安全代码
[workspace.lints.clippy]
all = { level = "warn", priority = -1 }
pedantic = { level = "warn", priority = -1 }
特点:
- 使用 Cargo Workspace 管理多个 crates
- 禁止
unsafe代码,确保内存安全 - 严格的 Clippy 检查(
all+pedantic)
Crate 1: api - API 客户端
路径 : rust/crates/api/
模块结构:
api/
├── src/
│ ├── client.rs # 客户端核心
│ ├── error.rs # 错误类型
│ ├── providers/
│ │ ├── claw_provider.rs # Claw API 提供者
│ │ ├── openai_compat.rs # OpenAI 兼容提供者
│ │ └── mod.rs
│ ├── sse.rs # Server-Sent Events 解析
│ └── types.rs # API 类型定义
└── tests/
├── client_integration.rs
├── openai_compat_integration.rs
└── provider_client_integration.rs
核心功能:
- ✅ Anthropic API 客户端
- ✅ OAuth 认证(PKCE 流程)
- ✅ 流式传输(SSE 解析)
- ✅ 多提供者支持(Claw + OpenAI 兼容)
- ✅ 模型别名解析
- ✅ Token 管理
导出类型:
rust
pub use client::{
oauth_token_is_expired,
read_base_url,
resolve_saved_oauth_token,
resolve_startup_auth_source,
MessageStream,
OAuthTokenSet,
ProviderClient,
};
pub use types::{
ContentBlockDelta,
InputContentBlock,
InputMessage,
MessageRequest,
MessageResponse,
OutputContentBlock,
StreamEvent,
ToolChoice,
ToolDefinition,
ToolResultContentBlock,
Usage,
};
Crate 2: runtime - 运行时核心
路径 : rust/crates/runtime/
模块结构:
runtime/
└── src/
├── bash.rs # Bash 命令执行
├── bootstrap.rs # 启动流程
├── compact.rs # 会话压缩
├── config.rs # 配置加载
├── conversation.rs # 对话运行时
├── file_ops.rs # 文件操作
├── hooks.rs # 钩子系统
├── json.rs # JSON 工具
├── mcp.rs # MCP 工具函数
├── mcp_client.rs # MCP 客户端
├── mcp_stdio.rs # MCP stdio 传输
├── oauth.rs # OAuth 实现
├── permissions.rs # 权限系统
├── prompt.rs # 提示词构建
├── remote.rs # 远程会话
├── sandbox.rs # 沙箱环境
├── session.rs # 会话管理
├── sse.rs # SSE 工具
└── usage.rs # 使用量追踪
核心功能:
1. 会话管理 (session.rs)
rust
pub struct Session {
pub messages: Vec<ConversationMessage>,
// ...
}
pub enum MessageRole {
User,
Assistant,
System,
}
pub struct ConversationMessage {
pub role: MessageRole,
pub content: Vec<ContentBlock>,
}
2. 对话运行时 (conversation.rs)
rust
pub struct ConversationRuntime {
pub api_client: Box<dyn ApiClient>,
pub tool_executor: Box<dyn ToolExecutor>,
pub session: Session,
// ...
}
pub trait ToolExecutor {
fn execute_tool(&mut self, tool_call: &ToolCall) -> Result<ToolResult, ToolError>;
}
3. MCP 支持 (mcp_stdio.rs)
rust
pub struct McpServerManager;
pub struct McpTool {
pub name: String,
pub description: String,
pub input_schema: serde_json::Value,
}
pub struct McpStdioProcess;
4. OAuth 认证 (oauth.rs)
rust
pub fn generate_pkce_pair() -> PkceCodePair;
pub fn generate_state() -> String;
pub fn save_oauth_credentials(token: &OAuthTokenSet);
pub fn load_oauth_credentials() -> Option<OAuthTokenSet>;
5. 权限系统 (permissions.rs)
rust
pub enum PermissionMode {
Auto,
Always,
Never,
}
pub struct PermissionRequest {
pub tool_name: String,
pub description: String,
}
6. 提示词构建 (prompt.rs)
rust
pub struct SystemPromptBuilder;
pub struct ProjectContext {
pub context_files: Vec<ContextFile>,
}
7. 会话压缩 (compact.rs)
rust
pub fn compact_session(
session: &Session,
config: &CompactionConfig,
) -> Result<CompactionResult, RuntimeError>;
pub fn should_compact(session: &Session) -> bool;
Crate 3: tools - 工具系统
路径 : rust/crates/tools/
功能:
- 全局工具注册表
- 工具执行器
- 工具发现和加载
Crate 4: plugins - 插件系统
路径 : rust/crates/plugins/
模块结构:
plugins/
└── src/
├── hooks.rs # 插件钩子
└── lib.rs
功能:
- 插件模型
- 钩子管道
- 插件生命周期管理
Crate 5: commands - 命令系统
路径 : rust/crates/commands/
功能:
- 斜杠命令解析
- 命令规范定义
- 命令处理器
Crate 6: claw-cli - CLI 二进制
路径 : rust/crates/claw-cli/
模块结构:
claw-cli/
└── src/
├── app.rs # 应用主逻辑
├── args.rs # 参数解析
├── init.rs # 初始化
├── input.rs # 输入处理
├── main.rs # 入口
└── render.rs # 渲染器
主函数流程:
rust
fn main() {
match parse_args(&args)? {
CliAction::Repl { model, allowed_tools, permission_mode } => {
run_repl(model, allowed_tools, permission_mode)?;
}
CliAction::Prompt { prompt, model, output_format, ... } => {
LiveCli::new(model, true, allowed_tools, permission_mode)?
.run_turn_with_output(&prompt, output_format)?;
}
CliAction::Login => run_login()?,
CliAction::Logout => run_logout()?,
CliAction::Init => run_init()?,
CliAction::Version => print_version(),
CliAction::Help => print_help(),
// ...
}
}
支持的命令:
claw <prompt>- 单次提示claw --repl- 交互式 REPLclaw --login- OAuth 登录claw --logout- 登出claw --init- 初始化仓库claw --version- 版本信息claw --help- 帮助
Crate 7: lsp - LSP 支持
路径 : rust/crates/lsp/
模块结构:
lsp/
└── src/
├── client.rs # LSP 客户端
├── error.rs # LSP 错误
├── manager.rs # LSP 管理器
├── types.rs # LSP 类型
└── lib.rs
功能:
- LSP 客户端实现
- 诊断信息管理
- 符号定位
- 工作区诊断
Crate 8: compat-harness - 兼容性测试
路径 : rust/crates/compat-harness/
功能:
- 与原始 TypeScript 版本的兼容性测试
- 清单提取和验证
Crate 9: server - 服务器模式
路径 : rust/crates/server/
功能:
- HTTP 服务器模式
- WebSocket 支持
- 远程会话管理
🐍 Python 架构
路径 : src/
主要模块:
src/
├── commands.py # 命令系统
├── main.py # CLI 入口
├── models.py # 数据模型
├── tools.py # 工具系统
└── ... # 其他支持模块
状态:基础功能已实现,作为 Rust 版本的参考和快速原型。
🔧 核心技术栈
Rust 依赖
lsp-types = "0.97"- LSP 协议类型serde_json = "1"- JSON 序列化tokio- 异步运行时(推断)reqwest- HTTP 客户端(推断)clap- 命令行参数解析(推断)
Python 依赖
anthropic- Anthropic SDKmcp- MCP 客户端(推断)
📊 功能完成度(根据 PARITY.md)
✅ 已实现
- 核心 API/OAuth 客户端
- 会话状态管理
- 工具循环和执行
- MCP stdio/bootstrap 支持
- 基础斜杠命令
- 配置系统
- 权限提示(配置级)
- 本地技能支持
⚠️ 部分实现
- 插件系统(模型已定义,运行时执行未完成)
- 钩子系统(仅配置支持,无运行时执行)
- CLI 命令(范围较窄)
- 技能系统(仅本地文件支持)
❌ 未实现
- 远程技能发现
- 插件热加载
- 完整的钩子管道
- 高级斜杠命令
🚀 快速开始
Python 版本
bash
cd /home/liushuo/Desktop/claude-code-main
# 查看摘要
python3 -m src.main summary
# 查看清单
python3 -m src.main manifest
# 运行测试
python3 -m unittest discover -s tests -v
Rust 版本
bash
cd /home/liushuo/Desktop/claude-code-main/rust
# 构建
cargo build --release
# 格式化
cargo fmt
# 代码检查
cargo clippy --workspace --all-targets -- -D warnings
# 运行测试
cargo test --workspace
# 运行 CLI
cargo run --release -- --help
🎯 设计亮点
1. 模块化架构
- Rust Workspace 分离关注点
- 每个 crate 独立可测试
- 清晰的依赖关系
2. 内存安全
- 禁止
unsafe代码 - 严格的 Clippy 检查
- 类型安全的 API 设计
3. 多提供者支持
- Claw API
- OpenAI 兼容 API
- 可扩展的提供者架构
4. 完整的 MCP 支持
- stdio 传输
- bootstrap 支持
- 工具和资源发现
5. 灵活的权限系统
- 自动批准
- 总是批准
- 从不批准
- 运行时提示
📝 开发规范
Rust 代码规范
toml
[workspace.lints.rust]
unsafe_code = "forbid"
[workspace.lints.clippy]
all = { level = "warn", priority = -1 }
pedantic = { level = "warn", priority = -1 }
module_name_repetitions = "allow"
missing_panics_doc = "allow"
missing_errors_doc = "allow"
测试策略
- 单元测试(每个 crate 内部)
- 集成测试(
tests/目录) - 兼容性测试(
compat-harness)
🔮 未来方向
-
完成 Rust 版本
- 插件运行时执行
- 钩子管道
- 扩展 CLI 命令
-
性能优化
- 异步 I/O
- 并行工具执行
- 缓存策略
-
功能扩展
- 远程技能发现
- 插件市场
- 多会话管理