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)]
56pub struct ToolBatch {
57 entries: Vec<ToolCallEntry>,
58 completed: usize,
59}
60
61impl ToolBatch {
62 pub fn new(calls: Vec<ToolCallContext>) -> Result<Self, BatchError> {
64 let mut declarations = HashSet::with_capacity(calls.len());
65 for call in &calls {
66 if !declarations.insert(call.call_block_id) {
67 return Err(BatchError::DuplicateDeclaration(call.call_block_id));
68 }
69 }
70 let batch = Self {
71 entries: calls
72 .into_iter()
73 .map(|call| ToolCallEntry { call, result: None })
74 .collect(),
75 completed: 0,
76 };
77 batch.validate()?;
78 Ok(batch)
79 }
80
81 pub fn calls(&self) -> &[ToolCallEntry] {
83 &self.entries[self.completed..]
84 }
85
86 pub fn calls_mut(&mut self) -> &mut [ToolCallEntry] {
88 &mut self.entries[self.completed..]
89 }
90
91 pub fn results(&self) -> &[ToolCallEntry] {
93 &self.entries[..self.completed]
94 }
95
96 pub fn results_mut(&mut self) -> &mut [ToolCallEntry] {
98 &mut self.entries[..self.completed]
99 }
100
101 pub fn completed_len(&self) -> usize {
103 self.completed
104 }
105
106 pub fn declaration_ids(&self) -> Vec<BlockId> {
108 self.entries
109 .iter()
110 .map(|entry| entry.call.call_block_id)
111 .collect()
112 }
113
114 pub fn validate(&self) -> Result<(), BatchError> {
116 if self.completed > self.entries.len() {
117 return Err(BatchError::InvalidPartition(format!(
118 "completed count {} exceeds entry count {}",
119 self.completed,
120 self.entries.len()
121 )));
122 }
123 let mut declarations = HashSet::with_capacity(self.entries.len());
124 for entry in &self.entries {
125 let declaration_id = entry.call.call_block_id;
126 if !declarations.insert(declaration_id) {
127 return Err(BatchError::DuplicateDeclaration(declaration_id));
128 }
129 }
130 let mut all_ids = declarations.clone();
131 for (index, entry) in self.entries.iter().enumerate() {
132 let declaration_id = entry.call.call_block_id;
133 match (index < self.completed, &entry.result) {
134 (true, Some((result_id, result))) => {
135 if result.call_block_id != declaration_id {
136 return Err(BatchError::MismatchedCall {
137 expected: declaration_id,
138 actual: result.call_block_id,
139 });
140 }
141 if !all_ids.insert(*result_id) {
142 return Err(BatchError::DuplicateResultBlockId(*result_id));
143 }
144 }
145 (false, None) => {}
146 (true, None) => {
147 return Err(BatchError::InvalidPartition(format!(
148 "completed entry {index} has no result"
149 )));
150 }
151 (false, Some(_)) => {
152 return Err(BatchError::InvalidPartition(format!(
153 "pending entry {index} already has a result"
154 )));
155 }
156 }
157 }
158 Ok(())
159 }
160
161 pub fn resolve_at(
165 &mut self,
166 index: usize,
167 result_block_id: BlockId,
168 mut result: ToolResultPayload,
169 ) -> Result<(), RejectedToolResult> {
170 if let Err(error) = self.check_resolve(index, result_block_id, &result) {
171 return Err(RejectedToolResult { error, result });
172 }
173 let mut notes = std::mem::take(&mut self.entries[index].call.result_notes);
174 notes.append(&mut result.notes);
175 result.notes = notes;
176 self.entries[index].result = Some((result_block_id, result));
177 self.entries.swap(index, self.completed);
178 self.completed += 1;
179 Ok(())
180 }
181
182 fn check_resolve(
183 &self,
184 index: usize,
185 result_block_id: BlockId,
186 result: &ToolResultPayload,
187 ) -> Result<(), BatchError> {
188 self.validate()?;
189 if index < self.completed || index >= self.entries.len() {
190 return Err(BatchError::InvalidIndex {
191 index,
192 completed: self.completed,
193 total: self.entries.len(),
194 });
195 }
196 let expected = self.entries[index].call.call_block_id;
197 if result.call_block_id != expected {
198 return Err(BatchError::MismatchedCall {
199 expected,
200 actual: result.call_block_id,
201 });
202 }
203 if self.entries[index].result.is_some() {
204 return Err(BatchError::InvalidPartition(format!(
205 "pending entry {index} already has a result"
206 )));
207 }
208 if self.entries.iter().any(|entry| {
209 entry.call.call_block_id == result_block_id
210 || entry
211 .result
212 .as_ref()
213 .is_some_and(|(id, _)| *id == result_block_id)
214 }) {
215 return Err(BatchError::DuplicateResultBlockId(result_block_id));
216 }
217 Ok(())
218 }
219
220 pub fn validate_complete(&self) -> Result<(), BatchError> {
222 self.validate()?;
223 if self.completed != self.entries.len() {
224 return Err(BatchError::Incomplete {
225 completed: self.completed,
226 total: self.entries.len(),
227 });
228 }
229 Ok(())
230 }
231
232 pub fn into_results(self) -> Result<Vec<(BlockId, ToolResultPayload)>, (BatchError, Self)> {
234 if let Err(error) = self.validate_complete() {
235 return Err((error, self));
236 }
237 Ok(self
238 .entries
239 .into_iter()
240 .map(|entry| entry.result.expect("validated complete entry"))
241 .collect())
242 }
243}
244
245#[non_exhaustive]
247pub struct ProcessorContext<'a> {
248 pub turn_id: &'a TurnId,
250 pub round_id: RoundId,
252 pub declaration_order: &'a [BlockId],
254 pub control: &'a CallControl,
256}
257impl<'a> ProcessorContext<'a> {
258 pub fn new(
260 turn_id: &'a TurnId,
261 round_id: RoundId,
262 declaration_order: &'a [BlockId],
263 control: &'a CallControl,
264 ) -> Self {
265 Self {
266 turn_id,
267 round_id,
268 declaration_order,
269 control,
270 }
271 }
272}
273
274#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
277#[non_exhaustive]
278pub enum ProcessorError {
279 #[error("processor failed: {0}")]
281 Failed(String),
282}
283
284#[async_trait]
286pub trait ToolBatchProcessor: Send + Sync {
287 async fn process(
290 &self,
291 batch: &mut ToolBatch,
292 ctx: &ProcessorContext<'_>,
293 ) -> Result<(), ProcessorError>;
294}
295
296#[derive(Debug, thiserror::Error)]
298#[non_exhaustive]
299pub enum BatchError {
300 #[error("duplicate declaration block id: {0:?}")]
302 DuplicateDeclaration(BlockId),
303 #[error("index {index} is not pending (completed {completed}, total {total})")]
305 #[non_exhaustive]
306 InvalidIndex {
307 index: usize,
309 completed: usize,
311 total: usize,
313 },
314 #[error("result call ID mismatch: expected {expected:?}, got {actual:?}")]
316 #[non_exhaustive]
317 MismatchedCall {
318 expected: BlockId,
320 actual: BlockId,
322 },
323 #[error("duplicate result block ID: {0:?}")]
325 DuplicateResultBlockId(BlockId),
326 #[error("invalid batch partition: {0}")]
328 InvalidPartition(String),
329 #[error("batch is incomplete: {completed} of {total} entries completed")]
331 #[non_exhaustive]
332 Incomplete {
333 completed: usize,
335 total: usize,
337 },
338}
339
340#[derive(Debug, thiserror::Error)]
342#[error("{error}")]
343#[non_exhaustive]
344pub struct RejectedToolResult {
345 pub error: BatchError,
347 pub result: ToolResultPayload,
349}