1pub mod claude;
7pub mod codex;
8
9use crate::model::{Activity, Harness, SpanKind, 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 web_searches: u64,
65 pub spans: SpanLog,
66 pub health: ParseHealth,
67 pub activity: Activity,
68 pub started_at: Option<SystemTime>,
69 pub last_activity: Option<SystemTime>,
70}
71
72pub const MAX_SPANS: usize = 256;
80
81#[derive(Debug, Clone)]
88pub struct SpanLog {
89 spans: VecDeque<ToolSpan>,
90 cap: usize,
91}
92
93impl Default for SpanLog {
94 fn default() -> Self {
95 SpanLog { spans: VecDeque::new(), cap: MAX_SPANS }
96 }
97}
98
99impl SpanLog {
100 pub fn unbounded() -> Self {
104 SpanLog { spans: VecDeque::new(), cap: usize::MAX }
105 }
106
107 pub fn open(&mut self, id: String, name: String, at: SystemTime, sidechain: bool) {
110 self.open_kind(id, name, at, sidechain, SpanKind::Tool);
111 }
112
113 pub fn open_kind(&mut self, id: String, name: String, at: SystemTime, sidechain: bool, kind: SpanKind) {
115 if id.is_empty() || self.spans.iter().any(|s| s.is_open() && s.id == id) {
116 return;
117 }
118 if self.spans.len() >= self.cap {
119 self.spans.pop_front();
120 }
121 self.spans.push_back(ToolSpan { id, name, started_at: at, duration_ms: None, sidechain, error: false, kind });
122 }
123
124 pub fn end_at(&mut self, id: &str, at: SystemTime) {
128 let Some(s) = self.spans.iter_mut().rev().find(|s| s.id == id) else { return };
129 s.duration_ms = Some(at.duration_since(s.started_at).map(|d| d.as_millis() as u64).unwrap_or(0));
130 }
131
132 pub fn open_of_kind(&self, kind: SpanKind) -> Option<&ToolSpan> {
134 self.spans.iter().rev().find(|s| s.is_open() && s.kind == kind)
135 }
136
137 pub fn discard_open(&mut self, id: &str) {
141 if let Some(i) = self.spans.iter().rposition(|s| s.is_open() && s.id == id) {
142 self.spans.remove(i);
143 }
144 }
145
146 pub fn close(&mut self, id: &str, at: SystemTime, error: bool) {
149 let Some(s) = self.spans.iter_mut().rev().find(|s| s.is_open() && s.id == id) else { return };
150 s.duration_ms = Some(at.duration_since(s.started_at).map(|d| d.as_millis() as u64).unwrap_or(0));
151 s.error = error;
152 }
153
154 pub fn len(&self) -> usize {
155 self.spans.len()
156 }
157
158 pub fn is_empty(&self) -> bool {
159 self.spans.is_empty()
160 }
161
162 pub fn iter(&self) -> impl DoubleEndedIterator<Item = &ToolSpan> + ExactSizeIterator {
165 self.spans.iter()
166 }
167
168 pub fn to_vec(&self) -> Vec<ToolSpan> {
169 self.spans.iter().cloned().collect()
170 }
171
172 pub fn merged<'a>(logs: impl IntoIterator<Item = &'a SpanLog>, cap: usize) -> SpanLog {
176 let mut spans: Vec<ToolSpan> = logs.into_iter().flat_map(|l| l.spans.iter().cloned()).collect();
177 spans.sort_by_key(|s| s.started_at);
178 if spans.len() > cap {
179 spans.drain(..spans.len() - cap);
180 }
181 SpanLog { spans: spans.into(), cap }
182 }
183
184 pub fn cap(&self) -> usize {
185 self.cap
186 }
187}
188
189#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
191pub enum SpanRetention {
192 #[default]
194 Recent,
195 All,
199}
200
201impl SpanRetention {
202 pub(crate) fn log(self) -> SpanLog {
203 match self {
204 SpanRetention::Recent => SpanLog::default(),
205 SpanRetention::All => SpanLog::unbounded(),
206 }
207 }
208}
209
210pub trait SessionTracker {
211 fn refresh(&mut self) -> anyhow::Result<bool>;
214 fn summary(&self) -> &SessionSummary;
215 fn path(&self) -> &Path;
216
217 fn refresh_all(&mut self) -> anyhow::Result<()> {
221 while self.refresh()? {}
222 Ok(())
223 }
224}
225
226pub fn detect(path: &Path) -> Option<Harness> {
230 use std::io::{BufRead, BufReader};
231 let f = std::fs::File::open(path).ok()?;
232 for line in BufReader::new(f).lines().map_while(Result::ok).take(5) {
233 let Ok(v) = serde_json::from_str::<serde_json::Value>(&line) else { continue };
234 if v.get("type").and_then(serde_json::Value::as_str) == Some("session_meta") {
235 return Some(Harness::Codex);
236 }
237 if v.get("sessionId").is_some() || v.get("parentUuid").is_some() {
238 return Some(Harness::Claude);
239 }
240 }
241 None
242}
243
244pub fn open_transcript(path: &Path, harness: Harness, spans: SpanRetention) -> Box<dyn SessionTracker> {
246 match harness {
247 Harness::Codex => Box::new(codex::CodexTranscript::new(path).with_spans(spans)),
248 _ => Box::new(claude::ClaudeTranscript::new(path).with_spans(spans)),
249 }
250}
251
252pub const REFRESH_BUDGET_BYTES: usize = 8 * 1024 * 1024;
255
256pub fn parse_rfc3339_utc(s: &str) -> Option<SystemTime> {
260 let s = s.strip_suffix('Z')?;
261 let (date, time) = s.split_once('T')?;
262 let mut d = date.split('-');
263 let (y, mo, da) = (d.next()?.parse::<i64>().ok()?, d.next()?.parse::<u32>().ok()?, d.next()?.parse::<u32>().ok()?);
264 let mut t = time.split(':');
265 let (h, mi) = (t.next()?.parse::<u64>().ok()?, t.next()?.parse::<u64>().ok()?);
266 let sec_str = t.next()?;
267 let (sec, frac) = match sec_str.split_once('.') {
268 Some((s, f)) => (s.parse::<u64>().ok()?, f),
269 None => (sec_str.parse::<u64>().ok()?, ""),
270 };
271 let nanos: u32 = if frac.is_empty() {
272 0
273 } else {
274 let mut f = frac.to_string();
275 f.truncate(9);
276 while f.len() < 9 {
277 f.push('0');
278 }
279 f.parse().ok()?
280 };
281 let days = days_from_civil(y, mo, da);
282 let secs = days * 86_400 + (h * 3600 + mi * 60 + sec) as i64;
283 if secs < 0 {
284 return None;
285 }
286 Some(SystemTime::UNIX_EPOCH + std::time::Duration::new(secs as u64, nanos))
287}
288
289fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
291 let y = if m <= 2 { y - 1 } else { y };
292 let era = if y >= 0 { y } else { y - 399 } / 400;
293 let yoe = y - era * 400;
294 let mp = (m as i64 + 9) % 12;
295 let doy = (153 * mp + 2) / 5 + d as i64 - 1;
296 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
297 era * 146_097 + doe - 719_468
298}
299
300#[cfg(test)]
301mod tests {
302 use super::*;
303 use std::time::Duration;
304
305 fn at(secs: u64) -> SystemTime {
306 SystemTime::UNIX_EPOCH + Duration::from_secs(secs)
307 }
308
309 #[test]
310 fn pairs_spans_by_id_out_of_order() {
311 let mut log = SpanLog::default();
312 log.open("a".into(), "Bash".into(), at(10), false);
313 log.open("b".into(), "Read".into(), at(11), true);
314 log.open("a".into(), "Bash".into(), at(10), false);
316 log.close("b", at(12), false);
318 log.close("a", at(14), true);
319 log.close("zzz", at(15), false);
321 let v = log.to_vec();
322 assert_eq!(v.len(), 2);
323 assert_eq!(v[0].name, "Bash");
324 assert_eq!(v[0].duration_ms, Some(4_000));
325 assert!(v[0].error);
326 assert_eq!(v[1].duration_ms, Some(1_000));
327 assert!(v[1].sidechain);
328 assert!(!v[1].error);
329 }
330
331 #[test]
332 fn keeps_the_newest_spans_and_reports_open_ones() {
333 let mut log = SpanLog::default();
334 for i in 0..(MAX_SPANS + 10) {
335 log.open(format!("id{i}"), "T".into(), at(i as u64), false);
336 log.close(&format!("id{i}"), at(i as u64), false);
337 }
338 assert_eq!(log.len(), MAX_SPANS);
339 assert_eq!(log.iter().next().unwrap().id, "id10");
340 log.open("live".into(), "Bash".into(), at(500), false);
341 let last = log.to_vec().pop().unwrap();
342 assert!(last.is_open());
343 assert_eq!(last.elapsed_ms(at(503)), 3_000);
344 }
345
346 #[test]
347 fn end_at_moves_the_end_of_any_kind_of_span() {
348 let mut log = SpanLog::default();
349 log.open_kind("inference:1".into(), "inference".into(), at(10), false, SpanKind::Inference);
350 assert!(log.open_of_kind(SpanKind::Inference).is_some());
351 assert!(log.open_of_kind(SpanKind::Turn).is_none());
352 log.end_at("inference:1", at(11));
354 log.end_at("inference:1", at(13));
355 log.end_at("nope", at(99));
356 let v = log.to_vec();
357 assert_eq!(v[0].duration_ms, Some(3_000));
358 assert_eq!(v[0].kind, SpanKind::Inference);
359 assert!(log.open_of_kind(SpanKind::Inference).is_none());
360 log.discard_open("inference:1");
362 assert_eq!(log.len(), 1);
363 log.open_kind("inference:2".into(), "inference".into(), at(20), false, SpanKind::Inference);
364 log.discard_open("inference:2");
365 assert_eq!(log.len(), 1);
366 }
367
368 #[test]
369 fn unbounded_log_keeps_everything() {
370 let mut log = SpanLog::unbounded();
371 for i in 0..(MAX_SPANS * 3) {
372 log.open(format!("id{i}"), "T".into(), at(i as u64), false);
373 log.close(&format!("id{i}"), at(i as u64 + 1), false);
374 }
375 assert_eq!(log.len(), MAX_SPANS * 3);
376 assert_eq!(log.iter().next().unwrap().id, "id0");
377 assert_eq!(SpanRetention::default(), SpanRetention::Recent);
378 }
379
380 #[test]
381 fn detects_the_harness_from_the_first_lines() {
382 let dir = std::env::temp_dir().join(format!("agent-top-detect-{}", std::process::id()));
383 std::fs::create_dir_all(&dir).unwrap();
384 let codex = dir.join("rollout.jsonl");
385 std::fs::write(&codex, "{\"type\":\"session_meta\",\"payload\":{\"id\":\"x\"}}\n").unwrap();
386 let claude = dir.join("s.jsonl");
387 std::fs::write(&claude, "{\"type\":\"summary\",\"leafUuid\":\"u\"}\n{\"type\":\"user\",\"sessionId\":\"abc\"}\n").unwrap();
389 let other = dir.join("other.jsonl");
390 std::fs::write(&other, "{\"hello\":1}\nnot json\n").unwrap();
391 assert_eq!(detect(&codex), Some(Harness::Codex));
392 assert_eq!(detect(&claude), Some(Harness::Claude));
393 assert_eq!(detect(&other), None);
394 assert_eq!(detect(&dir.join("missing.jsonl")), None);
395 let _ = std::fs::remove_dir_all(&dir);
396 }
397
398 #[test]
399 fn accuses_the_parser_only_with_enough_evidence() {
400 let h = ParseHealth { billable_messages: 40, usage_records: 40, empty_usage_records: 0 };
402 assert!(!h.fields_unrecognised());
403 let h = ParseHealth { billable_messages: 40, usage_records: 40, empty_usage_records: 39 };
405 assert!(!h.fields_unrecognised());
406 let h = ParseHealth { billable_messages: 40, usage_records: 40, empty_usage_records: 40 };
408 assert!(h.fields_unrecognised());
409 let h = ParseHealth { billable_messages: 40, usage_records: 0, empty_usage_records: 0 };
412 assert!(h.fields_unrecognised());
413 let h = ParseHealth { billable_messages: 2, usage_records: 0, empty_usage_records: 0 };
415 assert!(!h.fields_unrecognised());
416 assert!(!ParseHealth::default().fields_unrecognised());
418 }
419
420 #[test]
421 fn parses_timestamps() {
422 let t = parse_rfc3339_utc("1970-01-02T00:00:00.000Z").unwrap();
423 assert_eq!(t, SystemTime::UNIX_EPOCH + Duration::from_secs(86_400));
424 let t = parse_rfc3339_utc("2026-09-03T07:15:34.5Z").unwrap();
425 let secs = t.duration_since(SystemTime::UNIX_EPOCH).unwrap();
426 assert_eq!(secs.as_secs(), 1_788_419_734);
427 assert_eq!(secs.subsec_millis(), 500);
428 assert!(parse_rfc3339_utc("nope").is_none());
429 }
430}