Skip to main content

synaptic_deep/middleware/
memory.rs

1use async_trait::async_trait;
2use std::sync::Arc;
3use synaptic_core::SynapticError;
4use synaptic_middleware::{AgentMiddleware, ModelRequest};
5
6use crate::backend::Backend;
7
8/// Middleware that loads a memory file from the backend and injects it into the system prompt.
9///
10/// On each model call, reads the configured memory file (default `AGENTS.md`) and
11/// appends its contents wrapped in `<agent_memory>` tags to the system prompt.
12pub struct DeepMemoryMiddleware {
13    backend: Arc<dyn Backend>,
14    memory_file: String,
15}
16
17impl DeepMemoryMiddleware {
18    pub fn new(backend: Arc<dyn Backend>, memory_file: String) -> Self {
19        Self {
20            backend,
21            memory_file,
22        }
23    }
24}
25
26#[async_trait]
27impl AgentMiddleware for DeepMemoryMiddleware {
28    async fn before_model(&self, request: &mut ModelRequest) -> Result<(), SynapticError> {
29        match self.backend.read_file(&self.memory_file, 0, 10000).await {
30            Ok(content) if !content.is_empty() => {
31                let section = format!("\n<agent_memory>\n{}\n</agent_memory>\n", content);
32                if let Some(ref mut prompt) = request.system_prompt {
33                    prompt.push_str(&section);
34                } else {
35                    request.system_prompt = Some(section);
36                }
37            }
38            _ => {} // File not found or empty — silently skip
39        }
40        Ok(())
41    }
42}