1pub mod claude;
7pub mod codex;
8pub mod gemini;
9
10use crate::model::{Activity, Attribution, CostBreakdown, Harness, ProcNode, SpanKind, TokenUsage, ToolSpan};
11use crate::process::RawProc;
12use std::collections::{BTreeMap, HashSet, VecDeque};
13use std::path::{Path, PathBuf};
14use std::time::{Duration, SystemTime};
15
16#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
25pub struct ParseHealth {
26 pub billable_messages: u64,
28 pub usage_records: u64,
31 pub empty_usage_records: u64,
34}
35
36impl ParseHealth {
37 const MIN_EVIDENCE: u64 = 3;
40
41 pub fn fields_unrecognised(&self) -> bool {
48 self.billable_messages >= Self::MIN_EVIDENCE && self.usage_records == self.empty_usage_records
49 }
50}
51
52#[derive(Debug, Clone, Default)]
53pub struct SessionSummary {
54 pub harness: Option<Harness>,
55 pub session_id: Option<String>,
56 pub cwd: Option<PathBuf>,
57 pub model: Option<String>,
58 pub harness_version: Option<String>,
59 pub usage: TokenUsage,
60 pub cost_usd: f64,
61 pub cost_breakdown: CostBreakdown,
63 pub unpriced_tokens: u64,
64 pub turns: u64,
65 pub subagent_turns: u64,
66 pub tool_calls: u64,
67 pub web_searches: u64,
69 pub spans: SpanLog,
70 pub mcp: BTreeMap<String, McpUsage>,
72 pub health: ParseHealth,
73 pub activity: Activity,
74 pub started_at: Option<SystemTime>,
75 pub last_activity: Option<SystemTime>,
76}
77
78#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
81pub struct McpUsage {
82 pub calls: u64,
83 pub errors: u64,
84 pub last_call: Option<SystemTime>,
85}
86
87impl McpUsage {
88 pub fn add(&mut self, o: &McpUsage) {
89 self.calls += o.calls;
90 self.errors += o.errors;
91 self.last_call = self.last_call.max(o.last_call);
92 }
93}
94
95pub fn mcp_server_of(tool_name: &str) -> Option<&str> {
100 let rest = tool_name.strip_prefix("mcp__")?;
101 let server = match rest.rfind("__") {
102 Some(i) => &rest[..i],
103 None => rest,
104 };
105 if server.is_empty() { None } else { Some(server) }
106}
107
108pub const MAX_SPANS: usize = 256;
116
117#[derive(Debug, Clone)]
124pub struct SpanLog {
125 spans: VecDeque<ToolSpan>,
126 cap: usize,
127}
128
129impl Default for SpanLog {
130 fn default() -> Self {
131 SpanLog { spans: VecDeque::new(), cap: MAX_SPANS }
132 }
133}
134
135impl SpanLog {
136 pub fn unbounded() -> Self {
140 SpanLog { spans: VecDeque::new(), cap: usize::MAX }
141 }
142
143 pub fn open(&mut self, id: String, name: String, at: SystemTime, sidechain: bool) {
146 self.open_kind(id, name, at, sidechain, SpanKind::Tool);
147 }
148
149 pub fn open_kind(&mut self, id: String, name: String, at: SystemTime, sidechain: bool, kind: SpanKind) {
151 if id.is_empty() || self.spans.iter().any(|s| s.is_open() && s.id == id) {
152 return;
153 }
154 if self.spans.len() >= self.cap {
155 self.spans.pop_front();
156 }
157 self.spans.push_back(ToolSpan { id, name, started_at: at, duration_ms: None, sidechain, error: false, kind });
158 }
159
160 pub fn end_at(&mut self, id: &str, at: SystemTime) {
164 let Some(s) = self.spans.iter_mut().rev().find(|s| s.id == id) else { return };
165 s.duration_ms = Some(at.duration_since(s.started_at).map(|d| d.as_millis() as u64).unwrap_or(0));
166 }
167
168 pub fn open_of_kind(&self, kind: SpanKind) -> Option<&ToolSpan> {
170 self.spans.iter().rev().find(|s| s.is_open() && s.kind == kind)
171 }
172
173 pub fn discard_open(&mut self, id: &str) {
177 if let Some(i) = self.spans.iter().rposition(|s| s.is_open() && s.id == id) {
178 self.spans.remove(i);
179 }
180 }
181
182 pub fn close(&mut self, id: &str, at: SystemTime, error: bool) {
185 let Some(s) = self.spans.iter_mut().rev().find(|s| s.is_open() && s.id == id) else { return };
186 s.duration_ms = Some(at.duration_since(s.started_at).map(|d| d.as_millis() as u64).unwrap_or(0));
187 s.error = error;
188 }
189
190 pub fn len(&self) -> usize {
191 self.spans.len()
192 }
193
194 pub fn is_empty(&self) -> bool {
195 self.spans.is_empty()
196 }
197
198 pub fn iter(&self) -> impl DoubleEndedIterator<Item = &ToolSpan> + ExactSizeIterator {
201 self.spans.iter()
202 }
203
204 pub fn to_vec(&self) -> Vec<ToolSpan> {
205 self.spans.iter().cloned().collect()
206 }
207
208 pub fn merged<'a>(logs: impl IntoIterator<Item = &'a SpanLog>, cap: usize) -> SpanLog {
212 let mut spans: Vec<ToolSpan> = logs.into_iter().flat_map(|l| l.spans.iter().cloned()).collect();
213 spans.sort_by_key(|s| s.started_at);
214 if spans.len() > cap {
215 spans.drain(..spans.len() - cap);
216 }
217 SpanLog { spans: spans.into(), cap }
218 }
219
220 pub fn cap(&self) -> usize {
221 self.cap
222 }
223}
224
225#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
227pub enum SpanRetention {
228 #[default]
230 Recent,
231 All,
235}
236
237impl SpanRetention {
238 pub(crate) fn log(self) -> SpanLog {
239 match self {
240 SpanRetention::Recent => SpanLog::default(),
241 SpanRetention::All => SpanLog::unbounded(),
242 }
243 }
244}
245
246pub trait SessionTracker {
247 fn refresh(&mut self) -> anyhow::Result<bool>;
250 fn summary(&self) -> &SessionSummary;
251 fn path(&self) -> &Path;
252
253 fn refresh_all(&mut self) -> anyhow::Result<()> {
257 while self.refresh()? {}
258 Ok(())
259 }
260}
261
262#[derive(Debug, Clone, Default, PartialEq, Eq)]
266pub struct RegistryHints {
267 pub name: Option<String>,
268 pub session_id: Option<String>,
269 pub cwd: Option<PathBuf>,
270 pub version: Option<String>,
271 pub status: Option<String>,
274}
275
276pub struct AttributeContext<'a> {
279 pub cwd: Option<&'a Path>,
280 pub proc_start: SystemTime,
281 pub now: SystemTime,
282 pub attached: &'a HashSet<PathBuf>,
285 pub activity_timeout: Duration,
288}
289
290pub trait HarnessAdapter {
297 fn harness(&self) -> Harness;
298
299 fn rescan(&mut self, since: SystemTime);
302
303 fn prepare(&mut self, _roots: &[&ProcNode]) {}
308
309 fn hints(&self, _pid: u32) -> Option<RegistryHints> {
311 None
312 }
313
314 fn attribute(&self, root: &ProcNode, raw: Option<&RawProc>, ctx: &AttributeContext) -> (Vec<PathBuf>, Attribution);
318
319 fn unowned(&self, attached: &HashSet<PathBuf>) -> Vec<PathBuf>;
321
322 fn open(&self, path: &Path, spans: SpanRetention) -> Box<dyn SessionTracker>;
324
325 fn detect(&self, path: &Path) -> bool;
327
328 fn transcripts(&self) -> Vec<(String, PathBuf)>;
331}
332
333pub fn adapters() -> Vec<Box<dyn HarnessAdapter>> {
337 vec![Box::new(codex::CodexAdapter::default()), Box::new(gemini::GeminiAdapter::default()), Box::new(claude::ClaudeAdapter::default())]
338}
339
340pub fn adapter_for(harness: Harness) -> Option<Box<dyn HarnessAdapter>> {
342 adapters().into_iter().find(|a| a.harness() == harness)
343}
344
345pub fn detect(path: &Path) -> Option<Harness> {
348 adapters().iter().find(|a| a.detect(path)).map(|a| a.harness())
349}
350
351pub fn open_transcript(path: &Path, harness: Harness, spans: SpanRetention) -> Option<Box<dyn SessionTracker>> {
354 adapter_for(harness).map(|a| a.open(path, spans))
355}
356
357pub(crate) fn head_lines(path: &Path) -> Vec<serde_json::Value> {
359 use std::io::{BufRead, BufReader};
360 let Ok(f) = std::fs::File::open(path) else { return Vec::new() };
361 BufReader::new(f).lines().map_while(Result::ok).take(5).filter_map(|l| serde_json::from_str(&l).ok()).collect()
362}
363
364pub const REFRESH_BUDGET_BYTES: usize = 8 * 1024 * 1024;
367
368pub fn parse_rfc3339_utc(s: &str) -> Option<SystemTime> {
372 let s = s.strip_suffix('Z')?;
373 let (date, time) = s.split_once('T')?;
374 let mut d = date.split('-');
375 let (y, mo, da) = (d.next()?.parse::<i64>().ok()?, d.next()?.parse::<u32>().ok()?, d.next()?.parse::<u32>().ok()?);
376 let mut t = time.split(':');
377 let (h, mi) = (t.next()?.parse::<u64>().ok()?, t.next()?.parse::<u64>().ok()?);
378 let sec_str = t.next()?;
379 let (sec, frac) = match sec_str.split_once('.') {
380 Some((s, f)) => (s.parse::<u64>().ok()?, f),
381 None => (sec_str.parse::<u64>().ok()?, ""),
382 };
383 let nanos: u32 = if frac.is_empty() {
384 0
385 } else {
386 let mut f = frac.to_string();
387 f.truncate(9);
388 while f.len() < 9 {
389 f.push('0');
390 }
391 f.parse().ok()?
392 };
393 let days = days_from_civil(y, mo, da);
394 let secs = days * 86_400 + (h * 3600 + mi * 60 + sec) as i64;
395 if secs < 0 {
396 return None;
397 }
398 Some(SystemTime::UNIX_EPOCH + std::time::Duration::new(secs as u64, nanos))
399}
400
401fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
403 let y = if m <= 2 { y - 1 } else { y };
404 let era = if y >= 0 { y } else { y - 399 } / 400;
405 let yoe = y - era * 400;
406 let mp = (m as i64 + 9) % 12;
407 let doy = (153 * mp + 2) / 5 + d as i64 - 1;
408 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
409 era * 146_097 + doe - 719_468
410}
411
412#[cfg(test)]
413mod tests {
414 use super::*;
415 use std::time::Duration;
416
417 fn at(secs: u64) -> SystemTime {
418 SystemTime::UNIX_EPOCH + Duration::from_secs(secs)
419 }
420
421 #[test]
422 fn pairs_spans_by_id_out_of_order() {
423 let mut log = SpanLog::default();
424 log.open("a".into(), "Bash".into(), at(10), false);
425 log.open("b".into(), "Read".into(), at(11), true);
426 log.open("a".into(), "Bash".into(), at(10), false);
428 log.close("b", at(12), false);
430 log.close("a", at(14), true);
431 log.close("zzz", at(15), false);
433 let v = log.to_vec();
434 assert_eq!(v.len(), 2);
435 assert_eq!(v[0].name, "Bash");
436 assert_eq!(v[0].duration_ms, Some(4_000));
437 assert!(v[0].error);
438 assert_eq!(v[1].duration_ms, Some(1_000));
439 assert!(v[1].sidechain);
440 assert!(!v[1].error);
441 }
442
443 #[test]
444 fn keeps_the_newest_spans_and_reports_open_ones() {
445 let mut log = SpanLog::default();
446 for i in 0..(MAX_SPANS + 10) {
447 log.open(format!("id{i}"), "T".into(), at(i as u64), false);
448 log.close(&format!("id{i}"), at(i as u64), false);
449 }
450 assert_eq!(log.len(), MAX_SPANS);
451 assert_eq!(log.iter().next().unwrap().id, "id10");
452 log.open("live".into(), "Bash".into(), at(500), false);
453 let last = log.to_vec().pop().unwrap();
454 assert!(last.is_open());
455 assert_eq!(last.elapsed_ms(at(503)), 3_000);
456 }
457
458 #[test]
459 fn end_at_moves_the_end_of_any_kind_of_span() {
460 let mut log = SpanLog::default();
461 log.open_kind("inference:1".into(), "inference".into(), at(10), false, SpanKind::Inference);
462 assert!(log.open_of_kind(SpanKind::Inference).is_some());
463 assert!(log.open_of_kind(SpanKind::Turn).is_none());
464 log.end_at("inference:1", at(11));
466 log.end_at("inference:1", at(13));
467 log.end_at("nope", at(99));
468 let v = log.to_vec();
469 assert_eq!(v[0].duration_ms, Some(3_000));
470 assert_eq!(v[0].kind, SpanKind::Inference);
471 assert!(log.open_of_kind(SpanKind::Inference).is_none());
472 log.discard_open("inference:1");
474 assert_eq!(log.len(), 1);
475 log.open_kind("inference:2".into(), "inference".into(), at(20), false, SpanKind::Inference);
476 log.discard_open("inference:2");
477 assert_eq!(log.len(), 1);
478 }
479
480 #[test]
481 fn unbounded_log_keeps_everything() {
482 let mut log = SpanLog::unbounded();
483 for i in 0..(MAX_SPANS * 3) {
484 log.open(format!("id{i}"), "T".into(), at(i as u64), false);
485 log.close(&format!("id{i}"), at(i as u64 + 1), false);
486 }
487 assert_eq!(log.len(), MAX_SPANS * 3);
488 assert_eq!(log.iter().next().unwrap().id, "id0");
489 assert_eq!(SpanRetention::default(), SpanRetention::Recent);
490 }
491
492 #[test]
493 fn detects_the_harness_from_the_first_lines() {
494 let dir = std::env::temp_dir().join(format!("agent-top-detect-{}", std::process::id()));
495 std::fs::create_dir_all(&dir).unwrap();
496 let codex = dir.join("rollout.jsonl");
497 std::fs::write(&codex, "{\"type\":\"session_meta\",\"payload\":{\"id\":\"x\"}}\n").unwrap();
498 let claude = dir.join("s.jsonl");
499 std::fs::write(&claude, "{\"type\":\"summary\",\"leafUuid\":\"u\"}\n{\"type\":\"user\",\"sessionId\":\"abc\"}\n").unwrap();
501 let other = dir.join("other.jsonl");
502 std::fs::write(&other, "{\"hello\":1}\nnot json\n").unwrap();
503 assert_eq!(detect(&codex), Some(Harness::Codex));
504 assert_eq!(detect(&claude), Some(Harness::Claude));
505 assert_eq!(detect(&other), None);
506 assert_eq!(detect(&dir.join("missing.jsonl")), None);
507 let _ = std::fs::remove_dir_all(&dir);
508 }
509
510 #[test]
511 fn names_the_server_behind_an_mcp_tool() {
512 assert_eq!(mcp_server_of("mcp__filesystem__read_file"), Some("filesystem"));
513 assert_eq!(mcp_server_of("mcp__chrome-devtools__take_screenshot"), Some("chrome-devtools"));
514 assert_eq!(mcp_server_of("mcp__claude_ai_Gmail__authenticate"), Some("claude_ai_Gmail"));
515 assert_eq!(mcp_server_of("mcp__odd"), Some("odd"));
516 assert_eq!(mcp_server_of("mcp____x"), None);
517 assert_eq!(mcp_server_of("Bash"), None);
518 }
519
520 #[test]
521 fn accuses_the_parser_only_with_enough_evidence() {
522 let h = ParseHealth { billable_messages: 40, usage_records: 40, empty_usage_records: 0 };
524 assert!(!h.fields_unrecognised());
525 let h = ParseHealth { billable_messages: 40, usage_records: 40, empty_usage_records: 39 };
527 assert!(!h.fields_unrecognised());
528 let h = ParseHealth { billable_messages: 40, usage_records: 40, empty_usage_records: 40 };
530 assert!(h.fields_unrecognised());
531 let h = ParseHealth { billable_messages: 40, usage_records: 0, empty_usage_records: 0 };
534 assert!(h.fields_unrecognised());
535 let h = ParseHealth { billable_messages: 2, usage_records: 0, empty_usage_records: 0 };
537 assert!(!h.fields_unrecognised());
538 assert!(!ParseHealth::default().fields_unrecognised());
540 }
541
542 #[test]
543 fn parses_timestamps() {
544 let t = parse_rfc3339_utc("1970-01-02T00:00:00.000Z").unwrap();
545 assert_eq!(t, SystemTime::UNIX_EPOCH + Duration::from_secs(86_400));
546 let t = parse_rfc3339_utc("2026-09-03T07:15:34.5Z").unwrap();
547 let secs = t.duration_since(SystemTime::UNIX_EPOCH).unwrap();
548 assert_eq!(secs.as_secs(), 1_788_419_734);
549 assert_eq!(secs.subsec_millis(), 500);
550 assert!(parse_rfc3339_utc("nope").is_none());
551 }
552}