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,
21 UserPrompt,
23 AgentPrompt,
25 AssistantAnswer,
27 WorkflowNotice,
29}
30
31impl SessionMessageKind {
32 pub fn as_str(self) -> &'static str {
34 match self {
35 Self::ActivitySummary => "activity_summary",
36 Self::UserPrompt => "user_prompt",
37 Self::AgentPrompt => "agent_prompt",
38 Self::AssistantAnswer => "assistant_answer",
39 Self::WorkflowNotice => "workflow_notice",
40 }
41 }
42
43 pub fn is_conversation_message(self) -> bool {
46 matches!(
47 self,
48 Self::UserPrompt | Self::AgentPrompt | Self::AssistantAnswer
49 )
50 }
51
52 pub fn is_prompt(self) -> bool {
54 matches!(self, Self::UserPrompt | Self::AgentPrompt)
55 }
56}
57
58impl fmt::Display for SessionMessageKind {
59 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
60 formatter.write_str(self.as_str())
61 }
62}
63
64impl FromStr for SessionMessageKind {
65 type Err = SessionMessageKindParseError;
66
67 fn from_str(value: &str) -> Result<Self, Self::Err> {
68 match value {
69 "activity_summary" => Ok(Self::ActivitySummary),
70 "user_prompt" => Ok(Self::UserPrompt),
71 "agent_prompt" => Ok(Self::AgentPrompt),
72 "assistant_answer" => Ok(Self::AssistantAnswer),
73 "workflow_notice" => Ok(Self::WorkflowNotice),
74 _ => Err(SessionMessageKindParseError {
75 value: value.to_string(),
76 }),
77 }
78 }
79}
80
81#[derive(Clone, Debug, Eq, PartialEq)]
83pub struct SessionMessageKindParseError {
84 value: String,
85}
86
87impl fmt::Display for SessionMessageKindParseError {
88 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
89 write!(formatter, "unknown session message kind `{}`", self.value)
90 }
91}
92
93impl std::error::Error for SessionMessageKindParseError {}
94
95#[derive(Clone, Debug, Eq, PartialEq)]
97pub struct SessionMessage {
98 pub content: String,
100 pub kind: SessionMessageKind,
102 pub position: i64,
104}
105
106impl SessionMessage {
107 pub fn new(position: i64, kind: SessionMessageKind, content: impl Into<String>) -> Self {
109 Self {
110 content: content.into(),
111 kind,
112 position,
113 }
114 }
115
116 pub fn conversation(position: i64, kind: SessionMessageKind, content: impl AsRef<str>) -> Self {
119 Self {
120 content: stored_message_content(kind, content.as_ref()),
121 kind,
122 position,
123 }
124 }
125
126 fn is_user_only_notice(&self) -> bool {
129 let content = self.content.trim_start();
130
131 self.kind == SessionMessageKind::WorkflowNotice
132 && [
133 TranscriptNotice::Context,
134 TranscriptNotice::ContextWarning,
135 TranscriptNotice::Sandbox,
136 TranscriptNotice::SandboxWarning,
137 ]
138 .iter()
139 .any(|notice| content.starts_with(&format!("{} ", notice.prefix())))
140 }
141
142 fn append_display_text(&self, output: &mut String) {
144 match self.kind {
145 SessionMessageKind::ActivitySummary => {}
146 SessionMessageKind::UserPrompt | SessionMessageKind::AgentPrompt => {
147 Self::append_user_prompt_display_text(output, &self.content);
148 }
149 SessionMessageKind::AssistantAnswer => {
150 Self::append_assistant_answer_display_text(output, &self.content);
151 }
152 SessionMessageKind::WorkflowNotice => output.push_str(&self.content),
153 }
154 }
155
156 fn append_user_prompt_display_text(output: &mut String, content: &str) {
159 let content = normalized_user_prompt_content(content);
160 if content.trim().is_empty() {
161 return;
162 }
163
164 if !output.is_empty() {
165 output.push('\n');
166 }
167
168 let is_clarification_prompt = content
169 .lines()
170 .next()
171 .is_some_and(|line| line.trim() == CLARIFICATION_HEADER);
172
173 for (line_index, prompt_line) in content.split('\n').enumerate() {
174 if is_clarification_prompt
175 && line_index > 0
176 && Self::is_clarification_question_line(prompt_line)
177 {
178 output.push_str(USER_PROMPT_CONTINUATION_PREFIX);
179 output.push('\n');
180 }
181
182 if line_index == 0 {
183 output.push_str(USER_PROMPT_PREFIX);
184 } else {
185 output.push_str(USER_PROMPT_CONTINUATION_PREFIX);
186 }
187
188 output.push_str(prompt_line);
189 output.push('\n');
190 }
191
192 output.push('\n');
193 }
194
195 fn is_clarification_question_line(line: &str) -> bool {
198 let trimmed_line = line.trim_start();
199 let digit_count = trimmed_line
200 .chars()
201 .take_while(char::is_ascii_digit)
202 .count();
203 if digit_count == 0 {
204 return false;
205 }
206
207 let (_, suffix) = trimmed_line.split_at(digit_count);
208
209 suffix.starts_with(". Q: ")
210 }
211
212 fn append_assistant_answer_display_text(output: &mut String, content: &str) {
214 let content = content.trim();
215 if content.is_empty() {
216 return;
217 }
218
219 output.push_str(content);
220 output.push_str("\n\n");
221 }
222}
223
224#[derive(Clone, Debug, Default, Eq, PartialEq)]
226pub struct SessionTranscript {
227 content_hash: u64,
228 messages: Vec<SessionMessage>,
229 total_content_len: usize,
230 ephemeral: bool,
231}
232
233impl SessionTranscript {
234 pub fn new(mut messages: Vec<SessionMessage>) -> Self {
236 messages.sort_by_key(|message| message.position);
237
238 let content_hash = Self::content_hash_for_messages(&messages);
239 let total_content_len = messages.iter().map(|message| message.content.len()).sum();
240
241 Self {
242 content_hash,
243 messages,
244 total_content_len,
245 ephemeral: false,
246 }
247 }
248
249 pub fn ephemeral(messages: Vec<SessionMessage>) -> Self {
252 Self {
253 ephemeral: true,
254 ..Self::new(messages)
255 }
256 }
257
258 pub fn should_persist(&self) -> bool {
261 !self.ephemeral
262 }
263
264 pub fn is_empty(&self) -> bool {
266 self.messages.is_empty()
267 }
268
269 pub fn messages(&self) -> &[SessionMessage] {
271 &self.messages
272 }
273
274 pub fn content_hash(&self) -> u64 {
276 self.content_hash
277 }
278
279 pub fn total_content_len(&self) -> usize {
281 self.total_content_len
282 }
283
284 pub fn append_message(&mut self, kind: SessionMessageKind, content: &str) {
295 let content = stored_message_content(kind, content);
296 if content.trim().is_empty() {
297 return;
298 }
299
300 let position = self
301 .messages
302 .last()
303 .map_or(0, |message| message.position.saturating_add(1));
304 let message = SessionMessage::new(position, kind, content);
305 self.content_hash = Self::chained_content_hash(self.content_hash, &message);
306 self.total_content_len = self.total_content_len.saturating_add(message.content.len());
307 self.messages.push(message);
308 }
309
310 pub fn replay_text(&self) -> Option<String> {
315 let output = Self::display_text_for_messages(&self.messages);
316 if output.trim().is_empty() {
317 return None;
318 }
319
320 Some(output)
321 }
322
323 pub fn provider_replay_text(&self) -> Option<String> {
328 let messages = self
329 .messages
330 .iter()
331 .filter(|message| !message.is_user_only_notice())
332 .cloned()
333 .collect::<Vec<_>>();
334 let output = Self::display_text_for_messages(&messages);
335 if output.trim().is_empty() {
336 return None;
337 }
338
339 Some(output)
340 }
341
342 pub fn conversation_replay_text(&self) -> Option<String> {
345 let mut output = String::new();
346
347 for message in self
348 .messages
349 .iter()
350 .filter(|message| message.kind.is_conversation_message())
351 {
352 message.append_display_text(&mut output);
353 }
354
355 if output.trim().is_empty() {
356 return None;
357 }
358
359 Some(output)
360 }
361
362 pub fn display_text_for_messages(messages: &[SessionMessage]) -> String {
369 let mut output = String::new();
370
371 for message in messages {
372 message.append_display_text(&mut output);
373 }
374
375 output
376 }
377
378 fn content_hash_for_messages(messages: &[SessionMessage]) -> u64 {
389 messages.iter().fold(0, Self::chained_content_hash)
390 }
391
392 fn chained_content_hash(previous_hash: u64, message: &SessionMessage) -> u64 {
394 let mut hasher = FxHasher::default();
395 hasher.write_u64(previous_hash);
396 hasher.write_i64(message.position);
397 hasher.write(message.kind.as_str().as_bytes());
398 hasher.write_u8(0xff);
399 hasher.write(message.content.as_bytes());
400 hasher.write_u8(0xfe);
401
402 hasher.finish()
403 }
404}
405
406pub fn stored_message_content(kind: SessionMessageKind, content: &str) -> String {
413 match kind {
414 SessionMessageKind::UserPrompt | SessionMessageKind::AgentPrompt => {
415 normalized_user_prompt_content(content)
416 }
417 SessionMessageKind::AssistantAnswer | SessionMessageKind::ActivitySummary => {
418 normalized_message_content(content)
419 }
420 SessionMessageKind::WorkflowNotice => content.to_string(),
421 }
422}
423
424pub fn normalized_message_content(content: &str) -> String {
426 content.trim().to_string()
427}
428
429const CLARIFICATION_HEADER: &str = "Clarifications:";
430const USER_PROMPT_CONTINUATION_PREFIX: &str = " ";
431const USER_PROMPT_PREFIX: &str = " › ";
432
433fn normalized_user_prompt_content(content: &str) -> String {
436 content
437 .trim_end()
438 .trim_start_matches(['\r', '\n'])
439 .to_string()
440}
441
442#[cfg(test)]
443#[path = "message_test.rs"]
444mod tests;