Skip to main content

skrills_intelligence/create/
cli_detector.rs

1//! Detect which CLI environment is currently active.
2
3use std::env;
4
5/// Detected CLI environment.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
7pub enum CliEnvironment {
8    /// Running under Claude Code CLI.
9    ClaudeCode,
10    /// Running under Codex CLI.
11    CodexCli,
12    /// Unknown environment.
13    #[default]
14    Unknown,
15}
16
17impl std::fmt::Display for CliEnvironment {
18    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
19        match self {
20            Self::ClaudeCode => write!(f, "claude"),
21            Self::CodexCli => write!(f, "codex"),
22            Self::Unknown => write!(f, "unknown"),
23        }
24    }
25}
26
27/// Detect which CLI environment is currently active.
28pub fn detect_cli_environment() -> CliEnvironment {
29    // Honor explicit skrills client selection first.
30    if let Ok(client) = env::var("SKRILLS_CLIENT") {
31        if client.eq_ignore_ascii_case("claude") {
32            return CliEnvironment::ClaudeCode;
33        }
34        if client.eq_ignore_ascii_case("codex") {
35            return CliEnvironment::CodexCli;
36        }
37    }
38
39    // Check Claude Code environment variables
40    if env::var("CLAUDE_CODE_SESSION").is_ok()
41        || env::var("CLAUDE_CLI").is_ok()
42        || env::var("__CLAUDE_MCP_SERVER").is_ok()
43        || env::var("CLAUDE_CODE_ENTRYPOINT").is_ok()
44    {
45        return CliEnvironment::ClaudeCode;
46    }
47
48    // Check Codex CLI environment variables
49    if env::var("CODEX_CLI").is_ok()
50        || env::var("CODEX_SESSION_ID").is_ok()
51        || env::var("CODEX_HOME").is_ok()
52    {
53        return CliEnvironment::CodexCli;
54    }
55
56    // Check skrills configuration (low priority; API backend may differ from CLI)
57    if let Ok(backend) = env::var("SKRILLS_SUBAGENTS_DEFAULT_BACKEND") {
58        match backend.to_lowercase().as_str() {
59            "claude" => return CliEnvironment::ClaudeCode,
60            "codex" => return CliEnvironment::CodexCli,
61            _ => {}
62        }
63    }
64
65    // Try to detect from parent process (Linux)
66    #[cfg(target_os = "linux")]
67    {
68        if let Ok(cmdline) = std::fs::read_to_string("/proc/self/cmdline") {
69            let cmdline_lower = cmdline.to_lowercase();
70            if cmdline_lower.contains("claude") {
71                return CliEnvironment::ClaudeCode;
72            }
73            if cmdline_lower.contains("codex") {
74                return CliEnvironment::CodexCli;
75            }
76        }
77    }
78
79    CliEnvironment::Unknown
80}
81
82/// Get the appropriate CLI binary for the environment.
83pub fn get_cli_binary(env: CliEnvironment) -> &'static str {
84    match env {
85        CliEnvironment::ClaudeCode => "claude",
86        CliEnvironment::CodexCli => "codex",
87        CliEnvironment::Unknown => "claude", // Default to claude
88    }
89}
90
91/// Check if a CLI binary is available in PATH.
92pub fn is_cli_available(binary: &str) -> bool {
93    #[cfg(unix)]
94    {
95        std::process::Command::new("which")
96            .arg(binary)
97            .output()
98            .map(|o| o.status.success())
99            .unwrap_or(false)
100    }
101    #[cfg(windows)]
102    {
103        std::process::Command::new("where")
104            .arg(binary)
105            .output()
106            .map(|o| o.status.success())
107            .unwrap_or(false)
108    }
109}
110
111/// Get the best available CLI binary.
112pub fn get_available_cli() -> Option<&'static str> {
113    let env = detect_cli_environment();
114    let preferred = get_cli_binary(env);
115
116    if is_cli_available(preferred) {
117        return Some(preferred);
118    }
119
120    // Try alternatives
121    if is_cli_available("claude") {
122        return Some("claude");
123    }
124    if is_cli_available("codex") {
125        return Some("codex");
126    }
127
128    None
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134
135    #[test]
136    fn test_default_environment() {
137        // In test environment, should be Unknown
138        // unless specific env vars are set
139        let env = detect_cli_environment();
140        // Just ensure it doesn't panic
141        let _ = env.to_string();
142    }
143
144    #[test]
145    fn test_get_cli_binary() {
146        assert_eq!(get_cli_binary(CliEnvironment::ClaudeCode), "claude");
147        assert_eq!(get_cli_binary(CliEnvironment::CodexCli), "codex");
148        assert_eq!(get_cli_binary(CliEnvironment::Unknown), "claude");
149    }
150
151    #[test]
152    fn test_is_cli_available_common_binary() {
153        // Test with a binary that should exist on most systems
154        #[cfg(unix)]
155        {
156            assert!(is_cli_available("ls"));
157            assert!(!is_cli_available("nonexistent_binary_12345"));
158        }
159        #[cfg(windows)]
160        {
161            assert!(is_cli_available("cmd"));
162            assert!(!is_cli_available("nonexistent_binary_12345"));
163        }
164    }
165
166    #[test]
167    fn test_get_available_cli() {
168        // This test just verifies the function works without panicking
169        // The result depends on what's installed on the system
170        let _ = get_available_cli();
171    }
172}