Skip to main content

talos_memory/
prompt.rs

1use crate::MemoryStore;
2
3// ---------------------------------------------------------------------------
4// Memory prompt injection — bounded, disable-able, safety-filtered.
5// ---------------------------------------------------------------------------
6
7/// Configuration for memory prompt injection.
8#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
9#[serde(default)]
10pub struct MemoryPromptConfig {
11    /// Whether memory injection is enabled.
12    pub enabled: bool,
13    /// Maximum number of memory items to include.
14    pub max_items: usize,
15    /// Maximum character budget for the formatted section.
16    pub max_chars: usize,
17}
18
19impl Default for MemoryPromptConfig {
20    fn default() -> Self {
21        Self {
22            enabled: false,
23            max_items: 5,
24            max_chars: 2000,
25        }
26    }
27}
28
29/// Patterns that indicate content originated from hidden tool/system output.
30/// If any of these appear in a memory item's content, the item is filtered
31/// out as a defense-in-depth measure.
32const HIDDEN_OUTPUT_PATTERNS: &[&str] = &[
33    // Existing patterns (do not remove).
34    "<tool_result>",
35    "</tool_result>",
36    "Tool output:",
37    "is_error:",
38    "tool_call",
39    "tool_result",
40    // JSON-style markers.
41    "\"type\": \"tool_result\"",
42    "\"type\":\"tool_result\"",
43    "\"role\": \"tool\"",
44    "\"role\":\"tool\"",
45    // Anthropic-style markers.
46    "tool_use",
47    "tool_use_id",
48    "function_call",
49    // Whitespace-padded tag variants (caught after normalization, but listed
50    // here for documentation and direct matching on un-normalized content).
51    "< tool_result",
52    "tool_result >",
53    "<tool_result ",
54    // System markers.
55    "<system>",
56    "</system>",
57    "<system-reminder",
58    "system-reminder",
59];
60
61/// Returns `true` if `content` appears to contain hidden tool or system output.
62///
63/// Applies a normalization pass before pattern matching: trims leading/trailing
64/// whitespace and collapses runs of multiple spaces into a single space. This
65/// catches bypass attempts like `<tool_result  >` or `<  tool_result  >`.
66pub(crate) fn is_hidden_output(content: &str) -> bool {
67    let normalized = collapse_whitespace(content.trim());
68    let lower = normalized.to_lowercase();
69    HIDDEN_OUTPUT_PATTERNS.iter().any(|pat| lower.contains(pat))
70}
71
72fn collapse_whitespace(s: &str) -> std::borrow::Cow<'_, str> {
73    if !s.contains("  ") {
74        return std::borrow::Cow::Borrowed(s);
75    }
76    std::borrow::Cow::Owned(s.replace("  ", " "))
77}
78
79/// Format retrieved memory into a bounded prompt section.
80///
81/// Returns `None` if: disabled, no query, no results, or all results are filtered.
82/// The output includes provenance (source session/turn), confidence, freshness,
83/// and contradiction markers. Hidden tool output is filtered out.
84pub fn format_memory_prompt(
85    store: &MemoryStore,
86    query: &str,
87    config: &MemoryPromptConfig,
88) -> Option<String> {
89    if !config.enabled || query.trim().is_empty() {
90        return None;
91    }
92
93    let results = store.retrieve(query, config.max_items).ok()?;
94    if results.is_empty() {
95        return None;
96    }
97
98    let mut items = Vec::new();
99    let header = "## Relevant Memory\n";
100    let mut total_len = header.len();
101
102    for result in &results {
103        // Defense-in-depth: skip items that look like hidden tool output.
104        if is_hidden_output(&result.item.content) {
105            continue;
106        }
107
108        let source_ref = result
109            .evidence
110            .first()
111            .map(|e| e.source_ref.as_str())
112            .unwrap_or("unknown");
113
114        let reinforced = result.item.last_reinforced.format("%Y-%m-%d");
115
116        let line = if result.item.contradiction_ref.is_some() {
117            format!(
118                "- ⚠ CONTRADICTION: [confidence={:.1}] {} (source: {}, reinforced: {})\n",
119                result.item.confidence, result.item.content, source_ref, reinforced,
120            )
121        } else {
122            format!(
123                "- [confidence={:.1}] {} (source: {}, reinforced: {})\n",
124                result.item.confidence, result.item.content, source_ref, reinforced,
125            )
126        };
127
128        // Check if adding this line would exceed the budget.
129        let line_len = line.len();
130        if total_len + line_len > config.max_chars {
131            // Truncate: append the truncation notice and stop.
132            let truncation_notice = "... (memory section truncated)";
133            // Ensure we have room for the notice.
134            if total_len + truncation_notice.len() <= config.max_chars {
135                items.push(truncation_notice.to_string());
136            }
137            break;
138        }
139
140        items.push(line);
141        total_len += line_len;
142    }
143
144    if items.is_empty() {
145        // All results were filtered out.
146        return None;
147    }
148
149    let mut output = String::with_capacity(config.max_chars);
150    output.push_str(header);
151    for item in &items {
152        output.push_str(item);
153    }
154
155    Some(output)
156}