Skip to main content

clm_rust_core/
runtime_adapter.rs

1//! RuntimeAdapter trait and RuntimeDispatcher for Stage 1.3.
2//!
3//! Provides a unified dispatch interface for PCard runtime execution:
4//! - `RuntimeAdapter` trait: `fn execute(&self, script: &str, input: &Value) -> Result<Value, String>`.
5//! - `WasmRuntimeAdapter`: executes built-in handlers in WASM linear memory.
6//! - `ShellRuntimeAdapter` (native-only): spawns shell subprocess.
7//! - `PythonRuntimeAdapter` (native-only): spawns Python subprocess.
8//! - `NodeRuntimeAdapter` (native-only): spawns Node.js subprocess.
9//! - `RuntimeDispatcher`: HashMap<String, Box<dyn RuntimeAdapter>> registry.
10//!
11//! Under WASM, only `WasmRuntimeAdapter` is available. Under native, all four
12//! adapters are registered. The dispatcher replaces direct `std::process::Command`
13//! calls in `execute_pcard_binding`.
14
15use serde_json::Value;
16use std::collections::HashMap;
17
18/// Trait for executing a PCard binding script.
19///
20/// Each runtime type (shell, python, node, llm, echo, noop, math) implements
21/// this trait. The dispatcher looks up the runtime by name and calls `execute`.
22pub trait RuntimeAdapter: Send + Sync {
23    /// Execute the script with the given input and return the output.
24    fn execute(&self, script: &str, input: &Value) -> Result<Value, String>;
25
26    /// Human-readable name of this adapter (e.g. "shell", "python", "wasm").
27    fn name(&self) -> &str;
28}
29
30/// Dispatcher that maps runtime names to adapters.
31pub struct RuntimeDispatcher {
32    adapters: HashMap<String, Box<dyn RuntimeAdapter>>,
33}
34
35impl RuntimeDispatcher {
36    /// Create a new empty dispatcher.
37    pub fn new() -> Self {
38        Self {
39            adapters: HashMap::new(),
40        }
41    }
42
43    /// Create a dispatcher pre-populated with all available adapters for the
44    /// current target.
45    ///
46    /// Under WASM: only `WasmRuntimeAdapter` built-ins (echo, noop, math).
47    /// Under native: shell, python, node, plus WASM built-ins.
48    pub fn with_defaults() -> Self {
49        let mut d = Self::new();
50
51        // Built-in WASM-safe handlers (always available).
52        d.register("echo", Box::new(WasmRuntimeAdapter::Echo));
53        d.register("noop", Box::new(WasmRuntimeAdapter::Noop));
54        d.register("math", Box::new(WasmRuntimeAdapter::Math));
55
56        // Native-only adapters.
57        #[cfg(feature = "native")]
58        {
59            d.register("shell", Box::new(ShellRuntimeAdapter));
60            d.register("python", Box::new(PythonRuntimeAdapter));
61            d.register("node", Box::new(NodeRuntimeAdapter));
62            d.register("llm", Box::new(LlmRuntimeAdapter::new()));
63        }
64
65        d
66    }
67
68    /// Register an adapter under a runtime name.
69    pub fn register(&mut self, runtime: &str, adapter: Box<dyn RuntimeAdapter>) {
70        self.adapters.insert(runtime.to_string(), adapter);
71    }
72
73    /// Dispatch execution to the named runtime.
74    ///
75    /// Returns an error if the runtime is not registered.
76    pub fn dispatch(&self, runtime: &str, script: &str, input: &Value) -> Result<Value, String> {
77        let adapter = self
78            .adapters
79            .get(runtime)
80            .ok_or_else(|| format!("unknown runtime: {} (registered: {:?})", runtime, self.list_runtimes()))?;
81        adapter.execute(script, input)
82    }
83
84    /// List all registered runtime names.
85    pub fn list_runtimes(&self) -> Vec<&str> {
86        self.adapters.keys().map(|s| s.as_str()).collect()
87    }
88
89    /// Check if a runtime is registered.
90    pub fn has(&self, runtime: &str) -> bool {
91        self.adapters.contains_key(runtime)
92    }
93}
94
95impl Default for RuntimeDispatcher {
96    fn default() -> Self {
97        Self::with_defaults()
98    }
99}
100
101// ── WasmRuntimeAdapter ──────────────────────────────────────────────
102
103/// Built-in handlers that run entirely in WASM linear memory.
104/// These are always available (no subprocess, no filesystem).
105#[derive(Debug, Clone, Copy)]
106pub enum WasmRuntimeAdapter {
107    Echo,
108    Noop,
109    Math,
110}
111
112impl RuntimeAdapter for WasmRuntimeAdapter {
113    fn name(&self) -> &str {
114        match self {
115            Self::Echo => "echo",
116            Self::Noop => "noop",
117            Self::Math => "math",
118        }
119    }
120
121    fn execute(&self, script: &str, _input: &Value) -> Result<Value, String> {
122        match self {
123            Self::Echo => Ok(Value::String(script.to_string())),
124            Self::Noop => Ok(Value::String(String::new())),
125            Self::Math => {
126                let expr = script.trim();
127                for op in ['+', '-'] {
128                    if let Some(idx) = expr.find(op) {
129                        let left: i64 = expr[..idx]
130                            .trim()
131                            .parse()
132                            .map_err(|e| format!("math parse error: {e}"))?;
133                        let right: i64 = expr[idx + 1..]
134                            .trim()
135                            .parse()
136                            .map_err(|e| format!("math parse error: {e}"))?;
137                        let result = if op == '+' { left + right } else { left - right };
138                        return Ok(Value::Number(serde_json::Number::from(result)));
139                    }
140                }
141                // Also support multiplication
142                if let Some(idx) = expr.find('*') {
143                    let left: i64 = expr[..idx]
144                        .trim()
145                        .parse()
146                        .map_err(|e| format!("math parse error: {e}"))?;
147                    let right: i64 = expr[idx + 1..]
148                        .trim()
149                        .parse()
150                        .map_err(|e| format!("math parse error: {e}"))?;
151                    return Ok(Value::Number(serde_json::Number::from(left * right)));
152                }
153                Err(format!("math handler cannot evaluate: {}", expr))
154            }
155        }
156    }
157}
158
159// ── Native-only adapters ────────────────────────────────────────────
160
161#[cfg(feature = "native")]
162mod native {
163    use super::*;
164    use std::process::Command;
165
166    fn run_subprocess(cmd: &mut Command, script: &str) -> Result<Value, String> {
167        let output = cmd
168            .arg(script)
169            .output()
170            .map_err(|e| format!("subprocess failed: {e}"))?;
171        if output.status.success() {
172            let stdout = String::from_utf8_lossy(&output.stdout).to_string();
173            Ok(Value::String(stdout))
174        } else {
175            let stderr = String::from_utf8_lossy(&output.stderr).to_string();
176            Err(format!("subprocess exited {}: {}", output.status, stderr))
177        }
178    }
179
180    fn resolve_clm_root_path() -> std::path::PathBuf {
181        if let Ok(val) = std::env::var("CLM_ROOT") {
182            let path = crate::fs_utils::normalize_windows_path(std::path::Path::new(&val));
183            if path.is_absolute() {
184                return path;
185            } else if let Ok(curr) = std::env::current_dir() {
186                return curr.join(path);
187            } else {
188                return path;
189            }
190        }
191
192        if let Ok(mut dir) = std::env::current_dir() {
193            loop {
194                if dir.join("computable_knowledge/Concrete/layer5_system/bootstrap/evaluator").is_dir()
195                    || dir.join("computable_knowledge/Abstract/layer5_system/bootstrap/evaluator").is_dir() {
196                    return dir;
197                }
198                if dir.join("clm/computable_knowledge/Concrete/layer5_system/bootstrap/evaluator").is_dir()
199                    || dir.join("clm/computable_knowledge/Abstract/layer5_system/bootstrap/evaluator").is_dir() {
200                    return dir.join("clm");
201                }
202                if let Some(parent) = dir.parent() {
203                    dir = parent.to_path_buf();
204                } else {
205                    break;
206                }
207            }
208        }
209        crate::fs_utils::get_clm_root()
210    }
211
212    fn resolve_python_cmd(clm_root: &str) -> String {
213        let root_path = std::path::Path::new(clm_root);
214        let venv_py_win = root_path.join(".venv/Scripts/python.exe");
215        if venv_py_win.exists() {
216            return venv_py_win.to_string_lossy().to_string();
217        }
218        let venv_py_unix = root_path.join(".venv/bin/python3");
219        if venv_py_unix.exists() {
220            return venv_py_unix.to_string_lossy().to_string();
221        }
222        let venv_py_unix_2 = root_path.join(".venv/bin/python");
223        if venv_py_unix_2.exists() {
224            return venv_py_unix_2.to_string_lossy().to_string();
225        }
226
227        if cfg!(target_os = "windows") {
228            for cmd in &["python", "python3"] {
229                if std::process::Command::new(cmd).arg("--version").output().map(|o| o.status.success()).unwrap_or(false) {
230                    return cmd.to_string();
231                }
232            }
233        } else {
234            for cmd in &["python3", "python"] {
235                if std::process::Command::new(cmd).arg("--version").output().map(|o| o.status.success()).unwrap_or(false) {
236                    return cmd.to_string();
237                }
238            }
239        }
240        "python3".to_string()
241    }
242
243    /// Shell runtime adapter — executes scripts via `bash -c`.
244    pub struct ShellRuntimeAdapter;
245
246    impl RuntimeAdapter for ShellRuntimeAdapter {
247        fn name(&self) -> &str {
248            "shell"
249        }
250
251        fn execute(&self, script: &str, _input: &Value) -> Result<Value, String> {
252            let bash = crate::fs_utils::get_bash_command();
253            let clm_root = resolve_clm_root_path();
254            let clm_root_str = clm_root.to_string_lossy();
255            let full_script = format!(
256                "export CLM_ROOT=\"{clm_root}\"\n\
257                 clm_root() {{ echo \"$CLM_ROOT\"; }}\n\
258                 export -f clm_root 2>/dev/null || true\n\
259                 source \"{clm_root}/computable_knowledge/Concrete/layer5_system/bootstrap/evaluator/shell_utils.sh\" 2>/dev/null || true\n\
260                 source \"{clm_root}/computable_knowledge/Concrete/layer5_system/bootstrap/layer0_core/mcard_storage.sh\" 2>/dev/null || true\n\
261                 {script}",
262                clm_root = clm_root_str,
263                script = script
264            );
265            let mut cmd = Command::new(bash);
266            cmd.env("CLM_ROOT", clm_root_str.as_ref());
267            cmd.arg("-c");
268            run_subprocess(&mut cmd, &full_script)
269        }
270    }
271
272    /// Python runtime adapter — executes scripts via `python3 -c`.
273    pub struct PythonRuntimeAdapter;
274
275    impl RuntimeAdapter for PythonRuntimeAdapter {
276        fn name(&self) -> &str {
277            "python"
278        }
279
280        fn execute(&self, script: &str, _input: &Value) -> Result<Value, String> {
281            let clm_root_path = resolve_clm_root_path();
282            let clm_root_str = clm_root_path.to_string_lossy();
283            let py_cmd = resolve_python_cmd(&clm_root_str);
284            let mut cmd = Command::new(py_cmd);
285            cmd.arg("-c");
286            cmd.env("CLM_ROOT", clm_root_str.as_ref());
287            cmd.env("PYTHONPATH", format!("{}/kernel/scripts", clm_root_str));
288            run_subprocess(&mut cmd, script)
289        }
290    }
291
292    /// Node.js runtime adapter — executes scripts via `node -e`.
293    pub struct NodeRuntimeAdapter;
294
295    impl RuntimeAdapter for NodeRuntimeAdapter {
296        fn name(&self) -> &str {
297            "node"
298        }
299
300        fn execute(&self, script: &str, _input: &Value) -> Result<Value, String> {
301            let mut cmd = Command::new("node");
302            cmd.arg("-e");
303            run_subprocess(&mut cmd, script)
304        }
305    }
306
307    /// LLM runtime adapter — sends script as a prompt to an LLM API endpoint.
308    ///
309    /// Under native, uses `ureq` for synchronous HTTP POST.
310    /// Under WASM, a scaffold is provided that returns an error (async HTTP fetch
311    /// via `wasm-bindgen-futures` is future work).
312    ///
313    /// The endpoint URL and API key are read from `CLM_LLM_ENDPOINT` and
314    /// `CLM_LLM_API_KEY` environment variables. If not set, defaults to
315    /// `http://localhost:8080/v1/chat/completions` with no auth.
316    pub struct LlmRuntimeAdapter {
317        endpoint: String,
318        api_key: Option<String>,
319    }
320
321    impl LlmRuntimeAdapter {
322        pub fn new() -> Self {
323            let endpoint = std::env::var("CLM_LLM_ENDPOINT")
324                .unwrap_or_else(|_| "http://localhost:8080/v1/chat/completions".to_string());
325            let api_key = std::env::var("CLM_LLM_API_KEY").ok();
326            Self { endpoint, api_key }
327        }
328    }
329
330    impl RuntimeAdapter for LlmRuntimeAdapter {
331        fn name(&self) -> &str {
332            "llm"
333        }
334
335        fn execute(&self, script: &str, input: &Value) -> Result<Value, String> {
336            let user_message = if input.is_null() {
337                script.to_string()
338            } else {
339                format!("{}\n{}", script, input)
340            };
341
342            let body = serde_json::json!({
343                "messages": [
344                    {"role": "user", "content": user_message}
345                ],
346                "stream": false
347            });
348
349            let mut req = ureq::post(&self.endpoint)
350                .set("Content-Type", "application/json");
351            if let Some(ref key) = self.api_key {
352                req = req.set("Authorization", &format!("Bearer {}", key));
353            }
354
355            let response: Value = req
356                .send_json(body)
357                .map_err(|e| format!("LLM HTTP request failed: {}", e))?
358                .into_json()
359                .map_err(|e| format!("LLM response parse error: {}", e))?;
360
361            // Extract the assistant's message content from the response.
362            let content = response
363                .get("choices")
364                .and_then(|c| c.get(0))
365                .and_then(|c| c.get("message"))
366                .and_then(|m| m.get("content"))
367                .and_then(|c| c.as_str())
368                .unwrap_or("")
369                .to_string();
370
371            Ok(Value::String(content))
372        }
373    }
374}
375
376#[cfg(feature = "native")]
377pub use native::{LlmRuntimeAdapter, NodeRuntimeAdapter, PythonRuntimeAdapter, ShellRuntimeAdapter};
378
379// ── Tests ───────────────────────────────────────────────────────────
380
381#[cfg(test)]
382mod tests {
383    use super::*;
384
385    #[test]
386    fn test_dispatcher_registers_builtin_handlers() {
387        let d = RuntimeDispatcher::with_defaults();
388        assert!(d.has("echo"));
389        assert!(d.has("noop"));
390        assert!(d.has("math"));
391    }
392
393    #[test]
394    fn test_dispatcher_echo() {
395        let d = RuntimeDispatcher::with_defaults();
396        let result = d.dispatch("echo", "hello world", &Value::Null).unwrap();
397        assert_eq!(result, Value::String("hello world".to_string()));
398    }
399
400    #[test]
401    fn test_dispatcher_noop() {
402        let d = RuntimeDispatcher::with_defaults();
403        let result = d.dispatch("noop", "ignored", &Value::Null).unwrap();
404        assert_eq!(result, Value::String(String::new()));
405    }
406
407    #[test]
408    fn test_dispatcher_math_addition() {
409        let d = RuntimeDispatcher::with_defaults();
410        let result = d.dispatch("math", "3 + 4", &Value::Null).unwrap();
411        assert_eq!(result, Value::Number(serde_json::Number::from(7)));
412    }
413
414    #[test]
415    fn test_dispatcher_math_subtraction() {
416        let d = RuntimeDispatcher::with_defaults();
417        let result = d.dispatch("math", "10 - 3", &Value::Null).unwrap();
418        assert_eq!(result, Value::Number(serde_json::Number::from(7)));
419    }
420
421    #[test]
422    fn test_dispatcher_math_multiplication() {
423        let d = RuntimeDispatcher::with_defaults();
424        let result = d.dispatch("math", "6 * 7", &Value::Null).unwrap();
425        assert_eq!(result, Value::Number(serde_json::Number::from(42)));
426    }
427
428    #[test]
429    fn test_dispatcher_unknown_runtime_errors() {
430        let d = RuntimeDispatcher::with_defaults();
431        let result = d.dispatch("nonexistent", "script", &Value::Null);
432        assert!(result.is_err());
433        assert!(result.unwrap_err().contains("unknown runtime"));
434    }
435
436    #[test]
437    fn test_dispatcher_list_runtimes() {
438        let d = RuntimeDispatcher::with_defaults();
439        let runtimes = d.list_runtimes();
440        assert!(runtimes.contains(&"echo"));
441        assert!(runtimes.contains(&"noop"));
442        assert!(runtimes.contains(&"math"));
443    }
444
445    #[test]
446    fn test_dispatcher_custom_adapter() {
447        struct UpperAdapter;
448        impl RuntimeAdapter for UpperAdapter {
449            fn name(&self) -> &str {
450                "upper"
451            }
452            fn execute(&self, script: &str, _input: &Value) -> Result<Value, String> {
453                Ok(Value::String(script.to_uppercase()))
454            }
455        }
456
457        let mut d = RuntimeDispatcher::new();
458        d.register("upper", Box::new(UpperAdapter));
459        let result = d.dispatch("upper", "hello", &Value::Null).unwrap();
460        assert_eq!(result, Value::String("HELLO".to_string()));
461    }
462
463    #[cfg(feature = "native")]
464    #[test]
465    fn test_dispatcher_has_native_adapters() {
466        let d = RuntimeDispatcher::with_defaults();
467        assert!(d.has("shell"));
468        assert!(d.has("python"));
469        assert!(d.has("node"));
470        assert!(d.has("llm"));
471    }
472
473    #[cfg(feature = "native")]
474    #[test]
475    fn test_dispatcher_shell_echo() {
476        let d = RuntimeDispatcher::with_defaults();
477        let result = d.dispatch("shell", "echo hello_from_shell", &Value::Null).unwrap();
478        assert!(result.as_str().unwrap().contains("hello_from_shell"));
479    }
480
481    #[test]
482    fn test_wasm_adapter_implements_trait() {
483        let echo: Box<dyn RuntimeAdapter> = Box::new(WasmRuntimeAdapter::Echo);
484        assert_eq!(echo.name(), "echo");
485        let result = echo.execute("test", &Value::Null).unwrap();
486        assert_eq!(result, Value::String("test".to_string()));
487    }
488}