1use 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
19pub const META: &str = "meta.json";
21
22const TITLE_CHARS: usize = 60;
24
25#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
31#[serde(default)]
32pub struct SessionMeta {
33 pub title: String,
36 pub labels: BTreeMap<String, String>,
38 pub updated: u64,
40 pub model: String,
42 pub messages: usize,
44 #[serde(rename = "data", skip_serializing_if = "BTreeMap::is_empty")]
48 pub listed: BTreeMap<String, Value>,
49}
50
51impl SessionMeta {
52 pub fn read(files: &(impl Files + ?Sized)) -> Option<Self> {
54 serde_json::from_slice(&files.read_file(META).ok()?).ok()
55 }
56
57 pub fn write(&self, files: &(impl Files + ?Sized)) -> io::Result<()> {
63 files.write_file(META, &serde_json::to_vec_pretty(self)?)
64 }
65
66 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
99pub 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
120pub 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;