1use 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
21pub const HOST_BINARY_NAME: &str = "muse";
23
24pub const COMPATIBILITY_PAGE_URL: &str =
26 "https://meta-models.github.io/muse-code-sdk/compatibility/";
27
28pub const STDERR_TAIL_LIMIT: usize = 16 * 1024;
30
31pub const DEFAULT_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(30);
37
38pub const SIGTERM_GRACE: Duration = Duration::from_secs(2);
44
45pub const STDERR_DRAIN_TIMEOUT: Duration = Duration::from_secs(2);
47
48#[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 #[must_use]
63 pub const fn parameter(&self) -> &'static str {
64 self.parameter
65 }
66
67 #[must_use]
69 pub const fn compatibility_url(&self) -> &'static str {
70 self.compatibility_url
71 }
72}
73
74pub 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#[derive(Debug, Clone)]
212#[non_exhaustive]
213pub struct SpawnOptions {
214 pub muse_bin: Option<PathBuf>,
216 pub args: Vec<OsString>,
218 pub cwd: Option<PathBuf>,
220 pub env: Option<HashMap<OsString, OsString>>,
222 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#[derive(Debug, Error)]
243#[non_exhaustive]
244pub enum SpawnError {
245 #[error(transparent)]
247 Discovery(#[from] MuseHostDiscoveryError),
248 #[error("failed to spawn muse host at {}: {source}", binary.display())]
250 #[non_exhaustive]
251 Launch {
252 binary: PathBuf,
254 #[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
267pub 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}