Skip to main content

aidaemon_memory/
tools.rs

1//! [`RememberTool`] and [`RecallTool`]: explicit memory access for the
2//! model, as ordinary `aidaemon_core::Tool`s.
3//!
4//! The scope always comes from the trusted `ToolContext::session_id`
5//! through the scope resolver, never from the model's arguments, so a
6//! model cannot read or write another user's memory.
7
8use std::sync::Arc;
9
10use aidaemon_core::{
11    SourceTrust, Tool, ToolAnnotations, ToolContext, ToolOutput, ToolResult, ToolSpec,
12};
13use async_trait::async_trait;
14use serde_json::{Value, json};
15
16use crate::memory::{Memory, ScopeResolver};
17use crate::types::{NewFact, Provenance, UpsertOutcome};
18
19fn resolve(memory: &Memory, resolver: &Option<ScopeResolver>, session_id: &str) -> String {
20    match resolver {
21        Some(f) => f(session_id),
22        None => memory.scope_for(session_id),
23    }
24}
25
26/// Lets the model store a fact. Not read-only, not destructive, and
27/// idempotent: the same arguments reinforce instead of duplicating.
28pub struct RememberTool {
29    memory: Memory,
30    resolver: Option<ScopeResolver>,
31}
32
33impl RememberTool {
34    pub fn new(memory: Memory) -> Self {
35        Self {
36            memory,
37            resolver: None,
38        }
39    }
40
41    /// Override the memory's scope resolver for this tool.
42    pub fn scope_resolver(mut self, f: impl Fn(&str) -> String + Send + Sync + 'static) -> Self {
43        self.resolver = Some(Arc::new(f));
44        self
45    }
46}
47
48#[async_trait]
49impl Tool for RememberTool {
50    fn spec(&self) -> ToolSpec {
51        ToolSpec {
52            name: "remember".into(),
53            description: "Save a durable fact about the user or their world to long-term memory \
54                          (preferences, people, projects, decisions). Reusing a category and key \
55                          replaces the old value; the old one is kept as history. Do not save \
56                          secrets or transient task details."
57                .into(),
58            parameters: json!({
59                "type": "object",
60                "properties": {
61                    "category": {"type": "string", "description": "Short lowercase noun, e.g. user, preference, person, project"},
62                    "key": {"type": "string", "description": "snake_case attribute name, e.g. favorite_color"},
63                    "value": {"type": "string", "description": "The fact itself"},
64                    "confidence": {"type": "number", "minimum": 0, "maximum": 1}
65                },
66                "required": ["category", "key", "value"],
67                "additionalProperties": false
68            }),
69        }
70    }
71
72    fn annotations(&self) -> ToolAnnotations {
73        ToolAnnotations {
74            read_only: false,
75            destructive: false,
76            idempotent: true,
77            egress: false,
78        }
79    }
80
81    /// The owner's own memory store answers.
82    fn source_trust(&self, _arguments: &Value) -> SourceTrust {
83        SourceTrust::Trusted
84    }
85
86    async fn call(&self, arguments: Value, ctx: &ToolContext) -> ToolResult {
87        let field = |name: &str| arguments.get(name).and_then(Value::as_str).unwrap_or("");
88        let scope = resolve(&self.memory, &self.resolver, &ctx.session_id);
89        let fact = NewFact::new(scope, field("category"), field("key"), field("value"))
90            .confidence(
91                arguments
92                    .get("confidence")
93                    .and_then(Value::as_f64)
94                    .unwrap_or(1.0) as f32,
95            )
96            .source(Provenance {
97                run_id: Some(ctx.run_id.to_string()),
98                session_id: Some(ctx.session_id.clone()),
99                excerpt: None,
100            });
101        let audience = self.memory.audience_for(&ctx.session_id);
102        match self
103            .memory
104            .remember_with(fact, &audience.access_for_writes())
105            .await
106        {
107            // The earlier value may be something this audience cannot see.
108            Ok(UpsertOutcome::Superseded { id, .. }) if !audience.sees_everything() => {
109                Ok(ToolOutput::text("Saved to memory.")
110                    .with_details(json!({ "kind": "superseded", "id": id })))
111            }
112            Ok(outcome) => {
113                let text = match &outcome {
114                    UpsertOutcome::Inserted { .. } => "Saved to memory.".to_string(),
115                    UpsertOutcome::Reinforced { .. } => "Already in memory; refreshed.".to_string(),
116                    UpsertOutcome::Superseded { previous_value, .. } => {
117                        format!(
118                            "Saved to memory, replacing the previous value \"{previous_value}\"."
119                        )
120                    }
121                };
122                Ok(ToolOutput::text(text).with_details(json!(outcome)))
123            }
124            Err(crate::MemoryError::Invalid(reason)) => Ok(ToolOutput::error(reason)),
125            Err(other) => Err(other.to_string().into()),
126        }
127    }
128}
129
130/// Lets the model search memory. Read-only.
131pub struct RecallTool {
132    memory: Memory,
133    resolver: Option<ScopeResolver>,
134    max_limit: usize,
135}
136
137impl RecallTool {
138    pub fn new(memory: Memory) -> Self {
139        Self {
140            memory,
141            resolver: None,
142            max_limit: 20,
143        }
144    }
145
146    pub fn scope_resolver(mut self, f: impl Fn(&str) -> String + Send + Sync + 'static) -> Self {
147        self.resolver = Some(Arc::new(f));
148        self
149    }
150}
151
152#[async_trait]
153impl Tool for RecallTool {
154    fn spec(&self) -> ToolSpec {
155        ToolSpec {
156            name: "recall".into(),
157            description: "Search long-term memory for facts and past conversations relevant to \
158                          a query. Returns the best matches with relevance scores."
159                .into(),
160            parameters: json!({
161                "type": "object",
162                "properties": {
163                    "query": {"type": "string", "description": "What to look for"},
164                    "limit": {"type": "integer", "minimum": 1, "maximum": self.max_limit}
165                },
166                "required": ["query"],
167                "additionalProperties": false
168            }),
169        }
170    }
171
172    fn annotations(&self) -> ToolAnnotations {
173        ToolAnnotations::READ_ONLY
174    }
175
176    /// Facts from the owner's own memory store.
177    fn source_trust(&self, _arguments: &Value) -> SourceTrust {
178        SourceTrust::Trusted
179    }
180
181    async fn call(&self, arguments: Value, ctx: &ToolContext) -> ToolResult {
182        let query = arguments
183            .get("query")
184            .and_then(Value::as_str)
185            .unwrap_or("")
186            .trim();
187        if query.is_empty() {
188            return Ok(ToolOutput::error("query must not be empty"));
189        }
190        let limit = arguments
191            .get("limit")
192            .and_then(Value::as_u64)
193            .map(|n| n as usize)
194            .unwrap_or(5)
195            .clamp(1, self.max_limit);
196        let scope = resolve(&self.memory, &self.resolver, &ctx.session_id);
197        let audience = self.memory.audience_for(&ctx.session_id);
198        let facts = self
199            .memory
200            .recall_facts_for(&scope, query, limit, &audience)
201            .await
202            .map_err(|e| e.to_string())?;
203        let episodes = self
204            .memory
205            .recall_episodes_for(&scope, query, limit.div_ceil(2), &audience)
206            .await
207            .map_err(|e| e.to_string())?;
208        if facts.is_empty() && episodes.is_empty() {
209            return Ok(ToolOutput::text("No matching memories."));
210        }
211        let mut text = String::new();
212        for f in &facts {
213            text.push_str(&format!(
214                "- [{}] {}: {} (score {:.2})\n",
215                f.fact.category, f.fact.key, f.fact.value, f.score
216            ));
217        }
218        for e in &episodes {
219            text.push_str(&format!(
220                "- [episode {}] {} (score {:.2})\n",
221                e.episode.created_at.format("%Y-%m-%d"),
222                e.episode.summary,
223                e.score
224            ));
225        }
226        let details = json!({
227            "facts": facts.iter().map(|f| json!({
228                "id": f.fact.id, "category": f.fact.category, "key": f.fact.key,
229                "value": f.fact.value, "score": f.score,
230            })).collect::<Vec<_>>(),
231            "episodes": episodes.iter().map(|e| json!({
232                "id": e.episode.id, "summary": e.episode.summary, "score": e.score,
233            })).collect::<Vec<_>>(),
234        });
235        Ok(ToolOutput::text(text.trim_end().to_string()).with_details(details))
236    }
237}