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, ToolDescription, ToolHints};
9use async_trait::async_trait;
10use std::any::Any;
11use std::collections::HashSet;
12use std::sync::Arc;
13
14#[derive(Debug)]
16pub struct ToolCallEntry {
17 call: ToolCallContext,
18 result: Option<(BlockId, ToolResultPayload)>,
19}
20
21impl ToolCallEntry {
22 pub fn call(&self) -> &crate::ports::tool::ToolCallContext {
24 &self.call
25 }
26
27 pub fn input_mut(&mut self) -> Option<&mut ToolCallPayload> {
29 self.result.is_none().then_some(&mut self.call.input)
30 }
31
32 pub fn result(&self) -> Option<(&BlockId, &ToolResultPayload)> {
34 self.result.as_ref().map(|(id, result)| (id, result))
35 }
36
37 pub fn output_mut(&mut self) -> Option<&mut ToolOutput> {
39 self.result.as_mut().map(|(_, result)| &mut result.output)
40 }
41
42 pub fn media_mut(&mut self) -> Option<&mut Vec<MediaRef>> {
44 self.result.as_mut().map(|(_, result)| &mut result.media)
45 }
46
47 pub fn push_note(&mut self, note: TextPayload) {
49 match self.result.as_mut() {
50 Some((_, result)) => result.notes.push(note),
51 None => self.call.result_notes.push(note),
52 }
53 }
54}
55
56#[derive(Debug)]
66pub struct ToolBatch {
67 entries: Vec<ToolCallEntry>,
68 completed: usize,
69}
70
71impl ToolBatch {
72 pub fn new(calls: Vec<ToolCallContext>) -> Result<Self, BatchError> {
74 let mut declarations = HashSet::with_capacity(calls.len());
75 for call in &calls {
76 if !declarations.insert(call.call_block_id) {
77 return Err(BatchError::DuplicateDeclaration(call.call_block_id));
78 }
79 }
80 let batch = Self {
81 entries: calls
82 .into_iter()
83 .map(|call| ToolCallEntry { call, result: None })
84 .collect(),
85 completed: 0,
86 };
87 batch.validate()?;
88 Ok(batch)
89 }
90
91 pub fn calls(&self) -> &[ToolCallEntry] {
93 &self.entries[self.completed..]
94 }
95
96 pub fn calls_mut(&mut self) -> &mut [ToolCallEntry] {
98 &mut self.entries[self.completed..]
99 }
100
101 pub fn results(&self) -> &[ToolCallEntry] {
103 &self.entries[..self.completed]
104 }
105
106 pub fn results_mut(&mut self) -> &mut [ToolCallEntry] {
108 &mut self.entries[..self.completed]
109 }
110
111 pub fn completed_len(&self) -> usize {
113 self.completed
114 }
115
116 pub fn declaration_ids(&self) -> Vec<BlockId> {
118 self.entries
119 .iter()
120 .map(|entry| entry.call.call_block_id)
121 .collect()
122 }
123
124 pub fn validate(&self) -> Result<(), BatchError> {
126 if self.completed > self.entries.len() {
127 return Err(BatchError::InvalidPartition(format!(
128 "completed count {} exceeds entry count {}",
129 self.completed,
130 self.entries.len()
131 )));
132 }
133 let mut declarations = HashSet::with_capacity(self.entries.len());
134 for entry in &self.entries {
135 let declaration_id = entry.call.call_block_id;
136 if !declarations.insert(declaration_id) {
137 return Err(BatchError::DuplicateDeclaration(declaration_id));
138 }
139 }
140 let mut all_ids = declarations.clone();
141 for (index, entry) in self.entries.iter().enumerate() {
142 let declaration_id = entry.call.call_block_id;
143 match (index < self.completed, &entry.result) {
144 (true, Some((result_id, result))) => {
145 if result.call_block_id != declaration_id {
146 return Err(BatchError::MismatchedCall {
147 expected: declaration_id,
148 actual: result.call_block_id,
149 });
150 }
151 if !all_ids.insert(*result_id) {
152 return Err(BatchError::DuplicateResultBlockId(*result_id));
153 }
154 }
155 (false, None) => {}
156 (true, None) => {
157 return Err(BatchError::InvalidPartition(format!(
158 "completed entry {index} has no result"
159 )));
160 }
161 (false, Some(_)) => {
162 return Err(BatchError::InvalidPartition(format!(
163 "pending entry {index} already has a result"
164 )));
165 }
166 }
167 }
168 Ok(())
169 }
170
171 pub fn resolve_at(
175 &mut self,
176 index: usize,
177 result_block_id: BlockId,
178 mut result: ToolResultPayload,
179 ) -> Result<(), RejectedToolResult> {
180 if let Err(error) = self.check_resolve(index, result_block_id, &result) {
181 return Err(RejectedToolResult { error, result });
182 }
183 let mut notes = std::mem::take(&mut self.entries[index].call.result_notes);
184 notes.append(&mut result.notes);
185 result.notes = notes;
186 self.entries[index].result = Some((result_block_id, result));
187 self.entries.swap(index, self.completed);
188 self.completed += 1;
189 Ok(())
190 }
191
192 fn check_resolve(
193 &self,
194 index: usize,
195 result_block_id: BlockId,
196 result: &ToolResultPayload,
197 ) -> Result<(), BatchError> {
198 self.validate()?;
199 if index < self.completed || index >= self.entries.len() {
200 return Err(BatchError::InvalidIndex {
201 index,
202 completed: self.completed,
203 total: self.entries.len(),
204 });
205 }
206 let expected = self.entries[index].call.call_block_id;
207 if result.call_block_id != expected {
208 return Err(BatchError::MismatchedCall {
209 expected,
210 actual: result.call_block_id,
211 });
212 }
213 if self.entries[index].result.is_some() {
214 return Err(BatchError::InvalidPartition(format!(
215 "pending entry {index} already has a result"
216 )));
217 }
218 if self.entries.iter().any(|entry| {
219 entry.call.call_block_id == result_block_id
220 || entry
221 .result
222 .as_ref()
223 .is_some_and(|(id, _)| *id == result_block_id)
224 }) {
225 return Err(BatchError::DuplicateResultBlockId(result_block_id));
226 }
227 Ok(())
228 }
229
230 pub fn validate_complete(&self) -> Result<(), BatchError> {
232 self.validate()?;
233 if self.completed != self.entries.len() {
234 return Err(BatchError::Incomplete {
235 completed: self.completed,
236 total: self.entries.len(),
237 });
238 }
239 Ok(())
240 }
241
242 pub fn into_results(self) -> Result<Vec<(BlockId, ToolResultPayload)>, (BatchError, Self)> {
244 if let Err(error) = self.validate_complete() {
245 return Err((error, self));
246 }
247 Ok(self
248 .entries
249 .into_iter()
250 .map(|entry| entry.result.expect("validated complete entry"))
251 .collect())
252 }
253}
254
255#[non_exhaustive]
257pub struct ProcessorContext<'a> {
258 pub turn_id: &'a TurnId,
260 pub round_id: RoundId,
262 pub declaration_order: &'a [BlockId],
265 pub control: &'a CallControl,
267 pub tools: &'a [ToolDescription],
272 pub data: Option<&'a ProcessorData>,
275}
276impl<'a> ProcessorContext<'a> {
277 pub fn new(
280 turn_id: &'a TurnId,
281 round_id: RoundId,
282 declaration_order: &'a [BlockId],
283 control: &'a CallControl,
284 ) -> Self {
285 Self {
286 turn_id,
287 round_id,
288 declaration_order,
289 control,
290 tools: &[],
291 data: None,
292 }
293 }
294
295 pub fn with_tools(mut self, tools: &'a [ToolDescription]) -> Self {
297 self.tools = tools;
298 self
299 }
300
301 pub fn with_data(mut self, data: &'a ProcessorData) -> Self {
303 self.data = Some(data);
304 self
305 }
306
307 pub fn hints(&self, name: &str) -> Option<&'a ToolHints> {
312 self.tools
313 .iter()
314 .find(|tool| tool.definition.name == name)
315 .map(|tool| &tool.hints)
316 }
317
318 pub fn data<T: Any>(&self) -> Option<&'a T> {
321 self.data.and_then(ProcessorData::get)
322 }
323}
324
325#[derive(Clone)]
336pub struct ProcessorData(Arc<dyn Any + Send + Sync>);
337
338impl ProcessorData {
339 pub fn new<T: Any + Send + Sync>(value: T) -> Self {
341 Self(Arc::new(value))
342 }
343
344 pub fn get<T: Any>(&self) -> Option<&T> {
347 self.0.downcast_ref()
348 }
349}
350
351impl std::fmt::Debug for ProcessorData {
352 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
353 f.debug_struct("ProcessorData").finish_non_exhaustive()
354 }
355}
356
357#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
360#[non_exhaustive]
361pub enum ProcessorError {
362 #[error("processor failed: {0}")]
364 Failed(String),
365}
366
367#[async_trait]
369pub trait ToolBatchProcessor: Send + Sync {
370 async fn process(
373 &self,
374 batch: &mut ToolBatch,
375 ctx: &ProcessorContext<'_>,
376 ) -> Result<(), ProcessorError>;
377}
378
379#[derive(Debug, thiserror::Error)]
381#[non_exhaustive]
382pub enum BatchError {
383 #[error("duplicate declaration block id: {0:?}")]
385 DuplicateDeclaration(BlockId),
386 #[error("index {index} is not pending (completed {completed}, total {total})")]
388 #[non_exhaustive]
389 InvalidIndex {
390 index: usize,
392 completed: usize,
394 total: usize,
396 },
397 #[error("result call ID mismatch: expected {expected:?}, got {actual:?}")]
399 #[non_exhaustive]
400 MismatchedCall {
401 expected: BlockId,
403 actual: BlockId,
405 },
406 #[error("duplicate result block ID: {0:?}")]
408 DuplicateResultBlockId(BlockId),
409 #[error("invalid batch partition: {0}")]
411 InvalidPartition(String),
412 #[error("batch is incomplete: {completed} of {total} entries completed")]
414 #[non_exhaustive]
415 Incomplete {
416 completed: usize,
418 total: usize,
420 },
421}
422
423#[derive(Debug, thiserror::Error)]
425#[error("{error}")]
426#[non_exhaustive]
427pub struct RejectedToolResult {
428 pub error: BatchError,
430 pub result: ToolResultPayload,
432}