aither_agent/
transcript.rs1use std::fmt::Write;
13use std::path::{Path, PathBuf};
14
15use aither_core::llm::ToolResult;
16use async_fs::OpenOptions;
17use futures_lite::AsyncWriteExt;
18
19#[derive(Debug, Clone)]
21pub struct Transcript {
22 path: PathBuf,
23}
24
25impl Transcript {
26 #[must_use]
28 pub fn new(path: impl Into<PathBuf>) -> Self {
29 Self { path: path.into() }
30 }
31
32 #[must_use]
34 pub fn path(&self) -> &Path {
35 &self.path
36 }
37
38 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 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 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 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 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}