use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use crate::adapters::location::Location;
use crate::adapters::spec::AdapterSpec;
use crate::env::{Env, Os};
use crate::error::{CoreError, ErrorCode};
use crate::formats::NativeValue;
use crate::fs::Fs;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Probe {
Path(Location),
Executable(&'static str),
UninstallEntry(&'static str),
MsixPackage(Location),
}
pub trait RegistryProbe {
fn has_uninstall_entry(&self, display_name: &str) -> bool;
}
#[derive(Debug, Clone, Copy, Default)]
pub struct NoRegistry;
impl RegistryProbe for NoRegistry {
fn has_uninstall_entry(&self, _display_name: &str) -> bool {
false
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Evidence {
Path(PathBuf),
Executable(PathBuf),
UninstallEntry(&'static str),
MsixPackage(PathBuf),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Detection {
pub client: &'static str,
pub supported: bool,
pub evidence: Vec<Evidence>,
pub warnings: Vec<CoreError>,
}
impl Detection {
pub fn detected(&self) -> bool {
self.supported && !self.evidence.is_empty()
}
}
pub fn detect(
spec: &AdapterSpec,
env: &Env,
fs: &dyn Fs,
registry: &dyn RegistryProbe,
) -> Detection {
let supported = spec
.mcp
.as_ref()
.is_none_or(|mcp| mcp.oses.contains(&env.os()));
let mut evidence = Vec::new();
let mut warnings = Vec::new();
if supported {
for probe in spec.detect {
run(probe, env, fs, registry, &mut evidence);
}
warnings.extend(replacing_extension(spec, env, fs, None));
}
Detection {
client: spec.id,
supported,
evidence,
warnings,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct McpExtension {
pub package: &'static str,
pub paths: &'static [Location],
pub package_lists: &'static [Location],
}
pub fn replacing_extension(
spec: &AdapterSpec,
env: &Env,
fs: &dyn Fs,
project: Option<&Path>,
) -> Option<CoreError> {
let mcp = spec.mcp.as_ref()?;
mcp.replaced_by.iter().find_map(|extension| {
let found = extension
.paths
.iter()
.filter_map(|location| location.resolve(env, project))
.find(|path| fs.exists(path))
.or_else(|| {
extension
.package_lists
.iter()
.filter_map(|location| location.resolve(env, project))
.find(|file| lists_package(fs, file, extension.package))
})?;
Some(
CoreError::new(
ErrorCode::ClientMcpReplacedByExtension,
format!(
"{} is installed and replaces the MCP support of {}; it may not load the servers Surjection writes",
extension.package, spec.display_name
),
)
.with_path(found),
)
})
}
fn lists_package(fs: &dyn Fs, file: &Path, package: &str) -> bool {
let Ok(text) = fs.read_to_string(file) else {
return false;
};
let Ok(settings) = NativeValue::parse_json(&text) else {
return false;
};
let Some(packages) = settings
.as_object()
.and_then(|settings| settings.get("packages"))
.and_then(NativeValue::as_array)
else {
return false;
};
packages.iter().any(|entry| {
let source = match entry {
NativeValue::String(source) => Some(source.as_str()),
NativeValue::Object(entry) => entry.get("source").and_then(NativeValue::as_str),
_ => None,
};
source.is_some_and(|source| package_name(source) == package)
})
}
fn package_name(source: &str) -> &str {
let source = source
.strip_prefix("npm:")
.or_else(|| source.strip_prefix("git:"))
.unwrap_or(source);
let last = source
.trim_end_matches(['/', '\\'])
.rsplit(['/', '\\'])
.next()
.unwrap_or(source);
let last = match last.get(1..).and_then(|rest| rest.find('@')) {
Some(at) => &last[..at + 1],
None => last,
};
last.strip_suffix(".git").unwrap_or(last)
}
fn run(
probe: &Probe,
env: &Env,
fs: &dyn Fs,
registry: &dyn RegistryProbe,
evidence: &mut Vec<Evidence>,
) {
match *probe {
Probe::Path(location) => {
evidence.extend(
location
.expand(env, fs, None)
.into_iter()
.map(Evidence::Path),
);
}
Probe::Executable(name) => {
evidence.extend(find_executable(env, fs, name).map(Evidence::Executable));
}
Probe::UninstallEntry(display_name) => {
if env.os() == Os::Windows && registry.has_uninstall_entry(display_name) {
evidence.push(Evidence::UninstallEntry(display_name));
}
}
Probe::MsixPackage(location) => {
if env.os() == Os::Windows {
evidence.extend(
location
.expand(env, fs, None)
.into_iter()
.filter(|path| fs.is_dir(path))
.map(Evidence::MsixPackage),
);
}
}
}
}
fn find_executable(env: &Env, fs: &dyn Fs, name: &str) -> Option<PathBuf> {
let path = env.var("PATH")?.to_str()?;
let windows = env.os() == Os::Windows;
let separator = if windows { ';' } else { ':' };
let extensions: Vec<String> = if windows {
env.var("PATHEXT")
.and_then(OsStr::to_str)
.unwrap_or(".COM;.EXE;.BAT;.CMD")
.split(';')
.filter(|ext| !ext.is_empty())
.map(str::to_ascii_lowercase)
.collect()
} else {
vec![String::new()]
};
path.split(separator)
.map(|dir| Path::new(dir.trim_matches('"')))
.filter(|dir| dir.is_absolute())
.flat_map(|dir| {
extensions
.iter()
.map(move |ext| dir.join(format!("{name}{ext}")))
})
.find(|candidate| fs.exists(candidate) && !fs.is_dir(candidate))
}