1use std::io;
5use std::sync::Arc;
6
7use rig_agent::agent::{
8 AgentHook, DispatchAction, DispatchEvent, HookContext, OutcomeAction, OutcomeEvent,
9};
10use rig_core::effect::{Answered, EffectId, EffectKind};
11use rig_core::tool::ToolResult;
12use rig_core::wasm_compat::{WasmBoxedFuture, WasmCompatSend, WasmCompatSync};
13use rig_memory::AsyncStore;
14use serde::Serialize;
15use serde::de::DeserializeOwned;
16use serde_json::Value;
17
18use crate::swarm::HANDOFF_TOOL;
19
20trait Files: WasmCompatSend + WasmCompatSync {
22 fn read<'a>(&'a self, name: &'a str) -> WasmBoxedFuture<'a, io::Result<Vec<u8>>>;
23 fn write<'a>(&'a self, name: &'a str, bytes: &'a [u8]) -> WasmBoxedFuture<'a, io::Result<()>>;
24}
25
26impl<S: AsyncStore + WasmCompatSend + WasmCompatSync + 'static> Files for S {
27 fn read<'a>(&'a self, name: &'a str) -> WasmBoxedFuture<'a, io::Result<Vec<u8>>> {
28 Box::pin(self.read_file_async(name))
29 }
30
31 fn write<'a>(&'a self, name: &'a str, bytes: &'a [u8]) -> WasmBoxedFuture<'a, io::Result<()>> {
32 Box::pin(self.write_file_async(name, bytes))
33 }
34}
35
36#[derive(Debug, thiserror::Error)]
38#[non_exhaustive]
39pub enum CheckpointError {
40 #[error("run id {0:?} must be 1-128 letters, digits, '-' or '_'")]
42 InvalidRunId(String),
43 #[error("could not read checkpoint {name}: {source}")]
45 Read {
46 name: String,
48 #[source]
50 source: io::Error,
51 },
52 #[error("checkpoint {name} is unreadable: {source}")]
54 Unreadable {
55 name: String,
57 #[source]
59 source: serde_json::Error,
60 },
61 #[error("{0}")]
63 Encode(#[source] serde_json::Error),
64 #[error("could not write checkpoint {name}: {source}")]
66 Write {
67 name: String,
69 #[source]
71 source: io::Error,
72 },
73 #[error("node {0:?} of the checkpoint is not in the graph")]
75 UnknownNode(String),
76 #[error("agent {0:?} of the checkpoint is not in the swarm")]
78 UnknownAgent(String),
79}
80
81#[derive(Clone)]
84pub(crate) struct Checkpoints {
85 files: Arc<dyn Files>,
86 kind: &'static str,
87}
88
89impl Checkpoints {
90 pub(crate) fn new(
91 store: impl AsyncStore + WasmCompatSend + WasmCompatSync + 'static,
92 kind: &'static str,
93 ) -> Self {
94 Self {
95 files: Arc::new(store),
96 kind,
97 }
98 }
99
100 fn name(&self, id: &str) -> Result<String, CheckpointError> {
101 let valid = (1..=128).contains(&id.len())
102 && id
103 .bytes()
104 .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_');
105 if !valid {
106 return Err(CheckpointError::InvalidRunId(id.to_owned()));
107 }
108 Ok(format!("rig-multiagent/{}/{id}.json", self.kind))
109 }
110
111 pub(crate) async fn load<T: DeserializeOwned>(
113 &self,
114 id: &str,
115 ) -> Result<Option<T>, CheckpointError> {
116 let name = self.name(id)?;
117 match self.files.read(&name).await {
118 Ok(bytes) => serde_json::from_slice(&bytes)
119 .map(Some)
120 .map_err(|source| CheckpointError::Unreadable { name, source }),
121 Err(source) if source.kind() == io::ErrorKind::NotFound => Ok(None),
122 Err(source) => Err(CheckpointError::Read { name, source }),
123 }
124 }
125
126 pub(crate) async fn save<T: Serialize>(
128 &self,
129 id: &str,
130 state: &T,
131 ) -> Result<(), CheckpointError> {
132 let name = self.name(id)?;
133 let bytes = serde_json::to_vec(state).map_err(CheckpointError::Encode)?;
134 self.files
135 .write(&name, &bytes)
136 .await
137 .map_err(|source| CheckpointError::Write { name, source })
138 }
139}
140
141impl Checkpoints {
142 pub(crate) fn with_kind(&self, kind: &'static str) -> Self {
144 Self {
145 files: self.files.clone(),
146 kind,
147 }
148 }
149}
150
151#[derive(Clone)]
154pub(crate) struct Saving {
155 pub(crate) checkpoints: Checkpoints,
156 pub(crate) run_id: String,
157}
158
159impl Saving {
160 pub(crate) fn new(checkpoints: Checkpoints, run_id: impl Into<String>) -> Self {
161 Self {
162 checkpoints,
163 run_id: run_id.into(),
164 }
165 }
166
167 pub(crate) fn kind(&self, kind: &'static str) -> Self {
169 Self::new(self.checkpoints.with_kind(kind), self.run_id.clone())
170 }
171
172 pub(crate) fn part(&self, kind: &'static str, name: &str, n: usize) -> Self {
174 Self::new(
175 self.checkpoints.with_kind(kind),
176 part_id(&self.run_id, name, n),
177 )
178 }
179}
180
181fn part_id(parent: &str, name: &str, n: usize) -> String {
184 let name: String = name
185 .chars()
186 .map(|c| {
187 if c.is_ascii_alphanumeric() || c == '-' {
188 c
189 } else {
190 '_'
191 }
192 })
193 .collect();
194 let id = format!("{parent}-{name}-{n}");
195 if id.len() <= 128 {
196 return id;
197 }
198 let hash = id.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
200 (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
201 });
202 format!("{}-{hash:016x}", &id[..id.floor_char_boundary(111)])
204}
205
206#[derive(Clone)]
212pub(crate) struct Journal(Arc<JournalInner>);
213
214struct JournalInner {
215 saving: Saving,
216 state: std::sync::Mutex<JournalState>,
217}
218
219#[derive(Default)]
220struct JournalState {
221 recorded: Vec<Entry>,
222 unreplayed: Vec<Entry>,
223 replaying: std::collections::HashMap<EffectId, ToolResult>,
224}
225
226#[derive(Clone, serde::Serialize, serde::Deserialize)]
227struct Entry {
228 tool: String,
229 args: Value,
230 result: ToolResult,
231}
232
233fn arguments(args: &str) -> Value {
234 serde_json::from_str(args).unwrap_or_else(|_| Value::String(args.to_owned()))
235}
236
237impl Journal {
238 pub(crate) async fn open(saving: Saving) -> Result<Self, CheckpointError> {
240 let recorded: Vec<Entry> = saving
241 .checkpoints
242 .load(&saving.run_id)
243 .await?
244 .unwrap_or_default();
245 Ok(Self(Arc::new(JournalInner {
246 saving,
247 state: std::sync::Mutex::new(JournalState {
248 unreplayed: recorded.clone(),
249 recorded,
250 replaying: std::collections::HashMap::new(),
251 }),
252 })))
253 }
254
255 fn state(&self) -> std::sync::MutexGuard<'_, JournalState> {
256 self.0
257 .state
258 .lock()
259 .unwrap_or_else(std::sync::PoisonError::into_inner)
260 }
261}
262
263impl AgentHook for Journal {
264 async fn on_dispatch(&self, _ctx: &HookContext, event: DispatchEvent<'_>) -> DispatchAction {
265 let EffectKind::ToolCall { name, args } = event.kind else {
266 return DispatchAction::proceed();
267 };
268 if name == HANDOFF_TOOL {
269 return DispatchAction::proceed();
270 }
271 let args = arguments(args);
272 let mut state = self.state();
273 let Some(at) = state
274 .unreplayed
275 .iter()
276 .position(|entry| &entry.tool == name && entry.args == args)
277 else {
278 return DispatchAction::proceed();
279 };
280 let entry = state.unreplayed.remove(at);
281 state.replaying.insert(event.id, entry.result);
282 tracing::info!(tool = %name, "tool call replayed from the journal");
283 DispatchAction::skip("replayed from the run's journal")
285 }
286
287 async fn on_outcome(&self, _ctx: &HookContext, event: OutcomeEvent<'_>) -> OutcomeAction {
288 let EffectKind::ToolCall { name, args } = event.kind else {
289 return OutcomeAction::proceed();
290 };
291 let replayed = self.state().replaying.remove(&event.id);
292 if let Some(result) = replayed {
293 return OutcomeAction::replace(Ok(Answered::ToolResult { result }));
294 }
295 let Some(result) = event.tool_result().filter(|result| result.is_success()) else {
296 return OutcomeAction::proceed();
297 };
298 if name == HANDOFF_TOOL {
299 return OutcomeAction::proceed();
300 }
301 let entries = {
302 let mut state = self.state();
303 state.recorded.push(Entry {
304 tool: name.clone(),
305 args: arguments(args),
306 result: result.clone(),
307 });
308 state.recorded.clone()
309 };
310 let Saving {
311 checkpoints,
312 run_id,
313 } = &self.0.saving;
314 if let Err(error) = checkpoints.save(run_id, &entries).await {
315 tracing::warn!(%error, "could not record a tool result in the journal");
316 }
317 OutcomeAction::proceed()
318 }
319}