causa_kernel/context/material/
tool_results.rs1use crate::context::block::{BlockContent, ContextBlock};
4use crate::context::ids::BlockId;
5use crate::context::tool_data::ToolResultPayload;
6use std::collections::HashSet;
7
8#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
10#[non_exhaustive]
11pub enum ToolResultError {
12 #[error("missing tool declaration {call_block_id:?}")]
14 #[non_exhaustive]
15 MissingDeclaration {
16 call_block_id: BlockId,
18 },
19 #[error("tool declaration already completed: {call_block_id:?}")]
21 #[non_exhaustive]
22 AlreadyCompleted {
23 call_block_id: BlockId,
25 },
26 #[error("duplicate tool result for declaration {call_block_id:?}")]
28 #[non_exhaustive]
29 DuplicateResult {
30 call_block_id: BlockId,
32 },
33}
34
35pub fn validate_tool_result_append(
41 context_blocks: &[ContextBlock],
42 results: &[(BlockId, ToolResultPayload)],
43) -> Result<(), ToolResultError> {
44 let declarations = context_blocks
45 .iter()
46 .filter_map(|block| {
47 matches!(block.content(), BlockContent::ToolCall(_)).then_some(block.id())
48 })
49 .collect::<HashSet<_>>();
50 let completed = context_blocks
51 .iter()
52 .filter_map(|block| match block.content() {
53 BlockContent::ToolResult(result) => Some(result.call_block_id),
54 _ => None,
55 })
56 .collect::<HashSet<_>>();
57 let mut batch = HashSet::with_capacity(results.len());
58 for (_, result) in results {
59 let call_block_id = result.call_block_id;
60 if !declarations.contains(&call_block_id) {
61 return Err(ToolResultError::MissingDeclaration { call_block_id });
62 }
63 if completed.contains(&call_block_id) {
64 return Err(ToolResultError::AlreadyCompleted { call_block_id });
65 }
66 if !batch.insert(call_block_id) {
67 return Err(ToolResultError::DuplicateResult { call_block_id });
68 }
69 }
70 Ok(())
71}