use crate::llm::{ChatMessage, ChatResponse, ToolCall};
use crate::tools::USE_SKILL_TOOL_NAME;
use super::compaction::{CompactionConfig, should_compact, summarize_span};
#[derive(Debug, Clone)]
struct TranscriptEntry {
message: ChatMessage,
compacted: bool,
pinned: bool,
}
impl TranscriptEntry {
fn fresh(message: ChatMessage) -> Self {
Self {
message,
compacted: false,
pinned: false,
}
}
fn pinned(message: ChatMessage) -> Self {
Self {
message,
compacted: false,
pinned: true,
}
}
}
#[derive(Debug, Default, Clone)]
pub struct Transcript {
entries: Vec<TranscriptEntry>,
assistant_texts: Vec<String>,
compaction_triggered: bool,
}
impl Transcript {
pub fn seed(system: &str, task: &str) -> Self {
Self {
entries: vec![
TranscriptEntry::fresh(ChatMessage::system(system)),
TranscriptEntry::fresh(ChatMessage::user(task)),
],
assistant_texts: Vec::new(),
compaction_triggered: false,
}
}
pub fn push_assistant(&mut self, text: Option<String>, tool_calls: &[ToolCall]) {
if let Some(t) = &text
&& !t.is_empty()
{
self.assistant_texts.push(t.clone());
}
let tool_calls = if tool_calls.is_empty() {
None
} else {
Some(tool_calls.to_vec())
};
self.entries.push(TranscriptEntry::fresh(ChatMessage {
role: "assistant".into(),
content: text,
tool_calls,
tool_call_id: None,
name: None,
cache_control: None,
}));
}
pub fn push_tool_result(&mut self, tool_call_id: &str, name: &str, content: &str) {
let message = ChatMessage::tool_result(tool_call_id, name, content);
let entry = if name == USE_SKILL_TOOL_NAME {
TranscriptEntry::pinned(message)
} else {
TranscriptEntry::fresh(message)
};
self.entries.push(entry);
}
pub fn messages(&self) -> Vec<ChatMessage> {
self.entries.iter().map(|e| e.message.clone()).collect()
}
pub fn to_messages(&self) -> Vec<ChatMessage> {
let mut out = Vec::with_capacity(self.entries.len());
let mut compacted_span: Vec<ChatMessage> = Vec::new();
for entry in &self.entries {
if entry.compacted {
compacted_span.push(entry.message.clone());
continue;
}
flush_span(&mut out, &mut compacted_span);
out.push(entry.message.clone());
}
flush_span(&mut out, &mut compacted_span);
if self.compaction_triggered
&& let Some(last_user) = self.entries.iter().rev().find(|e| e.message.role == "user")
{
out.push(last_user.message.clone());
}
out
}
pub fn maybe_compact(&mut self, cfg: &CompactionConfig) -> bool {
if !should_compact(&self.to_messages(), cfg) {
return false;
}
let keep_from = self.entries.len().saturating_sub(cfg.keep_last_messages);
let mut newly_compacted = false;
for entry in &mut self.entries[..keep_from] {
if entry.compacted || entry.pinned {
continue;
}
if entry.message.role == "system" || entry.message.role == "user" {
continue;
}
entry.compacted = true;
newly_compacted = true;
}
if newly_compacted {
self.compaction_triggered = true;
}
newly_compacted
}
pub fn compacted_count(&self) -> usize {
self.entries.iter().filter(|e| e.compacted).count()
}
pub fn assistant_text(&self) -> String {
self.assistant_texts.join("\n\n")
}
pub fn push_response(&mut self, resp: &ChatResponse) {
let text = resp.first_text();
let calls = resp.first_tool_calls().to_vec();
self.push_assistant(text, &calls);
}
}
fn flush_span(out: &mut Vec<ChatMessage>, span: &mut Vec<ChatMessage>) {
if span.is_empty() {
return;
}
out.push(ChatMessage::system(summarize_span(span)));
span.clear();
}
#[cfg(test)]
mod tests {
use super::*;
use crate::llm::{FunctionCall, ToolCall};
fn sample_call(id: &str, name: &str) -> ToolCall {
ToolCall {
id: id.into(),
kind: "function".into(),
function: FunctionCall {
name: name.into(),
arguments: "{}".into(),
},
}
}
#[test]
fn seed_has_two_messages() {
let t = Transcript::seed("you are helpful", "do the thing");
assert_eq!(t.messages().len(), 2);
assert_eq!(t.messages()[0].role, "system");
assert_eq!(t.messages()[1].role, "user");
}
#[test]
fn push_assistant_records_text() {
let mut t = Transcript::seed("s", "u");
t.push_assistant(Some("hello".into()), &[]);
assert_eq!(t.assistant_text(), "hello");
assert_eq!(t.messages().last().expect("msg").role, "assistant");
}
#[test]
fn push_assistant_skips_empty_text() {
let mut t = Transcript::seed("s", "u");
t.push_assistant(Some(String::new()), &[sample_call("c1", "echo")]);
assert_eq!(t.assistant_text(), "");
}
#[test]
fn push_tool_result_sets_call_id() {
let mut t = Transcript::seed("s", "u");
t.push_tool_result("call_1", "echo", "echoed");
let messages = t.messages();
let last = messages.last().expect("msg");
assert_eq!(last.role, "tool");
assert_eq!(last.tool_call_id.as_deref(), Some("call_1"));
assert_eq!(last.name.as_deref(), Some("echo"));
}
#[test]
fn messages_reflects_appends() {
let mut t = Transcript::seed("s", "u");
t.push_assistant(None, &[sample_call("c1", "echo")]);
t.push_tool_result("c1", "echo", "ok");
assert_eq!(t.messages().len(), 4);
}
#[test]
fn assistant_text_joins_turns() {
let mut t = Transcript::seed("s", "u");
t.push_assistant(Some("first".into()), &[]);
t.push_assistant(Some("second".into()), &[]);
assert_eq!(t.assistant_text(), "first\n\nsecond");
}
#[test]
fn to_messages_is_passthrough_before_compaction() {
let mut t = Transcript::seed("s", "u");
t.push_assistant(Some("hi".into()), &[]);
assert_eq!(t.to_messages(), t.messages());
}
#[test]
fn maybe_compact_is_noop_below_threshold() {
let mut t = Transcript::seed("s", "u");
t.push_assistant(Some("hi".into()), &[]);
let cfg = CompactionConfig {
token_threshold: 10_000,
keep_last_messages: 1,
};
assert!(!t.maybe_compact(&cfg));
assert_eq!(t.compacted_count(), 0);
}
#[test]
fn maybe_compact_never_touches_system_or_user() {
let mut t = Transcript::seed("s", &"long task ".repeat(50));
for i in 0..10 {
t.push_assistant(Some(format!("assistant turn {i}")), &[]);
t.push_tool_result(&format!("c{i}"), "bash", "output");
}
let cfg = CompactionConfig {
token_threshold: 1,
keep_last_messages: 2,
};
assert!(t.maybe_compact(&cfg));
assert!(t.compacted_count() > 0);
let raw = t.messages();
assert_eq!(raw[0].role, "system");
assert_eq!(raw[1].role, "user");
assert_eq!(raw.len(), 2 + 20);
}
#[test]
fn maybe_compact_never_compacts_pinned_skill_output() {
let mut t = Transcript::seed("s", "task");
t.push_tool_result(
"call_skill",
USE_SKILL_TOOL_NAME,
"full skill body: do the distinctive thing",
);
for i in 0..10 {
t.push_assistant(Some(format!("turn {i}")), &[]);
t.push_tool_result(&format!("c{i}"), "bash", "output");
}
let cfg = CompactionConfig {
token_threshold: 1,
keep_last_messages: 2,
};
assert!(t.maybe_compact(&cfg));
let compacted_view = t.to_messages();
assert!(
compacted_view
.iter()
.any(|m| m.content.as_deref() == Some("full skill body: do the distinctive thing")),
"pinned skill output must survive verbatim in the compacted view: {compacted_view:?}"
);
}
#[test]
fn maybe_compact_still_compacts_non_skill_tool_results() {
let mut t = Transcript::seed("s", "task");
for i in 0..10 {
t.push_assistant(Some(format!("turn {i}")), &[]);
t.push_tool_result(&format!("c{i}"), "bash", "output");
}
let cfg = CompactionConfig {
token_threshold: 1,
keep_last_messages: 2,
};
assert!(t.maybe_compact(&cfg));
let compacted_view = t.to_messages();
assert!(compacted_view.len() < t.messages().len());
assert!(
compacted_view.iter().any(|m| m
.content
.as_deref()
.unwrap_or("")
.contains("[compacted")),
"expected non-skill tool results to still collapse into a summary: {compacted_view:?}"
);
}
#[test]
fn to_messages_collapses_compacted_span() {
let mut t = Transcript::seed("s", "task");
for i in 0..10 {
t.push_assistant(Some(format!("turn {i}")), &[]);
t.push_tool_result(&format!("c{i}"), "bash", "output");
}
let cfg = CompactionConfig {
token_threshold: 1,
keep_last_messages: 2,
};
assert!(t.maybe_compact(&cfg));
let compacted_view = t.to_messages();
assert!(compacted_view.len() < t.messages().len());
let has_summary = compacted_view
.iter()
.any(|m| m.content.as_deref().unwrap_or("").contains("[compacted"));
assert!(
has_summary,
"expected a summary message in {compacted_view:?}"
);
}
#[test]
fn to_messages_replays_last_user_message_after_compaction() {
let mut t = Transcript::seed("s", "the original task");
for i in 0..10 {
t.push_assistant(Some(format!("turn {i}")), &[]);
t.push_tool_result(&format!("c{i}"), "bash", "output");
}
let cfg = CompactionConfig {
token_threshold: 1,
keep_last_messages: 2,
};
assert!(t.maybe_compact(&cfg));
let compacted_view = t.to_messages();
let last = compacted_view.last().expect("non-empty view");
assert_eq!(last.role, "user");
assert_eq!(last.content.as_deref(), Some("the original task"));
}
#[test]
fn maybe_compact_is_noop_on_seed_only_transcript() {
let mut t = Transcript::seed("s", "u");
let cfg = CompactionConfig {
token_threshold: 0,
keep_last_messages: 100,
};
assert!(!t.maybe_compact(&cfg));
assert_eq!(t.compacted_count(), 0);
assert_eq!(t.to_messages(), t.messages());
}
#[test]
fn compacted_entries_remain_in_raw_history() {
let mut t = Transcript::seed("s", "task");
t.push_assistant(Some("distinctive-early-turn-text".into()), &[]);
for i in 0..10 {
t.push_assistant(Some(format!("turn {i}")), &[]);
t.push_tool_result(&format!("c{i}"), "bash", "output");
}
let cfg = CompactionConfig {
token_threshold: 1,
keep_last_messages: 2,
};
assert!(t.maybe_compact(&cfg));
assert!(t.compacted_count() > 0);
let raw = t.messages();
assert!(
raw.iter()
.any(|m| m.content.as_deref() == Some("distinctive-early-turn-text")),
"compacted entry's original content must survive in the raw history"
);
}
}