Skip to main content

causa_runtime/
filter.rs

1//! Tool-use filter policies — the framework's concrete behavior for the
2//! tool-use batch between model output and tool dispatch.
3//!
4//! ## One trait, one seam
5//!
6//! This crate defines `ToolUseHook` (the seam `TurnRunner::with_hook`
7//! consumes, alongside the driver itself) and the concrete
8//! policies below. Filters implement that trait directly — there is no
9//! second extension trait and no alias layer. The default is
10//! `PassthroughHook` (no opinion); dedup / kill-switch / approval are
11//! framework or host concerns, never kernel facts.
12
13use 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/// Default deduplication policy — same-batch `(tool_name, arguments)` dedup.
21/// Subsequent occurrences of an identical pair are pushed to `rejected` with
22/// the original `call_id` and a `{"error": "duplicate tool call"}` payload.
23///
24/// This is a *business policy*, not a fact-layer invariant. The kernel
25/// pair-validation rules (ToolCallId pairing, `append_tool_results`
26/// `call_seq` checks) are independent and remain.
27#[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/// A filter that lets every call through unchanged.
58///
59/// Useful for tests, opt-out scenarios, and as a baseline for chains
60/// that only add policy filters.
61#[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/// A filter that rejects every call with a fixed reason.
72///
73/// Useful for tests, kill-switch scenarios, and as a baseline for
74/// "deny by default" chains. The reason is recorded in the rejected
75/// outcome's output payload.
76#[derive(Debug, Clone)]
77pub struct DenyAllFilter {
78    /// The fixed reason recorded in every rejected outcome's output
79    /// payload.
80    pub reason: String,
81}
82
83impl DenyAllFilter {
84    /// A filter that rejects every call with `reason`.
85    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/// Composes multiple filters sequentially.
121///
122/// `FilterChain::apply` walks `filters` in order, feeding each
123/// filter's `to_execute` into the next. `rejected` accumulates across
124/// the chain. `FilterChain::default()` is empty (no opinion — callers opt
125/// in via `DedupFilter` or `dedup_only()`).
126///
127/// A chain plugs into the driver through the same trait it is made of:
128/// `TurnRunner::with_hook(gateway, executor, Arc::new(chain))`.
129#[derive(Clone)]
130pub struct FilterChain {
131    filters: Vec<Arc<dyn ToolUseHook>>,
132}
133
134impl FilterChain {
135    /// Build a chain from an explicit filter list. Order matters: the
136    /// first filter sees the raw batch, the next sees the previous
137    /// filter's `to_execute`, etc.
138    pub fn new(filters: Vec<Arc<dyn ToolUseHook>>) -> Self {
139        Self { filters }
140    }
141
142    /// True if the chain has no filters — in that case `apply` is a
143    /// pure passthrough.
144    pub fn is_empty(&self) -> bool {
145        self.filters.is_empty()
146    }
147
148    /// Returns the number of filters in the chain.
149    pub fn len(&self) -> usize {
150        self.filters.len()
151    }
152
153    /// Convenience: a chain containing only `DedupFilter`.
154    pub fn dedup_only() -> Self {
155        Self {
156            filters: vec![Arc::new(DedupFilter)],
157        }
158    }
159
160    /// Convenience: an empty chain (pure passthrough). Equivalent to
161    /// `FilterChain::new(vec![])` but documents intent.
162    pub fn passthrough() -> Self {
163        Self {
164            filters: Vec::new(),
165        }
166    }
167}
168
169impl Default for FilterChain {
170    /// Empty by default — the framework carries no opinion.
171    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// --- tests ----------------------------------------------------------------
204//
205// Unit tests for the filter policies. They live in the same file to keep
206// the test surface local; they do not require a full driver stack.
207
208#[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    /// Construct a `HookCtx` bound to a freshly built `CallControl`
228    /// via `Box::leak`. The control lives for the test's process —
229    /// acceptable for unit tests, never used in production.
230    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})), // dup
248            call("c", "echo", json!({"x": 2})),
249            call("d", "other", json!({"x": 1})), // different tool name
250        ];
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        // Rejected carries the original call_id (b), not a fresh one.
261        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        // Each rejected outcome must reuse the source payload's call_id;
268        // otherwise append_tool_results would reject it with
269        // UnpairedToolResult.
270        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})), // would be deduped, but AllowAll lets it through
293        ];
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        // Reason is recorded in the output payload's content field.
311        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        // DedupFilter passes both calls (different arguments).
340        // DenyAllFilter then rejects them all.
341        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        // Both ids must be preserved (call_id pairing invariant).
360        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        // DenyAllFilter runs first; everything is rejected before DedupFilter
367        // even sees it. This is the canonical pattern for "deny by default,
368        // permit allow-listed later".
369        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        // Both rejected at the first filter; DedupFilter never sees them.
382        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}