1use crate::model::{Harness, HostStats, ProcKind, ProcNode};
10use std::collections::HashMap;
11use std::path::PathBuf;
12use std::time::{SystemTime, UNIX_EPOCH};
13use sysinfo::{ProcessRefreshKind, ProcessesToUpdate, System, UpdateKind};
14
15#[derive(Debug, Clone)]
16pub struct RawProc {
17 pub pid: u32,
18 pub ppid: Option<u32>,
19 pub name: String,
20 pub exe: Option<PathBuf>,
21 pub cmd: Vec<String>,
22 pub cwd: Option<PathBuf>,
23 pub cpu_percent: f32,
24 pub rss_bytes: u64,
25 pub start_time: u64,
27 pub run_time: u64,
28}
29
30impl RawProc {
31 pub fn cmdline(&self) -> String {
32 if self.cmd.is_empty() { self.name.clone() } else { self.cmd.join(" ") }
33 }
34
35 fn program(&self) -> String {
37 let from_cmd = self.cmd.first().map(|c| basename(c));
38 let from_exe = self.exe.as_ref().and_then(|e| e.file_name()).map(|f| f.to_string_lossy().into_owned());
39 from_cmd.or(from_exe).unwrap_or_else(|| self.name.clone())
40 }
41
42 fn is_codex_launcher(&self) -> bool {
45 matches!(self.program().to_ascii_lowercase().as_str(), "node" | "node.exe" | "nodejs" | "bun" | "bun.exe")
46 && self.cmd.get(1).is_some_and(|s| s.replace('\\', "/").ends_with("/@openai/codex/bin/codex.js"))
47 }
48
49 fn codex_args(&self) -> Option<&[String]> {
50 if matches!(self.program().to_ascii_lowercase().as_str(), "codex" | "codex.exe") {
51 Some(self.cmd.get(1..).unwrap_or_default())
52 } else if self.is_codex_launcher() {
53 self.cmd.get(2..)
54 } else {
55 None
56 }
57 }
58
59 pub(crate) fn is_codex_runtime_of(&self, parent: &RawProc) -> bool {
62 self.ppid == Some(parent.pid)
63 && parent.is_codex_launcher()
64 && !self.is_codex_launcher()
65 && classify_agent(self) == Some(Harness::Codex)
66 && self.codex_args() == parent.codex_args()
67 }
68}
69
70fn basename(s: &str) -> String {
71 s.rsplit('/').next().unwrap_or(s).to_string()
72}
73
74pub struct ProcessScanner {
75 sys: System,
76 self_pid: Option<u32>,
77}
78
79impl Default for ProcessScanner {
80 fn default() -> Self {
81 Self::new()
82 }
83}
84
85impl ProcessScanner {
86 pub fn new() -> Self {
87 let mut sys = System::new();
88 sys.refresh_memory();
89 sys.refresh_cpu_usage();
90 sys.refresh_processes_specifics(ProcessesToUpdate::All, true, Self::refresh_kind());
91 let self_pid = sysinfo::get_current_pid().ok().map(|p| p.as_u32());
92 ProcessScanner { sys, self_pid }
93 }
94
95 pub fn refresh(&mut self) {
96 self.sys.refresh_memory();
97 self.sys.refresh_cpu_usage();
98 self.sys.refresh_processes_specifics(ProcessesToUpdate::All, true, Self::refresh_kind());
99 }
100
101 fn refresh_kind() -> ProcessRefreshKind {
112 ProcessRefreshKind::nothing()
113 .without_tasks()
114 .with_memory()
115 .with_cpu()
116 .with_exe(UpdateKind::OnlyIfNotSet)
117 .with_cmd(UpdateKind::OnlyIfNotSet)
118 .with_cwd(UpdateKind::OnlyIfNotSet)
119 }
120
121 pub fn host(&self) -> HostStats {
122 HostStats {
123 hostname: System::host_name(),
124 cpu_percent: self.sys.global_cpu_usage(),
125 cpu_count: self.sys.cpus().len(),
126 mem_used_bytes: self.sys.used_memory(),
127 mem_total_bytes: self.sys.total_memory(),
128 }
129 }
130
131 pub fn processes(&self) -> Vec<RawProc> {
132 self.sys
133 .processes()
134 .iter()
135 .filter(|(pid, _)| Some(pid.as_u32()) != self.self_pid)
136 .map(|(pid, p)| RawProc {
137 pid: pid.as_u32(),
138 ppid: p.parent().map(|x| x.as_u32()),
139 name: p.name().to_string_lossy().into_owned(),
140 exe: p.exe().map(|e| e.to_path_buf()),
141 cmd: p.cmd().iter().map(|c| c.to_string_lossy().into_owned()).collect(),
142 cwd: p.cwd().map(|c| c.to_path_buf()),
143 cpu_percent: p.cpu_usage(),
144 rss_bytes: p.memory(),
145 start_time: p.start_time(),
146 run_time: p.run_time(),
147 })
148 .collect()
149 }
150}
151
152pub fn classify_agent(p: &RawProc) -> Option<Harness> {
154 let prog = p.program();
155 let prog = prog.strip_suffix(".exe").unwrap_or(&prog).to_ascii_lowercase();
156 let joined = p.cmd.join(" ");
157
158 let script = p.cmd.get(1).map(|s| s.to_ascii_lowercase()).unwrap_or_default();
160
161 if prog == "claude" || script.contains("@anthropic-ai/claude-code") || script.ends_with("/claude") {
162 return Some(Harness::Claude);
163 }
164 if let Some(args) = p.codex_args() {
165 return (!codex_helper(args)).then_some(Harness::Codex);
166 }
167 if prog == "gemini" || script.contains("@google/gemini-cli") {
168 return Some(Harness::Gemini);
169 }
170 if prog == "opencode" {
171 return Some(Harness::OpenCode);
172 }
173 if prog == "aider" || joined.contains("aider/main.py") {
174 return Some(Harness::Aider);
175 }
176 if prog == "copilot" || script.contains("@github/copilot") {
177 return Some(Harness::Copilot);
178 }
179 if prog == "cursor-agent" {
180 return Some(Harness::Cursor);
181 }
182 None
183}
184
185pub fn classify_child(p: &RawProc) -> ProcKind {
187 let prog = p.program().to_ascii_lowercase();
188 let joined = p.cmdline().to_ascii_lowercase();
189 if p.codex_args().is_some_and(codex_helper) {
191 return ProcKind::Tool;
192 }
193 if matches!(prog.as_str(), "zsh" | "bash" | "sh" | "fish" | "dash" | "pwsh" | "cmd") {
194 return ProcKind::Shell;
195 }
196 if looks_like_mcp(&prog, &joined) {
197 return ProcKind::Mcp;
198 }
199 ProcKind::Tool
200}
201
202fn codex_helper(args: &[String]) -> bool {
207 matches!(
208 args.first().map(String::as_str),
209 Some(
210 "--codex-run-as-apply-patch"
211 | "--codex-run-as-arg0-exec-helper"
212 | "--codex-run-as-fs-helper"
213 | "--run-as-windows-sandbox"
214 | "--__codex-windows-mxc"
215 | "mcp"
216 | "sandbox"
217 | "exec-server"
218 | "stdio-to-uds"
219 | "responses-api-proxy"
220 )
221 ) || (args.first().map(String::as_str) == Some("app-server") && args.get(1).map(String::as_str) == Some("daemon"))
222}
223
224pub fn looks_like_mcp(prog: &str, joined: &str) -> bool {
228 prog.contains("mcp")
229 || joined.contains("modelcontextprotocol")
230 || joined.contains("mcp-server")
231 || joined.contains("mcp_server")
232 || joined.contains("-mcp ")
233 || joined.ends_with("-mcp")
234 || joined.contains("mcp-")
235 || joined.contains("/mcp/")
236 || joined.contains(" mcp ")
237}
238
239fn now_secs() -> u64 {
240 SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
241}
242
243pub fn build_forest(procs: &[RawProc]) -> (Vec<ProcNode>, Vec<ProcNode>) {
249 let by_pid: HashMap<u32, &RawProc> = procs.iter().map(|p| (p.pid, p)).collect();
250 let mut children: HashMap<u32, Vec<u32>> = HashMap::new();
251 for p in procs {
252 if let Some(pp) = p.ppid {
253 children.entry(pp).or_default().push(p.pid);
254 }
255 }
256 let harness_of: HashMap<u32, Harness> = procs.iter().filter_map(|p| classify_agent(p).map(|h| (p.pid, h))).collect();
257
258 let has_agent_ancestor = |mut pid: u32| -> bool {
259 let mut hops = 0;
260 while let Some(p) = by_pid.get(&pid) {
261 match p.ppid {
262 Some(pp) if pp != pid && hops < 64 => {
263 if harness_of.contains_key(&pp) {
264 return true;
265 }
266 pid = pp;
267 hops += 1;
268 }
269 _ => return false,
270 }
271 }
272 false
273 };
274
275 let now = now_secs();
276 fn build(
277 pid: u32,
278 kind: ProcKind,
279 by_pid: &HashMap<u32, &RawProc>,
280 children: &HashMap<u32, Vec<u32>>,
281 harness_of: &HashMap<u32, Harness>,
282 now: u64,
283 depth: usize,
284 ) -> ProcNode {
285 let p = by_pid[&pid];
286 let mut kids = Vec::new();
287 if depth < 32
288 && let Some(cs) = children.get(&pid)
289 {
290 let mut cs = cs.clone();
291 cs.sort_unstable();
292 for c in cs {
293 if c == pid {
294 continue;
295 }
296 let k = if harness_of.contains_key(&c) { ProcKind::Agent } else { classify_child(by_pid[&c]) };
297 kids.push(build(c, k, by_pid, children, harness_of, now, depth + 1));
298 }
299 }
300 ProcNode {
301 pid,
302 ppid: p.ppid,
303 name: p.program(),
304 cmdline: p.cmdline(),
305 kind,
306 harness: harness_of.get(&pid).copied(),
307 cpu_percent: p.cpu_percent,
308 rss_bytes: p.rss_bytes,
309 age_secs: if p.run_time > 0 { p.run_time } else { now.saturating_sub(p.start_time) },
310 cwd: p.cwd.clone(),
311 children: kids,
312 }
313 }
314
315 let mut roots: Vec<ProcNode> = harness_of
316 .keys()
317 .filter(|pid| !has_agent_ancestor(**pid))
318 .map(|pid| build(*pid, ProcKind::Agent, &by_pid, &children, &harness_of, now, 0))
319 .collect();
320 roots.sort_by_key(|r| r.pid);
321
322 let mut orphans: Vec<ProcNode> = procs
324 .iter()
325 .filter(|p| !harness_of.contains_key(&p.pid))
326 .filter(|p| classify_child(p) == ProcKind::Mcp)
327 .filter(|p| !has_agent_ancestor(p.pid))
328 .map(|p| ProcNode {
329 pid: p.pid,
330 ppid: p.ppid,
331 name: p.program(),
332 cmdline: p.cmdline(),
333 kind: ProcKind::Mcp,
334 harness: None,
335 cpu_percent: p.cpu_percent,
336 rss_bytes: p.rss_bytes,
337 age_secs: if p.run_time > 0 { p.run_time } else { now.saturating_sub(p.start_time) },
338 cwd: p.cwd.clone(),
339 children: Vec::new(),
340 })
341 .collect();
342 let orphan_pids: std::collections::HashSet<u32> = orphans.iter().map(|o| o.pid).collect();
344 orphans.retain(|o| {
345 let mut pid = o.pid;
346 let mut hops = 0;
347 while let Some(p) = by_pid.get(&pid) {
348 match p.ppid {
349 Some(pp) if pp != pid && hops < 64 => {
350 if orphan_pids.contains(&pp) {
351 return false;
352 }
353 pid = pp;
354 hops += 1;
355 }
356 _ => break,
357 }
358 }
359 true
360 });
361 orphans.sort_by_key(|o| std::cmp::Reverse(o.age_secs));
362 (roots, orphans)
363}
364
365pub fn session_id_from_args(cmd: &[String]) -> Option<String> {
367 let mut it = cmd.iter();
368 while let Some(a) = it.next() {
369 if a == "--resume" || a == "-r" || a == "resume" {
370 if let Some(v) = it.next()
371 && looks_like_uuid(v)
372 {
373 return Some(v.clone());
374 }
375 } else if let Some(v) = a.strip_prefix("--resume=")
376 && looks_like_uuid(v)
377 {
378 return Some(v.to_string());
379 }
380 }
381 None
382}
383
384fn looks_like_uuid(s: &str) -> bool {
385 s.len() == 36 && s.chars().all(|c| c.is_ascii_hexdigit() || c == '-')
386}
387
388#[cfg(test)]
389mod tests {
390 use super::*;
391
392 fn proc(pid: u32, ppid: Option<u32>, cmd: &[&str]) -> RawProc {
393 RawProc {
394 pid,
395 ppid,
396 name: basename(cmd[0]),
397 exe: None,
398 cmd: cmd.iter().map(|s| s.to_string()).collect(),
399 cwd: None,
400 cpu_percent: 0.0,
401 rss_bytes: 0,
402 start_time: 0,
403 run_time: 1,
404 }
405 }
406
407 #[test]
408 fn refreshes_processes_without_tasks() {
409 let kind = ProcessScanner::refresh_kind();
410 assert!(!kind.tasks(), "Linux threads share their process's RSS and must not become tree nodes");
411 assert!(kind.memory());
412 assert!(kind.cpu());
413 }
414
415 #[cfg(target_os = "linux")]
416 #[test]
417 fn scanner_excludes_live_worker_threads() {
418 use std::sync::mpsc;
419
420 std::thread::scope(|scope| {
421 let (ready, tid) = mpsc::channel();
422 let (_release, wait) = mpsc::channel::<()>();
423 scope.spawn(move || {
424 let path = std::fs::read_link("/proc/thread-self").unwrap();
425 let tid: u32 = path.file_name().unwrap().to_str().unwrap().parse().unwrap();
426 ready.send(tid).unwrap();
427 let _ = wait.recv();
430 });
431 let tid = tid.recv().unwrap();
432 let pid = std::process::id();
433 assert_ne!(tid, pid);
434
435 let mut scanner = ProcessScanner::new();
436 scanner.self_pid = None;
439 for _ in 0..2 {
440 let procs = scanner.processes();
441 assert!(procs.iter().any(|p| p.pid == pid), "the process itself must remain visible");
442 assert!(!procs.iter().any(|p| p.pid == tid), "a worker thread is not a child process");
443 scanner.refresh();
444 }
445 });
446 }
447
448 #[test]
449 fn nested_harnesses_are_agents_with_each_process_counted_once() {
450 let mut procs = vec![
451 proc(10, None, &["node", "/usr/lib/node_modules/@openai/codex/bin/codex.js", "--yolo"]),
452 proc(11, Some(10), &["/opt/codex/bin/codex", "--yolo"]),
453 proc(12, Some(11), &["bash", "-c", "codex --yolo"]),
454 proc(13, Some(12), &["codex", "--yolo"]),
455 proc(14, Some(10), &["codex", "exec", "review"]),
456 proc(15, Some(11), &["codex", "--yolo"]),
457 ];
458 for p in &mut procs {
459 p.rss_bytes = 100;
460 p.cpu_percent = 1.0;
461 }
462 let (roots, orphans) = build_forest(&procs);
463 assert!(orphans.is_empty());
464 assert_eq!(roots.len(), 1);
465 let root = &roots[0];
466 assert_eq!(root.pid, 10);
467 let runtime = &root.children[0];
468 assert_eq!(runtime.pid, 11);
469 assert_eq!(runtime.kind, ProcKind::Agent);
470 assert_eq!(runtime.children[0].kind, ProcKind::Shell);
471 assert_eq!(runtime.children[0].children[0].kind, ProcKind::Agent, "tool-launched harnesses are still agents");
472 assert_eq!(runtime.children[1].kind, ProcKind::Agent);
473 assert_eq!(root.children[1].kind, ProcKind::Agent);
474 assert_eq!(root.totals(), (6.0, 600, 6, 0), "each real PID contributes resources exactly once");
475 }
476
477 #[test]
478 fn codex_runtime_matches_only_its_launcher_and_forwarded_arguments() {
479 let launcher = proc(10, None, &["node", "/usr/lib/node_modules/@openai/codex/bin/codex.js", "exec", "review the diff"]);
480 let runtime = proc(11, Some(10), &["/opt/codex/bin/codex", "exec", "review the diff"]);
481 assert!(runtime.is_codex_runtime_of(&launcher));
482
483 for child in [
484 proc(12, Some(10), &["codex", "exec", "different task"]),
485 proc(12, Some(10), &["codex", "exec", "review", "the", "diff"]),
486 proc(12, Some(99), &["codex", "exec", "review the diff"]),
487 proc(12, Some(10), &["node", "/usr/lib/node_modules/@openai/codex/bin/codex.js", "exec", "review the diff"]),
488 ] {
489 assert!(!child.is_codex_runtime_of(&launcher), "not the forwarded runtime: {child:?}");
490 }
491 let nested = proc(12, Some(11), &["codex", "exec", "review the diff"]);
492 assert!(!nested.is_codex_runtime_of(&runtime), "a native agent is not a launcher");
493
494 let launcher = proc(10, None, &["node", "/usr/lib/node_modules/@openai/codex/bin/codex.js", "mcp", "list"]);
495 let helper = proc(11, Some(10), &["codex", "mcp", "list"]);
496 assert!(!helper.is_codex_runtime_of(&launcher), "a management helper does not own agent rollouts");
497 }
498
499 #[test]
500 fn legacy_process_subagent_kind_deserializes_as_agent() {
501 let kind: ProcKind = serde_json::from_str("\"subagent\"").unwrap();
502 assert_eq!(kind, ProcKind::Agent);
503 assert_eq!(kind.label(), "agent");
504 assert_eq!(serde_json::to_value(kind).unwrap(), "agent");
505 }
506
507 #[test]
508 fn codex_helpers_are_tools_not_agents_or_mcp_servers() {
509 let helpers: &[&[&str]] = &[
510 &["codex", "--codex-run-as-apply-patch", "patch"],
511 &["codex", "--codex-run-as-arg0-exec-helper"],
512 &["codex", "--codex-run-as-fs-helper"],
513 &["codex.exe", "--run-as-windows-sandbox"],
514 &["codex.exe", "--__codex-windows-mxc"],
515 &["codex", "mcp", "list"],
516 &["codex", "sandbox", "--", "sh"],
517 &["codex", "exec-server"],
518 &["codex", "stdio-to-uds", "/tmp/socket"],
519 &["codex", "responses-api-proxy"],
520 &["codex", "app-server", "daemon", "start"],
521 &["node", "/usr/lib/node_modules/@openai/codex/bin/codex.js", "mcp", "list"],
522 &["codex-linux-sandbox", "--", "sh"],
523 &["apply_patch", "patch"],
524 &["applypatch", "patch"],
525 ];
526 let mut procs = vec![proc(1, None, &["codex", "--yolo"])];
527 for (i, cmd) in helpers.iter().enumerate() {
528 let mut p = proc(i as u32 + 2, Some(1), cmd);
529 p.exe = Some(PathBuf::from("/opt/codex/bin/codex"));
531 assert_eq!(classify_agent(&p), None, "{cmd:?}");
532 assert_eq!(classify_child(&p), ProcKind::Tool, "{cmd:?}");
533 procs.push(p);
534 }
535 let (roots, orphans) = build_forest(&procs);
536 assert_eq!(roots.len(), 1);
537 assert!(roots[0].children.iter().all(|p| p.kind == ProcKind::Tool));
538 assert!(orphans.is_empty());
539
540 for cmd in [
541 vec!["codex"],
542 vec!["codex", "app-server", "--listen", "stdio://"],
543 vec!["codex", "exec", "mcp"],
544 vec!["codex", "--", "sandbox"],
545 vec!["codex", "review"],
546 vec!["codex", "resume", "--last"],
547 vec!["codex", "tcp-tunnel"],
550 ] {
551 assert_eq!(classify_agent(&proc(20, None, &cmd)), Some(Harness::Codex), "{cmd:?}");
552 }
553 assert_eq!(
554 classify_agent(&proc(20, None, &["cat", "/usr/lib/node_modules/@openai/codex/bin/codex.js"])),
555 None,
556 "mentioning the launcher path is not running it"
557 );
558 }
559
560 #[test]
561 fn classifies_roots_and_children() {
562 let procs = vec![
563 proc(1, None, &["/sbin/launchd"]),
564 proc(10, Some(1), &["claude", "--resume", "a29e19c3-2856-4510-87a0-80ce170ad830"]),
565 proc(11, Some(10), &["/bin/zsh", "-c", "cargo test"]),
566 proc(12, Some(10), &["npx", "-y", "@modelcontextprotocol/server-filesystem", "/tmp"]),
567 proc(13, Some(10), &["claude", "-p", "summarise"]),
568 proc(20, Some(1), &["uvx", "mcp-server-git"]),
569 proc(
570 30,
571 Some(1),
572 &["/Applications/ChatGPT.app/Contents/Frameworks/Codex Framework.framework/Helpers/browser_crashpad_handler"],
573 ),
574 ];
575 let (roots, orphans) = build_forest(&procs);
576 assert_eq!(roots.len(), 1);
577 let root = &roots[0];
578 assert_eq!(root.harness, Some(Harness::Claude));
579 let kinds: Vec<ProcKind> = root.children.iter().map(|c| c.kind).collect();
580 assert_eq!(kinds, vec![ProcKind::Shell, ProcKind::Mcp, ProcKind::Agent]);
581 assert_eq!(orphans.len(), 1);
582 assert_eq!(orphans[0].pid, 20);
583 assert_eq!(session_id_from_args(&procs[1].cmd).as_deref(), Some("a29e19c3-2856-4510-87a0-80ce170ad830"));
584 }
585}