use std::io;
use std::sync::Arc;
use rig_agent::agent::{
AgentHook, DispatchAction, DispatchEvent, HookContext, OutcomeAction, OutcomeEvent,
};
use rig_core::effect::{Answered, EffectId, EffectKind};
use rig_core::tool::ToolResult;
use rig_core::wasm_compat::{WasmBoxedFuture, WasmCompatSend, WasmCompatSync};
use rig_memory::AsyncStore;
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::Value;
use crate::swarm::HANDOFF_TOOL;
trait Files: WasmCompatSend + WasmCompatSync {
fn read<'a>(&'a self, name: &'a str) -> WasmBoxedFuture<'a, io::Result<Vec<u8>>>;
fn write<'a>(&'a self, name: &'a str, bytes: &'a [u8]) -> WasmBoxedFuture<'a, io::Result<()>>;
}
impl<S: AsyncStore + WasmCompatSend + WasmCompatSync + 'static> Files for S {
fn read<'a>(&'a self, name: &'a str) -> WasmBoxedFuture<'a, io::Result<Vec<u8>>> {
Box::pin(self.read_file_async(name))
}
fn write<'a>(&'a self, name: &'a str, bytes: &'a [u8]) -> WasmBoxedFuture<'a, io::Result<()>> {
Box::pin(self.write_file_async(name, bytes))
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum CheckpointError {
#[error("run id {0:?} must be 1-128 letters, digits, '-' or '_'")]
InvalidRunId(String),
#[error("could not read checkpoint {name}: {source}")]
Read {
name: String,
#[source]
source: io::Error,
},
#[error("checkpoint {name} is unreadable: {source}")]
Unreadable {
name: String,
#[source]
source: serde_json::Error,
},
#[error("{0}")]
Encode(#[source] serde_json::Error),
#[error("could not write checkpoint {name}: {source}")]
Write {
name: String,
#[source]
source: io::Error,
},
#[error("node {0:?} of the checkpoint is not in the graph")]
UnknownNode(String),
#[error("agent {0:?} of the checkpoint is not in the swarm")]
UnknownAgent(String),
}
#[derive(Clone)]
pub(crate) struct Checkpoints {
files: Arc<dyn Files>,
kind: &'static str,
}
impl Checkpoints {
pub(crate) fn new(
store: impl AsyncStore + WasmCompatSend + WasmCompatSync + 'static,
kind: &'static str,
) -> Self {
Self {
files: Arc::new(store),
kind,
}
}
fn name(&self, id: &str) -> Result<String, CheckpointError> {
let valid = (1..=128).contains(&id.len())
&& id
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_');
if !valid {
return Err(CheckpointError::InvalidRunId(id.to_owned()));
}
Ok(format!("rig-multiagent/{}/{id}.json", self.kind))
}
pub(crate) async fn load<T: DeserializeOwned>(
&self,
id: &str,
) -> Result<Option<T>, CheckpointError> {
let name = self.name(id)?;
match self.files.read(&name).await {
Ok(bytes) => serde_json::from_slice(&bytes)
.map(Some)
.map_err(|source| CheckpointError::Unreadable { name, source }),
Err(source) if source.kind() == io::ErrorKind::NotFound => Ok(None),
Err(source) => Err(CheckpointError::Read { name, source }),
}
}
pub(crate) async fn save<T: Serialize>(
&self,
id: &str,
state: &T,
) -> Result<(), CheckpointError> {
let name = self.name(id)?;
let bytes = serde_json::to_vec(state).map_err(CheckpointError::Encode)?;
self.files
.write(&name, &bytes)
.await
.map_err(|source| CheckpointError::Write { name, source })
}
}
impl Checkpoints {
pub(crate) fn with_kind(&self, kind: &'static str) -> Self {
Self {
files: self.files.clone(),
kind,
}
}
}
#[derive(Clone)]
pub(crate) struct Saving {
pub(crate) checkpoints: Checkpoints,
pub(crate) run_id: String,
}
impl Saving {
pub(crate) fn new(checkpoints: Checkpoints, run_id: impl Into<String>) -> Self {
Self {
checkpoints,
run_id: run_id.into(),
}
}
pub(crate) fn kind(&self, kind: &'static str) -> Self {
Self::new(self.checkpoints.with_kind(kind), self.run_id.clone())
}
pub(crate) fn part(&self, kind: &'static str, name: &str, n: usize) -> Self {
Self::new(
self.checkpoints.with_kind(kind),
part_id(&self.run_id, name, n),
)
}
}
fn part_id(parent: &str, name: &str, n: usize) -> String {
let name: String = name
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '-' {
c
} else {
'_'
}
})
.collect();
let id = format!("{parent}-{name}-{n}");
if id.len() <= 128 {
return id;
}
let hash = id.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
(hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
});
format!("{}-{hash:016x}", &id[..id.floor_char_boundary(111)])
}
#[derive(Clone)]
pub(crate) struct Journal(Arc<JournalInner>);
struct JournalInner {
saving: Saving,
state: std::sync::Mutex<JournalState>,
}
#[derive(Default)]
struct JournalState {
recorded: Vec<Entry>,
unreplayed: Vec<Entry>,
replaying: std::collections::HashMap<EffectId, ToolResult>,
}
#[derive(Clone, serde::Serialize, serde::Deserialize)]
struct Entry {
tool: String,
args: Value,
result: ToolResult,
}
fn arguments(args: &str) -> Value {
serde_json::from_str(args).unwrap_or_else(|_| Value::String(args.to_owned()))
}
impl Journal {
pub(crate) async fn open(saving: Saving) -> Result<Self, CheckpointError> {
let recorded: Vec<Entry> = saving
.checkpoints
.load(&saving.run_id)
.await?
.unwrap_or_default();
Ok(Self(Arc::new(JournalInner {
saving,
state: std::sync::Mutex::new(JournalState {
unreplayed: recorded.clone(),
recorded,
replaying: std::collections::HashMap::new(),
}),
})))
}
fn state(&self) -> std::sync::MutexGuard<'_, JournalState> {
self.0
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
}
impl AgentHook for Journal {
async fn on_dispatch(&self, _ctx: &HookContext, event: DispatchEvent<'_>) -> DispatchAction {
let EffectKind::ToolCall { name, args } = event.kind else {
return DispatchAction::proceed();
};
if name == HANDOFF_TOOL {
return DispatchAction::proceed();
}
let args = arguments(args);
let mut state = self.state();
let Some(at) = state
.unreplayed
.iter()
.position(|entry| &entry.tool == name && entry.args == args)
else {
return DispatchAction::proceed();
};
let entry = state.unreplayed.remove(at);
state.replaying.insert(event.id, entry.result);
tracing::info!(tool = %name, "tool call replayed from the journal");
DispatchAction::skip("replayed from the run's journal")
}
async fn on_outcome(&self, _ctx: &HookContext, event: OutcomeEvent<'_>) -> OutcomeAction {
let EffectKind::ToolCall { name, args } = event.kind else {
return OutcomeAction::proceed();
};
let replayed = self.state().replaying.remove(&event.id);
if let Some(result) = replayed {
return OutcomeAction::replace(Ok(Answered::ToolResult { result }));
}
let Some(result) = event.tool_result().filter(|result| result.is_success()) else {
return OutcomeAction::proceed();
};
if name == HANDOFF_TOOL {
return OutcomeAction::proceed();
}
let entries = {
let mut state = self.state();
state.recorded.push(Entry {
tool: name.clone(),
args: arguments(args),
result: result.clone(),
});
state.recorded.clone()
};
let Saving {
checkpoints,
run_id,
} = &self.0.saving;
if checkpoints.save(run_id, &entries).await.is_err() {
tracing::warn!(
kind = "checkpoint",
"could not record a tool result in the journal"
);
}
OutcomeAction::proceed()
}
}