1use std::future::Future;
34use std::pin::Pin;
35use std::sync::Arc;
36use std::time::Duration;
37
38use async_trait::async_trait;
39use tokio_util::sync::CancellationToken;
40
41pub type ToolOutcome = Result<ToolAnswer, String>;
43
44#[derive(Debug, Clone, PartialEq)]
57pub struct ToolAnswer {
58 pub text: String,
60 pub new_messages: Option<Vec<serde_json::Value>>,
62 pub reported_failure: bool,
64 pub structured: Option<serde_json::Value>,
66 pub file_changes: Vec<crate::interface::tool::FileChange>,
68}
69
70impl ToolAnswer {
71 pub fn text(s: impl Into<String>) -> Self {
73 Self {
74 text: s.into(),
75 new_messages: None,
76 reported_failure: false,
77 structured: None,
78 file_changes: Vec::new(),
79 }
80 }
81
82 pub fn failure(s: impl Into<String>) -> Self {
84 Self {
85 text: s.into(),
86 new_messages: None,
87 reported_failure: true,
88 structured: None,
89 file_changes: Vec::new(),
90 }
91 }
92}
93
94#[derive(Debug, Clone, Default)]
97pub struct ToolCall {
98 pub name: String,
99 pub input: serde_json::Value,
100 pub via: String,
104 pub plugin: Option<String>,
105 pub project_root: Option<std::path::PathBuf>,
107}
108
109impl ToolCall {
110 pub fn new(name: impl Into<String>, input: serde_json::Value) -> Self {
112 Self {
113 name: name.into(),
114 input,
115 via: "model".into(),
116 ..Default::default()
117 }
118 }
119}
120
121pub struct ToolExec {
123 cancel: CancellationToken,
127 deadline: Option<tokio::time::Instant>,
130}
131
132impl ToolExec {
133 pub fn new(cancel: CancellationToken) -> Self {
134 Self {
135 cancel,
136 deadline: None,
137 }
138 }
139
140 pub fn cancel(&self) -> &CancellationToken {
141 &self.cancel
142 }
143
144 pub fn with_timeout(&mut self, after: Duration) {
151 let at = tokio::time::Instant::now() + after;
152 self.deadline = Some(self.deadline.map_or(at, |earlier| earlier.min(at)));
153 self.cancel = self.cancel.child_token();
154 }
155
156 async fn run<F: Future<Output = ToolOutcome>>(&self, call: F) -> ToolOutcome {
159 let Some(deadline) = self.deadline else {
160 return call.await;
161 };
162 tokio::pin!(call);
163 tokio::select! {
164 outcome = &mut call => outcome,
165 _ = tokio::time::sleep_until(deadline) => {
166 self.cancel.cancel();
167 call.await
168 }
169 }
170 }
171}
172
173type Terminal<'a> = dyn Fn(CancellationToken) -> Pin<Box<dyn Future<Output = ToolOutcome> + Send + 'a>>
174 + Send
175 + Sync
176 + 'a;
177
178pub struct NextDispatch<'a> {
180 remaining: &'a [Arc<dyn ToolMiddleware>],
181 terminal: &'a Terminal<'a>,
182}
183
184impl<'a> NextDispatch<'a> {
185 pub async fn run(&self, call: &ToolCall, exec: &mut ToolExec) -> ToolOutcome {
190 match self.remaining.split_first() {
191 Some((next, rest)) => {
192 let inner = NextDispatch {
193 remaining: rest,
194 terminal: self.terminal,
195 };
196 next.around(call, exec, inner).await
197 }
198 None => exec.run((self.terminal)(exec.cancel.clone())).await,
199 }
200 }
201}
202
203#[async_trait]
205pub trait ToolMiddleware: Send + Sync {
206 async fn around(
207 &self,
208 call: &ToolCall,
209 exec: &mut ToolExec,
210 next: NextDispatch<'_>,
211 ) -> ToolOutcome;
212}
213
214pub async fn dispatch_through<'a, F, Fut>(
220 chain: &'a [Arc<dyn ToolMiddleware>],
221 call: ToolCall,
222 cancel: CancellationToken,
223 dispatch: F,
224) -> ToolOutcome
225where
226 F: Fn(CancellationToken) -> Fut + Send + Sync + 'a,
227 Fut: Future<Output = ToolOutcome> + Send + 'a,
228{
229 let terminal = move |cancel: CancellationToken| {
230 Box::pin(dispatch(cancel)) as Pin<Box<dyn Future<Output = ToolOutcome> + Send + 'a>>
231 };
232 let next = NextDispatch {
233 remaining: chain,
234 terminal: &terminal,
235 };
236 let mut exec = ToolExec::new(cancel);
237 next.run(&call, &mut exec).await
238}
239
240#[cfg(test)]
241mod tests {
242 use super::*;
243 use std::sync::atomic::{AtomicUsize, Ordering};
244
245 fn call() -> ToolCall {
246 ToolCall::new("Probe", serde_json::json!({}))
247 }
248
249 async fn run(
250 chain: Vec<Arc<dyn ToolMiddleware>>,
251 dispatch: impl Fn(CancellationToken) -> ToolOutcome + Send + Sync,
252 ) -> ToolOutcome {
253 dispatch_through(&chain, call(), CancellationToken::new(), |c| {
254 let out = dispatch(c);
255 async move { out }
256 })
257 .await
258 }
259
260 #[tokio::test]
261 async fn an_empty_chain_is_the_call_itself() {
262 let out = run(vec![], |_| Ok(ToolAnswer::text("ran"))).await;
263 assert_eq!(out, Ok(ToolAnswer::text("ran")));
264 }
265
266 #[tokio::test]
269 async fn a_wrapper_can_impose_a_deadline_the_call_feels() {
270 struct Deadline(Duration);
271 #[async_trait]
272 impl ToolMiddleware for Deadline {
273 async fn around(
274 &self,
275 call: &ToolCall,
276 exec: &mut ToolExec,
277 next: NextDispatch<'_>,
278 ) -> ToolOutcome {
279 exec.with_timeout(self.0);
280 next.run(call, exec).await
281 }
282 }
283
284 let chain: Vec<Arc<dyn ToolMiddleware>> =
285 vec![Arc::new(Deadline(Duration::from_millis(20)))];
286 let outcome = dispatch_through(
287 &chain,
288 call(),
289 CancellationToken::new(),
290 |cancel| async move {
291 cancel.cancelled().await;
293 Err("cancelled".to_string())
294 },
295 )
296 .await;
297 assert_eq!(outcome, Err("cancelled".to_string()));
298 }
299
300 #[tokio::test(flavor = "current_thread")]
301 async fn a_deadline_timer_ends_with_the_call() {
302 struct Deadline;
303 #[async_trait]
304 impl ToolMiddleware for Deadline {
305 async fn around(
306 &self,
307 call: &ToolCall,
308 exec: &mut ToolExec,
309 next: NextDispatch<'_>,
310 ) -> ToolOutcome {
311 exec.with_timeout(Duration::from_secs(3600));
312 next.run(call, exec).await
313 }
314 }
315
316 let metrics = tokio::runtime::Handle::current().metrics();
317 let before = metrics.num_alive_tasks();
318 let turn = CancellationToken::new();
319 let outcome = dispatch_through(
320 &[Arc::new(Deadline) as Arc<dyn ToolMiddleware>],
321 call(),
322 turn.clone(),
323 |_| async { Ok(ToolAnswer::text("quick")) },
324 )
325 .await;
326 assert_eq!(outcome, Ok(ToolAnswer::text("quick")));
327 for _ in 0..10 {
328 tokio::task::yield_now().await;
329 }
330 assert_eq!(metrics.num_alive_tasks(), before);
331 assert!(!turn.is_cancelled());
332 }
333
334 #[tokio::test]
337 async fn a_wrapper_cannot_outlive_the_turns_cancellation() {
338 struct Generous;
339 #[async_trait]
340 impl ToolMiddleware for Generous {
341 async fn around(
342 &self,
343 call: &ToolCall,
344 exec: &mut ToolExec,
345 next: NextDispatch<'_>,
346 ) -> ToolOutcome {
347 exec.with_timeout(Duration::from_secs(3600));
348 next.run(call, exec).await
349 }
350 }
351
352 let turn = CancellationToken::new();
353 let chain: Vec<Arc<dyn ToolMiddleware>> = vec![Arc::new(Generous)];
354 let fired = turn.clone();
355 tokio::spawn(async move {
356 tokio::time::sleep(Duration::from_millis(20)).await;
357 fired.cancel();
358 });
359 let outcome = dispatch_through(&chain, call(), turn, |cancel| async move {
360 cancel.cancelled().await;
361 Err("cancelled".to_string())
362 })
363 .await;
364 assert_eq!(outcome, Err("cancelled".to_string()));
365 }
366
367 #[tokio::test]
368 async fn a_wrapper_can_answer_without_calling_through() {
369 struct Cached;
370 #[async_trait]
371 impl ToolMiddleware for Cached {
372 async fn around(
373 &self,
374 _call: &ToolCall,
375 _exec: &mut ToolExec,
376 _next: NextDispatch<'_>,
377 ) -> ToolOutcome {
378 Ok(ToolAnswer::text("from cache"))
379 }
380 }
381
382 let calls = Arc::new(AtomicUsize::new(0));
383 let seen = calls.clone();
384 let out = run(vec![Arc::new(Cached)], move |_| {
385 seen.fetch_add(1, Ordering::SeqCst);
386 Ok(ToolAnswer::text("ran"))
387 })
388 .await;
389 assert_eq!(out, Ok(ToolAnswer::text("from cache")));
390 assert_eq!(
391 calls.load(Ordering::SeqCst),
392 0,
393 "a short circuit must not dispatch"
394 );
395 }
396
397 #[tokio::test]
398 async fn a_wrapper_can_call_through_more_than_once() {
399 struct RetryTwice;
400 #[async_trait]
401 impl ToolMiddleware for RetryTwice {
402 async fn around(
403 &self,
404 call: &ToolCall,
405 exec: &mut ToolExec,
406 next: NextDispatch<'_>,
407 ) -> ToolOutcome {
408 match next.run(call, exec).await {
409 Ok(v) => Ok(v),
410 Err(_) => next.run(call, exec).await,
411 }
412 }
413 }
414
415 let attempts = Arc::new(AtomicUsize::new(0));
416 let seen = attempts.clone();
417 let out = run(vec![Arc::new(RetryTwice)], move |_| {
418 if seen.fetch_add(1, Ordering::SeqCst) == 0 {
419 Err("flaked".into())
420 } else {
421 Ok(ToolAnswer::text("second time"))
422 }
423 })
424 .await;
425 assert_eq!(out, Ok(ToolAnswer::text("second time")));
426 assert_eq!(attempts.load(Ordering::SeqCst), 2);
427 }
428
429 #[tokio::test]
432 async fn the_first_registered_wrapper_is_the_outermost() {
433 struct Records(&'static str, Arc<std::sync::Mutex<Vec<String>>>);
434 #[async_trait]
435 impl ToolMiddleware for Records {
436 async fn around(
437 &self,
438 call: &ToolCall,
439 exec: &mut ToolExec,
440 next: NextDispatch<'_>,
441 ) -> ToolOutcome {
442 self.1.lock().unwrap().push(format!("enter {}", self.0));
443 let out = next.run(call, exec).await;
444 self.1.lock().unwrap().push(format!("exit {}", self.0));
445 out
446 }
447 }
448
449 let log = Arc::new(std::sync::Mutex::new(Vec::new()));
450 let chain: Vec<Arc<dyn ToolMiddleware>> = vec![
451 Arc::new(Records("outer", log.clone())),
452 Arc::new(Records("inner", log.clone())),
453 ];
454 let _ = run(chain, |_| Ok(ToolAnswer::text("ran"))).await;
455 assert_eq!(
456 log.lock().unwrap().as_slice(),
457 ["enter outer", "enter inner", "exit inner", "exit outer"]
458 );
459 }
460}