use serde_json::Value;
use std::collections::HashMap;
pub trait RuntimeAdapter: Send + Sync {
fn execute(&self, script: &str, input: &Value) -> Result<Value, String>;
fn name(&self) -> &str;
}
pub struct RuntimeDispatcher {
adapters: HashMap<String, Box<dyn RuntimeAdapter>>,
}
impl RuntimeDispatcher {
pub fn new() -> Self {
Self {
adapters: HashMap::new(),
}
}
pub fn with_defaults() -> Self {
let mut d = Self::new();
d.register("echo", Box::new(WasmRuntimeAdapter::Echo));
d.register("noop", Box::new(WasmRuntimeAdapter::Noop));
d.register("math", Box::new(WasmRuntimeAdapter::Math));
#[cfg(feature = "native")]
{
d.register("shell", Box::new(ShellRuntimeAdapter));
d.register("python", Box::new(PythonRuntimeAdapter));
d.register("node", Box::new(NodeRuntimeAdapter));
d.register("llm", Box::new(LlmRuntimeAdapter::new()));
}
d
}
pub fn register(&mut self, runtime: &str, adapter: Box<dyn RuntimeAdapter>) {
self.adapters.insert(runtime.to_string(), adapter);
}
pub fn dispatch(&self, runtime: &str, script: &str, input: &Value) -> Result<Value, String> {
let adapter = self
.adapters
.get(runtime)
.ok_or_else(|| format!("unknown runtime: {} (registered: {:?})", runtime, self.list_runtimes()))?;
adapter.execute(script, input)
}
pub fn list_runtimes(&self) -> Vec<&str> {
self.adapters.keys().map(|s| s.as_str()).collect()
}
pub fn has(&self, runtime: &str) -> bool {
self.adapters.contains_key(runtime)
}
}
impl Default for RuntimeDispatcher {
fn default() -> Self {
Self::with_defaults()
}
}
#[derive(Debug, Clone, Copy)]
pub enum WasmRuntimeAdapter {
Echo,
Noop,
Math,
}
impl RuntimeAdapter for WasmRuntimeAdapter {
fn name(&self) -> &str {
match self {
Self::Echo => "echo",
Self::Noop => "noop",
Self::Math => "math",
}
}
fn execute(&self, script: &str, _input: &Value) -> Result<Value, String> {
match self {
Self::Echo => Ok(Value::String(script.to_string())),
Self::Noop => Ok(Value::String(String::new())),
Self::Math => {
let expr = script.trim();
for op in ['+', '-'] {
if let Some(idx) = expr.find(op) {
let left: i64 = expr[..idx]
.trim()
.parse()
.map_err(|e| format!("math parse error: {e}"))?;
let right: i64 = expr[idx + 1..]
.trim()
.parse()
.map_err(|e| format!("math parse error: {e}"))?;
let result = if op == '+' { left + right } else { left - right };
return Ok(Value::Number(serde_json::Number::from(result)));
}
}
if let Some(idx) = expr.find('*') {
let left: i64 = expr[..idx]
.trim()
.parse()
.map_err(|e| format!("math parse error: {e}"))?;
let right: i64 = expr[idx + 1..]
.trim()
.parse()
.map_err(|e| format!("math parse error: {e}"))?;
return Ok(Value::Number(serde_json::Number::from(left * right)));
}
Err(format!("math handler cannot evaluate: {}", expr))
}
}
}
}
#[cfg(feature = "native")]
mod native {
use super::*;
use std::process::Command;
fn run_subprocess(cmd: &mut Command, script: &str) -> Result<Value, String> {
let output = cmd
.arg(script)
.output()
.map_err(|e| format!("subprocess failed: {e}"))?;
if output.status.success() {
let stdout = String::from_utf8_lossy(&output.stdout).to_string();
Ok(Value::String(stdout))
} else {
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
Err(format!("subprocess exited {}: {}", output.status, stderr))
}
}
fn resolve_clm_root_path() -> std::path::PathBuf {
if let Ok(val) = std::env::var("CLM_ROOT") {
let path = crate::fs_utils::normalize_windows_path(std::path::Path::new(&val));
if path.is_absolute() {
return path;
} else if let Ok(curr) = std::env::current_dir() {
return curr.join(path);
} else {
return path;
}
}
if let Ok(mut dir) = std::env::current_dir() {
loop {
if dir.join("computable_knowledge/Concrete/layer5_system/bootstrap/evaluator").is_dir()
|| dir.join("computable_knowledge/Abstract/layer5_system/bootstrap/evaluator").is_dir() {
return dir;
}
if dir.join("clm/computable_knowledge/Concrete/layer5_system/bootstrap/evaluator").is_dir()
|| dir.join("clm/computable_knowledge/Abstract/layer5_system/bootstrap/evaluator").is_dir() {
return dir.join("clm");
}
if let Some(parent) = dir.parent() {
dir = parent.to_path_buf();
} else {
break;
}
}
}
crate::fs_utils::get_clm_root()
}
fn resolve_python_cmd(clm_root: &str) -> String {
let root_path = std::path::Path::new(clm_root);
let venv_py_win = root_path.join(".venv/Scripts/python.exe");
if venv_py_win.exists() {
return venv_py_win.to_string_lossy().to_string();
}
let venv_py_unix = root_path.join(".venv/bin/python3");
if venv_py_unix.exists() {
return venv_py_unix.to_string_lossy().to_string();
}
let venv_py_unix_2 = root_path.join(".venv/bin/python");
if venv_py_unix_2.exists() {
return venv_py_unix_2.to_string_lossy().to_string();
}
if cfg!(target_os = "windows") {
for cmd in &["python", "python3"] {
if std::process::Command::new(cmd).arg("--version").output().map(|o| o.status.success()).unwrap_or(false) {
return cmd.to_string();
}
}
} else {
for cmd in &["python3", "python"] {
if std::process::Command::new(cmd).arg("--version").output().map(|o| o.status.success()).unwrap_or(false) {
return cmd.to_string();
}
}
}
"python3".to_string()
}
pub struct ShellRuntimeAdapter;
impl RuntimeAdapter for ShellRuntimeAdapter {
fn name(&self) -> &str {
"shell"
}
fn execute(&self, script: &str, _input: &Value) -> Result<Value, String> {
let bash = crate::fs_utils::get_bash_command();
let clm_root = resolve_clm_root_path();
let clm_root_str = clm_root.to_string_lossy();
let full_script = format!(
"export CLM_ROOT=\"{clm_root}\"\n\
clm_root() {{ echo \"$CLM_ROOT\"; }}\n\
export -f clm_root 2>/dev/null || true\n\
source \"{clm_root}/computable_knowledge/Concrete/layer5_system/bootstrap/evaluator/shell_utils.sh\" 2>/dev/null || true\n\
source \"{clm_root}/computable_knowledge/Concrete/layer5_system/bootstrap/layer0_core/mcard_storage.sh\" 2>/dev/null || true\n\
{script}",
clm_root = clm_root_str,
script = script
);
let mut cmd = Command::new(bash);
cmd.env("CLM_ROOT", clm_root_str.as_ref());
cmd.arg("-c");
run_subprocess(&mut cmd, &full_script)
}
}
pub struct PythonRuntimeAdapter;
impl RuntimeAdapter for PythonRuntimeAdapter {
fn name(&self) -> &str {
"python"
}
fn execute(&self, script: &str, _input: &Value) -> Result<Value, String> {
let clm_root_path = resolve_clm_root_path();
let clm_root_str = clm_root_path.to_string_lossy();
let py_cmd = resolve_python_cmd(&clm_root_str);
let mut cmd = Command::new(py_cmd);
cmd.arg("-c");
cmd.env("CLM_ROOT", clm_root_str.as_ref());
cmd.env("PYTHONPATH", format!("{}/kernel/scripts", clm_root_str));
run_subprocess(&mut cmd, script)
}
}
pub struct NodeRuntimeAdapter;
impl RuntimeAdapter for NodeRuntimeAdapter {
fn name(&self) -> &str {
"node"
}
fn execute(&self, script: &str, _input: &Value) -> Result<Value, String> {
let mut cmd = Command::new("node");
cmd.arg("-e");
run_subprocess(&mut cmd, script)
}
}
pub struct LlmRuntimeAdapter {
endpoint: String,
api_key: Option<String>,
}
impl LlmRuntimeAdapter {
pub fn new() -> Self {
let endpoint = std::env::var("CLM_LLM_ENDPOINT")
.unwrap_or_else(|_| "http://localhost:8080/v1/chat/completions".to_string());
let api_key = std::env::var("CLM_LLM_API_KEY").ok();
Self { endpoint, api_key }
}
}
impl RuntimeAdapter for LlmRuntimeAdapter {
fn name(&self) -> &str {
"llm"
}
fn execute(&self, script: &str, input: &Value) -> Result<Value, String> {
let user_message = if input.is_null() {
script.to_string()
} else {
format!("{}\n{}", script, input)
};
let body = serde_json::json!({
"messages": [
{"role": "user", "content": user_message}
],
"stream": false
});
let mut req = ureq::post(&self.endpoint)
.set("Content-Type", "application/json");
if let Some(ref key) = self.api_key {
req = req.set("Authorization", &format!("Bearer {}", key));
}
let response: Value = req
.send_json(body)
.map_err(|e| format!("LLM HTTP request failed: {}", e))?
.into_json()
.map_err(|e| format!("LLM response parse error: {}", e))?;
let content = response
.get("choices")
.and_then(|c| c.get(0))
.and_then(|c| c.get("message"))
.and_then(|m| m.get("content"))
.and_then(|c| c.as_str())
.unwrap_or("")
.to_string();
Ok(Value::String(content))
}
}
}
#[cfg(feature = "native")]
pub use native::{LlmRuntimeAdapter, NodeRuntimeAdapter, PythonRuntimeAdapter, ShellRuntimeAdapter};
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_dispatcher_registers_builtin_handlers() {
let d = RuntimeDispatcher::with_defaults();
assert!(d.has("echo"));
assert!(d.has("noop"));
assert!(d.has("math"));
}
#[test]
fn test_dispatcher_echo() {
let d = RuntimeDispatcher::with_defaults();
let result = d.dispatch("echo", "hello world", &Value::Null).unwrap();
assert_eq!(result, Value::String("hello world".to_string()));
}
#[test]
fn test_dispatcher_noop() {
let d = RuntimeDispatcher::with_defaults();
let result = d.dispatch("noop", "ignored", &Value::Null).unwrap();
assert_eq!(result, Value::String(String::new()));
}
#[test]
fn test_dispatcher_math_addition() {
let d = RuntimeDispatcher::with_defaults();
let result = d.dispatch("math", "3 + 4", &Value::Null).unwrap();
assert_eq!(result, Value::Number(serde_json::Number::from(7)));
}
#[test]
fn test_dispatcher_math_subtraction() {
let d = RuntimeDispatcher::with_defaults();
let result = d.dispatch("math", "10 - 3", &Value::Null).unwrap();
assert_eq!(result, Value::Number(serde_json::Number::from(7)));
}
#[test]
fn test_dispatcher_math_multiplication() {
let d = RuntimeDispatcher::with_defaults();
let result = d.dispatch("math", "6 * 7", &Value::Null).unwrap();
assert_eq!(result, Value::Number(serde_json::Number::from(42)));
}
#[test]
fn test_dispatcher_unknown_runtime_errors() {
let d = RuntimeDispatcher::with_defaults();
let result = d.dispatch("nonexistent", "script", &Value::Null);
assert!(result.is_err());
assert!(result.unwrap_err().contains("unknown runtime"));
}
#[test]
fn test_dispatcher_list_runtimes() {
let d = RuntimeDispatcher::with_defaults();
let runtimes = d.list_runtimes();
assert!(runtimes.contains(&"echo"));
assert!(runtimes.contains(&"noop"));
assert!(runtimes.contains(&"math"));
}
#[test]
fn test_dispatcher_custom_adapter() {
struct UpperAdapter;
impl RuntimeAdapter for UpperAdapter {
fn name(&self) -> &str {
"upper"
}
fn execute(&self, script: &str, _input: &Value) -> Result<Value, String> {
Ok(Value::String(script.to_uppercase()))
}
}
let mut d = RuntimeDispatcher::new();
d.register("upper", Box::new(UpperAdapter));
let result = d.dispatch("upper", "hello", &Value::Null).unwrap();
assert_eq!(result, Value::String("HELLO".to_string()));
}
#[cfg(feature = "native")]
#[test]
fn test_dispatcher_has_native_adapters() {
let d = RuntimeDispatcher::with_defaults();
assert!(d.has("shell"));
assert!(d.has("python"));
assert!(d.has("node"));
assert!(d.has("llm"));
}
#[cfg(feature = "native")]
#[test]
fn test_dispatcher_shell_echo() {
let d = RuntimeDispatcher::with_defaults();
let result = d.dispatch("shell", "echo hello_from_shell", &Value::Null).unwrap();
assert!(result.as_str().unwrap().contains("hello_from_shell"));
}
#[test]
fn test_wasm_adapter_implements_trait() {
let echo: Box<dyn RuntimeAdapter> = Box::new(WasmRuntimeAdapter::Echo);
assert_eq!(echo.name(), "echo");
let result = echo.execute("test", &Value::Null).unwrap();
assert_eq!(result, Value::String("test".to_string()));
}
}