use std::sync::Arc;
use crate::cancel::Token;
use crate::runtime::event::ToolEmitter;
use crate::runtime::tool::{Gate, StepToolSnapshot};
use crate::runtime::tool_batch::{self, PreparedToolCall, execute_prepared};
use crate::runtime::tool_batch_prepare::ToolBatchPreparePlan;
use crate::value::tool_call::ToolCall;
pub(crate) struct ToolRouteBinding {
emitter: ToolEmitter,
gate: Option<Arc<dyn Gate>>,
}
impl ToolRouteBinding {
pub(crate) const fn new(emitter: ToolEmitter, gate: Option<Arc<dyn Gate>>) -> Self {
Self { emitter, gate }
}
}
#[derive(Debug)]
pub(crate) enum ToolBatchRouteError<E> {
Binding { source_index: usize, error: E },
Execution(tool_batch::Error),
}
impl<E> ToolBatchRouteError<E> {
#[cfg_attr(not(test), expect(dead_code, reason = "reached only by tests so far"))]
pub(crate) const fn binding(&self) -> Option<(usize, &E)> {
match self {
Self::Binding {
source_index,
error,
} => Some((*source_index, error)),
Self::Execution(_) => None,
}
}
pub(crate) const fn execution(&self) -> Option<&tool_batch::Error> {
match self {
Self::Binding { .. } => None,
Self::Execution(failure) => Some(failure),
}
}
}
pub(crate) struct ToolRouteRecord {
original_call: ToolCall,
effective_call: ToolCall,
outcome: tool_batch::Outcome,
}
impl ToolRouteRecord {
#[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
}
#[cfg_attr(not(test), expect(dead_code, reason = "reached only by tests so far"))]
pub(crate) const fn effective_call(&self) -> &ToolCall {
&self.effective_call
}
pub(crate) const fn outcome(&self) -> &tool_batch::Outcome {
&self.outcome
}
pub(crate) fn into_parts(self) -> (ToolCall, ToolCall, tool_batch::Outcome) {
(self.original_call, self.effective_call, self.outcome)
}
}
pub(crate) struct RoutedToolBatch {
records: Vec<ToolRouteRecord>,
}
impl RoutedToolBatch {
pub(crate) fn records(&self) -> &[ToolRouteRecord] {
&self.records
}
pub(super) fn into_records(self) -> Vec<ToolRouteRecord> {
self.records
}
}
pub(crate) type ToolRouteBinder<'a, E> =
dyn FnMut(&ToolCall) -> Result<ToolRouteBinding, E> + Send + 'a;
pub(crate) async fn route_and_execute<E>(
plan: ToolBatchPreparePlan,
snapshot: Arc<StepToolSnapshot>,
session_id: Option<String>,
binder: &mut ToolRouteBinder<'_, E>,
cancellation: &Token,
) -> Result<RoutedToolBatch, ToolBatchRouteError<E>> {
if cancellation.is_cancelled() {
return Err(ToolBatchRouteError::Execution(
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 (source_index, prepared_call) in prepared.into_iter().enumerate() {
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).map_err(|error| ToolBatchRouteError::Binding {
source_index,
error,
})?;
PreparedToolCall::executable(
Arc::clone(&snapshot),
session_id.clone(),
effective_call.clone(),
binding.emitter,
binding.gate,
)
};
correlations.push((original_call, effective_call));
entries.push(entry);
}
let outcomes = execute_prepared(entries, cancellation)
.await
.map_err(ToolBatchRouteError::Execution)?;
let records = correlations
.into_iter()
.zip(outcomes)
.map(
|((original_call, effective_call), outcome)| ToolRouteRecord {
original_call,
effective_call,
outcome,
},
)
.collect();
Ok(RoutedToolBatch { records })
}