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 Default for LlmRuntimeAdapter {
322        fn default() -> Self {
323            Self::new()
324        }
325    }
326
327    impl LlmRuntimeAdapter {
328        pub fn new() -> Self {
329            let endpoint = std::env::var("CLM_LLM_ENDPOINT")
330                .unwrap_or_else(|_| "http://localhost:8080/v1/chat/completions".to_string());
331            let api_key = std::env::var("CLM_LLM_API_KEY").ok();
332            Self { endpoint, api_key }
333        }
334    }
335
336    impl RuntimeAdapter for LlmRuntimeAdapter {
337        fn name(&self) -> &str {
338            "llm"
339        }
340
341        fn execute(&self, script: &str, input: &Value) -> Result<Value, String> {
342            let user_message = if input.is_null() {
343                script.to_string()
344            } else {
345                format!("{}\n{}", script, input)
346            };
347
348            let body = serde_json::json!({
349                "messages": [
350                    {"role": "user", "content": user_message}
351                ],
352                "stream": false
353            });
354
355            let mut req = ureq::post(&self.endpoint)
356                .set("Content-Type", "application/json");
357            if let Some(ref key) = self.api_key {
358                req = req.set("Authorization", &format!("Bearer {}", key));
359            }
360
361            let response: Value = req
362                .send_json(body)
363                .map_err(|e| format!("LLM HTTP request failed: {}", e))?
364                .into_json()
365                .map_err(|e| format!("LLM response parse error: {}", e))?;
366
367            // Extract the assistant's message content from the response.
368            let content = response
369                .get("choices")
370                .and_then(|c| c.get(0))
371                .and_then(|c| c.get("message"))
372                .and_then(|m| m.get("content"))
373                .and_then(|c| c.as_str())
374                .unwrap_or("")
375                .to_string();
376
377            Ok(Value::String(content))
378        }
379    }
380}
381
382#[cfg(feature = "native")]
383pub use native::{LlmRuntimeAdapter, NodeRuntimeAdapter, PythonRuntimeAdapter, ShellRuntimeAdapter};
384
385// ── Tests ───────────────────────────────────────────────────────────
386
387#[cfg(test)]
388mod tests {
389    use super::*;
390
391    #[test]
392    fn test_dispatcher_registers_builtin_handlers() {
393        let d = RuntimeDispatcher::with_defaults();
394        assert!(d.has("echo"));
395        assert!(d.has("noop"));
396        assert!(d.has("math"));
397    }
398
399    #[test]
400    fn test_dispatcher_echo() {
401        let d = RuntimeDispatcher::with_defaults();
402        let result = d.dispatch("echo", "hello world", &Value::Null).unwrap();
403        assert_eq!(result, Value::String("hello world".to_string()));
404    }
405
406    #[test]
407    fn test_dispatcher_noop() {
408        let d = RuntimeDispatcher::with_defaults();
409        let result = d.dispatch("noop", "ignored", &Value::Null).unwrap();
410        assert_eq!(result, Value::String(String::new()));
411    }
412
413    #[test]
414    fn test_dispatcher_math_addition() {
415        let d = RuntimeDispatcher::with_defaults();
416        let result = d.dispatch("math", "3 + 4", &Value::Null).unwrap();
417        assert_eq!(result, Value::Number(serde_json::Number::from(7)));
418    }
419
420    #[test]
421    fn test_dispatcher_math_subtraction() {
422        let d = RuntimeDispatcher::with_defaults();
423        let result = d.dispatch("math", "10 - 3", &Value::Null).unwrap();
424        assert_eq!(result, Value::Number(serde_json::Number::from(7)));
425    }
426
427    #[test]
428    fn test_dispatcher_math_multiplication() {
429        let d = RuntimeDispatcher::with_defaults();
430        let result = d.dispatch("math", "6 * 7", &Value::Null).unwrap();
431        assert_eq!(result, Value::Number(serde_json::Number::from(42)));
432    }
433
434    #[test]
435    fn test_dispatcher_unknown_runtime_errors() {
436        let d = RuntimeDispatcher::with_defaults();
437        let result = d.dispatch("nonexistent", "script", &Value::Null);
438        assert!(result.is_err());
439        assert!(result.unwrap_err().contains("unknown runtime"));
440    }
441
442    #[test]
443    fn test_dispatcher_list_runtimes() {
444        let d = RuntimeDispatcher::with_defaults();
445        let runtimes = d.list_runtimes();
446        assert!(runtimes.contains(&"echo"));
447        assert!(runtimes.contains(&"noop"));
448        assert!(runtimes.contains(&"math"));
449    }
450
451    #[test]
452    fn test_dispatcher_custom_adapter() {
453        struct UpperAdapter;
454        impl RuntimeAdapter for UpperAdapter {
455            fn name(&self) -> &str {
456                "upper"
457            }
458            fn execute(&self, script: &str, _input: &Value) -> Result<Value, String> {
459                Ok(Value::String(script.to_uppercase()))
460            }
461        }
462
463        let mut d = RuntimeDispatcher::new();
464        d.register("upper", Box::new(UpperAdapter));
465        let result = d.dispatch("upper", "hello", &Value::Null).unwrap();
466        assert_eq!(result, Value::String("HELLO".to_string()));
467    }
468
469    #[cfg(feature = "native")]
470    #[test]
471    fn test_dispatcher_has_native_adapters() {
472        let d = RuntimeDispatcher::with_defaults();
473        assert!(d.has("shell"));
474        assert!(d.has("python"));
475        assert!(d.has("node"));
476        assert!(d.has("llm"));
477    }
478
479    #[cfg(feature = "native")]
480    #[test]
481    fn test_dispatcher_shell_echo() {
482        let d = RuntimeDispatcher::with_defaults();
483        let result = d.dispatch("shell", "echo hello_from_shell", &Value::Null).unwrap();
484        assert!(result.as_str().unwrap().contains("hello_from_shell"));
485    }
486
487    #[test]
488    fn test_wasm_adapter_implements_trait() {
489        let echo: Box<dyn RuntimeAdapter> = Box::new(WasmRuntimeAdapter::Echo);
490        assert_eq!(echo.name(), "echo");
491        let result = echo.execute("test", &Value::Null).unwrap();
492        assert_eq!(result, Value::String("test".to_string()));
493    }
494}