aither-core 0.31.0

Core trait abstractions for aither
Documentation
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
//! The per-call context a [`Tool`](super::Tool) runs with.
//!
//! Every invocation of [`Tool::call`](super::Tool::call) receives its own
//! [`ToolContext`]. Whoever dispatches the call decides what the context is
//! connected to: an MCP server connects it to the request's progress token, an
//! agent that has nowhere to show progress passes [`ToolContext::new`]. The
//! tool reports the same way in both cases and never learns which it got.
//! The same holds for approval: a tool asks [`ToolContext::approve`] and the
//! request reaches whichever [`Approver`] the dispatcher attached, and for
//! cancellation, which it observes through [`ToolContext::cancellation`].

use alloc::boxed::Box;
use alloc::string::String;
use core::fmt::{self, Debug, Display};
use core::future::Future;
use core::pin::Pin;

use super::{
    AnyApprover, Approval, ApprovalError, ApprovalRequest, Approver, CallIdentity, CancelSignal,
};

/// How far a running tool call has got.
///
/// `progress` is the amount of work done so far and `total`, when known, the
/// amount there is; both may be fractional and neither has a unit. `message`
/// is a human-readable line describing the current state.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Progress {
    done: f64,
    total: Option<f64>,
    message: Option<String>,
}

impl Progress {
    /// Progress with the given amount of work done, no total, and no message.
    #[must_use]
    pub const fn new(progress: f64) -> Self {
        Self {
            done: progress,
            total: None,
            message: None,
        }
    }

    /// Sets the total amount of work.
    #[must_use]
    pub const fn with_total(mut self, total: f64) -> Self {
        self.total = Some(total);
        self
    }

    /// Sets a human-readable description of the current state.
    #[must_use]
    pub fn with_message(mut self, message: impl Into<String>) -> Self {
        self.message = Some(message.into());
        self
    }

    /// The amount of work done so far.
    #[must_use]
    pub const fn progress(&self) -> f64 {
        self.done
    }

    /// The total amount of work, if known.
    #[must_use]
    pub const fn total(&self) -> Option<f64> {
        self.total
    }

    /// The human-readable description of the current state, if any.
    #[must_use]
    pub fn message(&self) -> Option<&str> {
        self.message.as_deref()
    }
}

/// Where a [`ToolContext`] delivers the progress its tool reports.
///
/// Implemented by whatever dispatches tool calls and has somewhere to show
/// progress, such as an MCP server forwarding it to the client as
/// `notifications/progress`. Every report reaching a sink has already been
/// validated by [`ToolContext::report_progress`]: its values are finite and
/// its `progress` is greater than that of the report before it.
pub trait ProgressSink: Send + 'static {
    /// Delivers one progress report.
    ///
    /// The returned future may wait for room to deliver (backpressure) but
    /// must not block the thread. A sink whose destination is gone drops the
    /// report: progress is advisory, and the call it belongs to is being torn
    /// down anyway.
    fn report(&mut self, progress: Progress) -> impl Future<Output = ()> + Send;
}

/// Object-safe twin of [`ProgressSink`], so [`ToolContext`] can hold any sink.
trait ProgressSinkImpl: Send {
    fn report(&mut self, progress: Progress) -> Pin<Box<dyn Future<Output = ()> + Send + '_>>;
}

impl<S: ProgressSink> ProgressSinkImpl for S {
    fn report(&mut self, progress: Progress) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
        Box::pin(ProgressSink::report(self, progress))
    }
}

/// A progress report that no receiver could make sense of.
///
/// Both variants are bugs in the reporting tool, so they are returned to it
/// rather than papered over.
#[derive(Debug, Clone, PartialEq)]
pub enum ProgressError {
    /// `progress` or `total` was NaN or infinite.
    NotFinite(Progress),
    /// `progress` did not exceed the previous report's. Progress must increase
    /// with every report, even when the total is unknown.
    NotIncreasing {
        /// The `progress` of the previous accepted report.
        previous: f64,
        /// The rejected report.
        reported: Progress,
    },
}

