use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
use tokio_util::sync::CancellationToken;
pub type ToolOutcome = Result<ToolAnswer, String>;
#[derive(Debug, Clone, PartialEq)]
pub struct ToolAnswer {
pub text: String,
pub new_messages: Option<Vec<serde_json::Value>>,
pub reported_failure: bool,
pub structured: Option<serde_json::Value>,
pub file_changes: Vec<crate::interface::tool::FileChange>,
}
impl ToolAnswer {
pub fn text(s: impl Into<String>) -> Self {
Self {
text: s.into(),
new_messages: None,
reported_failure: false,
structured: None,
file_changes: Vec::new(),
}
}
pub fn failure(s: impl Into<String>) -> Self {
Self {
text: s.into(),
new_messages: None,
reported_failure: true,
structured: None,
file_changes: Vec::new(),
}
}
}
#[derive(Debug, Clone, Default)]
pub struct ToolCall {
pub name: String,
pub input: serde_json::Value,
pub via: String,
pub plugin: Option<String>,
pub project_root: Option<std::path::PathBuf>,
}
impl ToolCall {
pub fn new(name: impl Into<String>, input: serde_json::Value) -> Self {
Self {
name: name.into(),
input,
via: "model".into(),
..Default::default()
}
}
}
pub struct ToolExec {
cancel: CancellationToken,
deadline: Option<tokio::time::Instant>,
}
impl ToolExec {
pub fn new(cancel: CancellationToken) -> Self {
Self {
cancel,
deadline: None,
}
}
pub fn cancel(&self) -> &CancellationToken {
&self.cancel
}
pub fn with_timeout(&mut self, after: Duration) {
let at = tokio::time::Instant::now() + after;
self.deadline = Some(self.deadline.map_or(at, |earlier| earlier.min(at)));
self.cancel = self.cancel.child_token();
}
async fn run<F: Future<Output = ToolOutcome>>(&self, call: F) -> ToolOutcome {
let Some(deadline) = self.deadline else {
return call.await;
};
tokio::pin!(call);
tokio::select! {
outcome = &mut call => outcome,
_ = tokio::time::sleep_until(deadline) => {
self.cancel.cancel();
call.await
}
}
}
}
type Terminal<'a> = dyn Fn(CancellationToken) -> Pin<Box<dyn Future<Output = ToolOutcome> + Send + 'a>>
+ Send
+ Sync
+ 'a;
pub struct NextDispatch<'a> {
remaining: &'a [Arc<dyn ToolMiddleware>],
terminal: &'a Terminal<'a>,
}
impl<'a> NextDispatch<'a> {
pub async fn run(&self, call: &ToolCall, exec: &mut ToolExec) -> ToolOutcome {
match self.remaining.split_first() {
Some((next, rest)) => {
let inner = NextDispatch {
remaining: rest,
terminal: self.terminal,
};
next.around(call, exec, inner).await
}
None => exec.run((self.terminal)(exec.cancel.clone())).await,
}
}
}
#[async_trait]
pub trait ToolMiddleware: Send + Sync {
async fn around(
&self,
call: &ToolCall,
exec: &mut ToolExec,
next: NextDispatch<'_>,
) -> ToolOutcome;
}
pub async fn dispatch_through<'a, F, Fut>(
chain: &'a [Arc<dyn ToolMiddleware>],
call: ToolCall,
cancel: CancellationToken,
dispatch: F,
) -> ToolOutcome
where
F: Fn(CancellationToken) -> Fut + Send + Sync + 'a,
Fut: Future<Output = ToolOutcome> + Send + 'a,
{
let terminal = move |cancel: CancellationToken| {
Box::pin(dispatch(cancel)) as Pin<Box<dyn Future<Output = ToolOutcome> + Send + 'a>>
};
let next = NextDispatch {
remaining: chain,
terminal: &terminal,
};
let mut exec = ToolExec::new(cancel);
next.run(&call, &mut exec).await
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
fn call() -> ToolCall {
ToolCall::new("Probe", serde_json::json!({}))
}
async fn run(
chain: Vec<Arc<dyn ToolMiddleware>>,
dispatch: impl Fn(CancellationToken) -> ToolOutcome + Send + Sync,
) -> ToolOutcome {
dispatch_through(&chain, call(), CancellationToken::new(), |c| {
let out = dispatch(c);
async move { out }
})
.await
}
#[tokio::test]
async fn an_empty_chain_is_the_call_itself() {
let out = run(vec![], |_| Ok(ToolAnswer::text("ran"))).await;
assert_eq!(out, Ok(ToolAnswer::text("ran")));
}
#[tokio::test]
async fn a_wrapper_can_impose_a_deadline_the_call_feels() {
struct Deadline(Duration);
#[async_trait]
impl ToolMiddleware for Deadline {
async fn around(
&self,
call: &ToolCall,
exec: &mut ToolExec,
next: NextDispatch<'_>,
) -> ToolOutcome {
exec.with_timeout(self.0);
next.run(call, exec).await
}
}
let chain: Vec<Arc<dyn ToolMiddleware>> =
vec![Arc::new(Deadline(Duration::from_millis(20)))];
let outcome = dispatch_through(
&chain,
call(),
CancellationToken::new(),
|cancel| async move {
cancel.cancelled().await;
Err("cancelled".to_string())
},
)
.await;
assert_eq!(outcome, Err("cancelled".to_string()));
}
#[tokio::test(flavor = "current_thread")]
async fn a_deadline_timer_ends_with_the_call() {
struct Deadline;
#[async_trait]
impl ToolMiddleware for Deadline {
async fn around(
&self,
call: &ToolCall,
exec: &mut ToolExec,
next: NextDispatch<'_>,
) -> ToolOutcome {
exec.with_timeout(Duration::from_secs(3600));
next.run(call, exec).await
}
}
let metrics = tokio::runtime::Handle::current().metrics();
let before = metrics.num_alive_tasks();
let turn = CancellationToken::new();
let outcome = dispatch_through(
&[Arc::new(Deadline) as Arc<dyn ToolMiddleware>],
call(),
turn.clone(),
|_| async { Ok(ToolAnswer::text("quick")) },
)
.await;
assert_eq!(outcome, Ok(ToolAnswer::text("quick")));
for _ in 0..10 {
tokio::task::yield_now().await;
}
assert_eq!(metrics.num_alive_tasks(), before);
assert!(!turn.is_cancelled());
}
#[tokio::test]
async fn a_wrapper_cannot_outlive_the_turns_cancellation() {
struct Generous;
#[async_trait]
impl ToolMiddleware for Generous {
async fn around(
&self,
call: &ToolCall,
exec: &mut ToolExec,
next: NextDispatch<'_>,
) -> ToolOutcome {
exec.with_timeout(Duration::from_secs(3600));
next.run(call, exec).await
}
}
let turn = CancellationToken::new();
let chain: Vec<Arc<dyn ToolMiddleware>> = vec![Arc::new(Generous)];
let fired = turn.clone();
tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(20)).await;
fired.cancel();
});
let outcome = dispatch_through(&chain, call(), turn, |cancel| async move {
cancel.cancelled().await;
Err("cancelled".to_string())
})
.await;
assert_eq!(outcome, Err("cancelled".to_string()));
}
#[tokio::test]
async fn a_wrapper_can_answer_without_calling_through() {
struct Cached;
#[async_trait]
impl ToolMiddleware for Cached {
async fn around(
&self,
_call: &ToolCall,
_exec: &mut ToolExec,
_next: NextDispatch<'_>,
) -> ToolOutcome {
Ok(ToolAnswer::text("from cache"))
}
}
let calls = Arc::new(AtomicUsize::new(0));
let seen = calls.clone();
let out = run(vec![Arc::new(Cached)], move |_| {
seen.fetch_add(1, Ordering::SeqCst);
Ok(ToolAnswer::text("ran"))
})
.await;
assert_eq!(out, Ok(ToolAnswer::text("from cache")));
assert_eq!(
calls.load(Ordering::SeqCst),
0,
"a short circuit must not dispatch"
);
}
#[tokio::test]
async fn a_wrapper_can_call_through_more_than_once() {
struct RetryTwice;
#[async_trait]
impl ToolMiddleware for RetryTwice {
async fn around(
&self,
call: &ToolCall,
exec: &mut ToolExec,
next: NextDispatch<'_>,
) -> ToolOutcome {
match next.run(call, exec).await {
Ok(v) => Ok(v),
Err(_) => next.run(call, exec).await,
}
}
}
let attempts = Arc::new(AtomicUsize::new(0));
let seen = attempts.clone();
let out = run(vec![Arc::new(RetryTwice)], move |_| {
if seen.fetch_add(1, Ordering::SeqCst) == 0 {
Err("flaked".into())
} else {
Ok(ToolAnswer::text("second time"))
}
})
.await;
assert_eq!(out, Ok(ToolAnswer::text("second time")));
assert_eq!(attempts.load(Ordering::SeqCst), 2);
}
#[tokio::test]
async fn the_first_registered_wrapper_is_the_outermost() {
struct Records(&'static str, Arc<std::sync::Mutex<Vec<String>>>);
#[async_trait]
impl ToolMiddleware for Records {
async fn around(
&self,
call: &ToolCall,
exec: &mut ToolExec,
next: NextDispatch<'_>,
) -> ToolOutcome {
self.1.lock().unwrap().push(format!("enter {}", self.0));
let out = next.run(call, exec).await;
self.1.lock().unwrap().push(format!("exit {}", self.0));
out
}
}
let log = Arc::new(std::sync::Mutex::new(Vec::new()));
let chain: Vec<Arc<dyn ToolMiddleware>> = vec![
Arc::new(Records("outer", log.clone())),
Arc::new(Records("inner", log.clone())),
];
let _ = run(chain, |_| Ok(ToolAnswer::text("ran"))).await;
assert_eq!(
log.lock().unwrap().as_slice(),
["enter outer", "enter inner", "exit inner", "exit outer"]
);
}
}