Skip to main content

aither_agent/context/
prefix.rs

1//! The hash chain of a request's prompt prefix.
2//!
3//! A provider's prompt cache serves the longest prefix of a request it has
4//! seen before. When a request reads less from cache than the previous one
5//! had cached, the question is *where* the prefix changed — the tool
6//! definitions, the system prompt, or a message in the conversation. A
7//! [`PrefixChain`] answers it: one link per block, in the order providers
8//! cache them, each link hashing every block up to and including its own.
9//! Two chains agree on a link exactly when they agree on everything before
10//! it, so the first differing link names the first changed block.
11//!
12//! The links are SHA-256 based so a host can persist a chain and compare it
13//! against a request made by a later build of the program.
14
15use std::io;
16
17use aither_core::llm::tool::ToolDefinition;
18use aither_core::llm::{Message, Role};
19use sha2::{Digest, Sha256};
20
21/// One block of a request's prompt prefix.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
23pub enum PrefixBlock {
24    /// The tool definitions, which providers cache ahead of everything else.
25    Tools,
26    /// A message of the request.
27    Message {
28        /// Position of the message in the request.
29        index: usize,
30        /// Who the message is from.
31        role: Role,
32    },
33}
34
35/// The hash chain of one request's prompt prefix.
36#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
37pub struct PrefixChain {
38    /// The block each link ends with.
39    blocks: Vec<PrefixBlock>,
40    /// The cumulative hash of every block up to and including the same index.
41    links: Vec<u64>,
42    /// How many leading blocks the request asks the provider to cache: all
43    /// but the live tail, which is rebuilt for every request.
44    cached: usize,
45}
46
47impl PrefixChain {
48    /// The chain of a request carrying `definitions` and `messages`.
49    ///
50    /// # Panics
51    ///
52    /// Panics when a message or tool definition cannot be serialized, which
53    /// would mean the request itself cannot be sent.
54    #[must_use]
55    pub fn of(definitions: &[ToolDefinition], messages: &[Message]) -> Self {
56        let mut hasher = HashWriter(Sha256::new());
57        let mut blocks = Vec::with_capacity(messages.len() + 1);
58        let mut links = Vec::with_capacity(messages.len() + 1);
59        serde_json::to_writer(&mut hasher, definitions).expect("tool definitions serialize");
60        blocks.push(PrefixBlock::Tools);
61        links.push(hasher.link());
62        for (index, message) in messages.iter().enumerate() {
63            serde_json::to_writer(&mut hasher, message).expect("messages serialize");
64            blocks.push(PrefixBlock::Message {
65                index,
66                role: message.role(),
67            });
68            links.push(hasher.link());
69        }
70        let cached = 1 + super::cache::stable_conversation_end(messages).map_or(0, |end| end + 1);
71        Self {
72            blocks,
73            links,
74            cached,
75        }
76    }
77
78    /// The first block of `previous`'s cached prefix that this request does
79    /// not repeat byte for byte, or `None` when it repeats all of it.
80    ///
81    /// A block this request no longer has at all counts as changed.
82    #[must_use]
83    pub fn first_divergence(&self, previous: &Self) -> Option<PrefixBlock> {
84        (0..previous.cached)
85            .find(|&index| self.links.get(index) != previous.links.get(index))
86            .map(|index| {
87                self.blocks
88                    .get(index)
89                    .copied()
90                    .unwrap_or(previous.blocks[index])
91            })
92    }
93
94    /// The number of blocks in the chain, the tool definitions included.
95    #[must_use]
96    pub const fn len(&self) -> usize {
97        self.links.len()
98    }
99
100    /// Whether the chain has no blocks; never true for a chain built by
101    /// [`PrefixChain::of`], which always has the tool definitions block.
102    #[must_use]
103    pub const fn is_empty(&self) -> bool {
104        self.links.is_empty()
105    }
106
107    /// How many leading blocks the request asks the provider to cache.
108    #[must_use]
109    pub const fn cached_blocks(&self) -> usize {
110        self.cached
111    }
112}
113
114/// What rewrote the prompt prefix since the agent's previous request.
115#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
116pub struct PrefixRewrites {
117    /// A compaction replaced the conversation with its handoff.
118    pub compacted: bool,
119    /// The window was reassembled: staged system-block updates and
120    /// superseded tool results folded in, or alerts cleaned for recovery.
121    pub reassembled: bool,
122}
123
124/// The prompt prefix of a request about to be sent.
125#[derive(Debug, Clone, PartialEq, Eq)]
126#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
127pub struct PromptPrefix {
128    /// The hash chain of the request's prefix.
129    pub chain: PrefixChain,
130    /// What rewrote the prefix since this agent's previous request.
131    pub rewrites: PrefixRewrites,
132    /// Whether this is the agent's first request, so whatever the host sent
133    /// before it came from another agent.
134    pub first_request: bool,
135}
136
137/// Feeds serialized bytes straight into the hasher, without a buffer.
138struct HashWriter(Sha256);
139
140impl HashWriter {
141    /// The chain link for everything written so far.
142    fn link(&self) -> u64 {
143        let digest = self.0.clone().finalize();
144        let head = digest
145            .first_chunk::<8>()
146            .expect("a SHA-256 digest is 32 bytes");
147        u64::from_le_bytes(*head)
148    }
149}
150
151impl io::Write for HashWriter {
152    fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
153        self.0.update(bytes);
154        Ok(bytes.len())
155    }
156
157    fn flush(&mut self) -> io::Result<()> {
158        Ok(())
159    }
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165
166    fn conversation() -> Vec<Message> {
167        vec![
168            Message::system("prefix"),
169            Message::user("hello"),
170            Message::assistant("hi"),
171            Message::system("live tail"),
172        ]
173    }
174
175    fn tool(name: &'static str) -> ToolDefinition {
176        ToolDefinition::from_parts(
177            name.into(),
178            "runs a command".into(),
179            serde_json::json!({"type": "object"}),
180        )
181        .expect("an object schema is valid")
182    }
183
184    #[test]
185    fn an_unchanged_prefix_with_a_new_tail_does_not_diverge() {
186        let tools = [tool("terminal")];
187        let first = PrefixChain::of(&tools, &conversation());
188        let mut next = conversation();
189        next.pop();
190        next.extend([Message::user("again"), Message::system("new tail")]);
191        let second = PrefixChain::of(&tools, &next);
192        assert_eq!(second.first_divergence(&first), None);
193        assert_eq!(
194            first.cached_blocks(),
195            4,
196            "tools plus every message but the tail"
197        );
198    }
199
200    #[test]
201    fn a_changed_tool_set_diverges_at_the_tools() {
202        let first = PrefixChain::of(&[tool("terminal")], &conversation());
203        let second = PrefixChain::of(&[tool("terminal"), tool("monitor")], &conversation());
204        assert_eq!(second.first_divergence(&first), Some(PrefixBlock::Tools));
205    }
206
207    #[test]
208    fn a_changed_message_names_its_index_and_role() {
209        let tools = [tool("terminal")];
210        let first = PrefixChain::of(&tools, &conversation());
211        let mut edited = conversation();
212        edited[1] = Message::user("hello there");
213        let second = PrefixChain::of(&tools, &edited);
214        assert_eq!(
215            second.first_divergence(&first),
216            Some(PrefixBlock::Message {
217                index: 1,
218                role: Role::User
219            })
220        );
221    }
222
223    #[test]
224    fn a_shorter_request_diverges_at_the_first_missing_block() {
225        let tools = [tool("terminal")];
226        let first = PrefixChain::of(&tools, &conversation());
227        let second = PrefixChain::of(&tools, &[Message::system("prefix")]);
228        assert_eq!(
229            second.first_divergence(&first),
230            Some(PrefixBlock::Message {
231                index: 1,
232                role: Role::User
233            })
234        );
235    }
236
237    #[test]
238    fn a_chain_survives_serialization() {
239        let chain = PrefixChain::of(&[tool("terminal")], &conversation());
240        let text = serde_json::to_string(&chain).expect("serializes");
241        let back: PrefixChain = serde_json::from_str(&text).expect("deserializes");
242        assert_eq!(back, chain);
243        assert_eq!(back.len(), 5);
244    }
245}