Skip to main content

agentmux_srv_core/backend/blockcontroller/
msp_session.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The MSP client's state: the handshake, the session, which turns are still
5//! running, and what each line from `muse serve` asks of the controller. No
6//! I/O, so the controller's whole reaction to a line is testable without a
7//! process (`MspController` in msp.rs does the I/O).
8//!
9//! Handshake: `initialize` → `initialized` → `session/start` (or
10//! `session/resume` of the pane's previous session, falling back to a new
11//! one). A turn is a `turn/start` command whose ack names its turn; the turn
12//! ends with the `turn/completed` notification.
13
14use std::collections::HashSet;
15
16use serde_json::{Map, Value};
17
18use super::msp_protocol as proto;
19
20/// What one line from the host asks of the controller.
21#[derive(Debug, Default, PartialEq)]
22pub(super) struct Effects {
23    /// Lines to write to the host's stdin, in order.
24    pub send: Vec<String>,
25    /// Keep the line out of the transcript: an error the client recovered
26    /// from, or the answer to a command the pane didn't send.
27    pub hide: bool,
28    /// Lines to write to the transcript after this one.
29    pub append: Vec<String>,
30    /// A session the controller now drives, to persist as `agent:sessionid`.
31    pub session: Option<String>,
32    /// The turn started (`true`) or every turn ended (`false`).
33    pub turn_active: Option<bool>,
34}
35
36/// The MSP client of one `muse serve` process.
37pub(super) struct MspSession {
38    next_id: u64,
39    cwd: String,
40    mcp_servers: Map<String, Value>,
41    /// The session to resume instead of starting one.
42    resume: Option<String>,
43    init_id: Option<u64>,
44    /// The `session/start` or `session/resume` in flight, and whether it is a
45    /// resume.
46    session_req: Option<(u64, bool)>,
47    session_id: Option<String>,
48    /// The session couldn't open: nothing runs until the agent restarts.
49    failed: bool,
50    /// Messages sent before the session opened, joined.
51    pending: Option<String>,
52    /// `turn/start`s sent and not answered yet.
53    turn_requests: HashSet<u64>,
54    /// Turns the host started (or queued) that haven't completed.
55    open_turns: HashSet<String>,
56    /// Turns that completed while a `turn/start` was unanswered: its late ack
57    /// may name one, which must not count as running again.
58    ended_turns: HashSet<String>,
59    /// Commands srv sent on its own (decisions, cancels, interrupts): an
60    /// error answering one is logged, not shown.
61    quiet: HashSet<u64>,
62    /// Approvals already decided, by approval and stage.
63    decided: HashSet<String>,
64}
65
66impl MspSession {
67    pub(super) fn new() -> Self {
68        Self {
69            next_id: 1,
70            cwd: String::new(),
71            mcp_servers: Map::new(),
72            resume: None,
73            init_id: None,
74            session_req: None,
75            session_id: None,
76            failed: false,
77            pending: None,
78            turn_requests: HashSet::new(),
79            open_turns: HashSet::new(),
80            ended_turns: HashSet::new(),
81            quiet: HashSet::new(),
82            decided: HashSet::new(),
83        }
84    }
85
86    fn id(&mut self) -> u64 {
87        let id = self.next_id;
88        self.next_id += 1;
89        id
90    }
91
92    /// A new process: the handshake starts over, in `cwd`, with these MCP
93    /// servers, resuming `resume` when given. A message still waiting for a
94    /// session waits for the new one. Returns the `initialize` request.
95    pub(super) fn begin(&mut self, cwd: String, mcp_servers: Map<String, Value>, resume: Option<String>) -> String {
96        let pending = self.pending.take();
97        *self = Self { next_id: self.next_id, ..Self::new() };
98        self.pending = pending;
99        self.cwd = cwd;
100        self.mcp_servers = mcp_servers;
101        self.resume = resume;
102        let id = self.id();
103        self.init_id = Some(id);
104        proto::request(id, "initialize", proto::initialize_params())
105    }
106
107    pub(super) fn session_id(&self) -> Option<&str> {
108        self.session_id.as_deref()
109    }
110
111    /// The session is over for good (`Agents fresh`): the id that was open, or the one still waiting to be resumed (after an
112    /// idle `session/closed`, or while a `session/resume` is in flight), comes back, and nothing is left to resume.
113    pub(super) fn forget_session(&mut self) -> Option<String> {
114        let resume = self.resume.take();
115        self.session_id.take().or(resume)
116    }
117
118    /// A turn is running, or a message waits to start one.
119    pub(super) fn turn_active(&self) -> bool {
120        !self.turn_requests.is_empty() || !self.open_turns.is_empty() || self.pending.is_some()
121    }
122
123    /// Work the process was doing when it exited: a turn, or a message
124    /// waiting for a session. Forgets it; the caller tells the pane.
125    pub(super) fn process_ended(&mut self) -> bool {
126        let had_work = self.turn_active();
127        self.pending = None;
128        self.turn_requests.clear();
129        self.open_turns.clear();
130        self.ended_turns.clear();
131        self.session_id = None;
132        had_work
133    }
134
135    fn session_request(&mut self, resume: bool) -> String {
136        let id = self.id();
137        self.session_req = Some((id, resume));
138        let resume_id = if resume { self.resume.clone() } else { None };
139        let (method, params) = proto::session_request(resume_id.as_deref(), &self.cwd, &self.mcp_servers);
140        proto::request(id, method, params)
141    }
142
143    fn turn_start(&mut self, session_id: &str, text: &str) -> (u64, String) {
144        let id = self.id();
145        self.turn_requests.insert(id);
146        (id, proto::request(id, "turn/start", proto::turn_start_params(session_id, text)))
147    }
148
149    /// The user's message. `Ok(Some((id, line)))`: send it (the turn is now
150    /// active). `Ok(None)`: it waits for the session, which a closed session
151    /// is reopened for (the returned line). `Err`: the session can't open.
152    pub(super) fn prompt(&mut self, text: &str) -> Result<PromptOutcome, String> {
153        if let Some(sid) = self.session_id.clone() {
154            let (id, line) = self.turn_start(&sid, text);
155            return Ok(PromptOutcome::Send { id, line });
156        }
157        if self.failed {
158            return Err("Muse Code couldn't open a session (see the error above). Fix that, then restart the agent.".to_string());
159        }
160        self.pending = Some(match self.pending.take() {
161            Some(earlier) => format!("{earlier}\n\n{text}"),
162            None => text.to_string(),
163        });
164        // The host unloaded the session (`session/closed`): load it again.
165        let reopen = (self.init_id.is_none() && self.session_req.is_none() && self.resume.is_some())
166            .then(|| self.session_request(true));
167        Ok(PromptOutcome::Queued { reopen })
168    }
169
170    /// A `turn/start` that never reached the host: forgotten. True when no
171    /// turn is left running.
172    pub(super) fn prompt_unsent(&mut self, id: u64) -> bool {
173        self.turn_requests.remove(&id);
174        !self.turn_active()
175    }
176
177    /// `turn/interrupt` for the running turn, when there is one to stop.
178    pub(super) fn interrupt(&mut self) -> Option<String> {
179        let sid = self.session_id.clone()?;
180        if self.turn_requests.is_empty() && self.open_turns.is_empty() {
181            return None;
182        }
183        let id = self.id();
184        self.quiet.insert(id);
185        Some(proto::request(id, "turn/interrupt", proto::turn_interrupt_params(&sid)))
186    }
187
188    /// React to one line from the host.
189    pub(super) fn on_message(&mut self, msg: &Value) -> Effects {
190        let mut fx = Effects::default();
191        let method = msg.get("method").and_then(Value::as_str);
192        match (method, msg.get("id")) {
193            (Some(method), Some(id)) => self.on_host_request(method, id, msg.get("params"), &mut fx),
194            (Some(method), None) => self.on_notification(method, msg.get("params"), &mut fx),
195            (None, Some(id)) => match id.as_u64() {
196                Some(id) => self.on_response(id, msg, &mut fx),
197                None => {}
198            },
199            (None, None) => {}
200        }
201        fx
202    }
203
204    fn on_host_request(&mut self, method: &str, id: &Value, params: Option<&Value>, fx: &mut Effects) {
205        fx.send.push(proto::reply_to_host_request(id, method));
206        let Some(params) = params else { return };
207        let command = match method {
208            "approval/request" => {
209                let key = format!("{}:{}", params["approvalId"], params["currentRequirementId"]);
210                if !self.decided.insert(key) {
211                    return;
212                }
213                proto::approval_decide_params(params).map(|p| ("approval/decide", p))
214            }
215            "userInput/request" => proto::user_input_cancel_params(params).map(|p| ("userInput/cancel", p)),
216            _ => None,
217        };
218        if let Some((method, p)) = command {
219            let id = self.id();
220            self.quiet.insert(id);
221            fx.send.push(proto::request(id, method, p));
222        }
223    }
224
225    fn on_notification(&mut self, method: &str, params: Option<&Value>, fx: &mut Effects) {
226        let turn_id = params.and_then(|p| p.get("turnId")).and_then(Value::as_str).filter(|t| !t.is_empty());
227        let ours = |p: Option<&Value>, sid: &Option<String>| {
228            sid.is_some() && p.and_then(|p| p.get("sessionId")).and_then(Value::as_str) == sid.as_deref()
229        };
230        match method {
231            "turn/started" => {
232                if let Some(t) = turn_id {
233                    if !self.ended_turns.contains(t) && self.open_turns.insert(t.to_string()) {
234                        fx.turn_active = Some(true);
235                    }
236                }
237            }
238            "turn/completed" => {
239                if let Some(t) = turn_id {
240                    self.open_turns.remove(t);
241                    if !self.turn_requests.is_empty() {
242                        self.ended_turns.insert(t.to_string());
243                    }
244                }
245                self.settle(fx);
246            }
247            "session/closed" if ours(params, &self.session_id) => {
248                // Unloaded while idle: the next message loads it again.
249                self.resume = self.session_id.take();
250                self.open_turns.clear();
251            }
252            _ => {}
253        }
254    }
255
256    fn on_response(&mut self, id: u64, msg: &Value, fx: &mut Effects) {
257        let error = msg.get("error");
258        let result = msg.get("result");
259        if self.init_id == Some(id) {
260            self.init_id = None;
261            match result {
262                Some(r) => self.on_initialized(r, fx),
263                None => self.fail(fx),
264            }
265        } else if self.session_req.map(|(sid, _)| sid) == Some(id) {
266            let (_, was_resume) = self.session_req.take().unwrap_or_default();
267            let opened = result.and_then(|r| r.pointer("/session/sessionId")).and_then(Value::as_str);
268            match (opened, error) {
269                (Some(sid), _) => {
270                    self.session_id = Some(sid.to_string());
271                    self.resume = None;
272                    fx.session = Some(sid.to_string());
273                    if let Some(text) = self.pending.take() {
274                        let sid = sid.to_string();
275                        let (_, line) = self.turn_start(&sid, &text);
276                        fx.send.push(line);
277                        fx.turn_active = Some(true);
278                    }
279                }
280                (None, Some(_)) if was_resume => {
281                    // The previous session is gone: a new one instead.
282                    tracing::info!(error = %msg, "[msp] session/resume refused; starting a new session");
283                    fx.hide = true;
284                    self.resume = None;
285                    let line = self.session_request(false);
286                    fx.send.push(line);
287                }
288                _ => self.fail(fx),
289            }
290        } else if self.turn_requests.remove(&id) {
291            if let Some(r) = result {
292                let disposition = r.get("disposition").and_then(Value::as_str).unwrap_or("started");
293                let turn = r.get("turnId").and_then(Value::as_str).filter(|t| !t.is_empty());
294                if let Some(t) = turn.filter(|_| matches!(disposition, "started" | "queued" | "steered")) {
295                    if !self.ended_turns.contains(t) {
296                        self.open_turns.insert(t.to_string());
297                    }
298                }
299            }
300            if !self.turn_active() && error.is_some() {
301                // Refused: no `turn/completed` will come for it.
302                fx.append.push(proto::TURN_ENDED_BY_SRV.to_string());
303            }
304            self.settle(fx);
305        } else if self.quiet.remove(&id) {
306            if error.is_some() {
307                tracing::info!(error = %msg, "[msp] a command srv sent was refused");
308            }
309            fx.hide = true;
310        }
311    }
312
313    /// `initialize` answered: check the schema, say `initialized`, open the
314    /// session.
315    fn on_initialized(&mut self, result: &Value, fx: &mut Effects) {
316        let fingerprint = result.pointer("/schema/fingerprint").and_then(Value::as_str).unwrap_or("");
317        if fingerprint != proto::MSP_SCHEMA_FINGERPRINT {
318            tracing::warn!(fingerprint, expected = proto::MSP_SCHEMA_FINGERPRINT, "[msp] the host's schema differs from the one AgentMux was written against");
319        }
320        let granted = result
321            .get("grantedCapabilities")
322            .and_then(Value::as_array)
323            .is_some_and(|caps| caps.iter().any(|c| c == "sessionMcp"));
324        if !granted && !self.mcp_servers.is_empty() {
325            tracing::warn!("[msp] the host didn't grant sessionMcp; starting the session without AgentMux's MCP servers");
326            self.mcp_servers.clear();
327        }
328        fx.send.push(proto::notification("initialized"));
329        let resume = self.resume.is_some();
330        let line = self.session_request(resume);
331        fx.send.push(line);
332    }
333
334    /// The handshake failed: no session until the agent restarts. A message
335    /// that was waiting for it ends its turn.
336    fn fail(&mut self, fx: &mut Effects) {
337        self.failed = true;
338        if self.pending.take().is_some() {
339            fx.append.push(proto::TURN_ENDED_BY_SRV.to_string());
340        }
341        self.settle(fx);
342    }
343
344    /// Report the end of the last turn once nothing is left running.
345    fn settle(&mut self, fx: &mut Effects) {
346        if !self.turn_active() {
347            self.ended_turns.clear();
348            fx.turn_active = Some(false);
349        }
350    }
351}
352
353/// What `MspSession::prompt` decided.
354#[derive(Debug, PartialEq)]
355pub(super) enum PromptOutcome {
356    /// Write `line`, the `turn/start` request `id`.
357    Send { id: u64, line: String },
358    /// The message waits for the session; write `reopen` first when given.
359    Queued { reopen: Option<String> },
360}