Skip to main content

clm_rust_core/
polyglot_runtime_script.rs

1#![allow(unused_imports)]
2use super::*;
3
4/// Execute a script in the named runtime and return (exit_code, stdout, stderr).
5///
6/// This is a standalone runtime dispatch function that handles shell, python, node,
7/// and rust runtimes with environment variables, entry points, and cargo test support.
8/// It is called by the `exec-runtime-script` CLI command to enable Python code to
9/// delegate runtime execution to the Rust binary instead of spawning subprocesses.
10#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
11pub struct RuntimeScriptInput {
12    pub runtime: String,
13    pub script: String,
14    #[serde(default)]
15    pub env: HashMap<String, String>,
16    #[serde(default)]
17    pub entry_point: String,
18    #[serde(default)]
19    pub cargo_test: String,
20    #[serde(default)]
21    pub args: Vec<String>,
22    #[serde(default)]
23    pub clm_root: String,
24}
25
26#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
27pub struct RuntimeScriptOutput {
28    pub exit_code: i32,
29    pub stdout: String,
30    pub stderr: String,
31}
32
33pub fn exec_runtime_script(input: &RuntimeScriptInput) -> Result<RuntimeScriptOutput, String> {
34    let clm_root = if input.clm_root.is_empty() {
35        std::env::var("CLM_ROOT").unwrap_or_default()
36    } else {
37        input.clm_root.clone()
38    };
39
40    let runtime = input.runtime.as_str();
41    let script_content = input.script.as_str();
42    let entry_point = input.entry_point.as_str();
43    let cargo_test_name = input.cargo_test.as_str();
44    let pos_args = &input.args;
45
46    let (code, out, err) = match runtime {
47        "shell" => {
48            let entry_call = if !entry_point.is_empty() {
49                let mut call = format!("{} ", entry_point);
50                for a in pos_args {
51                    call.push_str(&format!("\"{}\" ", a.replace('"', "\\\"")));
52                }
53                call
54            } else {
55                String::new()
56            };
57            let full_script = format!("{}\n{}", script_content, entry_call);
58            let mut cmd = create_sandboxed_command(
59                &crate::fs_utils::get_bash_command(),
60                &["-c".to_string(), full_script],
61                &input.env,
62                &clm_root,
63            );
64            let output = cmd.output().map_err(|e| format!("Failed to spawn bash: {}", e))?;
65            (
66                output.status.code().unwrap_or(0),
67                String::from_utf8_lossy(&output.stdout).into_owned(),
68                String::from_utf8_lossy(&output.stderr).into_owned(),
69            )
70        }
71        "python" => {
72            let py_cmd = resolve_python_cmd(&clm_root);
73            let mut cmd_args = vec!["-c".to_string(), script_content.to_string()];
74            cmd_args.extend(pos_args.clone());
75            let mut py_env = input.env.clone();
76            py_env.insert("PYTHONPATH".to_string(), format!("{}/kernel/scripts", clm_root));
77            let mut cmd = create_sandboxed_command(&py_cmd, &cmd_args, &py_env, &clm_root);
78            let output = cmd.output().map_err(|e| format!("Failed to spawn python: {}", e))?;
79            (
80                output.status.code().unwrap_or(0),
81                String::from_utf8_lossy(&output.stdout).into_owned(),
82                String::from_utf8_lossy(&output.stderr).into_owned(),
83            )
84        }
85        "node" => {
86            let rand_id = std::time::SystemTime::now()
87                .duration_since(std::time::UNIX_EPOCH)
88                .map(|d| d.as_nanos())
89                .unwrap_or(0);
90            let pid = std::process::id();
91            let temp_dir = std::env::temp_dir().join("clm_execution_logs/.tmp");
92            let _ = std::fs::create_dir_all(&temp_dir);
93            let temp_file = temp_dir.join(format!("clm_node_inline_{}_{}.cjs", rand_id, pid));
94            std::fs::write(&temp_file, script_content)
95                .map_err(|e| format!("Failed to write node inline script: {}", e))?;
96            let mut cmd_args = vec!["--trace-uncaught".to_string(), temp_file.to_string_lossy().to_string()];
97            cmd_args.extend(pos_args.clone());
98            let mut cmd = create_sandboxed_command("node", &cmd_args, &input.env, &clm_root);
99            let output = cmd.output();
100            let _ = std::fs::remove_file(&temp_file);
101            let output = output.map_err(|e| format!("Failed to spawn node: {}", e))?;
102            (
103                output.status.code().unwrap_or(0),
104                String::from_utf8_lossy(&output.stdout).into_owned(),
105                String::from_utf8_lossy(&output.stderr).into_owned(),
106            )
107        }
108        "rust" => {
109            if !cargo_test_name.is_empty() {
110                let self_exe = resolve_self_exe(&clm_root);
111                let mut cmd = create_sandboxed_command(
112                    &self_exe.to_string_lossy(),
113                    &["run-test".to_string(), cargo_test_name.to_string()],
114                    &input.env,
115                    &clm_root,
116                );
117                cmd.current_dir(Path::new(&clm_root).join("kernel/clm_rust_core"));
118                let output = cmd.output().map_err(|e| format!("Failed to spawn clm_rust_core: {}", e))?;
119                (
120                    output.status.code().unwrap_or(if output.status.success() { 0 } else { 1 }),
121                    String::from_utf8_lossy(&output.stdout).into_owned(),
122                    String::from_utf8_lossy(&output.stderr).into_owned(),
123                )
124            } else {
125                let rand_id = std::time::SystemTime::now()
126                    .duration_since(std::time::UNIX_EPOCH)
127                    .map(|d| d.as_nanos())
128                    .unwrap_or(0);
129                let pid = std::process::id();
130                let temp_dir = std::env::temp_dir().join("clm_execution_logs/.tmp");
131                let _ = std::fs::create_dir_all(&temp_dir);
132                let src_file = temp_dir.join(format!("clm_rust_inline_{}_{}.rs", rand_id, pid));
133                let bin_file = temp_dir.join(format!("clm_rust_bin_{}_{}", rand_id, pid));
134                let full_rust_src = if !script_content.contains("fn main") {
135                    format!("use std::io::{{self, Read}};\nfn main() {{\n{}\n}}", script_content)
136                } else {
137                    script_content.to_string()
138                };
139                std::fs::write(&src_file, full_rust_src)
140                    .map_err(|e| format!("Failed to write rust inline source: {}", e))?;
141                let compile_output = std::process::Command::new("rustc")
142                    .arg("-O")
143                    .arg("-o")
144                    .arg(&bin_file)
145                    .arg(&src_file)
146                    .output();
147                let _ = std::fs::remove_file(&src_file);
148                let compile_res = compile_output.map_err(|e| format!("Failed to run rustc: {}", e))?;
149                if !compile_res.status.success() {
150                    return Ok(RuntimeScriptOutput {
151                        exit_code: 1,
152                        stdout: String::new(),
153                        stderr: format!("Rust compilation failed:\n{}", String::from_utf8_lossy(&compile_res.stderr)),
154                    });
155                }
156                let mut cmd = std::process::Command::new(&bin_file);
157                for a in pos_args {
158                    cmd.arg(a);
159                }
160                for (k, v) in &input.env {
161                    cmd.env(k, v);
162                }
163                cmd.current_dir(&clm_root);
164                let output = cmd.output();
165                let _ = std::fs::remove_file(&bin_file);
166                let output = output.map_err(|e| format!("Failed to run rust binary: {}", e))?;
167                (
168                    output.status.code().unwrap_or(0),
169                    String::from_utf8_lossy(&output.stdout).into_owned(),
170                    String::from_utf8_lossy(&output.stderr).into_owned(),
171                )
172            }
173        }
174        _ => {
175            return Err(format!("Unsupported runtime: {}", runtime));
176        }
177    };
178
179    Ok(RuntimeScriptOutput {
180        exit_code: code,
181        stdout: out,
182        stderr: err,
183    })
184}
185