1use std::collections::{HashMap, HashSet};
4use std::sync::Arc;
5
6use crate::client::{
7 agent::RemoteAgent,
8 apply::{Applier, Subagent},
9 error::{Error, Result},
10 transport::Transport,
11};
12use crate::{Interrupt, Message, MessageId, ReasoningMessage, RunId, ThreadId, ToolCallId};
13use serde::{Deserialize, Serialize, de::DeserializeOwned};
14use serde_json::Value;
15
16use super::pending::{ResumeSubmission, SubmissionStatus, validate_responses};
17use super::run::RunEnd;
18use super::{Thread, random_id, unique};
19
20const VERSION: u32 = 2;
23
24fn current_protocol_version() -> Option<String> {
25 Some(crate::input::PROTOCOL_VERSION.to_owned())
26}
27
28#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
71#[non_exhaustive]
72pub struct ThreadSnapshot {
73 pub version: u32,
75 pub thread_id: ThreadId,
77 #[serde(default = "current_protocol_version")]
80 pub protocol_version: Option<String>,
81 pub messages: Vec<Message>,
83 pub state: Value,
85 #[serde(default, skip_serializing_if = "Vec::is_empty")]
89 pub reasoning: Vec<ReasoningMessage>,
90 pub subagents: Vec<Subagent>,
92 pub interrupts: Vec<Interrupt>,
94 #[serde(default, skip_serializing_if = "Vec::is_empty")]
96 pub decided_interrupt_tool_call_ids: Vec<ToolCallId>,
97 #[serde(default, skip_serializing_if = "Vec::is_empty")]
108 pub abandoned: Vec<MessageId>,
109 pub submission: Option<ResumeSubmission>,
111 pub run_ids: Vec<RunId>,
113 pub last_run_end: Option<RunEnd>,
115 pub active_run_id: Option<RunId>,
117}
118
119impl ThreadSnapshot {
120 pub fn new(thread_id: impl Into<ThreadId>) -> Self {
124 Self {
125 version: VERSION,
126 thread_id: thread_id.into(),
127 protocol_version: current_protocol_version(),
128 messages: Vec::new(),
129 state: serde_json::json!({}),
130 reasoning: Vec::new(),
131 subagents: Vec::new(),
132 interrupts: Vec::new(),
133 decided_interrupt_tool_call_ids: Vec::new(),
134 abandoned: Vec::new(),
135 submission: None,
136 run_ids: Vec::new(),
137 last_run_end: None,
138 active_run_id: None,
139 }
140 }
141}
142
143impl<T, S> Thread<T, S> {
144 pub fn snapshot(&self) -> ThreadSnapshot {
149 let mut run_ids: Vec<_> = self.run_ids.iter().cloned().collect();
150 run_ids.sort_by(|a, b| a.as_str().cmp(b.as_str()));
151 let mut decided_interrupt_tool_call_ids: Vec<_> = self
152 .decided_interrupt_tool_call_ids
153 .iter()
154 .cloned()
155 .collect();
156 decided_interrupt_tool_call_ids.sort_by(|a, b| a.as_str().cmp(b.as_str()));
157 let mut abandoned: Vec<_> = self
159 .abandoned
160 .iter()
161 .filter(|id| matches!(self.applier.message(id), Some(Message::Tool(_))))
162 .cloned()
163 .collect();
164 abandoned.sort_by(|a, b| a.as_str().cmp(b.as_str()));
165 ThreadSnapshot {
166 version: VERSION,
167 thread_id: self.thread_id.clone(),
168 protocol_version: self.protocol_version.clone(),
169 messages: self.messages().to_vec(),
170 state: self.raw_state().clone(),
171 reasoning: Vec::new(),
172 subagents: self.subagents().to_vec(),
173 interrupts: self.interrupts.clone(),
174 decided_interrupt_tool_call_ids,
175 abandoned,
176 submission: self.submission.clone(),
177 run_ids,
178 last_run_end: self.last_run_end.clone(),
179 active_run_id: self.active_run_id.clone(),
180 }
181 }
182}
183
184impl<T, S: DeserializeOwned> Thread<T, S> {
185 pub fn restore(transport: T, snapshot: ThreadSnapshot) -> Result<Self>
211 where
212 T: Transport,
213 {
214 Self::restore_shared(Arc::new(transport), snapshot)
215 }
216
217 pub(crate) fn restore_shared(transport: Arc<T>, mut snapshot: ThreadSnapshot) -> Result<Self> {
218 validate_snapshot(&snapshot)?;
219 if snapshot.active_run_id.take().is_some() {
220 snapshot.last_run_end = Some(RunEnd::Aborted);
221 }
222 let typed = S::deserialize(&snapshot.state).map_err(Error::State)?;
223 if let Some(submission) = &mut snapshot.submission {
224 submission.status = SubmissionStatus::Unconfirmed;
225 }
226 for subagent in &mut snapshot.subagents {
227 if subagent.status == crate::client::SubagentStatus::Running {
228 subagent.status = crate::client::SubagentStatus::Aborted;
229 }
230 }
231 let mut applier = Applier::new()
232 .with_messages(conversation(snapshot.messages, snapshot.reasoning))
233 .with_state(snapshot.state);
234 applier.restore_auxiliary(snapshot.subagents, snapshot.interrupts.clone());
235 let abandoned = snapshot
236 .abandoned
237 .into_iter()
238 .filter(|id| matches!(applier.message(id), Some(Message::Tool(_))))
239 .collect();
240 Ok(Self {
241 agent: RemoteAgent::new(transport),
242 thread_id: snapshot.thread_id,
243 applier,
244 state: Ok(typed),
245 tools: Vec::new(),
246 context: Vec::new(),
247 forwarded_props: Value::Null,
248 protocol_version: snapshot.protocol_version,
249 verify: true,
250 interrupts: snapshot.interrupts,
251 decided_interrupt_tool_call_ids: snapshot
252 .decided_interrupt_tool_call_ids
253 .into_iter()
254 .collect(),
255 abandoned,
256 submission: snapshot.submission,
257 run_ids: snapshot.run_ids.into_iter().collect(),
258 next_run_id: None,
259 last_run_end: snapshot.last_run_end,
260 active_run_id: None,
261 observer: None,
262 id_generator: Box::new(random_id),
263 diagnostic_limit: 100,
264 })
265 }
266}
267
268fn conversation(messages: Vec<Message>, reasoning: Vec<ReasoningMessage>) -> Vec<Message> {
272 if reasoning.is_empty() {
273 return messages;
274 }
275 let taken: HashSet<&MessageId> = messages.iter().map(Message::id).collect();
276 let mut conversation: Vec<Message> = reasoning
277 .into_iter()
278 .filter(|entry| {
279 let holds_nothing = entry.content.is_empty()
280 && entry.encrypted_value.is_none()
281 && entry.metadata.is_none();
282 !holds_nothing && !taken.contains(&entry.id)
283 })
284 .map(Message::Reasoning)
285 .collect();
286 conversation.extend(messages);
287 conversation
288}
289
290fn validate_snapshot(snapshot: &ThreadSnapshot) -> Result<()> {
291 match snapshot.version {
292 1 => unique(
293 snapshot.reasoning.iter().map(|message| message.id.as_str()),
294 "reasoning",
295 )?,
296 VERSION if snapshot.reasoning.is_empty() => {}
298 VERSION => {
299 return Err(Error::Snapshot(
300 "a version 2 snapshot holds reasoning in `messages`, so `reasoning` must be empty"
301 .into(),
302 ));
303 }
304 other => return Err(Error::Snapshot(format!("unsupported version {other}"))),
305 }
306 if snapshot.thread_id.as_str().is_empty() {
307 return Err(Error::Snapshot("empty thread ID".into()));
308 }
309 unique(
310 snapshot
311 .messages
312 .iter()
313 .map(|message| message.id().as_str()),
314 "message",
315 )?;
316 unique(
317 snapshot
318 .subagents
319 .iter()
320 .map(|subagent| subagent.run_id.as_str()),
321 "subagent",
322 )?;
323 unique(
324 snapshot
325 .interrupts
326 .iter()
327 .map(|interrupt| interrupt.id.as_str()),
328 "interrupt",
329 )?;
330 unique(
331 snapshot
332 .decided_interrupt_tool_call_ids
333 .iter()
334 .map(ToolCallId::as_str),
335 "decided interrupt tool call",
336 )?;
337 unique(snapshot.run_ids.iter().map(|id| id.as_str()), "run")?;
338 let run_ids: HashSet<&RunId> = snapshot.run_ids.iter().collect();
339 if let Some(id) = &snapshot.active_run_id {
340 if !run_ids.contains(id) {
341 return Err(Error::Snapshot(
342 "active run refers to an unknown run ID".into(),
343 ));
344 }
345 }
346 ancestry(&snapshot.subagents)?;
347 if let Some(submission) = &snapshot.submission {
348 if submission.status == SubmissionStatus::InFlight
349 && snapshot.active_run_id.as_ref() != Some(&submission.run_id)
350 {
351 return Err(Error::Snapshot(
352 "in-flight submission must reference the active run".into(),
353 ));
354 }
355 if !run_ids.contains(&submission.run_id) {
356 return Err(Error::Snapshot(
357 "submission refers to an unknown run ID".into(),
358 ));
359 }
360 validate_responses(&snapshot.interrupts, &submission.entries, false)
361 .map_err(|error| Error::Snapshot(error.to_string()))?;
362 }
363 Ok(())
364}
365
366fn ancestry(subagents: &[Subagent]) -> Result<usize> {
373 #[derive(Clone, Copy, PartialEq)]
375 enum Seen {
376 No,
377 Walking,
379 Rooted,
381 }
382 let index: HashMap<&str, usize> = subagents
383 .iter()
384 .enumerate()
385 .map(|(index, subagent)| (subagent.run_id.as_str(), index))
386 .collect();
387 let mut seen = vec![Seen::No; subagents.len()];
388 let mut walk = Vec::new();
389 let mut followed = 0;
390 for start in 0..subagents.len() {
391 let mut at = start;
392 loop {
393 match seen[at] {
394 Seen::Rooted => break,
395 Seen::Walking => return Err(Error::Snapshot("cyclic subagent ancestry".into())),
396 Seen::No => {}
397 }
398 seen[at] = Seen::Walking;
399 walk.push(at);
400 let Some(parent) = &subagents[at].parent_subagent_run_id else {
401 break;
402 };
403 at = *index
404 .get(parent.as_str())
405 .ok_or_else(|| Error::Snapshot(format!("unknown parent subagent {parent}")))?;
406 followed += 1;
407 }
408 for walked in walk.drain(..) {
409 seen[walked] = Seen::Rooted;
410 }
411 }
412 Ok(followed)
413}
414
415#[cfg(test)]
416mod tests {
417 use super::*;
418
419 fn subagent(id: &str, parent: Option<&str>) -> Subagent {
420 Subagent {
421 run_id: id.into(),
422 name: "worker".into(),
423 description: None,
424 parent_subagent_run_id: parent.map(Into::into),
425 parent_tool_call_id: None,
426 parent_message_id: None,
427 status: crate::client::SubagentStatus::Finished { result: None },
428 }
429 }
430
431 #[test]
436 fn a_chain_of_nested_subagents_is_checked_in_one_pass() {
437 const DEPTH: usize = 20_000;
438 let id = |depth: usize| format!("s-{depth}");
439 let mut chain: Vec<Subagent> = (0..DEPTH)
440 .map(|depth| {
441 let parent = depth.checked_sub(1).map(id);
442 subagent(&id(depth), parent.as_deref())
443 })
444 .collect();
445 assert_eq!(ancestry(&chain).unwrap(), DEPTH - 1);
446 chain.reverse();
447 assert_eq!(ancestry(&chain).unwrap(), DEPTH - 1);
448 }
449
450 #[test]
451 fn a_cycle_and_an_unlisted_parent_are_refused() {
452 let cycle = [
453 subagent("a", Some("c")),
454 subagent("b", Some("a")),
455 subagent("c", Some("b")),
456 subagent("d", Some("a")),
457 ];
458 assert_eq!(
459 ancestry(&cycle).unwrap_err().to_string(),
460 "invalid thread snapshot: cyclic subagent ancestry"
461 );
462 assert_eq!(
463 ancestry(&[subagent("a", Some("a"))])
464 .unwrap_err()
465 .to_string(),
466 "invalid thread snapshot: cyclic subagent ancestry"
467 );
468 assert_eq!(
469 ancestry(&[subagent("a", Some("gone"))])
470 .unwrap_err()
471 .to_string(),
472 "invalid thread snapshot: unknown parent subagent gone"
473 );
474 let tree = [
476 subagent("root", None),
477 subagent("left", Some("root")),
478 subagent("right", Some("root")),
479 subagent("leaf", Some("left")),
480 ];
481 assert_eq!(ancestry(&tree).unwrap(), 3);
482 }
483}