1use 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#[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 #[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 #[must_use]
48 pub const fn with_total(mut self, total: f64) -> Self {
49 self.total = Some(total);
50 self
51 }
52
53 #[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 #[must_use]
62 pub const fn progress(&self) -> f64 {
63 self.done
64 }
65
66 #[must_use]
68 pub const fn total(&self) -> Option<f64> {
69 self.total
70 }
71
72 #[must_use]
74 pub fn message(&self) -> Option<&str> {
75 self.message.as_deref()
76 }
77}
78
79pub trait ProgressSink: Send + 'static {
87 fn report(&mut self, progress: Progress) -> impl Future<Output = ()> + Send;
94}
95
96trait 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#[derive(Debug, Clone, PartialEq)]
112pub enum ProgressError {
113 NotFinite(Progress),
115 NotIncreasing {
118 previous: f64,
120 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
144pub 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 #[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 #[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 #[must_use]
188 pub fn with_approver(mut self, approver: AnyApprover) -> Self {
189 self.approver = Some(approver);
190 self
191 }
192
193 #[must_use]
195 pub fn with_cancellation(mut self, signal: CancelSignal) -> Self {
196 self.cancellation = signal;
197 self
198 }
199
200 #[must_use]
207 pub const fn cancellation(&self) -> &CancelSignal {
208 &self.cancellation
209 }
210
211 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 #[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 #[must_use]
271 pub fn working_dir(&self) -> Option<&str> {
272 self.working_dir.as_deref()
273 }
274
275 #[must_use]
277 pub fn with_identity(mut self, identity: CallIdentity) -> Self {
278 self.identity = Some(identity);
279 self
280 }
281
282 #[must_use]
287 pub const fn identity(&self) -> Option<&CallIdentity> {
288 self.identity.as_ref()
289 }
290
291 #[must_use]
298 pub const fn is_listening(&self) -> bool {
299 self.sink.is_some()
300 }
301
302 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 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 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 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 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 #[derive(Debug, thiserror::Error)]
477 #[error("request store unavailable")]
478 struct StoreDown;
479
480 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 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 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}