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