1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
//! Conversation compaction: truncates large tool-result blocks in older
//! messages, and (when truncation alone is not enough) summarises the
//! pre-split prefix through a one-shot LLM call. Drives both the
//! automatic threshold check from [`Repl::process_message`] and the
//! explicit `/compact` command.
use crate::api::CreateMessageRequest;
use crate::error::{Result, SofosError};
use crate::repl::{ConversationHistory, Repl};
use crate::ui::UI;
use colored::Colorize;
use std::sync::Arc;
impl Repl {
/// Compact the conversation by truncating tool results and summarizing older messages.
/// Returns Ok(true) if compaction was performed, Ok(false) if skipped.
pub fn compact_conversation(&mut self, force: bool) -> Result<bool> {
if !force && !self.session_state.conversation.needs_compaction() {
return Ok(false);
}
let tokens_before = self.session_state.conversation.estimate_total_tokens();
// Phase 1: Truncate large tool results in older messages
let split_point = self.session_state.conversation.compaction_split_point();
if split_point == 0 {
if force {
println!("\n{}\n", "Not enough messages to compact.".bright_yellow());
}
return Ok(false);
}
self.session_state
.conversation
.truncate_tool_results(split_point);
if !force && !self.session_state.conversation.needs_compaction() {
let tokens_after = self.session_state.conversation.estimate_total_tokens();
println!(
"\n{} {} -> {} tokens (tool results truncated)\n",
"Compacted:".bright_green(),
tokens_before,
tokens_after
);
return Ok(true);
}
// Phase 2: Summarize older messages via the LLM
let older_messages: Vec<_> =
self.session_state.conversation.messages()[..split_point].to_vec();
let serialized = ConversationHistory::serialize_messages_for_summary(&older_messages);
let summary_system = vec![crate::api::SystemPrompt::new_cached_with_ttl(
"You are a conversation summarizer. Produce a detailed but concise summary of the following \
coding assistant conversation. Preserve:\n\
1. All file paths mentioned or modified\n\
2. Key decisions made and their rationale\n\
3. Current state of any ongoing task\n\
4. Any errors encountered and how they were resolved\n\n\
Format as structured sections. Do NOT include raw file contents or verbose tool output — \
just what was done and decided."
.to_string(),
None,
)];
let summary_request = CreateMessageRequest {
model: self.model_config.model.clone(),
max_tokens: 4096,
messages: vec![crate::api::Message::user(serialized)],
system: Some(summary_system),
tools: None,
stream: None,
thinking: None,
output_config: None,
reasoning: None,
// Use a distinct cache key for the summary call. The
// summarization system prompt and serialized-history user
// turn share nothing with regular turns, so reusing the
// session id would just thrash the OpenAI prompt-cache
// shard between the two prefixes.
prompt_cache_key: Some(format!("{}-summary", self.session_state.session_id)),
// The summarization call is itself a one-shot request, not
// a long-running conversation, so server-side compaction
// would be a no-op even on supported models.
context_management: None,
};
let interrupt_flag = Arc::clone(&self.interrupt_flag);
let client = self.client.clone();
let mut request_handle = self
.runtime
.spawn(async move { client.create_message(summary_request).await });
let response_result = self.runtime.block_on(async {
tokio::select! {
res = &mut request_handle => {
match res {
Ok(inner) => inner,
Err(e) => Err(SofosError::Join(format!("{}", e)))
}
}
_ = Self::wait_for_interrupt(Arc::clone(&interrupt_flag)) => {
request_handle.abort();
Err(SofosError::Interrupted)
}
}
});
match response_result {
Ok(response) => {
// Bill the summary call before the length gate; the
// tokens are spent regardless of whether the summary
// ends up being used or discarded by the fallback.
self.session_state.add_usage(&response.usage);
let summary_text: String = response
.content
.iter()
.filter_map(|block| {
if let crate::api::ContentBlock::Text { text } = block {
Some(text.as_str())
} else {
None
}
})
.collect::<Vec<_>>()
.join("\n");
if summary_text.len() < 50 {
UI::print_warning(
"Compaction produced an insufficient summary. Falling back to trimming.",
);
self.session_state.conversation.fallback_trim();
return Ok(false);
}
self.session_state
.conversation
.replace_with_summary(summary_text, split_point);
let tokens_after = self.session_state.conversation.estimate_total_tokens();
let saved_percent = if tokens_before > 0 {
// The summary can be longer than what it replaced
// on short histories. Saturate so the "saved" line
// reports 0% instead of underflowing the subtraction.
let shrunk = tokens_before.saturating_sub(tokens_after);
shrunk * 100 / tokens_before
} else {
0
};
println!(
"{} {} -> {} tokens (saved {}%)",
"Compacted:".bright_green(),
tokens_before,
tokens_after,
saved_percent
);
Ok(true)
}
Err(SofosError::Interrupted) => {
UI::print_warning("Compaction interrupted. Falling back to trimming.");
self.session_state.conversation.fallback_trim();
Ok(false)
}
Err(e) => {
UI::print_warning(&format!(
"Compaction failed: {}. Falling back to trimming.",
e
));
self.session_state.conversation.fallback_trim();
Ok(false)
}
}
}
pub fn handle_compact_command(&mut self) -> Result<()> {
self.compact_conversation(true)?;
Ok(())
}
}