304 lines
15 KiB
Rust
304 lines
15 KiB
Rust
//! `memory_search` and `memory_get`, ported from OpenClaw's `memory-tool-contract` and `read-file`.
|
|
use std::path::{Component, Path, PathBuf};
|
|
use std::sync::Arc;
|
|
use std::time::Duration;
|
|
|
|
use async_trait::async_trait;
|
|
use capri_agent::tools::{Tool, ToolContext};
|
|
use capri_core::{utf16_len, SettingsStore};
|
|
use serde_json::{json, Value};
|
|
|
|
use crate::index::{MemoryIndex, DEFAULT_MAX_RESULTS, DEFAULT_MIN_SCORE};
|
|
use crate::{truncate_utf16, MemorySettings};
|
|
|
|
const SEARCH_TIMEOUT: Duration = Duration::from_secs(30);
|
|
const READ_LINES: usize = 120;
|
|
const READ_CHARS: usize = 12_000;
|
|
const MAX_READ: u64 = 8 * 1024 * 1024;
|
|
const FILES: &str = "MEMORY.md, USER.md, Markdown files recursively under memory/";
|
|
const CORPUS_GUIDANCE: &str = "Corpus outcomes cover each requested corpus; only a top-level corpus warning means results are partial and must be surfaced to the user. An optional corpus outcome of not-registered in a multi-corpus result is informational.";
|
|
const GET_GUIDANCE: &str = "status=ok means the requested excerpt was read; status=not_found means every requested available corpus missed; status=error means the requested read failed, not that memory is disabled.";
|
|
|
|
fn unavailable(error: &str, warning: &str, action: &str, timed_out: bool) -> Value {
|
|
let mut v = json!({"ok": false, "results": [], "disabled": true, "unavailable": true, "error": error, "warning": warning, "action": action});
|
|
if timed_out {
|
|
v["timedOut"] = json!(true);
|
|
v["timeoutMs"] = json!(SEARCH_TIMEOUT.as_millis() as u64);
|
|
}
|
|
v
|
|
}
|
|
|
|
fn corpus(args: &Value, allowed: &[&str]) -> Result<Option<String>, String> {
|
|
match args.get("corpus").and_then(Value::as_str) {
|
|
None => Ok(None),
|
|
Some(c) if allowed.contains(&c) => Ok(Some(c.to_string())),
|
|
Some(_) => Err(format!("corpus must be one of: {}", allowed.join(", "))),
|
|
}
|
|
}
|
|
|
|
fn positive(args: &Value, key: &str, alias: &str) -> Option<usize> {
|
|
let v = args.get(key).or_else(|| args.get(alias))?;
|
|
v.as_u64().or_else(|| v.as_f64().filter(|f| f.fract() == 0.0 && *f >= 1.0).map(|f| f as u64)).filter(|n| *n >= 1).map(|n| n as usize)
|
|
}
|
|
|
|
pub struct MemorySearch {
|
|
pub(crate) index: Arc<MemoryIndex>,
|
|
pub(crate) store: Arc<SettingsStore>,
|
|
}
|
|
|
|
#[async_trait]
|
|
impl Tool for MemorySearch {
|
|
fn name(&self) -> &str {
|
|
"memory_search"
|
|
}
|
|
|
|
fn description(&self) -> String {
|
|
let search = if self.store.section::<MemorySettings>().remember_across_conversations { format!("{FILES}, indexed session transcripts") } else { FILES.to_string() };
|
|
format!("Mandatory recall step: semantically search {search} before answering questions about prior work, decisions, dates, people, preferences, or todos. Omit `corpus` to search those configured sources. Session results are transcript search references, not readable memory-file paths. Optional `corpus=wiki` or `corpus=all` also searches registered compiled-wiki supplements; use `corpus=all` only when compiled wiki supplements are needed. `corpus=memory` restricts hits to indexed memory files (excludes session transcript chunks from ranking). `corpus=sessions` searches indexed session transcripts under the same visibility rules as session history tools and returns unavailable when semantic session indexing is disabled. {CORPUS_GUIDANCE} If response has disabled=true or stale=true, tell the user and include the warning/action guidance.")
|
|
}
|
|
|
|
fn parameters(&self) -> Value {
|
|
json!({"type": "object", "properties": {"query": {"type": "string"}, "maxResults": {"type": "integer", "minimum": 1}, "minScore": {"type": "number"},
|
|
"corpus": {"type": "string", "enum": ["memory", "wiki", "all", "sessions"]}}, "required": ["query"], "additionalProperties": false})
|
|
}
|
|
|
|
fn timeout(&self) -> Duration {
|
|
SEARCH_TIMEOUT + Duration::from_secs(5)
|
|
}
|
|
|
|
async fn call(&self, args: Value, _ctx: ToolContext) -> Value {
|
|
let Some(query) = args.get("query").and_then(Value::as_str).map(str::trim).filter(|q| !q.is_empty()) else {
|
|
return capri_agent::tools::error("query required");
|
|
};
|
|
let corpus = match corpus(&args, &["memory", "wiki", "all", "sessions"]) {
|
|
Ok(c) => c,
|
|
Err(e) => return capri_agent::tools::error(e),
|
|
};
|
|
let max_results = positive(&args, "maxResults", "max_results").unwrap_or(DEFAULT_MAX_RESULTS);
|
|
let min_score = args.get("minScore").or_else(|| args.get("min_score")).and_then(Value::as_f64).filter(|f| f.is_finite()).unwrap_or(DEFAULT_MIN_SCORE);
|
|
let sessions = self.store.section::<MemorySettings>().remember_across_conversations;
|
|
// TODO: there are no compiled-wiki supplements yet, so `wiki` always reports not-registered.
|
|
if corpus.as_deref() == Some("wiki") {
|
|
return capri_agent::tools::ok(json!({"results": [], "corpora": [{"corpus": "wiki", "outcome": "not-registered"}]}));
|
|
}
|
|
if corpus.as_deref() == Some("sessions") && !sessions {
|
|
return unavailable(
|
|
"Session transcript search is not enabled.",
|
|
"Session transcript search is unavailable for this agent.",
|
|
"Ask the owner to enable Remember across conversations in Capri's memory settings.",
|
|
false,
|
|
);
|
|
}
|
|
let source = match corpus.as_deref() {
|
|
Some("memory") => Some("memory"),
|
|
Some("sessions") => Some("sessions"),
|
|
_ => None,
|
|
};
|
|
let base = self.store.get().ollama_base_url();
|
|
let searched = tokio::time::timeout(SEARCH_TIMEOUT, self.index.search(&base, sessions, query, source, max_results, min_score)).await;
|
|
let outcome = match searched {
|
|
Err(_) => {
|
|
return unavailable(
|
|
"memory search timed out",
|
|
"Memory search did not finish within its time limit.",
|
|
"Retry memory_search after a short wait. If memory-corpus timeouts persist, inspect this agent's memory index before rebuilding it.",
|
|
true,
|
|
)
|
|
}
|
|
Ok(Err(e)) => {
|
|
return unavailable(&format!("{e:#}"), "Memory search is unavailable due to an embedding/provider error.", "Check embedding provider configuration and retry memory_search.", false)
|
|
}
|
|
Ok(Ok(o)) => o,
|
|
};
|
|
let results: Vec<Value> = outcome
|
|
.hits
|
|
.iter()
|
|
.map(|h| {
|
|
let lines = if h.start_line == h.end_line { format!("#L{}", h.start_line) } else { format!("#L{}-L{}", h.start_line, h.end_line) };
|
|
let citation = format!("{}{lines}", h.path);
|
|
json!({"path": h.path, "startLine": h.start_line, "endLine": h.end_line, "score": h.score,
|
|
"snippet": format!("{}\n\nSource: {citation}", h.snippet.trim_end()), "corpus": h.source, "citation": citation})
|
|
})
|
|
.collect();
|
|
let mut value = json!({"results": results, "provider": "ollama", "model": crate::embed::EMBED_MODEL, "citations": "auto",
|
|
"mode": if outcome.keyword_only { "keyword-only" } else { "hybrid" }});
|
|
if let Some(w) = outcome.warning {
|
|
value["warning"] = json!(w);
|
|
}
|
|
capri_agent::tools::ok(value)
|
|
}
|
|
}
|
|
|
|
pub struct MemoryGet {
|
|
pub(crate) workspace: PathBuf,
|
|
}
|
|
|
|
#[async_trait]
|
|
impl Tool for MemoryGet {
|
|
fn name(&self) -> &str {
|
|
"memory_get"
|
|
}
|
|
|
|
fn description(&self) -> String {
|
|
format!("Safe exact excerpt read from {FILES}. Session transcript paths are unsupported; use the available session-history workflow for session hits. Defaults to a bounded excerpt when lines are omitted and includes truncation/continuation info when more content exists. `corpus=wiki` reads registered compiled-wiki supplements. {GET_GUIDANCE} {CORPUS_GUIDANCE}")
|
|
}
|
|
|
|
fn parameters(&self) -> Value {
|
|
json!({"type": "object", "properties": {"path": {"type": "string"}, "from": {"type": "integer", "minimum": 1}, "lines": {"type": "integer", "minimum": 1},
|
|
"corpus": {"type": "string", "enum": ["memory", "wiki", "all"]}}, "required": ["path"], "additionalProperties": false})
|
|
}
|
|
|
|
async fn call(&self, args: Value, _ctx: ToolContext) -> Value {
|
|
let Some(path) = args.get("path").and_then(Value::as_str) else { return capri_agent::tools::error("path required") };
|
|
let corpus = match corpus(&args, &["memory", "wiki", "all"]) {
|
|
Ok(c) => c,
|
|
Err(e) => return capri_agent::tools::error(e),
|
|
};
|
|
if corpus.as_deref() == Some("wiki") {
|
|
return json!({"ok": true, "status": "not_found", "path": path, "text": ""});
|
|
}
|
|
let mut value = read_memory_file(&self.workspace, path, positive(&args, "from", "from"), positive(&args, "lines", "lines"));
|
|
value["ok"] = json!(value["status"] != "error");
|
|
value
|
|
}
|
|
}
|
|
|
|
fn read_error(path: &str, code: &str, error: &str) -> Value {
|
|
json!({"path": path, "text": "", "status": "error", "code": code, "error": error})
|
|
}
|
|
|
|
/// Reads an excerpt of `MEMORY.md`, `USER.md` or `memory/**.md`, refusing symbolic links anywhere in the path.
|
|
pub fn read_memory_file(workspace: &Path, raw: &str, from: Option<usize>, lines: Option<usize>) -> Value {
|
|
let raw = raw.trim();
|
|
if raw.is_empty() {
|
|
return read_error(raw, "MEMORY_READ_FAILED", "path required");
|
|
}
|
|
let mut abs = PathBuf::new();
|
|
for part in workspace.join(raw).components() {
|
|
match part {
|
|
Component::ParentDir => {
|
|
abs.pop();
|
|
}
|
|
Component::CurDir => {}
|
|
other => abs.push(other),
|
|
}
|
|
}
|
|
let rel = abs.strip_prefix(workspace).map(|p| p.to_string_lossy().into_owned()).unwrap_or_default();
|
|
let allowed = rel == "MEMORY.md" || rel == "USER.md" || rel.starts_with("memory/");
|
|
if !allowed || !rel.ends_with(".md") {
|
|
return read_error(&rel, "MEMORY_PATH_NOT_ALLOWED", "path is not an allowed Markdown memory file");
|
|
}
|
|
let mut at = workspace.to_path_buf();
|
|
for part in Path::new(&rel).components() {
|
|
at.push(part);
|
|
match std::fs::symlink_metadata(&at) {
|
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return json!({"status": "not_found", "text": "", "path": rel}),
|
|
Err(e) => return read_error(&rel, "MEMORY_READ_FAILED", &e.to_string()),
|
|
Ok(m) if m.file_type().is_symlink() => return read_error(&rel, "MEMORY_PATH_NOT_ALLOWED", "symbolic links are not allowed in memory paths"),
|
|
Ok(_) => {}
|
|
}
|
|
}
|
|
let content = match capri_core::fsutil::read_regular(&at, MAX_READ) {
|
|
Ok(Some(bytes)) => String::from_utf8_lossy(&bytes).into_owned(),
|
|
Ok(None) => return json!({"status": "not_found", "text": "", "path": rel}),
|
|
Err(_) if !at.is_file() => return read_error(&rel, "MEMORY_READ_FAILED", "path must be a regular file"),
|
|
Err(e) => return read_error(&rel, "MEMORY_READ_FAILED", &format!("{e:#}")),
|
|
};
|
|
read_result(&content, &rel, from, lines)
|
|
}
|
|
|
|
/// A line slice fitted to 12000 chars, with a continuation note.
|
|
fn read_result(content: &str, rel: &str, from: Option<usize>, lines: Option<usize>) -> Value {
|
|
let mut file_lines: Vec<&str> = content.split('\n').collect();
|
|
if file_lines.last() == Some(&"") {
|
|
file_lines.pop();
|
|
}
|
|
let start = from.unwrap_or(1).max(1);
|
|
let count = lines.unwrap_or(READ_LINES).max(1);
|
|
let begin = (start - 1).min(file_lines.len());
|
|
let selected = &file_lines[begin..(begin + count).min(file_lines.len())];
|
|
let more_source = begin + selected.len() < file_lines.len();
|
|
let (mut included, mut chars) = (0, 0);
|
|
for line in selected {
|
|
let next = chars + utf16_len(line) + usize::from(included > 0);
|
|
if included > 0 && next > READ_CHARS {
|
|
break;
|
|
}
|
|
included += 1;
|
|
chars = next;
|
|
}
|
|
let joined = selected[..included].join("\n");
|
|
let text = truncate_utf16(&joined, READ_CHARS);
|
|
let hard = chars > READ_CHARS;
|
|
let next_from = (!hard && (more_source || included < selected.len())).then_some(start + included);
|
|
let truncated = hard || included < selected.len() || more_source;
|
|
let mut out = text.to_string();
|
|
if truncated && (!text.is_empty() || hard) {
|
|
out.push_str(&match next_from {
|
|
Some(n) => format!("\n\n[More content available. Use from={n} to continue.]"),
|
|
None => "\n\n[More content available. Requested excerpt exceeded the default maxChars budget. If you need the full raw line, use read on the source file.]".into(),
|
|
});
|
|
}
|
|
let mut value = json!({"status": "ok", "text": out, "path": rel, "from": start, "lines": included});
|
|
if truncated {
|
|
value["truncated"] = json!(true);
|
|
}
|
|
if let Some(n) = next_from {
|
|
value["nextFrom"] = json!(n);
|
|
}
|
|
value
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn path_rules() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let ws = dir.path().join("ws");
|
|
std::fs::create_dir_all(ws.join("memory")).unwrap();
|
|
std::fs::write(ws.join("MEMORY.md"), "a\nb\n").unwrap();
|
|
std::fs::write(dir.path().join("secret.md"), "s").unwrap();
|
|
std::fs::write(ws.join("PERSONALITY.md"), "p").unwrap();
|
|
std::os::unix::fs::symlink(dir.path().join("secret.md"), ws.join("memory/link.md")).unwrap();
|
|
std::os::unix::fs::symlink(dir.path(), ws.join("memory/dir")).unwrap();
|
|
assert_eq!(read_memory_file(&ws, "MEMORY.md", None, None)["text"], "a\nb");
|
|
assert_eq!(read_memory_file(&ws, "./memory/../MEMORY.md", None, None)["status"], "ok");
|
|
for bad in ["PERSONALITY.md", "../secret.md", "/etc/passwd", "memory/x.txt", "dreams.md"] {
|
|
assert_eq!(read_memory_file(&ws, bad, None, None)["code"], "MEMORY_PATH_NOT_ALLOWED", "{bad}");
|
|
}
|
|
for link in ["memory/link.md", "memory/dir/secret.md"] {
|
|
assert_eq!(read_memory_file(&ws, link, None, None)["code"], "MEMORY_PATH_NOT_ALLOWED", "{link}");
|
|
}
|
|
assert_eq!(read_memory_file(&ws, "memory/none.md", None, None)["status"], "not_found");
|
|
}
|
|
|
|
#[test]
|
|
fn excerpts_are_bounded_with_continuation() {
|
|
let text: String = (1..=200).map(|i| format!("line {i}\n")).collect();
|
|
let v = read_result(&text, "MEMORY.md", None, None);
|
|
assert_eq!(v["lines"], 120);
|
|
assert_eq!(v["nextFrom"], 121);
|
|
assert_eq!(v["truncated"], true);
|
|
assert!(v["text"].as_str().unwrap().ends_with("line 120\n\n[More content available. Use from=121 to continue.]"));
|
|
let v = read_result(&text, "MEMORY.md", Some(190), Some(50));
|
|
assert_eq!(v["lines"], 11);
|
|
assert!(v.get("truncated").is_none());
|
|
let wide: String = (0..10).map(|_| "w".repeat(2000) + "\n").collect();
|
|
let v = read_result(&wide, "MEMORY.md", None, None);
|
|
assert_eq!(v["lines"], 5);
|
|
assert_eq!(v["nextFrom"], 6);
|
|
let huge = read_result(&"z".repeat(13_000), "MEMORY.md", None, None);
|
|
assert!(huge.get("nextFrom").is_none());
|
|
assert!(huge["text"].as_str().unwrap().ends_with("use read on the source file.]"));
|
|
}
|
|
|
|
#[test]
|
|
fn argument_helpers() {
|
|
assert_eq!(positive(&json!({"max_results": 3}), "maxResults", "max_results"), Some(3));
|
|
assert_eq!(positive(&json!({"maxResults": 0}), "maxResults", "max_results"), None);
|
|
assert!(corpus(&json!({"corpus": "secret"}), &["memory"]).is_err());
|
|
}
|
|
}
|