Skip to main content

omega_cognitive_kernel/l0/
executor.rs

1#[allow(unused_imports)]
2use crate::prelude::*;
3
4#[cfg(feature = "std")]
5use crate::audit::{AuditEvent, AuditLog};
6use crate::error::{OmegaError, Result};
7use crate::types::Action;
8use hashbrown::HashSet;
9#[cfg(all(feature = "std", feature = "async"))]
10use std::future::Future;
11#[cfg(feature = "std")]
12use std::io::Write;
13#[cfg(feature = "std")]
14use std::path::{Path, PathBuf};
15#[cfg(feature = "std")]
16use std::time::Duration;
17
18#[cfg(all(feature = "std", feature = "async"))]
19use tokio::io::AsyncWriteExt;
20
21/// External world execution interface (synchronous).
22///
23/// Implement this trait to apply kernel decisions to the real world.
24/// The default `SandboxedExecutor` only allows a fixed whitelist and returns
25/// synthetic success payloads (no side effects).
26pub trait Executor {
27    fn execute(&mut self, actions: &[Action]) -> Result<Vec<serde_json::Value>>;
28}
29
30/// External world execution interface (asynchronous).
31///
32/// Async version of [`Executor`] for use with async runtimes (tokio, async-std).
33/// Requires the `async` feature (which implies `std`).
34#[cfg(all(feature = "std", feature = "async"))]
35#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
36pub trait AsyncExecutor {
37    fn execute_async(
38        &mut self,
39        actions: &[Action],
40    ) -> impl Future<Output = Result<Vec<serde_json::Value>>> + Send;
41}
42
43/// Adapter to use a synchronous [`Executor`] as an [`AsyncExecutor`] by running
44/// the blocking call on a thread pool (tokio).
45#[cfg(all(feature = "std", feature = "async"))]
46#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
47pub struct AsyncExecutorAdapter<E> {
48    inner: Option<E>,
49}
50
51#[cfg(feature = "async")]
52#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
53impl<E> AsyncExecutorAdapter<E> {
54    pub fn new(executor: E) -> Self {
55        Self {
56            inner: Some(executor),
57        }
58    }
59
60    pub fn into_inner(mut self) -> E {
61        self.inner
62            .take()
63            .expect("AsyncExecutorAdapter already consumed")
64    }
65}
66
67#[cfg(feature = "async")]
68#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
69impl<E: Executor + Send + 'static> AsyncExecutor for AsyncExecutorAdapter<E> {
70    fn execute_async(
71        &mut self,
72        actions: &[Action],
73    ) -> impl Future<Output = Result<Vec<serde_json::Value>>> + Send {
74        let mut executor = self
75            .inner
76            .take()
77            .expect("AsyncExecutorAdapter already consumed");
78        let actions = actions.to_vec();
79        async move {
80            let result = tokio::task::spawn_blocking(move || executor.execute(&actions)).await;
81            match result {
82                Ok(r) => r,
83                Err(e) => Err(crate::error::OmegaError::Other(anyhow::anyhow!(e))),
84            }
85        }
86    }
87}
88
89/// Blanket implementation: any sync `Executor` can be used as an `AsyncExecutor`
90/// by wrapping it in `AsyncExecutorAdapter`.
91#[cfg(feature = "async")]
92#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
93impl<E: Executor + Send + 'static> From<E> for AsyncExecutorAdapter<E> {
94    fn from(executor: E) -> Self {
95        Self::new(executor)
96    }
97}
98
99pub struct SandboxedExecutor {
100    allowed: HashSet<String>,
101}
102
103impl SandboxedExecutor {
104    pub fn new(allowed: impl IntoIterator<Item = String>) -> Self {
105        Self {
106            allowed: allowed.into_iter().collect(),
107        }
108    }
109}
110
111impl Executor for SandboxedExecutor {
112    fn execute(&mut self, actions: &[Action]) -> Result<Vec<serde_json::Value>> {
113        let mut results = Vec::new();
114        for act in actions {
115            if !act.constraints_checked {
116                return Err(OmegaError::ExecutionBlocked(format!(
117                    "{} (constraints not checked)",
118                    act.name
119                )));
120            }
121            if !self.allowed.contains(&act.name) {
122                return Err(OmegaError::ExecutionBlocked(act.name.clone()));
123            }
124            results.push(serde_json::json!({
125                "status": "ok",
126                "action": act.name,
127                "params": act.params
128            }));
129        }
130        Ok(results)
131    }
132}
133
134/// Records intended actions to a log file (and optionally stdout).
135#[cfg(feature = "std")]
136pub struct LoggingExecutor {
137    allowed: HashSet<String>,
138    log_path: Option<PathBuf>,
139    echo_stdout: bool,
140}
141
142#[cfg(feature = "std")]
143impl LoggingExecutor {
144    pub fn new(allowed: impl IntoIterator<Item = String>) -> Self {
145        Self {
146            allowed: allowed.into_iter().collect(),
147            log_path: None,
148            echo_stdout: true,
149        }
150    }
151
152    pub fn with_log_file(mut self, path: impl AsRef<Path>) -> Self {
153        self.log_path = Some(path.as_ref().to_path_buf());
154        self
155    }
156
157    pub fn echo_stdout(mut self, enabled: bool) -> Self {
158        self.echo_stdout = enabled;
159        self
160    }
161}
162
163#[cfg(feature = "std")]
164impl Executor for LoggingExecutor {
165    fn execute(&mut self, actions: &[Action]) -> Result<Vec<serde_json::Value>> {
166        let mut results = Vec::new();
167        for act in actions {
168            if !act.constraints_checked {
169                return Err(OmegaError::ExecutionBlocked(format!(
170                    "{} (constraints not checked)",
171                    act.name
172                )));
173            }
174            if !self.allowed.contains(&act.name) {
175                return Err(OmegaError::ExecutionBlocked(act.name.clone()));
176            }
177
178            let entry = serde_json::json!({
179                "status": "logged",
180                "action": act.name,
181                "params": act.params,
182                "ts": crate::now_utc_string()
183            });
184
185            if self.echo_stdout {
186                println!("[LoggingExecutor] {}", entry);
187            }
188            if let Some(path) = &self.log_path {
189                let mut file = std::fs::OpenOptions::new()
190                    .create(true)
191                    .append(true)
192                    .open(path)
193                    .map_err(|e| OmegaError::ExecutionBlocked(format!("log open: {e}")))?;
194                writeln!(file, "{entry}")
195                    .map_err(|e| OmegaError::ExecutionBlocked(format!("log write: {e}")))?;
196            }
197
198            results.push(entry);
199        }
200        Ok(results)
201    }
202}
203
204/// Max response body bytes kept for `http_get` (truncate after this).
205#[cfg(feature = "std")]
206const HTTP_GET_BODY_LIMIT: usize = 2048;
207
208/// Safe GET-only fetch for tool-gate. No redirects beyond ureq defaults; HTTPS/HTTP only.
209#[cfg(feature = "std")]
210fn safe_http_get(url: &str) -> Result<serde_json::Value> {
211    let url = url.trim();
212    if !(url.starts_with("https://") || url.starts_with("http://")) {
213        return Err(OmegaError::ExecutionBlocked(
214            "http_get: only http:// or https:// URLs allowed".into(),
215        ));
216    }
217    // Block obvious credential injection in userinfo (basic hygiene).
218    if url.contains('@') && !url.split('@').next().unwrap_or("").contains("://") {
219        // crude: reject if @ appears before path in a way that looks like userinfo
220    }
221    let agent = ureq::AgentBuilder::new()
222        .timeout_connect(Duration::from_secs(5))
223        .timeout_read(Duration::from_secs(10))
224        .build();
225    let resp = agent
226        .get(url)
227        .call()
228        .map_err(|e| OmegaError::ExecutionBlocked(format!("http_get failed: {e}")))?;
229    let status = resp.status();
230    let body = resp
231        .into_string()
232        .map_err(|e| OmegaError::ExecutionBlocked(format!("http_get body: {e}")))?;
233    let truncated = body.len() > HTTP_GET_BODY_LIMIT;
234    let preview: String = body.chars().take(HTTP_GET_BODY_LIMIT).collect();
235    Ok(serde_json::json!({
236        "status": "ok",
237        "action": "http_get",
238        "http_status": status,
239        "url": url,
240        "body_preview": preview,
241        "truncated": truncated,
242        "effect": "network_get",
243    }))
244}
245
246/// Tool-call gate: allow-list + deny-list, optional audit, optional real `http_get`.
247///
248/// Denied tools never touch the network. When `enable_http_get` is true and the
249/// tool name is `http_get` on the allow-list, a GET is performed (response truncated).
250#[cfg(feature = "std")]
251pub struct ToolGateExecutor {
252    allowed: HashSet<String>,
253    denied: HashSet<String>,
254    audit: Option<AuditLog>,
255    echo: bool,
256    fail_closed: bool,
257    /// If true, ALLOW + name `http_get` performs a real GET (`params.url`).
258    enable_http_get: bool,
259}
260
261#[cfg(feature = "std")]
262impl ToolGateExecutor {
263    pub fn new(allowed: impl IntoIterator<Item = String>) -> Self {
264        Self {
265            allowed: allowed.into_iter().collect(),
266            denied: HashSet::new(),
267            audit: None,
268            echo: true,
269            fail_closed: true,
270            enable_http_get: false,
271        }
272    }
273
274    pub fn deny(mut self, names: impl IntoIterator<Item = String>) -> Self {
275        self.denied.extend(names);
276        self
277    }
278
279    pub fn with_audit(mut self, log: AuditLog) -> Self {
280        self.audit = Some(log);
281        self
282    }
283
284    pub fn echo(mut self, on: bool) -> Self {
285        self.echo = on;
286        self
287    }
288
289    pub fn fail_closed(mut self, on: bool) -> Self {
290        self.fail_closed = on;
291        self
292    }
293
294    /// Enable real HTTP GET for tool name `http_get` after allow-list pass.
295    pub fn enable_http_get(mut self, on: bool) -> Self {
296        self.enable_http_get = on;
297        self
298    }
299
300    fn is_denied(&self, name: &str) -> bool {
301        self.denied.contains(name) || !self.allowed.contains(name)
302    }
303}
304
305#[cfg(feature = "std")]
306impl Executor for ToolGateExecutor {
307    fn execute(&mut self, actions: &[Action]) -> Result<Vec<serde_json::Value>> {
308        let mut results = Vec::new();
309        for act in actions {
310            if !act.constraints_checked {
311                return Err(OmegaError::ExecutionBlocked(format!(
312                    "{} (constraints not checked)",
313                    act.name
314                )));
315            }
316
317            if self.is_denied(&act.name) {
318                let reason = if self.denied.contains(&act.name) {
319                    "deny_list"
320                } else {
321                    "not_on_allow_list"
322                };
323                if let Some(log) = &self.audit {
324                    let _ = log.append(AuditEvent::ToolDenied {
325                        tool: act.name.clone(),
326                        reason: reason.into(),
327                    });
328                }
329                if self.echo {
330                    println!("[tool-gate] DENY  {} ({reason})", act.name);
331                }
332                if self.fail_closed {
333                    return Err(OmegaError::ExecutionBlocked(format!(
334                        "tool denied: {} ({reason})",
335                        act.name
336                    )));
337                }
338                results.push(serde_json::json!({
339                    "status": "denied",
340                    "action": act.name,
341                    "reason": reason,
342                }));
343                continue;
344            }
345
346            if let Some(log) = &self.audit {
347                let _ = log.append(AuditEvent::ToolAllowed {
348                    tool: act.name.clone(),
349                });
350            }
351            if self.echo {
352                println!("[tool-gate] ALLOW {}", act.name);
353            }
354
355            // Real side effect only for http_get when explicitly enabled.
356            if self.enable_http_get && act.name == "http_get" {
357                let url = act.params.get("url").and_then(|v| v.as_str()).unwrap_or("");
358                if url.is_empty() {
359                    return Err(OmegaError::ExecutionBlocked(
360                        "http_get requires params.url".into(),
361                    ));
362                }
363                if self.echo {
364                    println!("[tool-gate] GET   {url}");
365                }
366                results.push(safe_http_get(url)?);
367                continue;
368            }
369
370            results.push(serde_json::json!({
371                "status": "ok",
372                "action": act.name,
373                "params": act.params,
374                "effect": "simulated",
375            }));
376        }
377        Ok(results)
378    }
379}
380
381/// Async logging executor using tokio's async filesystem.
382#[cfg(all(feature = "std", feature = "async"))]
383#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
384pub struct AsyncLoggingExecutor {
385    allowed: HashSet<String>,
386    log_path: Option<PathBuf>,
387    echo_stdout: bool,
388}
389
390#[cfg(all(feature = "std", feature = "async"))]
391#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
392impl AsyncLoggingExecutor {
393    pub fn new(allowed: impl IntoIterator<Item = String>) -> Self {
394        Self {
395            allowed: allowed.into_iter().collect(),
396            log_path: None,
397            echo_stdout: true,
398        }
399    }
400
401    pub fn with_log_file(mut self, path: impl AsRef<Path>) -> Self {
402        self.log_path = Some(path.as_ref().to_path_buf());
403        self
404    }
405
406    pub fn echo_stdout(mut self, enabled: bool) -> Self {
407        self.echo_stdout = enabled;
408        self
409    }
410}
411
412#[cfg(all(feature = "std", feature = "async"))]
413#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "async"))))]
414impl AsyncExecutor for AsyncLoggingExecutor {
415    fn execute_async(
416        &mut self,
417        actions: &[Action],
418    ) -> impl Future<Output = Result<Vec<serde_json::Value>>> + Send {
419        let allowed = self.allowed.clone();
420        let log_path = self.log_path.clone();
421        let echo_stdout = self.echo_stdout;
422        let actions = actions.to_vec();
423        async move {
424            let mut results = Vec::new();
425            for act in actions {
426                if !act.constraints_checked {
427                    return Err(OmegaError::ExecutionBlocked(format!(
428                        "{} (constraints not checked)",
429                        act.name
430                    )));
431                }
432                if !allowed.contains(&act.name) {
433                    return Err(OmegaError::ExecutionBlocked(act.name.clone()));
434                }
435
436                let entry = serde_json::json!({
437                    "status": "logged",
438                    "action": act.name,
439                    "params": act.params,
440                    "ts": crate::now_utc_string()
441                });
442
443                if echo_stdout {
444                    println!("[AsyncLoggingExecutor] {}", entry);
445                }
446
447                if let Some(path) = &log_path {
448                    if let Ok(mut file) = tokio::fs::OpenOptions::new()
449                        .create(true)
450                        .append(true)
451                        .open(path)
452                        .await
453                    {
454                        let line = format!("{}\n", entry);
455                        let _ = file.write_all(line.as_bytes()).await;
456                    }
457                }
458
459                results.push(entry);
460            }
461            Ok(results)
462        }
463    }
464}
465
466#[cfg(test)]
467mod tests {
468    use super::*;
469    use crate::types::Action;
470    use hashbrown::HashMap;
471    use std::env::temp_dir;
472
473    fn action(name: &str, checked: bool) -> Action {
474        Action {
475            name: name.into(),
476            params: HashMap::new(),
477            constraints_checked: checked,
478        }
479    }
480
481    #[test]
482    fn allows_whitelisted_checked_action() {
483        let mut ex = SandboxedExecutor::new(vec!["observe".into()]);
484        let res = ex.execute(&[action("observe", true)]);
485        assert!(res.is_ok());
486        assert_eq!(res.unwrap().len(), 1);
487    }
488
489    #[test]
490    fn blocks_unchecked_action() {
491        let mut ex = SandboxedExecutor::new(vec!["observe".into()]);
492        let res = ex.execute(&[action("observe", false)]);
493        assert!(res.is_err());
494    }
495
496    #[test]
497    fn blocks_non_whitelisted_action() {
498        let mut ex = SandboxedExecutor::new(vec!["observe".into()]);
499        let res = ex.execute(&[action("delete_everything", true)]);
500        assert!(res.is_err());
501    }
502
503    #[test]
504    fn logging_executor_records_action() {
505        let mut ex = LoggingExecutor::new(vec!["observe".into()]).echo_stdout(false);
506        let res = ex.execute(&[action("observe", true)]).unwrap();
507        assert_eq!(res[0]["status"], "logged");
508        assert_eq!(res[0]["action"], "observe");
509    }
510
511    #[test]
512    fn tool_gate_denies_dangerous_tool() {
513        let path = temp_dir().join(format!("omega-gate-{}.json", crate::new_uuid()));
514        let audit = AuditLog::beside_state(&path);
515        let mut gate = ToolGateExecutor::new(["search_docs".into(), "http_get".into()])
516            .deny(["delete_database".into(), "shell_exec".into()])
517            .with_audit(audit)
518            .echo(false)
519            .fail_closed(true);
520        assert!(gate.execute(&[action("search_docs", true)]).is_ok());
521        assert!(gate.execute(&[action("delete_database", true)]).is_err());
522        let rows = AuditLog::beside_state(&path).read_all().unwrap();
523        assert!(rows.len() >= 2);
524        let _ = std::fs::remove_file(AuditLog::beside_state(&path).path);
525        let _ = std::fs::remove_file(&path);
526    }
527
528    #[test]
529    fn http_get_rejects_non_http_scheme() {
530        let mut gate = ToolGateExecutor::new(["http_get".into()])
531            .enable_http_get(true)
532            .echo(false);
533        let mut params = HashMap::new();
534        params.insert("url".into(), serde_json::json!("file:///etc/passwd"));
535        let act = Action {
536            name: "http_get".into(),
537            params,
538            constraints_checked: true,
539        };
540        assert!(gate.execute(&[act]).is_err());
541    }
542}