microclaw_engine/
tool_gate.rs1use std::fmt;
23use std::sync::Arc;
24
25use async_trait::async_trait;
26use serde_json::Value;
27
28#[derive(Debug, Clone)]
30pub struct ToolGateCall<'a> {
31 pub tool: &'a str,
32 pub input: &'a Value,
34 pub caller_channel: &'a str,
35 pub principal: &'a str,
37 pub chat_id: i64,
38 pub approved: bool,
40}
41
42#[derive(Debug, Clone, PartialEq)]
44pub enum ToolGateDecision {
45 Allow,
46 Approve { rule: Option<String> },
47 Ask { reason: Option<String> },
48 Deny { reason: String },
49}
50
51#[derive(Debug, Clone, PartialEq)]
53pub struct ToolGateOutcome {
54 pub decision: ToolGateDecision,
55 pub updated_input: Option<Value>,
56}
57
58impl ToolGateOutcome {
59 pub fn allow() -> Self {
60 Self {
61 decision: ToolGateDecision::Allow,
62 updated_input: None,
63 }
64 }
65
66 pub fn with(decision: ToolGateDecision) -> Self {
67 Self {
68 decision,
69 updated_input: None,
70 }
71 }
72}
73
74#[derive(Debug, Clone)]
76pub struct ToolGateResult<'a> {
77 pub content: &'a str,
78 pub is_error: bool,
79 pub error_type: Option<&'a str>,
80}
81
82#[async_trait]
83pub trait ToolGate: Send + Sync {
84 async fn before(&self, call: &ToolGateCall<'_>) -> ToolGateOutcome;
86
87 async fn after(
90 &self,
91 _call: &ToolGateCall<'_>,
92 _result: &ToolGateResult<'_>,
93 ) -> Option<String> {
94 None
95 }
96}
97
98#[derive(Clone, Default)]
100pub struct ToolGateHandle(pub Option<Arc<dyn ToolGate>>);
101
102impl ToolGateHandle {
103 pub fn new(gate: Arc<dyn ToolGate>) -> Self {
104 Self(Some(gate))
105 }
106
107 pub fn get(&self) -> Option<&Arc<dyn ToolGate>> {
108 self.0.as_ref()
109 }
110}
111
112impl fmt::Debug for ToolGateHandle {
113 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114 f.write_str(if self.0.is_some() {
115 "ToolGateHandle(Some)"
116 } else {
117 "ToolGateHandle(None)"
118 })
119 }
120}
121
122pub fn public_input(input: &Value) -> Value {
124 match input {
125 Value::Object(map) => Value::Object(
126 map.iter()
127 .filter(|(k, _)| !k.starts_with("__microclaw"))
128 .map(|(k, v)| (k.clone(), v.clone()))
129 .collect(),
130 ),
131 other => other.clone(),
132 }
133}
134
135pub fn merge_internal_keys(original: &Value, updated: Value) -> Value {
137 match (original, updated) {
138 (Value::Object(orig), Value::Object(mut new)) => {
139 for (k, v) in orig {
140 if k.starts_with("__microclaw") {
141 new.insert(k.clone(), v.clone());
142 }
143 }
144 Value::Object(new)
145 }
146 (_, updated) => updated,
147 }
148}
149
150#[cfg(test)]
151mod tests {
152 use super::*;
153 use serde_json::json;
154
155 #[test]
156 fn strips_and_restores_internal_keys() {
157 let input = json!({"command": "ls", "__microclaw_auth": {"x": 1}});
158 assert_eq!(public_input(&input), json!({"command": "ls"}));
159 let merged = merge_internal_keys(&input, json!({"command": "ls -la"}));
160 assert_eq!(merged["command"], "ls -la");
161 assert_eq!(merged["__microclaw_auth"]["x"], 1);
162 }
163}