Skip to main content

causa_kernel/context/material/
tool_results.rs

1//! Execution-specific tool-result append validation.
2
3use crate::context::block::{BlockContent, ContextBlock};
4use crate::context::ids::BlockId;
5use crate::context::tool_data::ToolResultPayload;
6use std::collections::HashSet;
7
8/// Why tool results cannot be appended to the supplied material scope.
9#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
10#[non_exhaustive]
11pub enum ToolResultError {
12    /// The reference does not identify a tool declaration in this scope.
13    #[error("missing tool declaration {call_block_id:?}")]
14    MissingDeclaration {
15        /// The declaration referenced by the rejected result.
16        call_block_id: BlockId,
17    },
18    /// This declaration already has a result in the supplied material.
19    #[error("tool declaration already completed: {call_block_id:?}")]
20    AlreadyCompleted {
21        /// The declaration referenced by the rejected result.
22        call_block_id: BlockId,
23    },
24    /// This append would complete the same declaration more than once.
25    #[error("duplicate tool result for declaration {call_block_id:?}")]
26    DuplicateResult {
27        /// The declaration referenced by the rejected result.
28        call_block_id: BlockId,
29    },
30}
31
32/// Validates this result append without mutating or consuming its inputs.
33///
34/// Checks references in input order. Other local tool material need not form
35/// complete exchanges. Result block identity remains the responsibility of
36/// [`super::Context::apply`].
37pub fn validate_tool_result_append(
38    context_blocks: &[ContextBlock],
39    results: &[(BlockId, ToolResultPayload)],
40) -> Result<(), ToolResultError> {
41    let declarations = context_blocks
42        .iter()
43        .filter_map(|block| {
44            matches!(block.content(), BlockContent::ToolCall(_)).then_some(block.id())
45        })
46        .collect::<HashSet<_>>();
47    let completed = context_blocks
48        .iter()
49        .filter_map(|block| match block.content() {
50            BlockContent::ToolResult(result) => Some(result.call_block_id),
51            _ => None,
52        })
53        .collect::<HashSet<_>>();
54    let mut batch = HashSet::with_capacity(results.len());
55    for (_, result) in results {
56        let call_block_id = result.call_block_id;
57        if !declarations.contains(&call_block_id) {
58            return Err(ToolResultError::MissingDeclaration { call_block_id });
59        }
60        if completed.contains(&call_block_id) {
61            return Err(ToolResultError::AlreadyCompleted { call_block_id });
62        }
63        if !batch.insert(call_block_id) {
64            return Err(ToolResultError::DuplicateResult { call_block_id });
65        }
66    }
67    Ok(())
68}