1use serde_json::Value;
16use std::collections::HashMap;
17
18pub trait RuntimeAdapter: Send + Sync {
23 fn execute(&self, script: &str, input: &Value) -> Result<Value, String>;
25
26 fn name(&self) -> &str;
28}
29
30pub struct RuntimeDispatcher {
32 adapters: HashMap<String, Box<dyn RuntimeAdapter>>,
33}
34
35impl RuntimeDispatcher {
36 pub fn new() -> Self {
38 Self {
39 adapters: HashMap::new(),
40 }
41 }
42
43 pub fn with_defaults() -> Self {
49 let mut d = Self::new();
50
51 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 #[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 pub fn register(&mut self, runtime: &str, adapter: Box<dyn RuntimeAdapter>) {
70 self.adapters.insert(runtime.to_string(), adapter);
71 }
72
73 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 pub fn list_runtimes(&self) -> Vec<&str> {
86 self.adapters.keys().map(|s| s.as_str()).collect()
87 }
88
89 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#[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 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#[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 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 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 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 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 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#[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}