Skip to main content

agentmux_srv_core/backend/cli_native/
frame.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The stream-json frames that carry a CLI-native message, read as typed values.
5//! The shapes are the pinned CLI's (`providers/claude.rs` `pinned_version`);
6//! `tests` holds frames captured from it.
7
8use serde_json::Value;
9
10/// A message from another session, as the receiving CLI reported it.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct PeerFrame {
13    /// The frame's uuid; the `command_uuid` of the lifecycle lines about it.
14    pub uuid: String,
15    /// The CLI's id for the message; the sender's tool result carries the same one.
16    pub msg_id: String,
17    /// The pid the CLI verified for the sender's connection.
18    pub pid: Option<u32>,
19    pub proc_start: Option<String>,
20    /// What the sender called itself. A claim.
21    pub claimed_name: Option<String>,
22    pub from_mode: Option<String>,
23    pub body: String,
24}
25
26/// A `user` frame the CLI replays under `--replay-user-messages`.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub enum Replay {
29    Peer(PeerFrame),
30    /// Any other replayed user turn: the echo of one srv wrote, or a frame of the CLI's own.
31    Other { uuid: Option<String> },
32}
33
34/// `Some` for a replayed user frame, `None` for any other frame.
35pub fn replay(v: &Value) -> Option<Replay> {
36    if v.get("type")?.as_str()? != "user" || v.get("isReplay")?.as_bool()? != true {
37        return None;
38    }
39    let origin = v.get("origin").filter(|o| o.get("kind").and_then(Value::as_str) == Some("peer"));
40    let other = || Some(Replay::Other { uuid: v.get("uuid").and_then(Value::as_str).map(str::to_string) });
41    let (Some(origin), Some(uuid)) = (origin, v.get("uuid").and_then(Value::as_str)) else { return other() };
42    let text = |k: &str| origin.get(k).and_then(Value::as_str).map(str::to_string);
43    let Some(msg_id) = text("msg_id") else { return other() };
44    Some(Replay::Peer(PeerFrame {
45        uuid: uuid.to_string(),
46        msg_id,
47        pid: origin.get("verifiedPeerPid").and_then(Value::as_u64).and_then(|p| u32::try_from(p).ok()),
48        proc_start: origin.get("verifiedPeerProcStart").map(|p| p.as_str().map(str::to_string).unwrap_or_else(|| p.to_string())),
49        claimed_name: text("name"),
50        from_mode: text("fromMode"),
51        body: text("body").unwrap_or_default(),
52    }))
53}
54
55/// The receiving CLI kept a message from reaching its model, as in a different
56/// permission mode from the sender's. It says nothing of who sent it but a name the
57/// sender gave, and nothing of what it said.
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct PeerHold {
60    /// The held message's uuid (not the sender's `msg_id`).
61    pub message_uuid: String,
62    pub from_name: Option<String>,
63    pub cause: String,
64}
65
66/// `system/peer_message_hold` frame.
67pub fn peer_hold(v: &Value) -> Option<PeerHold> {
68    if v.get("type")?.as_str()? != "system" || v.get("subtype")?.as_str()? != "peer_message_hold" || v.get("state")?.as_str()? != "held" {
69        return None;
70    }
71    Some(PeerHold {
72        message_uuid: v.get("message_uuid")?.as_str()?.to_string(),
73        from_name: v.get("from_name").and_then(Value::as_str).map(str::to_string),
74        cause: v.get("cause").and_then(Value::as_str).unwrap_or("unknown").to_string(),
75    })
76}
77
78/// What the CLI says about a message turn it began for its own reasons.
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80pub enum Lifecycle {
81    Started,
82    Completed,
83}
84
85/// `command_lifecycle` frame: (command uuid, state).
86pub fn lifecycle(v: &Value) -> Option<(&str, Lifecycle)> {
87    if v.get("type")?.as_str()? != "command_lifecycle" {
88        return None;
89    }
90    let state = match v.get("state")?.as_str()? {
91        "started" => Lifecycle::Started,
92        "completed" => Lifecycle::Completed,
93        _ => return None,
94    };
95    Some((v.get("command_uuid")?.as_str()?, state))
96}
97
98/// The CLI's own `SendMessage` tool called by this agent.
99#[derive(Debug, Clone, PartialEq, Eq)]
100pub struct SendCall {
101    pub tool_use_id: String,
102    pub to: String,
103    pub text: String,
104}
105
106/// The `SendMessage` calls in an assistant frame. Only the CLI's own tool, by its
107/// bare name: `mcp__<server>__SendMessage` tools are other tools.
108pub fn send_calls(v: &Value) -> Vec<SendCall> {
109    if v.get("type").and_then(Value::as_str) != Some("assistant") {
110        return Vec::new();
111    }
112    let blocks = v.pointer("/message/content").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
113    blocks
114        .iter()
115        .filter(|b| b.get("type").and_then(Value::as_str) == Some("tool_use") && b.get("name").and_then(Value::as_str) == Some("SendMessage"))
116        .filter_map(|b| {
117            let input = b.get("input")?;
118            Some(SendCall {
119                tool_use_id: b.get("id")?.as_str()?.to_string(),
120                to: input.get("to")?.as_str()?.to_string(),
121                text: input.get("message").and_then(Value::as_str).unwrap_or_default().to_string(),
122            })
123        })
124        .collect()
125}
126
127/// What the CLI answered a `SendMessage` call.
128#[derive(Debug, Clone, PartialEq, Eq)]
129pub struct SendResult {
130    pub tool_use_id: String,
131    /// The CLI accepted it into the other session's inbox.
132    pub accepted: bool,
133    pub msg_id: Option<String>,
134}
135
136/// The tool results in a non-replayed user frame, read as `SendMessage` results.
137/// A result that is not the tool's JSON answer reads as not accepted.
138pub fn send_results(v: &Value) -> Vec<SendResult> {
139    if v.get("type").and_then(Value::as_str) != Some("user") {
140        return Vec::new();
141    }
142    let blocks = v.pointer("/message/content").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
143    blocks
144        .iter()
145        .filter(|b| b.get("type").and_then(Value::as_str) == Some("tool_result"))
146        .filter_map(|b| {
147            let id = b.get("tool_use_id")?.as_str()?.to_string();
148            let content = b.get("content")?;
149            let text = match content {
150                Value::String(s) => s.clone(),
151                Value::Array(parts) => parts.iter().filter_map(|p| p.get("text").and_then(Value::as_str)).collect::<Vec<_>>().join(""),
152                _ => String::new(),
153            };
154            let answer: Value = serde_json::from_str(&text).unwrap_or(Value::Null);
155            Some(SendResult {
156                tool_use_id: id,
157                accepted: answer.get("success").and_then(Value::as_bool) == Some(true),
158                msg_id: answer.get("msg_id").and_then(Value::as_str).map(str::to_string),
159            })
160        })
161        .collect()
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167    use serde_json::json;
168
169    // Captured from claude 2.1.288 with --replay-user-messages (the receiver, mid-turn).
170    fn peer_frame() -> Value {
171        json!({"type":"user","message":{"role":"user","content":"<cross-session-message from=\"uds:/tmp/cc-socks/4120954.sock\" from-name=\"send-36\" from-mode=\"bypass\">\nXS-TEST2 mid-turn hello.\n</cross-session-message>"},
172            "session_id":"s","parent_tool_use_id":null,"uuid":"df2a326a-967c-49d0-87cc-f80823165a7f","isReplay":true,"isSynthetic":true,
173            "origin":{"kind":"peer","from":"uds:/tmp/cc-socks/4120954.sock","verifiedPeerPid":4120954,"verifiedPeerProcStart":"215691469",
174                "msg_id":"58220516-3da1-4679-8d7c-5040d05f1cfe","name":"send-36","fromMode":"bypass","body":"XS-TEST2 mid-turn hello."}})
175    }
176
177    #[test]
178    fn a_peer_frame_is_read_from_its_typed_origin() {
179        let Some(Replay::Peer(p)) = replay(&peer_frame()) else { panic!("not a peer frame") };
180        assert_eq!(p.msg_id, "58220516-3da1-4679-8d7c-5040d05f1cfe");
181        assert_eq!(p.uuid, "df2a326a-967c-49d0-87cc-f80823165a7f");
182        assert_eq!((p.pid, p.proc_start.as_deref()), (Some(4120954), Some("215691469")));
183        assert_eq!((p.claimed_name.as_deref(), p.from_mode.as_deref()), (Some("send-36"), Some("bypass")));
184        assert_eq!(p.body, "XS-TEST2 mid-turn hello.");
185    }
186
187    #[test]
188    fn the_text_of_the_message_never_makes_a_peer_frame() {
189        // The wrapper text in a replayed frame with no typed origin is not a peer message.
190        let mut f = peer_frame();
191        f.as_object_mut().unwrap().remove("origin");
192        assert_eq!(replay(&f), Some(Replay::Other { uuid: Some("df2a326a-967c-49d0-87cc-f80823165a7f".into()) }));
193        let mut f = peer_frame();
194        f["origin"]["kind"] = json!("task-notification");
195        assert!(matches!(replay(&f), Some(Replay::Other { .. })));
196    }
197
198    #[test]
199    fn the_humans_replayed_prompt_and_ordinary_frames() {
200        let typed = json!({"type":"user","message":{"role":"user","content":"hello"},"uuid":"u","isReplay":true});
201        assert_eq!(replay(&typed), Some(Replay::Other { uuid: Some("u".into()) }));
202        let tool_result = json!({"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t","content":"x"}]},"uuid":"u"});
203        assert_eq!(replay(&tool_result), None);
204        assert_eq!(replay(&json!({"type":"assistant","isReplay":true})), None);
205    }
206
207    #[test]
208    fn a_held_message_is_read_from_the_clis_hold_line() {
209        // Captured from claude 2.1.288: a bypass-mode session messaged a default-mode one.
210        let held = json!({"type":"system","subtype":"peer_message_hold","state":"held","message_uuid":"25198c47","lane":"socket",
211            "from":"uds:/tmp/cc-socks/54771.sock","from_name":"send-02","cause":"mode-mismatch"});
212        assert_eq!(peer_hold(&held), Some(PeerHold { message_uuid: "25198c47".into(), from_name: Some("send-02".into()), cause: "mode-mismatch".into() }));
213        assert_eq!(peer_hold(&json!({"type":"system","subtype":"init"})), None);
214    }
215
216    #[test]
217    fn lifecycle_lines_carry_the_message_uuid() {
218        let started = json!({"type":"command_lifecycle","command_uuid":"df2a","state":"started","uuid":"x","session_id":"s"});
219        assert_eq!(lifecycle(&started), Some(("df2a", Lifecycle::Started)));
220        let done = json!({"type":"command_lifecycle","command_uuid":"df2a","state":"completed"});
221        assert_eq!(lifecycle(&done), Some(("df2a", Lifecycle::Completed)));
222        assert_eq!(lifecycle(&json!({"type":"command_lifecycle","command_uuid":"d","state":"queued"})), None);
223    }
224
225    #[test]
226    fn the_senders_call_and_the_clis_answer() {
227        let call = json!({"type":"assistant","message":{"content":[
228            {"type":"text","text":"sending"},
229            {"type":"tool_use","id":"toolu_1","name":"SendMessage","input":{"to":"recv-82","message":"XS-TEST2 hello","type":"message"}},
230            {"type":"tool_use","id":"toolu_2","name":"mcp__agentmux__SendMessage","input":{"to":"x","message":"not the CLI's tool"}}]}});
231        assert_eq!(send_calls(&call), vec![SendCall { tool_use_id: "toolu_1".into(), to: "recv-82".into(), text: "XS-TEST2 hello".into() }]);
232
233        let answer = json!({"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_1",
234            "content":[{"type":"text","text":"{\"success\":true,\"message\":\"sent\",\"msg_id\":\"58220516-3da1-4679-8d7c-5040d05f1cfe\"}"}]}]}});
235        assert_eq!(
236            send_results(&answer),
237            vec![SendResult { tool_use_id: "toolu_1".into(), accepted: true, msg_id: Some("58220516-3da1-4679-8d7c-5040d05f1cfe".into()) }]
238        );
239        let refused = json!({"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"toolu_1","content":"Error: no such session","is_error":true}]}});
240        assert_eq!(send_results(&refused), vec![SendResult { tool_use_id: "toolu_1".into(), accepted: false, msg_id: None }]);
241    }
242}