AstroResearch/src/agent/tools/search_history.rs
Asfmq eaf85707b5 refactor: 全栈架构重构与质量硬化
核心架构重构:
- Config 按职责拆分为 LlmConfig/EmbeddingConfig/VisionConfig/CdsConfig/StorageConfig 五个子结构
- AppState 拆分为 LlmState/DataSourceState/SessionState 三个子结构,消除 50+ 平铺字段
- 新增 ServiceError 结构化错误类型替代 handler 中的 msg.contains() 字符串匹配
- 移除 api::handlers 兼容命名空间,路由直接引用 agent/auth/papers 等模块

认证性能优化:
- login_rate_limiter/upload_rate_limiter 从 Mutex<HashMap> 迁移为 DashMap(无锁)
- 新增 session_last_active: DashMap<String, AtomicU64>,auth 中间件快速路径免写锁
- 会话过期清理改为按间隔触发(300s),避免每次请求全表扫描
- MAX_SESSIONS 1000→10000,SSE 广播通道 256→1024

Agent 工具增强:
- AgentTool trait 新增 is_internal()/display_name(),SSE 事件携带工具元数据
- 新增 GET /chat/tools 端点暴露注册工具列表
- pending_questions/pending_permissions 增加 created_at 时间戳,自动清理过期条目(10min TTL)
- Agent 超时现在正确 abort 后台任务并设置取消令牌

观测数据源修复:
- FITS 解析: APOGEE/DESI 改用 read_image+切片替代 read_rows(修复 fitsio panic)
- ZTF: CIRCLE 参数分隔符 +→空格(修复 IRSA 400),半径自动裁剪至硬上限
- MAST TESS: parse_tic_json 兼容数组/对象两种 API 响应格式
- 统一检索: per_target_limit 默认 50→1,sources 支持 per-source release/version
- Gaia 测光从 VizieR 镜像切换至官方 TAP 服务

RAG 并发优化:
- 向量化降级从串行改为并发 5 条/批(buffer_unordered)
- 混合检索 RRF 合并从借用改为 owned RetrievalResult

安全加固:
- PDF 中间件: URL 解码 %2F/%2E 后判扩展名;文件名过滤非 ASCII + 禁 \ 防头注入
- chat_agent 日志截断问题内容至 50 字符;list_sessions 强制 limit clamp

前端双主题:
- 设计令牌三层架构: primitive→semantic→component,浅色暖纸张学术/暗色 Night Indigo
- useTheme hook + ThemeToggle 侧边栏组件 + main.tsx 防 FOUC 初始化
- 全组件从硬编码 slate 色迁移至语义令牌(bg-surface/text-content/border-subtle 等)
- 新增 ToastContainer 非阻塞通知系统

部署优化:
- deploy.sh 引入 SSH ControlMaster 单次密码复用
2026-07-11 14:57:40 +08:00

146 lines
4.9 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// src/agent/tools/search_history.rs
//
// search_history 工具搜索跨会话历史记录P3 FTS5 集成)。
// Agent 可用此工具查找之前研究过的主题、已发现的结论。
use async_trait::async_trait;
use serde_json::json;
use super::{AgentTool, ToolContext, ToolOutput};
pub struct SearchHistoryTool;
#[async_trait]
impl AgentTool for SearchHistoryTool {
fn name(&self) -> &str {
"search_history"
}
fn display_name(&self) -> &str {
"检索历史"
}
fn is_internal(&self) -> bool {
true
}
fn description(&self) -> &str {
"搜索之前会话的历史记录,查找已研究过的主题、已发现的结论、已下载的文献。\
使用此工具可以避免重复研究已经完成的工作。"
}
fn parameters(&self) -> serde_json::Value {
json!({
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "搜索关键词(支持 FTS5 查询语法,多个词用空格分隔)"
},
"scope": {
"type": "string",
"enum": ["sessions", "messages", "all"],
"description": "搜索范围sessions=会话标题/摘要, messages=消息内容, all=全部",
"default": "all"
}
},
"required": ["query"]
})
}
fn is_concurrency_safe(&self, _args: &serde_json::Value) -> bool {
true
}
fn is_readonly(&self) -> bool {
true
}
fn defer_loading(&self) -> bool {
true
}
async fn execute(&self, args: serde_json::Value, ctx: &ToolContext) -> ToolOutput {
let raw_query = match args.get("query").and_then(|v| v.as_str()) {
Some(q) if !q.is_empty() => q,
_ => return ToolOutput::error("缺少 query 参数"),
};
let query = crate::services::search::sanitize_fts5_query(raw_query);
let scope = args.get("scope").and_then(|v| v.as_str()).unwrap_or("all");
let db = &ctx.app_state.db;
let mut results = Vec::new();
if scope == "all" || scope == "sessions" {
match sqlx::query_as::<_, (String, String, String)>(
"SELECT s.session_id, s.title, \
snippet(agent_sessions_fts, 1, '<mark>', '</mark>', '...', 40) \
FROM agent_sessions_fts fts \
JOIN agent_sessions s ON s.session_id = fts.session_id \
WHERE agent_sessions_fts MATCH $1 ORDER BY rank LIMIT 10",
)
.bind(&query)
.fetch_all(db)
.await
{
Ok(rows) => {
for (sid, title, snippet) in rows {
results.push(json!({
"type": "session",
"session_id": sid,
"title": title,
"snippet": snippet,
}));
}
}
Err(e) => {
tracing::warn!("[SearchHistory] 搜索会话失败: {}", e);
}
}
}
if scope == "all" || scope == "messages" {
match sqlx::query_as::<_, (String, String, String, String)>(
"SELECT fts.session_id, s.title, \
snippet(agent_messages_fts, 2, '<mark>', '</mark>', '...', 80), fts.role \
FROM agent_messages_fts fts \
JOIN agent_sessions s ON s.session_id = fts.session_id \
JOIN agent_messages m ON m.rowid = fts.rowid \
WHERE agent_messages_fts MATCH $1 AND m.active = 1 \
ORDER BY rank LIMIT 10",
)
.bind(&query)
.fetch_all(db)
.await
{
Ok(rows) => {
for (sid, title, snippet, role) in rows {
results.push(json!({
"type": format!("message/{}", role),
"session_id": sid,
"title": title,
"snippet": snippet,
}));
}
}
Err(e) => {
tracing::warn!("[SearchHistory] 搜索消息失败: {}", e);
}
}
}
if results.is_empty() {
ToolOutput::success(
format!("未找到与 \"{}\" 相关的历史记录。", query),
json!({"query": query, "results": [], "count": 0}),
)
} else {
let count = results.len();
ToolOutput::success(
format!("找到 {} 条与 \"{}\" 相关的历史记录", count, query),
json!({"query": query, "results": results, "count": count}),
)
}
}
}