use std::fmt;
use std::sync::Arc;
use async_trait::async_trait;
use serde_json::Value;
#[derive(Debug, Clone)]
pub struct ToolGateCall<'a> {
pub tool: &'a str,
pub input: &'a Value,
pub caller_channel: &'a str,
pub principal: &'a str,
pub chat_id: i64,
pub approved: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub enum ToolGateDecision {
Allow,
Approve { rule: Option<String> },
Ask { reason: Option<String> },
Deny { reason: String },
}
#[derive(Debug, Clone, PartialEq)]
pub struct ToolGateOutcome {
pub decision: ToolGateDecision,
pub updated_input: Option<Value>,
}
impl ToolGateOutcome {
pub fn allow() -> Self {
Self {
decision: ToolGateDecision::Allow,
updated_input: None,
}
}
pub fn with(decision: ToolGateDecision) -> Self {
Self {
decision,
updated_input: None,
}
}
}
#[derive(Debug, Clone)]
pub struct ToolGateResult<'a> {
pub content: &'a str,
pub is_error: bool,
pub error_type: Option<&'a str>,
}
#[async_trait]
pub trait ToolGate: Send + Sync {
async fn before(&self, call: &ToolGateCall<'_>) -> ToolGateOutcome;
async fn after(
&self,
_call: &ToolGateCall<'_>,
_result: &ToolGateResult<'_>,
) -> Option<String> {
None
}
}
#[derive(Clone, Default)]
pub struct ToolGateHandle(pub Option<Arc<dyn ToolGate>>);
impl ToolGateHandle {
pub fn new(gate: Arc<dyn ToolGate>) -> Self {
Self(Some(gate))
}
pub fn get(&self) -> Option<&Arc<dyn ToolGate>> {
self.0.as_ref()
}
}
impl fmt::Debug for ToolGateHandle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(if self.0.is_some() {
"ToolGateHandle(Some)"
} else {
"ToolGateHandle(None)"
})
}
}
pub fn public_input(input: &Value) -> Value {
match input {
Value::Object(map) => Value::Object(
map.iter()
.filter(|(k, _)| !k.starts_with("__microclaw"))
.map(|(k, v)| (k.clone(), v.clone()))
.collect(),
),
other => other.clone(),
}
}
pub fn merge_internal_keys(original: &Value, updated: Value) -> Value {
match (original, updated) {
(Value::Object(orig), Value::Object(mut new)) => {
for (k, v) in orig {
if k.starts_with("__microclaw") {
new.insert(k.clone(), v.clone());
}
}
Value::Object(new)
}
(_, updated) => updated,
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn strips_and_restores_internal_keys() {
let input = json!({"command": "ls", "__microclaw_auth": {"x": 1}});
assert_eq!(public_input(&input), json!({"command": "ls"}));
let merged = merge_internal_keys(&input, json!({"command": "ls -la"}));
assert_eq!(merged["command"], "ls -la");
assert_eq!(merged["__microclaw_auth"]["x"], 1);
}
}