surjection_core/adapters/
detect.rs1use std::ffi::OsStr;
6use std::path::{Path, PathBuf};
7
8use crate::adapters::location::Location;
9use crate::adapters::spec::AdapterSpec;
10use crate::env::{Env, Os};
11use crate::error::{CoreError, ErrorCode};
12use crate::formats::NativeValue;
13use crate::fs::Fs;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum Probe {
18 Path(Location),
21 Executable(&'static str),
24 UninstallEntry(&'static str),
26 MsixPackage(Location),
29}
30
31pub trait RegistryProbe {
35 fn has_uninstall_entry(&self, display_name: &str) -> bool;
39}
40
41#[derive(Debug, Clone, Copy, Default)]
43pub struct NoRegistry;
44
45impl RegistryProbe for NoRegistry {
46 fn has_uninstall_entry(&self, _display_name: &str) -> bool {
47 false
48 }
49}
50
51#[derive(Debug, Clone, PartialEq, Eq)]
53pub enum Evidence {
54 Path(PathBuf),
55 Executable(PathBuf),
56 UninstallEntry(&'static str),
57 MsixPackage(PathBuf),
58}
59
60#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct Detection {
63 pub client: &'static str,
64 pub supported: bool,
67 pub evidence: Vec<Evidence>,
69 pub warnings: Vec<CoreError>,
72}
73
74impl Detection {
75 pub fn detected(&self) -> bool {
76 self.supported && !self.evidence.is_empty()
77 }
78}
79
80pub fn detect(
83 spec: &AdapterSpec,
84 env: &Env,
85 fs: &dyn Fs,
86 registry: &dyn RegistryProbe,
87) -> Detection {
88 let supported = spec
89 .mcp
90 .as_ref()
91 .is_none_or(|mcp| mcp.oses.contains(&env.os()));
92 let mut evidence = Vec::new();
93 let mut warnings = Vec::new();
94 if supported {
95 for probe in spec.detect {
96 run(probe, env, fs, registry, &mut evidence);
97 }
98 warnings.extend(replacing_extension(spec, env, fs, None));
99 }
100 Detection {
101 client: spec.id,
102 supported,
103 evidence,
104 warnings,
105 }
106}
107
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub struct McpExtension {
113 pub package: &'static str,
115 pub paths: &'static [Location],
119 pub package_lists: &'static [Location],
124}
125
126pub fn replacing_extension(
132 spec: &AdapterSpec,
133 env: &Env,
134 fs: &dyn Fs,
135 project: Option<&Path>,
136) -> Option<CoreError> {
137 let mcp = spec.mcp.as_ref()?;
138 mcp.replaced_by.iter().find_map(|extension| {
139 let found = extension
140 .paths
141 .iter()
142 .filter_map(|location| location.resolve(env, project))
143 .find(|path| fs.exists(path))
144 .or_else(|| {
145 extension
146 .package_lists
147 .iter()
148 .filter_map(|location| location.resolve(env, project))
149 .find(|file| lists_package(fs, file, extension.package))
150 })?;
151 Some(
152 CoreError::new(
153 ErrorCode::ClientMcpReplacedByExtension,
154 format!(
155 "{} is installed and replaces the MCP support of {}; it may not load the servers Surjection writes",
156 extension.package, spec.display_name
157 ),
158 )
159 .with_path(found),
160 )
161 })
162}
163
164fn lists_package(fs: &dyn Fs, file: &Path, package: &str) -> bool {
166 let Ok(text) = fs.read_to_string(file) else {
167 return false;
168 };
169 let Ok(settings) = NativeValue::parse_json(&text) else {
170 return false;
171 };
172 let Some(packages) = settings
173 .as_object()
174 .and_then(|settings| settings.get("packages"))
175 .and_then(NativeValue::as_array)
176 else {
177 return false;
178 };
179 packages.iter().any(|entry| {
180 let source = match entry {
181 NativeValue::String(source) => Some(source.as_str()),
182 NativeValue::Object(entry) => entry.get("source").and_then(NativeValue::as_str),
183 _ => None,
184 };
185 source.is_some_and(|source| package_name(source) == package)
186 })
187}
188
189fn package_name(source: &str) -> &str {
192 let source = source
193 .strip_prefix("npm:")
194 .or_else(|| source.strip_prefix("git:"))
195 .unwrap_or(source);
196 let last = source
197 .trim_end_matches(['/', '\\'])
198 .rsplit(['/', '\\'])
199 .next()
200 .unwrap_or(source);
201 let last = match last.get(1..).and_then(|rest| rest.find('@')) {
204 Some(at) => &last[..at + 1],
205 None => last,
206 };
207 last.strip_suffix(".git").unwrap_or(last)
208}
209
210fn run(
211 probe: &Probe,
212 env: &Env,
213 fs: &dyn Fs,
214 registry: &dyn RegistryProbe,
215 evidence: &mut Vec<Evidence>,
216) {
217 match *probe {
218 Probe::Path(location) => {
219 evidence.extend(
220 location
221 .expand(env, fs, None)
222 .into_iter()
223 .map(Evidence::Path),
224 );
225 }
226 Probe::Executable(name) => {
227 evidence.extend(find_executable(env, fs, name).map(Evidence::Executable));
228 }
229 Probe::UninstallEntry(display_name) => {
230 if env.os() == Os::Windows && registry.has_uninstall_entry(display_name) {
231 evidence.push(Evidence::UninstallEntry(display_name));
232 }
233 }
234 Probe::MsixPackage(location) => {
235 if env.os() == Os::Windows {
236 evidence.extend(
237 location
238 .expand(env, fs, None)
239 .into_iter()
240 .filter(|path| fs.is_dir(path))
241 .map(Evidence::MsixPackage),
242 );
243 }
244 }
245 }
246}
247
248fn find_executable(env: &Env, fs: &dyn Fs, name: &str) -> Option<PathBuf> {
251 let path = env.var("PATH")?.to_str()?;
252 let windows = env.os() == Os::Windows;
253 let separator = if windows { ';' } else { ':' };
254 let extensions: Vec<String> = if windows {
255 env.var("PATHEXT")
256 .and_then(OsStr::to_str)
257 .unwrap_or(".COM;.EXE;.BAT;.CMD")
258 .split(';')
259 .filter(|ext| !ext.is_empty())
260 .map(str::to_ascii_lowercase)
261 .collect()
262 } else {
263 vec![String::new()]
264 };
265 path.split(separator)
266 .map(|dir| Path::new(dir.trim_matches('"')))
267 .filter(|dir| dir.is_absolute())
268 .flat_map(|dir| {
269 extensions
270 .iter()
271 .map(move |ext| dir.join(format!("{name}{ext}")))
272 })
273 .find(|candidate| fs.exists(candidate) && !fs.is_dir(candidate))
274}