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