Skip to main content

aidaemon_memory/full/tools/
mod.rs

1//! The full memory system's tools: `remember_fact`, `manage_memories`,
2//! and `manage_people`, over the memory stores.
3//!
4//! Each is an [`aidaemon_tools::OutcomeTool`], so a host with its
5//! own dispatcher (receipts, approvals, result fitting) runs it directly and
6//! keeps the typed outcome; [`kernel_tools`] gives the same tools to a plain
7//! `aidaemon_core` agent. [`tool_facts`] says how a host's turn should treat
8//! each tool's calls and results.
9
10use std::collections::HashMap;
11use std::sync::Arc;
12
13use aidaemon_tools::semantics::{
14    EvidenceAuthority::{Advisory, Canonical},
15    EvidencePurpose::{self, Attribution, Content, CurrentState, HistoricalRecord},
16    EvidenceTemporalScope::{Both, Historical},
17    ToolEvidenceCapability,
18    ToolSemanticScope::{self, UserMemory},
19};
20use aidaemon_tools::services::SettingsStore;
21use aidaemon_tools::{KernelAdapter, OutcomeTool};
22
23use crate::stores::MemoryStores;
24
25mod manage_memories;
26mod manage_people;
27mod remember_fact;
28
29pub use manage_memories::{
30    MEMORY_ACTIONS, ManageMemoriesTool, memory_parameters, unknown_action_message,
31};
32pub use manage_people::ManagePeopleTool;
33pub use remember_fact::{RememberFactTool, call_deletes_facts};
34
35/// The names of the full memory system's tools.
36pub const TOOL_NAMES: &[&str] = &["remember_fact", "manage_memories", "manage_people"];
37
38/// The three tools over `store`. `settings` holds the `people_enabled`
39/// switch `manage_people` reads and sets.
40pub fn outcome_tools(
41    store: Arc<dyn MemoryStores>,
42    settings: Arc<dyn SettingsStore>,
43) -> Vec<Arc<dyn OutcomeTool>> {
44    vec![
45        Arc::new(RememberFactTool::new(store.clone())),
46        Arc::new(ManageMemoriesTool::new(store.clone())),
47        Arc::new(ManagePeopleTool::new(settings, store)),
48    ]
49}
50
51/// [`outcome_tools`] as kernel tools, for an agent without a dispatcher of
52/// its own.
53pub fn kernel_tools(
54    store: Arc<dyn MemoryStores>,
55    settings: Arc<dyn SettingsStore>,
56) -> Vec<Arc<dyn aidaemon_core::Tool>> {
57    outcome_tools(store, settings)
58        .into_iter()
59        .map(|tool| Arc::new(KernelAdapter::new(tool)) as Arc<dyn aidaemon_core::Tool>)
60        .collect()
61}
62
63/// Settings kept in memory, for a host with no settings store of its own:
64/// `people_enabled` lasts until the process ends.
65#[derive(Default)]
66pub struct LocalSettings(std::sync::Mutex<HashMap<String, String>>);
67
68#[async_trait::async_trait]
69impl SettingsStore for LocalSettings {
70    async fn get_setting(&self, key: &str) -> anyhow::Result<Option<String>> {
71        Ok(self
72            .0
73            .lock()
74            .unwrap_or_else(|poisoned| poisoned.into_inner())
75            .get(key)
76            .cloned())
77    }
78
79    async fn set_setting(&self, key: &str, value: &str) -> anyhow::Result<()> {
80        self.0
81            .lock()
82            .unwrap_or_else(|poisoned| poisoned.into_inner())
83            .insert(key.to_string(), value.to_string());
84        Ok(())
85    }
86}
87
88/// What a call with these arguments can prove.
89pub type Evidence = Box<dyn Fn(&str) -> Vec<ToolEvidenceCapability> + Send + Sync>;
90
91/// How a host's turn treats one memory tool's calls and results.
92pub struct MemoryToolFacts {
93    pub scope: Option<ToolSemanticScope>,
94    /// The result says little worth carrying into a checkpoint.
95    pub low_signal_result: bool,
96    /// Older calls are summarized by their `action` argument.
97    pub summary_from_action: bool,
98    /// An older result stays as an excerpt, because it may be the evidence
99    /// behind an answer.
100    pub keep_result_excerpt: bool,
101    /// What a call with these arguments can prove.
102    pub evidence: Evidence,
103    /// `evidence` is complete enough to rule this tool out for an inquiry.
104    pub evidence_modeled: bool,
105    pub representative_calls: &'static [&'static str],
106    /// A successful read whose text must not be mistaken for a failure.
107    pub output_is_report: Option<fn(&str, Option<&str>) -> bool>,
108    /// A call with these arguments stores something new in memory (not a
109    /// read, a deletion, a visibility change or requested work): what a turn
110    /// opted out of learning may not do.
111    pub stores: fn(&str) -> bool,
112}
113
114fn capability(
115    scope: ToolSemanticScope,
116    purposes: &[EvidencePurpose],
117    authority: aidaemon_tools::semantics::EvidenceAuthority,
118    temporal_scope: aidaemon_tools::semantics::EvidenceTemporalScope,
119) -> ToolEvidenceCapability {
120    ToolEvidenceCapability::new(scope, purposes, authority, temporal_scope)
121}
122
123/// The `action` argument, trimmed, if any.
124pub fn action_from_arguments(arguments: &str) -> Option<String> {
125    serde_json::from_str::<serde_json::Value>(arguments)
126        .ok()?
127        .get("action")?
128        .as_str()
129        .map(str::trim)
130        .filter(|value| !value.is_empty())
131        .map(str::to_string)
132}
133
134/// Reading the user's memory: what is stored now and was stored before, by
135/// whom. Whether a claim exists is an authoritative store fact.
136fn memory_read() -> ToolEvidenceCapability {
137    capability(
138        UserMemory,
139        &[CurrentState, HistoricalRecord, Content, Attribution],
140        Canonical,
141        Both,
142    )
143}
144
145/// The facts of each of this system's tools, by name.
146pub fn tool_facts() -> HashMap<String, MemoryToolFacts> {
147    let write_only = |scope: Option<ToolSemanticScope>,
148                      low_signal_result,
149                      summary_from_action,
150                      stores: fn(&str) -> bool| MemoryToolFacts {
151        scope,
152        low_signal_result,
153        summary_from_action,
154        keep_result_excerpt: false,
155        evidence: Box::new(|_| Vec::new()),
156        evidence_modeled: false,
157        representative_calls: &["{}"],
158        output_is_report: None,
159        stores,
160    };
161    let manage_memories = MemoryToolFacts {
162        scope: Some(UserMemory),
163        low_signal_result: true,
164        summary_from_action: true,
165        keep_result_excerpt: true,
166        evidence: Box::new(manage_memories_evidence),
167        evidence_modeled: true,
168        representative_calls: &[r#"{"action":"search"}"#, r#"{"action":"search_episodes"}"#],
169        output_is_report: Some(manage_memories_output_is_report),
170        // Its writes forget, repair or re-scope stored facts; none stores
171        // the turn.
172        stores: |_| false,
173    };
174    let manage_people = MemoryToolFacts {
175        scope: None,
176        low_signal_result: true,
177        summary_from_action: false,
178        keep_result_excerpt: false,
179        evidence: Box::new(|_| vec![memory_read()]),
180        evidence_modeled: true,
181        representative_calls: &["{}"],
182        output_is_report: None,
183        stores: |arguments| {
184            matches!(
185                action_from_arguments(arguments).as_deref(),
186                Some("add" | "update" | "add_fact" | "link" | "confirm" | "reconnect")
187            )
188        },
189    };
190    [
191        (
192            "remember_fact",
193            write_only(Some(UserMemory), true, true, |arguments| {
194                !call_deletes_facts(arguments)
195            }),
196        ),
197        ("manage_memories", manage_memories),
198        ("manage_people", manage_people),
199    ]
200    .into_iter()
201    .map(|(name, facts)| (name.to_string(), facts))
202    .collect()
203}
204
205/// What a `manage_memories` call can prove: a fact lookup reads the
206/// canonical memory ledger; episodes are generated summaries.
207pub fn manage_memories_evidence(arguments: &str) -> Vec<ToolEvidenceCapability> {
208    match action_from_arguments(arguments).as_deref() {
209        Some("search_episodes") => vec![capability(
210            UserMemory,
211            &[HistoricalRecord, Content, Attribution],
212            Advisory,
213            Historical,
214        )],
215        Some("list" | "search") | None => vec![memory_read()],
216        _ => Vec::new(),
217    }
218}
219
220fn manage_memories_output_is_report(result_text: &str, tool_arguments: Option<&str>) -> bool {
221    let action = tool_arguments.and_then(action_from_arguments);
222    if !matches!(
223        action.as_deref(),
224        Some("list" | "health" | "search" | "search_episodes")
225    ) {
226        return false;
227    }
228    let trimmed = result_text.trim_start();
229    !trimmed.starts_with("ERROR:")
230        && !trimmed.starts_with("Error:")
231        && !trimmed.starts_with("Failed to ")
232        && !trimmed.starts_with("Request blocked:")
233        && !trimmed.starts_with("Blocked:")
234}
235
236/// Stores and helpers for the tools' tests.
237#[cfg(test)]
238pub(crate) mod test_support {
239    use std::sync::Arc;
240
241    use aidaemon_tools::OutcomeTool;
242    use aidaemon_tools::semantics::ToolCallContext;
243    use async_trait::async_trait;
244
245    use crate::sqlite::SqliteMemory;
246
247    /// An empty memory store on one in-memory connection.
248    pub(crate) async fn memory() -> Arc<SqliteMemory> {
249        let pool = sqlx::sqlite::SqlitePoolOptions::new()
250            .max_connections(1)
251            .connect("sqlite::memory:")
252            .await
253            .unwrap();
254        crate::sqlite::migrate(&pool).await.unwrap();
255        Arc::new(SqliteMemory::new(
256            pool,
257            Arc::new(crate::HashEmbedder::new(384)),
258        ))
259    }
260
261    pub(crate) use super::LocalSettings as Settings;
262
263    /// Calling a tool directly from a test.
264    #[async_trait]
265    pub(crate) trait ToolCalls: OutcomeTool {
266        /// Run with no call facts and return the output text.
267        async fn call(&self, arguments: &str) -> anyhow::Result<String> {
268            Ok(self
269                .execute(arguments, &ToolCallContext::default())
270                .await?
271                .output)
272        }
273    }
274
275    impl<T: OutcomeTool + ?Sized> ToolCalls for T {}
276}