Skip to content

Commit 20ec769

Browse files
committed
Add summarization feature
1 parent 6e8f35f commit 20ec769

4 files changed

Lines changed: 421 additions & 0 deletions

File tree

src/agent.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ use context::build_messages;
1717
pub mod context;
1818
pub mod session;
1919
pub mod subagent_manager;
20+
pub mod summarize;
2021

2122
const MAX_ITERATIONS: u32 = 20;
2223

@@ -163,6 +164,15 @@ pub async fn process_message(
163164
tool_ctx: &ToolCtx,
164165
) -> Result<String, AgentError> {
165166
let mut session = Session::load(workspace_path, chat_id).await?;
167+
168+
// Check if summarization is needed (before building context so summary is included)
169+
if session.history().len() > summarize::SUMMARIZE_THRESHOLD {
170+
if let Err(e) = summarize::summarize_if_needed(llm, &mut session, model).await {
171+
eprintln!("Warning: summarization failed: {}", e);
172+
// Continue anyway — summarization is optimization
173+
}
174+
}
175+
166176
let skills_summary = skills::build_skills_summary(workspace_path)?;
167177
let tool_summaries = registry.summaries();
168178

src/agent/session.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,14 @@ impl Session {
132132
pub fn set_summary(&mut self, s: String) {
133133
self.summary = s;
134134
}
135+
136+
/// Truncate history to last `keep` messages. Does nothing if history.len() <= keep.
137+
pub fn truncate_history(&mut self, keep: usize) {
138+
if self.history.len() > keep {
139+
let start = self.history.len() - keep;
140+
self.history.drain(..start);
141+
}
142+
}
135143
}
136144

137145
#[cfg(test)]
@@ -214,4 +222,31 @@ mod tests {
214222
assert!(session.history().first().map(|m| m.content.as_str()) == Some("msg 5"));
215223
let _ = std::fs::remove_dir_all(&w);
216224
}
225+
226+
#[test]
227+
fn session_truncate_history() {
228+
let w = temp_session_dir("truncate");
229+
let path = workspace::session_file(&w, "truncate");
230+
let mut session = Session {
231+
history: Vec::new(),
232+
summary: String::new(),
233+
path,
234+
};
235+
236+
// Add 10 messages
237+
for i in 0..10 {
238+
session.add_user_message(&format!("msg {}", i));
239+
}
240+
assert_eq!(session.history().len(), 10);
241+
242+
// Truncate to last 4
243+
session.truncate_history(4);
244+
assert_eq!(session.history().len(), 4);
245+
assert_eq!(session.history()[0].content, "msg 6");
246+
assert_eq!(session.history()[3].content, "msg 9");
247+
248+
// Truncate when already shorter - should do nothing
249+
session.truncate_history(10);
250+
assert_eq!(session.history().len(), 4);
251+
}
217252
}

0 commit comments

Comments
 (0)