1use async_trait::async_trait;
14use std::collections::HashSet;
15use std::sync::Arc;
16
17use crate::hook::{HookCtx, HookOutcome, ToolUseHook};
18use causa_kernel::{ToolCallPayload, ToolOutput, ToolResultPayload, ToolResultStatus};
19
20#[derive(Debug, Default, Clone)]
28pub struct DedupFilter;
29
30#[async_trait]
31impl ToolUseHook for DedupFilter {
32 async fn apply(&self, calls: Vec<ToolCallPayload>, _ctx: &HookCtx<'_>) -> HookOutcome {
33 let mut seen: HashSet<(String, serde_json::Value)> = HashSet::new();
34 let mut to_execute = Vec::new();
35 let mut rejected = Vec::new();
36 for payload in calls {
37 let key = (payload.tool_name.clone(), payload.arguments.clone());
38 if seen.insert(key) {
39 to_execute.push(payload);
40 } else {
41 rejected.push(ToolResultPayload {
42 call_id: payload.call_id.clone(),
43 status: ToolResultStatus::Rejected,
44 output: ToolOutput::new(serde_json::json!({"error": "duplicate tool call"})),
45 media: Vec::new(),
46 });
47 }
48 }
49 HookOutcome {
50 to_execute,
51 rejected,
52 unknown_decisions: Vec::new(),
53 }
54 }
55}
56
57#[derive(Debug, Default, Clone)]
62pub struct AllowAllFilter;
63
64#[async_trait]
65impl ToolUseHook for AllowAllFilter {
66 async fn apply(&self, calls: Vec<ToolCallPayload>, _ctx: &HookCtx<'_>) -> HookOutcome {
67 HookOutcome::passthrough(calls)
68 }
69}
70
71#[derive(Debug, Clone)]
77pub struct DenyAllFilter {
78 pub reason: String,
81}
82
83impl DenyAllFilter {
84 pub fn new(reason: impl Into<String>) -> Self {
86 Self {
87 reason: reason.into(),
88 }
89 }
90}
91
92impl Default for DenyAllFilter {
93 fn default() -> Self {
94 Self {
95 reason: "denied by filter".into(),
96 }
97 }
98}
99
100#[async_trait]
101impl ToolUseHook for DenyAllFilter {
102 async fn apply(&self, calls: Vec<ToolCallPayload>, _ctx: &HookCtx<'_>) -> HookOutcome {
103 let rejected = calls
104 .into_iter()
105 .map(|payload| ToolResultPayload {
106 call_id: payload.call_id.clone(),
107 status: ToolResultStatus::Rejected,
108 output: ToolOutput::new(serde_json::json!({"error": self.reason.clone()})),
109 media: Vec::new(),
110 })
111 .collect();
112 HookOutcome {
113 to_execute: Vec::new(),
114 rejected,
115 unknown_decisions: Vec::new(),
116 }
117 }
118}
119
120#[derive(Clone)]
130pub struct FilterChain {
131 filters: Vec<Arc<dyn ToolUseHook>>,
132}
133
134impl FilterChain {
135 pub fn new(filters: Vec<Arc<dyn ToolUseHook>>) -> Self {
139 Self { filters }
140 }
141
142 pub fn is_empty(&self) -> bool {
145 self.filters.is_empty()
146 }
147
148 pub fn len(&self) -> usize {
150 self.filters.len()
151 }
152
153 pub fn dedup_only() -> Self {
155 Self {
156 filters: vec![Arc::new(DedupFilter)],
157 }
158 }
159
160 pub fn passthrough() -> Self {
163 Self {
164 filters: Vec::new(),
165 }
166 }
167}
168
169impl Default for FilterChain {
170 fn default() -> Self {
172 Self {
173 filters: Vec::new(),
174 }
175 }
176}
177
178impl std::fmt::Debug for FilterChain {
179 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
180 f.debug_struct("FilterChain")
181 .field("len", &self.filters.len())
182 .finish()
183 }
184}
185
186#[async_trait]
187impl ToolUseHook for FilterChain {
188 async fn apply(&self, mut calls: Vec<ToolCallPayload>, ctx: &HookCtx<'_>) -> HookOutcome {
189 let mut all_rejected = Vec::new();
190 for filter in &self.filters {
191 let outcome = filter.apply(std::mem::take(&mut calls), ctx).await;
192 all_rejected.extend(outcome.rejected);
193 calls = outcome.to_execute;
194 }
195 HookOutcome {
196 to_execute: calls,
197 rejected: all_rejected,
198 unknown_decisions: Vec::new(),
199 }
200 }
201}
202
203#[cfg(test)]
209mod tests {
210 use super::*;
211 use causa_kernel::{RoundId, ToolCallId, TurnId};
212 use serde_json::json;
213 use tokio_util::sync::CancellationToken;
214
215 fn call(call_id: &str, tool_name: &str, args: serde_json::Value) -> ToolCallPayload {
216 ToolCallPayload {
217 call_id: ToolCallId(call_id.to_string()),
218 tool_name: tool_name.to_string(),
219 arguments: args,
220 }
221 }
222
223 fn dummy_turn_id() -> TurnId {
224 TurnId::new("test-turn")
225 }
226
227 fn make_ctx<'a>(turn_id: &'a TurnId, round_id: RoundId) -> HookCtx<'a> {
231 let cancellation = CancellationToken::new();
232 let control = Box::leak(Box::new(causa_kernel::CallControl::new(cancellation, None)));
233 HookCtx {
234 turn_id,
235 conversation_id: None,
236 round_id,
237 control,
238 }
239 }
240
241 #[tokio::test]
242 async fn dedup_filter_collapses_same_tool_name_and_arguments() {
243 let turn_id = dummy_turn_id();
244 let ctx = make_ctx(&turn_id, RoundId(0));
245 let calls = vec![
246 call("a", "echo", json!({"x": 1})),
247 call("b", "echo", json!({"x": 1})), call("c", "echo", json!({"x": 2})),
249 call("d", "other", json!({"x": 1})), ];
251 let outcome = DedupFilter.apply(calls, &ctx).await;
252 assert_eq!(outcome.to_execute.len(), 3);
253 assert_eq!(outcome.rejected.len(), 1);
254 let ids: Vec<&str> = outcome
255 .to_execute
256 .iter()
257 .map(|p| p.call_id.0.as_str())
258 .collect();
259 assert_eq!(ids, vec!["a", "c", "d"]);
260 assert_eq!(outcome.rejected[0].call_id.0, "b");
262 assert_eq!(outcome.rejected[0].status, ToolResultStatus::Rejected);
263 }
264
265 #[tokio::test]
266 async fn dedup_filter_preserves_call_id_pairing_invariant() {
267 let turn_id = dummy_turn_id();
271 let ctx = make_ctx(&turn_id, RoundId(0));
272 let calls = vec![
273 call("id-1", "echo", json!({"k": "v"})),
274 call("id-2", "echo", json!({"k": "v"})),
275 call("id-3", "echo", json!({"k": "v"})),
276 ];
277 let outcome = DedupFilter.apply(calls, &ctx).await;
278 let rejected_ids: Vec<String> = outcome
279 .rejected
280 .iter()
281 .map(|r| r.call_id.0.clone())
282 .collect();
283 assert_eq!(rejected_ids, vec!["id-2", "id-3"]);
284 }
285
286 #[tokio::test]
287 async fn allow_all_filter_passes_through() {
288 let turn_id = dummy_turn_id();
289 let ctx = make_ctx(&turn_id, RoundId(0));
290 let calls = vec![
291 call("a", "echo", json!({"x": 1})),
292 call("b", "echo", json!({"x": 1})), ];
294 let outcome = AllowAllFilter.apply(calls, &ctx).await;
295 assert_eq!(outcome.to_execute.len(), 2);
296 assert!(outcome.rejected.is_empty());
297 }
298
299 #[tokio::test]
300 async fn deny_all_filter_rejects_every_call() {
301 let turn_id = dummy_turn_id();
302 let ctx = make_ctx(&turn_id, RoundId(0));
303 let calls = vec![call("a", "echo", json!({})), call("b", "other", json!({}))];
304 let outcome = DenyAllFilter::new("test deny").apply(calls, &ctx).await;
305 assert!(outcome.to_execute.is_empty());
306 assert_eq!(outcome.rejected.len(), 2);
307 assert_eq!(outcome.rejected[0].call_id.0, "a");
308 assert_eq!(outcome.rejected[1].call_id.0, "b");
309 assert_eq!(outcome.rejected[0].status, ToolResultStatus::Rejected);
310 let json = &outcome.rejected[0].output.content;
312 assert_eq!(json["error"], "test deny");
313 }
314
315 #[tokio::test]
316 async fn filter_chain_default_is_empty() {
317 let chain = FilterChain::default();
318 assert_eq!(chain.len(), 0);
319 assert!(chain.is_empty());
320 }
321
322 #[tokio::test]
323 async fn filter_chain_passthrough_lets_calls_through() {
324 let turn_id = dummy_turn_id();
325 let ctx = make_ctx(&turn_id, RoundId(0));
326 let chain = FilterChain::passthrough();
327 assert!(chain.is_empty());
328 let calls = vec![
329 call("a", "echo", json!({"x": 1})),
330 call("b", "echo", json!({"x": 1})),
331 ];
332 let outcome = chain.apply(calls, &ctx).await;
333 assert_eq!(outcome.to_execute.len(), 2);
334 assert!(outcome.rejected.is_empty());
335 }
336
337 #[tokio::test]
338 async fn filter_chain_dedup_then_deny_rejects_everything() {
339 let turn_id = dummy_turn_id();
342 let ctx = make_ctx(&turn_id, RoundId(0));
343 let chain = FilterChain::new(vec![
344 Arc::new(DedupFilter),
345 Arc::new(DenyAllFilter::new("kill switch")),
346 ]);
347 let calls = vec![
348 call("a", "echo", json!({"x": 1})),
349 call("b", "echo", json!({"x": 2})),
350 ];
351 let outcome = chain.apply(calls, &ctx).await;
352 assert!(outcome.to_execute.is_empty());
353 assert_eq!(outcome.rejected.len(), 2);
354 let ids: Vec<String> = outcome
355 .rejected
356 .iter()
357 .map(|r| r.call_id.0.clone())
358 .collect();
359 assert!(ids.contains(&"a".to_string()));
361 assert!(ids.contains(&"b".to_string()));
362 }
363
364 #[tokio::test]
365 async fn filter_chain_deny_then_dedup_is_pre_filter_pattern() {
366 let turn_id = dummy_turn_id();
370 let ctx = make_ctx(&turn_id, RoundId(0));
371 let chain = FilterChain::new(vec![
372 Arc::new(DenyAllFilter::new("block all")),
373 Arc::new(DedupFilter),
374 ]);
375 let calls = vec![
376 call("a", "echo", json!({"x": 1})),
377 call("b", "echo", json!({"x": 1})),
378 ];
379 let outcome = chain.apply(calls, &ctx).await;
380 assert!(outcome.to_execute.is_empty());
381 assert_eq!(outcome.rejected.len(), 2);
383 }
384
385 #[tokio::test]
386 async fn filter_chain_is_clone() {
387 let chain = FilterChain::new(vec![Arc::new(DedupFilter)]);
388 let cloned = chain.clone();
389 assert_eq!(cloned.len(), 1);
390 }
391}