reef-core 0.4.0

Provider-neutral primitives for building LLM agents: run lifecycle, transcript, tools, hooks
Documentation
//! Closed errors for Agent construction, admission, and teardown.

use std::error::Error;
use std::fmt;
use std::sync::Arc;

use crate::runtime::hook::{self, AttributedError};
use crate::runtime::model::RequestError;
use crate::runtime::session::LeaseError;
use crate::transcript::store;
use crate::value::lifecycle::CoordError;

/// A panic isolated at one Agent teardown callback boundary.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ClosePanickedError;

impl fmt::Display for ClosePanickedError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("Agent OnClose callback panicked")
    }
}

impl Error for ClosePanickedError {}

/// Configuration validation failure.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum ConfigError {
    /// Hook registry construction failed.
    Hooks(hook::RegistryError),
    /// Frozen request defaults were invalid.
    InvalidDefaults(RequestError),
    /// The process-wide nonzero revision identity space was exhausted.
    RevisionIdExhausted,
}

impl fmt::Display for ConfigError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Hooks(error) => error.fmt(formatter),
            Self::InvalidDefaults(error) => error.fmt(formatter),
            Self::RevisionIdExhausted => formatter.write_str("Agent revision identity exhausted"),
        }
    }
}

impl Error for ConfigError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Hooks(error) => Some(error),
            Self::InvalidDefaults(error) => Some(error),
            Self::RevisionIdExhausted => None,
        }
    }
}

/// Why [`Agent::start`](super::Agent::start) admitted no Run.
///
/// Every variant is pre-admission. A `StartError` means no Run exists, the
/// Session lease and Agent attachment have been rolled back, and the transcript
/// is as it was; once admission completes, failure is reported by the returned
/// Run's [`Terminal`](crate::runtime::run::Terminal) instead. `Agent::start`
/// documents which condition produces which variant.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum StartError {
    /// Agent close sealed new attachment before any Session access.
    AgentClosed,
    /// The target Session already has an active lease.
    SessionBusy,
    /// Cancellation won before admission completed.
    Cancelled,
    /// The process-wide Run identity space was exhausted.
    RunIdExhausted,
    /// Session or Run identity validation failed.
    InvalidIdentity(CoordError),
    /// Lease admission or a lease-bound prepare mutation failed.
    Admission(LeaseError),
    /// A prepare hook failed.
    Prepare(AttributedError),
    /// Transcript mutation failed.
    Transcript(store::Error),
}

impl fmt::Display for StartError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::AgentClosed => formatter.write_str("Agent is closed"),
            Self::SessionBusy => formatter.write_str("Session already has an active Run"),
            Self::Cancelled => formatter.write_str("Run admission canceled"),
            Self::RunIdExhausted => formatter.write_str("Run identity exhausted"),
            Self::InvalidIdentity(error) => error.fmt(formatter),
            Self::Admission(error) => error.fmt(formatter),
            Self::Prepare(error) => {
                write!(formatter, "hook {} prepare failed", error.name())
            }
            Self::Transcript(error) => error.fmt(formatter),
        }
    }
}

impl Error for StartError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::InvalidIdentity(error) => Some(error),
            Self::Admission(error) => Some(error),
            // The attributed failure, not the `HookError` inside it: skipping
            // that link would drop the registration name, which `Display`
            // reports but nothing below the wrapper carries.
            Self::Prepare(error) => Some(error),
            Self::Transcript(error) => Some(error),
            Self::AgentClosed | Self::SessionBusy | Self::Cancelled | Self::RunIdExhausted => None,
        }
    }
}

/// Ordered immutable Agent teardown failures.
///
/// [`Error::source`] returns the first [`AttributedError`]. Remaining failures
/// stay reachable only through [`entries`](Self::entries).
#[derive(Clone, Debug)]
pub struct TeardownError(pub(super) Arc<[AttributedError]>);

impl TeardownError {
    /// Returns failures in hook registration order.
    #[must_use]
    pub fn entries(&self) -> &[AttributedError] {
        &self.0
    }
}

impl fmt::Display for TeardownError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "{} Agent OnClose callback(s) failed",
            self.0.len()
        )
    }
}

impl Error for TeardownError {
    /// The first teardown failure, in registration order.
    ///
    /// A generic `source()` walk therefore sees that first [`AttributedError`]
    /// and stops. Remaining failures are not on this chain;
    /// [`entries`](Self::entries) is the ordered list. This is not "the most
    /// severe" entry — the type does not own a severity order.
    ///
    /// [`Agent::close`](super::Agent::close) never constructs an empty aggregate:
    /// it wraps [`CloseError::Hooks`] only when `failures` is nonempty. `source()`
    /// is therefore `Some` whenever close produces this type.
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        self.0.first().map(|error| error as &(dyn Error + 'static))
    }
}

/// Agent close result, separating retryable active-run state from cached hooks.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum CloseError {
    /// One or more Run attachments still own the Agent.
    #[non_exhaustive]
    Busy {
        /// Exact number of attachments at the close linearization point.
        active_runs: usize,
    },
    /// Every teardown ran, and these callbacks failed or panicked.
    Hooks(TeardownError),
}

impl fmt::Display for CloseError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Busy { active_runs } => {
                write!(formatter, "Agent has {active_runs} active Run(s)")
            }
            Self::Hooks(errors) => errors.fmt(formatter),
        }
    }
}

impl Error for CloseError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Busy { .. } => None,
            Self::Hooks(errors) => Some(errors),
        }
    }
}