use async_trait::async_trait;
use std::collections::HashSet;
use std::sync::Arc;
use crate::hook::{HookCtx, HookOutcome, ToolUseHook};
use causa_kernel::{ToolCallPayload, ToolOutput, ToolResultPayload, ToolResultStatus};
#[derive(Debug, Default, Clone)]
pub struct DedupFilter;
#[async_trait]
impl ToolUseHook for DedupFilter {
async fn apply(&self, calls: Vec<ToolCallPayload>, _ctx: &HookCtx<'_>) -> HookOutcome {
let mut seen: HashSet<(String, serde_json::Value)> = HashSet::new();
let mut to_execute = Vec::new();
let mut rejected = Vec::new();
for payload in calls {
let key = (payload.tool_name.clone(), payload.arguments.clone());
if seen.insert(key) {
to_execute.push(payload);
} else {
rejected.push(ToolResultPayload {
call_id: payload.call_id.clone(),
status: ToolResultStatus::Rejected,
output: ToolOutput::new(serde_json::json!({"error": "duplicate tool call"})),
media: Vec::new(),
});
}
}
HookOutcome {
to_execute,
rejected,
unknown_decisions: Vec::new(),
}
}
}
#[derive(Debug, Default, Clone)]
pub struct AllowAllFilter;
#[async_trait]
impl ToolUseHook for AllowAllFilter {
async fn apply(&self, calls: Vec<ToolCallPayload>, _ctx: &HookCtx<'_>) -> HookOutcome {
HookOutcome::passthrough(calls)
}
}
#[derive(Debug, Clone)]
pub struct DenyAllFilter {
pub reason: String,
}
impl DenyAllFilter {
pub fn new(reason: impl Into<String>) -> Self {
Self {
reason: reason.into(),
}
}
}
impl Default for DenyAllFilter {
fn default() -> Self {
Self {
reason: "denied by filter".into(),
}
}
}
#[async_trait]
impl ToolUseHook for DenyAllFilter {
async fn apply(&self, calls: Vec<ToolCallPayload>, _ctx: &HookCtx<'_>) -> HookOutcome {
let rejected = calls
.into_iter()
.map(|payload| ToolResultPayload {
call_id: payload.call_id.clone(),
status: ToolResultStatus::Rejected,
output: ToolOutput::new(serde_json::json!({"error": self.reason.clone()})),
media: Vec::new(),
})
.collect();
HookOutcome {
to_execute: Vec::new(),
rejected,
unknown_decisions: Vec::new(),
}
}
}
#[derive(Clone)]
pub struct FilterChain {
filters: Vec<Arc<dyn ToolUseHook>>,
}
impl FilterChain {
pub fn new(filters: Vec<Arc<dyn ToolUseHook>>) -> Self {
Self { filters }
}
pub fn is_empty(&self) -> bool {
self.filters.is_empty()
}
pub fn len(&self) -> usize {
self.filters.len()
}
pub fn dedup_only() -> Self {
Self {
filters: vec![Arc::new(DedupFilter)],
}
}
pub fn passthrough() -> Self {
Self {
filters: Vec::new(),
}
}
}
impl Default for FilterChain {
fn default() -> Self {
Self {
filters: Vec::new(),
}
}
}
impl std::fmt::Debug for FilterChain {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FilterChain")
.field("len", &self.filters.len())
.finish()
}
}
#[async_trait]
impl ToolUseHook for FilterChain {
async fn apply(&self, mut calls: Vec<ToolCallPayload>, ctx: &HookCtx<'_>) -> HookOutcome {
let mut all_rejected = Vec::new();
for filter in &self.filters {
let outcome = filter.apply(std::mem::take(&mut calls), ctx).await;
all_rejected.extend(outcome.rejected);
calls = outcome.to_execute;
}
HookOutcome {
to_execute: calls,
rejected: all_rejected,
unknown_decisions: Vec::new(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use causa_kernel::{RoundId, ToolCallId, TurnId};
use serde_json::json;
use tokio_util::sync::CancellationToken;
fn call(call_id: &str, tool_name: &str, args: serde_json::Value) -> ToolCallPayload {
ToolCallPayload {
call_id: ToolCallId(call_id.to_string()),
tool_name: tool_name.to_string(),
arguments: args,
}
}
fn dummy_turn_id() -> TurnId {
TurnId::new("test-turn")
}
fn make_ctx<'a>(turn_id: &'a TurnId, round_id: RoundId) -> HookCtx<'a> {
let cancellation = CancellationToken::new();
let control = Box::leak(Box::new(causa_kernel::CallControl::new(cancellation, None)));
HookCtx {
turn_id,
conversation_id: None,
round_id,
control,
}
}
#[tokio::test]
async fn dedup_filter_collapses_same_tool_name_and_arguments() {
let turn_id = dummy_turn_id();
let ctx = make_ctx(&turn_id, RoundId(0));
let calls = vec![
call("a", "echo", json!({"x": 1})),
call("b", "echo", json!({"x": 1})), call("c", "echo", json!({"x": 2})),
call("d", "other", json!({"x": 1})), ];
let outcome = DedupFilter.apply(calls, &ctx).await;
assert_eq!(outcome.to_execute.len(), 3);
assert_eq!(outcome.rejected.len(), 1);
let ids: Vec<&str> = outcome
.to_execute
.iter()
.map(|p| p.call_id.0.as_str())
.collect();
assert_eq!(ids, vec!["a", "c", "d"]);
assert_eq!(outcome.rejected[0].call_id.0, "b");
assert_eq!(outcome.rejected[0].status, ToolResultStatus::Rejected);
}
#[tokio::test]
async fn dedup_filter_preserves_call_id_pairing_invariant() {
let turn_id = dummy_turn_id();
let ctx = make_ctx(&turn_id, RoundId(0));
let calls = vec![
call("id-1", "echo", json!({"k": "v"})),
call("id-2", "echo", json!({"k": "v"})),
call("id-3", "echo", json!({"k": "v"})),
];
let outcome = DedupFilter.apply(calls, &ctx).await;
let rejected_ids: Vec<String> = outcome
.rejected
.iter()
.map(|r| r.call_id.0.clone())
.collect();
assert_eq!(rejected_ids, vec!["id-2", "id-3"]);
}
#[tokio::test]
async fn allow_all_filter_passes_through() {
let turn_id = dummy_turn_id();
let ctx = make_ctx(&turn_id, RoundId(0));
let calls = vec![
call("a", "echo", json!({"x": 1})),
call("b", "echo", json!({"x": 1})), ];
let outcome = AllowAllFilter.apply(calls, &ctx).await;
assert_eq!(outcome.to_execute.len(), 2);
assert!(outcome.rejected.is_empty());
}
#[tokio::test]
async fn deny_all_filter_rejects_every_call() {
let turn_id = dummy_turn_id();
let ctx = make_ctx(&turn_id, RoundId(0));
let calls = vec![call("a", "echo", json!({})), call("b", "other", json!({}))];
let outcome = DenyAllFilter::new("test deny").apply(calls, &ctx).await;
assert!(outcome.to_execute.is_empty());
assert_eq!(outcome.rejected.len(), 2);
assert_eq!(outcome.rejected[0].call_id.0, "a");
assert_eq!(outcome.rejected[1].call_id.0, "b");
assert_eq!(outcome.rejected[0].status, ToolResultStatus::Rejected);
let json = &outcome.rejected[0].output.content;
assert_eq!(json["error"], "test deny");
}
#[tokio::test]
async fn filter_chain_default_is_empty() {
let chain = FilterChain::default();
assert_eq!(chain.len(), 0);
assert!(chain.is_empty());
}
#[tokio::test]
async fn filter_chain_passthrough_lets_calls_through() {
let turn_id = dummy_turn_id();
let ctx = make_ctx(&turn_id, RoundId(0));
let chain = FilterChain::passthrough();
assert!(chain.is_empty());
let calls = vec![
call("a", "echo", json!({"x": 1})),
call("b", "echo", json!({"x": 1})),
];
let outcome = chain.apply(calls, &ctx).await;
assert_eq!(outcome.to_execute.len(), 2);
assert!(outcome.rejected.is_empty());
}
#[tokio::test]
async fn filter_chain_dedup_then_deny_rejects_everything() {
let turn_id = dummy_turn_id();
let ctx = make_ctx(&turn_id, RoundId(0));
let chain = FilterChain::new(vec![
Arc::new(DedupFilter),
Arc::new(DenyAllFilter::new("kill switch")),
]);
let calls = vec![
call("a", "echo", json!({"x": 1})),
call("b", "echo", json!({"x": 2})),
];
let outcome = chain.apply(calls, &ctx).await;
assert!(outcome.to_execute.is_empty());
assert_eq!(outcome.rejected.len(), 2);
let ids: Vec<String> = outcome
.rejected
.iter()
.map(|r| r.call_id.0.clone())
.collect();
assert!(ids.contains(&"a".to_string()));
assert!(ids.contains(&"b".to_string()));
}
#[tokio::test]
async fn filter_chain_deny_then_dedup_is_pre_filter_pattern() {
let turn_id = dummy_turn_id();
let ctx = make_ctx(&turn_id, RoundId(0));
let chain = FilterChain::new(vec![
Arc::new(DenyAllFilter::new("block all")),
Arc::new(DedupFilter),
]);
let calls = vec![
call("a", "echo", json!({"x": 1})),
call("b", "echo", json!({"x": 1})),
];
let outcome = chain.apply(calls, &ctx).await;
assert!(outcome.to_execute.is_empty());
assert_eq!(outcome.rejected.len(), 2);
}
#[tokio::test]
async fn filter_chain_is_clone() {
let chain = FilterChain::new(vec![Arc::new(DedupFilter)]);
let cloned = chain.clone();
assert_eq!(cloned.len(), 1);
}
}