reef-core 0.4.0

Provider-neutral primitives for building LLM agents: run lifecycle, transcript, tools, hooks
Documentation
//! Correlates prepare plans with routing and execution outcomes.
//!
//! This crate-private layer does only three things: convert every
//! source-ordered prepare slot to its matching engine entry, obtain invocation-local
//! routing capabilities for executable slots, and close successful outcomes with
//! both the original and effective calls. Result rewriting, transcript items,
//! controller commits, producer seams, and lifecycle callbacks remain outside.

use std::sync::Arc;

use crate::cancel::Token;

use crate::runtime::event::ToolEmitter;
use crate::runtime::tool::StepToolSnapshot;
use crate::runtime::tool_batch::{self, PreparedToolCall, execute_prepared};
use crate::runtime::tool_batch_prepare::ToolBatchPreparePlan;
use crate::value::tool_call::ToolCall;

/// Invocation-local capabilities supplied after the effective call is known.
pub(crate) struct ToolRouteBinding {
    emitter: ToolEmitter,
}

impl ToolRouteBinding {
    /// Creates one binding returned by the runtime-owned binder.
    pub(crate) const fn new(emitter: ToolEmitter) -> Self {
        Self { emitter }
    }
}

/// The single closed failure returned by the execution engine.
#[derive(Debug)]
pub(crate) struct ToolBatchRouteError(tool_batch::Error);

impl ToolBatchRouteError {
    /// Wraps the execution engine's closed failure.
    pub(super) const fn new(error: tool_batch::Error) -> Self {
        Self(error)
    }

    /// Returns the closed engine failure.
    pub(crate) const fn execution(&self) -> &tool_batch::Error {
        &self.0
    }
}

/// One successful source position with both sides of rewrite correlation.
pub(crate) struct ToolRouteRecord {
    original_call: ToolCall,
    effective_call: ToolCall,
    outcome: tool_batch::Outcome,
}

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

    /// Returns the final call used for binding, routing, and transcript commit.
    pub(crate) const fn effective_call(&self) -> &ToolCall {
        &self.effective_call
    }

    /// Returns the closed business outcome.
    pub(crate) const fn outcome(&self) -> &tool_batch::Outcome {
        &self.outcome
    }

    /// Transfers the complete closed correlation record.
    pub(crate) fn into_parts(self) -> (ToolCall, ToolCall, tool_batch::Outcome) {
        (self.original_call, self.effective_call, self.outcome)
    }
}

/// The linear, source-ordered proof that routing completed for the whole batch.
///
/// This type is intentionally not [`Clone`] and has no constructor or mutable
/// record access. Only [`route_and_execute`] can create it, and the commit layer
/// consumes it whole, so callers cannot duplicate or reorder successful records
/// between execution and the atomic transcript append.
pub(crate) struct RoutedToolBatch {
    records: Vec<ToolRouteRecord>,
}

impl RoutedToolBatch {
    /// Borrows the successful records in immutable model source order.
    pub(crate) fn records(&self) -> &[ToolRouteRecord] {
        &self.records
    }

    /// Transfers the sealed order to the sibling commit layer.
    pub(super) fn into_records(self) -> Vec<ToolRouteRecord> {
        self.records
    }
}

/// The runtime-owned per-effective-call binding callback.
pub(crate) type ToolRouteBinder<'a> = dyn FnMut(&ToolCall) -> ToolRouteBinding + Send + 'a;

/// Binds and executes one all-or-nothing prepare plan.
///
/// `binder` is called exactly once for each executable slot and never for a
/// settled slot. It receives the final effective call, after all
/// `OnBeforeToolCall` rewrites. Binding completes for the whole batch before the
/// engine starts any execution. The engine owns every execution future and joins
/// or cancel-drops all of them before this function resolves.
///
/// The input shape comes from the tool-batch prepare stage; each executable
/// conversion delegates invocation minting to `PreparedToolCall`, preserving the
/// effective call's ID and this Step's frozen `StepToolSnapshot`.
pub(crate) async fn route_and_execute(
    plan: ToolBatchPreparePlan,
    snapshot: Arc<StepToolSnapshot>,
    session_id: Option<String>,
    binder: &mut ToolRouteBinder<'_>,
    cancellation: &Token,
) -> Result<RoutedToolBatch, ToolBatchRouteError> {
    if cancellation.is_cancelled() {
        return Err(ToolBatchRouteError::new(
            tool_batch::Error::cancelled_batch(),
        ));
    }

    let prepared = plan.into_entries();
    let mut correlations = Vec::with_capacity(prepared.len());
    let mut entries = Vec::with_capacity(prepared.len());
    for prepared_call in prepared {
        // `PreparedCallPlan` is produced by the prepare layer; its settled marker
        // is the only authority deciding whether this source position can be bound.
        let (original_call, effective_call, settled) = prepared_call.into_parts();
        let entry = if let Some(settled) = settled {
            let (result, disposition) = settled.into_parts();
            PreparedToolCall::settled(result, disposition)
        } else {
            let binding = binder(&effective_call);
            PreparedToolCall::executable(
                Arc::clone(&snapshot),
                session_id.clone(),
                effective_call.clone(),
                binding.emitter,
            )
        };
        correlations.push((original_call, effective_call));
        entries.push(entry);
    }

    let outcomes = execute_prepared(entries, cancellation)
        .await
        .map_err(ToolBatchRouteError::new)?;
    let records = correlations
        .into_iter()
        .zip(outcomes)
        .map(
            |((original_call, effective_call), outcome)| ToolRouteRecord {
                original_call,
                effective_call,
                outcome,
            },
        )
        .collect();
    Ok(RoutedToolBatch { records })
}