aither_agent/context/
prefix.rs1use std::io;
16
17use aither_core::llm::tool::ToolDefinition;
18use aither_core::llm::{Message, Role};
19use sha2::{Digest, Sha256};
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
23pub enum PrefixBlock {
24 Tools,
26 Message {
28 index: usize,
30 role: Role,
32 },
33}
34
35#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
37pub struct PrefixChain {
38 blocks: Vec<PrefixBlock>,
40 links: Vec<u64>,
42 cached: usize,
45}
46
47impl PrefixChain {
48 #[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 #[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 #[must_use]
96 pub const fn len(&self) -> usize {
97 self.links.len()
98 }
99
100 #[must_use]
103 pub const fn is_empty(&self) -> bool {
104 self.links.is_empty()
105 }
106
107 #[must_use]
109 pub const fn cached_blocks(&self) -> usize {
110 self.cached
111 }
112}
113
114#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
116pub struct PrefixRewrites {
117 pub compacted: bool,
119 pub reassembled: bool,
122}
123
124#[derive(Debug, Clone, PartialEq, Eq)]
126#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
127pub struct PromptPrefix {
128 pub chain: PrefixChain,
130 pub rewrites: PrefixRewrites,
132 pub first_request: bool,
135}
136
137struct HashWriter(Sha256);
139
140impl HashWriter {
141 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}