Skip to main content

llm/
context.rs

1use serde::{Deserialize, Serialize};
2
3use crate::model_settings::ModelSettings;
4use crate::reasoning::ReasoningEffort;
5use crate::types::IsoString;
6
7use super::{ChatMessage, MessageId, ToolDefinition};
8
9#[doc = include_str!("docs/context.md")]
10#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct Context {
12    messages: Vec<ChatMessage>,
13    tools: Vec<ToolDefinition>,
14    #[serde(skip)]
15    reasoning_effort: ReasoningEffort,
16    #[serde(skip)]
17    model_settings: ModelSettings,
18    #[serde(skip)]
19    prompt_cache_key: Option<String>,
20    #[serde(skip)]
21    session_affinity_key: Option<String>,
22}
23
24impl Context {
25    pub fn new(messages: Vec<ChatMessage>, tools: Vec<ToolDefinition>) -> Self {
26        Self {
27            messages,
28            tools,
29            reasoning_effort: ReasoningEffort::Default,
30            model_settings: ModelSettings::default(),
31            prompt_cache_key: None,
32            session_affinity_key: None,
33        }
34    }
35
36    pub fn prompt_cache_key(&self) -> Option<&str> {
37        self.prompt_cache_key.as_deref()
38    }
39
40    pub fn set_prompt_cache_key(&mut self, key: Option<String>) {
41        self.prompt_cache_key = key;
42    }
43
44    pub fn session_affinity_key(&self) -> Option<&str> {
45        self.session_affinity_key.as_deref()
46    }
47
48    pub fn set_session_affinity_key(&mut self, key: Option<String>) {
49        self.session_affinity_key = key;
50    }
51
52    pub fn reasoning_effort(&self) -> ReasoningEffort {
53        self.reasoning_effort
54    }
55
56    pub fn set_reasoning_effort(&mut self, effort: ReasoningEffort) {
57        self.reasoning_effort = effort;
58    }
59
60    pub fn model_settings(&self) -> &ModelSettings {
61        &self.model_settings
62    }
63
64    pub fn set_model_settings(&mut self, settings: ModelSettings) {
65        self.model_settings = settings;
66    }
67
68    pub fn add_message(&mut self, message: ChatMessage) {
69        self.messages.push(message);
70    }
71
72    pub fn set_tools(&mut self, tools: Vec<ToolDefinition>) {
73        self.tools = tools;
74    }
75
76    pub fn set_system_content(&mut self, content: String) {
77        if let Some(ChatMessage::System { content: existing, .. }) = self.messages.first_mut() {
78            *existing = content;
79        } else {
80            self.messages.insert(0, ChatMessage::system(content));
81        }
82    }
83
84    pub fn system_content(&self) -> Option<&str> {
85        match self.messages.first() {
86            Some(ChatMessage::System { content, .. }) if !content.is_empty() => Some(content),
87            _ => None,
88        }
89    }
90
91    pub fn messages(&self) -> &Vec<ChatMessage> {
92        &self.messages
93    }
94
95    pub fn tools(&self) -> &Vec<ToolDefinition> {
96        &self.tools
97    }
98
99    /// Returns the number of messages in the context
100    pub fn message_count(&self) -> usize {
101        self.messages.len()
102    }
103
104    /// Estimate total token count using the ~4 bytes/token heuristic.
105    /// Includes messages and tool definitions. Used for pre-flight overflow detection.
106    pub fn estimated_token_count(&self) -> u32 {
107        let message_bytes: usize = self.messages.iter().map(ChatMessage::estimated_bytes).sum();
108        let tool_bytes: usize = self
109            .tools
110            .iter()
111            .map(|tool| tool.name.len() + tool.description.len() + tool.parameters.to_string().len())
112            .sum();
113        let total_bytes = message_bytes + tool_bytes;
114        u32::try_from(total_bytes / 4).unwrap_or(u32::MAX)
115    }
116
117    /// Clear all non-system messages, retaining only system prompts.
118    pub fn clear_conversation(&mut self) {
119        self.messages.retain(super::chat_message::ChatMessage::is_system);
120    }
121
122    /// Replace all non-system messages while preserving the system prompt and runtime state.
123    pub fn replace_conversation(&mut self, messages: Vec<ChatMessage>) {
124        self.messages = self
125            .messages
126            .drain(..)
127            .filter(ChatMessage::is_system)
128            .chain(messages.into_iter().filter(|m| !m.is_system()))
129            .collect();
130    }
131
132    /// Get all non-system messages for summarization
133    pub fn messages_for_summary(&self) -> Vec<&ChatMessage> {
134        self.messages.iter().filter(|msg| !msg.is_system()).collect()
135    }
136
137    /// Create a new context with all messages replaced by a summary.
138    /// Preserves the system prompt and tools.
139    pub fn with_compacted_summary(&self, message_id: MessageId, summary: &str) -> Context {
140        let system_messages: Vec<_> = self.messages.iter().filter(|msg| msg.is_system()).cloned().collect();
141
142        let non_system_count = self.messages.len() - system_messages.len();
143
144        let mut messages = system_messages;
145        if non_system_count > 0 {
146            messages.push(ChatMessage::Summary {
147                message_id,
148                content: summary.to_string(),
149                timestamp: IsoString::now(),
150                messages_compacted: non_system_count,
151            });
152        }
153
154        Context { messages, ..self.clone() }
155    }
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161
162    use crate::testing::assistant_message;
163    use crate::{AssistantContent, ToolCallResult};
164
165    fn create_test_context() -> Context {
166        let messages = vec![
167            ChatMessage::system("You are a helpful assistant."),
168            ChatMessage::user("Hello"),
169            assistant_message().text("Hi there!").build(),
170            ChatMessage::ToolCallResult(Ok(ToolCallResult {
171                id: "1".to_string(),
172                name: "tool1".to_string(),
173                arguments: "{}".to_string(),
174                result: "Result 1".to_string(),
175            })),
176            ChatMessage::ToolCallResult(Ok(ToolCallResult {
177                id: "2".to_string(),
178                name: "tool2".to_string(),
179                arguments: "{}".to_string(),
180                result: "Result 2".to_string(),
181            })),
182            ChatMessage::ToolCallResult(Ok(ToolCallResult {
183                id: "3".to_string(),
184                name: "tool3".to_string(),
185                arguments: "{}".to_string(),
186                result: "Result 3".to_string(),
187            })),
188        ];
189        Context::new(messages, vec![])
190    }
191
192    #[test]
193    fn replace_conversation_preserves_system_message() {
194        let mut ctx = create_test_context();
195        ctx.replace_conversation(vec![ChatMessage::user("new")]);
196
197        assert_eq!(ctx.message_count(), 2);
198        assert!(ctx.messages()[0].is_system());
199        assert!(matches!(ctx.messages()[1], ChatMessage::User { .. }));
200    }
201
202    #[test]
203    fn replace_conversation_replaces_old_non_system_messages() {
204        let mut ctx = create_test_context();
205        ctx.replace_conversation(vec![assistant_message().text("replacement").build()]);
206
207        assert_eq!(ctx.message_count(), 2);
208        assert!(
209            ctx.messages()
210                .iter()
211                .all(|message| { !matches!(message, ChatMessage::User { .. } | ChatMessage::ToolCallResult(_)) })
212        );
213        assert!(
214            matches!(&ctx.messages()[1], ChatMessage::Assistant { content, .. } if content.text() == "replacement")
215        );
216    }
217
218    #[test]
219    fn replace_conversation_filters_incoming_system_messages() {
220        let mut ctx = create_test_context();
221        ctx.replace_conversation(vec![ChatMessage::system("wrong system"), ChatMessage::user("kept")]);
222
223        assert_eq!(ctx.message_count(), 2);
224        assert!(
225            matches!(ctx.messages()[0], ChatMessage::System { ref content, .. } if content == "You are a helpful assistant.")
226        );
227        assert!(matches!(ctx.messages()[1], ChatMessage::User { .. }));
228    }
229
230    #[test]
231    fn replace_conversation_does_not_change_tools() {
232        let tool = ToolDefinition::new("read_file", "Reads a file", serde_json::json!({}));
233        let mut ctx = Context::new(vec![ChatMessage::system("system")], vec![tool.clone()]);
234        ctx.replace_conversation(vec![ChatMessage::user("new")]);
235
236        assert_eq!(ctx.tools(), &vec![tool]);
237    }
238
239    #[test]
240    fn test_message_count() {
241        let ctx = create_test_context();
242        assert_eq!(ctx.message_count(), 6);
243    }
244
245    #[test]
246    fn test_with_compacted_summary_preserves_system_prompt() {
247        let ctx = create_test_context();
248        let compacted = ctx.with_compacted_summary(MessageId::new(), "This is a summary of previous conversation.");
249
250        assert_eq!(compacted.message_count(), 2);
251        assert!(compacted.messages()[0].is_system());
252        assert!(compacted.messages()[1].is_summary());
253    }
254
255    #[test]
256    fn test_with_compacted_summary_empty_context() {
257        let ctx = Context::new(vec![ChatMessage::system("System")], vec![]);
258        let compacted = ctx.with_compacted_summary(MessageId::new(), "Summary");
259
260        assert_eq!(compacted.message_count(), 1);
261    }
262
263    #[test]
264    fn test_messages_for_summary() {
265        let ctx = create_test_context();
266        let msgs = ctx.messages_for_summary();
267
268        assert_eq!(msgs.len(), 5);
269        assert!(msgs.iter().all(|m| !m.is_system()));
270    }
271
272    #[test]
273    fn test_prompt_cache_key_default_is_none() {
274        let ctx = create_test_context();
275        assert_eq!(ctx.prompt_cache_key(), None);
276    }
277
278    #[test]
279    fn test_prompt_cache_key_set_and_get() {
280        let mut ctx = create_test_context();
281        ctx.set_prompt_cache_key(Some("session-123".to_string()));
282        assert_eq!(ctx.prompt_cache_key(), Some("session-123"));
283
284        ctx.set_prompt_cache_key(None);
285        assert_eq!(ctx.prompt_cache_key(), None);
286    }
287
288    #[test]
289    fn test_prompt_cache_key_preserved_through_compaction() {
290        let mut ctx = create_test_context();
291        ctx.set_prompt_cache_key(Some("session-abc".to_string()));
292        let compacted = ctx.with_compacted_summary(MessageId::new(), "Summary");
293        assert_eq!(compacted.prompt_cache_key(), Some("session-abc"));
294    }
295
296    #[test]
297    fn session_affinity_key_is_runtime_metadata_preserved_by_compaction() {
298        let mut context = create_test_context();
299        assert_eq!(context.session_affinity_key(), None);
300
301        context.set_session_affinity_key(Some("conversation-123".to_string()));
302
303        assert_eq!(context.session_affinity_key(), Some("conversation-123"));
304        assert_eq!(
305            context.with_compacted_summary(MessageId::new(), "Summary").session_affinity_key(),
306            Some("conversation-123")
307        );
308    }
309
310    #[test]
311    fn test_reasoning_effort_initializes_to_default() {
312        let ctx = create_test_context();
313        assert_eq!(ctx.reasoning_effort(), ReasoningEffort::Default);
314    }
315
316    #[test]
317    fn test_reasoning_effort_set_and_get() {
318        let mut ctx = create_test_context();
319        ctx.set_reasoning_effort(crate::ReasoningEffort::High);
320        assert_eq!(ctx.reasoning_effort(), crate::ReasoningEffort::High);
321
322        ctx.set_reasoning_effort(ReasoningEffort::Default);
323        assert_eq!(ctx.reasoning_effort(), ReasoningEffort::Default);
324    }
325
326    #[test]
327    fn test_reasoning_effort_preserved_through_compaction() {
328        let mut ctx = create_test_context();
329        ctx.set_reasoning_effort(crate::ReasoningEffort::Disabled);
330        let compacted = ctx.with_compacted_summary(MessageId::new(), "Summary");
331        assert_eq!(compacted.reasoning_effort(), crate::ReasoningEffort::Disabled);
332        assert_eq!(ctx.clone().reasoning_effort(), ReasoningEffort::Disabled);
333        ctx.replace_conversation(vec![]);
334        assert_eq!(ctx.reasoning_effort(), ReasoningEffort::Disabled);
335    }
336
337    #[test]
338    fn test_estimated_token_count() {
339        use crate::ToolDefinition;
340
341        // "You are a helpful assistant." = 28 bytes
342        // "Hello" = 5 bytes
343        // "Hi there!" = 9 bytes (assistant, no reasoning, no tool calls)
344        // 3 tool results: "Result 1" (8) + "tool1" (5) + "{}" (2) = 15 each = 45 total
345        // Total message bytes = 28 + 5 + 9 + 45 = 87
346        let ctx = create_test_context();
347        let base_estimate = ctx.estimated_token_count();
348
349        // With no tools, estimate = message_bytes / 4
350        assert_eq!(base_estimate, 87 / 4);
351
352        let tool = ToolDefinition::new("read_file", "Reads a file", serde_json::json!({}));
353        let ctx_with_tools = Context::new(ctx.messages().clone(), vec![tool]);
354        let with_tools_estimate = ctx_with_tools.estimated_token_count();
355        assert_eq!(with_tools_estimate, (87 + 9 + 12 + 2) / 4);
356        assert!(with_tools_estimate > base_estimate);
357    }
358
359    #[test]
360    fn compaction_drops_encrypted_reasoning() {
361        let ctx = Context::new(
362            vec![
363                ChatMessage::user("Hello"),
364                assistant_message()
365                    .model("anthropic:claude-opus-4-6")
366                    .reasoning("thinking")
367                    .encrypted_reasoning("r_test", "blob")
368                    .text("I see.")
369                    .build(),
370            ],
371            vec![],
372        );
373        let compacted = ctx.with_compacted_summary(MessageId::new(), "Summary of conversation");
374
375        assert!(compacted.messages().iter().all(|message| encrypted_reasoning(message).is_empty()));
376    }
377
378    fn encrypted_reasoning(message: &ChatMessage) -> Vec<&str> {
379        let ChatMessage::Assistant { content, .. } = message else { return vec![] };
380        content
381            .blocks()
382            .iter()
383            .filter_map(|block| match block {
384                AssistantContent::Reasoning { encrypted: Some(encrypted), .. } => Some(encrypted.content.as_str()),
385                _ => None,
386            })
387            .collect()
388    }
389}