agent-hub-runtime 0.6.0

AgentHub desktop and companion CLI runtime for Tauri applications
Documentation
//! Installation evidence is executable code, never settings or Skills directories.
use std::path::{Path, PathBuf};

struct InstallationProbe {
    bins: Vec<PathBuf>,
    apps: Vec<PathBuf>,
    extension_hosts: Vec<(bool, PathBuf)>,
}

pub(crate) fn executable(path: &Path) -> bool {
    let Ok(metadata) = path.metadata() else {
        return false;
    };
    if !metadata.is_file() {
        return false;
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        metadata.permissions().mode() & 0o111 != 0
    }
    #[cfg(not(unix))]
    {
        true
    }
}

fn commands(key: &str) -> &[&str] {
    match key {
        "claude_code" => &["claude"],
        "omp_agent" => &["omp"],
        "gemini_cli" => &["gemini"],
        "github_copilot" => &["copilot"],
        "cursor" => &["cursor", "cursor-agent"],
        "qwen_code" => &["qwen"],
        "antigravity" => &["agy", "antigravity"],
        "kiro" => &["kiro-cli"],
        "qoder" => &["qoder", "qodercli"],
        "kilo_code" => &["kilo"],
        "mistral_vibe" => &["vibe"],
        "continue" => &["cn"],
        "gitlab_duo" => &[],
        _ => &[],
    }
}

fn apps(key: &str) -> &[&str] {
    match key {
        "cursor" => &["Cursor"],
        "windsurf" => &["Windsurf"],
        "trae" => &["Trae"],
        "trae_cn" => &["Trae CN"],
        "antigravity" => &["Antigravity"],
        "warp" => &["Warp"],
        "kiro" => &["Kiro"],
        "qoder" => &["Qoder"],
        "codebuddy" => &["CodeBuddy"],
        "workbuddy" => &["WorkBuddy"],
        "qclaw" => &["QClaw"],
        "easyclaw" => &["EasyClaw"],
        "autoclaw" => &["AutoClaw"],
        _ => &[],
    }
}

fn extensions(key: &str) -> &[&str] {
    match key {
        "github_copilot" => &["github.copilot", "github.copilot-chat"],
        "cline" => &["saoudrizwan.claude-dev"],
        "roo_code" => &["rooveterinaryinc.roo-cline"],
        "kilo_code" => &["kilocode.kilo-code"],
        "continue" => &["continue.continue"],
        "augment" => &["augment.vscode-augment"],
        "gitlab_duo" => &["gitlab.gitlab-workflow"],
        _ => &[],
    }
}

impl InstallationProbe {
    fn command(&self, name: &str) -> bool {
        self.command_path(name).is_some()
    }

    fn command_path(&self, name: &str) -> Option<PathBuf> {
        if name.is_empty()
            || !name
                .bytes()
                .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
        {
            return None;
        }
        self.bins.iter().find_map(|root| {
            #[cfg(windows)]
            {
                ["exe", "cmd", "bat", "com"]
                    .iter()
                    .map(|ext| root.join(format!("{name}.{ext}")))
                    .find(|path| executable(path))
            }
            #[cfg(not(windows))]
            {
                let path = root.join(name);
                executable(&path).then_some(path)
            }
        })
    }

    fn app(&self, name: &str) -> bool {
        self.apps.iter().any(|root| {
            #[cfg(target_os = "macos")]
            {
                let bundle = root.join(format!("{name}.app/Contents"));
                bundle.join("Info.plist").is_file()
                    && std::fs::read_dir(bundle.join("MacOS")).is_ok_and(|mut entries| {
                        entries.any(|entry| entry.is_ok_and(|entry| executable(&entry.path())))
                    })
            }
            #[cfg(windows)]
            {
                executable(&root.join(name).join(format!("{name}.exe")))
            }
            #[cfg(not(any(target_os = "macos", windows)))]
            {
                executable(&root.join(name).join(name))
            }
        })
    }

    fn extension(&self, ids: &[&str]) -> bool {
        if ids.is_empty() {
            return false;
        }
        self.extension_hosts.iter().any(|(installed, root)| {
            if !installed {
                return false;
            }
            let obsolete: serde_json::Value = std::fs::read(root.join(".obsolete"))
                .ok()
                .and_then(|data| serde_json::from_slice(&data).ok())
                .unwrap_or_default();
            std::fs::read_dir(root).is_ok_and(|mut entries| {
                entries.any(|entry| {
                    let Ok(entry) = entry else {
                        return false;
                    };
                    if obsolete
                        .get(entry.file_name().to_string_lossy().as_ref())
                        .and_then(|v| v.as_bool())
                        == Some(true)
                    {
                        return false;
                    }
                    let Ok(data) = std::fs::read(entry.path().join("package.json")) else {
                        return false;
                    };
                    let Ok(manifest) = serde_json::from_slice::<serde_json::Value>(&data) else {
                        return false;
                    };
                    let (Some(publisher), Some(name)) =
                        (manifest["publisher"].as_str(), manifest["name"].as_str())
                    else {
                        return false;
                    };
                    let id = format!("{publisher}.{name}").to_ascii_lowercase();
                    ids.contains(&id.as_str())
                        && ["main", "browser"].iter().any(|field| {
                            manifest[field].as_str().is_some_and(|relative| {
                                let path = Path::new(relative);
                                !path.is_absolute()
                                    && !path
                                        .components()
                                        .any(|c| matches!(c, std::path::Component::ParentDir))
                                    && entry.path().join(path).is_file()
                            })
                        })
                })
            })
        })
    }

