reef-core 0.4.0

Provider-neutral primitives for building LLM agents: run lifecycle, transcript, tools, hooks
Documentation
//! The cooperative cancellation signal every reef boundary shares.
//!
//! [`Token`] is the only cancellation type in reef's public surface. It wraps a
//! battle-tested implementation rather than reimplementing one: every semantic
//! below — the atomic cancelled flag, the wakeup of every waiter, and child
//! derivation from a parent — is delegated, so there is no reef-owned
//! concurrency to get wrong.
//!
//! Wrapping exists for the *dependency*, not for the semantics. The concrete
//! token comes from a crate at `0.7.x` on its own release cadence, and naming it
//! in a public trait method would put reef's frozen surface at the mercy of a
//! `0.7 → 0.8` bump it does not control while also forcing every `tool::Executor`
//! and `tool::Provider` implementor to add a dependency they never asked for.
//! ADR-020 records the decision, including why the wrapper
//! deliberately offers **no** conversion back to the underlying token.

use std::fmt;
use std::future::Future;

use tokio_util::sync::CancellationToken;

/// A cooperative cancellation signal.
///
/// A token is cheap to clone and every clone observes the same cancellation.
/// [`Token::child_token`] derives a token that cancels when its parent does but
/// whose own cancellation stays local, which is how a Run scopes a tool batch's
/// cancellation beneath its own.
///
/// Cancellation is one-way and idempotent: once cancelled, a token stays
/// cancelled and further [`Token::cancel`] calls change nothing.
///
/// ```
/// use reef_core::cancel;
///
/// let run = cancel::Token::new();
/// let batch = run.child_token();
/// assert!(!batch.is_cancelled());
///
/// // Cancelling the child leaves the parent running.
/// batch.cancel();
/// assert!(batch.is_cancelled());
/// assert!(!run.is_cancelled());
///
/// // Cancelling the parent reaches every descendant.
/// let sibling = run.child_token();
/// run.cancel();
/// assert!(sibling.is_cancelled());
/// ```
#[derive(Clone, Default)]
pub struct Token(CancellationToken);

impl Token {
    /// Creates a token that has not been cancelled.
    #[must_use]
    pub fn new() -> Self {
        Self(CancellationToken::new())
    }

    /// Reports whether cancellation has been requested.
    #[must_use]
    pub fn is_cancelled(&self) -> bool {
        self.0.is_cancelled()
    }

    /// Requests cancellation for this token and every token derived from it.
    pub fn cancel(&self) {
        self.0.cancel();
    }

    /// Derives a token cancelled by this one but not cancelling it.
    #[must_use]
    pub fn child_token(&self) -> Self {
        Self(self.0.child_token())
    }

    /// Completes once cancellation has been requested.
    ///
    /// The returned future is anonymous on purpose: naming a concrete future
    /// type here would put the underlying implementation back into the public
    /// surface that [`Token`] exists to keep it out of. Awaiting it is
    /// cancel-safe — dropping the future deregisters its waker and observes
    /// nothing.
    pub fn cancelled(&self) -> impl Future<Output = ()> + Send + '_ {
        self.0.cancelled()
    }
}

impl fmt::Debug for Token {
    /// Renders the observable state without naming the wrapped type.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Token")
            .field("cancelled", &self.0.is_cancelled())
            .finish()
    }
}

#[cfg(test)]
#[path = "cancel_tests.rs"]
mod cancel_tests;