Skip to main content

muse_code_sdk/
spawn.rs

1//! Host discovery and process ownership.
2
3use std::collections::HashMap;
4use std::env;
5use std::ffi::{OsStr, OsString};
6use std::io;
7use std::path::{Path, PathBuf};
8use std::time::Duration;
9
10pub use exit::{CloseAttribution, ExitClassification, ExitKind, RetryGuidance, classify_exit};
11use thiserror::Error;
12
13mod child;
14mod exit;
15
16pub use child::MuseChild;
17
18#[cfg(doctest)]
19mod evolution;
20
21/// The executable searched for when callers do not pass `muse_bin`.
22pub const HOST_BINARY_NAME: &str = "muse";
23
24/// The compatibility matrix cited by discovery errors.
25pub const COMPATIBILITY_PAGE_URL: &str =
26    "https://meta-models.github.io/muse-code-sdk/compatibility/";
27
28/// Maximum retained host stderr evidence for exit classification.
29pub const STDERR_TAIL_LIMIT: usize = 16 * 1024;
30
31/// Default [`SpawnOptions::shutdown_timeout`]: how long [`MuseChild::close`]
32/// (and so `MuseClient::close`) lets the host drain after stdin EOF before it
33/// escalates (`SIGTERM` on Unix; the platform kill elsewhere). It is the host's
34/// own stdio drain timeout, so a healthy host finishes its orderly wind-down
35/// (turn cancel, durable session end) inside it.
36pub const DEFAULT_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(30);
37
38/// Fixed grace between `SIGTERM` and `SIGKILL` inside [`MuseChild::close`].
39/// Not a knob: by then the host has had its whole drain window, so this only
40/// covers a signal handler's final flush. Off Unix, where the first escalation
41/// is already the platform kill, it only spaces the repeated kill request; the
42/// reap stays unbounded.
43pub const SIGTERM_GRACE: Duration = Duration::from_secs(2);
44
45/// Bound on waiting for the host's stderr tail once its exit was observed.
46pub const STDERR_DRAIN_TIMEOUT: Duration = Duration::from_secs(2);
47
48/// No host was supplied explicitly and no executable `muse` was on `PATH`.
49#[derive(Debug, Clone, PartialEq, Eq, Error)]
50#[error(
51    "no muse host found: pass {parameter}=<path to a muse binary> or put `muse` on PATH. \
52     The crate does not bundle a host; supported host versions are listed on the \
53     compatibility page's Rust row: {compatibility_url}"
54)]
55pub struct MuseHostDiscoveryError {
56    parameter: &'static str,
57    compatibility_url: &'static str,
58}
59
60impl MuseHostDiscoveryError {
61    /// The spawn option callers use to provide an explicit host path.
62    #[must_use]
63    pub const fn parameter(&self) -> &'static str {
64        self.parameter
65    }
66
67    /// The compatibility matrix that explains supported host versions.
68    #[must_use]
69    pub const fn compatibility_url(&self) -> &'static str {
70        self.compatibility_url
71    }
72}
73
74/// Resolve `muse_bin`, then `PATH`; return an explicit path verbatim.
75///
76/// The deterministic injected-`PATH` helper is not part of the public API:
77///
78/// ```compile_fail
79/// use muse_code_sdk::spawn::discover_muse_bin_with_path_for_test;
80/// ```
81pub fn discover_muse_bin(muse_bin: Option<&Path>) -> Result<PathBuf, MuseHostDiscoveryError> {
82    discover_muse_bin_with_path(muse_bin, env::var_os("PATH").as_deref())
83}
84
85fn discover_muse_bin_with_path(
86    muse_bin: Option<&Path>,
87    path: Option<&OsStr>,
88) -> Result<PathBuf, MuseHostDiscoveryError> {
89    if let Some(muse_bin) = muse_bin {
90        return Ok(muse_bin.to_path_buf());
91    }
92
93    if let Some(path) = path
94        && let Some(found) = find_executable_on_path(path)
95    {
96        return Ok(found);
97    }
98
99    Err(MuseHostDiscoveryError {
100        parameter: "muse_bin",
101        compatibility_url: COMPATIBILITY_PAGE_URL,
102    })
103}
104
105fn find_executable_on_path(path: &OsStr) -> Option<PathBuf> {
106    env::split_paths(path).find_map(|directory| {
107        #[cfg(windows)]
108        let candidate = directory.join("muse.exe");
109        #[cfg(not(windows))]
110        let candidate = directory.join(HOST_BINARY_NAME);
111
112        is_executable(&candidate).then_some(candidate)
113    })
114}
115
116#[cfg(unix)]
117fn is_executable(candidate: &Path) -> bool {
118    use std::os::unix::fs::PermissionsExt;
119
120    candidate
121        .metadata()
122        .is_ok_and(|metadata| metadata.is_file() && metadata.permissions().mode() & 0o111 != 0)
123}
124
125#[cfg(windows)]
126fn is_executable(candidate: &Path) -> bool {
127    candidate.is_file()
128}
129
130#[cfg(test)]
131mod discovery_tests {
132    use std::fs;
133    use std::io;
134    use std::path::{Path, PathBuf};
135
136    use super::{COMPATIBILITY_PAGE_URL, SpawnError, discover_muse_bin_with_path};
137
138    fn temp_dir(label: &str) -> io::Result<PathBuf> {
139        let dir =
140            std::env::temp_dir().join(format!("muse-code-sdk-{label}-{}", std::process::id()));
141        let _ = fs::remove_dir_all(&dir);
142        fs::create_dir(&dir)?;
143        Ok(dir)
144    }
145
146    #[cfg(unix)]
147    fn install_fake_muse(dir: &Path) -> io::Result<PathBuf> {
148        use std::os::unix::fs::PermissionsExt;
149
150        let binary = dir.join("muse");
151        fs::write(&binary, "#!/bin/sh\nexit 0\n")?;
152        fs::set_permissions(&binary, fs::Permissions::from_mode(0o755))?;
153        Ok(binary)
154    }
155
156    #[cfg(windows)]
157    fn install_fake_muse(dir: &Path) -> io::Result<PathBuf> {
158        let binary = dir.join("muse.exe");
159        fs::copy(std::env::current_exe()?, &binary)?;
160        Ok(binary)
161    }
162
163    #[test]
164    fn path_lookup_returns_the_first_executable_muse() -> Result<(), Box<dyn std::error::Error>> {
165        let first = temp_dir("path-first")?;
166        let second = temp_dir("path-second")?;
167        let expected = install_fake_muse(&first)?;
168        install_fake_muse(&second)?;
169        let path = std::env::join_paths([&first, &second])?;
170
171        let discovered = discover_muse_bin_with_path(None, Some(path.as_os_str()))?;
172
173        assert_eq!(discovered, expected);
174        fs::remove_dir_all(first)?;
175        fs::remove_dir_all(second)?;
176        Ok(())
177    }
178
179    #[test]
180    fn missing_host_is_typed_before_spawn_and_names_the_parameter_and_compatibility_page()
181    -> Result<(), Box<dyn std::error::Error>> {
182        let empty_path = temp_dir("missing-host")?;
183
184        let discovery = match discover_muse_bin_with_path(None, Some(empty_path.as_os_str())) {
185            Ok(path) => {
186                return Err(format!("unexpected host discovery: {}", path.display()).into());
187            }
188            Err(error) => error,
189        };
190        let error: SpawnError = discovery.into();
191        let discovery = match error {
192            SpawnError::Discovery(discovery) => discovery,
193            error => return Err(format!("expected a discovery error, got {error:?}").into()),
194        };
195
196        assert_eq!(discovery.parameter(), "muse_bin");
197        assert_eq!(discovery.compatibility_url(), COMPATIBILITY_PAGE_URL);
198        let message = discovery.to_string();
199        assert!(message.contains("muse_bin"), "{message}");
200        assert!(message.contains(COMPATIBILITY_PAGE_URL), "{message}");
201        assert!(
202            std::error::Error::source(&discovery).is_none(),
203            "the typed discovery failure precedes any OS spawn error"
204        );
205        fs::remove_dir_all(empty_path)?;
206        Ok(())
207    }
208}
209
210/// Inputs for an SDK-owned `muse serve` process.
211#[derive(Debug, Clone)]
212#[non_exhaustive]
213pub struct SpawnOptions {
214    /// Explicit host binary. When absent, discovery searches `PATH`.
215    pub muse_bin: Option<PathBuf>,
216    /// Host arguments. The default is exactly `serve`.
217    pub args: Vec<OsString>,
218    /// Optional child working directory.
219    pub cwd: Option<PathBuf>,
220    /// Optional child environment overrides, inherited environment preserved.
221    pub env: Option<HashMap<OsString, OsString>>,
222    /// How long [`MuseChild::close`] and `MuseClient::close` let the host drain
223    /// after stdin EOF before `SIGTERM` (the platform kill off Unix). Defaults to [`DEFAULT_SHUTDOWN_TIMEOUT`]; match it to a host
224    /// configured with a different drain timeout. Zero skips the drain window
225    /// but not the fixed [`SIGTERM_GRACE`] before `SIGKILL`.
226    pub shutdown_timeout: Duration,
227}
228
229impl Default for SpawnOptions {
230    fn default() -> Self {
231        Self {
232            muse_bin: None,
233            args: vec![OsString::from("serve")],
234            cwd: None,
235            env: None,
236            shutdown_timeout: DEFAULT_SHUTDOWN_TIMEOUT,
237        }
238    }
239}
240
241/// A discovery failure or an OS refusal to launch the discovered binary.
242#[derive(Debug, Error)]
243#[non_exhaustive]
244pub enum SpawnError {
245    /// Neither discovery tier produced a host, before any spawn was attempted.
246    #[error(transparent)]
247    Discovery(#[from] MuseHostDiscoveryError),
248    /// The explicit or discovered path could not be launched.
249    #[error("failed to spawn muse host at {}: {source}", binary.display())]
250    #[non_exhaustive]
251    Launch {
252        /// Binary passed to the OS.
253        binary: PathBuf,
254        /// OS spawn failure.
255        #[source]
256        source: io::Error,
257    },
258}
259
260fn launch_error(binary: &Path, source: io::Error) -> SpawnError {
261    SpawnError::Launch {
262        binary: binary.to_path_buf(),
263        source,
264    }
265}
266
267/// Spawn an SDK-owned host driven by the caller's runtime.
268pub fn spawn_muse(options: SpawnOptions) -> Result<MuseChild, SpawnError> {
269    let binary = discover_muse_bin(options.muse_bin.as_deref())?;
270    child::launch(binary, options)
271}