Compare commits
2 Commits
495c8cdc7e
...
7c48a0f7f9
| Author | SHA1 | Date | |
|---|---|---|---|
| 7c48a0f7f9 | |||
| aa7f1d6160 |
@ -61,13 +61,8 @@ impl SchedulerMaintenanceService {
|
||||
self.session_manager.cleanup_expired_sessions().await
|
||||
}
|
||||
|
||||
async fn run_memory_maintenance(
|
||||
&self,
|
||||
updated_since: Option<i64>,
|
||||
) -> Result<Vec<MemoryMaintenanceScopeResult>, AgentError> {
|
||||
self.session_manager
|
||||
.run_memory_maintenance_for_all_scopes(updated_since)
|
||||
.await
|
||||
async fn run_memory_maintenance(&self) -> Result<Vec<MemoryMaintenanceScopeResult>, AgentError> {
|
||||
self.session_manager.run_memory_maintenance_for_all_scopes().await
|
||||
}
|
||||
}
|
||||
|
||||
@ -77,11 +72,8 @@ impl MaintenanceExecutor for SchedulerMaintenanceService {
|
||||
self.cleanup_sessions().await
|
||||
}
|
||||
|
||||
async fn run_memory_maintenance_for_all_scopes(
|
||||
&self,
|
||||
updated_since: Option<i64>,
|
||||
) -> anyhow::Result<Vec<MaintenanceRunSummary>> {
|
||||
self.run_memory_maintenance(updated_since)
|
||||
async fn run_memory_maintenance_for_all_scopes(&self) -> anyhow::Result<Vec<MaintenanceRunSummary>> {
|
||||
self.run_memory_maintenance()
|
||||
.await
|
||||
.map(|results| {
|
||||
results
|
||||
|
||||
@ -220,22 +220,10 @@ impl MemoryMaintenanceService {
|
||||
|
||||
pub(crate) async fn run_for_all_scopes(
|
||||
&self,
|
||||
updated_since: Option<i64>,
|
||||
) -> Result<Vec<MemoryMaintenanceScopeResult>, AgentError> {
|
||||
let scope_keys = if let Some(cutoff) = updated_since {
|
||||
self.store
|
||||
.list_memory_scope_keys_updated_since("user", cutoff)
|
||||
.map_err(|err| {
|
||||
AgentError::Other(format!(
|
||||
"list memory scope keys updated since error: {}",
|
||||
err
|
||||
))
|
||||
})?
|
||||
} else {
|
||||
self.store.list_memory_scope_keys("user").map_err(|err| {
|
||||
let scope_keys = self.store.list_memory_scope_keys("user").map_err(|err| {
|
||||
AgentError::Other(format!("list memory scope keys error: {}", err))
|
||||
})?
|
||||
};
|
||||
})?;
|
||||
let mut results = Vec::new();
|
||||
|
||||
for scope_key in scope_keys {
|
||||
|
||||
@ -32,9 +32,8 @@ impl MemoryMaintenanceCoordinator {
|
||||
|
||||
pub(crate) async fn run_for_all_scopes(
|
||||
&self,
|
||||
updated_since: Option<i64>,
|
||||
) -> Result<Vec<MemoryMaintenanceScopeResult>, AgentError> {
|
||||
self.service()?.run_for_all_scopes(updated_since).await
|
||||
self.service()?.run_for_all_scopes().await
|
||||
}
|
||||
|
||||
fn service(&self) -> Result<MemoryMaintenanceService, AgentError> {
|
||||
|
||||
@ -4,23 +4,63 @@ use std::path::{Path, PathBuf};
|
||||
use crate::agent::AgentError;
|
||||
|
||||
pub(crate) const DEFAULT_AGENT_PROMPT: &str = include_str!("default_agent_prompt.md");
|
||||
pub(crate) const MANAGED_AGENT_MEMORY_BLOCK_START: &str = "<!-- PICOBOT_MANAGED_MEMORY:START -->";
|
||||
pub(crate) const MANAGED_AGENT_MEMORY_BLOCK_END: &str = "<!-- PICOBOT_MANAGED_MEMORY:END -->";
|
||||
pub(crate) const MANAGED_AGENT_MEMORY_TITLE: &str = "## 用户记忆摘要";
|
||||
|
||||
#[derive(Clone)]
|
||||
struct PromptSource {
|
||||
path: PathBuf,
|
||||
default_content: Option<&'static str>,
|
||||
}
|
||||
|
||||
pub(crate) fn load_agent_prompt() -> Result<Option<String>, AgentError> {
|
||||
let path = agent_prompt_path()?;
|
||||
if let Some(parent) = path.parent() {
|
||||
fs::create_dir_all(parent)
|
||||
.map_err(|err| AgentError::Other(format!("create agent prompt dir error: {}", err)))?;
|
||||
load_prompt_from_sources(&prompt_sources()?)
|
||||
}
|
||||
|
||||
pub(crate) fn upsert_managed_agent_memory_summary(markdown_body: &str) -> Result<(), AgentError> {
|
||||
persist_memory_summary(&memory_summary_path()?, markdown_body)
|
||||
}
|
||||
|
||||
fn prompt_sources() -> Result<Vec<PromptSource>, AgentError> {
|
||||
Ok(vec![
|
||||
PromptSource {
|
||||
path: agent_prompt_path()?,
|
||||
default_content: Some(DEFAULT_AGENT_PROMPT),
|
||||
},
|
||||
PromptSource {
|
||||
path: memory_summary_path()?,
|
||||
default_content: None,
|
||||
},
|
||||
])
|
||||
}
|
||||
|
||||
fn load_prompt_from_sources(sources: &[PromptSource]) -> Result<Option<String>, AgentError> {
|
||||
let mut fragments = Vec::with_capacity(sources.len());
|
||||
|
||||
for source in sources {
|
||||
if let Some(fragment) = read_prompt_fragment(source)? {
|
||||
fragments.push(fragment);
|
||||
}
|
||||
}
|
||||
|
||||
if !path.exists() {
|
||||
write_agent_prompt(&path, DEFAULT_AGENT_PROMPT)?;
|
||||
if fragments.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let content = fs::read_to_string(&path)
|
||||
.map_err(|err| AgentError::Other(format!("read agent prompt file error: {}", err)))?;
|
||||
Ok(Some(fragments.join("\n\n")))
|
||||
}
|
||||
|
||||
fn read_prompt_fragment(source: &PromptSource) -> Result<Option<String>, AgentError> {
|
||||
ensure_parent_dir(&source.path)?;
|
||||
|
||||
if !source.path.exists() {
|
||||
if let Some(default_content) = source.default_content {
|
||||
write_prompt_file(&source.path, default_content)?;
|
||||
} else {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
|
||||
let content = fs::read_to_string(&source.path)
|
||||
.map_err(|err| AgentError::Other(format!("read prompt file error: {}", err)))?;
|
||||
let trimmed = content.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Ok(None);
|
||||
@ -29,121 +69,151 @@ pub(crate) fn load_agent_prompt() -> Result<Option<String>, AgentError> {
|
||||
Ok(Some(trimmed.to_string()))
|
||||
}
|
||||
|
||||
pub(crate) fn upsert_managed_agent_memory_summary(markdown_body: &str) -> Result<(), AgentError> {
|
||||
let path = agent_prompt_path()?;
|
||||
let existing = if path.exists() {
|
||||
fs::read_to_string(&path)
|
||||
.map_err(|err| AgentError::Other(format!("read agent prompt file error: {}", err)))?
|
||||
} else {
|
||||
DEFAULT_AGENT_PROMPT.to_string()
|
||||
};
|
||||
let updated = upsert_managed_agent_memory_block(&existing, markdown_body);
|
||||
write_agent_prompt(&path, &updated)
|
||||
}
|
||||
|
||||
pub(crate) fn upsert_managed_agent_memory_block(existing: &str, markdown_body: &str) -> String {
|
||||
let managed_block = render_managed_agent_memory_block(markdown_body);
|
||||
|
||||
if let (Some(start), Some(end)) = (
|
||||
existing.find(MANAGED_AGENT_MEMORY_BLOCK_START),
|
||||
existing.find(MANAGED_AGENT_MEMORY_BLOCK_END),
|
||||
) {
|
||||
let end = end + MANAGED_AGENT_MEMORY_BLOCK_END.len();
|
||||
let mut updated = String::new();
|
||||
updated.push_str(existing[..start].trim_end());
|
||||
updated.push_str("\n\n");
|
||||
updated.push_str(&managed_block);
|
||||
updated.push_str("\n\n");
|
||||
updated.push_str(existing[end..].trim_start());
|
||||
return updated.trim().to_string() + "\n";
|
||||
fn persist_memory_summary(path: &Path, markdown_body: &str) -> Result<(), AgentError> {
|
||||
let trimmed = markdown_body.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if let Some(reply_rules_index) = existing.find("## 回复规则") {
|
||||
let mut updated = String::new();
|
||||
updated.push_str(existing[..reply_rules_index].trim_end());
|
||||
updated.push_str("\n\n");
|
||||
updated.push_str(&managed_block);
|
||||
updated.push_str("\n\n");
|
||||
updated.push_str(existing[reply_rules_index..].trim_start());
|
||||
return updated.trim().to_string() + "\n";
|
||||
}
|
||||
|
||||
let mut updated = existing.trim_end().to_string();
|
||||
if !updated.is_empty() {
|
||||
updated.push_str("\n\n");
|
||||
}
|
||||
updated.push_str(&managed_block);
|
||||
updated.push('\n');
|
||||
updated
|
||||
write_prompt_file(path, trimmed)
|
||||
}
|
||||
|
||||
fn render_managed_agent_memory_block(markdown_body: &str) -> String {
|
||||
format!(
|
||||
"{MANAGED_AGENT_MEMORY_BLOCK_START}\n{MANAGED_AGENT_MEMORY_TITLE}\n\n{}\n{MANAGED_AGENT_MEMORY_BLOCK_END}",
|
||||
markdown_body.trim()
|
||||
)
|
||||
fn write_prompt_file(path: &Path, content: &str) -> Result<(), AgentError> {
|
||||
ensure_parent_dir(path)?;
|
||||
|
||||
let normalized = content.trim_end().to_string() + "\n";
|
||||
let temp_path = path.with_extension("md.tmp");
|
||||
fs::write(&temp_path, normalized)
|
||||
.map_err(|err| AgentError::Other(format!("write prompt temp file error: {}", err)))?;
|
||||
fs::rename(&temp_path, path)
|
||||
.map_err(|err| AgentError::Other(format!("replace prompt file error: {}", err)))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_agent_prompt(path: &Path, content: &str) -> Result<(), AgentError> {
|
||||
fn ensure_parent_dir(path: &Path) -> Result<(), AgentError> {
|
||||
if let Some(parent) = path.parent() {
|
||||
fs::create_dir_all(parent)
|
||||
.map_err(|err| AgentError::Other(format!("create agent prompt dir error: {}", err)))?;
|
||||
}
|
||||
|
||||
let temp_path = path.with_extension("md.tmp");
|
||||
fs::write(&temp_path, content)
|
||||
.map_err(|err| AgentError::Other(format!("write agent prompt temp file error: {}", err)))?;
|
||||
fs::rename(&temp_path, path)
|
||||
.map_err(|err| AgentError::Other(format!("replace agent prompt file error: {}", err)))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn agent_prompt_path() -> Result<PathBuf, AgentError> {
|
||||
Ok(agent_dir_path()?.join("AGENT.md"))
|
||||
}
|
||||
|
||||
fn memory_summary_path() -> Result<PathBuf, AgentError> {
|
||||
Ok(agent_dir_path()?.join("MEMORY_SUMMARY.md"))
|
||||
}
|
||||
|
||||
fn agent_dir_path() -> Result<PathBuf, AgentError> {
|
||||
let home = dirs::home_dir()
|
||||
.ok_or_else(|| AgentError::Other("home directory not found".to_string()))?;
|
||||
Ok(home.join(".picobot").join("agent").join("AGENT.md"))
|
||||
Ok(home.join(".picobot").join("agent"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[test]
|
||||
fn test_upsert_managed_agent_memory_block_inserts_before_reply_rules() {
|
||||
let original =
|
||||
"# PicoBot 代理配置\n\n## 身份\n- 你是 PicoBot。\n\n## 回复规则\n- 使用中文回复。\n";
|
||||
let updated = upsert_managed_agent_memory_block(
|
||||
original,
|
||||
"### 用户事实\n- 用户在做AI产品\n\n### 用户偏好\n- 偏好简洁表达",
|
||||
);
|
||||
fn test_load_prompt_from_sources_aggregates_multiple_fragments_in_order() {
|
||||
let temp = tempdir().unwrap();
|
||||
let agent_path = temp.path().join("AGENT.md");
|
||||
let memory_path = temp.path().join("MEMORY_SUMMARY.md");
|
||||
|
||||
let managed_pos = updated.find(MANAGED_AGENT_MEMORY_BLOCK_START).unwrap();
|
||||
let reply_rules_pos = updated.find("## 回复规则").unwrap();
|
||||
assert!(managed_pos < reply_rules_pos);
|
||||
assert!(updated.contains(MANAGED_AGENT_MEMORY_TITLE));
|
||||
assert!(updated.contains("用户在做AI产品"));
|
||||
assert!(updated.contains("偏好简洁表达"));
|
||||
write_prompt_file(&agent_path, "# Agent\n静态规则").unwrap();
|
||||
write_prompt_file(&memory_path, "## 用户记忆摘要\n- 偏好简洁").unwrap();
|
||||
|
||||
let prompt = load_prompt_from_sources(&[
|
||||
PromptSource {
|
||||
path: agent_path.clone(),
|
||||
default_content: Some(DEFAULT_AGENT_PROMPT),
|
||||
},
|
||||
PromptSource {
|
||||
path: memory_path.clone(),
|
||||
default_content: None,
|
||||
},
|
||||
])
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(prompt, "# Agent\n静态规则\n\n## 用户记忆摘要\n- 偏好简洁");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_upsert_managed_agent_memory_block_replaces_existing_block() {
|
||||
let original = format!(
|
||||
"# PicoBot\n\n{MANAGED_AGENT_MEMORY_BLOCK_START}\n{MANAGED_AGENT_MEMORY_TITLE}\n\nold\n{MANAGED_AGENT_MEMORY_BLOCK_END}\n\n## 回复规则\n- 简洁。\n"
|
||||
);
|
||||
fn test_load_prompt_from_sources_ignores_missing_optional_source() {
|
||||
let temp = tempdir().unwrap();
|
||||
let agent_path = temp.path().join("AGENT.md");
|
||||
let memory_path = temp.path().join("MEMORY_SUMMARY.md");
|
||||
|
||||
let updated = upsert_managed_agent_memory_block(&original, "new");
|
||||
write_prompt_file(&agent_path, "# Agent\n静态规则").unwrap();
|
||||
|
||||
assert!(updated.contains("new"));
|
||||
assert!(!updated.contains("old"));
|
||||
assert_eq!(updated.matches(MANAGED_AGENT_MEMORY_BLOCK_START).count(), 1);
|
||||
assert_eq!(updated.matches(MANAGED_AGENT_MEMORY_BLOCK_END).count(), 1);
|
||||
let prompt = load_prompt_from_sources(&[
|
||||
PromptSource {
|
||||
path: agent_path.clone(),
|
||||
default_content: Some(DEFAULT_AGENT_PROMPT),
|
||||
},
|
||||
PromptSource {
|
||||
path: memory_path.clone(),
|
||||
default_content: None,
|
||||
},
|
||||
])
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(prompt, "# Agent\n静态规则");
|
||||
assert!(!memory_path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_upsert_managed_agent_memory_block_trims_summary_body() {
|
||||
let updated = upsert_managed_agent_memory_block("# PicoBot\n", "\n\nsummary\n\n");
|
||||
fn test_load_prompt_from_sources_creates_default_agent_prompt() {
|
||||
let temp = tempdir().unwrap();
|
||||
let agent_path = temp.path().join("AGENT.md");
|
||||
|
||||
assert!(updated.contains("\n\nsummary\n"));
|
||||
assert!(!updated.contains("\n\nsummary\n\n\n"));
|
||||
let prompt = load_prompt_from_sources(&[PromptSource {
|
||||
path: agent_path.clone(),
|
||||
default_content: Some("# Default Agent\n规则"),
|
||||
}])
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(prompt, "# Default Agent\n规则");
|
||||
assert_eq!(fs::read_to_string(&agent_path).unwrap(), "# Default Agent\n规则\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_load_prompt_from_sources_returns_none_when_all_sources_empty() {
|
||||
let temp = tempdir().unwrap();
|
||||
let agent_path = temp.path().join("AGENT.md");
|
||||
let memory_path = temp.path().join("MEMORY_SUMMARY.md");
|
||||
|
||||
write_prompt_file(&agent_path, " ").unwrap();
|
||||
write_prompt_file(&memory_path, "\n\n").unwrap();
|
||||
|
||||
let prompt = load_prompt_from_sources(&[
|
||||
PromptSource {
|
||||
path: agent_path.clone(),
|
||||
default_content: None,
|
||||
},
|
||||
PromptSource {
|
||||
path: memory_path.clone(),
|
||||
default_content: None,
|
||||
},
|
||||
])
|
||||
.unwrap();
|
||||
|
||||
assert!(prompt.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_upsert_managed_agent_memory_summary_writes_trimmed_markdown() {
|
||||
let temp = tempdir().unwrap();
|
||||
let memory_path = temp.path().join("MEMORY_SUMMARY.md");
|
||||
|
||||
persist_memory_summary(&memory_path, "\n## 用户记忆摘要\n- 偏好简洁\n\n").unwrap();
|
||||
|
||||
assert_eq!(fs::read_to_string(&memory_path).unwrap(), "## 用户记忆摘要\n- 偏好简洁\n");
|
||||
}
|
||||
}
|
||||
|
||||
@ -420,11 +420,8 @@ impl SessionManager {
|
||||
|
||||
pub(crate) async fn run_memory_maintenance_for_all_scopes(
|
||||
&self,
|
||||
updated_since: Option<i64>,
|
||||
) -> Result<Vec<MemoryMaintenanceScopeResult>, AgentError> {
|
||||
self.memory_maintenance
|
||||
.run_for_all_scopes(updated_since)
|
||||
.await
|
||||
self.memory_maintenance.run_for_all_scopes().await
|
||||
}
|
||||
|
||||
/// 确保 session 存在且未超时,超时则重建
|
||||
@ -1239,18 +1236,34 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_run_memory_maintenance_for_all_scopes_returns_empty_when_no_recent_updates() {
|
||||
async fn test_run_memory_maintenance_for_all_scopes_scans_all_scopes_even_without_recent_updates() {
|
||||
let mock_response_content = serde_json::to_string(&json!({
|
||||
"user_facts": ["用户在做AI产品"],
|
||||
"preferences": [],
|
||||
"behavior_patterns": [],
|
||||
"merges": [],
|
||||
"conflicts": [],
|
||||
"low_value_ids": [],
|
||||
"managed_markdown": "### 用户事实\n- 用户在做AI产品"
|
||||
}))
|
||||
.unwrap();
|
||||
let base_url =
|
||||
start_mock_openai_server_with_content(Some(mock_response_content.clone())).await;
|
||||
|
||||
let provider_config = LLMProviderConfig {
|
||||
provider_type: "openai".to_string(),
|
||||
name: "maintenance-provider".to_string(),
|
||||
base_url: "http://localhost".to_string(),
|
||||
base_url,
|
||||
api_key: "test-key".to_string(),
|
||||
extra_headers: HashMap::new(),
|
||||
model_id: "maintenance-model".to_string(),
|
||||
temperature: Some(0.0),
|
||||
max_tokens: Some(256),
|
||||
context_window_tokens: None,
|
||||
model_extra: HashMap::new(),
|
||||
model_extra: HashMap::from([(
|
||||
"mock_response_content".to_string(),
|
||||
json!(mock_response_content),
|
||||
)]),
|
||||
max_tool_iterations: 1,
|
||||
llm_timeout_secs: 30,
|
||||
tool_result_max_chars: 20_000,
|
||||
@ -1268,7 +1281,7 @@ mod tests {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let memory = session_manager
|
||||
session_manager
|
||||
.store()
|
||||
.put_memory(&crate::storage::MemoryUpsert {
|
||||
scope_kind: "user".to_string(),
|
||||
@ -1286,11 +1299,13 @@ mod tests {
|
||||
.unwrap();
|
||||
|
||||
let results = session_manager
|
||||
.run_memory_maintenance_for_all_scopes(Some(memory.updated_at + 1))
|
||||
.run_memory_maintenance_for_all_scopes()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert!(results.is_empty());
|
||||
assert_eq!(results.len(), 1);
|
||||
assert_eq!(results[0].scope_key, "feishu:user-1");
|
||||
assert!(results[0].output.user_facts.contains(&"用户在做AI产品".to_string()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@ -1343,7 +1358,7 @@ mod tests {
|
||||
}
|
||||
|
||||
let results = session_manager
|
||||
.run_memory_maintenance_for_all_scopes(None)
|
||||
.run_memory_maintenance_for_all_scopes()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
|
||||
@ -52,10 +52,7 @@ pub trait AgentTaskExecutor: Send + Sync {
|
||||
pub trait MaintenanceExecutor: Send + Sync {
|
||||
async fn cleanup_expired_sessions(&self) -> usize;
|
||||
|
||||
async fn run_memory_maintenance_for_all_scopes(
|
||||
&self,
|
||||
updated_since: Option<i64>,
|
||||
) -> anyhow::Result<Vec<MaintenanceRunSummary>>;
|
||||
async fn run_memory_maintenance_for_all_scopes(&self) -> anyhow::Result<Vec<MaintenanceRunSummary>>;
|
||||
}
|
||||
|
||||
pub struct Scheduler {
|
||||
@ -652,9 +649,7 @@ async fn execute_internal_event(
|
||||
Ok(())
|
||||
}
|
||||
"memory_maintenance" => {
|
||||
let results = maintenance_executor
|
||||
.run_memory_maintenance_for_all_scopes(job.last_fired_at)
|
||||
.await?;
|
||||
let results = maintenance_executor.run_memory_maintenance_for_all_scopes().await?;
|
||||
for result in &results {
|
||||
tracing::info!(
|
||||
job_id = %job.id,
|
||||
@ -1039,10 +1034,7 @@ mod tests {
|
||||
0
|
||||
}
|
||||
|
||||
async fn run_memory_maintenance_for_all_scopes(
|
||||
&self,
|
||||
_updated_since: Option<i64>,
|
||||
) -> anyhow::Result<Vec<MaintenanceRunSummary>> {
|
||||
async fn run_memory_maintenance_for_all_scopes(&self) -> anyhow::Result<Vec<MaintenanceRunSummary>> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user