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 ActivitySummary,
13 UserPrompt,
15 AgentPrompt,
17 AssistantAnswer,
19 WorkflowNotice,
21}
22
23impl SessionMessageKind {
24 pub fn as_str(self) -> &'static str {
26 match self {
27 Self::ActivitySummary => "activity_summary",
28 Self::UserPrompt => "user_prompt",
29 Self::AgentPrompt => "agent_prompt",
30 Self::AssistantAnswer => "assistant_answer",
31 Self::WorkflowNotice => "workflow_notice",
32 }
33 }
34
35 pub fn is_conversation_message(self) -> bool {
38 matches!(
39 self,
40 Self::UserPrompt | Self::AgentPrompt | Self::AssistantAnswer
41 )
42 }
43
44 pub fn is_prompt(self) -> bool {
46 matches!(self, Self::UserPrompt | Self::AgentPrompt)
47 }
48}
49
50impl fmt::Display for SessionMessageKind {
51 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
52 formatter.write_str(self.as_str())
53 }
54}
55
56impl FromStr for SessionMessageKind {
57 type Err = SessionMessageKindParseError;
58
59 fn from_str(value: &str) -> Result<Self, Self::Err> {
60 match value {
61 "activity_summary" => Ok(Self::ActivitySummary),
62 "user_prompt" => Ok(Self::UserPrompt),
63 "agent_prompt" => Ok(Self::AgentPrompt),
64 "assistant_answer" => Ok(Self::AssistantAnswer),
65 "workflow_notice" => Ok(Self::WorkflowNotice),
66 _ => Err(SessionMessageKindParseError {
67 value: value.to_string(),
68 }),
69 }
70 }
71}
72
73#[derive(Clone, Debug, Eq, PartialEq)]
75pub struct SessionMessageKindParseError {
76 value: String,
77}
78
79impl fmt::Display for SessionMessageKindParseError {
80 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
81 write!(formatter, "unknown session message kind `{}`", self.value)
82 }
83}
84
85impl std::error::Error for SessionMessageKindParseError {}
86
87#[derive(Clone, Debug, Eq, PartialEq)]
89pub struct SessionMessage {
90 pub content: String,
92 pub kind: SessionMessageKind,
94 pub position: i64,
96}
97
98impl SessionMessage {
99 pub fn new(position: i64, kind: SessionMessageKind, content: impl Into<String>) -> Self {
101 Self {
102 content: content.into(),
103 kind,
104 position,
105 }
106 }
107
108 pub fn conversation(position: i64, kind: SessionMessageKind, content: impl AsRef<str>) -> Self {
111 Self {
112 content: stored_message_content(kind, content.as_ref()),
113 kind,
114 position,
115 }
116 }
117
118 fn append_display_text(&self, output: &mut String) {
120 match self.kind {
121 SessionMessageKind::ActivitySummary => {}
122 SessionMessageKind::UserPrompt | SessionMessageKind::AgentPrompt => {
123 Self::append_user_prompt_display_text(output, &self.content);
124 }
125 SessionMessageKind::AssistantAnswer => {
126 Self::append_assistant_answer_display_text(output, &self.content);
127 }
128 SessionMessageKind::WorkflowNotice => output.push_str(&self.content),
129 }
130 }
131
132 fn append_user_prompt_display_text(output: &mut String, content: &str) {
135 let content = normalized_user_prompt_content(content);
136 if content.trim().is_empty() {
137 return;
138 }
139
140 if !output.is_empty() {
141 output.push('\n');
142 }
143
144 let is_clarification_prompt = content
145 .lines()
146 .next()
147 .is_some_and(|line| line.trim() == CLARIFICATION_HEADER);
148
149 for (line_index, prompt_line) in content.split('\n').enumerate() {
150 if is_clarification_prompt
151 && line_index > 0
152 && Self::is_clarification_question_line(prompt_line)
153 {
154 output.push_str(USER_PROMPT_CONTINUATION_PREFIX);
155 output.push('\n');
156 }
157
158 if line_index == 0 {
159 output.push_str(USER_PROMPT_PREFIX);
160 } else {
161 output.push_str(USER_PROMPT_CONTINUATION_PREFIX);
162 }
163
164 output.push_str(prompt_line);
165 output.push('\n');
166 }
167
168 output.push('\n');
169 }
170
171 fn is_clarification_question_line(line: &str) -> bool {
174 let trimmed_line = line.trim_start();
175 let digit_count = trimmed_line
176 .chars()
177 .take_while(char::is_ascii_digit)
178 .count();
179 if digit_count == 0 {
180 return false;
181 }
182
183 let (_, suffix) = trimmed_line.split_at(digit_count);
184
185 suffix.starts_with(". Q: ")
186 }
187
188 fn append_assistant_answer_display_text(output: &mut String, content: &str) {
190 let content = content.trim();
191 if content.is_empty() {
192 return;
193 }
194
195 output.push_str(content);
196 output.push_str("\n\n");
197 }
198}
199
200#[derive(Clone, Debug, Default, Eq, PartialEq)]
202pub struct SessionTranscript {
203 content_hash: u64,
204 messages: Vec<SessionMessage>,
205 total_content_len: usize,
206}
207
208impl SessionTranscript {
209 pub fn new(mut messages: Vec<SessionMessage>) -> Self {
211 messages.sort_by_key(|message| message.position);
212
213 let content_hash = Self::content_hash_for_messages(&messages);
214 let total_content_len = messages.iter().map(|message| message.content.len()).sum();
215
216 Self {
217 content_hash,
218 messages,
219 total_content_len,
220 }
221 }
222
223 pub fn is_empty(&self) -> bool {
225 self.messages.is_empty()
226 }
227
228 pub fn messages(&self) -> &[SessionMessage] {
230 &self.messages
231 }
232
233 pub fn content_hash(&self) -> u64 {
235 self.content_hash
236 }
237
238 pub fn total_content_len(&self) -> usize {
240 self.total_content_len
241 }
242
243 pub fn append_message(&mut self, kind: SessionMessageKind, content: &str) {
250 let content = stored_message_content(kind, content);
251 if content.trim().is_empty() {
252 return;
253 }
254
255 let position = self
256 .messages
257 .last()
258 .map_or(0, |message| message.position.saturating_add(1));
259 self.total_content_len = self.total_content_len.saturating_add(content.len());
260 self.messages
261 .push(SessionMessage::new(position, kind, content));
262 self.content_hash = Self::content_hash_for_messages(&self.messages);
263 }
264
265 pub fn replay_text(&self) -> Option<String> {
270 let output = Self::display_text_for_messages(&self.messages);
271 if output.trim().is_empty() {
272 return None;
273 }
274
275 Some(output)
276 }
277
278 pub fn conversation_replay_text(&self) -> Option<String> {
281 let mut output = String::new();
282
283 for message in self
284 .messages
285 .iter()
286 .filter(|message| message.kind.is_conversation_message())
287 {
288 message.append_display_text(&mut output);
289 }
290
291 if output.trim().is_empty() {
292 return None;
293 }
294
295 Some(output)
296 }
297
298 pub fn display_text_for_messages(messages: &[SessionMessage]) -> String {
305 let mut output = String::new();
306
307 for message in messages {
308 message.append_display_text(&mut output);
309 }
310
311 output
312 }
313
314 fn content_hash_for_messages(messages: &[SessionMessage]) -> u64 {
318 let mut hasher = FxHasher::default();
319
320 for message in messages {
321 hasher.write_i64(message.position);
322 hasher.write(message.kind.as_str().as_bytes());
323 hasher.write_u8(0xff);
324 hasher.write(message.content.as_bytes());
325 hasher.write_u8(0xfe);
326 }
327
328 hasher.finish()
329 }
330}
331
332pub fn stored_message_content(kind: SessionMessageKind, content: &str) -> String {
339 match kind {
340 SessionMessageKind::UserPrompt | SessionMessageKind::AgentPrompt => {
341 normalized_user_prompt_content(content)
342 }
343 SessionMessageKind::AssistantAnswer | SessionMessageKind::ActivitySummary => {
344 normalized_message_content(content)
345 }
346 SessionMessageKind::WorkflowNotice => content.to_string(),
347 }
348}
349
350pub fn normalized_message_content(content: &str) -> String {
352 content.trim().to_string()
353}
354
355const CLARIFICATION_HEADER: &str = "Clarifications:";
356const USER_PROMPT_CONTINUATION_PREFIX: &str = " ";
357const USER_PROMPT_PREFIX: &str = " › ";
358
359fn normalized_user_prompt_content(content: &str) -> String {
362 content
363 .trim_end()
364 .trim_start_matches(['\r', '\n'])
365 .to_string()
366}
367
368#[cfg(test)]
369#[path = "message_test.rs"]
370mod tests;