Skip to main content

agentmux_srv_core/backend/cli_native/
sender.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Who sent a CLI-native message, from the process id the CLI verified for the
5//! sender's connection to the receiving session's socket (`SO_PEERCRED`, in the
6//! frame's `origin.verifiedPeerPid`).
7//!
8//! Everything else in the message is the sender's own words: its name, its
9//! address, its mode, its text. Any process of the same user can connect to a
10//! session's socket and say what it likes, but none can choose the pid the
11//! kernel reports. So the sender is the agent whose CLI process that pid
12//! belongs to, or descends from, in srv's own table, and a pid outside every
13//! agent is an outside session whatever name it gives.
14
15/// What AgentMux knows about the process behind a message.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub enum Sender {
18    /// The pid is, or descends from, the CLI process srv runs for this block.
19    Agent { block_id: String },
20    /// A live process that belongs to no agent pane srv runs.
21    Outside { pid: u32 },
22    /// No verified pid, a pid that is gone, or one the system has recycled.
23    Unverified,
24}
25
26/// The parts of the process table the mapping reads.
27pub trait ProcView {
28    /// The parent of `pid`; `None` when the process does not exist.
29    fn parent(&self, pid: u32) -> Option<u32>;
30    /// The process's start time in the unit the CLI reports it (Linux: clock
31    /// ticks since boot, `/proc/<pid>/stat` field 22); `None` when unknown.
32    fn start_time(&self, pid: u32) -> Option<u64>;
33}
34
35/// Longest parent chain walked.
36const MAX_DEPTH: usize = 64;
37
38/// Maps the CLI-verified connecting process to a sender. `cli_pids` is srv's
39/// (block, CLI process) table; `proc_start` the start time the CLI reported.
40pub fn resolve(pid: Option<u32>, proc_start: Option<&str>, cli_pids: &[(String, u32)], procs: &dyn ProcView) -> Sender {
41    let Some(pid) = pid.filter(|p| *p > 1) else { return Sender::Unverified };
42    // A pid is only a name for a process while it keeps the start time it had.
43    if let (Some(reported), Some(now)) = (proc_start.and_then(|s| s.parse::<u64>().ok()), procs.start_time(pid)) {
44        if reported != now {
45            return Sender::Unverified;
46        }
47    }
48    let mut cur = pid;
49    for _ in 0..MAX_DEPTH {
50        if let Some((block, _)) = cli_pids.iter().find(|(_, p)| *p == cur) {
51            return Sender::Agent { block_id: block.clone() };
52        }
53        match procs.parent(cur) {
54            Some(parent) if parent > 1 && parent != cur => cur = parent,
55            _ => break,
56        }
57    }
58    // Gone before it could be looked at: nothing to say it was outside.
59    if procs.parent(pid).is_none() {
60        return Sender::Unverified;
61    }
62    Sender::Outside { pid }
63}
64
65/// The running system's process table.
66pub struct SystemProcs;
67
68#[cfg(target_os = "linux")]
69impl ProcView for SystemProcs {
70    fn parent(&self, pid: u32) -> Option<u32> {
71        let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
72        stat_fields(&stat).get(1)?.parse().ok()
73    }
74
75    fn start_time(&self, pid: u32) -> Option<u64> {
76        let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
77        stat_fields(&stat).get(19)?.parse().ok()
78    }
79}
80
81/// The fields of a `/proc/<pid>/stat` line after the process name, which can
82/// hold spaces and brackets: index 0 is the state, 1 the parent, 19 the start time.
83#[cfg(target_os = "linux")]
84fn stat_fields(stat: &str) -> Vec<&str> {
85    stat.rsplit_once(')').map(|(_, rest)| rest.split_whitespace().collect()).unwrap_or_default()
86}
87
88#[cfg(not(target_os = "linux"))]
89impl ProcView for SystemProcs {
90    fn parent(&self, pid: u32) -> Option<u32> {
91        use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate, System};
92        let mut sys = System::new();
93        sys.refresh_processes_specifics(ProcessesToUpdate::Some(&[Pid::from_u32(pid)]), true, ProcessRefreshKind::nothing());
94        sys.process(Pid::from_u32(pid)).map(|p| p.parent().map(|pp| pp.as_u32()).unwrap_or(0))
95    }
96
97    // The CLI's start-time unit is not known here, so the recycled-pid check is skipped.
98    fn start_time(&self, _pid: u32) -> Option<u64> {
99        None
100    }
101}
102
103#[cfg(test)]
104mod tests {
105    use super::*;
106    use std::collections::HashMap;
107
108    struct Table {
109        parents: HashMap<u32, u32>,
110        starts: HashMap<u32, u64>,
111    }
112
113    impl ProcView for Table {
114        fn parent(&self, pid: u32) -> Option<u32> {
115            self.parents.get(&pid).copied()
116        }
117        fn start_time(&self, pid: u32) -> Option<u64> {
118            self.starts.get(&pid).copied()
119        }
120    }
121
122    // agent A's CLI is 100 (child 101, grandchild 102); agent B's CLI is 200; 300 is a
123    // terminal session of the operator under init; 400's parent chain ends in a pid that is gone.
124    fn table() -> Table {
125        Table {
126            parents: HashMap::from([(100, 10), (101, 100), (102, 101), (200, 10), (300, 20), (400, 399)]),
127            starts: HashMap::from([(100, 5_000), (101, 5_100), (200, 6_000), (300, 7_000), (400, 8_000)]),
128        }
129    }
130
131    fn cli() -> Vec<(String, u32)> {
132        vec![("block-a".into(), 100), ("block-b".into(), 200)]
133    }
134
135    #[test]
136    fn the_cli_process_maps_to_its_agent() {
137        assert_eq!(resolve(Some(100), Some("5000"), &cli(), &table()), Sender::Agent { block_id: "block-a".into() });
138    }
139
140    #[test]
141    fn a_child_or_grandchild_of_the_cli_process_maps_to_the_same_agent() {
142        assert_eq!(resolve(Some(101), Some("5100"), &cli(), &table()), Sender::Agent { block_id: "block-a".into() });
143        assert_eq!(resolve(Some(102), None, &cli(), &table()), Sender::Agent { block_id: "block-a".into() });
144    }
145
146    #[test]
147    fn another_agents_pid_maps_to_that_agent_whatever_name_is_claimed() {
148        // The claimed name is not an input: B's process is B, however the message signs itself.
149        assert_eq!(resolve(Some(200), Some("6000"), &cli(), &table()), Sender::Agent { block_id: "block-b".into() });
150    }
151
152    #[test]
153    fn a_pid_outside_every_agent_is_an_outside_session() {
154        assert_eq!(resolve(Some(300), Some("7000"), &cli(), &table()), Sender::Outside { pid: 300 });
155    }
156
157    #[test]
158    fn a_recycled_pid_is_unverified() {
159        // The CLI reported start time 5000 for pid 100; the process now at 100 started at 9999.
160        let mut t = table();
161        t.starts.insert(100, 9_999);
162        assert_eq!(resolve(Some(100), Some("5000"), &cli(), &t), Sender::Unverified);
163    }
164
165    #[test]
166    fn a_missing_a_system_or_a_vanished_pid_is_unverified() {
167        assert_eq!(resolve(None, None, &cli(), &table()), Sender::Unverified);
168        assert_eq!(resolve(Some(0), None, &cli(), &table()), Sender::Unverified);
169        assert_eq!(resolve(Some(1), None, &cli(), &table()), Sender::Unverified);
170        assert_eq!(resolve(Some(777), Some("1"), &cli(), &table()), Sender::Unverified);
171    }
172
173    #[test]
174    fn a_parent_cycle_ends_the_walk() {
175        let mut t = table();
176        t.parents.insert(500, 501);
177        t.parents.insert(501, 500);
178        assert_eq!(resolve(Some(500), None, &cli(), &t), Sender::Outside { pid: 500 });
179    }
180
181    #[cfg(target_os = "linux")]
182    #[test]
183    fn the_running_system_reads_its_own_process() {
184        let me = std::process::id();
185        let parent = SystemProcs.parent(me).expect("own parent");
186        assert!(parent > 0);
187        assert!(SystemProcs.start_time(me).is_some());
188        assert_eq!(SystemProcs.parent(u32::MAX - 7), None);
189    }
190}