Skip to main content

agentmux_srv_core/backend/cli_native/
reader.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! One agent pane's view of CLI-native messages: watches the frames its CLI
5//! writes, audits each message from whichever end this pane is, and says which
6//! frames the pane's transcript must not carry.
7
8use std::collections::{HashMap, VecDeque};
9
10use serde_json::Value;
11
12use super::frame::{self, Lifecycle, PeerFrame, Replay};
13use super::sender::{self, ProcView, Sender};
14use super::sent::SentPrompts;
15
16/// Frames and messages remembered per pane.
17const REMEMBERED: usize = 256;
18
19/// Whether the transcript carries a frame.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum Disposition {
22    Keep,
23    /// The CLI replayed it only because of `--replay-user-messages`: a turn srv wrote
24    /// (recorded by srv and the pane already) or a peer message handled here.
25    Drop,
26}
27
28/// One state of one message, as seen from this pane.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct Event {
31    /// The pane that saw it.
32    pub block_id: String,
33    pub msg_id: String,
34    /// `sent` (the CLI took it into the other session's inbox), `held` (the
35    /// receiving CLI kept it from its model), `read` (the receiving CLI handed it
36    /// to its model), `done` (the turn it started ended).
37    pub state: &'static str,
38    /// `sender` or `receiver`: which end this pane is.
39    pub seen_by: &'static str,
40    /// Who sent it, as AgentMux names it: an agent, "outside session (pid N)" or
41    /// "unverified sender". Never the name the message gave.
42    pub source: String,
43    /// `agent`, `outside` or `unverified`.
44    pub identity: &'static str,
45    /// Who it is for: the receiving agent, or from the sender's end the session
46    /// name it addressed.
47    pub target: String,
48    /// The name the message gave for its sender (a claim).
49    pub claimed_name: Option<String>,
50    pub cli_to_name: Option<String>,
51    pub sender_pid: Option<u32>,
52    pub from_mode: Option<String>,
53    pub text: String,
54    /// Why a held message was held, as the CLI put it.
55    pub reason: Option<String>,
56}
57
58/// What the reader needs from the running system.
59pub trait Env {
60    /// (block, CLI process) for every agent pane.
61    fn cli_pids(&self) -> Vec<(String, u32)>;
62    fn procs(&self) -> &dyn ProcView;
63    /// The agent running in `block_id`.
64    fn agent_name(&self, block_id: &str) -> Option<String>;
65    fn record(&self, event: Event);
66}
67
68pub struct CliNativeReader {
69    block_id: String,
70    sent: SentPrompts,
71    /// `SendMessage` calls waiting for the CLI's answer, by tool use id.
72    sends: BoundedMap<frame::SendCall>,
73    /// Messages handed to the model whose turn has not ended, by frame uuid.
74    inbound: BoundedMap<Event>,
75    seen: VecDeque<String>,
76}
77
78/// A map that forgets its oldest entry past [`REMEMBERED`].
79struct BoundedMap<T> {
80    map: HashMap<String, T>,
81    order: VecDeque<String>,
82}
83
84impl<T> BoundedMap<T> {
85    fn new() -> Self {
86        Self { map: HashMap::new(), order: VecDeque::new() }
87    }
88    fn insert(&mut self, key: String, value: T) {
89        if self.order.len() >= REMEMBERED {
90            if let Some(old) = self.order.pop_front() {
91                self.map.remove(&old);
92            }
93        }
94        self.order.push_back(key.clone());
95        self.map.insert(key, value);
96    }
97    fn remove(&mut self, key: &str) -> Option<T> {
98        self.map.remove(key)
99    }
100}
101
102impl CliNativeReader {
103    /// `sent`: the user turns srv writes to this CLI.
104    pub fn new(block_id: &str, sent: SentPrompts) -> Self {
105        Self { block_id: block_id.to_string(), sent, sends: BoundedMap::new(), inbound: BoundedMap::new(), seen: VecDeque::new() }
106    }
107
108    /// Reads one stdout frame.
109    pub fn observe(&mut self, v: &Value, env: &dyn Env) -> Disposition {
110        match frame::replay(v) {
111            Some(Replay::Peer(peer)) => {
112                self.received(peer, env);
113                return Disposition::Drop;
114            }
115            // The echo of a turn srv wrote goes; a replay of the CLI's own stays.
116            Some(Replay::Other { uuid }) => {
117                return if uuid.is_some_and(|u| self.sent.take(&u)) { Disposition::Drop } else { Disposition::Keep };
118            }
119            None => {}
120        }
121        if let Some(hold) = frame::peer_hold(v) {
122            self.held(hold, env);
123            return Disposition::Keep;
124        }
125        if let Some((uuid, Lifecycle::Completed)) = frame::lifecycle(v) {
126            if let Some(read) = self.inbound.remove(uuid) {
127                env.record(Event { state: "done", ..read });
128            }
129            return Disposition::Keep;
130        }
131        for call in frame::send_calls(v) {
132            self.sends.insert(call.tool_use_id.clone(), call);
133        }
134        for result in frame::send_results(v) {
135            let Some(call) = self.sends.remove(&result.tool_use_id) else { continue };
136            let (true, Some(msg_id)) = (result.accepted, result.msg_id) else { continue };
137            let me = env.agent_name(&self.block_id).unwrap_or_else(|| self.block_id.clone());
138            env.record(Event {
139                block_id: self.block_id.clone(),
140                msg_id,
141                state: "sent",
142                seen_by: "sender",
143                source: me,
144                identity: "agent",
145                target: call.to.clone(),
146                claimed_name: None,
147                cli_to_name: Some(call.to),
148                sender_pid: None,
149                from_mode: None,
150                text: call.text,
151                reason: None,
152            });
153        }
154        Disposition::Keep
155    }
156
157    /// True the first time `id` is seen.
158    fn first(&mut self, id: &str) -> bool {
159        if self.seen.iter().any(|s| s == id) {
160            return false;
161        }
162        if self.seen.len() >= REMEMBERED {
163            self.seen.pop_front();
164        }
165        self.seen.push_back(id.to_string());
166        true
167    }
168
169    /// The CLI kept a message from its model. It did not say who sent it, so the
170    /// sender stays unverified, and not what it said.
171    fn held(&mut self, hold: frame::PeerHold, env: &dyn Env) {
172        if !self.first(&hold.message_uuid) {
173            return;
174        }
175        env.record(Event {
176            block_id: self.block_id.clone(),
177            msg_id: hold.message_uuid,
178            state: "held",
179            seen_by: "receiver",
180            source: "unverified sender".to_string(),
181            identity: "unverified",
182            target: env.agent_name(&self.block_id).unwrap_or_else(|| self.block_id.clone()),
183            claimed_name: hold.from_name,
184            cli_to_name: None,
185            sender_pid: None,
186            from_mode: None,
187            text: String::new(),
188            reason: Some(hold.cause),
189        });
190    }
191
192    fn received(&mut self, peer: PeerFrame, env: &dyn Env) {
193        if !self.first(&peer.msg_id) {
194            return;
195        }
196
197        let sender = sender::resolve(peer.pid, peer.proc_start.as_deref(), &env.cli_pids(), env.procs());
198        let (source, identity) = match &sender {
199            Sender::Agent { block_id } => (env.agent_name(block_id).unwrap_or_else(|| block_id.clone()), "agent"),
200            Sender::Outside { pid } => (format!("outside session (pid {pid})"), "outside"),
201            Sender::Unverified => ("unverified sender".to_string(), "unverified"),
202        };
203        let event = Event {
204            block_id: self.block_id.clone(),
205            msg_id: peer.msg_id,
206            state: "read",
207            seen_by: "receiver",
208            source,
209            identity,
210            target: env.agent_name(&self.block_id).unwrap_or_else(|| self.block_id.clone()),
211            claimed_name: peer.claimed_name,
212            cli_to_name: None,
213            sender_pid: peer.pid,
214            from_mode: peer.from_mode,
215            text: peer.body,
216            reason: None,
217        };
218        self.inbound.insert(peer.uuid, event.clone());
219        env.record(event);
220    }
221}
222
223#[cfg(test)]
224mod tests {
225    use super::*;
226    use serde_json::json;
227    use std::sync::Mutex;
228
229    struct Fake {
230        events: Mutex<Vec<Event>>,
231        parents: HashMap<u32, u32>,
232    }
233
234    impl Fake {
235        fn new() -> Self {
236            // Agent "alpha" runs its CLI as 100 (with a child 101); "beta" as 200; 300 is outside.
237            Self { events: Mutex::new(Vec::new()), parents: HashMap::from([(100, 10), (101, 100), (200, 10), (300, 20)]) }
238        }
239        fn events(&self) -> Vec<Event> {
240            self.events.lock().unwrap().clone()
241        }
242    }
243
244    impl ProcView for Fake {
245        fn parent(&self, pid: u32) -> Option<u32> {
246            self.parents.get(&pid).copied()
247        }
248        fn start_time(&self, _pid: u32) -> Option<u64> {
249            None
250        }
251    }
252
253    impl Env for Fake {
254        fn cli_pids(&self) -> Vec<(String, u32)> {
255            vec![("block-alpha".into(), 100), ("block-beta".into(), 200), ("block-me".into(), 400)]
256        }
257        fn procs(&self) -> &dyn ProcView {
258            self
259        }
260        fn agent_name(&self, block_id: &str) -> Option<String> {
261            block_id.strip_prefix("block-").map(str::to_string)
262        }
263        fn record(&self, event: Event) {
264            self.events.lock().unwrap().push(event);
265        }
266    }
267
268    fn peer(pid: u64, claimed: &str, msg_id: &str, uuid: &str) -> Value {
269        json!({"type":"user","message":{"role":"user","content":"<cross-session-message>…</cross-session-message>"},"uuid":uuid,"isReplay":true,"isSynthetic":true,
270            "origin":{"kind":"peer","from":"uds:/tmp/cc-socks/x.sock","verifiedPeerPid":pid,"msg_id":msg_id,"name":claimed,"fromMode":"bypass","body":"please look at #5561"}})
271    }
272
273    #[test]
274    fn a_message_is_read_then_done_under_the_name_agentmux_maps() {
275        let (env, mut r) = (Fake::new(), CliNativeReader::new("block-me", SentPrompts::default()));
276        assert_eq!(r.observe(&peer(101, "alpha-session-7", "m1", "u1"), &env), Disposition::Drop);
277        assert_eq!(r.observe(&json!({"type":"command_lifecycle","command_uuid":"u1","state":"started"}), &env), Disposition::Keep);
278        assert_eq!(r.observe(&json!({"type":"command_lifecycle","command_uuid":"u1","state":"completed"}), &env), Disposition::Keep);
279        let ev = env.events();
280        assert_eq!(ev.iter().map(|e| e.state).collect::<Vec<_>>(), ["read", "done"]);
281        assert_eq!((ev[0].source.as_str(), ev[0].identity, ev[0].target.as_str()), ("alpha", "agent", "me"));
282        assert_eq!((ev[0].seen_by, ev[0].sender_pid, ev[0].text.as_str()), ("receiver", Some(101), "please look at #5561"));
283        assert_eq!(ev[1].msg_id, "m1");
284    }
285
286    #[test]
287    fn a_claimed_name_never_becomes_the_sender() {
288        // A process under beta's CLI says it is alpha; a stranger says it is beta.
289        let (env, mut r) = (Fake::new(), CliNativeReader::new("block-me", SentPrompts::default()));
290        r.observe(&peer(200, "alpha", "m1", "u1"), &env);
291        r.observe(&peer(300, "beta", "m2", "u2"), &env);
292        r.observe(&peer(0, "alpha", "m3", "u3"), &env);
293        let ev = env.events();
294        assert_eq!((ev[0].source.as_str(), ev[0].claimed_name.as_deref()), ("beta", Some("alpha")));
295        assert_eq!((ev[1].source.as_str(), ev[1].identity, ev[1].claimed_name.as_deref()), ("outside session (pid 300)", "outside", Some("beta")));
296        assert_eq!((ev[2].source.as_str(), ev[2].identity), ("unverified sender", "unverified"));
297    }
298
299    #[test]
300    fn a_message_the_cli_holds_is_audited_as_held_with_its_cause_and_no_sender() {
301        let (env, mut r) = (Fake::new(), CliNativeReader::new("block-me", SentPrompts::default()));
302        let held = json!({"type":"system","subtype":"peer_message_hold","state":"held","message_uuid":"h1","from_name":"alpha","cause":"mode-mismatch"});
303        assert_eq!(r.observe(&held, &env), Disposition::Keep);
304        r.observe(&held, &env);
305        let ev = env.events();
306        assert_eq!(ev.len(), 1);
307        assert_eq!((ev[0].state, ev[0].identity, ev[0].source.as_str()), ("held", "unverified", "unverified sender"));
308        assert_eq!((ev[0].reason.as_deref(), ev[0].claimed_name.as_deref(), ev[0].text.as_str()), (Some("mode-mismatch"), Some("alpha"), ""));
309    }
310
311    #[test]
312    fn a_replayed_message_is_audited_once() {
313        let (env, mut r) = (Fake::new(), CliNativeReader::new("block-me", SentPrompts::default()));
314        r.observe(&peer(100, "alpha", "m1", "u1"), &env);
315        assert_eq!(r.observe(&peer(100, "alpha", "m1", "u1-again"), &env), Disposition::Drop);
316        assert_eq!(env.events().len(), 1);
317    }
318
319    #[test]
320    fn the_echo_of_a_turn_srv_wrote_leaves_the_stream_and_records_nothing() {
321        let sent = SentPrompts::default();
322        let tagged = sent.tag(r#"{"type":"user","message":{"role":"user","content":"hello"}}"#);
323        let uuid = serde_json::from_str::<Value>(&tagged).unwrap()["uuid"].as_str().unwrap().to_string();
324        let (env, mut r) = (Fake::new(), CliNativeReader::new("block-me", sent));
325        let echo = json!({"type":"user","message":{"role":"user","content":"hello"},"uuid":uuid,"isReplay":true});
326        assert_eq!(r.observe(&echo, &env), Disposition::Drop);
327        assert_eq!(r.observe(&echo, &env), Disposition::Keep, "an echo is dropped once");
328        assert!(env.events().is_empty());
329    }
330
331    #[test]
332    fn a_replayed_frame_of_the_clis_own_stays_in_the_stream() {
333        // The card a /compact leaves: the CLI marks it isReplay without the flag; srv wrote no turn for it.
334        let (env, mut r) = (Fake::new(), CliNativeReader::new("block-me", SentPrompts::default()));
335        let card = json!({"type":"user","message":{"role":"user","content":"<local-command-stdout>Compacted </local-command-stdout>"},"uuid":"51d8a799","isReplay":true});
336        assert_eq!(r.observe(&card, &env), Disposition::Keep);
337        let no_uuid = json!({"type":"user","message":{"role":"user","content":"x"},"isReplay":true});
338        assert_eq!(r.observe(&no_uuid, &env), Disposition::Keep);
339        assert!(env.events().is_empty());
340    }
341
342    #[test]
343    fn a_sent_message_is_audited_when_the_cli_accepts_it() {
344        let (env, mut r) = (Fake::new(), CliNativeReader::new("block-me", SentPrompts::default()));
345        let call = json!({"type":"assistant","message":{"content":[{"type":"tool_use","id":"t1","name":"SendMessage","input":{"to":"recv-82","message":"hello"}}]}});
346        assert_eq!(r.observe(&call, &env), Disposition::Keep);
347        assert!(env.events().is_empty(), "nothing before the CLI answers");
348        let answer = json!({"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"t1","content":[{"type":"text","text":"{\"success\":true,\"msg_id\":\"m9\"}"}]}]}});
349        assert_eq!(r.observe(&answer, &env), Disposition::Keep);
350        let ev = env.events();
351        assert_eq!(ev.len(), 1);
352        assert_eq!((ev[0].state, ev[0].seen_by, ev[0].source.as_str(), ev[0].target.as_str()), ("sent", "sender", "me", "recv-82"));
353        assert_eq!((ev[0].msg_id.as_str(), ev[0].cli_to_name.as_deref(), ev[0].text.as_str()), ("m9", Some("recv-82"), "hello"));
354    }
355
356    #[test]
357    fn a_refused_send_and_another_tool_record_nothing() {
358        let (env, mut r) = (Fake::new(), CliNativeReader::new("block-me", SentPrompts::default()));
359        let calls = json!({"type":"assistant","message":{"content":[
360            {"type":"tool_use","id":"t1","name":"SendMessage","input":{"to":"x","message":"m"}},
361            {"type":"tool_use","id":"t2","name":"mcp__agentmux__SendMessage","input":{"to":"y","message":"m"}}]}});
362        r.observe(&calls, &env);
363        let answers = json!({"type":"user","message":{"content":[
364            {"type":"tool_result","tool_use_id":"t1","content":"Error: no such session","is_error":true},
365            {"type":"tool_result","tool_use_id":"t2","content":"{\"success\":true,\"msg_id\":\"jekt\"}"}]}});
366        r.observe(&answers, &env);
367        assert!(env.events().is_empty());
368    }
369
370    #[test]
371    fn ordinary_frames_are_kept() {
372        let (env, mut r) = (Fake::new(), CliNativeReader::new("block-me", SentPrompts::default()));
373        for f in [json!({"type":"assistant","message":{"content":[{"type":"text","text":"hi"}]}}), json!({"type":"result"}), json!({"type":"system","subtype":"init"})] {
374            assert_eq!(r.observe(&f, &env), Disposition::Keep);
375        }
376    }
377}