    fn installed(&self, key: &str) -> bool {
        let aliases = commands(key);
        (if aliases.is_empty() {
            self.command(key)
        } else {
            aliases.iter().any(|name| self.command(name))
        }) || apps(key).iter().any(|name| self.app(name))
            || self.extension(extensions(key))
    }

    fn system() -> Self {
        let home = dirs::home_dir().unwrap_or_default();
        let bins = command_directories(&home);
        #[cfg(target_os = "macos")]
        let apps = vec![PathBuf::from("/Applications"), home.join("Applications")];
        #[cfg(windows)]
        let apps = ["ProgramFiles", "ProgramFiles(x86)", "LOCALAPPDATA"]
            .into_iter()
            .filter_map(std::env::var_os)
            .map(PathBuf::from)
            .flat_map(|root| [root.clone(), root.join("Programs")])
            .collect();
        #[cfg(not(any(target_os = "macos", windows)))]
        let apps = Vec::new();
        let mut probe = Self {
            bins,
            apps,
            extension_hosts: Vec::new(),
        };
        for (folder, command, app) in [
            (".vscode", "code", "Visual Studio Code"),
            (
                ".vscode-insiders",
                "code-insiders",
                "Visual Studio Code - Insiders",
            ),
            (".cursor", "cursor", "Cursor"),
            (".windsurf", "windsurf", "Windsurf"),
        ] {
            probe.extension_hosts.push((
                probe.command(command) || probe.app(app),
                home.join(folder).join("extensions"),
            ));
        }
        probe
    }
}

pub(super) fn command_directories(home: &Path) -> Vec<PathBuf> {
    let mut bins: Vec<PathBuf> = std::env::var_os("PATH")
        .map(|path| std::env::split_paths(&path).collect())
        .unwrap_or_default();
    #[cfg(unix)]
    bins.extend(["/usr/local/bin", "/opt/homebrew/bin", "/usr/bin"].map(PathBuf::from));
    bins.extend(
        [
            ".local/bin",
            ".cargo/bin",
            ".opencode/bin",
            ".claude/local",
            ".bun/bin",
            ".npm-global/bin",
            ".volta/bin",
        ]
        .map(|path| home.join(path)),
    );
    bins
}

pub(super) fn find_command(name: &str) -> Option<PathBuf> {
    InstallationProbe::system().command_path(name)
}

/// Let CLI shims resolve their runtime using the same roots as tool discovery.
/// Preserve inherited PATH precedence and change only the child environment.
pub(super) fn command_search_path(
    executable: &Path,
) -> Result<std::ffi::OsString, std::env::JoinPathsError> {
    let mut bins = InstallationProbe::system().bins;
    if let Some(parent) = executable.parent() {
        bins.push(parent.to_path_buf());
    }
    std::env::join_paths(bins)
}

pub(super) fn is_installed(key: &str) -> bool {
    InstallationProbe::system().installed(key)
}

#[cfg(test)]
mod tests;

/// Resolve user-configured launch programs, including absolute paths and local wrappers.
/// Uses the same bounded command roots as installation detection; never searches directories.
pub(crate) fn resolve_program(program: &str, cwd: &Path) -> Option<PathBuf> {
    let path = Path::new(program);
    if path.is_absolute() {
        return executable(path).then(|| path.into());
    }
    if program.contains(['/', '\\']) {
        let path = cwd.join(path);
        return executable(&path).then_some(path);
    }
    if program.is_empty()
        || program == "."
        || program == ".."
        || program.contains(['\0', '\r', '\n'])
    {
        return None;
    }
    InstallationProbe::system().bins.iter().find_map(|root| {
        let direct = root.join(program);
        if executable(&direct) {
            return Some(direct);
        }
        #[cfg(windows)]
        for extension in ["exe", "cmd", "bat", "com"] {
            let candidate = root.join(format!("{program}.{extension}"));
            if executable(&candidate) {
                return Some(candidate);
            }
        }
        None
    })
}