1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
//! Pattern-based tool filtering at registration time.
//!
//! [`ToolFilter`] uses exact, glob, and regex patterns to restrict which tools
//! are available to the agent. Patterns are applied at registration time so that
//! filtered tools never appear in the LLM prompt.
//!
//! # Example
//!
//! ```
//! use swink_agent::{ToolFilter, ToolPattern};
//!
//! let filter = ToolFilter::new()
//! .with_allowed(vec![ToolPattern::parse("read_*")])
//! .with_rejected(vec![ToolPattern::parse("read_secret")]);
//!
//! assert!(filter.is_allowed("read_file"));
//! assert!(!filter.is_allowed("read_secret"));
//! assert!(!filter.is_allowed("bash"));
//! ```
use std::sync::Arc;
use regex::Regex;
use crate::tool::AgentTool;
// ─── ToolPattern ────────────────────────────────────────────────────────────
/// A pattern for matching tool names.
///
/// Auto-detected by [`parse()`](ToolPattern::parse):
/// - Strings starting with `^` or ending with `$` → [`Regex`](ToolPattern::Regex)
/// - Strings containing `*` or `?` → [`Glob`](ToolPattern::Glob)
/// - Everything else → [`Exact`](ToolPattern::Exact)
#[non_exhaustive]
#[derive(Debug, Clone)]
pub enum ToolPattern {
/// Match the tool name exactly.
Exact(String),
/// Match using glob syntax (`*` = any chars, `?` = single char).
Glob(String),
/// Match using a regular expression.
///
/// Note: this variant embeds [`regex::Regex`] directly, so constructing
/// or destructuring it couples downstream code to the same `regex` crate
/// version this crate depends on. Prefer [`ToolPattern::parse`], which
/// builds the variant from a plain string, when that coupling is
/// undesirable.
Regex(Regex),
}
impl ToolPattern {
/// Parse a pattern string, auto-detecting the pattern type.
#[must_use]
pub fn parse(pattern: &str) -> Self {
if pattern.starts_with('^') || pattern.ends_with('$') {
Regex::new(pattern).map_or_else(|_| Self::Exact(pattern.to_string()), Self::Regex)
} else if pattern.contains('*') || pattern.contains('?') {
Self::Glob(pattern.to_string())
} else {
Self::Exact(pattern.to_string())
}
}
/// Test whether this pattern matches the given tool name.
#[must_use]
pub fn matches(&self, name: &str) -> bool {
match self {
Self::Exact(pat) => name == pat,
Self::Glob(pat) => glob_matches(pat, name),
Self::Regex(re) => re.is_match(name),
}
}
}
/// Simple glob matching: `*` matches any sequence, `?` matches one char.
fn glob_matches(pattern: &str, text: &str) -> bool {
let pattern_chars: Vec<char> = pattern.chars().collect();
let text_chars: Vec<char> = text.chars().collect();
let mut pattern_idx = 0;
let mut text_idx = 0;
let mut star_idx = None;
let mut match_after_star = 0;
while text_idx < text_chars.len() {
if pattern_idx < pattern_chars.len()
&& (pattern_chars[pattern_idx] == '?'
|| pattern_chars[pattern_idx] == text_chars[text_idx])
{
pattern_idx += 1;
text_idx += 1;
continue;
}
if pattern_idx < pattern_chars.len() && pattern_chars[pattern_idx] == '*' {
star_idx = Some(pattern_idx);
pattern_idx += 1;
match_after_star = text_idx;
continue;
}
if let Some(star) = star_idx {
pattern_idx = star + 1;
match_after_star += 1;
text_idx = match_after_star;
continue;
}
return false;
}
while pattern_idx < pattern_chars.len() && pattern_chars[pattern_idx] == '*' {
pattern_idx += 1;
}
pattern_idx == pattern_chars.len()
}
// ─── ToolFilter ─────────────────────────────────────────────────────────────
/// Filters tools at registration time using pattern-based allow/reject lists.
///
/// When both `allowed` and `rejected` match a tool name, `rejected` takes
/// precedence — the tool is excluded.
#[derive(Debug, Clone, Default)]
pub struct ToolFilter {
/// Patterns that a tool name must match to be included. Empty = allow all.
allowed: Vec<ToolPattern>,
/// Patterns that exclude a tool name. Takes precedence over `allowed`.
rejected: Vec<ToolPattern>,
}
impl ToolFilter {
/// Create a new empty filter (allows all tools).
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// Set the allowed patterns.
#[must_use]
pub fn with_allowed(mut self, patterns: Vec<ToolPattern>) -> Self {
self.allowed = patterns;
self
}
/// Set the rejected patterns.
#[must_use]
pub fn with_rejected(mut self, patterns: Vec<ToolPattern>) -> Self {
self.rejected = patterns;
self
}
/// Test whether a tool name passes through this filter.
#[must_use]
pub fn is_allowed(&self, name: &str) -> bool {
// Rejected takes precedence.
if self.rejected.iter().any(|p| p.matches(name)) {
return false;
}
// If no allowed patterns, everything passes. Otherwise must match at least one.
if self.allowed.is_empty() {
return true;
}
self.allowed.iter().any(|p| p.matches(name))
}
/// Filter a list of tools, returning only those that pass the filter.
#[must_use]
pub fn filter_tools(&self, tools: Vec<Arc<dyn AgentTool>>) -> Vec<Arc<dyn AgentTool>> {
tools
.into_iter()
.filter(|t| self.is_allowed(t.name()))
.collect()
}
}
// ─── Compile-time Send + Sync assertions ────────────────────────────────────
const _: () = {
const fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<ToolFilter>();
assert_send_sync::<ToolPattern>();
};
#[cfg(test)]
#[path = "tool_filter_tests.rs"]
mod tests;