重构: aichat agent 能力系统化(L1元能力+L2/L3后端+list去重)

L1 agent 元能力层(治痛①死循环零交付):
- env_profile 环境姿势注入 + shell 默认 PowerShell(防引号地狱)
- 断路器:同类工具失败≥3熔断 + guard.reset
- detect_environment 主动探测工具(python/node/shell)
- 求助协议 AiHelpRequired 事件 + 前端求助卡

L2 统一状态机后端(治痛②,前端批2):
- ConvState enum 5态 + 合法转换守卫(conv_state.rs)
- GeneratingGuard 接入视图层(guard.rs)

L3 事件总线后端骨架(治痛③④⑤,接入批2):
- EventBus pub-sub + AiBusEvent 8变体(event_bus.rs)

list 工具调用重复治理第一步:
- build_system_prompt_with_excluded 去重被@实体 + 清单注明语
This commit is contained in:
lxy
2026-06-22 00:04:14 +08:00
parent bd6a41fe6e
commit d2cada97cd
16 changed files with 1752 additions and 31 deletions
+99 -12
View File
@@ -31,24 +31,31 @@ pub(crate) async fn get_active_provider(state: &AppState) -> Result<AiProviderRe
}
}
/// 当前运行环境信息(注入 system prompt,供 LLM 写日期/命令时参考)
/// 当前运行环境画像(注入 system prompt):日期 + OS + shell 执行姿势 + 可用解释器。
/// L1 环境感知(治 kms seq26-52 引号地狱):教 AI 避命令行 -c 内联,复杂脚本写文件执行。
///
/// - 日期:LLM 无法自行获取当前日期,不注入则写文件日期全靠猜(常从项目已有文件名模式推断出错)
/// - 操作系统:LLM 写 shell 命令需知道平台(dir vs ls、路径分隔符等)
/// - 日期:LLM 无法自行获取,不注入则写文件日期全靠猜
/// - OS + shell:平台对应 shell(Windows=PowerShell / Linux·macOS=bash),AI 写命令需对齐
/// - 执行姿势:复杂脚本(多行/含引号/$变量)写 .ps1/.py 文件用 `powershell -File`/`python` 执行,
/// 避免命令行 -c 内联(cmd/PowerShell 引号转义易出错,kms 实证 20+ 次失败)
/// - 可用解释器:Windows=python(无 python3);Linux·macOS=python3;node 均有
///
/// 两项合计约 25 token,消除一整类系统性错误。
fn env_info_line() -> String {
/// 跨设备:cfg! 分支,平台各自正确姿势。补充探测见 detect_environment 工具(失败自愈)。
fn env_profile_line() -> String {
let today = chrono::Local::now().format("%Y-%m-%d");
let os = if cfg!(target_os = "windows") {
"Windows"
let (os, shell, interp) = if cfg!(target_os = "windows") {
("Windows", "PowerShell", "python(无 python3)、node")
} else if cfg!(target_os = "macos") {
"macOS"
("macOS", "bash/zsh", "python3、node")
} else if cfg!(target_os = "linux") {
"Linux"
("Linux", "bash", "python3、node")
} else {
"Unknown"
("Unknown", "sh", "python3、node")
};
format!("当前日期: {today} | 运行环境: {os}\n\n")
format!(
"当前日期: {today} | 运行环境: {os} | shell: {shell}\n\
执行姿势: 复杂脚本(多行/含引号/$变量)写成 .ps1 或 .py 文件,用 `powershell -File x.ps1` 或 `python x.py` 执行,避免命令行 -c 内联(引号转义易出错)。可用解释器: {interp}。\n\n"
)
}
/// 按语言返回系统提示词的 (固定前缀, 项目上下文标题, 任务上下文标题)
@@ -113,9 +120,34 @@ fn system_prompt_parts(lang: &str) -> (&'static str, &'static str, &'static str)
/// 非 build_system_prompt 职责 —— 两套并行:全局清单(全貌)+ augmentation(用户本次引用)。
///
/// 注入克制:仅各取最近 20 条,防 context 膨胀。
///
/// 保留旧签名供 agentic/mod.rs(无 mention 场景)等零改动调用,内部委托给
/// [`build_system_prompt_with_excluded`] 传两个空排除列表(无去重)。
pub(crate) async fn build_system_prompt(state: &AppState, lang: &str) -> String {
build_system_prompt_with_excluded(state, lang, &[], &[]).await
}
/// 构建系统提示词(可去重版本)——主路径 chat.rs send / force_send 调用。
///
/// 与 [`build_system_prompt`] 的差异(机制而非说教):
/// 1. **去重**:被 @ 的 project/task 已由 augmentation 层精准投影(含 path/正文),清单中
/// 再现会造成同一实体两次入 prompt(实测 build f64dee94 会话 list_projects 8 次 /
/// list_tasks 20 次)。此处把 `excluded_project_ids`/`excluded_task_ids` 命中的条目
/// 从全局清单循环中跳过,被@实体只保留 augmentation 一次。
/// 2. **注明语**:清单末尾按语言追加一行,告知 LLM 「项目已全部列出无需再调 list_projects」/
/// 「任务仅最近 20 条,全量查询请用 list_tasks」,从机制层降低工具与清单重复调用
/// (而非在行为准则里反复说教)。
///
/// - 空排除列表(无 mention 的调用)与 [`build_system_prompt`] 行为完全等价(仅多一行注明语)。
/// - 注入克制策略不变:仍各 take(20)。
pub(crate) async fn build_system_prompt_with_excluded(
state: &AppState,
lang: &str,
excluded_project_ids: &[String],
excluded_task_ids: &[String],
) -> String {
let (prefix, proj_label, task_label) = system_prompt_parts(lang);
let mut prompt = env_info_line();
let mut prompt = env_profile_line();
prompt.push_str(prefix);
// 附加当前数据上下文
@@ -123,9 +155,15 @@ pub(crate) async fn build_system_prompt(state: &AppState, lang: &str) -> String
if !projects.is_empty() {
prompt.push_str(proj_label);
// system prompt 前缀克制:仅最近 20 个项目,防 context 膨胀
// 去重:被 @ 的项目跳过(已有 augmentation 精准投影,清单再现致同一实体两次入 prompt)
for p in projects.iter().take(20) {
if excluded_project_ids.iter().any(|id| id == &p.id) {
continue;
}
prompt.push_str(&format!("- {} ({}): {}\n", p.name, p.status, p.description));
}
// 机制层注明语(中/英):项目已全部列出,降 list_projects 重复调用
prompt.push_str(&projects_listed_note(lang, 20));
}
}
// 任务全貌清单(供 LLM 知道存在哪些任务;被@任务的精准投影走 augmentation 层)
@@ -133,15 +171,48 @@ pub(crate) async fn build_system_prompt(state: &AppState, lang: &str) -> String
if let Ok(tasks) = state.tasks.list_active().await {
if !tasks.is_empty() {
prompt.push_str(task_label);
// 去重:被 @ 的任务跳过(同项目去重机理)
for tk in tasks.iter().take(20) {
if excluded_task_ids.iter().any(|id| id == &tk.id) {
continue;
}
prompt.push_str(&format!("- {} ({}): {}\n", tk.title, tk.status, tk.description));
}
// 机制层注明语(中/英):仅最近 20 条,全量/按项目查询走 list_tasks
prompt.push_str(&tasks_listed_note(lang));
}
}
prompt
}
/// 项目清单尾部注明语(中/英)。
///
/// 机制层降重复:直接告知「已全部列出」,LLM 知道再调 list_projects 是冗余。
/// `shown` 取实际注入条数上限 20(避免传运态 list_active 长度,只描述清单本身)。
fn projects_listed_note(lang: &str, shown: usize) -> String {
match lang {
"en" => format!(
"(Listed {} active projects above; the active set is shown, no need to call list_projects again.)\n",
shown
),
_ => format!(
"(以上为活跃项目清单,无需重复调用 list_projects)\n"
),
}
}
/// 任务清单尾部注明语(中/英)。
///
/// 机制层降重复:明确「仅最近 20 条 + 全量查询走 list_tasks」,避免 LLM 误以为清单即全量
/// 而反复调 list_tasks 校验(实测单会话 20 次)。
fn tasks_listed_note(lang: &str) -> String {
match lang {
"en" => "(Only the 20 most recent tasks are shown. For the full list or filtered by project, use the list_tasks tool.)\n".to_string(),
_ => "(仅显示最近 20 条任务,全量或按项目查询请用 list_tasks 工具)\n".to_string(),
}
}
/// 上下文压缩 system prompt 模板(F-15 §4.2,纯函数无 IO)。
///
/// 引导 LLM 把对话压缩为四段式结构化摘要(意图/决策/文件/约束),最大化保留
@@ -284,4 +355,20 @@ mod tests {
assert!(en.contains("topic words"));
assert!(en.contains("breaks the context"));
}
// 项目/任务清单注明语(中/英)存在
#[test]
fn listed_notes_present_zh_en() {
let zh_proj = projects_listed_note("zh-CN", 20);
assert!(zh_proj.contains("无需重复调用 list_projects"));
let en_proj = projects_listed_note("en", 20);
assert!(en_proj.contains("no need to call list_projects"));
let zh_task = tasks_listed_note("zh-CN");
assert!(zh_task.contains("仅显示最近 20 条任务"));
assert!(zh_task.contains("list_tasks"));
let en_task = tasks_listed_note("en");
assert!(en_task.contains("20 most recent tasks"));
assert!(en_task.contains("list_tasks"));
}
}