Skip to main content

agentmux_srv_core/backend/blockcontroller/
msp.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! MspController: Muse Code over the Muse Session Protocol (MSP), `muse
5//! serve`'s newline-delimited JSON-RPC 2.0 on stdio. Shaped like the ACP
6//! controller (acp.rs): one long-lived process, one session in it, each user
7//! message a turn, every line the host writes kept in the pane's transcript
8//! for the frontend's `msp-translator.ts`. The protocol state lives in
9//! `msp_session.rs`; this file spawns the process and moves lines.
10//!
11//! SPEC_NINE_NEW_HARNESSES_2026_10_14.md §4, §7.7.
12
13#[cfg(windows)]
14use agentmux_common::win32::NoWindow;
15use std::collections::{HashMap, VecDeque};
16use std::sync::{Arc, Mutex};
17
18use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
19use tokio::sync::mpsc;
20
21use super::health::TurnActivityTracker;
22use super::msp_session::{MspSession, PromptOutcome};
23use super::{
24    agent_runtime_status, core, BlockControllerRuntimeStatus, BlockInputUnion, Controller, BLOCK_CONTROLLER_MSP,
25    STATUS_DONE, STATUS_INIT, STATUS_RUNNING,
26};
27use crate::backend::eventbus::EventBus;
28use crate::backend::mps;
29use crate::backend::storage::filestore::FileStore;
30use crate::backend::storage::store::Store;
31
32/// MPS file subject the transcript is written to (the ACP controller's too).
33const MSP_OUTPUT_SUBJECT: &str = "output";
34
35/// How many of the host's last stderr lines are kept, for the error shown
36/// when it exits mid-turn.
37const STDERR_TAIL_LINES: usize = 12;
38
39struct MspInner {
40    proc_status: String,
41    proc_exit_code: i32,
42    status_version: i32,
43    current_pid: Option<u32>,
44    stdin_tx: Option<mpsc::Sender<String>>,
45    kill_tx: Option<tokio::sync::oneshot::Sender<bool>>,
46    /// Counts spawns, so a finished process's waiter leaves a newer one alone.
47    generation: u64,
48    session: MspSession,
49    stderr_tail: VecDeque<String>,
50    /// Sessions `Agents fresh` ended: a launch built from a pane meta read before the id was cleared must not resume one.
51    retired_sessions: Vec<String>,
52}
53
54/// Drives one `muse serve` process for an agent pane.
55pub struct MspController {
56    block_id: String,
57    inner: Arc<Mutex<MspInner>>,
58    broker: Option<Arc<mps::Broker>>,
59    event_bus: Option<Arc<EventBus>>,
60    mstore: Option<Arc<Store>>,
61    filestore: Option<Arc<FileStore>>,
62    health_monitor: Arc<TurnActivityTracker>,
63    /// Serializes `ensure_started`, so two deliveries can't both start it.
64    start_lock: Mutex<()>,
65    /// srv's auth key, for the agent's `agentmux-mcp` (see the ACP controller).
66    auth_key: String,
67}
68
69/// The session a launch resumes: the pane's saved one, unless `Agents fresh` ended it (a message that raced the fresh start
70/// can launch from a pane meta read before the id was cleared).
71fn resume_id(block_meta: &super::super::obj::MetaMapType, retired: &[String]) -> Option<String> {
72    let saved = super::super::obj::meta_get_string(block_meta, core::META_SESSION_ID, "");
73    Some(saved).filter(|s| !s.is_empty() && !retired.contains(s))
74}
75
76/// What the reader, waiter and senders share: enough to publish the turn's
77/// state and write lines to the transcript.
78#[derive(Clone)]
79struct Outlet {
80    block_id: String,
81    inner: Arc<Mutex<MspInner>>,
82    broker: Option<Arc<mps::Broker>>,
83    filestore: Option<Arc<FileStore>>,
84    health: Arc<TurnActivityTracker>,
85    zone: Option<String>,
86}
87
88impl Outlet {
89    fn write(&self, line: &str) {
90        if let Some(ref broker) = self.broker {
91            let data = format!("{line}\n");
92            super::shell::handle_append_block_file(
93                broker,
94                &self.block_id,
95                MSP_OUTPUT_SUBJECT,
96                data.as_bytes(),
97                self.filestore.as_ref(),
98                self.zone.as_deref(),
99            );
100        }
101    }
102
103    fn set_turn(&self, inner: &MspInner, active: bool) {
104        publish_turn(&self.block_id, self.broker.as_ref(), &self.health, inner, active);
105    }
106}
107
108/// Set the turn's state and publish it, so the pane and the fleet see a turn
109/// start and end as it happens.
110fn publish_turn(block_id: &str, broker: Option<&Arc<mps::Broker>>, health: &TurnActivityTracker, inner: &MspInner, active: bool) {
111    if active {
112        health.mark_turn_active_returning_was_active();
113    } else {
114        health.set_active_turn(false);
115    }
116    if let Some(broker) = broker {
117        let status = agent_runtime_status(block_id, inner.status_version, &inner.proc_status, inner.proc_exit_code, active);
118        super::publish_controller_status(broker, &status);
119    }
120}
121
122impl MspController {
123    pub fn new(
124        block_id: String,
125        broker: Option<Arc<mps::Broker>>,
126        event_bus: Option<Arc<EventBus>>,
127        mstore: Option<Arc<Store>>,
128        filestore: Option<Arc<FileStore>>,
129    ) -> Self {
130        let health_monitor = Arc::new(TurnActivityTracker::for_block(block_id.clone(), broker.as_ref()));
131        Self {
132            block_id,
133            inner: Arc::new(Mutex::new(MspInner {
134                proc_status: STATUS_INIT.to_string(),
135                proc_exit_code: 0,
136                status_version: 0,
137                current_pid: None,
138                stdin_tx: None,
139                kill_tx: None,
140                generation: 0,
141                session: MspSession::new(),
142                stderr_tail: VecDeque::new(),
143                retired_sessions: Vec::new(),
144            })),
145            broker,
146            event_bus,
147            mstore,
148            filestore,
149            health_monitor,
150            start_lock: Mutex::new(()),
151            auth_key: String::new(),
152        }
153    }
154
155    /// The server auth key `agentmux-mcp` needs to reach srv.
156    pub fn with_auth_key(mut self, auth_key: String) -> Self {
157        self.auth_key = auth_key;
158        self
159    }
160
161    fn outlet(&self) -> Outlet {
162        Outlet {
163            block_id: self.block_id.clone(),
164            inner: self.inner.clone(),
165            broker: self.broker.clone(),
166            filestore: self.filestore.clone(),
167            health: self.health_monitor.clone(),
168            zone: crate::backend::transcript::append::resolve_global_output_zone(&self.mstore, &self.block_id),
169        }
170    }
171
172    fn set_turn(&self, inner: &MspInner, active: bool) {
173        publish_turn(&self.block_id, self.broker.as_ref(), &self.health_monitor, inner, active);
174    }
175
176    fn set_status(inner: &mut MspInner, status: &str) {
177        inner.proc_status = status.to_string();
178        inner.status_version += 1;
179    }
180
181    fn publish_status(&self) {
182        if let Some(ref broker) = self.broker {
183            super::publish_controller_status(broker, &self.get_status_snapshot());
184        }
185    }
186
187    fn get_status_snapshot(&self) -> BlockControllerRuntimeStatus {
188        let inner = self.inner.lock().unwrap();
189        agent_runtime_status(&self.block_id, inner.status_version, &inner.proc_status, inner.proc_exit_code, self.health_monitor.is_active_turn())
190            .spawned_at(self.health_monitor.spawned_at_ms())
191    }
192
193    pub(crate) fn is_running(&self) -> bool {
194        self.inner.lock().unwrap().stdin_tx.is_some()
195    }
196
197    /// Start the agent again if its process has exited; a no-op while it runs.
198    pub fn ensure_started(&self, block_meta: super::super::obj::MetaMapType) -> Result<(), String> {
199        let _one_at_a_time = self.start_lock.lock().unwrap();
200        if self.is_running() {
201            return Ok(());
202        }
203        Controller::start(self, block_meta, None, false)
204    }
205
206    /// The session id saved in the pane's meta: what the next launch would resume.
207    fn saved_session_id(&self) -> Option<String> {
208        let block = self.mstore.as_ref()?.get::<super::super::obj::Block>(&self.block_id).ok()??;
209        Some(super::super::obj::meta_get_string(&block.meta, core::META_SESSION_ID, "")).filter(|s| !s.is_empty())
210    }
211
212    /// Ends the agent's session so the next message opens a new one (`Agents fresh`): the process is stopped and the pane's
213    /// saved session id forgotten, so the launch that follows sends `session/start` and not `session/resume`. Only between
214    /// turns; the check, the end of the session and the closing of stdin are one lock hold, so a message either started its
215    /// turn first (refused; the caller waits and tries again) or finds the agent not running and starts it. Returns the old
216    /// session id.
217    pub fn start_fresh_session(&self) -> Result<Option<String>, &'static str> {
218        let (old, kill_tx) = {
219            let mut inner = self.inner.lock().unwrap();
220            if inner.session.turn_active() || self.health_monitor.is_active_turn() {
221                return Err("a turn is running");
222            }
223            let old = inner.session.forget_session().or_else(|| self.saved_session_id());
224            inner.retired_sessions.extend(old.clone());
225            inner.stdin_tx = None;
226            Self::set_status(&mut inner, STATUS_DONE);
227            (old, inner.kill_tx.take())
228        };
229        core::persist_session_id(&self.block_id, "", &self.mstore, &self.event_bus);
230        if let Some(tx) = kill_tx {
231            let _ = tx.send(true);
232        }
233        self.health_monitor.set_active_turn(false);
234        self.publish_status();
235        Ok(old)
236    }
237
238    /// A user message from `agentinput` / `agent.send`, acknowledged as the
239    /// other controllers acknowledge theirs.
240    pub fn send_message(&self, message: String, message_id: Option<&str>) -> Result<(), String> {
241        Controller::send_input(self, BlockInputUnion::data(message.into_bytes()), None)?;
242        if let (Some(id), Some(broker)) = (message_id, self.broker.as_ref()) {
243            super::publish_message_accepted(broker, &self.block_id, id);
244        }
245        Ok(())
246    }
247
248    /// Spawn `muse serve` and send `initialize`; the stdout reader carries
249    /// the handshake on (`MspSession`).
250    fn spawn_process(&self, cli_command: String, cli_args: Vec<String>, launch: Launch) -> Result<(), String> {
251        let Launch { working_dir, env_vars, mcp_servers, resume } = launch;
252        let mut cmd = crate::backend::pane_env::make_cli_cmd(&cli_command);
253        cmd.args(&cli_args);
254        core::apply_working_dir(&mut cmd, &self.block_id, &working_dir, &env_vars);
255        crate::backend::identity_spawn::record_process_spawn(&self.block_id, crate::backend::identity_spawn::SpawnPath::Acp, &env_vars);
256        #[cfg(windows)]
257        {
258            cmd.no_window();
259        }
260        cmd.stdin(std::process::Stdio::piped());
261        cmd.stdout(std::process::Stdio::piped());
262        cmd.stderr(std::process::Stdio::piped());
263
264        let mut child = crate::backend::process_tracker::registry::spawn_tracked(&self.block_id, &mut cmd, crate::backend::process_tracker::registry::Join::Agent)
265            .map_err(|e| format!("failed to spawn Muse Code: {e}"))?;
266        let pid = child.id().unwrap_or(0);
267        tracing::info!(block_id = %self.block_id, pid, cmd = %cli_command, args = ?cli_args, "[msp] muse serve spawned");
268
269        let stdin = child.stdin.take().ok_or("[msp] stdin not captured")?;
270        let stdout = child.stdout.take().ok_or("[msp] stdout not captured")?;
271        let stderr = child.stderr.take();
272        let (kill_tx, kill_rx) = tokio::sync::oneshot::channel::<bool>();
273        let (msg_tx, mut msg_rx) = mpsc::channel::<String>(64);
274        let (generation, init) = {
275            let mut inner = self.inner.lock().unwrap();
276            inner.generation += 1;
277            inner.current_pid = Some(pid);
278            inner.kill_tx = Some(kill_tx);
279            inner.stdin_tx = Some(msg_tx.clone());
280            inner.stderr_tail.clear();
281            Self::set_status(&mut inner, STATUS_RUNNING);
282            let init = inner.session.begin(super::acp::session_cwd(&working_dir), mcp_servers, resume);
283            (inner.generation, init)
284        };
285        self.health_monitor.set_active_turn(false);
286        self.health_monitor.note_spawned();
287        self.publish_status();
288
289        if let Some(stderr) = stderr {
290            let (block_id, inner) = (self.block_id.clone(), self.inner.clone());
291            tokio::spawn(async move {
292                let mut lines = BufReader::new(stderr).lines();
293                while let Ok(Some(line)) = lines.next_line().await {
294                    if line.trim().is_empty() {
295                        continue;
296                    }
297                    crate::backend::blockcontroller::stderr_log::log_stderr_line(&block_id, "msp muse serve", &line, true);
298                    let mut inner = inner.lock().unwrap();
299                    if inner.stderr_tail.len() == STDERR_TAIL_LINES {
300                        inner.stderr_tail.pop_front();
301                    }
302                    inner.stderr_tail.push_back(line);
303                }
304            });
305        }
306
307        let block_id_stdin = self.block_id.clone();
308        tokio::spawn(async move {
309            let mut stdin = tokio::io::BufWriter::new(stdin);
310            while let Some(line) = msg_rx.recv().await {
311                let written = async {
312                    stdin.write_all(line.as_bytes()).await?;
313                    stdin.write_all(b"\n").await?;
314                    stdin.flush().await
315                };
316                if let Err(e) = written.await {
317                    tracing::error!(block_id = %block_id_stdin, error = %e, "[msp] stdin write error");
318                    break;
319                }
320            }
321        });
322
323        let outlet = self.outlet();
324        let (mstore, event_bus) = (self.mstore.clone(), self.event_bus.clone());
325        let reader = tokio::spawn(async move {
326            let mut lines = BufReader::new(stdout).lines();
327            while let Ok(Some(line)) = lines.next_line().await {
328                if line.trim().is_empty() {
329                    continue;
330                }
331                outlet.health.note_output();
332                let Ok(json) = serde_json::from_str::<serde_json::Value>(&line) else {
333                    outlet.write(&line);
334                    continue;
335                };
336                let fx = {
337                    let mut inner = outlet.inner.lock().unwrap();
338                    let fx = inner.session.on_message(&json);
339                    if let Some(ref tx) = inner.stdin_tx {
340                        for msg in &fx.send {
341                            if tx.try_send(msg.clone()).is_err() {
342                                tracing::warn!(block_id = %outlet.block_id, "[msp] a message to muse serve was dropped — channel full or closed");
343                            }
344                        }
345                    }
346                    if let Some(active) = fx.turn_active {
347                        outlet.set_turn(&inner, active);
348                    }
349                    fx
350                };
351                if let Some(ref sid) = fx.session {
352                    tracing::info!(block_id = %outlet.block_id, session_id = %sid, "[msp] session open");
353                    core::persist_session_id(&outlet.block_id, sid, &mstore, &event_bus);
354                }
355                if !fx.hide {
356                    outlet.write(&line);
357                }
358                for extra in &fx.append {
359                    outlet.write(extra);
360                }
361            }
362            tracing::info!(block_id = %outlet.block_id, "[msp] stdout closed");
363        });
364
365        let outlet = self.outlet();
366        tokio::spawn(async move {
367            // The exit code when the process ended by itself; `None` when
368            // `stop` killed it.
369            let exited = tokio::select! {
370                _ = kill_rx => {
371                    let _ = agentmux_common::process::kill_child_and_group(&mut child).await;
372                    None
373                }
374                status = child.wait() => Some(status.map(|s| s.code().unwrap_or(-1)).unwrap_or(-1)),
375            };
376            if exited.is_some() {
377                // Its last lines (a final `turn/completed`) go first.
378                let _ = tokio::time::timeout(std::time::Duration::from_secs(2), reader).await;
379            }
380            let mut inner = outlet.inner.lock().unwrap();
381            if inner.generation != generation {
382                return;
383            }
384            inner.stdin_tx = None;
385            inner.current_pid = None;
386            let exit_code = exited.unwrap_or(-1);
387            if exited.is_some() {
388                inner.proc_exit_code = exit_code;
389            }
390            Self::set_status(&mut inner, STATUS_DONE);
391            let had_work = inner.session.process_ended();
392            let tail: Vec<String> = inner.stderr_tail.iter().cloned().collect();
393            outlet.set_turn(&inner, false);
394            drop(inner);
395            tracing::info!(block_id = %outlet.block_id, exit_code, killed = exited.is_none(), "[msp] muse serve ended");
396            // Exited by itself with work in hand: say why, and end the turn.
397            if exited.is_some() && had_work {
398                outlet.write(&super::msp_protocol::process_exit_error(exit_code, &tail));
399                outlet.write(super::msp_protocol::TURN_ENDED_BY_SRV);
400            }
401        });
402
403        if msg_tx.try_send(init).is_err() {
404            tracing::error!(block_id = %self.block_id, "[msp] initialize dropped; the agent will not start");
405        }
406        Ok(())
407    }
408}
409
410/// Where and how a process is started, read from the pane's meta.
411struct Launch {
412    working_dir: String,
413    env_vars: HashMap<String, String>,
414    mcp_servers: serde_json::Map<String, serde_json::Value>,
415    /// The pane's previous session (`agent:sessionid`).
416    resume: Option<String>,
417}
418
419impl Controller for MspController {
420    fn start(&self, block_meta: super::super::obj::MetaMapType, _rt_opts: Option<serde_json::Value>, _force: bool) -> Result<(), String> {
421        use super::super::obj::meta_get_string;
422        crate::backend::mcp_folder_rule::not_refused(&block_meta)?;
423        let cmd = meta_get_string(&block_meta, super::META_KEY_CMD, "");
424        if cmd.is_empty() {
425            return Err("MSP controller: no cmd specified in block meta".to_string());
426        }
427        let working_dir = meta_get_string(&block_meta, super::META_KEY_CMD_CWD, "");
428        let args = super::acp::meta_string_list(&block_meta, super::META_KEY_CMD_ARGS);
429        let resume = resume_id(&block_meta, &self.inner.lock().unwrap().retired_sessions);
430        let env_vars = super::acp::session_agent_env(&block_meta, &self.block_id, &self.mstore, &self.auth_key);
431        // AgentMux's MCP servers: the config the launch wrote for this agent, which is
432        // outside the working directory when that is the user's own project (#3680),
433        // passed in `session/start`.
434        let mcp_servers = crate::backend::mcp_config_file::read_for_turn(&super::acp::session_cwd(&working_dir)).map_or_else(
435            || serde_json::Map::new(),
436            |raw| {
437                let path = env_vars.get("PATH").map(String::as_str);
438                let lookup = |k: &str| env_vars.get(k).cloned().or_else(|| std::env::var(k).ok());
439                super::msp_protocol::msp_mcp_servers(&raw, |c| super::acp_mcp::resolve_command(c, path), lookup)
440            },
441        );
442        self.spawn_process(cmd, args, Launch { working_dir, env_vars, mcp_servers, resume })
443    }
444
445    fn stop(&self, _graceful: bool, _new_status: &str) -> Result<(), String> {
446        // Closing stdin ends `muse serve`'s sessions in order; the kill makes
447        // sure it is gone.
448        let kill_tx = {
449            let mut inner = self.inner.lock().unwrap();
450            inner.stdin_tx = None;
451            Self::set_status(&mut inner, STATUS_DONE);
452            inner.kill_tx.take()
453        };
454        if let Some(tx) = kill_tx {
455            let _ = tx.send(true);
456        }
457        self.health_monitor.set_active_turn(false);
458        self.publish_status();
459        Ok(())
460    }
461
462    fn get_runtime_status(&self) -> BlockControllerRuntimeStatus {
463        self.get_status_snapshot()
464    }
465
466    fn send_input(&self, input: BlockInputUnion, _seq: Option<u64>) -> Result<(), String> {
467        if let Some(data) = input.input_data {
468            let message = String::from_utf8_lossy(&data).to_string();
469            if message.trim().is_empty() {
470                return Ok(());
471            }
472            let mut inner = self.inner.lock().unwrap();
473            let Some(tx) = inner.stdin_tx.clone() else {
474                // Not running: not kept. The caller starts a turn, which
475                // sends the message once the process is up (delivery.rs).
476                return Err("Muse Code is not running".to_string());
477            };
478            match inner.session.prompt(&message)? {
479                PromptOutcome::Send { id, line } => {
480                    // Marked before the send: the lock is held until it is
481                    // queued, so the reader can't report the turn's end first.
482                    self.set_turn(&inner, true);
483                    if let Err(e) = tx.try_send(line) {
484                        if inner.session.prompt_unsent(id) {
485                            self.set_turn(&inner, false);
486                        }
487                        return Err(format!("Muse Code stdin send failed: {e}"));
488                    }
489                }
490                PromptOutcome::Queued { reopen } => {
491                    self.set_turn(&inner, true);
492                    if let Some(line) = reopen {
493                        let _ = tx.try_send(line);
494                    }
495                }
496            }
497        }
498        if let Some(sig) = input.sig_name {
499            // Stop the running turn when there is one; otherwise, as for an
500            // ACP agent, stop the agent.
501            if sig == "SIGINT" {
502                let mut inner = self.inner.lock().unwrap();
503                if let (Some(line), Some(tx)) = (inner.session.interrupt(), inner.stdin_tx.clone()) {
504                    return tx.try_send(line).map_err(|e| format!("Muse Code stdin send failed: {e}"));
505                }
506            }
507            if sig == "SIGTERM" || sig == "SIGINT" {
508                return self.stop(true, STATUS_DONE);
509            }
510        }
511        Ok(())
512    }
513
514    fn turn_tracker(&self) -> Option<Arc<TurnActivityTracker>> {
515        Some(Arc::clone(&self.health_monitor))
516    }
517
518    fn controller_type(&self) -> &str {
519        BLOCK_CONTROLLER_MSP
520    }
521
522    fn block_id(&self) -> &str {
523        &self.block_id
524    }
525
526    fn as_any(&self) -> &dyn std::any::Any {
527        self
528    }
529}
530
531#[cfg(test)]
532#[path = "msp_tests.rs"]
533mod tests;