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
10use crate::transcript_notice::TranscriptNotice;
11
12/// Durable category for one saved session transcript message.
13#[derive(Clone, Copy, Debug, Eq, PartialEq)]
14pub enum SessionMessageKind {
15    /// Observed tool and skill usage, displayed but excluded from provider
16    /// replay.
17    ActivitySummary,
18    /// Raw user prompt text without TUI prompt markers or transcript padding.
19    UserPrompt,
20    /// Generated agent-facing prompt retained for replay but hidden from chat.
21    AgentPrompt,
22    /// Raw assistant answer text without transcript padding.
23    AssistantAnswer,
24    /// Generic workflow notice emitted by Agentty session workflows.
25    WorkflowNotice,
26}
27
28impl SessionMessageKind {
29    /// Returns the stable database string for this message kind.
30    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    /// Returns whether this kind represents a raw conversation message that
41    /// belongs in the normal `session_message` store.
42    pub fn is_conversation_message(self) -> bool {
43        matches!(
44            self,
45            Self::UserPrompt | Self::AgentPrompt | Self::AssistantAnswer
46        )
47    }
48
49    /// Returns whether this kind starts one user-visible or generated turn.
50    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/// Error returned when a stored session message kind is unknown.
79#[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/// One persisted transcript message for a session.
93#[derive(Clone, Debug, Eq, PartialEq)]
94pub struct SessionMessage {
95    /// Canonical transcript text for this message.
96    pub content: String,
97    /// Durable message category.
98    pub kind: SessionMessageKind,
99    /// Monotonic position within the owning session transcript.
100    pub position: i64,
101}
102
103impl SessionMessage {
104    /// Creates one transcript message at a stable transcript position.
105    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    /// Creates one raw user or assistant message using kind-specific storage
114    /// normalization.
115    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    /// Returns whether this is a workflow notice only the user reads, such as
124    /// a context compaction or sandbox notice.
125    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    /// Appends this message to a formatted transcript display buffer.
140    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    /// Appends one raw user prompt using the session transcript marker and
154    /// spacing.
155    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    /// Returns true for raw clarification question rows like `1. Q: Need
193    /// tests?`.
194    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    /// Appends one raw assistant answer using session transcript spacing.
210    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/// Ordered transcript view assembled from persisted session messages.
222#[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    /// Creates an ordered transcript from persisted messages.
232    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    /// Creates an isolated projection for task-owned host effects. Messages
247    /// appended here must never enter the owning session's ordinary history.
248    pub fn ephemeral(messages: Vec<SessionMessage>) -> Self {
249        Self {
250            ephemeral: true,
251            ..Self::new(messages)
252        }
253    }
254
255    /// Whether host append operations may persist into ordinary session
256    /// history.
257    pub fn should_persist(&self) -> bool {
258        !self.ephemeral
259    }
260
261    /// Returns whether the transcript contains no saved messages.
262    pub fn is_empty(&self) -> bool {
263        self.messages.is_empty()
264    }
265
266    /// Returns the ordered transcript messages.
267    pub fn messages(&self) -> &[SessionMessage] {
268        &self.messages
269    }
270
271    /// Returns the cached content identity for render and projection caches.
272    pub fn content_hash(&self) -> u64 {
273        self.content_hash
274    }
275
276    /// Returns the total byte length of message content in this transcript.
277    pub fn total_content_len(&self) -> usize {
278        self.total_content_len
279    }
280
281    /// Appends one message after the ordered transcript tail using the same
282    /// content normalization as durable storage.
283    ///
284    /// [`Self::new`] sorts persisted input before this method derives the next
285    /// position, so the message slice and its cached content hash retain the
286    /// same ordering as a newly reconstructed transcript.
287    ///
288    /// The content hash is extended with only the appended message, so each
289    /// append costs time proportional to that message rather than the whole
290    /// transcript.
291    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    /// Returns formatted transcript text for replay when content exists.
308    ///
309    /// User and assistant rows store raw content, so replay injects the prompt
310    /// marker and transcript spacing only for display and provider replay.
311    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    /// Returns [`Self::replay_text`] for a provider: without the notices that
321    /// only tell the user how Agentty ran a turn, such as context compaction
322    /// and sandbox
323    /// notices, which would mislead a model reading the full history.
324    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    /// Returns formatted user and assistant transcript text when any
340    /// conversation messages exist.
341    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    /// Formats an ordered message slice using canonical transcript display
360    /// markers and spacing.
361    ///
362    /// Unlike [`Self::new`], this method preserves the caller-provided order.
363    /// It is useful when rendering a selected subset of an existing transcript
364    /// without constructing another transcript aggregate.
365    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    /// Computes one ordered identity across message positions, kinds, and raw
376    /// content so render caches can compare transcripts without rescanning them
377    /// on every frame.
378    ///
379    /// The identity chains one per-message hash onto the previous value,
380    /// starting from `0`, the derived [`Default`] hash of an empty transcript.
381    /// [`Self::append_message`] therefore extends a cached hash in place and
382    /// still matches a transcript rebuilt from the same messages. The value is
383    /// an in-process cache key; it is never persisted or compared across
384    /// processes.
385    fn content_hash_for_messages(messages: &[SessionMessage]) -> u64 {
386        messages.iter().fold(0, Self::chained_content_hash)
387    }
388
389    /// Extends one transcript content hash with the next ordered message.
390    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
403/// Returns the durable message content for one kind.
404///
405/// User prompts preserve leading horizontal whitespace so pasted indentation
406/// survives persistence while outer line breaks and trailing whitespace are
407/// normalized. Assistant and activity rows remove outer whitespace, and
408/// workflow notices preserve spacing.
409pub 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
421/// Returns raw persisted message content with only outer whitespace removed.
422pub 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
430/// Normalizes prompt boundaries without consuming indentation on the first
431/// content line.
432fn 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;