impl Display for ProgressError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NotFinite(progress) => write!(
                f,
                "progress report is not finite: progress {}, total {:?}",
                progress.done, progress.total
            ),
            Self::NotIncreasing { previous, reported } => write!(
                f,
                "progress must increase with every report: {} does not exceed {previous}",
                reported.done
            ),
        }
    }
}

impl core::error::Error for ProgressError {}

/// The context of one tool call.
///
/// A tool receives it by value in [`Tool::call`](super::Tool::call) and may
/// move it wherever the work happens. It is deliberately not `Clone`: one
/// owner reports in sequence, which is what lets it guarantee that progress
/// increases report by report.
pub struct ToolContext {
    sink: Option<Box<dyn ProgressSinkImpl>>,
    last_progress: Option<f64>,
    identity: Option<CallIdentity>,
    working_dir: Option<String>,
    approver: Option<AnyApprover>,
    cancellation: CancelSignal,
}

impl ToolContext {
    /// A context whose caller does not listen for progress.
    ///
    /// Reports are still validated, so a tool that misreports fails the same
    /// way whether or not anyone is listening, but they are delivered nowhere.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            sink: None,
            last_progress: None,
            identity: None,
            working_dir: None,
            approver: None,
            cancellation: CancelSignal::never(),
        }
    }

    /// A context that delivers its tool's progress reports to `sink`.
    #[must_use]
    pub fn with_progress(sink: impl ProgressSink) -> Self {
        Self {
            sink: Some(Box::new(sink)),
            ..Self::new()
        }
    }

    /// Attaches the approver that answers this call's
    /// [`approve`](Self::approve) requests.
    #[must_use]
    pub fn with_approver(mut self, approver: AnyApprover) -> Self {
        self.approver = Some(approver);
        self
    }

    /// Attaches the signal through which the dispatcher cancels this call.
    #[must_use]
    pub fn with_cancellation(mut self, signal: CancelSignal) -> Self {
        self.cancellation = signal;
        self
    }

    /// The signal that fires when the dispatcher cancels this call; one
    /// that never fires when the dispatcher attached none.
    ///
    /// Work the call's future drives stops when the future is dropped; a
    /// tool watches this for work that outlives it, such as a spawned
    /// process, and clones it into that work.
    #[must_use]
    pub const fn cancellation(&self) -> &CancelSignal {
        &self.cancellation
    }

    /// Asks this call's approver whether `request` may go ahead, attributing
    /// it to this call when the context carries its identity.
    ///
    /// The returned future owns what it needs, so it is `'static` and can be
    /// moved into the part of the work that waits for the answer.
    ///
    /// # Errors
    ///
    /// [`ApprovalError::NoApprover`] when the dispatcher attached no
    /// approver: nobody can approve the action, so it must not go ahead.
    /// [`ApprovalError::Failed`] when the approver could not decide.
    /// [`ApprovalError::Cancelled`] when the call is cancelled before the
    /// approver answers; the approver's pending future is dropped.
    pub fn approve(
        &self,
        mut request: ApprovalRequest,
    ) -> impl Future<Output = Result<Approval, ApprovalError>> + Send + 'static {
        let approver = self.approver.clone();
        let cancellation = self.cancellation.clone();
        if let Some(identity) = &self.identity {
            request = request.with_call(identity.clone());
        }
        async move {
            let Some(approver) = approver else {
                return Err(ApprovalError::NoApprover {
                    kind: request.kind().clone(),
                });
            };
            if cancellation.is_cancelled() {
                return Err(ApprovalError::Cancelled);
            }
            let kind = request.kind().clone();
            let answer = async {
                approver
                    .approve(request)
                    .await
                    .map_err(|failure| ApprovalError::Failed { kind, failure })
            };
            futures_lite::future::or(answer, async {
                cancellation.cancelled().await;
                Err(ApprovalError::Cancelled)
            })
            .await
        }
    }

    /// Attaches the working directory of the process that made the call.
    #[must_use]
    pub fn with_working_dir(mut self, working_dir: impl Into<String>) -> Self {
        self.working_dir = Some(working_dir.into());
        self
    }

    /// The working directory of the process that made the call, when the
    /// dispatcher knows it.
    ///
    /// A command a shell script runs after `cd` sees the directory the script
    /// changed to; a relative path argument resolves against it. `None` for
    /// dispatchers that have no calling process, such as the agent loop.
    #[must_use]
    pub fn working_dir(&self) -> Option<&str> {
        self.working_dir.as_deref()
    }

    /// Attaches the identity of the call this context belongs to.
    #[must_use]
    pub fn with_identity(mut self, identity: CallIdentity) -> Self {
        self.identity = Some(identity);
        self
    }

    /// The id of this call and the agent making it.
    ///
    /// `None` when the dispatcher does not identify its calls, such as an MCP
    /// server or a direct call from a test; the agent loop always does.
    #[must_use]
    pub const fn identity(&self) -> Option<&CallIdentity> {
        self.identity.as_ref()
    }

    /// Whether the caller listens for progress.
    ///
    /// A tool whose work can outlast its caller's idle limit decides from
    /// this whether reporting progress keeps the call alive: without a
    /// listener, reports go nowhere and the caller sees nothing until the
    /// call returns.
    #[must_use]
    pub const fn is_listening(&self) -> bool {
        self.sink.is_some()
    }

    /// Reports how far the call has got.
    ///
    /// Delivered to the caller when it listens for progress, and a no-op when
    /// it does not. Awaiting the returned future may wait for the caller to
    /// take earlier reports.
    ///
    /// # Errors
    ///
    /// Returns [`ProgressError::NotFinite`] when `progress` or `total` is NaN
    /// or infinite, and [`ProgressError::NotIncreasing`] when `progress` does
    /// not exceed the previous report's. A rejected report is not delivered
    /// and does not count as the previous report.
    pub async fn report_progress(&mut self, progress: Progress) -> Result<(), ProgressError> {
        if !progress.done.is_finite() || progress.total.is_some_and(|total| !total.is_finite()) {
            return Err(ProgressError::NotFinite(progress));
        }
        if let Some(previous) = self.last_progress
            && progress.done <= previous
        {
            return Err(ProgressError::NotIncreasing {
                previous,
                reported: progress,
            });
        }
        self.last_progress = Some(progress.done);
        if let Some(sink) = &mut self.sink {
            sink.report(progress).await;
        }
        Ok(())
    }
}

