feat: Docker 容器化、Cookie 鉴权、Coordinator 编排、FTS5 搜索与 P1-P3 全面收尾

Docker 容器化部署
  - 提供 Mode A (Alpine musl, ~23MB) 和 Mode B (Distroless glibc, ~87MB)
    两种镜像,Docker Compose 一键启动
  - build.rs 支持 SKIP_DASHBOARD_BUILD 跳过前端构建
  - 国内镜像加速 (npm/apt/apk) 通过 USE_MIRRORS build-arg 控制

  安全:Cookie-Based 鉴权系统
  - HttpOnly/SameSite=Strict Cookie 会话管理(24h 过期自动清理)
  - 登录/登出/验证接口 + 中间件注入
  - 前端登录页面 + 退出按钮
  - 三层 CORS:localhost 鉴权 / 全放通 bookmarklet / 受保护路由
  - 书签脚本 fetch 添加 credentials:'include'

  Coordinator 模式 (P2)
  - 4 个 meta-tool (delegate_task/check_task/task_stop/synthesize)
  - WorkerPool + Semaphore 并发控制 + 超时保护
  - 前端协调者模式开关

  Hook 系统:UserPromptSubmit 事件 (P2)
  - 第 13 个生命周期事件,fire-and-forget 审计

  FTS5 全文搜索 (P3)
  - agent_sessions_fts + agent_messages_fts 虚拟表
  - search_history Agent 工具 + /api/search/history HTTP 接口
  - 前端防抖搜索框 + 仅当前会话筛选

  工具加载优化 (P3)
  - defer_loading 延迟加载 (7 个重型工具)
  - is_readonly 只读标记 (9 个查询工具)
  - classifier_summary 工具目录供 LLM 按需判断

  模型回退策略 (P3)
  - LLM_FALLBACK_MODEL 优先回退 + LLM_FALLBACK_CHAIN 链式轮换
  - LlmClient model 改为 Arc<RwLock> 支持运行时切换
  - 连续 3 次过载后自动切换

  压缩记忆桥接 (P3)
  - 压缩丢弃消息 → 子代理提取持久记忆 (extract_memories_from_compaction)

  git2 依赖修复
  - 切换到 vendored-libgit2,消除 OpenSSL 系统依赖
