feat: 合并上游 Rust 实现,扩展 API/运行时/工具链能力

将 claw-code/rust/crates 的完整实现合并到主 workspace,涵盖
  9 个 crate 的更新与 2 个新 crate 的引入。

  API 层:
  - 用原生 Anthropic 客户端(anthropic.rs)替换 claw_provider,
    新增 prompt cache 减少重复请求开销
  - 新增 HTTP 客户端构建器统一代理配置,OpenAI 兼容端增加
    DashScope/Qwen 支持与抖动重试
  - MessageRequest 扩展 temperature/top_p 等模型调参字段
  - SSE 解析器增加 provider 上下文感知的错误信息

  运行时(~11,000 行新增):
  - 新增 bash 命令安全校验、分支锁碰撞检测、配置文件校验
  - 新增会话存储与控制面、MCP 生命周期状态机与服务端实现
  - 新增权限执行引擎、策略引擎、插件生命周期管理
  - 新增 worker 启动编排、任务/定时任务注册表、信任解析器
  - 保留 Windows cmd /C fallback

  命令/插件/工具:
  - commands 大幅重写,扩展 sandbox、doctor、plan 等 slash 命令
  - plugins 新增 PostToolUseFailure hook 与宽容加载机制
  - tools 新增 PDF 提取与 lane 补全工具

  新增 crate:mock-anthropic-service(测试)、telemetry(遥测)

  适配 claw-cli/server:ClawApiClient→AnthropicClient 重命名,
  SlashCommand::parse 返回 Result,移除 session 级 Thinking 变体,
  TokenUsage/ConversationMessage 补充序列化支持
