Skip to main content

agent_top_core/
model.rs

1//! The data model shared by discovery, the TUI and the JSON output.
2
3use serde::{Deserialize, Serialize};
4use std::path::PathBuf;
5use std::time::SystemTime;
6
7/// Which agent harness a process or transcript belongs to.
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, PartialOrd, Ord)]
9#[serde(rename_all = "kebab-case")]
10pub enum Harness {
11    Claude,
12    Codex,
13    Gemini,
14    OpenCode,
15    Aider,
16    Copilot,
17    Cursor,
18    Unknown,
19}
20
21impl Harness {
22    pub fn label(self) -> &'static str {
23        match self {
24            Harness::Claude => "claude",
25            Harness::Codex => "codex",
26            Harness::Gemini => "gemini",
27            Harness::OpenCode => "opencode",
28            Harness::Aider => "aider",
29            Harness::Copilot => "copilot",
30            Harness::Cursor => "cursor",
31            Harness::Unknown => "unknown",
32        }
33    }
34}
35
36/// Coarse lifecycle state, in the htop sense.
37///
38/// `Running` means the agent is mid-turn (inference or tool execution),
39/// `Idle` means the process is alive but waiting for a human, `Stopped` means
40/// the transcript exists and was recently active but no process owns it.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, PartialOrd, Ord)]
42#[serde(rename_all = "kebab-case")]
43pub enum AgentState {
44    Running,
45    Idle,
46    Stopped,
47}
48
49impl AgentState {
50    pub fn label(self) -> &'static str {
51        match self {
52            AgentState::Running => "running",
53            AgentState::Idle => "idle",
54            AgentState::Stopped => "stopped",
55        }
56    }
57}
58
59/// What the transcript says the agent was last doing. Harness-neutral.
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
61#[serde(rename_all = "kebab-case")]
62pub enum Activity {
63    /// Mid-turn: a prompt or tool result was just submitted, or a tool call is pending.
64    Working,
65    /// The last thing that happened was the assistant ending its turn.
66    Waiting,
67    #[default]
68    Unknown,
69}
70
71/// Token counts, split the way the Anthropic and OpenAI usage objects split them.
72#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
73pub struct TokenUsage {
74    pub input: u64,
75    pub cache_write_5m: u64,
76    pub cache_write_1h: u64,
77    pub cache_read: u64,
78    pub output: u64,
79}
80
81impl TokenUsage {
82    pub fn cache_write(&self) -> u64 {
83        self.cache_write_5m + self.cache_write_1h
84    }
85
86    /// Everything the model consumed or produced. This is the "TOKENS" column.
87    pub fn total(&self) -> u64 {
88        self.input + self.cache_write() + self.cache_read + self.output
89    }
90
91    /// The input side: everything sent to the model as the prompt, fresh input
92    /// plus cache writes plus cache reads, but not the output it produced.
93    pub fn prompt(&self) -> u64 {
94        self.input + self.cache_write() + self.cache_read
95    }
96
97    /// The share of the prompt served from cache (the cheap reads), in `0..=1`.
98    /// A high number means most of the re-sent conversation was billed at the
99    /// cache-read rate rather than full input; a low one on a long session is
100    /// money left on the table. `None` when there was no prompt to judge, or
101    /// the model does not cache at all.
102    pub fn cache_hit_rate(&self) -> Option<f64> {
103        let p = self.prompt();
104        (p > 0).then(|| self.cache_read as f64 / p as f64)
105    }
106
107    pub fn add(&mut self, other: &TokenUsage) {
108        self.input += other.input;
109        self.cache_write_5m += other.cache_write_5m;
110        self.cache_write_1h += other.cache_write_1h;
111        self.cache_read += other.cache_read;
112        self.output += other.output;
113    }
114
115    pub fn sub(&mut self, other: &TokenUsage) {
116        self.input = self.input.saturating_sub(other.input);
117        self.cache_write_5m = self.cache_write_5m.saturating_sub(other.cache_write_5m);
118        self.cache_write_1h = self.cache_write_1h.saturating_sub(other.cache_write_1h);
119        self.cache_read = self.cache_read.saturating_sub(other.cache_read);
120        self.output = self.output.saturating_sub(other.output);
121    }
122}
123
124/// What a span measures. Tool calls came first and gave the type its name;
125/// the other two label the time between them.
126#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default, PartialOrd, Ord)]
127#[serde(rename_all = "kebab-case")]
128pub enum SpanKind {
129    /// One tool call, from the harness issuing it to the result coming back.
130    #[default]
131    Tool,
132    /// The model producing a response: from a prompt or tool results being
133    /// submitted to the last block of the reply being written. The gap in a
134    /// waterfall that is not a tool call is almost always one of these.
135    Inference,
136    /// One human turn: from the prompt to the model ending its reply.
137    /// Contains every tool call and inference span issued in between.
138    Turn,
139}
140
141impl SpanKind {
142    pub const ALL: [SpanKind; 3] = [SpanKind::Tool, SpanKind::Inference, SpanKind::Turn];
143
144    pub fn label(self) -> &'static str {
145        match self {
146            SpanKind::Tool => "tool",
147            SpanKind::Inference => "inference",
148            SpanKind::Turn => "turn",
149        }
150    }
151}
152
153/// One span of an agent trace: a tool call, an inference, or a turn.
154///
155/// Every harness writes the same shape in its own vocabulary — Claude pairs a
156/// `tool_use` block with a `tool_result` block by `tool_use_id`, Codex pairs a
157/// `function_call` with a `function_call_output` by `call_id` — and both stamp
158/// each line with a timestamp. That is a span: a name, a start and a duration.
159/// Only the call's metadata is kept; arguments and output are never read.
160///
161/// The name predates `kind`: the type carried only tool calls until 0.3.1 and
162/// is kept for the sake of the published API.
163#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
164pub struct ToolSpan {
165    /// The harness's own call id, so a span survives across refreshes. For
166    /// inference and turn spans, a counter the parser assigns.
167    pub id: String,
168    /// Tool name as the harness reports it (`Bash`, `exec_command`, ...), or
169    /// `inference` / `turn`.
170    pub name: String,
171    pub started_at: SystemTime,
172    /// Wall-clock duration, or `None` while the call is still in flight.
173    pub duration_ms: Option<u64>,
174    /// The call was issued by a subagent (Claude's `isSidechain`).
175    pub sidechain: bool,
176    /// The harness reported the result as an error.
177    pub error: bool,
178    /// Absent in snapshots written before 0.3.1, which held tool calls only.
179    #[serde(default)]
180    pub kind: SpanKind,
181}
182
183impl ToolSpan {
184    pub fn is_open(&self) -> bool {
185        self.duration_ms.is_none()
186    }
187
188    /// Duration if closed, otherwise how long it has been running as of `now`.
189    pub fn elapsed_ms(&self, now: SystemTime) -> u64 {
190        match self.duration_ms {
191            Some(ms) => ms,
192            None => now.duration_since(self.started_at).map(|d| d.as_millis() as u64).unwrap_or(0),
193        }
194    }
195
196    pub fn ended_at(&self, now: SystemTime) -> SystemTime {
197        self.started_at + std::time::Duration::from_millis(self.elapsed_ms(now))
198    }
199}
200
201/// One MCP server an agent uses, seen from either side or both: the process
202/// table has the server's pid, CPU and memory; the transcript has how often
203/// the agent called it. Claude Code names an MCP tool `mcp__<server>__<tool>`,
204/// which is where the server name and the call count come from.
205#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
206pub struct McpServer {
207    /// The server's name as the harness configured it, or, for a process the
208    /// transcript never named, the program it is running.
209    pub name: String,
210    pub pid: Option<u32>,
211    pub cmdline: Option<String>,
212    pub cpu_percent: f32,
213    pub rss_bytes: u64,
214    pub age_secs: Option<u64>,
215    /// Tool calls the agent made to this server, from the transcript.
216    pub calls: u64,
217    /// Of those, how many the harness reported as errors.
218    pub errors: u64,
219    pub last_call: Option<SystemTime>,
220    /// How the process and the transcript's server were put together, for
221    /// the UI to label a guess as one.
222    pub matched_by: McpMatch,
223}
224
225/// How an `McpServer` row was formed.
226#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
227#[serde(rename_all = "kebab-case")]
228pub enum McpMatch {
229    /// A process under the agent that no transcript server names. Either it
230    /// has not been called yet, or its name does not appear in its command.
231    ProcessOnly,
232    /// A server the transcript calls with no process under the agent: an HTTP
233    /// server, or one that has exited.
234    TranscriptOnly,
235    /// The server's name appears in the process's command line.
236    Name,
237    /// One unmatched process and one unmatched server were left; they are
238    /// taken to be the same. A guess.
239    Sole,
240}
241
242/// Role of a process inside an agent's tree.
243#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
244#[serde(rename_all = "kebab-case")]
245pub enum ProcKind {
246    /// The agent's root process (the harness itself).
247    Agent,
248    /// Another agent process nested under an agent (e.g. `claude -p` run from a tool).
249    Subagent,
250    /// A Model Context Protocol server or helper.
251    Mcp,
252    /// A shell spawned to run a tool call.
253    Shell,
254    /// Anything else the agent launched (test runners, sleep, caffeinate, ...).
255    Tool,
256}
257
258impl ProcKind {
259    pub fn label(self) -> &'static str {
260        match self {
261            ProcKind::Agent => "agent",
262            ProcKind::Subagent => "subagent",
263            ProcKind::Mcp => "mcp",
264            ProcKind::Shell => "shell",
265            ProcKind::Tool => "tool",
266        }
267    }
268}
269
270/// One process, with its descendants.
271#[derive(Debug, Clone, Serialize, Deserialize)]
272pub struct ProcNode {
273    pub pid: u32,
274    pub ppid: Option<u32>,
275    pub name: String,
276    pub cmdline: String,
277    pub kind: ProcKind,
278    pub harness: Option<Harness>,
279    pub cpu_percent: f32,
280    pub rss_bytes: u64,
281    pub age_secs: u64,
282    pub cwd: Option<PathBuf>,
283    pub children: Vec<ProcNode>,
284}
285
286impl ProcNode {
287    /// CPU, RSS, process count and MCP server count summed over the whole
288    /// subtree. An MCP process's own children (an `npx` wrapper's `node`) are
289    /// the same server, so they add to the process count and not to the
290    /// server count.
291    pub fn totals(&self) -> (f32, u64, usize, usize) {
292        let mut cpu = self.cpu_percent;
293        let mut rss = self.rss_bytes;
294        let mut count = 1;
295        let mut mcp = usize::from(self.kind == ProcKind::Mcp);
296        for c in &self.children {
297            let (ccpu, crss, ccount, cmcp) = c.totals();
298            cpu += ccpu;
299            rss += crss;
300            count += ccount;
301            if self.kind != ProcKind::Mcp {
302                mcp += cmcp;
303            }
304        }
305        (cpu, rss, count, mcp)
306    }
307
308    /// The MCP servers in this tree: each `Mcp` node whose parent is not one.
309    /// A server started through `npx` or `uvx` is two or three processes; the
310    /// top one stands for the server.
311    pub fn mcp_roots(&self) -> Vec<&ProcNode> {
312        let mut out = Vec::new();
313        self.collect_mcp_roots(&mut out);
314        out
315    }
316
317    fn collect_mcp_roots<'a>(&'a self, out: &mut Vec<&'a ProcNode>) {
318        if self.kind == ProcKind::Mcp {
319            out.push(self);
320            return;
321        }
322        for c in &self.children {
323            c.collect_mcp_roots(out);
324        }
325    }
326
327    pub fn walk<'a>(&'a self, depth: usize, f: &mut dyn FnMut(&'a ProcNode, usize)) {
328        f(self, depth);
329        for c in &self.children {
330            c.walk(depth + 1, f);
331        }
332    }
333}
334
335/// A single row in the agent table.
336#[derive(Debug, Clone, Serialize, Deserialize)]
337pub struct Agent {
338    /// Stable identity across refreshes: `pid:<n>` for live agents, `session:<id>` for stopped ones.
339    pub id: String,
340    pub name: String,
341    pub harness: Harness,
342    pub state: AgentState,
343    pub activity: Activity,
344    pub pid: Option<u32>,
345    pub session_id: Option<String>,
346    pub session_path: Option<PathBuf>,
347    pub cwd: Option<PathBuf>,
348    pub model: Option<String>,
349    pub harness_version: Option<String>,
350    pub usage: TokenUsage,
351    /// USD spent on messages whose model had a known price.
352    pub cost_usd: f64,
353    /// `cost_usd` by kind of token, so a figure that differs from another
354    /// tool's can be traced to the one line that differs.
355    #[serde(default)]
356    pub cost_breakdown: CostBreakdown,
357    /// Where the price of this row's model came from; `None` when it has none.
358    #[serde(default)]
359    pub price_source: Option<PriceSource>,
360    /// Tokens on messages whose model had no known price (so `cost_usd` is a floor).
361    pub unpriced_tokens: u64,
362    pub turns: u64,
363    pub subagent_turns: u64,
364    pub tool_calls: u64,
365    /// Server-side web searches the model ran, billed per search on top of
366    /// tokens. Counted for every harness; priced only where the price table
367    /// has a rate (Anthropic's, for Claude Code).
368    #[serde(default)]
369    pub web_searches: u64,
370    /// The most recent spans, oldest first: tool calls, inferences and turns.
371    /// Bounded; see `harness::MAX_SPANS`.
372    pub spans: Vec<ToolSpan>,
373    /// Seconds since the process started (live) or since the last transcript write (stopped).
374    pub age_secs: u64,
375    /// Seconds since the transcript was last written.
376    pub idle_secs: Option<u64>,
377    pub cpu_percent: f32,
378    pub rss_bytes: u64,
379    pub process_count: usize,
380    pub mcp_count: usize,
381    /// The MCP servers this agent uses, one row each, from the process tree
382    /// and the transcript. See `McpServer`.
383    #[serde(default)]
384    pub mcp_servers: Vec<McpServer>,
385    pub tree: Option<ProcNode>,
386    /// How the session was attributed to the process, for debugging attribution.
387    pub attribution: Attribution,
388    /// True when another row shares this pid and carries its CPU, memory and
389    /// process counts. One Codex app-server hosts many conversations, so its
390    /// threads each get a row while the process is only counted once.
391    /// Absent in snapshots written before 0.2.0.
392    #[serde(default)]
393    pub shares_process: bool,
394    /// Set when the transcript parsed but its usage records did not, which
395    /// means this row's tokens and cost are not to be believed. Almost always a
396    /// harness that changed its format under us.
397    pub parse_warning: Option<String>,
398    /// How close the session is to its rate limit, when the harness reports it.
399    #[serde(default)]
400    pub rate_limit: Option<RateLimit>,
401}
402
403/// One rolling usage window a harness reports against a rate limit: how much
404/// of it is spent and when it rolls over. Codex writes two, a short window and
405/// a long one, on every usage record.
406#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
407pub struct RateWindow {
408    /// Percent of the window used, 0..=100.
409    pub used_percent: f64,
410    /// The window length in minutes (Codex: 300 for the short one, 10080 weekly).
411    pub window_minutes: u64,
412    /// When the window rolls over and the usage resets, if the harness says.
413    pub resets_at: Option<SystemTime>,
414}
415
416/// What a harness reports about how close a session is to its rate limit. Only
417/// the harnesses that write it (Codex today) populate this; the rest leave it
418/// `None`. Read-only, like everything else: a number the harness already wrote.
419#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
420pub struct RateLimit {
421    /// The short rolling window.
422    pub primary: Option<RateWindow>,
423    /// The long rolling window.
424    pub secondary: Option<RateWindow>,
425    /// The plan the limit is for (Codex: `plus`, `pro`, ...).
426    pub plan: Option<String>,
427    /// True when the harness says the limit is currently hit.
428    pub reached: bool,
429}
430
431impl RateLimit {
432    /// The window closest to its limit, for a one-glance figure.
433    pub fn tightest(&self) -> Option<&RateWindow> {
434        [self.primary.as_ref(), self.secondary.as_ref()]
435            .into_iter()
436            .flatten()
437            .max_by(|a, b| a.used_percent.partial_cmp(&b.used_percent).unwrap_or(std::cmp::Ordering::Equal))
438    }
439}
440
441/// USD by kind of token, accumulated message by message at each message's
442/// own model price, so a session that changed model part way is still exact.
443/// The lines sum to `Agent::cost_usd`.
444#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
445pub struct CostBreakdown {
446    pub input: f64,
447    pub cache_write_5m: f64,
448    pub cache_write_1h: f64,
449    pub cache_read: f64,
450    pub output: f64,
451    /// Server-side web searches, billed per search on top of the tokens.
452    pub web_search: f64,
453}
454
455impl CostBreakdown {
456    pub fn total(&self) -> f64 {
457        self.input + self.cache_write_5m + self.cache_write_1h + self.cache_read + self.output + self.web_search
458    }
459
460    pub fn add(&mut self, o: &CostBreakdown) {
461        self.input += o.input;
462        self.cache_write_5m += o.cache_write_5m;
463        self.cache_write_1h += o.cache_write_1h;
464        self.cache_read += o.cache_read;
465        self.output += o.output;
466        self.web_search += o.web_search;
467    }
468
469    pub fn sub(&mut self, o: &CostBreakdown) {
470        self.input -= o.input;
471        self.cache_write_5m -= o.cache_write_5m;
472        self.cache_write_1h -= o.cache_write_1h;
473        self.cache_read -= o.cache_read;
474        self.output -= o.output;
475        self.web_search -= o.web_search;
476    }
477}
478
479/// Where a model's price came from. The built-in table carries list prices;
480/// a user's file is whatever they chose to write, and the UI says which.
481#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
482#[serde(rename_all = "kebab-case")]
483pub enum PriceSource {
484    Builtin,
485    UserFile,
486}
487
488#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
489#[serde(rename_all = "kebab-case")]
490pub enum Attribution {
491    /// The harness told us (Claude's `~/.claude/sessions/<pid>.json`).
492    HarnessRegistry,
493    /// A `--resume <id>` style argument on the command line.
494    CommandLine,
495    /// The process has the transcript open (Codex keeps every live thread's
496    /// rollout open); exact.
497    OpenFile,
498    /// Matched by working directory and start time; may be wrong with concurrent sessions.
499    CwdHeuristic,
500    /// No transcript found; process only.
501    None,
502    /// No process; transcript only.
503    TranscriptOnly,
504}
505
506#[derive(Debug, Clone, Default, Serialize, Deserialize)]
507pub struct HostStats {
508    pub hostname: Option<String>,
509    pub cpu_percent: f32,
510    pub cpu_count: usize,
511    pub mem_used_bytes: u64,
512    pub mem_total_bytes: u64,
513}
514
515#[derive(Debug, Clone, Default, Serialize, Deserialize)]
516pub struct Totals {
517    pub agents: usize,
518    pub running: usize,
519    pub idle: usize,
520    pub stopped: usize,
521    pub tokens: u64,
522    pub cost_usd: f64,
523    pub unpriced_tokens: u64,
524    pub processes: usize,
525    pub mcp_processes: usize,
526    pub orphaned_mcp: usize,
527    pub cpu_percent: f32,
528    pub rss_bytes: u64,
529}
530
531/// Version of the `--json` document. Bumped when a field changes meaning or
532/// disappears; new fields alone do not bump it.
533pub const SNAPSHOT_SCHEMA_VERSION: u32 = 1;
534
535/// What the collector remembers about an orphaned MCP process: when it first
536/// saw it, and, if it watched the process lose its parent, which agent that
537/// was. Memory lasts for the run; a process that was already an orphan when
538/// agent-top started has no parent on record.
539#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
540pub struct OrphanOrigin {
541    pub pid: u32,
542    pub first_seen: SystemTime,
543    /// When the process was first seen without its parent, if the parent was
544    /// seen before that.
545    pub orphaned_at: Option<SystemTime>,
546    pub parent: Option<OrphanParent>,
547}
548
549/// The agent an orphan used to belong to.
550#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
551pub struct OrphanParent {
552    pub pid: u32,
553    pub agent_id: String,
554    pub name: String,
555}
556
557/// Everything the UI needs for one frame.
558#[derive(Debug, Clone, Serialize, Deserialize)]
559pub struct Snapshot {
560    pub schema_version: u32,
561    pub taken_at: SystemTime,
562    pub host: HostStats,
563    pub agents: Vec<Agent>,
564    /// MCP-looking processes with no live agent ancestor: leak candidates.
565    pub orphans: Vec<ProcNode>,
566    /// One entry per orphan, saying where it came from when that is known.
567    #[serde(default)]
568    pub orphan_origins: Vec<OrphanOrigin>,
569    pub totals: Totals,
570}
571
572impl Snapshot {
573    pub fn compute_totals(&mut self) {
574        let mut t = Totals::default();
575        for a in &self.agents {
576            t.agents += 1;
577            match a.state {
578                AgentState::Running => t.running += 1,
579                AgentState::Idle => t.idle += 1,
580                AgentState::Stopped => t.stopped += 1,
581            }
582            t.tokens += a.usage.total();
583            t.cost_usd += a.cost_usd;
584            t.unpriced_tokens += a.unpriced_tokens;
585            t.processes += a.process_count;
586            t.mcp_processes += a.mcp_count;
587            t.cpu_percent += a.cpu_percent;
588            t.rss_bytes += a.rss_bytes;
589        }
590        t.orphaned_mcp = self.orphans.len();
591        self.totals = t;
592    }
593}
594
595#[cfg(test)]
596mod usage_tests {
597    use super::TokenUsage;
598
599    #[test]
600    fn cache_hit_rate_is_reads_over_the_prompt() {
601        let u = TokenUsage { input: 200, cache_read: 800, cache_write_5m: 0, cache_write_1h: 0, output: 50 };
602        // Prompt is 1000 (output excluded); 800 of it from cache.
603        assert_eq!(u.prompt(), 1000);
604        assert!((u.cache_hit_rate().unwrap() - 0.8).abs() < 1e-9);
605        // A cache write counts as prompt input, not as a hit.
606        let u = TokenUsage { input: 100, cache_read: 0, cache_write_5m: 900, cache_write_1h: 0, output: 0 };
607        assert_eq!(u.cache_hit_rate(), Some(0.0));
608        // Nothing to judge.
609        assert_eq!(TokenUsage::default().cache_hit_rate(), None);
610    }
611}