Skip to main content

causa_runtime/executor/
processing.rs

1//! Ordered before/dispatch/after processing and bound-name enforcement.
2
3use 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    /// Processes a new, entirely pending batch using only this binding's fixed
11    /// targets. The caller retains the batch on every return path.
12    ///
13    /// On controlled interruption, accepted results remain, started calls with
14    /// no accepted result become unknown, and unstarted calls remain pending.
15    /// A stop first seen after the last after-processor finished is not an
16    /// interruption of this call: the batch is complete and `Ok` is returned.
17    /// Ordinary failed, rejected, or unknown results do not make this method
18    /// fail. It does not commit material or cancel the caller's parent token.
19    // ToolProcessingError preserves the rejected payload without boxing.
20    pub async fn process(self, batch: &mut ToolBatch) -> Result<(), ToolProcessingError> {
21        batch
22            .validate()
23            .map_err(ToolProcessingError::InvalidBatch)?;
24        if batch.completed_len() != 0 {
25            return Err(ToolProcessingError::NotFreshBatch {
26                completed: batch.completed_len(),
27            });
28        }
29        let declaration_order = batch.declaration_ids();
30        self.control.check().map_err(ToolProcessingError::Control)?;
31        let context = ProcessorContext::new(
32            &self.invocation_id.turn_id,
33            self.invocation_id.round_id,
34            &declaration_order,
35            &self.control,
36        );
37        self.reject_unbound(batch)?;
38        process_phase(
39            &self.executor.options.before,
40            batch,
41            &context,
42            ToolProcessorPhase::Before,
43        )
44        .await?;
45        self.control.check().map_err(ToolProcessingError::Control)?;
46        self.reject_unbound(batch)?;
47        self.dispatch(batch).await?;
48        // The after phase checks for a stop before each of its processors.
49        // With none configured, a batch whose tools all returned is finished.
50        process_phase(
51            &self.executor.options.after,
52            batch,
53            &context,
54            ToolProcessorPhase::After,
55        )
56        .await?;
57        // A stop seen from here on does not fail the call: every tool has
58        // returned and every processor has run, so the batch is reported as
59        // processed and the caller decides what the stop means.
60        batch
61            .validate()
62            .map_err(ToolProcessingError::InvalidBatch)?;
63        if batch.completed_len() != declaration_order.len() {
64            return Err(ToolProcessingError::InvalidBatch(BatchError::Incomplete {
65                completed: batch.completed_len(),
66                total: declaration_order.len(),
67            }));
68        }
69        Ok(())
70    }
71
72    // Preserve the confirmed error API carrying an unboxed rejected payload.
73    fn reject_unbound(&self, batch: &mut ToolBatch) -> Result<(), ToolProcessingError> {
74        let rejected: Vec<_> = batch
75            .calls()
76            .iter()
77            .filter(|entry| !self.targets.contains_key(&entry.call().input.tool_name))
78            .map(|entry| {
79                (
80                    entry.call().call_block_id,
81                    entry.call().input.tool_name.clone(),
82                )
83            })
84            .collect();
85        for (call_block_id, name) in rejected {
86            resolve(
87                batch,
88                call_block_id,
89                ToolResultPayload::new(
90                    call_block_id,
91                    ToolResultStatus::Rejected,
92                    ToolOutput::new(serde_json::json!({"error": format!("unknown tool: {name}")})),
93                ),
94            )?;
95        }
96        Ok(())
97    }
98}