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,
};
#[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 {
#[must_use]
pub const fn new(progress: f64) -> Self {
Self {
done: progress,
total: None,
message: None,
}
}
#[must_use]
pub const fn with_total(mut self, total: f64) -> Self {
self.total = Some(total);
self
}
#[must_use]
pub fn with_message(mut self, message: impl Into<String>) -> Self {
self.message = Some(message.into());
self
}
#[must_use]
pub const fn progress(&self) -> f64 {
self.done
}
#[must_use]
pub const fn total(&self) -> Option<f64> {
self.total
}
#[must_use]
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
pub trait ProgressSink: Send + 'static {
fn report(&mut self, progress: Progress) -> impl Future<Output = ()> + Send;
}
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))
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum ProgressError {
NotFinite(Progress),
NotIncreasing {
previous: f64,
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 {}
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 {
#[must_use]
pub const fn new() -> Self {
Self {
sink: None,
last_progress: None,
identity: None,
working_dir: None,
approver: None,
cancellation: CancelSignal::never(),
}
}
#[must_use]
pub fn with_progress(sink: impl ProgressSink) -> Self {
Self {
sink: Some(Box::new(sink)),
..Self::new()
}
}
#[must_use]
pub fn with_approver(mut self, approver: AnyApprover) -> Self {
self.approver = Some(approver);
self
}
#[must_use]
pub fn with_cancellation(mut self, signal: CancelSignal) -> Self {
self.cancellation = signal;
self
}
#[must_use]
pub const fn cancellation(&self) -> &CancelSignal {
&self.cancellation
}
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
}
}
#[must_use]
pub fn with_working_dir(mut self, working_dir: impl Into<String>) -> Self {
self.working_dir = Some(working_dir.into());
self
}
#[must_use]
pub fn working_dir(&self) -> Option<&str> {
self.working_dir.as_deref()
}
#[must_use]
pub fn with_identity(mut self, identity: CallIdentity) -> Self {
self.identity = Some(identity);
self
}
#[must_use]
pub const fn identity(&self) -> Option<&CallIdentity> {
self.identity.as_ref()
}
#[must_use]
pub const fn is_listening(&self) -> bool {
self.sink.is_some()
}
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;
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(_))
));
cx.report_progress(Progress::new(3.5)).await.unwrap();
assert_eq!(
seen.try_iter().collect::<Vec<_>>(),
[Progress::new(3.0), Progress::new(3.5)]
);
}
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()),
}
}))
}
}
struct Unanswered;
impl Approver for Unanswered {
async fn approve(&self, _request: ApprovalRequest) -> Result<Approval, ApproverFailure> {
core::future::pending().await
}
}
#[derive(Debug, thiserror::Error)]
#[error("request store unavailable")]
struct StoreDown;
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)));
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};
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());
}
}