Skip to main content

ag_session/
message.rs

1//! Session messages and transcripts, with display formatting, replay text,
2//! and stored-content normalization.
3
4use std::fmt;
5use std::hash::Hasher;
6use std::str::FromStr;
7
8use rustc_hash::FxHasher;
9
10/// Durable category for one saved session transcript message.
11#[derive(Clone, Copy, Debug, Eq, PartialEq)]
12pub enum SessionMessageKind {
13    /// Observed tool and skill usage, displayed but excluded from provider
14    /// replay.
15    ActivitySummary,
16    /// Raw user prompt text without TUI prompt markers or transcript padding.
17    UserPrompt,
18    /// Generated agent-facing prompt retained for replay but hidden from chat.
19    AgentPrompt,
20    /// Raw assistant answer text without transcript padding.
21    AssistantAnswer,
22    /// Generic workflow notice emitted by Agentty session workflows.
23    WorkflowNotice,
24}
25
26impl SessionMessageKind {
27    /// Returns the stable database string for this message kind.
28    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    /// Returns whether this kind represents a raw conversation message that
39    /// belongs in the normal `session_message` store.
40    pub fn is_conversation_message(self) -> bool {
41        matches!(
42            self,
43            Self::UserPrompt | Self::AgentPrompt | Self::AssistantAnswer
44        )
45    }
46
47    /// Returns whether this kind starts one user-visible or generated turn.
48    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/// Error returned when a stored session message kind is unknown.
77#[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/// One persisted transcript message for a session.
91#[derive(Clone, Debug, Eq, PartialEq)]
92pub struct SessionMessage {
93    /// Canonical transcript text for this message.
94    pub content: String,
95    /// Durable message category.
96    pub kind: SessionMessageKind,
97    /// Monotonic position within the owning session transcript.
98    pub position: i64,
99}
100
101impl SessionMessage {
102    /// Creates one transcript message at a stable transcript position.
103    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    /// Creates one raw user or assistant message using kind-specific storage
112    /// normalization.
113    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    /// Appends this message to a formatted transcript display buffer.
122    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    /// Appends one raw user prompt using the session transcript marker and
136    /// spacing.
137    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    /// Returns true for raw clarification question rows like `1. Q: Need
175    /// tests?`.
176    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    /// Appends one raw assistant answer using session transcript spacing.
192    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/// Ordered transcript view assembled from persisted session messages.
204#[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    /// Creates an ordered transcript from persisted messages.
214    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    /// Creates an isolated projection for task-owned host effects. Messages
229    /// appended here must never enter the owning session's ordinary history.
230    pub fn ephemeral(messages: Vec<SessionMessage>) -> Self {
231        Self {
232            ephemeral: true,
233            ..Self::new(messages)
234        }
235    }
236
237    /// Whether host append operations may persist into ordinary session
238    /// history.
239    pub fn should_persist(&self) -> bool {
240        !self.ephemeral
241    }
242
243    /// Returns whether the transcript contains no saved messages.
244    pub fn is_empty(&self) -> bool {
245        self.messages.is_empty()
246    }
247
248    /// Returns the ordered transcript messages.
249    pub fn messages(&self) -> &[SessionMessage] {
250        &self.messages
251    }
252
253    /// Returns the cached content identity for render and projection caches.
254    pub fn content_hash(&self) -> u64 {
255        self.content_hash
256    }
257
258    /// Returns the total byte length of message content in this transcript.
259    pub fn total_content_len(&self) -> usize {
260        self.total_content_len
261    }
262
263    /// Appends one message after the ordered transcript tail using the same
264    /// content normalization as durable storage.
265    ///
266    /// [`Self::new`] sorts persisted input before this method derives the next
267    /// position, so the message slice and its cached content hash retain the
268    /// same ordering as a newly reconstructed transcript.
269    ///
270    /// The content hash is extended with only the appended message, so each
271    /// append costs time proportional to that message rather than the whole
272    /// transcript.
273    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    /// Returns formatted transcript text for replay when content exists.
290    ///
291    /// User and assistant rows store raw content, so replay injects the prompt
292    /// marker and transcript spacing only for display and provider replay.
293    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    /// Returns formatted user and assistant transcript text when any
303    /// conversation messages exist.
304    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    /// Formats an ordered message slice using canonical transcript display
323    /// markers and spacing.
324    ///
325    /// Unlike [`Self::new`], this method preserves the caller-provided order.
326    /// It is useful when rendering a selected subset of an existing transcript
327    /// without constructing another transcript aggregate.
328    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    /// Computes one ordered identity across message positions, kinds, and raw
339    /// content so render caches can compare transcripts without rescanning them
340    /// on every frame.
341    ///
342    /// The identity chains one per-message hash onto the previous value,
343    /// starting from `0`, the derived [`Default`] hash of an empty transcript.
344    /// [`Self::append_message`] therefore extends a cached hash in place and
345    /// still matches a transcript rebuilt from the same messages. The value is
346    /// an in-process cache key; it is never persisted or compared across
347    /// processes.
348    fn content_hash_for_messages(messages: &[SessionMessage]) -> u64 {
349        messages.iter().fold(0, Self::chained_content_hash)
350    }
351
352    /// Extends one transcript content hash with the next ordered message.
353    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
366/// Returns the durable message content for one kind.
367///
368/// User prompts preserve leading horizontal whitespace so pasted indentation
369/// survives persistence while outer line breaks and trailing whitespace are
370/// normalized. Assistant and activity rows remove outer whitespace, and
371/// workflow notices preserve spacing.
372pub 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
384/// Returns raw persisted message content with only outer whitespace removed.
385pub 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
393/// Normalizes prompt boundaries without consuming indentation on the first
394/// content line.
395fn 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;