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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
//! Agent session and conversation history management.
//!
//! Re-exports persistence types from [`super::session_store`] so `crate::agent::session::*`
//! remains stable.
pub use super::session_store::*;
use super::{fence_external_system_messages_for_resume, Message, PawanAgent, Role};
use crate::config::PawanConfig;
use crate::tools::ToolDefinition;
use crate::Result;
impl PawanAgent {
pub fn history(&self) -> &[Message] {
&self.history
}
/// Save current conversation as a session, returns session ID
pub fn save_session(&self) -> Result<String> {
let mut session = Session::new(&self.config.model);
session.messages = self.history.clone();
session.total_tokens = self.context_tokens_estimate as u64;
session.save()?;
Ok(session.id)
}
/// Resume a saved session by ID
pub fn resume_session(&mut self, session_id: &str) -> Result<()> {
let session = Session::load(session_id)?;
self.history = session.messages;
self.context_tokens_estimate = session.total_tokens as usize;
// Adopt the loaded session's id so eruka writes cluster under the
// same key as the on-disk session.
self.session_id = session_id.to_string();
fence_external_system_messages_for_resume(&mut self.history);
Ok(())
}
/// Archive the current conversation to Eruka's context store. Safe to
/// call from any async context; returns Ok even when eruka is disabled
/// or unreachable so callers can fire-and-forget after save_session().
pub async fn archive_to_eruka(&self) -> Result<()> {
let Some(eruka) = &self.eruka else {
return Ok(());
};
let mut session = Session::new(&self.config.model);
session.id = self.session_id.clone();
session.messages = self.history.clone();
session.total_tokens = self.context_tokens_estimate as u64;
eruka.archive_session(&session).await
}
/// Build a compact snapshot of the current history for on_pre_compress.
/// Keeps message role + first 200 chars per entry so the eruka write
/// stays bounded even with huge histories.
pub(crate) fn history_snapshot_for_eruka(history: &[Message]) -> String {
let mut out = String::with_capacity(2048);
for msg in history {
let prefix = match msg.role {
Role::User => "U: ",
Role::Assistant => "A: ",
Role::Tool => "T: ",
Role::System => "S: ",
};
let body: String = msg.content.chars().take(200).collect();
out.push_str(prefix);
out.push_str(&body);
out.push('\n');
if out.len() > 4000 {
break;
}
}
out
}
/// Get the configuration
pub fn config(&self) -> &PawanConfig {
&self.config
}
/// Clear the conversation history
pub fn clear_history(&mut self) {
self.history.clear();
}
/// Prune conversation history to reduce context size.
/// Uses importance scoring (inspired by claude-code-rust's consolidation engine):
/// - Tool results with errors: high importance (learning from failures)
/// - User messages: medium importance (intent context)
/// - Successful tool results: low importance (can be re-derived)
///
/// Keeps system prompt + last 4 messages, summarizes the rest.
pub(crate) fn prune_history(&mut self) {
let len = self.history.len();
if len <= 5 {
return; // Nothing to prune
}
let keep_end = 4;
let start = 1; // Skip system prompt at index 0
let end = len - keep_end;
let pruned_count = end - start;
// Score messages by importance for summary prioritization
let mut scored: Vec<(f32, &Message)> = self.history[start..end]
.iter()
.map(|msg| {
let score = Self::message_importance(msg);
(score, msg)
})
.collect();
scored.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
// Build summary from highest-importance messages first (UTF-8 safe)
let mut summary = String::with_capacity(2048);
for (score, msg) in &scored {
let prefix = match msg.role {
Role::User => "User: ",
Role::Assistant => "Assistant: ",
Role::Tool => {
if *score > 0.7 {
"Tool error: "
} else {
"Tool: "
}
}
Role::System => "System: ",
};
let chunk: String = msg.content.chars().take(200).collect();
summary.push_str(prefix);
summary.push_str(&chunk);
summary.push('\n');
if summary.len() > 2000 {
let safe_end = summary
.char_indices()
.take_while(|(i, _)| *i <= 2000)
.last()
.map(|(i, c)| i + c.len_utf8())
.unwrap_or(0);
summary.truncate(safe_end);
break;
}
}
let summary_msg = Message {
role: Role::System,
content: format!(
"Previous conversation summary (pruned {} messages, importance-ranked): {}",
pruned_count, summary
),
tool_calls: vec![],
tool_result: None,
};
self.history.drain(start..end);
self.history.insert(start, summary_msg);
tracing::info!(
pruned = pruned_count,
context_estimate = self.context_tokens_estimate,
"Pruned messages from history (importance-ranked)"
);
}
/// Score a message's importance for pruning decisions (0.0-1.0).
/// Higher = more important = kept in summary.
pub(crate) fn message_importance(msg: &Message) -> f32 {
match msg.role {
Role::User => 0.6, // User intent is moderately important
Role::System => 0.3, // System messages are usually ephemeral
Role::Assistant => {
if msg.content.contains("error") || msg.content.contains("Error") {
0.8
} else {
0.4
}
}
Role::Tool => {
if let Some(ref result) = msg.tool_result {
if !result.success {
0.9
}
// Failed tools are very important (learning)
else {
0.2
} // Successful tools can be re-derived
} else {
0.3
}
}
}
}
/// Add a message to history
pub fn add_message(&mut self, message: Message) {
self.history.push(message);
}
/// Switch the LLM model at runtime. Recreates the backend with the new model.
pub fn switch_model(&mut self, model: &str) -> Result<()> {
self.config.model = model.to_string();
let system_prompt = self.config.get_system_prompt_checked()?;
self.backend = Self::create_backend(&self.config, &system_prompt);
tracing::info!(model = model, "Model switched at runtime");
Ok(())
}
/// Get the current model name
pub fn model_name(&self) -> &str {
&self.config.model
}
/// Stable session id for this agent (Eruka sync, persistence keys)
pub fn session_id(&self) -> &str {
&self.session_id
}
/// Get tool definitions for the LLM
pub fn get_tool_definitions(&self) -> Vec<ToolDefinition> {
self.tools.get_definitions()
}
}