1use std::fmt;
2use std::hash::Hasher;
3use std::str::FromStr;
4
5use rustc_hash::FxHasher;
6use serde::{Deserialize, Serialize};
7
8use crate::TaskAgentRole;
9
10#[derive(Clone, Copy, Debug, Eq, PartialEq)]
12pub enum SessionMessageKind {
13 ActivitySummary,
16 UserPrompt,
18 AgentPrompt,
20 AgentAnswer,
24 AgentGraph,
28 AssistantAnswer,
30 WorkflowNotice,
32}
33
34impl SessionMessageKind {
35 pub fn as_str(self) -> &'static str {
37 match self {
38 Self::ActivitySummary => "activity_summary",
39 Self::UserPrompt => "user_prompt",
40 Self::AgentPrompt => "agent_prompt",
41 Self::AgentAnswer => "agent_answer",
42 Self::AgentGraph => "agent_graph",
43 Self::AssistantAnswer => "assistant_answer",
44 Self::WorkflowNotice => "workflow_notice",
45 }
46 }
47
48 pub fn is_conversation_message(self) -> bool {
54 matches!(
55 self,
56 Self::UserPrompt | Self::AgentPrompt | Self::AssistantAnswer
57 )
58 }
59
60 pub fn is_prompt(self) -> bool {
62 matches!(self, Self::UserPrompt | Self::AgentPrompt)
63 }
64}
65
66impl fmt::Display for SessionMessageKind {
67 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
68 formatter.write_str(self.as_str())
69 }
70}
71
72impl FromStr for SessionMessageKind {
73 type Err = SessionMessageKindParseError;
74
75 fn from_str(value: &str) -> Result<Self, Self::Err> {
76 match value {
77 "activity_summary" => Ok(Self::ActivitySummary),
78 "user_prompt" => Ok(Self::UserPrompt),
79 "agent_prompt" => Ok(Self::AgentPrompt),
80 "agent_answer" => Ok(Self::AgentAnswer),
81 "agent_graph" => Ok(Self::AgentGraph),
82 "assistant_answer" => Ok(Self::AssistantAnswer),
83 "workflow_notice" => Ok(Self::WorkflowNotice),
84 _ => Err(SessionMessageKindParseError {
85 value: value.to_string(),
86 }),
87 }
88 }
89}
90
91#[derive(Clone, Debug, Eq, PartialEq)]
93pub struct SessionMessageKindParseError {
94 value: String,
95}
96
97impl fmt::Display for SessionMessageKindParseError {
98 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
99 write!(formatter, "unknown session message kind `{}`", self.value)
100 }
101}
102
103impl std::error::Error for SessionMessageKindParseError {}
104
105#[derive(Clone, Debug, Eq, PartialEq)]
113pub struct AgentAnswerContent {
114 pub agent: TaskAgentRole,
116 pub text: String,
118}
119
120impl AgentAnswerContent {
121 pub fn encode(&self) -> String {
124 serde_json::json!(EncodedAgentAnswer {
125 agent: self.agent.id().to_string(),
126 text: self.text.trim().to_string(),
127 })
128 .to_string()
129 }
130
131 pub fn decode(content: &str) -> Option<Self> {
133 let encoded = serde_json::from_str::<EncodedAgentAnswer>(content).ok()?;
134
135 Some(Self {
136 agent: TaskAgentRole::from_id(&encoded.agent)?,
137 text: encoded.text,
138 })
139 }
140}
141
142#[derive(Clone, Debug, Eq, PartialEq)]
144pub struct SessionMessage {
145 pub content: String,
147 pub kind: SessionMessageKind,
149 pub position: i64,
151}
152
153impl SessionMessage {
154 pub fn new(position: i64, kind: SessionMessageKind, content: impl Into<String>) -> Self {
156 Self {
157 content: content.into(),
158 kind,
159 position,
160 }
161 }
162
163 pub fn conversation(position: i64, kind: SessionMessageKind, content: impl AsRef<str>) -> Self {
166 Self {
167 content: stored_message_content(kind, content.as_ref()),
168 kind,
169 position,
170 }
171 }
172
173 pub fn agent_answer(&self) -> Option<AgentAnswerContent> {
176 if self.kind != SessionMessageKind::AgentAnswer {
177 return None;
178 }
179
180 AgentAnswerContent::decode(&self.content)
181 }
182
183 pub fn agent_graph_chain_id(&self) -> Option<&str> {
186 (self.kind == SessionMessageKind::AgentGraph).then_some(self.content.as_str())
187 }
188
189 fn append_display_text(&self, output: &mut String) {
194 match self.kind {
195 SessionMessageKind::ActivitySummary
196 | SessionMessageKind::AgentAnswer
197 | SessionMessageKind::AgentGraph => {}
198 SessionMessageKind::UserPrompt | SessionMessageKind::AgentPrompt => {
199 Self::append_user_prompt_display_text(output, &self.content);
200 }
201 SessionMessageKind::AssistantAnswer => {
202 Self::append_assistant_answer_display_text(output, &self.content);
203 }
204 SessionMessageKind::WorkflowNotice => output.push_str(&self.content),
205 }
206 }
207
208 fn append_user_prompt_display_text(output: &mut String, content: &str) {
211 let content = normalized_user_prompt_content(content);
212 if content.trim().is_empty() {
213 return;
214 }
215
216 if !output.is_empty() {
217 output.push('\n');
218 }
219
220 let is_clarification_prompt = content
221 .lines()
222 .next()
223 .is_some_and(|line| line.trim() == CLARIFICATION_HEADER);
224
225 for (line_index, prompt_line) in content.split('\n').enumerate() {
226 if is_clarification_prompt
227 && line_index > 0
228 && Self::is_clarification_question_line(prompt_line)
229 {
230 output.push_str(USER_PROMPT_CONTINUATION_PREFIX);
231 output.push('\n');
232 }
233
234 if line_index == 0 {
235 output.push_str(USER_PROMPT_PREFIX);
236 } else {
237 output.push_str(USER_PROMPT_CONTINUATION_PREFIX);
238 }
239
240 output.push_str(prompt_line);
241 output.push('\n');
242 }
243
244 output.push('\n');
245 }
246
247 fn is_clarification_question_line(line: &str) -> bool {
250 let trimmed_line = line.trim_start();
251 let digit_count = trimmed_line
252 .chars()
253 .take_while(char::is_ascii_digit)
254 .count();
255 if digit_count == 0 {
256 return false;
257 }
258
259 let (_, suffix) = trimmed_line.split_at(digit_count);
260
261 suffix.starts_with(". Q: ")
262 }
263
264 fn append_assistant_answer_display_text(output: &mut String, content: &str) {
266 let content = content.trim();
267 if content.is_empty() {
268 return;
269 }
270
271 output.push_str(content);
272 output.push_str("\n\n");
273 }
274}
275
276#[derive(Clone, Debug, Default, Eq, PartialEq)]
278pub struct SessionTranscript {
279 content_hash: u64,
280 messages: Vec<SessionMessage>,
281 total_content_len: usize,
282 ephemeral: bool,
283}
284
285impl SessionTranscript {
286 pub fn new(mut messages: Vec<SessionMessage>) -> Self {
288 messages.sort_by_key(|message| message.position);
289
290 let content_hash = Self::content_hash_for_messages(&messages);
291 let total_content_len = messages.iter().map(|message| message.content.len()).sum();
292
293 Self {
294 content_hash,
295 messages,
296 total_content_len,
297 ephemeral: false,
298 }
299 }
300
301 pub fn ephemeral(messages: Vec<SessionMessage>) -> Self {
304 Self {
305 ephemeral: true,
306 ..Self::new(messages)
307 }
308 }
309
310 pub fn should_persist(&self) -> bool {
313 !self.ephemeral
314 }
315
316 pub fn is_empty(&self) -> bool {
318 self.messages.is_empty()
319 }
320
321 pub fn messages(&self) -> &[SessionMessage] {
323 &self.messages
324 }
325
326 pub fn content_hash(&self) -> u64 {
328 self.content_hash
329 }
330
331 pub fn total_content_len(&self) -> usize {
333 self.total_content_len
334 }
335
336 pub fn append_message(&mut self, kind: SessionMessageKind, content: &str) {
343 let content = stored_message_content(kind, content);
344 if content.trim().is_empty() {
345 return;
346 }
347
348 let position = self
349 .messages
350 .last()
351 .map_or(0, |message| message.position.saturating_add(1));
352 self.total_content_len = self.total_content_len.saturating_add(content.len());
353 self.messages
354 .push(SessionMessage::new(position, kind, content));
355 self.content_hash = Self::content_hash_for_messages(&self.messages);
356 }
357
358 pub fn replay_text(&self) -> Option<String> {
363 let output = Self::display_text_for_messages(&self.messages);
364 if output.trim().is_empty() {
365 return None;
366 }
367
368 Some(output)
369 }
370
371 pub fn conversation_replay_text(&self) -> Option<String> {
374 let mut output = String::new();
375
376 for message in self
377 .messages
378 .iter()
379 .filter(|message| message.kind.is_conversation_message())
380 {
381 message.append_display_text(&mut output);
382 }
383
384 if output.trim().is_empty() {
385 return None;
386 }
387
388 Some(output)
389 }
390
391 pub fn display_text_for_messages(messages: &[SessionMessage]) -> String {
398 let mut output = String::new();
399
400 for message in messages {
401 message.append_display_text(&mut output);
402 }
403
404 output
405 }
406
407 fn content_hash_for_messages(messages: &[SessionMessage]) -> u64 {
411 let mut hasher = FxHasher::default();
412
413 for message in messages {
414 hasher.write_i64(message.position);
415 hasher.write(message.kind.as_str().as_bytes());
416 hasher.write_u8(0xff);
417 hasher.write(message.content.as_bytes());
418 hasher.write_u8(0xfe);
419 }
420
421 hasher.finish()
422 }
423}
424
425pub fn stored_message_content(kind: SessionMessageKind, content: &str) -> String {
433 match kind {
434 SessionMessageKind::UserPrompt | SessionMessageKind::AgentPrompt => {
435 normalized_user_prompt_content(content)
436 }
437 SessionMessageKind::AssistantAnswer
438 | SessionMessageKind::ActivitySummary
439 | SessionMessageKind::AgentAnswer => normalized_message_content(content),
440 SessionMessageKind::AgentGraph | SessionMessageKind::WorkflowNotice => content.to_string(),
441 }
442}
443
444pub fn normalized_message_content(content: &str) -> String {
446 content.trim().to_string()
447}
448
449#[derive(Deserialize, Serialize)]
451struct EncodedAgentAnswer {
452 agent: String,
453 text: String,
454}
455
456const CLARIFICATION_HEADER: &str = "Clarifications:";
457const USER_PROMPT_CONTINUATION_PREFIX: &str = " ";
458const USER_PROMPT_PREFIX: &str = " › ";
459
460fn normalized_user_prompt_content(content: &str) -> String {
463 content
464 .trim_end()
465 .trim_start_matches(['\r', '\n'])
466 .to_string()
467}
468
469#[cfg(test)]
470#[path = "message_test.rs"]
471mod tests;