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 context = ProcessorContext::new(
30            &self.invocation_id.turn_id,
31            self.invocation_id.round_id,
32            &declaration_order,
33            &self.control,
34        );
35        self.reject_unbound(batch)?;
36        process_phase(
37            &self.executor.options.before,
38            batch,
39            &context,
40            ToolProcessorPhase::Before,
41        )
42        .await?;
43        self.control.check().map_err(ToolProcessingError::Control)?;
44        self.reject_unbound(batch)?;
45        self.dispatch(batch).await?;
46        // The after phase checks for a stop before each of its processors.
47        // With none configured, a batch whose tools all returned is finished.
48        process_phase(
49            &self.executor.options.after,
50            batch,
51            &context,
52            ToolProcessorPhase::After,
53        )
54        .await?;
55        // A stop seen from here on does not fail the call: every tool has
56        // returned and every processor has run, so the batch is reported as
57        // processed and the caller decides what the stop means.
58        batch
59            .validate_complete()
60            .map_err(ToolProcessingError::InvalidBatch)
61    }
62
63    // Preserve the confirmed error API carrying an unboxed rejected payload.
64    fn reject_unbound(&self, batch: &mut ToolBatch) -> Result<(), ToolProcessingError> {
65        let rejected: Vec<_> = batch
66            .calls()
67            .iter()
68            .filter(|entry| !self.targets.contains_key(&entry.call().input.tool_name))
69            .map(|entry| {
70                (
71                    entry.call().call_block_id,
72                    entry.call().input.tool_name.clone(),
73                )
74            })
75            .collect();
76        for (call_block_id, name) in rejected {
77            resolve(
78                batch,
79                call_block_id,
80                ToolResultPayload::new(
81                    call_block_id,
82                    ToolResultStatus::Rejected,
83                    ToolOutput::new(serde_json::json!({"error": format!("unknown tool: {name}")})),
84                ),
85            )?;
86        }
87        Ok(())
88    }
89}