use std::collections::{HashMap, VecDeque};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use rig_core::message::Message;
use rig_core::wasm_compat::{WasmBoxedFuture, WasmCompatSend, WasmCompatSync};
use rig_memory::recent::{Recent, view};
use rig_memory::{AsyncStore, SessionError, load_async, save_async};
use sha2::{Digest, Sha256};
const MAX_LOG_ID: usize = 128;
const SAVE_ATTEMPTS: u32 = 10;
pub(crate) type HistoryError = Box<dyn std::error::Error + Send + Sync>;
pub(crate) trait HistoryStore: WasmCompatSend + WasmCompatSync + 'static {
fn load<'a>(
&'a self,
session: &'a str,
) -> WasmBoxedFuture<'a, Result<Vec<Arc<Message>>, HistoryError>>;
fn append<'a>(
&'a self,
session: &'a str,
messages: Vec<Message>,
window: &'a dyn Recent,
) -> WasmBoxedFuture<'a, Result<(), HistoryError>>;
}
fn names_its_log(session: &str) -> bool {
!session.is_empty()
&& session.len() <= MAX_LOG_ID
&& session
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_')
}
pub(crate) struct InMemory(Mutex<Bounded>);
struct Bounded {
by_session: HashMap<String, Vec<Arc<Message>>>,
started: VecDeque<String>,
max: usize,
}
impl InMemory {
pub(crate) fn new(max: usize) -> Self {
Self(Mutex::new(Bounded {
by_session: HashMap::new(),
started: VecDeque::new(),
max: max.max(1),
}))
}
fn lock(&self) -> MutexGuard<'_, Bounded> {
self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
}
impl HistoryStore for InMemory {
fn load<'a>(
&'a self,
session: &'a str,
) -> WasmBoxedFuture<'a, Result<Vec<Arc<Message>>, HistoryError>> {
let messages = self
.lock()
.by_session
.get(session)
.cloned()
.unwrap_or_default();
Box::pin(async move { Ok(messages) })
}
fn append<'a>(
&'a self,
session: &'a str,
messages: Vec<Message>,
window: &'a dyn Recent,
) -> WasmBoxedFuture<'a, Result<(), HistoryError>> {
let mut bounded = self.lock();
if !bounded.by_session.contains_key(session) {
bounded.started.push_back(session.to_owned());
while bounded.started.len() > bounded.max {
if let Some(oldest) = bounded.started.pop_front() {
bounded.by_session.remove(&oldest);
}
}
}
let conversation = bounded.by_session.entry(session.to_owned()).or_default();
conversation.extend(messages.into_iter().map(Arc::new));
let kept = view(conversation, window).len();
conversation.drain(..conversation.len() - kept);
Box::pin(async { Ok(()) })
}
}
pub(crate) struct Persistent<S>(pub(crate) S);
impl<S> Persistent<S> {
fn log(session: &str) -> String {
if names_its_log(session) {
format!("agentcore-s-{session}")
} else {
let digest = Sha256::digest(session.as_bytes());
let hex: String = digest.iter().map(|byte| format!("{byte:02x}")).collect();
format!("agentcore-h-{hex}")
}
}
}
impl<S> HistoryStore for Persistent<S>
where
S: AsyncStore + WasmCompatSend + WasmCompatSync + 'static,
{
fn load<'a>(
&'a self,
session: &'a str,
) -> WasmBoxedFuture<'a, Result<Vec<Arc<Message>>, HistoryError>> {
Box::pin(async move {
let conversation = load_async(&self.0, &Self::log(session)).await?;
Ok(conversation.messages().to_vec())
})
}
fn append<'a>(
&'a self,
session: &'a str,
messages: Vec<Message>,
_window: &'a dyn Recent,
) -> WasmBoxedFuture<'a, Result<(), HistoryError>> {
Box::pin(async move {
let log = Self::log(session);
for attempt in 1..=SAVE_ATTEMPTS {
let mut conversation = load_async(&self.0, &log).await?;
conversation.extend(messages.iter().cloned());
match save_async(&self.0, &log, &mut conversation).await {
Ok(()) => return Ok(()),
Err(SessionError::Changed { .. }) if attempt < SAVE_ATTEMPTS => {
tokio::time::sleep(backoff(attempt)).await;
}
Err(error) => return Err(error.into()),
}
}
Err(format!("the log {log} changed under {SAVE_ATTEMPTS} saves").into())
})
}
}
fn backoff(attempt: u32) -> std::time::Duration {
let jitter = u64::from(
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |elapsed| elapsed.subsec_nanos())
% 8,
);
std::time::Duration::from_millis(u64::from(attempt) * 2 + jitter)
}
pub(crate) fn local_id() -> String {
static NEXT: AtomicU64 = AtomicU64::new(0);
format!(
"local-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
)
}
#[cfg(test)]
mod tests {
use rig_memory::HeuristicTokenCounter;
use rig_memory::recent::{LastMessages, TokenBudget};
use super::*;
#[tokio::test]
async fn a_session_keeps_only_its_newest_history_within_the_window() {
let filler = "x".repeat(392);
let cost =
HeuristicTokenCounter::default().count(&Message::user(format!("run 000 {filler}")));
let window = TokenBudget::new(cost * 10 + cost / 2);
let store = InMemory::new(1);
for run in 0..200 {
store
.append(
"session",
vec![
Message::user(format!("run {run:03} {filler}")),
Message::assistant(format!("reply {run:03} {filler}")),
],
&window,
)
.await
.unwrap();
}
let kept = store.load("session").await.unwrap();
assert_eq!(kept.len(), 10);
assert!(
kept.first()
.is_some_and(|m| format!("{m:?}").contains("run 195"))
);
assert!(
kept.last()
.is_some_and(|m| format!("{m:?}").contains("reply 199"))
);
}
#[tokio::test]
async fn an_empty_window_keeps_no_history() {
let store = InMemory::new(1);
store
.append("session", vec![Message::user("hello")], &LastMessages(0))
.await
.unwrap();
assert!(store.load("session").await.unwrap().is_empty());
}
#[test]
fn every_session_id_names_a_safe_log() {
assert_eq!(
Persistent::<()>::log("019a2b3c-4d5e-7f00-8a9b-0c1d2e3f4a5b"),
"agentcore-s-019a2b3c-4d5e-7f00-8a9b-0c1d2e3f4a5b"
);
for odd in ["../etc", "a/b", "a.b", "a b", &"x".repeat(256)] {
let log = Persistent::<()>::log(odd);
assert!(log.starts_with("agentcore-h-"), "{odd:?}");
assert_eq!(log.len(), "agentcore-h-".len() + 64, "{odd:?}");
assert!(
log["agentcore-h-".len()..]
.bytes()
.all(|byte| byte.is_ascii_hexdigit()),
"{odd:?}"
);
}
assert_eq!(Persistent::<()>::log("h-kept"), "agentcore-s-h-kept");
assert_ne!(
Persistent::<()>::log("a/b"),
Persistent::<()>::log("a_b"),
"distinct ids keep distinct logs"
);
}
}