impl Default for ToolContext {
    fn default() -> Self {
        Self::new()
    }
}

impl Debug for ToolContext {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ToolContext")
            .field("listening", &self.sink.is_some())
            .field("last_progress", &self.last_progress)
            .field("identity", &self.identity)
            .field("working_dir", &self.working_dir)
            .field("approver", &self.approver)
            .field("cancellation", &self.cancellation)
            .finish()
    }
}

#[cfg(test)]
mod tests {
    extern crate std;

    use super::super::ApproverFailure;
    use super::*;
    use alloc::vec::Vec;
    use std::sync::mpsc;

    /// Forwards every report it is handed to a channel the test drains.
    struct Collect(mpsc::Sender<Progress>);

    impl ProgressSink for Collect {
        async fn report(&mut self, progress: Progress) {
            self.0.send(progress).expect("test receiver alive");
        }
    }

    fn listening() -> (ToolContext, mpsc::Receiver<Progress>) {
        let (tx, rx) = mpsc::channel();
        (ToolContext::with_progress(Collect(tx)), rx)
    }

    #[test]
    fn reports_whether_the_caller_listens() {
        assert!(!ToolContext::new().is_listening());
        assert!(listening().0.is_listening());
    }

    #[test]
    fn carries_the_identity_it_was_given() {
        use super::super::{AgentIdentity, ToolCallId};

        assert_eq!(ToolContext::new().identity(), None);
        let identity = CallIdentity::new(ToolCallId::new("call_1"), AgentIdentity::Main);
        let cx = ToolContext::new().with_identity(identity.clone());
        assert_eq!(cx.identity(), Some(&identity));
        assert_eq!(identity.call().as_str(), "call_1");
    }

