Skip to main content

aither_core/llm/tool/
context.rs

1//! The per-call context a [`Tool`](super::Tool) runs with.
2//!
3//! Every invocation of [`Tool::call`](super::Tool::call) receives its own
4//! [`ToolContext`]. Whoever dispatches the call decides what the context is
5//! connected to: an MCP server connects it to the request's progress token, an
6//! agent that has nowhere to show progress passes [`ToolContext::new`]. The
7//! tool reports the same way in both cases and never learns which it got.
8//! The same holds for approval: a tool asks [`ToolContext::approve`] and the
9//! request reaches whichever [`Approver`] the dispatcher attached, and for
10//! cancellation, which it observes through [`ToolContext::cancellation`].
11
12use alloc::boxed::Box;
13use alloc::string::String;
14use core::fmt::{self, Debug, Display};
15use core::future::Future;
16use core::pin::Pin;
17
18use super::{
19    AnyApprover, Approval, ApprovalError, ApprovalRequest, Approver, CallIdentity, CancelSignal,
20};
21
22/// How far a running tool call has got.
23///
24/// `progress` is the amount of work done so far and `total`, when known, the
25/// amount there is; both may be fractional and neither has a unit. `message`
26/// is a human-readable line describing the current state.
27#[derive(Debug, Clone, PartialEq)]
28#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
29pub struct Progress {
30    done: f64,
31    total: Option<f64>,
32    message: Option<String>,
33}
34
35impl Progress {
36    /// Progress with the given amount of work done, no total, and no message.
37    #[must_use]
38    pub const fn new(progress: f64) -> Self {
39        Self {
40            done: progress,
41            total: None,
42            message: None,
43        }
44    }
45
46    /// Sets the total amount of work.
47    #[must_use]
48    pub const fn with_total(mut self, total: f64) -> Self {
49        self.total = Some(total);
50        self
51    }
52
53    /// Sets a human-readable description of the current state.
54    #[must_use]
55    pub fn with_message(mut self, message: impl Into<String>) -> Self {
56        self.message = Some(message.into());
57        self
58    }
59
60    /// The amount of work done so far.
61    #[must_use]
62    pub const fn progress(&self) -> f64 {
63        self.done
64    }
65
66    /// The total amount of work, if known.
67    #[must_use]
68    pub const fn total(&self) -> Option<f64> {
69        self.total
70    }
71
72    /// The human-readable description of the current state, if any.
73    #[must_use]
74    pub fn message(&self) -> Option<&str> {
75        self.message.as_deref()
76    }
77}
78
79/// Where a [`ToolContext`] delivers the progress its tool reports.
80///
81/// Implemented by whatever dispatches tool calls and has somewhere to show
82/// progress, such as an MCP server forwarding it to the client as
83/// `notifications/progress`. Every report reaching a sink has already been
84/// validated by [`ToolContext::report_progress`]: its values are finite and
85/// its `progress` is greater than that of the report before it.
86pub trait ProgressSink: Send + 'static {
87    /// Delivers one progress report.
88    ///
89    /// The returned future may wait for room to deliver (backpressure) but
90    /// must not block the thread. A sink whose destination is gone drops the
91    /// report: progress is advisory, and the call it belongs to is being torn
92    /// down anyway.
93    fn report(&mut self, progress: Progress) -> impl Future<Output = ()> + Send;
94}
95
96/// Object-safe twin of [`ProgressSink`], so [`ToolContext`] can hold any sink.
97trait ProgressSinkImpl: Send {
98    fn report(&mut self, progress: Progress) -> Pin<Box<dyn Future<Output = ()> + Send + '_>>;
99}
100
101impl<S: ProgressSink> ProgressSinkImpl for S {
102    fn report(&mut self, progress: Progress) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
103        Box::pin(ProgressSink::report(self, progress))
104    }
105}
106
107/// A progress report that no receiver could make sense of.
108///
109/// Both variants are bugs in the reporting tool, so they are returned to it
110/// rather than papered over.
111#[derive(Debug, Clone, PartialEq)]
112pub enum ProgressError {
113    /// `progress` or `total` was NaN or infinite.
114    NotFinite(Progress),
115    /// `progress` did not exceed the previous report's. Progress must increase
116    /// with every report, even when the total is unknown.
117    NotIncreasing {
118        /// The `progress` of the previous accepted report.
119        previous: f64,
120        /// The rejected report.
121        reported: Progress,
122    },
123}
124
125impl Display for ProgressError {
126    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127        match self {
128            Self::NotFinite(progress) => write!(
129                f,
130                "progress report is not finite: progress {}, total {:?}",
131                progress.done, progress.total
132            ),
133            Self::NotIncreasing { previous, reported } => write!(
134                f,
135                "progress must increase with every report: {} does not exceed {previous}",
136                reported.done
137            ),
138        }
139    }
140}
141
142impl core::error::Error for ProgressError {}
143
144/// The context of one tool call.
145///
146/// A tool receives it by value in [`Tool::call`](super::Tool::call) and may
147/// move it wherever the work happens. It is deliberately not `Clone`: one
148/// owner reports in sequence, which is what lets it guarantee that progress
149/// increases report by report.
150pub struct ToolContext {
151    sink: Option<Box<dyn ProgressSinkImpl>>,
152    last_progress: Option<f64>,
153    identity: Option<CallIdentity>,
154    working_dir: Option<String>,
155    approver: Option<AnyApprover>,
156    cancellation: CancelSignal,
157}
158
159impl ToolContext {
160    /// A context whose caller does not listen for progress.
161    ///
162    /// Reports are still validated, so a tool that misreports fails the same
163    /// way whether or not anyone is listening, but they are delivered nowhere.
164    #[must_use]
165    pub const fn new() -> Self {
166        Self {
167            sink: None,
168            last_progress: None,
169            identity: None,
170            working_dir: None,
171            approver: None,
172            cancellation: CancelSignal::never(),
173        }
174    }
175
176    /// A context that delivers its tool's progress reports to `sink`.
177    #[must_use]
178    pub fn with_progress(sink: impl ProgressSink) -> Self {
179        Self {
180            sink: Some(Box::new(sink)),
181            ..Self::new()
182        }
183    }
184
185    /// Attaches the approver that answers this call's
186    /// [`approve`](Self::approve) requests.
187    #[must_use]
188    pub fn with_approver(mut self, approver: AnyApprover) -> Self {
189        self.approver = Some(approver);
190        self
191    }
192
193    /// Attaches the signal through which the dispatcher cancels this call.
194    #[must_use]
195    pub fn with_cancellation(mut self, signal: CancelSignal) -> Self {
196        self.cancellation = signal;
197        self
198    }
199
200    /// The signal that fires when the dispatcher cancels this call; one
201    /// that never fires when the dispatcher attached none.
202    ///
203    /// Work the call's future drives stops when the future is dropped; a
204    /// tool watches this for work that outlives it, such as a spawned
205    /// process, and clones it into that work.
206    #[must_use]
207    pub const fn cancellation(&self) -> &CancelSignal {
208        &self.cancellation
209    }
210
211    /// Asks this call's approver whether `request` may go ahead, attributing
212    /// it to this call when the context carries its identity.
213    ///
214    /// The returned future owns what it needs, so it is `'static` and can be
215    /// moved into the part of the work that waits for the answer.
216    ///
217    /// # Errors
218    ///
219    /// [`ApprovalError::NoApprover`] when the dispatcher attached no
220    /// approver: nobody can approve the action, so it must not go ahead.
221    /// [`ApprovalError::Failed`] when the approver could not decide.
222    /// [`ApprovalError::Cancelled`] when the call is cancelled before the
223    /// approver answers; the approver's pending future is dropped.
224    pub fn approve(
225        &self,
226        mut request: ApprovalRequest,
227    ) -> impl Future<Output = Result<Approval, ApprovalError>> + Send + 'static {
228        let approver = self.approver.clone();
229        let cancellation = self.cancellation.clone();
230        if let Some(identity) = &self.identity {
231            request = request.with_call(identity.clone());
232        }
233        async move {
234            let Some(approver) = approver else {
235                return Err(ApprovalError::NoApprover {
236                    kind: request.kind().clone(),
237                });
238            };
239            if cancellation.is_cancelled() {
240                return Err(ApprovalError::Cancelled);
241            }
242            let kind = request.kind().clone();
243            let answer = async {
244                approver
245                    .approve(request)
246                    .await
247                    .map_err(|failure| ApprovalError::Failed { kind, failure })
248            };
249            futures_lite::future::or(answer, async {
250                cancellation.cancelled().await;
251                Err(ApprovalError::Cancelled)
252            })
253            .await
254        }
255    }
256
257    /// Attaches the working directory of the process that made the call.
258    #[must_use]
259    pub fn with_working_dir(mut self, working_dir: impl Into<String>) -> Self {
260        self.working_dir = Some(working_dir.into());
261        self
262    }
263
264    /// The working directory of the process that made the call, when the
265    /// dispatcher knows it.
266    ///
267    /// A command a shell script runs after `cd` sees the directory the script
268    /// changed to; a relative path argument resolves against it. `None` for
269    /// dispatchers that have no calling process, such as the agent loop.
270    #[must_use]
271    pub fn working_dir(&self) -> Option<&str> {
272        self.working_dir.as_deref()
273    }
274
275    /// Attaches the identity of the call this context belongs to.
276    #[must_use]
277    pub fn with_identity(mut self, identity: CallIdentity) -> Self {
278        self.identity = Some(identity);
279        self
280    }
281
282    /// The id of this call and the agent making it.
283    ///
284    /// `None` when the dispatcher does not identify its calls, such as an MCP
285    /// server or a direct call from a test; the agent loop always does.
286    #[must_use]
287    pub const fn identity(&self) -> Option<&CallIdentity> {
288        self.identity.as_ref()
289    }
290
291    /// Whether the caller listens for progress.
292    ///
293    /// A tool whose work can outlast its caller's idle limit decides from
294    /// this whether reporting progress keeps the call alive: without a
295    /// listener, reports go nowhere and the caller sees nothing until the
296    /// call returns.
297    #[must_use]
298    pub const fn is_listening(&self) -> bool {
299        self.sink.is_some()
300    }
301
302    /// Reports how far the call has got.
303    ///
304    /// Delivered to the caller when it listens for progress, and a no-op when
305    /// it does not. Awaiting the returned future may wait for the caller to
306    /// take earlier reports.
307    ///
308    /// # Errors
309    ///
310    /// Returns [`ProgressError::NotFinite`] when `progress` or `total` is NaN
311    /// or infinite, and [`ProgressError::NotIncreasing`] when `progress` does
312    /// not exceed the previous report's. A rejected report is not delivered
313    /// and does not count as the previous report.
314    pub async fn report_progress(&mut self, progress: Progress) -> Result<(), ProgressError> {
315        if !progress.done.is_finite() || progress.total.is_some_and(|total| !total.is_finite()) {
316            return Err(ProgressError::NotFinite(progress));
317        }
318        if let Some(previous) = self.last_progress
319            && progress.done <= previous
320        {
321            return Err(ProgressError::NotIncreasing {
322                previous,
323                reported: progress,
324            });
325        }
326        self.last_progress = Some(progress.done);
327        if let Some(sink) = &mut self.sink {
328            sink.report(progress).await;
329        }
330        Ok(())
331    }
332}
333
334impl Default for ToolContext {
335    fn default() -> Self {
336        Self::new()
337    }
338}
339
340impl Debug for ToolContext {
341    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
342        f.debug_struct("ToolContext")
343            .field("listening", &self.sink.is_some())
344            .field("last_progress", &self.last_progress)
345            .field("identity", &self.identity)
346            .field("working_dir", &self.working_dir)
347            .field("approver", &self.approver)
348            .field("cancellation", &self.cancellation)
349            .finish()
350    }
351}
352
353#[cfg(test)]
354mod tests {
355    extern crate std;
356
357    use super::super::ApproverFailure;
358    use super::*;
359    use alloc::vec::Vec;
360    use std::sync::mpsc;
361
362    /// Forwards every report it is handed to a channel the test drains.
363    struct Collect(mpsc::Sender<Progress>);
364
365    impl ProgressSink for Collect {
366        async fn report(&mut self, progress: Progress) {
367            self.0.send(progress).expect("test receiver alive");
368        }
369    }
370
371    fn listening() -> (ToolContext, mpsc::Receiver<Progress>) {
372        let (tx, rx) = mpsc::channel();
373        (ToolContext::with_progress(Collect(tx)), rx)
374    }
375
376    #[test]
377    fn reports_whether_the_caller_listens() {
378        assert!(!ToolContext::new().is_listening());
379        assert!(listening().0.is_listening());
380    }
381
382    #[test]
383    fn carries_the_identity_it_was_given() {
384        use super::super::{AgentIdentity, ToolCallId};
385
386        assert_eq!(ToolContext::new().identity(), None);
387        let identity = CallIdentity::new(ToolCallId::new("call_1"), AgentIdentity::Main);
388        let cx = ToolContext::new().with_identity(identity.clone());
389        assert_eq!(cx.identity(), Some(&identity));
390        assert_eq!(identity.call().as_str(), "call_1");
391    }
392
393    #[tokio::test]
394    async fn delivers_increasing_reports_in_order() {
395        let (mut cx, seen) = listening();
396
397        cx.report_progress(Progress::new(1.0)).await.unwrap();
398        cx.report_progress(Progress::new(2.5).with_total(10.0).with_message("half"))
399            .await
400            .unwrap();
401
402        assert_eq!(
403            seen.try_iter().collect::<Vec<_>>(),
404            [
405                Progress::new(1.0),
406                Progress::new(2.5).with_total(10.0).with_message("half"),
407            ]
408        );
409    }
410
411    #[tokio::test]
412    async fn rejects_non_increasing_and_non_finite_reports() {
413        let (mut cx, seen) = listening();
414
415        cx.report_progress(Progress::new(3.0)).await.unwrap();
416        assert_eq!(
417            cx.report_progress(Progress::new(3.0)).await,
418            Err(ProgressError::NotIncreasing {
419                previous: 3.0,
420                reported: Progress::new(3.0),
421            })
422        );
423        assert!(matches!(
424            cx.report_progress(Progress::new(f64::NAN)).await,
425            Err(ProgressError::NotFinite(_))
426        ));
427        assert!(matches!(
428            cx.report_progress(Progress::new(4.0).with_total(f64::INFINITY))
429                .await,
430            Err(ProgressError::NotFinite(_))
431        ));
432        // A rejected report is not the new baseline.
433        cx.report_progress(Progress::new(3.5)).await.unwrap();
434
435        assert_eq!(
436            seen.try_iter().collect::<Vec<_>>(),
437            [Progress::new(3.0), Progress::new(3.5)]
438        );
439    }
440
441    /// Approves `allowed` and denies everything else, recording the call each
442    /// request was attributed to.
443    struct ApproveOnly {
444        allowed: &'static str,
445        seen: mpsc::Sender<Option<CallIdentity>>,
446    }
447
448    impl Approver for ApproveOnly {
449        fn approve(
450            &self,
451            request: ApprovalRequest,
452        ) -> impl Future<Output = Result<Approval, ApproverFailure>> + Send {
453            self.seen
454                .send(request.call().cloned())
455                .expect("test receiver alive");
456            core::future::ready(Ok(if request.subject() == self.allowed {
457                Approval::Approved
458            } else {
459                Approval::Denied {
460                    reason: alloc::format!("{} is not allowed", request.subject()),
461                }
462            }))
463        }
464    }
465
466    /// Never answers, like a person who is away.
467    struct Unanswered;
468
469    impl Approver for Unanswered {
470        async fn approve(&self, _request: ApprovalRequest) -> Result<Approval, ApproverFailure> {
471            core::future::pending().await
472        }
473    }
474
475    /// The store an approver records requests in failed.
476    #[derive(Debug, thiserror::Error)]
477    #[error("request store unavailable")]
478    struct StoreDown;
479
480    /// Fails on every request, like an approver whose store is down.
481    struct Broken;
482
483    impl Approver for Broken {
484        fn approve(
485            &self,
486            _request: ApprovalRequest,
487        ) -> impl Future<Output = Result<Approval, ApproverFailure>> + Send {
488            core::future::ready(Err(ApproverFailure::new(StoreDown)))
489        }
490    }
491
492    fn unsandboxed(subject: &str) -> ApprovalRequest {
493        ApprovalRequest::new(super::super::ApprovalKind::new("unsandboxed"), subject)
494    }
495
496    #[tokio::test]
497    async fn approve_reaches_the_attached_approver() {
498        use super::super::{AgentIdentity, ToolCallId};
499
500        let (tx, seen) = mpsc::channel();
501        let identity = CallIdentity::new(ToolCallId::new("call_7"), AgentIdentity::Main);
502        let cx = ToolContext::new()
503            .with_identity(identity.clone())
504            .with_approver(AnyApprover::new(ApproveOnly {
505                allowed: "cargo build",
506                seen: tx,
507            }));
508
509        assert_eq!(
510            cx.approve(unsandboxed("cargo build")).await.unwrap(),
511            Approval::Approved
512        );
513        assert_eq!(
514            cx.approve(unsandboxed("rm -rf ~")).await.unwrap(),
515            Approval::Denied {
516                reason: "rm -rf ~ is not allowed".into(),
517            }
518        );
519        assert_eq!(
520            seen.try_iter().collect::<Vec<_>>(),
521            [Some(identity.clone()), Some(identity)]
522        );
523    }
524
525    #[tokio::test]
526    async fn approve_without_an_approver_fails() {
527        let error = ToolContext::new()
528            .approve(unsandboxed("cargo build"))
529            .await
530            .expect_err("no approver, no approval");
531        assert!(
532            matches!(&error, ApprovalError::NoApprover { kind } if kind.as_str() == "unsandboxed"),
533            "{error:?}"
534        );
535        assert!(
536            alloc::string::ToString::to_string(&error).contains("no approver"),
537            "{error}"
538        );
539    }
540
541    #[tokio::test]
542    async fn an_approver_failure_is_an_error_not_a_denial() {
543        use core::error::Error;
544
545        let error = ToolContext::new()
546            .with_approver(AnyApprover::new(Broken))
547            .approve(unsandboxed("cargo build"))
548            .await
549            .expect_err("a failed approver approves nothing");
550        let ApprovalError::Failed { kind, .. } = &error else {
551            panic!("expected ApprovalError::Failed, got {error:?}");
552        };
553        assert_eq!(kind.as_str(), "unsandboxed");
554        let failure = error
555            .source()
556            .expect("the approver's failure is the source");
557        assert!(failure.is::<ApproverFailure>(), "{failure:?}");
558        let cause = failure.source().expect("the approver's own error");
559        assert!(cause.is::<StoreDown>(), "{cause:?}");
560    }
561
562    #[tokio::test]
563    async fn cancelling_the_call_withdraws_a_pending_approval() {
564        let canceller = super::super::Canceller::new();
565        let cx = ToolContext::new()
566            .with_approver(AnyApprover::new(Unanswered))
567            .with_cancellation(canceller.signal());
568        let pending = cx.approve(unsandboxed("cargo build"));
569        futures_lite::pin!(pending);
570        assert!(
571            futures_lite::future::poll_once(&mut pending)
572                .await
573                .is_none()
574        );
575        canceller.cancel();
576        assert!(matches!(pending.await, Err(ApprovalError::Cancelled)));
577        // Asking after the cancellation does not reach the approver.
578        assert!(matches!(
579            cx.approve(unsandboxed("cargo build")).await,
580            Err(ApprovalError::Cancelled)
581        ));
582    }
583
584    #[tokio::test]
585    async fn a_tool_observes_its_cancellation() {
586        use super::super::{Canceller, Tool, ToolResult};
587
588        /// Works until its call is cancelled, then says so.
589        struct UntilCancelled;
590
591        impl Tool for UntilCancelled {
592            fn name(&self) -> alloc::borrow::Cow<'static, str> {
593                "until_cancelled".into()
594            }
595
596            fn description(&self) -> alloc::borrow::Cow<'static, str> {
597                "Works until its call is cancelled.".into()
598            }
599
600            type Arguments = ();
601            type Res = ToolResult;
602
603            async fn call(&self, (): (), cx: ToolContext) -> crate::Result<ToolResult> {
604                assert!(!cx.cancellation().is_cancelled());
605                cx.cancellation().cancelled().await;
606                Ok(ToolResult::text("stopped on cancel"))
607            }
608        }
609
610        let canceller = Canceller::new();
611        let cx = ToolContext::new().with_cancellation(canceller.signal());
612        let call = UntilCancelled.call((), cx);
613        futures_lite::pin!(call);
614        assert!(
615            futures_lite::future::poll_once(&mut call).await.is_none(),
616            "the tool works until it is cancelled"
617        );
618        canceller.cancel();
619        let result = call.await.expect("tool result");
620        assert_eq!(result, ToolResult::text("stopped on cancel"));
621        assert!(!ToolContext::new().cancellation().is_cancelled());
622    }
623
624    #[tokio::test]
625    async fn context_without_a_listener_still_validates() {
626        let mut cx = ToolContext::new();
627        cx.report_progress(Progress::new(1.0)).await.unwrap();
628        assert!(cx.report_progress(Progress::new(0.5)).await.is_err());
629    }
630}