1use serde_json::{Map, Value, json};
5use session_file::SessionManager;
6
7fn str_of<'a>(value: &'a Value, key: &str) -> Option<&'a str> {
8 value.get(key).and_then(Value::as_str)
9}
10
11pub fn entries(manager: &SessionManager) -> Vec<Value> {
13 manager.entries().into_iter().cloned().collect()
14}
15
16pub fn messages(manager: &SessionManager) -> Vec<Value> {
18 manager.build_session_context().messages
19}
20
21pub fn tree(manager: &SessionManager) -> Value {
23 let tree = manager.tree();
24 fn node(tree: &session_file::SessionTree<'_>, index: usize) -> Value {
25 let n = &tree.nodes[index];
26 let mut out = Map::new();
27 out.insert("entry".into(), n.entry.clone());
28 out.insert(
29 "children".into(),
30 Value::Array(n.children.iter().map(|c| node(tree, *c)).collect()),
31 );
32 if let Some(label) = n.label {
33 out.insert("label".into(), label.clone());
34 }
35 if let Some(timestamp) = n.label_timestamp {
36 out.insert("labelTimestamp".into(), timestamp.clone());
37 }
38 Value::Object(out)
39 }
40 Value::Array(tree.roots.iter().map(|r| node(&tree, *r)).collect())
41}
42
43pub fn last_assistant_text(manager: &SessionManager) -> Option<String> {
45 let messages = messages(manager);
46 let last = messages.iter().rev().find(|m| {
47 str_of(m, "role") == Some("assistant")
48 && !(str_of(m, "stopReason") == Some("aborted") && m["content"].as_array().is_none_or(Vec::is_empty))
49 })?;
50 Some(
51 last["content"]
52 .as_array()
53 .map(|blocks| {
54 blocks
55 .iter()
56 .filter(|b| b["type"] == "text")
57 .filter_map(|b| b["text"].as_str())
58 .collect()
59 })
60 .unwrap_or_default(),
61 )
62}
63
64pub fn fork_messages(manager: &SessionManager) -> Vec<Value> {
66 manager
67 .entries()
68 .into_iter()
69 .filter(|e| str_of(e, "type") == Some("message") && str_of(&e["message"], "role") == Some("user"))
70 .filter_map(|e| {
71 let text = protocol::pi_message::text(&e["message"]);
72 (!text.is_empty()).then(|| json!({"entryId": e["id"], "text": text}))
73 })
74 .collect()
75}
76
77#[derive(Default)]
78struct Totals {
79 input: f64,
80 output: f64,
81 cache_read: f64,
82 cache_write: f64,
83 cost: f64,
84}
85
86impl Totals {
87 fn add(&mut self, usage: &Value) {
89 let n = |v: &Value| v.as_f64().unwrap_or(0.0);
90 self.input += n(&usage["input"]);
91 self.output += n(&usage["output"]);
92 self.cache_read += n(&usage["cacheRead"]);
93 self.cache_write += n(&usage["cacheWrite"]);
94 self.cost += n(&usage["cost"]["total"]);
95 }
96}
97
98pub fn stats(manager: &SessionManager, session_file: Option<&str>, session_id: &str, context_window: u64) -> Value {
100 let (mut users, mut assistants, mut tool_results, mut total, mut tool_calls) = (0, 0, 0, 0, 0);
101 let mut totals = Totals::default();
102 for entry in manager.entries() {
103 match str_of(entry, "type") {
104 Some("usage") => totals.add(&entry["usage"]),
105 Some("branch_summary" | "compaction") if entry.get("usage").is_some_and(|u| !u.is_null()) => {
106 totals.add(&entry["usage"])
107 }
108 _ => {}
109 }
110 if str_of(entry, "type") != Some("message") {
111 continue;
112 }
113 total += 1;
114 let message = &entry["message"];
115 match str_of(message, "role") {
116 Some("user") => users += 1,
117 Some("toolResult") => {
118 tool_results += 1;
119 if let Some(usage) = message.get("usage").filter(|u| !u.is_null()) {
120 totals.add(usage);
121 }
122 }
123 Some("assistant") => {
124 assistants += 1;
125 tool_calls += message["content"]
126 .as_array()
127 .map_or(0, |c| c.iter().filter(|b| b["type"] == "toolCall").count());
128 totals.add(&message["usage"]);
129 }
130 _ => {}
131 }
132 }
133 let mut out = Map::new();
134 if let Some(file) = session_file {
135 out.insert("sessionFile".into(), file.into());
136 }
137 out.insert("sessionId".into(), session_id.into());
138 out.insert("userMessages".into(), users.into());
139 out.insert("assistantMessages".into(), assistants.into());
140 out.insert("toolCalls".into(), tool_calls.into());
141 out.insert("toolResults".into(), tool_results.into());
142 out.insert("totalMessages".into(), total.into());
143 out.insert(
144 "tokens".into(),
145 json!({
146 "input": jsrt::json::number(totals.input), "output": jsrt::json::number(totals.output),
147 "cacheRead": jsrt::json::number(totals.cache_read), "cacheWrite": jsrt::json::number(totals.cache_write),
148 "total": jsrt::json::number(totals.input + totals.output + totals.cache_read + totals.cache_write),
149 }),
150 );
151 out.insert("cost".into(), jsrt::json::number(totals.cost));
152 if let Some(usage) = context_usage(manager, context_window) {
153 out.insert("contextUsage".into(), usage);
154 }
155 Value::Object(out)
156}
157
158fn context_usage(manager: &SessionManager, context_window: u64) -> Option<Value> {
160 if context_window == 0 {
161 return None;
162 }
163 let projection = manager.build_session_projection();
164 let branch: Vec<Value> = manager.branch_entries(None).into_iter().cloned().collect();
165 if let Some(compaction) = branch.iter().rposition(|e| str_of(e, "type") == Some("compaction")) {
166 let projected_assistants: Vec<&Value> = projection
167 .entries
168 .iter()
169 .filter(|entry| {
170 entry.messages.iter().any(|m| {
171 str_of(m, "role") == Some("assistant")
172 && !matches!(str_of(m, "stopReason"), Some("aborted" | "error"))
173 && compaction::calculate_context_tokens(&m["usage"]) > 0
174 })
175 })
176 .filter_map(|entry| entry.source.get("id"))
177 .collect();
178 let has_usage_after = branch[compaction + 1..]
179 .iter()
180 .any(|e| e.get("id").is_some_and(|id| projected_assistants.contains(&id)));
181 if !has_usage_after {
182 return Some(json!({"tokens": null, "contextWindow": context_window, "percent": null}));
183 }
184 }
185 let estimate = compaction::estimate_projected_context_tokens(&projection, &branch);
186 let percent = estimate.tokens as f64 / context_window as f64 * 100.0;
187 Some(json!({"tokens": estimate.tokens, "contextWindow": context_window, "percent": jsrt::json::number(percent)}))
188}