Skip to main content

aidaemon_channels/
session.rs

1//! Mapping conversations to the run they continue from.
2
3use std::collections::HashMap;
4use std::sync::Mutex;
5
6use aidaemon_core::RunId;
7use async_trait::async_trait;
8
9/// Remembers the latest run of each session so a conversation continues
10/// from its last saved [`aidaemon_core::RunState`] (loaded from the runner's
11/// [`aidaemon_core::RunStore`]). Implement it on your database to survive
12/// restarts; [`MemorySessionIndex`] is the in-process default.
13#[async_trait]
14pub trait SessionIndex: Send + Sync {
15    async fn latest_run(&self, session_id: &str) -> Option<RunId>;
16    async fn set_latest(&self, session_id: &str, run_id: RunId);
17    /// Forget the session (the `/new` command): the next message starts a
18    /// fresh run.
19    async fn clear(&self, session_id: &str);
20}
21
22#[derive(Default)]
23pub struct MemorySessionIndex {
24    latest: Mutex<HashMap<String, RunId>>,
25}
26
27impl MemorySessionIndex {
28    pub fn new() -> Self {
29        Self::default()
30    }
31}
32
33#[async_trait]
34impl SessionIndex for MemorySessionIndex {
35    async fn latest_run(&self, session_id: &str) -> Option<RunId> {
36        self.latest
37            .lock()
38            .ok()
39            .and_then(|map| map.get(session_id).copied())
40    }
41
42    async fn set_latest(&self, session_id: &str, run_id: RunId) {
43        if let Ok(mut map) = self.latest.lock() {
44            map.insert(session_id.to_string(), run_id);
45        }
46    }
47
48    async fn clear(&self, session_id: &str) {
49        if let Ok(mut map) = self.latest.lock() {
50            map.remove(session_id);
51        }
52    }
53}
54
55/// The session id the runner uses: `"{channel_name}:{conversation_id}"`.
56pub fn session_id(channel_name: &str, conversation_id: &str) -> String {
57    format!("{channel_name}:{conversation_id}")
58}