use crate::context::block::{MediaRef, TextPayload, ToolCallPayload};
use crate::context::ids::BlockId;
use crate::context::ids::{RoundId, TurnId};
use crate::context::tool_data::{ToolOutput, ToolResultPayload};
use crate::ports::control::CallControl;
use crate::ports::tool::ToolCallContext;
use async_trait::async_trait;
use std::collections::HashSet;
#[derive(Debug)]
pub struct ToolCallEntry {
call: ToolCallContext,
result: Option<(BlockId, ToolResultPayload)>,
}
impl ToolCallEntry {
pub fn call(&self) -> &crate::ports::tool::ToolCallContext {
&self.call
}
pub fn input_mut(&mut self) -> Option<&mut ToolCallPayload> {
self.result.is_none().then_some(&mut self.call.input)
}
pub fn result(&self) -> Option<(&BlockId, &ToolResultPayload)> {
self.result.as_ref().map(|(id, result)| (id, result))
}
pub fn output_mut(&mut self) -> Option<&mut ToolOutput> {
self.result.as_mut().map(|(_, result)| &mut result.output)
}
pub fn media_mut(&mut self) -> Option<&mut Vec<MediaRef>> {
self.result.as_mut().map(|(_, result)| &mut result.media)
}
pub fn push_note(&mut self, note: TextPayload) {
match self.result.as_mut() {
Some((_, result)) => result.notes.push(note),
None => self.call.result_notes.push(note),
}
}
}
#[derive(Debug)]
pub struct ToolBatch {
entries: Vec<ToolCallEntry>,
completed: usize,
}
impl ToolBatch {
pub fn new(calls: Vec<ToolCallContext>) -> Result<Self, BatchError> {
let mut declarations = HashSet::with_capacity(calls.len());
for call in &calls {
if !declarations.insert(call.call_block_id) {
return Err(BatchError::DuplicateDeclaration(call.call_block_id));
}
}
let batch = Self {
entries: calls
.into_iter()
.map(|call| ToolCallEntry { call, result: None })
.collect(),
completed: 0,
};
batch.validate()?;
Ok(batch)
}
pub fn calls(&self) -> &[ToolCallEntry] {
&self.entries[self.completed..]
}
pub fn calls_mut(&mut self) -> &mut [ToolCallEntry] {
&mut self.entries[self.completed..]
}
pub fn results(&self) -> &[ToolCallEntry] {
&self.entries[..self.completed]
}
pub fn results_mut(&mut self) -> &mut [ToolCallEntry] {
&mut self.entries[..self.completed]
}
pub fn completed_len(&self) -> usize {
self.completed
}
pub fn declaration_ids(&self) -> Vec<BlockId> {
self.entries
.iter()
.map(|entry| entry.call.call_block_id)
.collect()
}
pub fn validate(&self) -> Result<(), BatchError> {
if self.completed > self.entries.len() {
return Err(BatchError::InvalidPartition(format!(
"completed count {} exceeds entry count {}",
self.completed,
self.entries.len()
)));
}
let mut declarations = HashSet::with_capacity(self.entries.len());
for entry in &self.entries {
let declaration_id = entry.call.call_block_id;
if !declarations.insert(declaration_id) {
return Err(BatchError::DuplicateDeclaration(declaration_id));
}
}
let mut all_ids = declarations.clone();
for (index, entry) in self.entries.iter().enumerate() {
let declaration_id = entry.call.call_block_id;
match (index < self.completed, &entry.result) {
(true, Some((result_id, result))) => {
if result.call_block_id != declaration_id {
return Err(BatchError::MismatchedCall {
expected: declaration_id,
actual: result.call_block_id,
});
}
if !all_ids.insert(*result_id) {
return Err(BatchError::DuplicateResultBlockId(*result_id));
}
}
(false, None) => {}
(true, None) => {
return Err(BatchError::InvalidPartition(format!(
"completed entry {index} has no result"
)));
}
(false, Some(_)) => {
return Err(BatchError::InvalidPartition(format!(
"pending entry {index} already has a result"
)));
}
}
}
Ok(())
}
pub fn resolve_at(
&mut self,
index: usize,
result_block_id: BlockId,
mut result: ToolResultPayload,
) -> Result<(), RejectedToolResult> {
if let Err(error) = self.check_resolve(index, result_block_id, &result) {
return Err(RejectedToolResult { error, result });
}
let mut notes = std::mem::take(&mut self.entries[index].call.result_notes);
notes.append(&mut result.notes);
result.notes = notes;
self.entries[index].result = Some((result_block_id, result));
self.entries.swap(index, self.completed);
self.completed += 1;
Ok(())
}
fn check_resolve(
&self,
index: usize,
result_block_id: BlockId,
result: &ToolResultPayload,
) -> Result<(), BatchError> {
self.validate()?;
if index < self.completed || index >= self.entries.len() {
return Err(BatchError::InvalidIndex {
index,
completed: self.completed,
total: self.entries.len(),
});
}
let expected = self.entries[index].call.call_block_id;
if result.call_block_id != expected {
return Err(BatchError::MismatchedCall {
expected,
actual: result.call_block_id,
});
}
if self.entries[index].result.is_some() {
return Err(BatchError::InvalidPartition(format!(
"pending entry {index} already has a result"
)));
}
if self.entries.iter().any(|entry| {
entry.call.call_block_id == result_block_id
|| entry
.result
.as_ref()
.is_some_and(|(id, _)| *id == result_block_id)
}) {
return Err(BatchError::DuplicateResultBlockId(result_block_id));
}
Ok(())
}
pub fn validate_complete(&self) -> Result<(), BatchError> {
self.validate()?;
if self.completed != self.entries.len() {
return Err(BatchError::Incomplete {
completed: self.completed,
total: self.entries.len(),
});
}
Ok(())
}
pub fn into_results(self) -> Result<Vec<(BlockId, ToolResultPayload)>, (BatchError, Self)> {
if let Err(error) = self.validate_complete() {
return Err((error, self));
}
Ok(self
.entries
.into_iter()
.map(|entry| entry.result.expect("validated complete entry"))
.collect())
}
}
#[non_exhaustive]
pub struct ProcessorContext<'a> {
pub turn_id: &'a TurnId,
pub round_id: RoundId,
pub declaration_order: &'a [BlockId],
pub control: &'a CallControl,
}
impl<'a> ProcessorContext<'a> {
pub fn new(
turn_id: &'a TurnId,
round_id: RoundId,
declaration_order: &'a [BlockId],
control: &'a CallControl,
) -> Self {
Self {
turn_id,
round_id,
declaration_order,
control,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ProcessorError {
#[error("processor failed: {0}")]
Failed(String),
}
#[async_trait]
pub trait ToolBatchProcessor: Send + Sync {
async fn process(
&self,
batch: &mut ToolBatch,
ctx: &ProcessorContext<'_>,
) -> Result<(), ProcessorError>;
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum BatchError {
#[error("duplicate declaration block id: {0:?}")]
DuplicateDeclaration(BlockId),
#[error("index {index} is not pending (completed {completed}, total {total})")]
#[non_exhaustive]
InvalidIndex {
index: usize,
completed: usize,
total: usize,
},
#[error("result call ID mismatch: expected {expected:?}, got {actual:?}")]
#[non_exhaustive]
MismatchedCall {
expected: BlockId,
actual: BlockId,
},
#[error("duplicate result block ID: {0:?}")]
DuplicateResultBlockId(BlockId),
#[error("invalid batch partition: {0}")]
InvalidPartition(String),
#[error("batch is incomplete: {completed} of {total} entries completed")]
#[non_exhaustive]
Incomplete {
completed: usize,
total: usize,
},
}
#[derive(Debug, thiserror::Error)]
#[error("{error}")]
#[non_exhaustive]
pub struct RejectedToolResult {
pub error: BatchError,
pub result: ToolResultPayload,
}