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::{CallAttachments, ToolCallContext, ToolDescription};
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 attachments_mut(&mut self) -> Option<&mut CallAttachments> {
35 self.result.is_none().then_some(&mut self.call.attachments)
36 }
37
38 pub fn attach<T: Any + Send + Sync>(&mut self, value: T) -> bool {
42 if let Some(attachments) = self.attachments_mut() {
43 attachments.insert(value);
44 true
45 } else {
46 false
47 }
48 }
49
50 pub fn result(&self) -> Option<(&BlockId, &ToolResultPayload)> {
52 self.result.as_ref().map(|(id, result)| (id, result))
53 }
54
55 pub fn output_mut(&mut self) -> Option<&mut ToolOutput> {
57 self.result.as_mut().map(|(_, result)| &mut result.output)
58 }
59
60 pub fn media_mut(&mut self) -> Option<&mut Vec<MediaRef>> {
62 self.result.as_mut().map(|(_, result)| &mut result.media)
63 }
64
65 pub fn push_note(&mut self, note: TextPayload) {
67 match self.result.as_mut() {
68 Some((_, result)) => result.notes.push(note),
69 None => self.call.result_notes.push(note),
70 }
71 }
72}
73
74#[derive(Debug)]
84pub struct ToolBatch {
85 entries: Vec<ToolCallEntry>,
86 completed: usize,
87}
88
89impl ToolBatch {
90 pub fn new(calls: Vec<ToolCallContext>) -> Result<Self, BatchError> {
92 let mut declarations = HashSet::with_capacity(calls.len());
93 for call in &calls {
94 if !declarations.insert(call.call_block_id) {
95 return Err(BatchError::DuplicateDeclaration(call.call_block_id));
96 }
97 }
98 let batch = Self {
99 entries: calls
100 .into_iter()
101 .map(|call| ToolCallEntry { call, result: None })
102 .collect(),
103 completed: 0,
104 };
105 batch.validate()?;
106 Ok(batch)
107 }
108
109 pub fn calls(&self) -> &[ToolCallEntry] {
111 &self.entries[self.completed..]
112 }
113
114 pub fn calls_mut(&mut self) -> &mut [ToolCallEntry] {
116 &mut self.entries[self.completed..]
117 }
118
119 pub fn results(&self) -> &[ToolCallEntry] {
121 &self.entries[..self.completed]
122 }
123
124 pub fn results_mut(&mut self) -> &mut [ToolCallEntry] {
126 &mut self.entries[..self.completed]
127 }
128
129 pub fn completed_len(&self) -> usize {
131 self.completed
132 }
133
134 pub fn declaration_ids(&self) -> Vec<BlockId> {
136 self.entries
137 .iter()
138 .map(|entry| entry.call.call_block_id)
139 .collect()
140 }
141
142 pub fn validate(&self) -> Result<(), BatchError> {
144 if self.completed > self.entries.len() {
145 return Err(BatchError::InvalidPartition(format!(
146 "completed count {} exceeds entry count {}",
147 self.completed,
148 self.entries.len()
149 )));
150 }
151 let mut declarations = HashSet::with_capacity(self.entries.len());
152 for entry in &self.entries {
153 let declaration_id = entry.call.call_block_id;
154 if !declarations.insert(declaration_id) {
155 return Err(BatchError::DuplicateDeclaration(declaration_id));
156 }
157 }
158 let mut all_ids = declarations.clone();
159 for (index, entry) in self.entries.iter().enumerate() {
160 let declaration_id = entry.call.call_block_id;
161 match (index < self.completed, &entry.result) {
162 (true, Some((result_id, result))) => {
163 if result.call_block_id != declaration_id {
164 return Err(BatchError::MismatchedCall {
165 expected: declaration_id,
166 actual: result.call_block_id,
167 });
168 }
169 if !all_ids.insert(*result_id) {
170 return Err(BatchError::DuplicateResultBlockId(*result_id));
171 }
172 }
173 (false, None) => {}
174 (true, None) => {
175 return Err(BatchError::InvalidPartition(format!(
176 "completed entry {index} has no result"
177 )));
178 }
179 (false, Some(_)) => {
180 return Err(BatchError::InvalidPartition(format!(
181 "pending entry {index} already has a result"
182 )));
183 }
184 }
185 }
186 Ok(())
187 }
188
189 pub fn resolve_at(
195 &mut self,
196 index: usize,
197 result_block_id: BlockId,
198 mut result: ToolResultPayload,
199 ) -> Result<(), RejectedToolResult> {
200 if let Err(error) = self.check_resolve(index, result_block_id, &result) {
201 return Err(RejectedToolResult { error, result });
202 }
203 let mut notes = std::mem::take(&mut self.entries[index].call.result_notes);
204 notes.append(&mut result.notes);
205 result.notes = notes;
206 self.entries[index].call.attachments.clear();
207 self.entries[index].result = Some((result_block_id, result));
208 self.entries.swap(index, self.completed);
209 self.completed += 1;
210 Ok(())
211 }
212
213 fn check_resolve(
214 &self,
215 index: usize,
216 result_block_id: BlockId,
217 result: &ToolResultPayload,
218 ) -> Result<(), BatchError> {
219 self.validate()?;
220 if index < self.completed || index >= self.entries.len() {
221 return Err(BatchError::InvalidIndex {
222 index,
223 completed: self.completed,
224 total: self.entries.len(),
225 });
226 }
227 let expected = self.entries[index].call.call_block_id;
228 if result.call_block_id != expected {
229 return Err(BatchError::MismatchedCall {
230 expected,
231 actual: result.call_block_id,
232 });
233 }
234 if self.entries[index].result.is_some() {
235 return Err(BatchError::InvalidPartition(format!(
236 "pending entry {index} already has a result"
237 )));
238 }
239 if self.entries.iter().any(|entry| {
240 entry.call.call_block_id == result_block_id
241 || entry
242 .result
243 .as_ref()
244 .is_some_and(|(id, _)| *id == result_block_id)
245 }) {
246 return Err(BatchError::DuplicateResultBlockId(result_block_id));
247 }
248 Ok(())
249 }
250
251 pub fn validate_complete(&self) -> Result<(), BatchError> {
253 self.validate()?;
254 if self.completed != self.entries.len() {
255 return Err(BatchError::Incomplete {
256 completed: self.completed,
257 total: self.entries.len(),
258 });
259 }
260 Ok(())
261 }
262
263 pub fn into_results(self) -> Result<Vec<(BlockId, ToolResultPayload)>, (BatchError, Self)> {
265 if let Err(error) = self.validate_complete() {
266 return Err((error, self));
267 }
268 Ok(self
269 .entries
270 .into_iter()
271 .map(|entry| entry.result.expect("validated complete entry"))
272 .collect())
273 }
274}
275
276#[non_exhaustive]
278pub struct ProcessorContext<'a> {
279 pub turn_id: &'a TurnId,
281 pub round_id: RoundId,
283 pub declaration_order: &'a [BlockId],
286 pub control: &'a CallControl,
288 pub tools: &'a [ToolDescription],
293 pub data: Option<&'a ProcessorData>,
296}
297impl<'a> ProcessorContext<'a> {
298 pub fn new(
301 turn_id: &'a TurnId,
302 round_id: RoundId,
303 declaration_order: &'a [BlockId],
304 control: &'a CallControl,
305 ) -> Self {
306 Self {
307 turn_id,
308 round_id,
309 declaration_order,
310 control,
311 tools: &[],
312 data: None,
313 }
314 }
315
316 pub fn with_tools(mut self, tools: &'a [ToolDescription]) -> Self {
318 self.tools = tools;
319 self
320 }
321
322 pub fn with_data(mut self, data: &'a ProcessorData) -> Self {
324 self.data = Some(data);
325 self
326 }
327
328 pub fn tool(&self, name: &str) -> Option<&'a ToolDescription> {
333 self.tools.iter().find(|tool| tool.definition.name == name)
334 }
335
336 pub fn tool_metadata<T: Any>(&self, name: &str) -> Option<&'a T> {
339 self.tool(name).and_then(|tool| tool.metadata.get::<T>())
340 }
341
342 pub fn data<T: Any>(&self) -> Option<&'a T> {
345 self.data.and_then(ProcessorData::get)
346 }
347}
348
349#[derive(Clone)]
360pub struct ProcessorData(Arc<dyn Any + Send + Sync>);
361
362impl ProcessorData {
363 pub fn new<T: Any + Send + Sync>(value: T) -> Self {
365 Self(Arc::new(value))
366 }
367
368 pub fn get<T: Any>(&self) -> Option<&T> {
371 self.0.downcast_ref()
372 }
373}
374
375impl std::fmt::Debug for ProcessorData {
376 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
377 f.debug_struct("ProcessorData").finish_non_exhaustive()
378 }
379}
380
381#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
384#[non_exhaustive]
385pub enum ProcessorError {
386 #[error("processor failed: {0}")]
388 Failed(String),
389}
390
391#[async_trait]
393pub trait ToolBatchProcessor: Send + Sync {
394 async fn process(
397 &self,
398 batch: &mut ToolBatch,
399 ctx: &ProcessorContext<'_>,
400 ) -> Result<(), ProcessorError>;
401}
402
403#[derive(Debug, thiserror::Error)]
405#[non_exhaustive]
406pub enum BatchError {
407 #[error("duplicate declaration block id: {0:?}")]
409 DuplicateDeclaration(BlockId),
410 #[error("index {index} is not pending (completed {completed}, total {total})")]
412 #[non_exhaustive]
413 InvalidIndex {
414 index: usize,
416 completed: usize,
418 total: usize,
420 },
421 #[error("result call ID mismatch: expected {expected:?}, got {actual:?}")]
423 #[non_exhaustive]
424 MismatchedCall {
425 expected: BlockId,
427 actual: BlockId,
429 },
430 #[error("duplicate result block ID: {0:?}")]
432 DuplicateResultBlockId(BlockId),
433 #[error("invalid batch partition: {0}")]
435 InvalidPartition(String),
436 #[error("batch is incomplete: {completed} of {total} entries completed")]
438 #[non_exhaustive]
439 Incomplete {
440 completed: usize,
442 total: usize,
444 },
445}
446
447#[derive(Debug, thiserror::Error)]
449#[error("{error}")]
450#[non_exhaustive]
451pub struct RejectedToolResult {
452 pub error: BatchError,
454 pub result: ToolResultPayload,
456}