    #[tokio::test]
    async fn delivers_increasing_reports_in_order() {
        let (mut cx, seen) = listening();

        cx.report_progress(Progress::new(1.0)).await.unwrap();
        cx.report_progress(Progress::new(2.5).with_total(10.0).with_message("half"))
            .await
            .unwrap();

        assert_eq!(
            seen.try_iter().collect::<Vec<_>>(),
            [
                Progress::new(1.0),
                Progress::new(2.5).with_total(10.0).with_message("half"),
            ]
        );
    }

    #[tokio::test]
    async fn rejects_non_increasing_and_non_finite_reports() {
        let (mut cx, seen) = listening();

        cx.report_progress(Progress::new(3.0)).await.unwrap();
        assert_eq!(
            cx.report_progress(Progress::new(3.0)).await,
            Err(ProgressError::NotIncreasing {
                previous: 3.0,
                reported: Progress::new(3.0),
            })
        );
        assert!(matches!(
            cx.report_progress(Progress::new(f64::NAN)).await,
            Err(ProgressError::NotFinite(_))
        ));
        assert!(matches!(
            cx.report_progress(Progress::new(4.0).with_total(f64::INFINITY))
                .await,
            Err(ProgressError::NotFinite(_))
        ));
        // A rejected report is not the new baseline.
        cx.report_progress(Progress::new(3.5)).await.unwrap();

        assert_eq!(
            seen.try_iter().collect::<Vec<_>>(),
            [Progress::new(3.0), Progress::new(3.5)]
        );
    }

    /// Approves `allowed` and denies everything else, recording the call each
    /// request was attributed to.
    struct ApproveOnly {
        allowed: &'static str,
        seen: mpsc::Sender<Option<CallIdentity>>,
    }

    impl Approver for ApproveOnly {
        fn approve(
            &self,
            request: ApprovalRequest,
        ) -> impl Future<Output = Result<Approval, ApproverFailure>> + Send {
            self.seen
                .send(request.call().cloned())
                .expect("test receiver alive");
            core::future::ready(Ok(if request.subject() == self.allowed {
                Approval::Approved
            } else {
                Approval::Denied {
                    reason: alloc::format!("{} is not allowed", request.subject()),
                }
            }))
        }
    }

    /// Never answers, like a person who is away.
    struct Unanswered;

    impl Approver for Unanswered {
        async fn approve(&self, _request: ApprovalRequest) -> Result<Approval, ApproverFailure> {
            core::future::pending().await
        }
    }

    /// The store an approver records requests in failed.
    #[derive(Debug, thiserror::Error)]
    #[error("request store unavailable")]
    struct StoreDown;

    /// Fails on every request, like an approver whose store is down.
    struct Broken;

    impl Approver for Broken {
        fn approve(
            &self,
            _request: ApprovalRequest,
        ) -> impl Future<Output = Result<Approval, ApproverFailure>> + Send {
            core::future::ready(Err(ApproverFailure::new(StoreDown)))
        }
    }

    fn unsandboxed(subject: &str) -> ApprovalRequest {
        ApprovalRequest::new(super::super::ApprovalKind::new("unsandboxed"), subject)
    }

    #[tokio::test]
    async fn approve_reaches_the_attached_approver() {
        use super::super::{AgentIdentity, ToolCallId};

        let (tx, seen) = mpsc::channel();
        let identity = CallIdentity::new(ToolCallId::new("call_7"), AgentIdentity::Main);
        let cx = ToolContext::new()
            .with_identity(identity.clone())
            .with_approver(AnyApprover::new(ApproveOnly {
                allowed: "cargo build",
                seen: tx,
            }));

        assert_eq!(
            cx.approve(unsandboxed("cargo build")).await.unwrap(),
            Approval::Approved
        );
        assert_eq!(
            cx.approve(unsandboxed("rm -rf ~")).await.unwrap(),
            Approval::Denied {
                reason: "rm -rf ~ is not allowed".into(),
            }
        );
        assert_eq!(
            seen.try_iter().collect::<Vec<_>>(),
            [Some(identity.clone()), Some(identity)]
        );
    }

