causa_runtime/executor/
processing.rs1use super::{ToolProcessingError, ToolProcessorPhase, catalog::BoundTools, collection::resolve};
4use crate::processors::process_phase;
5use causa_kernel::{
6 BatchError, ProcessorContext, ToolBatch, ToolOutput, ToolResultPayload, ToolResultStatus,
7};
8
9impl BoundTools<'_> {
10 #[allow(clippy::result_large_err)]
19 pub async fn process(self, batch: &mut ToolBatch) -> Result<(), ToolProcessingError> {
20 batch
21 .validate()
22 .map_err(ToolProcessingError::InvalidBatch)?;
23 if batch.completed_len() != 0 {
24 return Err(ToolProcessingError::NotFreshBatch {
25 completed: batch.completed_len(),
26 });
27 }
28 let declaration_order = batch.declaration_ids();
29 self.control.check().map_err(ToolProcessingError::Control)?;
30 let context = ProcessorContext {
31 turn_id: &self.invocation_id.turn_id,
32 round_id: self.invocation_id.round_id,
33 declaration_order: &declaration_order,
34 control: &self.control,
35 };
36 self.reject_unbound(batch)?;
37 process_phase(
38 &self.executor.options.before,
39 batch,
40 &context,
41 ToolProcessorPhase::Before,
42 )
43 .await?;
44 self.control.check().map_err(ToolProcessingError::Control)?;
45 self.reject_unbound(batch)?;
46 self.dispatch(batch).await?;
47 self.control.check().map_err(ToolProcessingError::Control)?;
48 process_phase(
49 &self.executor.options.after,
50 batch,
51 &context,
52 ToolProcessorPhase::After,
53 )
54 .await?;
55 self.control.check().map_err(ToolProcessingError::Control)?;
56 batch
57 .validate()
58 .map_err(ToolProcessingError::InvalidBatch)?;
59 if batch.completed_len() != declaration_order.len() {
60 return Err(ToolProcessingError::InvalidBatch(BatchError::Incomplete {
61 completed: batch.completed_len(),
62 total: declaration_order.len(),
63 }));
64 }
65 Ok(())
66 }
67
68 #[allow(clippy::result_large_err)]
70 fn reject_unbound(&self, batch: &mut ToolBatch) -> Result<(), ToolProcessingError> {
71 let rejected: Vec<_> = batch
72 .calls()
73 .iter()
74 .filter(|entry| !self.targets.contains_key(&entry.call().input.tool_name))
75 .map(|entry| {
76 (
77 entry.call().call_block_id,
78 entry.call().input.tool_name.clone(),
79 )
80 })
81 .collect();
82 for (call_block_id, name) in rejected {
83 resolve(
84 batch,
85 call_block_id,
86 ToolResultPayload {
87 call_block_id,
88 status: ToolResultStatus::Rejected,
89 output: ToolOutput::new(
90 serde_json::json!({"error": format!("unknown tool: {name}")}),
91 ),
92 media: Vec::new(),
93 notes: Vec::new(),
94 },
95 )?;
96 }
97 Ok(())
98 }
99}