Skip to main content

rig_memory/
meta.rs

1//! What a session says about itself beside its logs, kept as a file of its
2//! store: what a listing shows of it ([`SessionMeta`], in [`META`]).
3//!
4//! The file changes only by fields that a reader not knowing them skips and
5//! a reader missing them takes as empty.
6
7use std::collections::{BTreeMap, BTreeSet};
8use std::io;
9
10use rig_core::completion::Message;
11use rig_core::conversation::EntryRef;
12use rig_core::message::UserContent;
13use serde::{Deserialize, Serialize};
14use serde_json::Value;
15
16use crate::{Files, SavedAgent, Session};
17use rig_core::now_ms;
18
19/// The file of a session's store that holds its [`SessionMeta`].
20pub const META: &str = "meta.json";
21
22/// Most characters of a title made by [`title_of`].
23const TITLE_CHARS: usize = 60;
24
25/// What a listing shows of a session, kept in its store: what it is
26/// about, the labels plugins give it, and when it last changed. Its logs
27/// hold the same facts; this is the cache a listing reads without folding
28/// them. Fields a reader does not know are skipped, and missing ones are
29/// empty.
30#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
31#[serde(default)]
32pub struct SessionMeta {
33    /// What the session is about: the start of the first message the user
34    /// typed ([`title_of`]); empty until a turn ended.
35    pub title: String,
36    /// Plugins' labels by tag, such as a goal or what it cost.
37    pub labels: BTreeMap<String, String>,
38    /// When it last changed, in milliseconds since the Unix epoch.
39    pub updated: u64,
40    /// The main agent's model, `vendor/model`; empty when unknown.
41    pub model: String,
42    /// How many messages the main agent's active line holds.
43    pub messages: usize,
44    /// Plugins' listed values by key, each copied here whenever it changes,
45    /// so a listing shows and filters by them without opening a log; kept
46    /// small.
47    #[serde(rename = "data", skip_serializing_if = "BTreeMap::is_empty")]
48    pub listed: BTreeMap<String, Value>,
49}
50
51impl SessionMeta {
52    /// The listing kept in `files`, if it has one that reads.
53    pub fn read(files: &(impl Files + ?Sized)) -> Option<Self> {
54        serde_json::from_slice(&files.read_file(META).ok()?).ok()
55    }
56
57    /// Keeps it as the listing in `files`.
58    ///
59    /// # Errors
60    ///
61    /// When `files` cannot write it.
62    pub fn write(&self, files: &(impl Files + ?Sized)) -> io::Result<()> {
63        files.write_file(META, &serde_json::to_vec_pretty(self)?)
64    }
65
66    /// Updates this listing from `session`, for a program that writes a
67    /// session no rig is running: the main agent's model and message count,
68    /// `updated` set to now, and each listed value (keys in `listed`, plus
69    /// those already listed), taken from the session's own values, else from
70    /// the main agent ([`Session::main_agent`]) and then the first other
71    /// agent that has one, those nothing spawned first, each group by id, as
72    /// a running rig lists them. A value that is gone is unlisted. The title
73    /// and labels stay.
74    pub fn relist(&mut self, session: &Session, listed: &BTreeSet<String>) {
75        let main = session.main_agent();
76        let is_main = |agent: &SavedAgent| main.is_some_and(|main| std::ptr::eq(agent, main));
77        let mut agents: Vec<_> = (session.agents.iter())
78            .filter(|agent| !agent.retired)
79            .collect();
80        agents.sort_by_key(|agent| (!is_main(agent), agent.parent.is_some(), &agent.id));
81        self.messages = main.map_or(0, |main| main.conversation.messages().len());
82        self.model = main.and_then(|main| main.model()).unwrap_or_default();
83        let keys: BTreeSet<String> = listed.iter().chain(self.listed.keys()).cloned().collect();
84        self.listed = keys
85            .into_iter()
86            .filter_map(|key| {
87                let mut holders = agents.iter().map(|agent| &agent.saved);
88                let value = session
89                    .saved
90                    .get(&key)
91                    .or_else(|| holders.find_map(|state| state.get(&key)))?;
92                Some((key, value.clone()))
93            })
94            .collect();
95        self.updated = now_ms();
96    }
97}
98
99/// A title or label of `text`, as a listing shows it: on one line, each
100/// run of whitespace one space, cut to 60 characters (the last an
101/// ellipsis when cut).
102///
103/// ```
104/// use rig_memory::title_of;
105///
106/// assert_eq!(title_of("  fix\n the   parser "), "fix the parser");
107/// assert_eq!(title_of(&"a".repeat(80)).chars().count(), 60);
108/// ```
109pub fn title_of(text: &str) -> String {
110    let line = text.split_whitespace().collect::<Vec<_>>().join(" ");
111    match line.char_indices().nth(TITLE_CHARS) {
112        None => line,
113        Some(_) => {
114            let kept = line.chars().take(TITLE_CHARS - 1);
115            kept.chain(['…']).collect()
116        }
117    }
118}
119
120/// One line of `entry`: who wrote it, then the start of its text, or the
121/// tools it called.
122pub fn excerpt(entry: &EntryRef<'_>) -> String {
123    let (who, text) = match entry.message {
124        Message::System { content } => ("system", content.clone()),
125        Message::User { content } => {
126            let text: Vec<&str> = content.iter().filter_map(UserContent::as_text).collect();
127            match text.is_empty() {
128                true => ("tool results", String::new()),
129                false => ("user", text.join(" ")),
130            }
131        }
132        Message::Assistant(turn) => {
133            let text = turn.text();
134            let calls: Vec<&str> = turn
135                .tool_calls()
136                .map(|call| call.function.name.as_str())
137                .collect();
138            match (text.trim().is_empty(), calls.is_empty()) {
139                (true, false) => ("calls", calls.join(", ")),
140                _ => ("assistant", text),
141            }
142        }
143    };
144    format!("{who}: {}", title_of(&text)).trim_end().to_owned()
145}
146
147#[cfg(test)]
148mod tests;