Skip to main content

rig_memory/
listing.rs

1//! One agent's conversation of a saved session, read without the rest
2//! ([`read_conversation`]), as a session picker previews it.
3
4use 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
12/// The conversation of `agent` (the main agent when `None`, found from the
13/// session's own log and the agent logs' headers) of the session in
14/// `store`, folded from that agent's log only, writing nothing. Returns
15/// the agent's id and its conversation, with ids and made-times kept.
16///
17/// # Errors
18///
19/// As [`load`](crate::load), or when there is no such agent.
20pub 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
36/// The main agent's log, folded: of the logs whose header names no parent
37/// and that are not retired, the one the session's [`CURRENT`] names, else
38/// the first by id, as [`Session::main_agent`](crate::Session::main_agent)
39/// finds it; only its candidates are folded.
40fn 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;