This commit is contained in:
fmq
2026-06-23 20:22:06 +08:00
parent 698d007f39
commit cec4b8cf7b
58 changed files with 3366 additions and 345 deletions
+88 -21
View File
@@ -40,7 +40,9 @@ use tracing::{error, info, warn};
use super::background::BgNotificationQueue;
use super::compact;
use super::hooks::{HookRegistry, SessionStartContext, StepCompleteContext};
use super::hooks::{
HookRegistry, SessionStartContext, StepCompleteContext, UserPromptSubmitContext,
};
use super::terminal::TurnTerminal;
use super::tools::ToolRegistry;
use crate::api::AppState;
@@ -313,6 +315,8 @@ pub struct AgentRuntime {
collapse_log: Arc<std::sync::Mutex<compact::collapse::CollapseLog>>,
/// Checkpoint 管理器(跨 turn 共享,文件变更操作前自动快照)
checkpoint_manager: Arc<checkpoint::CheckpointManager>,
/// 是否启用协调者模式(Coordinator delegates to Workers
coordinator_mode: bool,
}
impl AgentRuntime {
@@ -370,6 +374,7 @@ impl AgentRuntime {
prompt_cache: std::sync::Mutex::new(SystemPromptCache::new()),
collapse_log: Arc::new(std::sync::Mutex::new(compact::collapse::CollapseLog::new())),
checkpoint_manager,
coordinator_mode: false,
}
}
@@ -424,6 +429,7 @@ impl AgentRuntime {
prompt_cache: std::sync::Mutex::new(SystemPromptCache::new()),
collapse_log: Arc::new(std::sync::Mutex::new(compact::collapse::CollapseLog::new())),
checkpoint_manager,
coordinator_mode: false,
}
}
@@ -442,6 +448,41 @@ impl AgentRuntime {
self
}
/// 设置是否启用协调者模式
pub fn with_coordinator_mode(mut self, enabled: bool) -> Self {
self.coordinator_mode = enabled;
self
}
// ── Coordinator Mode ──
/// 运行协调者模式 turn:创建 CoordinatorAgent 并委托执行。
async fn run_coordinator_turn(
&self,
session_info: &session::SessionInfo,
question: &str,
tx: mpsc::UnboundedSender<AgentStreamEvent>,
) -> anyhow::Result<String> {
use super::coordinator::agent::CoordinatorAgent;
use super::coordinator::CoordinatorConfig;
let coordinator_config = CoordinatorConfig::default();
let coordinator = CoordinatorAgent::new(
self.app_state.clone(),
self.config.clone(),
coordinator_config,
);
coordinator
.run(
&session_info.session_id,
question,
session_info.turn_index,
tx,
)
.await
}
// ── Private Helpers ──
/// 执行文件缓存快照 → 压缩 → 恢复 → 上下文注入 的完整周期。
@@ -466,6 +507,10 @@ impl AgentRuntime {
}
};
// 压缩前捕获消息快照(用于记忆提取桥接,P3)
let pre_compact_snapshot: Vec<crate::clients::llm::ChatMessage> =
messages.iter().cloned().collect();
compact::compress_context_with_hooks_and_log(
messages,
llm,
@@ -476,6 +521,14 @@ impl AgentRuntime {
)
.await;
// 压缩后提取记忆(P3 桥接:将丢弃的消息内容喂给记忆提取子代理)
compact::extract_memories_from_compaction(
&pre_compact_snapshot,
session_id,
self.app_state.memory_manager.clone(),
self.app_state.clone(),
);
// ── 文件缓存恢复(压缩后:重新注入最近文件 + 恢复缓存)──
{
if let Ok(mut cache) = self.read_file_state.lock() {
@@ -517,6 +570,11 @@ impl AgentRuntime {
// Phase 1: 创建或恢复会话
let session_info = session::create_or_resume_session(db, session_id.clone(), llm).await?;
// 协调者模式分支:委托给 CoordinatorAgent
if self.coordinator_mode {
return self.run_coordinator_turn(&session_info, question, tx).await;
}
// 构建 hook 注册表(注入依赖,复用 AgentRuntime 的 metrics_data
let hook_registry = HookRegistry::with_builtins(
db.clone(),
@@ -533,6 +591,15 @@ impl AgentRuntime {
})
.await;
// 触发 UserPromptSubmit —— hooks 可在上下文构建前检查/记录用户输入
hook_registry
.run_on_user_prompt_submit(&UserPromptSubmitContext {
session_id: session_info.session_id.clone(),
prompt: question.to_string(),
turn_index: session_info.turn_index,
})
.await;
let _ = tx.send(AgentStreamEvent::Session {
session_id: session_info.session_id.clone(),
title: String::new(),
@@ -566,6 +633,7 @@ impl AgentRuntime {
// Phase 4: 会话收尾(传入实际的终止原因 + trajectory 导出参数)
let system_prompt = self.system_prompt();
let model_name = self.app_state.llm.model();
finalize::finalize_turn(
db,
&session_info.session_id,
@@ -575,7 +643,7 @@ impl AgentRuntime {
&hook_registry,
loop_terminal,
Some(&self.app_state.config.library_dir),
Some(self.app_state.llm.model()),
Some(&model_name),
Some(&system_prompt),
Some(self.app_state.clone()),
)
@@ -1164,14 +1232,25 @@ impl AgentRuntime {
if matches!(error_kind, ErrorKind::Overloaded) {
consecutive_overloads += 1;
if consecutive_overloads >= 3 {
if let Ok(fallback) = std::env::var("FALLBACK_MODEL") {
let fallback = &self.app_state.config.llm_fallback_model;
if !fallback.is_empty() {
warn!(
"[AgentRuntime] 连续 {} 次过载,切换到备用模型: {}",
consecutive_overloads, fallback
);
// Note: The LlmClient model is immutable. In production,
// this would require a model-override capable client.
// For now, log and continue retrying with current model.
llm.set_model(fallback.clone());
consecutive_overloads = 0;
} else if !self.app_state.config.llm_fallback_chain.is_empty() {
let idx = ((consecutive_overloads as usize - 3)
% self.app_state.config.llm_fallback_chain.len())
.min(self.app_state.config.llm_fallback_chain.len() - 1);
let alt = &self.app_state.config.llm_fallback_chain[idx];
warn!(
"[AgentRuntime] 连续 {} 次过载,从链中切换: {}",
consecutive_overloads, alt
);
llm.set_model(alt.clone());
consecutive_overloads = 0;
}
}
}
@@ -1390,22 +1469,10 @@ impl AgentRuntime {
let env_section = cache.get_or_compute("environment", || self.build_environment_section());
sp.add_section("environment", env_section);
// 工具列表:ToolRegistry 在 session 内不变
// 工具目录:使用 tool_catalog() 列出常驻+延迟工具(P3 defer_loading 集成)
let tools_section = cache.get_or_compute("tools", || {
let mut tools_desc = String::from("你可以使用以下工具:\n");
for def in self.tool_registry.definitions() {
let short_desc: String = def
.function
.description
.split('。')
.next()
.unwrap_or(&def.function.description)
.chars()
.take(80)
.collect();
tools_desc.push_str(&format!("- {}: {}\n", def.function.name, short_desc));
}
tools_desc
let catalog = self.tool_registry.tool_catalog();
format!("你可以使用以下工具([deferred] 标记的工具需要通过 load_skill 发现详情):\n{}", catalog)
});
sp.add_section("tools", tools_section);