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