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    /// Summary of one turn's tool calls, saved before its answer or failure
16    /// notice, displayed but excluded from provider replay. Current rows are
17    /// tab-separated text whose first line names the format and its version,
18    /// such as `turn-summary v1`, so a renderer can tell layouts apart; older
19    /// rows without that line list tool, MCP, and skill counts.
20    ActivitySummary,
21    /// Raw user prompt text without TUI prompt markers or transcript padding.
22    UserPrompt,
23    /// Generated agent-facing prompt retained for replay but hidden from chat.
24    AgentPrompt,
25    /// Raw assistant answer text without transcript padding.
26    AssistantAnswer,
27    /// Generic workflow notice emitted by Agentty session workflows.
28    WorkflowNotice,
29}
30
31impl SessionMessageKind {
32    /// Returns the stable database string for this message kind.
33    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    /// Returns whether this kind represents a raw conversation message that
44    /// belongs in the normal `session_message` store.
45    pub fn is_conversation_message(self) -> bool {
46        matches!(
47            self,
48            Self::UserPrompt | Self::AgentPrompt | Self::AssistantAnswer
49        )
50    }
51
52    /// Returns whether this kind starts one user-visible or generated turn.
53    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/// Error returned when a stored session message kind is unknown.
82#[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/// One persisted transcript message for a session.
96#[derive(Clone, Debug, Eq, PartialEq)]
97pub struct SessionMessage {
98    /// Canonical transcript text for this message.
99    pub content: String,
100    /// Durable message category.
101    pub kind: SessionMessageKind,
102    /// Monotonic position within the owning session transcript.
103    pub position: i64,
104}
105
106impl SessionMessage {
107    /// Creates one transcript message at a stable transcript position.
108    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    /// Creates one raw user or assistant message using kind-specific storage
117    /// normalization.
118    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    /// Returns whether this is a workflow notice only the user reads, such as
127    /// a context compaction or sandbox notice.
128    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    /// Appends this message to a formatted transcript display buffer.
143    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    /// Appends one raw user prompt using the session transcript marker and
157    /// spacing.
158    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    /// Returns true for raw clarification question rows like `1. Q: Need
196    /// tests?`.
197    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    /// Appends one raw assistant answer using session transcript spacing.
213    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/// Ordered transcript view assembled from persisted session messages.
225#[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    /// Creates an ordered transcript from persisted messages.
235    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    /// Creates an isolated projection for task-owned host effects. Messages
250    /// appended here must never enter the owning session's ordinary history.
251    pub fn ephemeral(messages: Vec<SessionMessage>) -> Self {
252        Self {
253            ephemeral: true,
254            ..Self::new(messages)
255        }
256    }
257
258    /// Whether host append operations may persist into ordinary session
259    /// history.
260    pub fn should_persist(&self) -> bool {
261        !self.ephemeral
262    }
263
264    /// Returns whether the transcript contains no saved messages.
265    pub fn is_empty(&self) -> bool {
266        self.messages.is_empty()
267    }
268
269    /// Returns the ordered transcript messages.
270    pub fn messages(&self) -> &[SessionMessage] {
271        &self.messages
272    }
273
274    /// Returns the cached content identity for render and projection caches.
275    pub fn content_hash(&self) -> u64 {
276        self.content_hash
277    }
278
279    /// Returns the total byte length of message content in this transcript.
280    pub fn total_content_len(&self) -> usize {
281        self.total_content_len
282    }
283
284    /// Appends one message after the ordered transcript tail using the same
285    /// content normalization as durable storage.
286    ///
287    /// [`Self::new`] sorts persisted input before this method derives the next
288    /// position, so the message slice and its cached content hash retain the
289    /// same ordering as a newly reconstructed transcript.
290    ///
291    /// The content hash is extended with only the appended message, so each
292    /// append costs time proportional to that message rather than the whole
293    /// transcript.
294    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    /// Returns formatted transcript text for replay when content exists.
311    ///
312    /// User and assistant rows store raw content, so replay injects the prompt
313    /// marker and transcript spacing only for display and provider replay.
314    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    /// Returns [`Self::replay_text`] for a provider: without the notices that
324    /// only tell the user how Agentty ran a turn, such as context compaction
325    /// and sandbox
326    /// notices, which would mislead a model reading the full history.
327    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    /// Returns formatted user and assistant transcript text when any
343    /// conversation messages exist.
344    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    /// Formats an ordered message slice using canonical transcript display
363    /// markers and spacing.
364    ///
365    /// Unlike [`Self::new`], this method preserves the caller-provided order.
366    /// It is useful when rendering a selected subset of an existing transcript
367    /// without constructing another transcript aggregate.
368    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    /// Computes one ordered identity across message positions, kinds, and raw
379    /// content so render caches can compare transcripts without rescanning them
380    /// on every frame.
381    ///
382    /// The identity chains one per-message hash onto the previous value,
383    /// starting from `0`, the derived [`Default`] hash of an empty transcript.
384    /// [`Self::append_message`] therefore extends a cached hash in place and
385    /// still matches a transcript rebuilt from the same messages. The value is
386    /// an in-process cache key; it is never persisted or compared across
387    /// processes.
388    fn content_hash_for_messages(messages: &[SessionMessage]) -> u64 {
389        messages.iter().fold(0, Self::chained_content_hash)
390    }
391
392    /// Extends one transcript content hash with the next ordered message.
393    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
406/// Returns the durable message content for one kind.
407///
408/// User prompts preserve leading horizontal whitespace so pasted indentation
409/// survives persistence while outer line breaks and trailing whitespace are
410/// normalized. Assistant and activity rows remove outer whitespace, and
411/// workflow notices preserve spacing.
412pub 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
424/// Returns raw persisted message content with only outer whitespace removed.
425pub 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
433/// Normalizes prompt boundaries without consuming indentation on the first
434/// content line.
435fn 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;