Skip to main content

clm_rust_core/polyglot/
config.rs

1use std::collections::HashMap;
2use std::path::{Path, PathBuf};
3
4pub fn resolve_python_cmd(clm_root: &str) -> String {
5    let local_venv = Path::new(clm_root).join(".venv");
6    if local_venv.exists() {
7        let venv_py = if cfg!(target_os = "windows") {
8            local_venv.join("Scripts").join("python.exe")
9        } else {
10            local_venv.join("bin").join("python")
11        };
12        if venv_py.exists() {
13            return venv_py.to_string_lossy().to_string();
14        }
15    }
16
17    if cfg!(target_os = "windows") {
18        for cmd in &["python", "python3"] {
19            if std::process::Command::new(cmd).arg("--version").output().map(|o| o.status.success()).unwrap_or(false) {
20                return cmd.to_string();
21            }
22        }
23    } else {
24        for cmd in &["python3", "python"] {
25            if std::process::Command::new(cmd).arg("--version").output().map(|o| o.status.success()).unwrap_or(false) {
26                return cmd.to_string();
27            }
28        }
29    }
30    
31    if cfg!(target_os = "windows") {
32        "python".to_string()
33    } else {
34        "python3".to_string()
35    }
36}
37
38pub fn get_interpreter_version(interpreter: &str, clm_root: &str) -> Option<String> {
39    let cmd_name = match interpreter {
40        "python" | "python3" => resolve_python_cmd(clm_root),
41        other => other.to_string(),
42    };
43    let output = std::process::Command::new(&cmd_name)
44        .arg("--version")
45        .output()
46        .ok();
47    if let Some(out) = output {
48        let text = String::from_utf8_lossy(&out.stdout).to_string()
49            + String::from_utf8_lossy(&out.stderr).as_ref();
50        let re = regex::Regex::new(r"(\d+\.\d+(?:\.\d+)?)").unwrap();
51        if let Some(caps) = re.captures(&text) {
52            return Some(caps[1].to_string());
53        }
54    }
55    None
56}
57
58pub fn compare_versions(current: &str, op: &str, req: &str) -> bool {
59    let parse_ver = |s: &str| -> (u32, u32, u32) {
60        let parts: Vec<&str> = s.split('.').collect();
61        let major = parts.first().and_then(|v| v.parse().ok()).unwrap_or(0);
62        let minor = parts.get(1).and_then(|v| v.parse().ok()).unwrap_or(0);
63        let patch = parts.get(2).and_then(|v| v.parse().ok()).unwrap_or(0);
64        (major, minor, patch)
65    };
66    let v1 = parse_ver(current);
67    let v2 = parse_ver(req);
68    match op {
69        ">=" => v1 >= v2,
70        "<=" => v1 <= v2,
71        ">" => v1 > v2,
72        "<" => v1 < v2,
73        _ => v1 == v2,
74    }
75}
76
77pub fn check_precondition(req_str: &str, clm_root: &str) -> bool {
78    let re = regex::Regex::new(r"^interpreter:([a-zA-Z0-9_-]+)(>=|<=|>|<|==|=)([0-9.]+)$").unwrap();
79    if let Some(caps) = re.captures(req_str) {
80        let interpreter = &caps[1];
81        let op = &caps[2];
82        let req_ver = &caps[3];
83        if let Some(current_ver) = get_interpreter_version(interpreter, clm_root) {
84            compare_versions(&current_ver, op, req_ver)
85        } else {
86            false
87        }
88    } else {
89        true
90    }
91}
92
93pub fn resolve_self_exe(clm_root: &str) -> PathBuf {
94    if let Ok(self_exe) = std::env::current_exe() {
95        if self_exe.to_string_lossy().contains("deps") {
96            let alt_exe = Path::new(clm_root).join({
97                #[cfg(windows)] { "kernel/clm_rust_core/target/debug/clm_rust_core.exe" }
98                #[cfg(not(windows))] { "kernel/clm_rust_core/target/debug/clm_rust_core" }
99            });
100            if alt_exe.exists() {
101                return alt_exe;
102            }
103            let alt_exe_release = Path::new(clm_root).join({
104                #[cfg(windows)] { "kernel/clm_rust_core/target/release/clm_rust_core.exe" }
105                #[cfg(not(windows))] { "kernel/clm_rust_core/target/release/clm_rust_core" }
106            });
107            if alt_exe_release.exists() {
108                return alt_exe_release;
109            }
110        }
111        if let Some(parent) = self_exe.parent() {
112            let local_exe = parent.join({
113                #[cfg(windows)] { "clm_rust_core.exe" }
114                #[cfg(not(windows))] { "clm_rust_core" }
115            });
116            if local_exe.exists() {
117                return local_exe;
118            }
119        }
120        return self_exe;
121    }
122    Path::new(clm_root).join({
123        #[cfg(windows)] { "kernel/clm_rust_core/target/release/clm_rust_core.exe" }
124        #[cfg(not(windows))] { "kernel/clm_rust_core/target/release/clm_rust_core" }
125    })
126}
127
128pub fn create_sandboxed_command(
129    program: &str,
130    args: &[String],
131    envs: &HashMap<String, String>,
132    clm_root: &str,
133) -> std::process::Command {
134    let clm_no_sandbox = envs.get(crate::layer0::vocabulary_env::ENV_CLM_NO_SANDBOX).map(|v| v == "true").unwrap_or_else(|| {
135        crate::cross_cutting::context::CLMContext::get_scoped_or_env(crate::layer0::vocabulary_env::ENV_CLM_NO_SANDBOX)
136            .unwrap_or_default()
137            == "true"
138    });
139    let has_sandbox_exec = std::process::Command::new("which")
140        .arg("sandbox-exec")
141        .output()
142        .map(|o| o.status.success())
143        .unwrap_or(false);
144
145    let mut cmd = if !clm_no_sandbox && has_sandbox_exec {
146        let home_dir = crate::layer0::environment::var("HOME").unwrap_or_default();
147        let profile = format!(
148            r#"(version 1)
149(deny default)
150(allow file-read-metadata)
151(allow file-read-data)
152(allow file-write-data)
153(allow file-read*
154    (subpath "/usr")
155    (subpath "/System")
156    (subpath "/Library")
157    (subpath "/private")
158    (subpath "/var")
159    (subpath "/tmp")
160    (subpath "/etc")
161    (subpath "/opt")
162    (subpath "/dev")
163    (subpath "{}")
164    (subpath "{}"))
165(allow file-write*
166    (subpath "{}/data")
167    (subpath "{}/db")
168    (subpath "{}/types/meta")
169    (literal "{}/result_open_interpreter.txt")
170    (subpath "{}/.clm")
171    (subpath "/private/var")
172    (subpath "/private/tmp")
173    (subpath "/var")
174    (subpath "/tmp")
175    (literal "/dev/null")
176    (literal "/dev/zero"))
177(allow file-map-executable
178    (subpath "/usr")
179    (subpath "/System")
180    (subpath "/Library")
181    (subpath "/opt")
182    (subpath "{}")
183    (subpath "{}"))
184(allow process-exec
185    (subpath "/bin")
186    (subpath "/usr/bin")
187    (subpath "/usr/local/bin")
188    (subpath "/opt/homebrew")
189    (subpath "/Library/Frameworks/Python.framework")
190    (subpath "/Library/Developer/CommandLineTools")
191    (subpath "/private/var")
192    (subpath "/var")
193    (subpath "/tmp")
194    (subpath "{}")
195    (subpath "{}"))
196(allow process-fork)
197(allow process-info*)
198(allow ipc-posix*)
199(allow sysctl-read)
200(allow mach-lookup)
201(allow dynamic-code-generation)
202(allow network-bind)
203(allow network-inbound)
204(allow network-outbound)
205(deny file-read*
206    (literal "/private/etc/passwd")
207    (literal "/etc/passwd"))
208(deny file-read-data
209    (literal "/private/etc/passwd")
210    (literal "/etc/passwd"))"#,
211            clm_root, home_dir, clm_root, clm_root, clm_root, clm_root, home_dir, clm_root, home_dir, clm_root, home_dir
212        );
213
214        let mut scmd = std::process::Command::new("sandbox-exec");
215        scmd.arg("-p").arg(profile).arg(program);
216        scmd
217    } else {
218        std::process::Command::new(program)
219    };
220
221    for var_name in &[crate::layer0::vocabulary_env::ENV_CLM_ACTIVE_A_HASH, crate::layer0::vocabulary_env::ENV_CLM_ACTIVE_C_HASH, crate::layer0::vocabulary_env::ENV_CLM_ACTIVE_INSTANCE_ID, crate::layer0::vocabulary_env::ENV_CLM_CALLING_PCARD, crate::layer0::vocabulary_env::ENV_CLM_SYSTEM_CALL] {
222        if let Some(val) = crate::cross_cutting::context::CLMContext::get_scoped_or_env(var_name) {
223            cmd.env(var_name, val);
224        }
225    }
226    crate::cross_cutting::context::CLMContext::apply_current_to_command(&mut cmd);
227    for (k, v) in envs {
228        cmd.env(k, v);
229    }
230    for a in args {
231        cmd.arg(a);
232    }
233    cmd
234}
235
236pub fn normalize_output(raw_out: &str) -> String {
237    use serde_json::Value;
238    let stripped = raw_out.replace('\r', "");
239    let stripped = stripped.trim_end().to_string();
240    if let Ok(val) = serde_json::from_str::<Value>(&stripped) {
241        serde_json::to_string(&val).unwrap_or(stripped)
242    } else {
243        stripped
244    }
245}
246
247pub fn print_diff(first_norm: &str, second_norm: &str) {
248    let temp_dir = std::env::temp_dir().join("clm_execution_logs/.tmp");
249    let f1 = temp_dir.join(format!("norm_f1_{}", std::process::id()));
250    let f2 = temp_dir.join(format!("norm_f2_{}", std::process::id()));
251    let _ = std::fs::write(&f1, first_norm);
252    let _ = std::fs::write(&f2, second_norm);
253    
254    let diff_output = std::process::Command::new("diff")
255        .arg("-u")
256        .arg(&f1)
257        .arg(&f2)
258        .output();
259    if let Ok(out) = diff_output {
260        let text = String::from_utf8_lossy(&out.stdout);
261        eprintln!("{}", text);
262    }
263    
264    let _ = std::fs::remove_file(f1);
265    let _ = std::fs::remove_file(f2);
266}