1pub mod claude;
7pub mod codex;
8
9use crate::model::{Activity, Harness, TokenUsage, ToolSpan};
10use std::collections::VecDeque;
11use std::path::{Path, PathBuf};
12use std::time::SystemTime;
13
14#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
23pub struct ParseHealth {
24 pub billable_messages: u64,
26 pub usage_records: u64,
29 pub empty_usage_records: u64,
32}
33
34impl ParseHealth {
35 const MIN_EVIDENCE: u64 = 3;
38
39 pub fn fields_unrecognised(&self) -> bool {
46 self.billable_messages >= Self::MIN_EVIDENCE && self.usage_records == self.empty_usage_records
47 }
48}
49
50#[derive(Debug, Clone, Default)]
51pub struct SessionSummary {
52 pub harness: Option<Harness>,
53 pub session_id: Option<String>,
54 pub cwd: Option<PathBuf>,
55 pub model: Option<String>,
56 pub harness_version: Option<String>,
57 pub usage: TokenUsage,
58 pub cost_usd: f64,
59 pub unpriced_tokens: u64,
60 pub turns: u64,
61 pub subagent_turns: u64,
62 pub tool_calls: u64,
63 pub spans: SpanLog,
64 pub health: ParseHealth,
65 pub activity: Activity,
66 pub started_at: Option<SystemTime>,
67 pub last_activity: Option<SystemTime>,
68}
69
70pub const MAX_SPANS: usize = 128;
75
76#[derive(Debug, Clone)]
83pub struct SpanLog {
84 spans: VecDeque<ToolSpan>,
85 cap: usize,
86}
87
88impl Default for SpanLog {
89 fn default() -> Self {
90 SpanLog { spans: VecDeque::new(), cap: MAX_SPANS }
91 }
92}
93
94impl SpanLog {
95 pub fn unbounded() -> Self {
99 SpanLog { spans: VecDeque::new(), cap: usize::MAX }
100 }
101
102 pub fn open(&mut self, id: String, name: String, at: SystemTime, sidechain: bool) {
105 if id.is_empty() || self.spans.iter().any(|s| s.is_open() && s.id == id) {
106 return;
107 }
108 if self.spans.len() >= self.cap {
109 self.spans.pop_front();
110 }
111 self.spans.push_back(ToolSpan { id, name, started_at: at, duration_ms: None, sidechain, error: false });
112 }
113
114 pub fn close(&mut self, id: &str, at: SystemTime, error: bool) {
117 let Some(s) = self.spans.iter_mut().rev().find(|s| s.is_open() && s.id == id) else { return };
118 s.duration_ms = Some(at.duration_since(s.started_at).map(|d| d.as_millis() as u64).unwrap_or(0));
119 s.error = error;
120 }
121
122 pub fn len(&self) -> usize {
123 self.spans.len()
124 }
125
126 pub fn is_empty(&self) -> bool {
127 self.spans.is_empty()
128 }
129
130 pub fn iter(&self) -> impl DoubleEndedIterator<Item = &ToolSpan> + ExactSizeIterator {
133 self.spans.iter()
134 }
135
136 pub fn to_vec(&self) -> Vec<ToolSpan> {
137 self.spans.iter().cloned().collect()
138 }
139
140 pub fn merged<'a>(logs: impl IntoIterator<Item = &'a SpanLog>, cap: usize) -> SpanLog {
144 let mut spans: Vec<ToolSpan> = logs.into_iter().flat_map(|l| l.spans.iter().cloned()).collect();
145 spans.sort_by_key(|s| s.started_at);
146 if spans.len() > cap {
147 spans.drain(..spans.len() - cap);
148 }
149 SpanLog { spans: spans.into(), cap }
150 }
151
152 pub fn cap(&self) -> usize {
153 self.cap
154 }
155}
156
157#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
159pub enum SpanRetention {
160 #[default]
162 Recent,
163 All,
167}
168
169impl SpanRetention {
170 pub(crate) fn log(self) -> SpanLog {
171 match self {
172 SpanRetention::Recent => SpanLog::default(),
173 SpanRetention::All => SpanLog::unbounded(),
174 }
175 }
176}
177
178pub trait SessionTracker {
179 fn refresh(&mut self) -> anyhow::Result<bool>;
182 fn summary(&self) -> &SessionSummary;
183 fn path(&self) -> &Path;
184
185 fn refresh_all(&mut self) -> anyhow::Result<()> {
189 while self.refresh()? {}
190 Ok(())
191 }
192}
193
194pub fn detect(path: &Path) -> Option<Harness> {
198 use std::io::{BufRead, BufReader};
199 let f = std::fs::File::open(path).ok()?;
200 for line in BufReader::new(f).lines().map_while(Result::ok).take(5) {
201 let Ok(v) = serde_json::from_str::<serde_json::Value>(&line) else { continue };
202 if v.get("type").and_then(serde_json::Value::as_str) == Some("session_meta") {
203 return Some(Harness::Codex);
204 }
205 if v.get("sessionId").is_some() || v.get("parentUuid").is_some() {
206 return Some(Harness::Claude);
207 }
208 }
209 None
210}
211
212pub fn open_transcript(path: &Path, harness: Harness, spans: SpanRetention) -> Box<dyn SessionTracker> {
214 match harness {
215 Harness::Codex => Box::new(codex::CodexTranscript::new(path).with_spans(spans)),
216 _ => Box::new(claude::ClaudeTranscript::new(path).with_spans(spans)),
217 }
218}
219
220pub const REFRESH_BUDGET_BYTES: usize = 8 * 1024 * 1024;
223
224pub fn parse_rfc3339_utc(s: &str) -> Option<SystemTime> {
228 let s = s.strip_suffix('Z')?;
229 let (date, time) = s.split_once('T')?;
230 let mut d = date.split('-');
231 let (y, mo, da) = (d.next()?.parse::<i64>().ok()?, d.next()?.parse::<u32>().ok()?, d.next()?.parse::<u32>().ok()?);
232 let mut t = time.split(':');
233 let (h, mi) = (t.next()?.parse::<u64>().ok()?, t.next()?.parse::<u64>().ok()?);
234 let sec_str = t.next()?;
235 let (sec, frac) = match sec_str.split_once('.') {
236 Some((s, f)) => (s.parse::<u64>().ok()?, f),
237 None => (sec_str.parse::<u64>().ok()?, ""),
238 };
239 let nanos: u32 = if frac.is_empty() {
240 0
241 } else {
242 let mut f = frac.to_string();
243 f.truncate(9);
244 while f.len() < 9 {
245 f.push('0');
246 }
247 f.parse().ok()?
248 };
249 let days = days_from_civil(y, mo, da);
250 let secs = days * 86_400 + (h * 3600 + mi * 60 + sec) as i64;
251 if secs < 0 {
252 return None;
253 }
254 Some(SystemTime::UNIX_EPOCH + std::time::Duration::new(secs as u64, nanos))
255}
256
257fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
259 let y = if m <= 2 { y - 1 } else { y };
260 let era = if y >= 0 { y } else { y - 399 } / 400;
261 let yoe = y - era * 400;
262 let mp = (m as i64 + 9) % 12;
263 let doy = (153 * mp + 2) / 5 + d as i64 - 1;
264 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
265 era * 146_097 + doe - 719_468
266}
267
268#[cfg(test)]
269mod tests {
270 use super::*;
271 use std::time::Duration;
272
273 fn at(secs: u64) -> SystemTime {
274 SystemTime::UNIX_EPOCH + Duration::from_secs(secs)
275 }
276
277 #[test]
278 fn pairs_spans_by_id_out_of_order() {
279 let mut log = SpanLog::default();
280 log.open("a".into(), "Bash".into(), at(10), false);
281 log.open("b".into(), "Read".into(), at(11), true);
282 log.open("a".into(), "Bash".into(), at(10), false);
284 log.close("b", at(12), false);
286 log.close("a", at(14), true);
287 log.close("zzz", at(15), false);
289 let v = log.to_vec();
290 assert_eq!(v.len(), 2);
291 assert_eq!(v[0].name, "Bash");
292 assert_eq!(v[0].duration_ms, Some(4_000));
293 assert!(v[0].error);
294 assert_eq!(v[1].duration_ms, Some(1_000));
295 assert!(v[1].sidechain);
296 assert!(!v[1].error);
297 }
298
299 #[test]
300 fn keeps_the_newest_spans_and_reports_open_ones() {
301 let mut log = SpanLog::default();
302 for i in 0..(MAX_SPANS + 10) {
303 log.open(format!("id{i}"), "T".into(), at(i as u64), false);
304 log.close(&format!("id{i}"), at(i as u64), false);
305 }
306 assert_eq!(log.len(), MAX_SPANS);
307 assert_eq!(log.iter().next().unwrap().id, "id10");
308 log.open("live".into(), "Bash".into(), at(500), false);
309 let last = log.to_vec().pop().unwrap();
310 assert!(last.is_open());
311 assert_eq!(last.elapsed_ms(at(503)), 3_000);
312 }
313
314 #[test]
315 fn unbounded_log_keeps_everything() {
316 let mut log = SpanLog::unbounded();
317 for i in 0..(MAX_SPANS * 3) {
318 log.open(format!("id{i}"), "T".into(), at(i as u64), false);
319 log.close(&format!("id{i}"), at(i as u64 + 1), false);
320 }
321 assert_eq!(log.len(), MAX_SPANS * 3);
322 assert_eq!(log.iter().next().unwrap().id, "id0");
323 assert_eq!(SpanRetention::default(), SpanRetention::Recent);
324 }
325
326 #[test]
327 fn detects_the_harness_from_the_first_lines() {
328 let dir = std::env::temp_dir().join(format!("agent-top-detect-{}", std::process::id()));
329 std::fs::create_dir_all(&dir).unwrap();
330 let codex = dir.join("rollout.jsonl");
331 std::fs::write(&codex, "{\"type\":\"session_meta\",\"payload\":{\"id\":\"x\"}}\n").unwrap();
332 let claude = dir.join("s.jsonl");
333 std::fs::write(&claude, "{\"type\":\"summary\",\"leafUuid\":\"u\"}\n{\"type\":\"user\",\"sessionId\":\"abc\"}\n").unwrap();
335 let other = dir.join("other.jsonl");
336 std::fs::write(&other, "{\"hello\":1}\nnot json\n").unwrap();
337 assert_eq!(detect(&codex), Some(Harness::Codex));
338 assert_eq!(detect(&claude), Some(Harness::Claude));
339 assert_eq!(detect(&other), None);
340 assert_eq!(detect(&dir.join("missing.jsonl")), None);
341 let _ = std::fs::remove_dir_all(&dir);
342 }
343
344 #[test]
345 fn accuses_the_parser_only_with_enough_evidence() {
346 let h = ParseHealth { billable_messages: 40, usage_records: 40, empty_usage_records: 0 };
348 assert!(!h.fields_unrecognised());
349 let h = ParseHealth { billable_messages: 40, usage_records: 40, empty_usage_records: 39 };
351 assert!(!h.fields_unrecognised());
352 let h = ParseHealth { billable_messages: 40, usage_records: 40, empty_usage_records: 40 };
354 assert!(h.fields_unrecognised());
355 let h = ParseHealth { billable_messages: 40, usage_records: 0, empty_usage_records: 0 };
358 assert!(h.fields_unrecognised());
359 let h = ParseHealth { billable_messages: 2, usage_records: 0, empty_usage_records: 0 };
361 assert!(!h.fields_unrecognised());
362 assert!(!ParseHealth::default().fields_unrecognised());
364 }
365
366 #[test]
367 fn parses_timestamps() {
368 let t = parse_rfc3339_utc("1970-01-02T00:00:00.000Z").unwrap();
369 assert_eq!(t, SystemTime::UNIX_EPOCH + Duration::from_secs(86_400));
370 let t = parse_rfc3339_utc("2026-09-03T07:15:34.5Z").unwrap();
371 let secs = t.duration_since(SystemTime::UNIX_EPOCH).unwrap();
372 assert_eq!(secs.as_secs(), 1_788_419_734);
373 assert_eq!(secs.subsec_millis(), 500);
374 assert!(parse_rfc3339_utc("nope").is_none());
375 }
376}