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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
//! Middleware wrapper for [`AgentTool`] that intercepts `execute()` while
//! delegating all metadata methods to the inner tool.
//!
//! # Example
//!
//! ```no_run
//! # #[cfg(feature = "builtin-tools")]
//! # {
//! use std::sync::Arc;
//! use swink_agent::{AgentTool, AgentToolResult, BashTool, ToolMiddleware};
//!
//! let tool = Arc::new(BashTool::new());
//! let logged = ToolMiddleware::new(tool, |inner, id, params, cancel, on_update, state, credential| {
//! Box::pin(async move {
//! println!("before");
//! let result = inner.execute(&id, params, cancel, on_update, state, credential).await;
//! println!("after");
//! result
//! })
//! });
//!
//! assert_eq!(logged.name(), "bash");
//! # }
//! ```
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
use serde_json::Value;
use tokio_util::sync::CancellationToken;
use crate::tool::{AgentTool, AgentToolResult, ToolFuture};
// ─── Type alias for the middleware closure ──────────────────────────────────
type MiddlewareFn = Arc<
dyn Fn(
Arc<dyn AgentTool>,
String,
Value,
CancellationToken,
Option<Box<dyn Fn(AgentToolResult) + Send + Sync>>,
std::sync::Arc<std::sync::RwLock<crate::SessionState>>,
Option<crate::credential::ResolvedCredential>,
) -> ToolFuture<'static>
+ Send
+ Sync,
>;
// ─── ToolMiddleware ─────────────────────────────────────────────────────────
/// Intercepts [`execute()`](AgentTool::execute) on a wrapped [`AgentTool`].
///
/// All descriptor methods (`name`, `label`, `description`,
/// `parameters_schema`, `metadata`, `requires_approval`, `auth_config`)
/// delegate to the inner tool.
pub struct ToolMiddleware {
inner: Arc<dyn AgentTool>,
middleware_fn: MiddlewareFn,
}
impl ToolMiddleware {
/// Create a new middleware wrapping `inner`.
///
/// The closure receives `(inner_tool, tool_call_id, params, cancel, on_update, state, credential)`
/// and can call through to the inner tool's `execute()` at any point.
pub fn new<F>(inner: Arc<dyn AgentTool>, f: F) -> Self
where
F: Fn(
Arc<dyn AgentTool>,
String,
Value,
CancellationToken,
Option<Box<dyn Fn(AgentToolResult) + Send + Sync>>,
std::sync::Arc<std::sync::RwLock<crate::SessionState>>,
Option<crate::credential::ResolvedCredential>,
) -> ToolFuture<'static>
+ Send
+ Sync
+ 'static,
{
Self {
inner,
middleware_fn: Arc::new(f),
}
}
/// Create a middleware that enforces a timeout on tool execution.
///
/// If the inner tool does not complete within `timeout`, an error result
/// is returned.
pub fn with_timeout(inner: Arc<dyn AgentTool>, timeout: Duration) -> Self {
Self::new(
inner,
move |tool, id, params, cancel, on_update, state, credential| {
Box::pin(async move {
tokio::select! {
result = tool.execute(&id, params, cancel.clone(), on_update, state, credential) => result,
() = tokio::time::sleep(timeout) => {
cancel.cancel();
AgentToolResult::error(format!(
"tool timed out after {}ms",
timeout.as_millis()
))
}
}
})
},
)
}
/// Create a middleware that calls a logging callback before and after
/// tool execution.
///
/// The callback receives `(tool_name, tool_call_id, is_start)` where
/// `is_start` is `true` before execution and `false` after.
pub fn with_logging<F>(inner: Arc<dyn AgentTool>, callback: F) -> Self
where
F: Fn(&str, &str, bool) + Send + Sync + 'static,
{
let callback = Arc::new(callback);
Self::new(
inner,
move |tool, id, params, cancel, on_update, state, credential| {
let cb = callback.clone();
let name = tool.name().to_owned();
Box::pin(async move {
cb(&name, &id, true);
let result = tool
.execute(&id, params, cancel, on_update, state, credential)
.await;
cb(&name, &id, false);
result
})
},
)
}
}
impl AgentTool for ToolMiddleware {
fn name(&self) -> &str {
self.inner.name()
}
fn label(&self) -> &str {
self.inner.label()
}
fn description(&self) -> &str {
self.inner.description()
}
fn parameters_schema(&self) -> &Value {
self.inner.parameters_schema()
}
fn metadata(&self) -> Option<crate::tool::ToolMetadata> {
self.inner.metadata()
}
fn execution_root(&self) -> Option<&Path> {
self.inner.execution_root()
}
fn requires_approval(&self) -> bool {
self.inner.requires_approval()
}
fn approval_context(&self, params: &Value) -> Option<Value> {
self.inner.approval_context(params)
}
fn auth_config(&self) -> Option<crate::credential::AuthConfig> {
self.inner.auth_config()
}
fn execute(
&self,
tool_call_id: &str,
params: Value,
cancellation_token: CancellationToken,
on_update: Option<Box<dyn Fn(AgentToolResult) + Send + Sync>>,
state: std::sync::Arc<std::sync::RwLock<crate::SessionState>>,
credential: Option<crate::credential::ResolvedCredential>,
) -> ToolFuture<'_> {
let inner = self.inner.clone();
let id = tool_call_id.to_owned();
let fut = (self.middleware_fn)(
inner,
id,
params,
cancellation_token,
on_update,
state,
credential,
);
Box::pin(fut)
}
}
impl std::fmt::Debug for ToolMiddleware {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ToolMiddleware")
.field("inner_name", &self.inner.name())
.finish_non_exhaustive()
}
}
// ─── Compile-time Send + Sync assertion ─────────────────────────────────────
const _: () = {
const fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<ToolMiddleware>();
};
#[cfg(test)]
#[path = "tool_middleware_tests.rs"]
mod tests;