1use crate::context::block::{MediaRef, TextPayload, ToolCallPayload};
4use crate::context::ids::BlockId;
5use crate::context::ids::{RoundId, TurnId};
6use crate::context::tool_data::{ToolOutput, ToolResultPayload};
7use crate::ports::control::CallControl;
8use crate::ports::tool::ToolCallContext;
9use async_trait::async_trait;
10use std::collections::HashSet;
11
12#[derive(Debug)]
14pub struct ToolCallEntry {
15 call: ToolCallContext,
16 result: Option<(BlockId, ToolResultPayload)>,
17}
18
19impl ToolCallEntry {
20 pub fn call(&self) -> &crate::ports::tool::ToolCallContext {
22 &self.call
23 }
24
25 pub fn input_mut(&mut self) -> Option<&mut ToolCallPayload> {
27 self.result.is_none().then_some(&mut self.call.input)
28 }
29
30 pub fn result(&self) -> Option<(&BlockId, &ToolResultPayload)> {
32 self.result.as_ref().map(|(id, result)| (id, result))
33 }
34
35 pub fn output_mut(&mut self) -> Option<&mut ToolOutput> {
37 self.result.as_mut().map(|(_, result)| &mut result.output)
38 }
39
40 pub fn media_mut(&mut self) -> Option<&mut Vec<MediaRef>> {
42 self.result.as_mut().map(|(_, result)| &mut result.media)
43 }
44
45 pub fn push_note(&mut self, note: TextPayload) {
47 match self.result.as_mut() {
48 Some((_, result)) => result.notes.push(note),
49 None => self.call.result_notes.push(note),
50 }
51 }
52}
53
54#[derive(Debug)]
64pub struct ToolBatch {
65 entries: Vec<ToolCallEntry>,
66 completed: usize,
67}
68
69impl ToolBatch {
70 pub fn new(calls: Vec<ToolCallContext>) -> Result<Self, BatchError> {
72 let mut declarations = HashSet::with_capacity(calls.len());
73 for call in &calls {
74 if !declarations.insert(call.call_block_id) {
75 return Err(BatchError::DuplicateDeclaration(call.call_block_id));
76 }
77 }
78 let batch = Self {
79 entries: calls
80 .into_iter()
81 .map(|call| ToolCallEntry { call, result: None })
82 .collect(),
83 completed: 0,
84 };
85 batch.validate()?;
86 Ok(batch)
87 }
88
89 pub fn calls(&self) -> &[ToolCallEntry] {
91 &self.entries[self.completed..]
92 }
93
94 pub fn calls_mut(&mut self) -> &mut [ToolCallEntry] {
96 &mut self.entries[self.completed..]
97 }
98
99 pub fn results(&self) -> &[ToolCallEntry] {
101 &self.entries[..self.completed]
102 }
103
104 pub fn results_mut(&mut self) -> &mut [ToolCallEntry] {
106 &mut self.entries[..self.completed]
107 }
108
109 pub fn completed_len(&self) -> usize {
111 self.completed
112 }
113
114 pub fn declaration_ids(&self) -> Vec<BlockId> {
116 self.entries
117 .iter()
118 .map(|entry| entry.call.call_block_id)
119 .collect()
120 }
121
122 pub fn validate(&self) -> Result<(), BatchError> {
124 if self.completed > self.entries.len() {
125 return Err(BatchError::InvalidPartition(format!(
126 "completed count {} exceeds entry count {}",
127 self.completed,
128 self.entries.len()
129 )));
130 }
131 let mut declarations = HashSet::with_capacity(self.entries.len());
132 for entry in &self.entries {
133 let declaration_id = entry.call.call_block_id;
134 if !declarations.insert(declaration_id) {
135 return Err(BatchError::DuplicateDeclaration(declaration_id));
136 }
137 }
138 let mut all_ids = declarations.clone();
139 for (index, entry) in self.entries.iter().enumerate() {
140 let declaration_id = entry.call.call_block_id;
141 match (index < self.completed, &entry.result) {
142 (true, Some((result_id, result))) => {
143 if result.call_block_id != declaration_id {
144 return Err(BatchError::MismatchedCall {
145 expected: declaration_id,
146 actual: result.call_block_id,
147 });
148 }
149 if !all_ids.insert(*result_id) {
150 return Err(BatchError::DuplicateResultBlockId(*result_id));
151 }
152 }
153 (false, None) => {}
154 (true, None) => {
155 return Err(BatchError::InvalidPartition(format!(
156 "completed entry {index} has no result"
157 )));
158 }
159 (false, Some(_)) => {
160 return Err(BatchError::InvalidPartition(format!(
161 "pending entry {index} already has a result"
162 )));
163 }
164 }
165 }
166 Ok(())
167 }
168
169 pub fn resolve_at(
173 &mut self,
174 index: usize,
175 result_block_id: BlockId,
176 mut result: ToolResultPayload,
177 ) -> Result<(), RejectedToolResult> {
178 if let Err(error) = self.check_resolve(index, result_block_id, &result) {
179 return Err(RejectedToolResult { error, result });
180 }
181 let mut notes = std::mem::take(&mut self.entries[index].call.result_notes);
182 notes.append(&mut result.notes);
183 result.notes = notes;
184 self.entries[index].result = Some((result_block_id, result));
185 self.entries.swap(index, self.completed);
186 self.completed += 1;
187 Ok(())
188 }
189
190 fn check_resolve(
191 &self,
192 index: usize,
193 result_block_id: BlockId,
194 result: &ToolResultPayload,
195 ) -> Result<(), BatchError> {
196 self.validate()?;
197 if index < self.completed || index >= self.entries.len() {
198 return Err(BatchError::InvalidIndex {
199 index,
200 completed: self.completed,
201 total: self.entries.len(),
202 });
203 }
204 let expected = self.entries[index].call.call_block_id;
205 if result.call_block_id != expected {
206 return Err(BatchError::MismatchedCall {
207 expected,
208 actual: result.call_block_id,
209 });
210 }
211 if self.entries[index].result.is_some() {
212 return Err(BatchError::InvalidPartition(format!(
213 "pending entry {index} already has a result"
214 )));
215 }
216 if self.entries.iter().any(|entry| {
217 entry.call.call_block_id == result_block_id
218 || entry
219 .result
220 .as_ref()
221 .is_some_and(|(id, _)| *id == result_block_id)
222 }) {
223 return Err(BatchError::DuplicateResultBlockId(result_block_id));
224 }
225 Ok(())
226 }
227
228 pub fn validate_complete(&self) -> Result<(), BatchError> {
230 self.validate()?;
231 if self.completed != self.entries.len() {
232 return Err(BatchError::Incomplete {
233 completed: self.completed,
234 total: self.entries.len(),
235 });
236 }
237 Ok(())
238 }
239
240 pub fn into_results(self) -> Result<Vec<(BlockId, ToolResultPayload)>, (BatchError, Self)> {
242 if let Err(error) = self.validate_complete() {
243 return Err((error, self));
244 }
245 Ok(self
246 .entries
247 .into_iter()
248 .map(|entry| entry.result.expect("validated complete entry"))
249 .collect())
250 }
251}
252
253#[non_exhaustive]
255pub struct ProcessorContext<'a> {
256 pub turn_id: &'a TurnId,
258 pub round_id: RoundId,
260 pub declaration_order: &'a [BlockId],
263 pub control: &'a CallControl,
265}
266impl<'a> ProcessorContext<'a> {
267 pub fn new(
269 turn_id: &'a TurnId,
270 round_id: RoundId,
271 declaration_order: &'a [BlockId],
272 control: &'a CallControl,
273 ) -> Self {
274 Self {
275 turn_id,
276 round_id,
277 declaration_order,
278 control,
279 }
280 }
281}
282
283#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
286#[non_exhaustive]
287pub enum ProcessorError {
288 #[error("processor failed: {0}")]
290 Failed(String),
291}
292
293#[async_trait]
295pub trait ToolBatchProcessor: Send + Sync {
296 async fn process(
299 &self,
300 batch: &mut ToolBatch,
301 ctx: &ProcessorContext<'_>,
302 ) -> Result<(), ProcessorError>;
303}
304
305#[derive(Debug, thiserror::Error)]
307#[non_exhaustive]
308pub enum BatchError {
309 #[error("duplicate declaration block id: {0:?}")]
311 DuplicateDeclaration(BlockId),
312 #[error("index {index} is not pending (completed {completed}, total {total})")]
314 #[non_exhaustive]
315 InvalidIndex {
316 index: usize,
318 completed: usize,
320 total: usize,
322 },
323 #[error("result call ID mismatch: expected {expected:?}, got {actual:?}")]
325 #[non_exhaustive]
326 MismatchedCall {
327 expected: BlockId,
329 actual: BlockId,
331 },
332 #[error("duplicate result block ID: {0:?}")]
334 DuplicateResultBlockId(BlockId),
335 #[error("invalid batch partition: {0}")]
337 InvalidPartition(String),
338 #[error("batch is incomplete: {completed} of {total} entries completed")]
340 #[non_exhaustive]
341 Incomplete {
342 completed: usize,
344 total: usize,
346 },
347}
348
349#[derive(Debug, thiserror::Error)]
351#[error("{error}")]
352#[non_exhaustive]
353pub struct RejectedToolResult {
354 pub error: BatchError,
356 pub result: ToolResultPayload,
358}