1use std::fmt;
5use std::hash::Hasher;
6use std::str::FromStr;
7
8use rustc_hash::FxHasher;
9
10#[derive(Clone, Copy, Debug, Eq, PartialEq)]
12pub enum SessionMessageKind {
13 ActivitySummary,
16 UserPrompt,
18 AgentPrompt,
20 AssistantAnswer,
22 WorkflowNotice,
24}
25
26impl SessionMessageKind {
27 pub fn as_str(self) -> &'static str {
29 match self {
30 Self::ActivitySummary => "activity_summary",
31 Self::UserPrompt => "user_prompt",
32 Self::AgentPrompt => "agent_prompt",
33 Self::AssistantAnswer => "assistant_answer",
34 Self::WorkflowNotice => "workflow_notice",
35 }
36 }
37
38 pub fn is_conversation_message(self) -> bool {
41 matches!(
42 self,
43 Self::UserPrompt | Self::AgentPrompt | Self::AssistantAnswer
44 )
45 }
46
47 pub fn is_prompt(self) -> bool {
49 matches!(self, Self::UserPrompt | Self::AgentPrompt)
50 }
51}
52
53impl fmt::Display for SessionMessageKind {
54 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
55 formatter.write_str(self.as_str())
56 }
57}
58
59impl FromStr for SessionMessageKind {
60 type Err = SessionMessageKindParseError;
61
62 fn from_str(value: &str) -> Result<Self, Self::Err> {
63 match value {
64 "activity_summary" => Ok(Self::ActivitySummary),
65 "user_prompt" => Ok(Self::UserPrompt),
66 "agent_prompt" => Ok(Self::AgentPrompt),
67 "assistant_answer" => Ok(Self::AssistantAnswer),
68 "workflow_notice" => Ok(Self::WorkflowNotice),
69 _ => Err(SessionMessageKindParseError {
70 value: value.to_string(),
71 }),
72 }
73 }
74}
75
76#[derive(Clone, Debug, Eq, PartialEq)]
78pub struct SessionMessageKindParseError {
79 value: String,
80}
81
82impl fmt::Display for SessionMessageKindParseError {
83 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
84 write!(formatter, "unknown session message kind `{}`", self.value)
85 }
86}
87
88impl std::error::Error for SessionMessageKindParseError {}
89
90#[derive(Clone, Debug, Eq, PartialEq)]
92pub struct SessionMessage {
93 pub content: String,
95 pub kind: SessionMessageKind,
97 pub position: i64,
99}
100
101impl SessionMessage {
102 pub fn new(position: i64, kind: SessionMessageKind, content: impl Into<String>) -> Self {
104 Self {
105 content: content.into(),
106 kind,
107 position,
108 }
109 }
110
111 pub fn conversation(position: i64, kind: SessionMessageKind, content: impl AsRef<str>) -> Self {
114 Self {
115 content: stored_message_content(kind, content.as_ref()),
116 kind,
117 position,
118 }
119 }
120
121 fn append_display_text(&self, output: &mut String) {
123 match self.kind {
124 SessionMessageKind::ActivitySummary => {}
125 SessionMessageKind::UserPrompt | SessionMessageKind::AgentPrompt => {
126 Self::append_user_prompt_display_text(output, &self.content);
127 }
128 SessionMessageKind::AssistantAnswer => {
129 Self::append_assistant_answer_display_text(output, &self.content);
130 }
131 SessionMessageKind::WorkflowNotice => output.push_str(&self.content),
132 }
133 }
134
135 fn append_user_prompt_display_text(output: &mut String, content: &str) {
138 let content = normalized_user_prompt_content(content);
139 if content.trim().is_empty() {
140 return;
141 }
142
143 if !output.is_empty() {
144 output.push('\n');
145 }
146
147 let is_clarification_prompt = content
148 .lines()
149 .next()
150 .is_some_and(|line| line.trim() == CLARIFICATION_HEADER);
151
152 for (line_index, prompt_line) in content.split('\n').enumerate() {
153 if is_clarification_prompt
154 && line_index > 0
155 && Self::is_clarification_question_line(prompt_line)
156 {
157 output.push_str(USER_PROMPT_CONTINUATION_PREFIX);
158 output.push('\n');
159 }
160
161 if line_index == 0 {
162 output.push_str(USER_PROMPT_PREFIX);
163 } else {
164 output.push_str(USER_PROMPT_CONTINUATION_PREFIX);
165 }
166
167 output.push_str(prompt_line);
168 output.push('\n');
169 }
170
171 output.push('\n');
172 }
173
174 fn is_clarification_question_line(line: &str) -> bool {
177 let trimmed_line = line.trim_start();
178 let digit_count = trimmed_line
179 .chars()
180 .take_while(char::is_ascii_digit)
181 .count();
182 if digit_count == 0 {
183 return false;
184 }
185
186 let (_, suffix) = trimmed_line.split_at(digit_count);
187
188 suffix.starts_with(". Q: ")
189 }
190
191 fn append_assistant_answer_display_text(output: &mut String, content: &str) {
193 let content = content.trim();
194 if content.is_empty() {
195 return;
196 }
197
198 output.push_str(content);
199 output.push_str("\n\n");
200 }
201}
202
203#[derive(Clone, Debug, Default, Eq, PartialEq)]
205pub struct SessionTranscript {
206 content_hash: u64,
207 messages: Vec<SessionMessage>,
208 total_content_len: usize,
209 ephemeral: bool,
210}
211
212impl SessionTranscript {
213 pub fn new(mut messages: Vec<SessionMessage>) -> Self {
215 messages.sort_by_key(|message| message.position);
216
217 let content_hash = Self::content_hash_for_messages(&messages);
218 let total_content_len = messages.iter().map(|message| message.content.len()).sum();
219
220 Self {
221 content_hash,
222 messages,
223 total_content_len,
224 ephemeral: false,
225 }
226 }
227
228 pub fn ephemeral(messages: Vec<SessionMessage>) -> Self {
231 Self {
232 ephemeral: true,
233 ..Self::new(messages)
234 }
235 }
236
237 pub fn should_persist(&self) -> bool {
240 !self.ephemeral
241 }
242
243 pub fn is_empty(&self) -> bool {
245 self.messages.is_empty()
246 }
247
248 pub fn messages(&self) -> &[SessionMessage] {
250 &self.messages
251 }
252
253 pub fn content_hash(&self) -> u64 {
255 self.content_hash
256 }
257
258 pub fn total_content_len(&self) -> usize {
260 self.total_content_len
261 }
262
263 pub fn append_message(&mut self, kind: SessionMessageKind, content: &str) {
274 let content = stored_message_content(kind, content);
275 if content.trim().is_empty() {
276 return;
277 }
278
279 let position = self
280 .messages
281 .last()
282 .map_or(0, |message| message.position.saturating_add(1));
283 let message = SessionMessage::new(position, kind, content);
284 self.content_hash = Self::chained_content_hash(self.content_hash, &message);
285 self.total_content_len = self.total_content_len.saturating_add(message.content.len());
286 self.messages.push(message);
287 }
288
289 pub fn replay_text(&self) -> Option<String> {
294 let output = Self::display_text_for_messages(&self.messages);
295 if output.trim().is_empty() {
296 return None;
297 }
298
299 Some(output)
300 }
301
302 pub fn conversation_replay_text(&self) -> Option<String> {
305 let mut output = String::new();
306
307 for message in self
308 .messages
309 .iter()
310 .filter(|message| message.kind.is_conversation_message())
311 {
312 message.append_display_text(&mut output);
313 }
314
315 if output.trim().is_empty() {
316 return None;
317 }
318
319 Some(output)
320 }
321
322 pub fn display_text_for_messages(messages: &[SessionMessage]) -> String {
329 let mut output = String::new();
330
331 for message in messages {
332 message.append_display_text(&mut output);
333 }
334
335 output
336 }
337
338 fn content_hash_for_messages(messages: &[SessionMessage]) -> u64 {
349 messages.iter().fold(0, Self::chained_content_hash)
350 }
351
352 fn chained_content_hash(previous_hash: u64, message: &SessionMessage) -> u64 {
354 let mut hasher = FxHasher::default();
355 hasher.write_u64(previous_hash);
356 hasher.write_i64(message.position);
357 hasher.write(message.kind.as_str().as_bytes());
358 hasher.write_u8(0xff);
359 hasher.write(message.content.as_bytes());
360 hasher.write_u8(0xfe);
361
362 hasher.finish()
363 }
364}
365
366pub fn stored_message_content(kind: SessionMessageKind, content: &str) -> String {
373 match kind {
374 SessionMessageKind::UserPrompt | SessionMessageKind::AgentPrompt => {
375 normalized_user_prompt_content(content)
376 }
377 SessionMessageKind::AssistantAnswer | SessionMessageKind::ActivitySummary => {
378 normalized_message_content(content)
379 }
380 SessionMessageKind::WorkflowNotice => content.to_string(),
381 }
382}
383
384pub fn normalized_message_content(content: &str) -> String {
386 content.trim().to_string()
387}
388
389const CLARIFICATION_HEADER: &str = "Clarifications:";
390const USER_PROMPT_CONTINUATION_PREFIX: &str = " ";
391const USER_PROMPT_PREFIX: &str = " › ";
392
393fn normalized_user_prompt_content(content: &str) -> String {
396 content
397 .trim_end()
398 .trim_start_matches(['\r', '\n'])
399 .to_string()
400}
401
402#[cfg(test)]
403#[path = "message_test.rs"]
404mod tests;