This commit is contained in:
fengmengqi
2026-04-13 14:39:17 +08:00
parent 4a04faf926
commit d8d77824f4
94 changed files with 49049 additions and 4429 deletions
+40 -70
View File
@@ -16,7 +16,7 @@ use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use api::{
resolve_startup_auth_source, AuthSource, ClawApiClient, ContentBlockDelta, InputContentBlock,
resolve_startup_auth_source, AnthropicClient, AuthSource, ContentBlockDelta, InputContentBlock,
InputMessage, MessageRequest, MessageResponse, OutputContentBlock,
StreamEvent as ApiStreamEvent, ToolChoice, ToolDefinition, ToolResultContentBlock,
};
@@ -329,7 +329,7 @@ fn join_optional_args(args: &[String]) -> Option<String> {
fn parse_direct_slash_cli_action(rest: &[String]) -> Result<CliAction, String> {
let raw = rest.join(" ");
match SlashCommand::parse(&raw) {
match SlashCommand::parse(&raw).map_err(|e| e.to_string())? {
Some(SlashCommand::Help) => Ok(CliAction::Help),
Some(SlashCommand::Agents { args }) => Ok(CliAction::Agents { args }),
Some(SlashCommand::Skills { args }) => Ok(CliAction::Skills { args }),
@@ -484,7 +484,7 @@ fn dump_manifests() {
}
fn print_bootstrap_plan() {
for phase in runtime::BootstrapPlan::claw_default().phases() {
for phase in runtime::BootstrapPlan::claude_code_default().phases() {
println!("- {phase:?}");
}
}
@@ -541,7 +541,7 @@ fn run_login() -> Result<(), Box<dyn std::error::Error>> {
return Err(io::Error::new(io::ErrorKind::InvalidData, "oauth state mismatch").into());
}
let client = ClawApiClient::from_auth(AuthSource::None).with_base_url(api::read_base_url());
let client = AnthropicClient::from_auth(AuthSource::None).with_base_url(api::read_base_url());
let exchange_request =
OAuthTokenExchangeRequest::from_config(oauth, code, state, pkce.verifier, redirect_uri);
let runtime = tokio::runtime::Runtime::new()?;
@@ -650,7 +650,7 @@ fn resume_session(session_path: &Path, commands: &[String]) {
let mut session = session;
for raw_command in commands {
let Some(command) = SlashCommand::parse(raw_command) else {
let Ok(Some(command)) = SlashCommand::parse(raw_command) else {
eprintln!("unsupported resumed command: {raw_command}");
std::process::exit(2);
};
@@ -987,8 +987,6 @@ fn run_resume_command(
}
SlashCommand::Bughunter { .. }
| SlashCommand::Branch { .. }
| SlashCommand::Worktree { .. }
| SlashCommand::CommitPushPr { .. }
| SlashCommand::Commit
| SlashCommand::Pr { .. }
| SlashCommand::Issue { .. }
@@ -1000,7 +998,7 @@ fn run_resume_command(
| SlashCommand::Permissions { .. }
| SlashCommand::Session { .. }
| SlashCommand::Plugins { .. }
| SlashCommand::Unknown(_) => Err("unsupported resumed slash command".into()),
| _ => Err("unsupported resumed slash command".into()),
}
}
@@ -1024,7 +1022,7 @@ fn run_repl(
cli.persist_session()?;
break;
}
if let Some(command) = SlashCommand::parse(trimmed) {
if let Ok(Some(command)) = SlashCommand::parse(trimmed) {
if cli.handle_repl_command(command)? {
cli.persist_session()?;
}
@@ -1336,24 +1334,14 @@ impl LiveCli {
);
false
}
SlashCommand::Worktree { .. } => {
eprintln!(
"{}",
render_mode_unavailable("worktree", "git worktree commands")
);
false
}
SlashCommand::CommitPushPr { .. } => {
eprintln!(
"{}",
render_mode_unavailable("commit-push-pr", "commit + push + PR automation")
);
false
}
SlashCommand::Unknown(name) => {
eprintln!("{}", render_unknown_repl_command(&name));
false
}
_ => {
eprintln!("command not available in this mode");
false
}
})
}
@@ -2505,12 +2493,6 @@ fn render_export_text(session: &Session) -> String {
for block in &message.blocks {
match block {
ContentBlock::Text { text } => lines.push(text.clone()),
ContentBlock::Thinking { thinking, .. } => {
lines.push(format!("[thinking] {thinking}"));
}
ContentBlock::RedactedThinking { .. } => {
lines.push("[thinking] <redacted>".to_string());
}
ContentBlock::ToolUse { id, name, input } => {
lines.push(format!("[tool_use id={id} name={name}] {input}"));
}
@@ -2995,7 +2977,7 @@ fn build_runtime(
CliToolExecutor::new(allowed_tools.clone(), emit_output, tool_registry.clone()),
permission_policy(permission_mode, &tool_registry),
system_prompt,
feature_config,
&feature_config,
))
}
@@ -3047,7 +3029,7 @@ impl runtime::PermissionPrompter for CliPermissionPrompter {
struct DefaultRuntimeClient {
runtime: tokio::runtime::Runtime,
client: ClawApiClient,
client: AnthropicClient,
model: String,
enable_tools: bool,
emit_output: bool,
@@ -3067,7 +3049,7 @@ impl DefaultRuntimeClient {
) -> Result<Self, Box<dyn std::error::Error>> {
Ok(Self {
runtime: tokio::runtime::Runtime::new()?,
client: ClawApiClient::from_auth(resolve_cli_auth_source()?)
client: AnthropicClient::from_auth(resolve_cli_auth_source()?)
.with_base_url(api::read_base_url()),
model,
enable_tools,
@@ -3105,6 +3087,12 @@ impl ApiClient for DefaultRuntimeClient {
.then(|| filter_tool_specs(&self.tool_registry, self.allowed_tools.as_ref())),
tool_choice: self.enable_tools.then_some(ToolChoice::Auto),
stream: true,
temperature: None,
top_p: None,
frequency_penalty: None,
presence_penalty: None,
stop: None,
reasoning_effort: None,
};
self.runtime.block_on(async {
@@ -3173,7 +3161,6 @@ impl ApiClient for DefaultRuntimeClient {
.and_then(|()| out.flush())
.map_err(|error| RuntimeError::new(error.to_string()))?;
}
events.push(AssistantEvent::ThinkingDelta(thinking));
}
}
ContentBlockDelta::SignatureDelta { .. } => {}
@@ -3254,9 +3241,7 @@ fn final_assistant_text(summary: &runtime::TurnSummary) -> String {
.iter()
.filter_map(|block| match block {
ContentBlock::Text { text } => Some(text.as_str()),
ContentBlock::Thinking { thinking, .. } => Some(thinking.as_str()),
ContentBlock::RedactedThinking { .. }
| ContentBlock::ToolUse { .. }
ContentBlock::ToolUse { .. }
| ContentBlock::ToolResult { .. } => None,
})
.collect::<Vec<_>>()
@@ -3276,9 +3261,7 @@ fn collect_tool_uses(summary: &runtime::TurnSummary) -> Vec<serde_json::Value> {
"name": name,
"input": input,
})),
ContentBlock::Thinking { .. }
| ContentBlock::RedactedThinking { .. }
| ContentBlock::Text { .. }
ContentBlock::Text { .. }
| ContentBlock::ToolResult { .. } => None,
})
.collect()
@@ -3301,9 +3284,7 @@ fn collect_tool_results(summary: &runtime::TurnSummary) -> Vec<serde_json::Value
"output": output,
"is_error": is_error,
})),
ContentBlock::Thinking { .. }
| ContentBlock::RedactedThinking { .. }
| ContentBlock::Text { .. }
ContentBlock::Text { .. }
| ContentBlock::ToolUse { .. } => None,
})
.collect()
@@ -3851,7 +3832,6 @@ fn push_output_block(
write!(out, "\x1b[2m{thinking}\x1b[0m")
.and_then(|()| out.flush())
.map_err(|error| RuntimeError::new(error.to_string()))?;
events.push(AssistantEvent::ThinkingDelta(thinking));
}
}
OutputContentBlock::RedactedThinking { .. } => {}
@@ -3942,7 +3922,7 @@ impl ToolExecutor for CliToolExecutor {
}
fn permission_policy(mode: PermissionMode, tool_registry: &GlobalToolRegistry) -> PermissionPolicy {
tool_registry.permission_specs(None).into_iter().fold(
tool_registry.permission_specs(None).unwrap_or_default().into_iter().fold(
PermissionPolicy::new(mode),
|policy, (name, required_permission)| {
policy.with_tool_requirement(name, required_permission)
@@ -3963,16 +3943,6 @@ fn convert_messages(messages: &[ConversationMessage]) -> Vec<InputMessage> {
.iter()
.map(|block| match block {
ContentBlock::Text { text } => InputContentBlock::Text { text: text.clone() },
ContentBlock::Thinking {
thinking,
signature,
} => InputContentBlock::Thinking {
thinking: thinking.clone(),
signature: signature.clone(),
},
ContentBlock::RedactedThinking { data } => InputContentBlock::RedactedThinking {
data: serde_json::from_str(&data.render()).unwrap_or(serde_json::Value::Null),
},
ContentBlock::ToolUse { id, name, input } => InputContentBlock::ToolUse {
id: id.clone(),
name: name.clone(),
@@ -4735,39 +4705,39 @@ mod tests {
#[test]
fn clear_command_requires_explicit_confirmation_flag() {
assert_eq!(
SlashCommand::parse("/clear"),
Some(SlashCommand::Clear { confirm: false })
SlashCommand::parse("/clear").map_err(|e| e.to_string()),
Ok(Some(SlashCommand::Clear { confirm: false }))
);
assert_eq!(
SlashCommand::parse("/clear --confirm"),
Some(SlashCommand::Clear { confirm: true })
SlashCommand::parse("/clear --confirm").map_err(|e| e.to_string()),
Ok(Some(SlashCommand::Clear { confirm: true }))
);
}
#[test]
fn parses_resume_and_config_slash_commands() {
assert_eq!(
SlashCommand::parse("/resume saved-session.json"),
Some(SlashCommand::Resume {
SlashCommand::parse("/resume saved-session.json").map_err(|e| e.to_string()),
Ok(Some(SlashCommand::Resume {
session_path: Some("saved-session.json".to_string())
})
}))
);
assert_eq!(
SlashCommand::parse("/clear --confirm"),
Some(SlashCommand::Clear { confirm: true })
SlashCommand::parse("/clear --confirm").map_err(|e| e.to_string()),
Ok(Some(SlashCommand::Clear { confirm: true }))
);
assert_eq!(
SlashCommand::parse("/config"),
Some(SlashCommand::Config { section: None })
SlashCommand::parse("/config").map_err(|e| e.to_string()),
Ok(Some(SlashCommand::Config { section: None }))
);
assert_eq!(
SlashCommand::parse("/config env"),
Some(SlashCommand::Config {
SlashCommand::parse("/config env").map_err(|e| e.to_string()),
Ok(Some(SlashCommand::Config {
section: Some("env".to_string())
})
}))
);
assert_eq!(SlashCommand::parse("/memory"), Some(SlashCommand::Memory));
assert_eq!(SlashCommand::parse("/init"), Some(SlashCommand::Init));
assert_eq!(SlashCommand::parse("/memory").map_err(|e| e.to_string()), Ok(Some(SlashCommand::Memory)));
assert_eq!(SlashCommand::parse("/init").map_err(|e| e.to_string()), Ok(Some(SlashCommand::Init)));
}
#[test]