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;
pub(crate) struct ToolRouteBinding {
emitter: ToolEmitter,
}
impl ToolRouteBinding {
pub(crate) const fn new(emitter: ToolEmitter) -> Self {
Self { emitter }
}
}
#[derive(Debug)]
pub(crate) struct ToolBatchRouteError(tool_batch::Error);
impl ToolBatchRouteError {
pub(super) const fn new(error: tool_batch::Error) -> Self {
Self(error)
}
pub(crate) const fn execution(&self) -> &tool_batch::Error {
&self.0
}
}
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
}
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> = dyn FnMut(&ToolCall) -> ToolRouteBinding + Send + 'a;
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 {
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 })
}