Skip to main content

base/interface/
tool_middleware.rs

1//! `ToolMiddleware` — the ring around tool dispatch.
2//!
3//! Timeouts, retries, metrics, caching, idempotent de-duplication: none of
4//! these belong to a tool's implementation and none of them are permission
5//! decisions. They are the things you wrap a call in. With nowhere to put
6//! them, they get hardcoded into the loop — which is where the engine's
7//! existing timeout and retry logic lives today, and why adding a per-tool
8//! deadline currently means editing the turn.
9//!
10//! # What a wrapper may do, and the one thing it may not
11//!
12//! It may **narrow the signal**: hand the call a stricter cancellation than
13//! the turn's, which is how a timeout is expressed. It may **short-circuit**:
14//! answer without calling through at all, which is how a cache hit is
15//! expressed. It may **call through more than once**, which is how a retry is
16//! expressed.
17//!
18//! It may not rewrite the call's input. That is a different act with a
19//! different risk — rewriting arguments turns an approved call into a
20//! different call, after approval — and it belongs to a hook point of its own
21//! with its own trust rules. Here it is not a rule to remember, it is a thing
22//! the types do not let you say: the call arrives behind a shared reference
23//! and dispatch takes no arguments.
24//!
25//! # Order
26//!
27//! Wrappers nest in registration order: the first registered is outermost, so
28//! it sees the others' retries as one call. That is the ordering a metrics
29//! wrapper wants (register it first and it measures everything inside) and
30//! the one a cache wants (register it first and a hit costs nothing further
31//! in).
32
33use 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
41/// What dispatch returns.
42pub type ToolOutcome = Result<ToolAnswer, String>;
43
44/// A tool that ran, and what it produced.
45///
46/// `reported_failure` is not the same thing as the `Err` this rides beside.
47/// `Err` is the engine failing to run a tool at all: it cancels the rest of a
48/// concurrent batch and fires `PostToolUseFailure`. This is the tool running
49/// exactly as designed and saying the work did not go well — a shell command
50/// with a non-zero exit, an HTTP status a fetch will not follow, an MCP
51/// server answering `isError`, a plugin whose guest trapped. The model has to
52/// be able to tell those from an answer, which is what `is_error` on the wire
53/// is for, and carrying the flag here is the only way it gets there: a
54/// wrapper sits between the tool and the caller, so a shape with no room for
55/// it drops it.
56#[derive(Debug, Clone, PartialEq)]
57pub struct ToolAnswer {
58    /// The text the model sees.
59    pub text: String,
60    /// Messages the tool asked to have injected.
61    pub new_messages: Option<Vec<serde_json::Value>>,
62    /// The tool ran and is calling its own result a failure.
63    pub reported_failure: bool,
64    /// The result's structured content, when the tool gave one.
65    pub structured: Option<serde_json::Value>,
66    /// The files the call wrote, for the host.
67    pub file_changes: Vec<crate::interface::tool::FileChange>,
68}
69
70impl ToolAnswer {
71    /// A tool that ran and answered.
72    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    /// A tool that ran and is calling the result a failure.
83    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/// The call being made, as a wrapper may see it. Read-only by design — see
95/// the module docs.
96#[derive(Debug, Clone, Default)]
97pub struct ToolCall {
98    pub name: String,
99    pub input: serde_json::Value,
100    /// Who made the call: `model`, `RunCode`, `RunExt:<command>` or
101    /// `PluginCall:<function>` of the package `plugin`, `user` for a `/name`
102    /// plugin command, `skill` for a skill's inline command, `host` outside any turn.
103    pub via: String,
104    pub plugin: Option<String>,
105    /// The session's working directory (a worktree's, in one) if it has a project.
106    pub project_root: Option<std::path::PathBuf>,
107}
108
109impl ToolCall {
110    /// A call the model made.
111    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
121/// The conditions the call runs under, as a wrapper may change them.
122pub struct ToolExec {
123    /// Cancelled when the call should stop. A wrapper replaces this to impose
124    /// something stricter; it cannot loosen the turn's, because a child token
125    /// fires when its parent does no matter what.
126    cancel: CancellationToken,
127    /// The earliest deadline a wrapper set; `cancel` fires there while the
128    /// call runs.
129    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    /// Stop the call after `after`, on top of whatever already stops it.
145    ///
146    /// The new signal is a *child* of the current one, which is what makes
147    /// this one-way: it can fire earlier than the turn's cancellation, never
148    /// later, so a wrapper cannot extend a call past the point the session
149    /// gave up on it.
150    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    /// `call` under this signal, which fires at the deadline if the call is
157    /// still running then.
158    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
178/// The rest of the chain, ending in the engine's own dispatch.
179pub struct NextDispatch<'a> {
180    remaining: &'a [Arc<dyn ToolMiddleware>],
181    terminal: &'a Terminal<'a>,
182}
183
184impl<'a> NextDispatch<'a> {
185    /// Run everything inside this wrapper.
186    ///
187    /// Takes `&self` so it can be called more than once — that is what makes
188    /// a retry expressible rather than something a wrapper has to fake.
189    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/// A ring around every tool call.
204#[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
214/// Run `chain` around `dispatch`.
215///
216/// With an empty chain this is `dispatch` and nothing else — no clone, no
217/// allocation, no future wrapped in another future. That matters: tool
218/// dispatch is on the hot path, and a seam nobody uses should cost nothing.
219pub 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    /// The acceptance case: a wrapper imposes a deadline the tool actually
267    /// feels, without the turn knowing anything about it.
268    #[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                // A tool that would run forever if nothing stopped it.
292                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    /// A wrapper narrows the signal; it cannot widen it. The turn's own
335    /// cancellation still ends the call.
336    #[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    /// Registration order is nesting order, and the outermost wrapper sees an
430    /// inner one's retries as a single call.
431    #[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}