Skip to main content

artifactize_core/agent/session/
summary.rs

1//! `session show --summary`: what a saved conversation spent and did, computed from its
2//! session file alone.
3
4use std::collections::BTreeMap;
5
6use rig_core::message::{AssistantContent, Message, UserContent};
7use serde::Serialize;
8
9use super::Conversation;
10
11/// A saved conversation's backend, time span, turns, tokens and tool calls.
12#[derive(Debug, Serialize)]
13#[serde(rename_all = "camelCase")]
14pub struct Summary {
15    pub backend: Option<crate::config::Backend>,
16    pub model: Option<crate::config::ModelId>,
17    pub reasoning: Option<crate::config::Reasoning>,
18    /// The first and last event's time.
19    pub started_at: Option<crate::types::Timestamp>,
20    pub ended_at: Option<crate::types::Timestamp>,
21    #[serde(serialize_with = "crate::config::validation::milliseconds::serialize")]
22    pub duration_ms: Option<std::time::Duration>,
23    pub follow_ups: usize,
24    /// Every provider turn in order: the review's, then each follow-up's.
25    pub turns: Vec<Turn>,
26    /// The reported token counters of every attempt, summed.
27    pub tokens: BTreeMap<String, u64>,
28    /// By tool name.
29    pub tool_calls: BTreeMap<crate::types::CalledTool, ToolCalls>,
30}
31
32/// One provider request and its attempts.
33#[derive(Debug, Serialize)]
34#[serde(rename_all = "camelCase")]
35pub struct Turn {
36    /// The follow-up the turn answered; absent for the review's turns.
37    #[serde(skip_serializing_if = "Option::is_none")]
38    pub follow_up: Option<u64>,
39    pub turn: u64,
40    pub attempts: u64,
41    /// The reported token counters of its attempts, summed.
42    pub tokens: BTreeMap<String, u64>,
43}
44
45#[derive(Debug, Default, Serialize)]
46pub struct ToolCalls {
47    pub calls: u64,
48    /// Calls whose result was an error, and calls never answered because the review or
49    /// follow-up stopped first.
50    pub failed: u64,
51}
52
53impl Summary {
54    pub fn new(conversation: &Conversation) -> Self {
55        let header = conversation.header();
56
57        let (started_at, ended_at) = (
58            conversation.header_at,
59            conversation
60                .events()
61                .last()
62                .map_or(conversation.header_at, |event| event.at),
63        );
64        let duration_ms = started_at
65            .zip(ended_at)
66            .map(|(start, end)| end.since(start));
67        let mut summary = Self {
68            backend: header.backend.clone(),
69            model: header.model.clone(),
70            reasoning: header.reasoning,
71            started_at,
72            ended_at,
73            duration_ms,
74            follow_ups: conversation.sends(),
75            turns: Vec::new(),
76            tokens: BTreeMap::new(),
77            tool_calls: BTreeMap::new(),
78        };
79        // Calls by tool, then the results that answered them and those that failed.
80        let mut answered = BTreeMap::<crate::types::CalledTool, (u64, u64)>::new();
81        for event in conversation.events() {
82            match &event.kind {
83                super::Kind::Attempt(attempt) => summary.attempt(event.send, attempt),
84                super::Kind::Message(event) => match event.message() {
85                    Message::Assistant { content, .. } => {
86                        for part in content {
87                            if let AssistantContent::ToolCall(call) = part {
88                                let name =
89                                    crate::types::CalledTool::called(call.function.name.as_str());
90                                summary.tool_calls.entry(name).or_default().calls += 1;
91                            }
92                        }
93                    }
94                    Message::User { content } => {
95                        let results = content.iter().filter_map(|part| match part {
96                            UserContent::ToolResult(result) => Some(result),
97                            _ => None,
98                        });
99                        for (index, result) in results.enumerate() {
100                            let (count, failed) = answered
101                                .entry(crate::types::CalledTool::called(result.name.as_str()))
102                                .or_default();
103                            *count += 1;
104                            *failed += u64::from(event.is_error.get(index) == Some(&true));
105                        }
106                    }
107                    Message::System { .. } => {}
108                },
109                _ => {}
110            }
111        }
112        for (name, calls) in &mut summary.tool_calls {
113            let (count, failed) = answered.get(name).copied().unwrap_or_default();
114            calls.failed = failed + calls.calls.saturating_sub(count);
115        }
116        summary
117    }
118
119    /// Count an attempt in its turn and in the totals.
120    fn attempt(&mut self, send: Option<usize>, attempt: &crate::llm::Attempt) {
121        let follow_up = send.map(|send| send as u64);
122        let turn = attempt.turn as u64;
123        if self
124            .turns
125            .last()
126            .is_none_or(|last| (last.follow_up, last.turn) != (follow_up, turn))
127        {
128            self.turns.push(Turn {
129                follow_up,
130                turn,
131                attempts: 0,
132                tokens: BTreeMap::new(),
133            });
134        }
135        let current = self.turns.last_mut().expect("the attempt's turn");
136        current.attempts += 1;
137        for (name, value) in attempt.usage.iter() {
138            for tokens in [&mut current.tokens, &mut self.tokens] {
139                let total = tokens.entry(name.clone()).or_default();
140                *total = total.saturating_add(*value);
141            }
142        }
143    }
144}
145
146/// Token counters as text, in a fixed order with readable names; `None` without any.
147pub fn tokens_text(tokens: &BTreeMap<String, u64>) -> Option<String> {
148    let parts: Vec<_> = [
149        ("inputTokens", "input"),
150        ("outputTokens", "output"),
151        ("cacheReadTokens", "cache read"),
152        ("cacheWriteTokens", "cache write"),
153        ("reasoningTokens", "reasoning"),
154    ]
155    .into_iter()
156    .filter_map(|(name, label)| Some(format!("{label} {}", tokens.get(name)?)))
157    .collect();
158    (!parts.is_empty()).then(|| parts.join(" · "))
159}
160
161#[cfg(test)]
162mod tests {
163    use rig_core::message::{ToolCall, ToolFunction, ToolName, ToolResultContent};
164    use serde_json::json;
165
166    use super::*;
167
168    fn call(id: &str, name: &str) -> ToolCall {
169        ToolCall::from_wire(
170            id,
171            ToolFunction::new(ToolName::new(name).unwrap(), json!({})),
172        )
173    }
174
175    #[test]
176    fn a_summary_counts_turns_tokens_and_failed_calls() {
177        let answer = Message::Assistant {
178            id: None,
179            content: vec![
180                AssistantContent::ToolCall(call("c1", "read")),
181                AssistantContent::ToolCall(call("c2", "list")),
182            ],
183        };
184        let results = Message::tool_results(
185            [call("c1", "read"), call("c2", "list")]
186                .into_iter()
187                .map(|call| call.result(vec![ToolResultContent::text("ok")]))
188                .collect(),
189        );
190        let unanswered = Message::Assistant {
191            id: None,
192            content: vec![AssistantContent::ToolCall(call("c3", "read"))],
193        };
194        let events = [
195            json!({"kind":"review","backend":"openai","model":"m","at":"2026-10-06T01:00:00Z"}),
196            json!({"kind":"attempt","turn":1,"attempt":1,"usage":{},"error":"busy"}),
197            json!({
198                "kind":"attempt",
199                "turn":1,
200                "attempt":2,
201                "usage":{"inputTokens":10,"outputTokens":4,"cacheReadTokens":2},
202            }),
203            json!({"kind":"message","turn":1,"message":answer}),
204            json!({"kind":"message","turn":2,"message":results,"isError":[true,false]}),
205            json!({
206                "kind":"attempt",
207                "turn":2,
208                "attempt":1,
209                "usage":{"inputTokens":20,"outputTokens":6},
210            }),
211            json!({"kind":"end","result":{"verdict":"GREEN"}}),
212            json!({"kind":"send","send":1}),
213            json!({
214                "kind":"attempt",
215                "send":1,
216                "turn":1,
217                "attempt":1,
218                "usage":{"inputTokens":30,"outputTokens":1,"reasoningTokens":1},
219            }),
220            json!({"kind":"message","send":1,"turn":1,"message":unanswered}),
221            json!({"kind":"answer","send":1,"error":"stopped","at":"2026-10-06T01:00:02.5Z"}),
222        ];
223        let root = crate::test_os::tempdir();
224        let path = root.path().join("session.jsonl");
225        std::fs::write(
226            &path,
227            events
228                .iter()
229                .map(serde_json::Value::to_string)
230                .collect::<Vec<_>>()
231                .join("\n"),
232        )
233        .unwrap();
234        let summary = Summary::new(&Conversation::load(&path).unwrap().unwrap());
235        assert_eq!(
236            summary.backend,
237            Some(crate::config::Provider::Openai.into())
238        );
239        assert_eq!(
240            summary.duration_ms,
241            Some(std::time::Duration::from_millis(2500))
242        );
243        assert_eq!(summary.follow_ups, 1);
244        let turns: Vec<_> = summary
245            .turns
246            .iter()
247            .map(|turn| (turn.follow_up, turn.turn, turn.attempts))
248            .collect();
249        assert_eq!(turns, [(None, 1, 2), (None, 2, 1), (Some(1), 1, 1)]);
250        assert_eq!(
251            json!(summary.tokens),
252            json!({"inputTokens":60,"outputTokens":11,"cacheReadTokens":2,"reasoningTokens":1})
253        );
254        assert_eq!(
255            json!(summary.tool_calls),
256            json!({"list":{"calls":1,"failed":0},"read":{"calls":2,"failed":2}})
257        );
258        assert_eq!(
259            tokens_text(&summary.tokens).unwrap(),
260            "input 60 · output 11 · cache read 2 · reasoning 1"
261        );
262    }
263}