1use std::fmt;
2use std::hash::Hasher;
3use std::str::FromStr;
4
5use rustc_hash::FxHasher;
6
7#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub enum SessionMessageKind {
10 UserPrompt,
12 AgentPrompt,
14 AssistantAnswer,
16 WorkflowNotice,
18}
19
20impl SessionMessageKind {
21 pub fn as_str(self) -> &'static str {
23 match self {
24 Self::UserPrompt => "user_prompt",
25 Self::AgentPrompt => "agent_prompt",
26 Self::AssistantAnswer => "assistant_answer",
27 Self::WorkflowNotice => "workflow_notice",
28 }
29 }
30
31 pub fn is_conversation_message(self) -> bool {
34 matches!(
35 self,
36 Self::UserPrompt | Self::AgentPrompt | Self::AssistantAnswer
37 )
38 }
39
40 pub fn is_prompt(self) -> bool {
42 matches!(self, Self::UserPrompt | Self::AgentPrompt)
43 }
44}
45
46impl fmt::Display for SessionMessageKind {
47 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
48 formatter.write_str(self.as_str())
49 }
50}
51
52impl FromStr for SessionMessageKind {
53 type Err = SessionMessageKindParseError;
54
55 fn from_str(value: &str) -> Result<Self, Self::Err> {
56 match value {
57 "user_prompt" => Ok(Self::UserPrompt),
58 "agent_prompt" => Ok(Self::AgentPrompt),
59 "assistant_answer" => Ok(Self::AssistantAnswer),
60 "workflow_notice" => Ok(Self::WorkflowNotice),
61 _ => Err(SessionMessageKindParseError {
62 value: value.to_string(),
63 }),
64 }
65 }
66}
67
68#[derive(Clone, Debug, Eq, PartialEq)]
70pub struct SessionMessageKindParseError {
71 value: String,
72}
73
74impl fmt::Display for SessionMessageKindParseError {
75 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
76 write!(formatter, "unknown session message kind `{}`", self.value)
77 }
78}
79
80impl std::error::Error for SessionMessageKindParseError {}
81
82#[derive(Clone, Debug, Eq, PartialEq)]
84pub struct SessionMessage {
85 pub content: String,
87 pub kind: SessionMessageKind,
89 pub position: i64,
91}
92
93impl SessionMessage {
94 pub fn new(position: i64, kind: SessionMessageKind, content: impl Into<String>) -> Self {
96 Self {
97 content: content.into(),
98 kind,
99 position,
100 }
101 }
102
103 pub fn conversation(position: i64, kind: SessionMessageKind, content: impl AsRef<str>) -> Self {
106 Self {
107 content: stored_message_content(kind, content.as_ref()),
108 kind,
109 position,
110 }
111 }
112
113 fn append_display_text(&self, output: &mut String) {
115 match self.kind {
116 SessionMessageKind::UserPrompt | SessionMessageKind::AgentPrompt => {
117 Self::append_user_prompt_display_text(output, &self.content);
118 }
119 SessionMessageKind::AssistantAnswer => {
120 Self::append_assistant_answer_display_text(output, &self.content);
121 }
122 SessionMessageKind::WorkflowNotice => output.push_str(&self.content),
123 }
124 }
125
126 fn append_user_prompt_display_text(output: &mut String, content: &str) {
129 let content = normalized_user_prompt_content(content);
130 if content.trim().is_empty() {
131 return;
132 }
133
134 if !output.is_empty() {
135 output.push('\n');
136 }
137
138 let is_clarification_prompt = content
139 .lines()
140 .next()
141 .is_some_and(|line| line.trim() == CLARIFICATION_HEADER);
142
143 for (line_index, prompt_line) in content.split('\n').enumerate() {
144 if is_clarification_prompt
145 && line_index > 0
146 && Self::is_clarification_question_line(prompt_line)
147 {
148 output.push_str(USER_PROMPT_CONTINUATION_PREFIX);
149 output.push('\n');
150 }
151
152 if line_index == 0 {
153 output.push_str(USER_PROMPT_PREFIX);
154 } else {
155 output.push_str(USER_PROMPT_CONTINUATION_PREFIX);
156 }
157
158 output.push_str(prompt_line);
159 output.push('\n');
160 }
161
162 output.push('\n');
163 }
164
165 fn is_clarification_question_line(line: &str) -> bool {
168 let trimmed_line = line.trim_start();
169 let digit_count = trimmed_line
170 .chars()
171 .take_while(char::is_ascii_digit)
172 .count();
173 if digit_count == 0 {
174 return false;
175 }
176
177 let (_, suffix) = trimmed_line.split_at(digit_count);
178
179 suffix.starts_with(". Q: ")
180 }
181
182 fn append_assistant_answer_display_text(output: &mut String, content: &str) {
184 let content = content.trim();
185 if content.is_empty() {
186 return;
187 }
188
189 output.push_str(content);
190 output.push_str("\n\n");
191 }
192}
193
194#[derive(Clone, Debug, Default, Eq, PartialEq)]
196pub struct SessionTranscript {
197 content_hash: u64,
198 messages: Vec<SessionMessage>,
199 total_content_len: usize,
200}
201
202impl SessionTranscript {
203 pub fn new(mut messages: Vec<SessionMessage>) -> Self {
205 messages.sort_by_key(|message| message.position);
206
207 let content_hash = Self::content_hash_for_messages(&messages);
208 let total_content_len = messages.iter().map(|message| message.content.len()).sum();
209
210 Self {
211 content_hash,
212 messages,
213 total_content_len,
214 }
215 }
216
217 pub fn is_empty(&self) -> bool {
219 self.messages.is_empty()
220 }
221
222 pub fn messages(&self) -> &[SessionMessage] {
224 &self.messages
225 }
226
227 pub fn content_hash(&self) -> u64 {
229 self.content_hash
230 }
231
232 pub fn total_content_len(&self) -> usize {
234 self.total_content_len
235 }
236
237 pub fn append_message(&mut self, kind: SessionMessageKind, content: &str) {
244 let content = stored_message_content(kind, content);
245 if content.trim().is_empty() {
246 return;
247 }
248
249 let position = self
250 .messages
251 .last()
252 .map_or(0, |message| message.position.saturating_add(1));
253 self.total_content_len = self.total_content_len.saturating_add(content.len());
254 self.messages
255 .push(SessionMessage::new(position, kind, content));
256 self.content_hash = Self::content_hash_for_messages(&self.messages);
257 }
258
259 pub fn replay_text(&self) -> Option<String> {
264 let output = Self::display_text_for_messages(&self.messages);
265 if output.trim().is_empty() {
266 return None;
267 }
268
269 Some(output)
270 }
271
272 pub fn conversation_replay_text(&self) -> Option<String> {
275 let mut output = String::new();
276
277 for message in self
278 .messages
279 .iter()
280 .filter(|message| message.kind.is_conversation_message())
281 {
282 message.append_display_text(&mut output);
283 }
284
285 if output.trim().is_empty() {
286 return None;
287 }
288
289 Some(output)
290 }
291
292 pub fn display_text_for_messages(messages: &[SessionMessage]) -> String {
299 let mut output = String::new();
300
301 for message in messages {
302 message.append_display_text(&mut output);
303 }
304
305 output
306 }
307
308 fn content_hash_for_messages(messages: &[SessionMessage]) -> u64 {
312 let mut hasher = FxHasher::default();
313
314 for message in messages {
315 hasher.write_i64(message.position);
316 hasher.write(message.kind.as_str().as_bytes());
317 hasher.write_u8(0xff);
318 hasher.write(message.content.as_bytes());
319 hasher.write_u8(0xfe);
320 }
321
322 hasher.finish()
323 }
324}
325
326pub fn stored_message_content(kind: SessionMessageKind, content: &str) -> String {
333 match kind {
334 SessionMessageKind::UserPrompt | SessionMessageKind::AgentPrompt => {
335 normalized_user_prompt_content(content)
336 }
337 SessionMessageKind::AssistantAnswer => normalized_message_content(content),
338 SessionMessageKind::WorkflowNotice => content.to_string(),
339 }
340}
341
342pub fn normalized_message_content(content: &str) -> String {
344 content.trim().to_string()
345}
346
347const CLARIFICATION_HEADER: &str = "Clarifications:";
348const USER_PROMPT_CONTINUATION_PREFIX: &str = " ";
349const USER_PROMPT_PREFIX: &str = " › ";
350
351fn normalized_user_prompt_content(content: &str) -> String {
354 content
355 .trim_end()
356 .trim_start_matches(['\r', '\n'])
357 .to_string()
358}
359
360#[cfg(test)]
361#[path = "message_test.rs"]
362mod tests;