Skip to main content

clm_rust_core/layer1/
runtime_dispatcher.rs

1//! RuntimeDispatcher extracted from `runtime_adapter.rs` (Sprint 534 ratchet).
2
3use super::*;
4
5/// Dispatcher that maps runtime names to adapters.
6pub struct RuntimeDispatcher {
7    adapters: HashMap<String, Box<dyn RuntimeAdapter>>,
8}
9
10impl RuntimeDispatcher {
11    /// Create a new empty dispatcher.
12    pub fn new() -> Self {
13        Self {
14            adapters: HashMap::new(),
15        }
16    }
17
18    /// Create a dispatcher pre-populated with all available adapters for the
19    /// current target.
20    ///
21    /// Populates built-in adapters (echo, noop, math) and native subprocess adapters.
22    pub fn with_defaults() -> Self {
23        let mut d = Self::new();
24
25        // Built-in handlers (always available).
26        d.register("echo", Box::new(BuiltinRuntimeAdapter::Echo));
27        d.register("noop", Box::new(BuiltinRuntimeAdapter::Noop));
28        d.register("math", Box::new(BuiltinRuntimeAdapter::Math));
29
30        // Native-only adapters.
31        #[cfg(feature = "native")]
32        {
33            d.register("shell", Box::new(ShellRuntimeAdapter));
34            d.register("python", Box::new(PythonRuntimeAdapter));
35            d.register("node", Box::new(NodeRuntimeAdapter));
36            d.register("llm", Box::new(LlmRuntimeAdapter::new()));
37        }
38
39        d
40    }
41
42    /// Register an adapter under a runtime name.
43    pub fn register(&mut self, runtime: &str, adapter: Box<dyn RuntimeAdapter>) {
44        self.adapters.insert(runtime.to_string(), adapter);
45    }
46
47    /// Dispatch execution to the named runtime.
48    ///
49    /// Returns an error if the runtime is not registered.
50    pub fn dispatch(&self, runtime: &str, script: &str, input: &Value) -> Result<Value, String> {
51        let adapter = self
52            .adapters
53            .get(runtime)
54            .ok_or_else(|| format!("unknown runtime: {} (registered: {:?})", runtime, self.list_runtimes()))?;
55        adapter.execute(script, input)
56    }
57
58    /// List all registered runtime names.
59    pub fn list_runtimes(&self) -> Vec<&str> {
60        self.adapters.keys().map(|s| s.as_str()).collect()
61    }
62
63    /// Check if a runtime is registered.
64    pub fn has(&self, runtime: &str) -> bool {
65        self.adapters.contains_key(runtime)
66    }
67}
68
69impl Default for RuntimeDispatcher {
70    fn default() -> Self {
71        Self::with_defaults()
72    }
73}