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