use std::collections::{HashMap, VecDeque};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, LazyLock, Mutex, MutexGuard, PoisonError};
use rig_agent::Agent;
use rig_core::conversation::pairing::safe_start;
use rig_core::message::{Message, UserContent};
use rig_core::wasm_compat::{WasmBoxedFuture, WasmCompatSend, WasmCompatSync};
use rig_memory::recent::{Recent, view};
use rig_memory::{
AsyncStore, SUMMARIZATION_SYSTEM_PROMPT, SessionError, SummaryState, apply_summary, load_async,
save_async, serialize_conversation,
};
use sha2::{Digest, Sha256};
use tracing::{Instrument, Span};
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 replace_head<'a>(
&'a self,
session: &'a str,
read: &'a [Arc<Message>],
summary: &'a SummaryState,
) -> WasmBoxedFuture<'a, Result<Option<Vec<Arc<Message>>>, 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(()) })
}
fn replace_head<'a>(
&'a self,
session: &'a str,
read: &'a [Arc<Message>],
summary: &'a SummaryState,
) -> WasmBoxedFuture<'a, Result<Option<Vec<Arc<Message>>>, HistoryError>> {
let mut bounded = self.lock();
let replaced = bounded
.by_session
.get_mut(session)
.and_then(|conversation| {
let same = conversation
.get(..read.len())?
.iter()
.zip(read)
.all(|(now, read)| Arc::ptr_eq(now, read));
if !same || read.is_empty() {
return None;
}
let text = summary.message()?;
conversation.drain(..read.len());
conversation.insert(0, Arc::new(Message::user(text)));
Some(conversation.clone())
});
Box::pin(async { Ok(replaced) })
}
}
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 replace_head<'a>(
&'a self,
session: &'a str,
read: &'a [Arc<Message>],
summary: &'a SummaryState,
) -> WasmBoxedFuture<'a, Result<Option<Vec<Arc<Message>>>, HistoryError>> {
Box::pin(async move {
let log = Self::log(session);
let mut conversation = load_async(&self.0, &log).await?;
let replaces: Vec<Arc<Message>> = {
let now = conversation.messages();
let same = now
.get(..read.len())
.is_some_and(|now| now.iter().zip(read).all(|(now, read)| **now == **read));
match now.get(..read.len()) {
Some(head) if same && !read.is_empty() => head.to_vec(),
_ => return Ok(None),
}
};
if apply_summary(&mut conversation, &replaces, summary).is_none() {
return Ok(None);
}
save_async(&self.0, &log, &mut conversation).await?;
Ok(Some(conversation.messages().to_vec()))
})
}
}
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)
}
#[derive(Clone)]
pub(crate) struct Summarizing {
pub(crate) summarizer: Agent,
pub(crate) keep_recent: usize,
pub(crate) trigger_messages: usize,
}
#[derive(Debug, thiserror::Error)]
enum SummarizeError {
#[error("the summarizer failed: {0}")]
Run(String),
#[error("the summarizer returned no text")]
Empty,
#[error("the summary could not be stored: {0}")]
Store(String),
#[error("the conversation changed while it was summarized")]
Changed,
}
impl SummarizeError {
fn kind(&self) -> &'static str {
match self {
Self::Run(_) => "run_failed",
Self::Empty => "empty_reply",
Self::Store(_) => "store_error",
Self::Changed => "changed",
}
}
}
const PROBE: &str = "\u{1}";
static OPENING: LazyLock<String> = LazyLock::new(|| {
SummaryState {
summary: PROBE.to_owned(),
..SummaryState::default()
}
.message()
.unwrap_or_default()
.split(PROBE)
.next()
.unwrap_or_default()
.to_owned()
});
pub(crate) fn is_summary(message: &Message) -> bool {
let Message::User { content } = message else {
return false;
};
matches!(
content.first(),
Some(UserContent::Text(text)) if text.text.starts_with(OPENING.as_str())
)
}
pub(crate) struct Retained<'a> {
pub(crate) window: &'a dyn Recent,
pub(crate) floor: usize,
}
impl Recent for Retained<'_> {
fn start(&self, messages: &[Arc<Message>]) -> usize {
self.window
.start(messages)
.min(messages.len().saturating_sub(self.floor))
}
}
fn summary_prompt(read: &[Arc<Message>]) -> String {
format!(
"{SUMMARIZATION_SYSTEM_PROMPT}\n\n<conversation>\n{}\n</conversation>\n\n\
Summarize the conversation above in plain prose and short lists: the user's goals, \
decisions made, facts and names later turns depend on, and tasks still open. If it \
begins with an earlier summary, carry its facts forward.",
serialize_conversation(read)
)
}
pub(crate) async fn summarize(
store: &dyn HistoryStore,
summarizing: &Summarizing,
session: &str,
messages: &[Arc<Message>],
record_content: bool,
) -> Option<Vec<Arc<Message>>> {
let cut = safe_start(
messages,
messages.len().saturating_sub(summarizing.keep_recent),
);
let kept = messages.len().saturating_sub(cut);
let span = tracing::info_span!(
"agentcore.summarize",
agentcore.session_id = %session,
agentcore.summary.messages_summarized = cut,
agentcore.summary.messages_kept = kept,
agentcore.summary.outcome = tracing::field::Empty,
gen_ai.usage.input_tokens = tracing::field::Empty,
gen_ai.usage.output_tokens = tracing::field::Empty,
agentcore.summary.prompt = tracing::field::Empty,
agentcore.summary.text = tracing::field::Empty,
);
let Some(read) = messages.get(..cut).filter(|read| !read.is_empty()) else {
span.record("agentcore.summary.outcome", "skipped_nothing_older");
return None;
};
let attempt = try_summarize(store, summarizing, session, read, record_content, &span)
.instrument(span.clone())
.await;
match attempt {
Ok(summarized) => {
span.record("agentcore.summary.outcome", "summarized");
tracing::info!(
parent: &span,
messages_summarized = cut,
messages_kept = kept,
"summarized the conversation"
);
Some(summarized)
}
Err(SummarizeError::Changed) => {
span.record("agentcore.summary.outcome", "skipped_changed");
tracing::info!(
parent: &span,
"the conversation changed while it was summarized; keeping its history"
);
None
}
Err(error) => {
span.record("agentcore.summary.outcome", "failed");
let shown = crate::logged(record_content, error.kind(), &error);
tracing::warn!(parent: &span, error = %shown, "could not summarize the conversation; keeping its full history");
None
}
}
}
async fn try_summarize(
store: &dyn HistoryStore,
summarizing: &Summarizing,
session: &str,
read: &[Arc<Message>],
record_content: bool,
span: &Span,
) -> Result<Vec<Arc<Message>>, SummarizeError> {
let prompt = summary_prompt(read);
if record_content {
span.record("agentcore.summary.prompt", prompt.as_str());
}
let response = summarizing
.summarizer
.prompt(prompt)
.run()
.await
.map_err(|failure| SummarizeError::Run(failure.to_string()))?;
let usage = response.usage();
if let Some(input) = usage.input_tokens {
span.record("gen_ai.usage.input_tokens", input);
}
if let Some(output) = usage.output_tokens {
span.record("gen_ai.usage.output_tokens", output);
}
let text = response.output();
let text = text.trim();
if text.is_empty() {
return Err(SummarizeError::Empty);
}
if record_content {
span.record("agentcore.summary.text", text);
}
let state = SummaryState {
summary: text.to_owned(),
..SummaryState::default()
};
store
.replace_head(session, read, &state)
.await
.map_err(|failure| SummarizeError::Store(failure.to_string()))?
.ok_or(SummarizeError::Changed)
}
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"
);
}
}