    #[tokio::test]
    async fn approve_without_an_approver_fails() {
        let error = ToolContext::new()
            .approve(unsandboxed("cargo build"))
            .await
            .expect_err("no approver, no approval");
        assert!(
            matches!(&error, ApprovalError::NoApprover { kind } if kind.as_str() == "unsandboxed"),
            "{error:?}"
        );
        assert!(
            alloc::string::ToString::to_string(&error).contains("no approver"),
            "{error}"
        );
    }

    #[tokio::test]
    async fn an_approver_failure_is_an_error_not_a_denial() {
        use core::error::Error;

        let error = ToolContext::new()
            .with_approver(AnyApprover::new(Broken))
            .approve(unsandboxed("cargo build"))
            .await
            .expect_err("a failed approver approves nothing");
        let ApprovalError::Failed { kind, .. } = &error else {
            panic!("expected ApprovalError::Failed, got {error:?}");
        };
        assert_eq!(kind.as_str(), "unsandboxed");
        let failure = error
            .source()
            .expect("the approver's failure is the source");
        assert!(failure.is::<ApproverFailure>(), "{failure:?}");
        let cause = failure.source().expect("the approver's own error");
        assert!(cause.is::<StoreDown>(), "{cause:?}");
    }

    #[tokio::test]
    async fn cancelling_the_call_withdraws_a_pending_approval() {
        let canceller = super::super::Canceller::new();
        let cx = ToolContext::new()
            .with_approver(AnyApprover::new(Unanswered))
            .with_cancellation(canceller.signal());
        let pending = cx.approve(unsandboxed("cargo build"));
        futures_lite::pin!(pending);
        assert!(
            futures_lite::future::poll_once(&mut pending)
                .await
                .is_none()
        );
        canceller.cancel();
        assert!(matches!(pending.await, Err(ApprovalError::Cancelled)));
        // Asking after the cancellation does not reach the approver.
        assert!(matches!(
            cx.approve(unsandboxed("cargo build")).await,
            Err(ApprovalError::Cancelled)
        ));
    }

    #[tokio::test]
    async fn a_tool_observes_its_cancellation() {
        use super::super::{Canceller, Tool, ToolResult};

        /// Works until its call is cancelled, then says so.
        struct UntilCancelled;

        impl Tool for UntilCancelled {
            fn name(&self) -> alloc::borrow::Cow<'static, str> {
                "until_cancelled".into()
            }

            fn description(&self) -> alloc::borrow::Cow<'static, str> {
                "Works until its call is cancelled.".into()
            }

            type Arguments = ();
            type Res = ToolResult;

            async fn call(&self, (): (), cx: ToolContext) -> crate::Result<ToolResult> {
                assert!(!cx.cancellation().is_cancelled());
                cx.cancellation().cancelled().await;
                Ok(ToolResult::text("stopped on cancel"))
            }
        }

        let canceller = Canceller::new();
        let cx = ToolContext::new().with_cancellation(canceller.signal());
        let call = UntilCancelled.call((), cx);
        futures_lite::pin!(call);
        assert!(
            futures_lite::future::poll_once(&mut call).await.is_none(),
            "the tool works until it is cancelled"
        );
        canceller.cancel();
        let result = call.await.expect("tool result");
        assert_eq!(result, ToolResult::text("stopped on cancel"));
        assert!(!ToolContext::new().cancellation().is_cancelled());
    }

    #[tokio::test]
    async fn context_without_a_listener_still_validates() {
        let mut cx = ToolContext::new();
        cx.report_progress(Progress::new(1.0)).await.unwrap();
        assert!(cx.report_progress(Progress::new(0.5)).await.is_err());
    }
}