Skip to main content

aither_agent/
transcript.rs

1//! Readable transcript for LLM context recovery.
2//!
3//! A clean, append-only markdown file placed in the agent's sandbox so it can
4//! read its own history after compaction. Contains the conversational flow
5//! (user messages, assistant text, tool invocations with brief results) but
6//! omits internal details (reasoning tokens, signatures, model metadata).
7//!
8//! When compaction occurs a short marker is written -- no summary is included
9//! so the model knows information was lost and will actively recover from
10//! files or by re-reading the transcript.
11
12use std::fmt::Write;
13use std::path::{Path, PathBuf};
14
15use aither_core::llm::ToolResult;
16use async_fs::OpenOptions;
17use futures_lite::AsyncWriteExt;
18
19/// Append-only writer for the readable transcript.
20#[derive(Debug, Clone)]
21pub struct Transcript {
22    path: PathBuf,
23}
24
25impl Transcript {
26    /// Creates a transcript that appends to `path`.
27    #[must_use]
28    pub fn new(path: impl Into<PathBuf>) -> Self {
29        Self { path: path.into() }
30    }
31
32    /// The file this transcript is written to.
33    #[must_use]
34    pub fn path(&self) -> &Path {
35        &self.path
36    }
37
38    /// Appends a user turn.
39    pub async fn write_user_message(&self, content: &str) {
40        let mut block = String::new();
41        let _ = writeln!(block, "\n## User\n");
42        let _ = writeln!(block, "{content}\n");
43        self.append(&block).await;
44    }
45
46    /// Appends an assistant turn. Empty content is skipped.
47    pub async fn write_assistant_text(&self, content: &str) {
48        if content.is_empty() {
49            return;
50        }
51        let mut block = String::new();
52        let _ = writeln!(block, "\n## Assistant\n");
53        let _ = writeln!(block, "{content}\n");
54        self.append(&block).await;
55    }
56
57    /// Appends the command a tool was invoked with.
58    pub async fn write_tool_call(&self, name: &str, command: &str) {
59        let mut block = String::new();
60        let _ = writeln!(block, "\n### Tool: {name}\n");
61        let _ = writeln!(block, "```");
62        let _ = writeln!(block, "{command}");
63        let _ = writeln!(block, "```\n");
64        self.append(&block).await;
65    }
66
67    /// Append a tool result block.
68    pub async fn write_tool_result(&self, name: &str, result: &ToolResult) {
69        let mut block = String::new();
70        let rendered = result
71            .render_for_cli()
72            .unwrap_or_else(|error| format!("failed to render tool result: {error}"));
73        let truncated = truncate_lines(&rendered, 200);
74        if result.is_error() {
75            let _ = writeln!(block, "-> {name} (error): {truncated}\n");
76        } else {
77            let _ = writeln!(block, "-> {name}: {truncated}\n");
78        }
79        self.append(&block).await;
80    }
81
82    /// Marker written on compaction. Deliberately excludes the summary so the
83    /// model knows context was lost and should recover from files.
84    pub async fn write_compact_marker(&self) {
85        let marker = "\n---\n\n*[Context was compacted here. Earlier messages were summarized and removed. Details may be missing -- recover from files or re-read this transcript if needed.]*\n\n---\n\n";
86        self.append(marker).await;
87    }
88
89    async fn append(&self, content: &str) {
90        let result = OpenOptions::new()
91            .create(true)
92            .append(true)
93            .open(&self.path)
94            .await;
95
96        match result {
97            Ok(mut file) => {
98                if let Err(e) = file.write_all(content.as_bytes()).await {
99                    tracing::warn!("Failed to append to transcript: {}", e);
100                }
101            }
102            Err(e) => {
103                tracing::warn!("Failed to open transcript for append: {}", e);
104            }
105        }
106    }
107}
108
109fn truncate_lines(s: &str, max_lines: usize) -> String {
110    let lines: Vec<&str> = s.lines().collect();
111    if lines.len() <= max_lines {
112        return s.to_string();
113    }
114    let kept: Vec<&str> = lines[..max_lines].to_vec();
115    let omitted = lines.len() - max_lines;
116    format!("{}\n... ({omitted} lines omitted)", kept.join("\n"))
117}