reef-core 0.4.0

Provider-neutral primitives for building LLM agents: run lifecycle, transcript, tools, hooks
Documentation
//! Pure `OnBeforeToolCall` rewrite planning for one source-ordered batch.
//!
//! This module owns only the rewrite-planning boundary. It does not resolve
//! tools, execute calls, materialize transcript items, or publish
//! events. A plan is returned only after every source position has been prepared
//! successfully.

use std::sync::Arc;

use crate::cancel::Token;

use crate::runtime::hook::{
    self, CallbackResources, DispatchError, StepSnapshot, ToolCallDecision,
};
use crate::runtime::tool_batch::SettledDisposition;
use crate::value::tool_call::{ToolCall, ToolResult};

/// One closed pre-routing result retained by the prepare plan.
///
/// The disposition uses the exact four-state pre-routing vocabulary accepted by
/// the execution engine: short-circuited, blocked, truncated, or not executed.
/// This layer creates only the first two; later unwind code can represent the
/// other two without widening this plan.
pub(crate) struct PreparedSettlement {
    result: ToolResult,
    disposition: SettledDisposition,
}

impl PreparedSettlement {
    /// Creates one closed pre-routing result.
    pub(crate) const fn new(result: ToolResult, disposition: SettledDisposition) -> Self {
        Self {
            result,
            disposition,
        }
    }

    /// Returns the model-visible closed result.
    #[cfg_attr(not(test), expect(dead_code, reason = "reached only by tests so far"))]
    pub(crate) const fn result(&self) -> &ToolResult {
        &self.result
    }

    /// Returns the stable pre-routing disposition.
    #[cfg_attr(not(test), expect(dead_code, reason = "reached only by tests so far"))]
    pub(crate) const fn disposition(&self) -> SettledDisposition {
        self.disposition
    }

    /// Transfers the closed result and disposition to the route layer.
    pub(crate) fn into_parts(self) -> (ToolResult, SettledDisposition) {
        (self.result, self.disposition)
    }
}

/// One source position after the complete hook rewrite fan-out.
pub(crate) struct PreparedCallPlan {
    original: ToolCall,
    effective: ToolCall,
    settled: Option<PreparedSettlement>,
}

impl PreparedCallPlan {
    /// Returns the exact call emitted by the model.
    #[cfg_attr(not(test), expect(dead_code, reason = "reached only by tests so far"))]
    pub(crate) const fn original(&self) -> &ToolCall {
        &self.original
    }

    /// Returns the final chained rewrite, retaining the original call identity.
    pub(crate) const fn effective(&self) -> &ToolCall {
        &self.effective
    }

    /// Returns a closed result when routing must be skipped.
    #[cfg_attr(not(test), expect(dead_code, reason = "reached only by tests so far"))]
    pub(crate) const fn settled(&self) -> Option<&PreparedSettlement> {
        self.settled.as_ref()
    }

    /// Transfers all facts to the routing conversion boundary.
    pub(crate) fn into_parts(self) -> (ToolCall, ToolCall, Option<PreparedSettlement>) {
        (self.original, self.effective, self.settled)
    }
}

/// An all-or-nothing, source-ordered before-tool-call plan.
pub(crate) struct ToolBatchPreparePlan {
    entries: Vec<PreparedCallPlan>,
}

impl ToolBatchPreparePlan {
    /// Returns every prepared source position in model order.
    pub(crate) fn entries(&self) -> &[PreparedCallPlan] {
        &self.entries
    }

    /// Transfers the complete source-ordered plan to the route layer.
    pub(crate) fn into_entries(self) -> Vec<PreparedCallPlan> {
        self.entries
    }
}

/// Runs the pure before-tool-call rewrite plane in source and registration order.
///
/// Every adapter receives the callback resources at its full registry index, so
/// registrations that do not mount tool hooks cannot collapse resource identity.
/// A callback error or observed cancellation returns one batch-level error and
/// drops the local entries, making a partial plan unobservable.
pub(crate) fn prepare_tool_calls(
    calls: Vec<ToolCall>,
    registry: &hook::RuntimeRegistry,
    resources: &[CallbackResources<'_>],
    snapshot: Arc<StepSnapshot>,
    cancellation: &Token,
) -> Result<ToolBatchPreparePlan, DispatchError> {
    if cancellation.is_cancelled() {
        return Err(DispatchError::Cancelled);
    }

    let mut entries = Vec::with_capacity(calls.len());
    for original in calls {
        let mut effective = original.clone();
        let mut settled = None;
        for adapter in registry.tool_hooks() {
            let callback_resources = *resources
                .get(adapter.index())
                .expect("before-tool-call resources cover every registry index");
            let decision = adapter.invoke_before_tool_call(
                callback_resources,
                &snapshot,
                &effective,
                cancellation,
            )?;
            match decision {
                ToolCallDecision::Continue => {}
                ToolCallDecision::Modify(modified) => {
                    // `ToolCall` is produced by its validated value constructor.
                    // Rewrites may replace name and arguments, but never the
                    // model-assigned correlation ID.
                    let (_, name, arguments) = modified.into_parts();
                    effective = ToolCall::new(original.id().clone(), name, arguments);
                }
                ToolCallDecision::Block(reason) => {
                    // A block is a business result carrying its reason, not a
                    // control-path failure: the model is told and the Run goes on.
                    settled = Some(PreparedSettlement::new(
                        ToolResult::error_text(format!("blocked: {reason}")),
                        SettledDisposition::Blocked,
                    ));
                    break;
                }
                ToolCallDecision::ShortCircuit(result) => {
                    settled = Some(PreparedSettlement::new(
                        result,
                        SettledDisposition::ShortCircuited,
                    ));
                    break;
                }
            }
        }
        entries.push(PreparedCallPlan {
            original,
            effective,
            settled,
        });
    }

    Ok(ToolBatchPreparePlan { entries })
}