feat: Agent 安全纵深防御、Checkpoint 快照、会话 Rewind/Branch、自进化
Skill、流式执行优化与系统架构全面升级
本次提交对标 Claude Code 与 Hermes-Agent 的工程细节,在安全、可靠性、
会话管理、自我进化四个维度进行了系统性加固,变更总量 48 文件 / +12680 -2292 行。
═══════ 安全纵深防御 ═══════
1. Hardline 硬阻止层 (src/agent/runtime/hardline.rs, +534 行)
- 不可绕过的危险命令拦截(关重启、磁盘擦除、Fork 炸弹、rm -rf /、kill -1)
- 反规避标准化管线: ANSI 序列剥离 → Unicode NFKC → shell 反斜杠还原 → 空字面量清理
- 在 PermissionChecker 之前执行,YOLO/Bypass 模式下同样生效
- 集成到 executor Phase 2,被拒绝工具直接注入错误结果
2. Permission 优先级裁决器 (src/agent/runtime/permission.rs, +200 行)
- 7 层正式优先级规则 (P0 Deny → P7 Allow),带冲突日志
- explain() 方法支持审计追溯
- Hook PermissionRequired 与 Checker 结果的正确叠加逻辑
═══════ Checkpoint 文件快照系统 ═══════
3. git2 原生快照 (src/agent/runtime/checkpoint.rs, +920 行)
- 基于 git2 bare repo,内容寻址自动去重
- 文件变更操作前自动触发 (file_write/file_edit/run_bash)
- 每目录每 turn 最多一次快照,防止同一轮重复
- 支持 list/diff/restore API + pre-rollback 安全快照
- 旧快照自动 prune(保留最近 N 个)+ 按目录隔离 ref
- 排除规则自动过滤 node_modules/target/.git/*.pdf 等
- 集成到 executor: 文件操作前 ckpt.ensure_checkpoint()
═══════ 错误恢复系统大升级 ═══════
4. 21 种 FailoverReason 分类 (src/agent/runtime/error_recovery.rs, +1200 行)
- 参考 Hermes-Agent error_classifier.py
- 8 步分类管线: provider-specific → HTTP status → text pattern → error body → fallback
- is_retryable / should_compress / should_failover / is_permanent 方法
- Context Overflow 自动修复: 从错误消息提取 token 限制,自动下调预算
- RecoveryStep::AdjustMaxTokens 实现 (参考 Claude Code 自动修复)
- 向后兼容 ErrorKind 别名
═══════ 会话 Rewind / Branch / Retry 体系 ═══════
5. 完整 undo 栈 (src/agent/runtime/session.rs, +800 行 + 2 迁移脚本)
- Rewind (软删除): active=0 标记,审计 trail 保留,LLM 不可见
- Restore (撤销回退): 冲突检测——回退后有新消息则拒绝,引导使用 Branch
- Branch: 分叉会话,复制所有 active=1 消息到新会话
- Retry: 硬删除最后一轮对话,返回原消息文本供前端重提交
- 数据库: agent_messages.active 列 + agent_sessions.rewind_count + parent_session_id
- API: 4 个新端点 (/branch, /retry, /rewind, /rewind/restore)
- load_history_for_agent 全面使用 active=1 过滤
═══════ Hooks 系统模块化重构 ═══════
6. 单文件 → 7 模块体系 (src/agent/hooks/)
hooks.rs (994 行) 拆分为:
- mod.rs — 入口 + HookRegistry + SessionHookManager
- types.rs — 类型定义 (Context, TaggedContext, PermissionRequestAction 等)
- traits.rs — AgentHook + AsyncAgentHook + 15 种生命周期事件
- matcher.rs — 工具名/参数匹配 + session 作用域过滤
- dispatch.rs — 并行调度引擎 (run_pre/post_tool_use 等)
- registry.rs — 注册/注销/查询
- builtins.rs — CancellationHook + MetricsHook + AuditLogHook + ContextDeduplicator
关键改进:
- run_pre_tool_use 并行执行所有匹配 hooks,聚合 Block/MutateInput/Continue
- TaggedContext 带完整来源标记的上下文注入 (hook_name + event)
- ContextDeduplicator 单 dispatch cycle 内内容哈希去重
- AsyncAgentHook 支持 fire-and-forget 异步 hooks
═══════ Executor 并发执行升级 ═══════
7. 三阶段管道重写 (src/agent/runtime/executor.rs, +600 行)
- Phase 1: 死循环检测 + 参数解析 (不变)
- Phase 2: Hardline 预检查 (新增) → PermissionChecker (改进)
- Phase 3: ToolPartitioner 分区 → 逐批次执行 (重写)
- 并行批次内 FuturesUnordered 并发
- 串行批次确保非并发安全工具独占执行
- Checkpoint 预触发集成
- Hook 上下文注入: system-reminder 格式 + ContextDeduplicator 去重
- Hook 阻塞错误详细记录
═══════ 流式执行真正的流式调度 ═══════
8. StreamingExecutor 重写 (src/agent/runtime/streaming_executor.rs, ~400 行变更)
- on_tool_use 中对并发安全工具立即 tokio::spawn,不等待 flush
- executing_non_concurrent 标志阻塞后继工具直到独占工具完成
- JoinHandle 管理替代自定义 cancel channel
- completed_queue 按流顺序 yield
- Sibling Abort 通过 broadcast channel + tokio::select! 竞速
- ToolContext 实现 Clone (支持 per-task 上下文复制)
═══════ 自改进 Skill 系统 ═══════
9. PatternDetector + SkillCreator + Curator (src/agent/skills/, +1500 行)
- PatternDetector: 扫描 agent_messages 表,检测跨 session 重复工具调用模式
- SkillCreator: 将高置信度模式自动生成 SKILL.md (YAML frontmatter + 工作流步骤)
- SelfImprovePipeline: 一站式 模式检测 → 创建 → 质量审查
- Curator: 分析 skill 使用统计,标记 stale/deprecated,建议清理
- Skill frontmatter 新增 pinned 字段 (禁止 Curator 自动清理)
═══════ 基础设施优化 ═══════
10. 系统提示词缓存 (src/agent/runtime/system_prompt.rs + mod.rs)
- SystemPromptCache: 首次计算后永久复用,/clear 时失效
- 新增 SAFETY / SYSTEM_CONTEXT / TOOL_USAGE 静态 section
- 环境/tools/skills/memory 动态 section 通过 get_or_compute 缓存
11. ToolRegistry schema 缓存 (src/agent/tools/mod.rs)
- schema_cache + schema_generation 版本号
- 工具变更/过滤器变更时自动失效
- precompute_definitions() 预计算 (AgentRuntime 初始化时调用)
12. 迭代摘要融合 (src/agent/compact.rs, +100 行)
- 参考 Hermes context_compressor.py
- CollapseLog 追踪压缩历史,支持溢出合并
- extract_prior_summary: 提取已有摘要融入新压缩
13. SubAgent 系统提示词模块化 (src/agent/tools/subagent.rs)
- 复用 5 个标准 section + 子代理专有上下文 section
- 独立 ToolRegistry 构建工具列表
═══════ 前端 — CSS 变量主题系统 ═══════
14. 全新主题变量体系 (dashboard/src/index.css + App.tsx + 各面板)
- CSS 自定义属性: --bg-card, --text-main, --text-muted, --border-precision
- 语义化颜色: --accent-blueprint, --accent-star
- 全面替换硬编码 Tailwind 颜色 (slate-xxx → var(--xxx))
- 文献入库提示优化 ("核心知识节点" 替代 "向量块")
- ReaderPanel 样式变量化
This commit is contained in:
@@ -0,0 +1,302 @@
|
||||
// src/agent/hooks/matcher.rs
|
||||
//
|
||||
// 工具级匹配器。
|
||||
// Hook 可通过 `match_filter()` 声明只关心特定工具或参数模式,
|
||||
// 从而避免在热路径上被无关调用触发。
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
/// 工具名匹配模式。
|
||||
///
|
||||
/// 三种策略:
|
||||
/// - `Exact("search_papers")` — 精确名称匹配
|
||||
/// - `Prefix("file_")` — 前缀匹配(末尾 `*` 隐式)
|
||||
/// - `Wildcard` — 匹配所有工具(默认行为)
|
||||
///
|
||||
/// # 示例
|
||||
///
|
||||
/// ```
|
||||
/// use crate::agent::hooks::matcher::ToolNamePattern;
|
||||
/// let pat = ToolNamePattern::parse("file_*");
|
||||
/// assert!(pat.matches("file_write"));
|
||||
/// assert!(!pat.matches("search_papers"));
|
||||
/// ```
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ToolNamePattern {
|
||||
/// 精确匹配工具名
|
||||
Exact(String),
|
||||
/// 前缀匹配 — `"file_*"` 匹配所有以 `"file_"` 开头的工具名
|
||||
Prefix(String),
|
||||
/// 匹配所有工具
|
||||
Wildcard,
|
||||
}
|
||||
|
||||
impl ToolNamePattern {
|
||||
/// 从模式字符串解析。
|
||||
///
|
||||
/// - `"*"` 或空字符串 → `Wildcard`
|
||||
/// - `"xxx_*"` → `Prefix("xxx_")`
|
||||
/// - 其他 → `Exact(pattern)`
|
||||
pub fn parse(pattern: &str) -> Self {
|
||||
let trimmed = pattern.trim();
|
||||
if trimmed.is_empty() || trimmed == "*" {
|
||||
return ToolNamePattern::Wildcard;
|
||||
}
|
||||
if let Some(prefix) = trimmed.strip_suffix('*') {
|
||||
if !prefix.is_empty() {
|
||||
return ToolNamePattern::Prefix(prefix.to_string());
|
||||
}
|
||||
// 只有 "*" — 上面已经处理
|
||||
return ToolNamePattern::Wildcard;
|
||||
}
|
||||
ToolNamePattern::Exact(trimmed.to_string())
|
||||
}
|
||||
|
||||
/// 若 `tool_name` 与此模式匹配则返回 true。
|
||||
pub fn matches(&self, tool_name: &str) -> bool {
|
||||
match self {
|
||||
ToolNamePattern::Wildcard => true,
|
||||
ToolNamePattern::Exact(name) => name == tool_name,
|
||||
ToolNamePattern::Prefix(prefix) => tool_name.starts_with(prefix),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Hook 通过 `match_filter()` 声明的结构化过滤器,用于限制关注哪些工具调用。
|
||||
///
|
||||
/// 若 hook 返回非空 `ToolMatchFilter`,则仅当工具名和参数匹配时
|
||||
/// 才调用其 `pre_tool_use` / `post_tool_use`。
|
||||
///
|
||||
/// 默认情况下(空过滤器,等价于 `[Wildcard]`),匹配所有工具。
|
||||
///
|
||||
/// # 示例
|
||||
///
|
||||
/// ```
|
||||
/// use crate::agent::hooks::matcher::{ToolMatchFilter, ToolNamePattern};
|
||||
///
|
||||
/// // 仅匹配文件相关工具
|
||||
/// let filter = ToolMatchFilter {
|
||||
/// name_patterns: vec![ToolNamePattern::parse("file_*")],
|
||||
/// content_patterns: vec![],
|
||||
/// };
|
||||
/// assert!(filter.matches("file_read", &serde_json::json!({})));
|
||||
/// assert!(!filter.matches("search_papers", &serde_json::json!({})));
|
||||
/// ```
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ToolMatchFilter {
|
||||
/// 工具名模式 — 任意一个匹配即可通过。
|
||||
/// 空 Vec = 匹配全部(等价于 `[Wildcard]`)。
|
||||
pub name_patterns: Vec<ToolNamePattern>,
|
||||
/// 可选的内容级模式。格式:`"字段:子串"` 或直接 `"子串"`。
|
||||
/// 例如 `"command:rm *"` 匹配 `run_bash` 调用中 command 字段以 "rm " 开头的情况。
|
||||
/// 空 Vec = 不过滤内容。
|
||||
pub content_patterns: Vec<String>,
|
||||
}
|
||||
|
||||
impl ToolMatchFilter {
|
||||
/// 若此过滤器匹配给定的工具调用则返回 true。
|
||||
///
|
||||
/// 检查流程:
|
||||
/// 1. 若 `name_patterns` 为空,所有工具名匹配
|
||||
/// 2. 任一非通配模式必须匹配 tool_name
|
||||
/// 3. 任一 content_patterns 必须匹配 tool_args 中的某个字段
|
||||
pub fn matches(&self, tool_name: &str, tool_args: &Value) -> bool {
|
||||
// 名称匹配
|
||||
if !self.name_patterns.is_empty() {
|
||||
let name_match = self.name_patterns.iter().any(|pat| pat.matches(tool_name));
|
||||
if !name_match {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 内容匹配:每个模式必须至少匹配一个字段/值
|
||||
if !self.content_patterns.is_empty() {
|
||||
for pattern in &self.content_patterns {
|
||||
if !content_matches(pattern, tool_args) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
/// 快捷构造:创建仅匹配单个工具名的过滤器。
|
||||
pub fn exact(tool_name: &str) -> Self {
|
||||
ToolMatchFilter {
|
||||
name_patterns: vec![ToolNamePattern::Exact(tool_name.to_string())],
|
||||
content_patterns: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// 快捷构造:创建前缀过滤器。
|
||||
pub fn prefix(prefix: &str) -> Self {
|
||||
ToolMatchFilter {
|
||||
name_patterns: vec![ToolNamePattern::Prefix(prefix.to_string())],
|
||||
content_patterns: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// 若此过滤器为默认"匹配全部"(空 name_patterns + 空 content_patterns)则返回 true。
|
||||
pub fn is_match_all(&self) -> bool {
|
||||
self.name_patterns.is_empty() && self.content_patterns.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// 检查内容模式是否匹配 JSON 值中的任意字段。
|
||||
///
|
||||
/// 模式格式:
|
||||
/// - `"字段:值"` — 值必须是该字段字符串表示的子串
|
||||
/// - `"值"` — 值必须出现在 JSON 字符串化后的任意位置
|
||||
fn content_matches(pattern: &str, args: &Value) -> bool {
|
||||
if let Some((field, wanted)) = pattern.split_once(':') {
|
||||
// 匹配指定字段
|
||||
if let Some(field_val) = args.get(field.trim()) {
|
||||
let field_str = match field_val {
|
||||
Value::String(s) => s.clone(),
|
||||
other => other.to_string(),
|
||||
};
|
||||
return field_str.contains(wanted.trim());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// 在 JSON 中任意位置匹配
|
||||
let full_str = serde_json::to_string(args).unwrap_or_default();
|
||||
full_str.contains(pattern.trim())
|
||||
}
|
||||
|
||||
// ── 测试 ──
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// ── ToolNamePattern ──
|
||||
|
||||
#[test]
|
||||
fn test_pattern_exact() {
|
||||
let pat = ToolNamePattern::parse("search_papers");
|
||||
assert!(pat.matches("search_papers"));
|
||||
assert!(!pat.matches("download_paper"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_pattern_prefix() {
|
||||
let pat = ToolNamePattern::parse("file_*");
|
||||
assert!(pat.matches("file_write"));
|
||||
assert!(pat.matches("file_read"));
|
||||
assert!(pat.matches("file_edit"));
|
||||
assert!(!pat.matches("search_papers"));
|
||||
assert!(!pat.matches("fi")); // 前缀比 "file_" 短
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_pattern_wildcard() {
|
||||
let pat = ToolNamePattern::parse("*");
|
||||
assert!(matches!(pat, ToolNamePattern::Wildcard));
|
||||
assert!(pat.matches("anything"));
|
||||
assert!(pat.matches("search_papers"));
|
||||
|
||||
let pat_empty = ToolNamePattern::parse("");
|
||||
assert!(matches!(pat_empty, ToolNamePattern::Wildcard));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_pattern_prefix_no_trailing_wild() {
|
||||
// "file" 不带 * 应被解析为 Exact
|
||||
let pat = ToolNamePattern::parse("file");
|
||||
assert!(matches!(pat, ToolNamePattern::Exact(_)));
|
||||
assert!(pat.matches("file"));
|
||||
assert!(!pat.matches("file_write"));
|
||||
}
|
||||
|
||||
// ── ToolMatchFilter ──
|
||||
|
||||
#[test]
|
||||
fn test_filter_default_matches_all() {
|
||||
let filter = ToolMatchFilter::default();
|
||||
assert!(filter.matches("search_papers", &serde_json::json!({})));
|
||||
assert!(filter.matches("run_bash", &serde_json::json!({"command": "rm -rf /"})));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_exact_name_match() {
|
||||
let filter = ToolMatchFilter::exact("search_papers");
|
||||
assert!(filter.matches("search_papers", &serde_json::json!({})));
|
||||
assert!(!filter.matches("download_paper", &serde_json::json!({})));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_prefix_name_match() {
|
||||
let filter = ToolMatchFilter::prefix("file_");
|
||||
assert!(filter.matches("file_write", &serde_json::json!({})));
|
||||
assert!(filter.matches("file_read", &serde_json::json!({})));
|
||||
assert!(!filter.matches("run_bash", &serde_json::json!({})));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_content_match_field() {
|
||||
let filter = ToolMatchFilter {
|
||||
name_patterns: vec![],
|
||||
content_patterns: vec!["command:rm".to_string()],
|
||||
};
|
||||
assert!(filter.matches(
|
||||
"run_bash",
|
||||
&serde_json::json!({"command": "rm -rf /tmp/test"})
|
||||
));
|
||||
assert!(!filter.matches("run_bash", &serde_json::json!({"command": "ls -la"})));
|
||||
assert!(!filter.matches("read_file", &serde_json::json!({"path": "/tmp/test"})));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_content_match_anywhere() {
|
||||
let filter = ToolMatchFilter {
|
||||
name_patterns: vec![],
|
||||
content_patterns: vec!["dangerous".to_string()],
|
||||
};
|
||||
assert!(filter.matches(
|
||||
"run_bash",
|
||||
&serde_json::json!({"command": "echo dangerous stuff"})
|
||||
));
|
||||
assert!(!filter.matches(
|
||||
"run_bash",
|
||||
&serde_json::json!({"command": "echo safe stuff"})
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_name_and_content_combined() {
|
||||
let filter = ToolMatchFilter {
|
||||
name_patterns: vec![ToolNamePattern::parse("file_*")],
|
||||
content_patterns: vec!["path:.env".to_string()],
|
||||
};
|
||||
// 正确工具名 + 敏感路径 → 匹配
|
||||
assert!(filter.matches("file_read", &serde_json::json!({"path": "/app/.env"})));
|
||||
// 正确工具名 + 安全路径 → 不匹配
|
||||
assert!(!filter.matches("file_read", &serde_json::json!({"path": "/app/README.md"})));
|
||||
// 错误工具名 + 敏感路径 → 不匹配
|
||||
assert!(!filter.matches("run_bash", &serde_json::json!({"path": "/app/.env"})));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_empty_content_false() {
|
||||
// 内容模式指定了不存在的字段 → 不匹配
|
||||
let filter = ToolMatchFilter {
|
||||
name_patterns: vec![],
|
||||
content_patterns: vec!["nonexistent:value".to_string()],
|
||||
};
|
||||
assert!(!filter.matches("run_bash", &serde_json::json!({"command": "ls"})));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_match_all() {
|
||||
assert!(ToolMatchFilter::default().is_match_all());
|
||||
assert!(!ToolMatchFilter::exact("foo").is_match_all());
|
||||
assert!(!ToolMatchFilter {
|
||||
name_patterns: vec![],
|
||||
content_patterns: vec!["cmd:ls".to_string()]
|
||||
}
|
||||
.is_match_all());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user