1use std::io;
5
6use rig_core::conversation::Conversation;
7
8use crate::format::SESSION;
9use crate::session::{Fold, Folded, conversation_of, fold, log_lines, read_header};
10use crate::{CURRENT, SessionError, Store};
11
12pub fn read_conversation(
21 store: &dyn Store,
22 agent: Option<&str>,
23) -> Result<(String, Conversation), SessionError> {
24 let how = Fold::WHOLE;
25 let folded = match agent {
26 Some(agent) => fold(store, agent, how)?,
27 None => main_log(store, how)?,
28 };
29 let Some(folded) = folded.filter(|folded| folded.name != SESSION) else {
30 let why = format!("the session has no agent {}", agent.unwrap_or("to talk to"));
31 return Err(io::Error::new(io::ErrorKind::NotFound, why).into());
32 };
33 Ok((folded.name.clone(), conversation_of(Some(folded))?))
34}
35
36fn main_log(store: &dyn Store, how: Fold) -> Result<Option<Folded>, SessionError> {
41 let own = Fold {
42 images: false,
43 ..how
44 };
45 let current = fold(store, SESSION, own)?
46 .and_then(|session| session.state.get(CURRENT)?.as_str().map(str::to_owned));
47 let mut candidates = Vec::new();
48 for name in store.logs()? {
49 if name == SESSION {
50 continue;
51 }
52 let Some(lines) = log_lines(store, &name)? else {
53 continue;
54 };
55 if let Some((_, _, first)) = lines.iter().next() {
56 let (_, header) = read_header(&name, first)?;
57 if header.parent.is_none() {
58 candidates.push((Some(&name) != current.as_ref(), name));
59 }
60 }
61 }
62 candidates.sort();
63 for (.., name) in candidates {
64 if let Some(folded) = fold(store, &name, how)?.filter(|folded| !folded.retired) {
65 return Ok(Some(folded));
66 }
67 }
68 Ok(None)
69}
70
71#[cfg(test)]
72mod tests;