1use std::fmt;
5use std::hash::Hasher;
6use std::str::FromStr;
7
8use rustc_hash::FxHasher;
9
10use crate::transcript_notice::TranscriptNotice;
11
12#[derive(Clone, Copy, Debug, Eq, PartialEq)]
14pub enum SessionMessageKind {
15 ActivitySummary,
18 UserPrompt,
20 AgentPrompt,
22 AssistantAnswer,
24 WorkflowNotice,
26}
27
28impl SessionMessageKind {
29 pub fn as_str(self) -> &'static str {
31 match self {
32 Self::ActivitySummary => "activity_summary",
33 Self::UserPrompt => "user_prompt",
34 Self::AgentPrompt => "agent_prompt",
35 Self::AssistantAnswer => "assistant_answer",
36 Self::WorkflowNotice => "workflow_notice",
37 }
38 }
39
40 pub fn is_conversation_message(self) -> bool {
43 matches!(
44 self,
45 Self::UserPrompt | Self::AgentPrompt | Self::AssistantAnswer
46 )
47 }
48
49 pub fn is_prompt(self) -> bool {
51 matches!(self, Self::UserPrompt | Self::AgentPrompt)
52 }
53}
54
55impl fmt::Display for SessionMessageKind {
56 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
57 formatter.write_str(self.as_str())
58 }
59}
60
61impl FromStr for SessionMessageKind {
62 type Err = SessionMessageKindParseError;
63
64 fn from_str(value: &str) -> Result<Self, Self::Err> {
65 match value {
66 "activity_summary" => Ok(Self::ActivitySummary),
67 "user_prompt" => Ok(Self::UserPrompt),
68 "agent_prompt" => Ok(Self::AgentPrompt),
69 "assistant_answer" => Ok(Self::AssistantAnswer),
70 "workflow_notice" => Ok(Self::WorkflowNotice),
71 _ => Err(SessionMessageKindParseError {
72 value: value.to_string(),
73 }),
74 }
75 }
76}
77
78#[derive(Clone, Debug, Eq, PartialEq)]
80pub struct SessionMessageKindParseError {
81 value: String,
82}
83
84impl fmt::Display for SessionMessageKindParseError {
85 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
86 write!(formatter, "unknown session message kind `{}`", self.value)
87 }
88}
89
90impl std::error::Error for SessionMessageKindParseError {}
91
92#[derive(Clone, Debug, Eq, PartialEq)]
94pub struct SessionMessage {
95 pub content: String,
97 pub kind: SessionMessageKind,
99 pub position: i64,
101}
102
103impl SessionMessage {
104 pub fn new(position: i64, kind: SessionMessageKind, content: impl Into<String>) -> Self {
106 Self {
107 content: content.into(),
108 kind,
109 position,
110 }
111 }
112
113 pub fn conversation(position: i64, kind: SessionMessageKind, content: impl AsRef<str>) -> Self {
116 Self {
117 content: stored_message_content(kind, content.as_ref()),
118 kind,
119 position,
120 }
121 }
122
123 fn is_user_only_notice(&self) -> bool {
126 let content = self.content.trim_start();
127
128 self.kind == SessionMessageKind::WorkflowNotice
129 && [
130 TranscriptNotice::Context,
131 TranscriptNotice::ContextWarning,
132 TranscriptNotice::Sandbox,
133 TranscriptNotice::SandboxWarning,
134 ]
135 .iter()
136 .any(|notice| content.starts_with(&format!("{} ", notice.prefix())))
137 }
138
139 fn append_display_text(&self, output: &mut String) {
141 match self.kind {
142 SessionMessageKind::ActivitySummary => {}
143 SessionMessageKind::UserPrompt | SessionMessageKind::AgentPrompt => {
144 Self::append_user_prompt_display_text(output, &self.content);
145 }
146 SessionMessageKind::AssistantAnswer => {
147 Self::append_assistant_answer_display_text(output, &self.content);
148 }
149 SessionMessageKind::WorkflowNotice => output.push_str(&self.content),
150 }
151 }
152
153 fn append_user_prompt_display_text(output: &mut String, content: &str) {
156 let content = normalized_user_prompt_content(content);
157 if content.trim().is_empty() {
158 return;
159 }
160
161 if !output.is_empty() {
162 output.push('\n');
163 }
164
165 let is_clarification_prompt = content
166 .lines()
167 .next()
168 .is_some_and(|line| line.trim() == CLARIFICATION_HEADER);
169
170 for (line_index, prompt_line) in content.split('\n').enumerate() {
171 if is_clarification_prompt
172 && line_index > 0
173 && Self::is_clarification_question_line(prompt_line)
174 {
175 output.push_str(USER_PROMPT_CONTINUATION_PREFIX);
176 output.push('\n');
177 }
178
179 if line_index == 0 {
180 output.push_str(USER_PROMPT_PREFIX);
181 } else {
182 output.push_str(USER_PROMPT_CONTINUATION_PREFIX);
183 }
184
185 output.push_str(prompt_line);
186 output.push('\n');
187 }
188
189 output.push('\n');
190 }
191
192 fn is_clarification_question_line(line: &str) -> bool {
195 let trimmed_line = line.trim_start();
196 let digit_count = trimmed_line
197 .chars()
198 .take_while(char::is_ascii_digit)
199 .count();
200 if digit_count == 0 {
201 return false;
202 }
203
204 let (_, suffix) = trimmed_line.split_at(digit_count);
205
206 suffix.starts_with(". Q: ")
207 }
208
209 fn append_assistant_answer_display_text(output: &mut String, content: &str) {
211 let content = content.trim();
212 if content.is_empty() {
213 return;
214 }
215
216 output.push_str(content);
217 output.push_str("\n\n");
218 }
219}
220
221#[derive(Clone, Debug, Default, Eq, PartialEq)]
223pub struct SessionTranscript {
224 content_hash: u64,
225 messages: Vec<SessionMessage>,
226 total_content_len: usize,
227 ephemeral: bool,
228}
229
230impl SessionTranscript {
231 pub fn new(mut messages: Vec<SessionMessage>) -> Self {
233 messages.sort_by_key(|message| message.position);
234
235 let content_hash = Self::content_hash_for_messages(&messages);
236 let total_content_len = messages.iter().map(|message| message.content.len()).sum();
237
238 Self {
239 content_hash,
240 messages,
241 total_content_len,
242 ephemeral: false,
243 }
244 }
245
246 pub fn ephemeral(messages: Vec<SessionMessage>) -> Self {
249 Self {
250 ephemeral: true,
251 ..Self::new(messages)
252 }
253 }
254
255 pub fn should_persist(&self) -> bool {
258 !self.ephemeral
259 }
260
261 pub fn is_empty(&self) -> bool {
263 self.messages.is_empty()
264 }
265
266 pub fn messages(&self) -> &[SessionMessage] {
268 &self.messages
269 }
270
271 pub fn content_hash(&self) -> u64 {
273 self.content_hash
274 }
275
276 pub fn total_content_len(&self) -> usize {
278 self.total_content_len
279 }
280
281 pub fn append_message(&mut self, kind: SessionMessageKind, content: &str) {
292 let content = stored_message_content(kind, content);
293 if content.trim().is_empty() {
294 return;
295 }
296
297 let position = self
298 .messages
299 .last()
300 .map_or(0, |message| message.position.saturating_add(1));
301 let message = SessionMessage::new(position, kind, content);
302 self.content_hash = Self::chained_content_hash(self.content_hash, &message);
303 self.total_content_len = self.total_content_len.saturating_add(message.content.len());
304 self.messages.push(message);
305 }
306
307 pub fn replay_text(&self) -> Option<String> {
312 let output = Self::display_text_for_messages(&self.messages);
313 if output.trim().is_empty() {
314 return None;
315 }
316
317 Some(output)
318 }
319
320 pub fn provider_replay_text(&self) -> Option<String> {
325 let messages = self
326 .messages
327 .iter()
328 .filter(|message| !message.is_user_only_notice())
329 .cloned()
330 .collect::<Vec<_>>();
331 let output = Self::display_text_for_messages(&messages);
332 if output.trim().is_empty() {
333 return None;
334 }
335
336 Some(output)
337 }
338
339 pub fn conversation_replay_text(&self) -> Option<String> {
342 let mut output = String::new();
343
344 for message in self
345 .messages
346 .iter()
347 .filter(|message| message.kind.is_conversation_message())
348 {
349 message.append_display_text(&mut output);
350 }
351
352 if output.trim().is_empty() {
353 return None;
354 }
355
356 Some(output)
357 }
358
359 pub fn display_text_for_messages(messages: &[SessionMessage]) -> String {
366 let mut output = String::new();
367
368 for message in messages {
369 message.append_display_text(&mut output);
370 }
371
372 output
373 }
374
375 fn content_hash_for_messages(messages: &[SessionMessage]) -> u64 {
386 messages.iter().fold(0, Self::chained_content_hash)
387 }
388
389 fn chained_content_hash(previous_hash: u64, message: &SessionMessage) -> u64 {
391 let mut hasher = FxHasher::default();
392 hasher.write_u64(previous_hash);
393 hasher.write_i64(message.position);
394 hasher.write(message.kind.as_str().as_bytes());
395 hasher.write_u8(0xff);
396 hasher.write(message.content.as_bytes());
397 hasher.write_u8(0xfe);
398
399 hasher.finish()
400 }
401}
402
403pub fn stored_message_content(kind: SessionMessageKind, content: &str) -> String {
410 match kind {
411 SessionMessageKind::UserPrompt | SessionMessageKind::AgentPrompt => {
412 normalized_user_prompt_content(content)
413 }
414 SessionMessageKind::AssistantAnswer | SessionMessageKind::ActivitySummary => {
415 normalized_message_content(content)
416 }
417 SessionMessageKind::WorkflowNotice => content.to_string(),
418 }
419}
420
421pub fn normalized_message_content(content: &str) -> String {
423 content.trim().to_string()
424}
425
426const CLARIFICATION_HEADER: &str = "Clarifications:";
427const USER_PROMPT_CONTINUATION_PREFIX: &str = " ";
428const USER_PROMPT_PREFIX: &str = " › ";
429
430fn normalized_user_prompt_content(content: &str) -> String {
433 content
434 .trim_end()
435 .trim_start_matches(['\r', '\n'])
436 .to_string()
437}
438
439#[cfg(test)]
440#[path = "message_test.rs"]
441mod tests;