Skip to main content

ag_session/
message.rs

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/// 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    /// Task-chain role answer encoded by [`AgentAnswerContent`]. Displayed in
21    /// chat but excluded from ordinary provider replay because the role keeps
22    /// its own isolated conversation.
23    AgentAnswer,
24    /// Live execution-graph marker whose content is only the owning task-chain
25    /// identity. Renderers project current chain state, so stored content
26    /// never goes stale; excluded from provider replay.
27    AgentGraph,
28    /// Raw assistant answer text without transcript padding.
29    AssistantAnswer,
30    /// Generic workflow notice emitted by Agentty session workflows.
31    WorkflowNotice,
32}
33
34impl SessionMessageKind {
35    /// Returns the stable database string for this message kind.
36    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    /// Returns whether this kind represents a raw conversation message that
49    /// belongs in the normal `session_message` store.
50    ///
51    /// Task-chain kinds are excluded: role answers belong to their own task
52    /// conversations, and graph markers carry no conversation text.
53    pub fn is_conversation_message(self) -> bool {
54        matches!(
55            self,
56            Self::UserPrompt | Self::AgentPrompt | Self::AssistantAnswer
57        )
58    }
59
60    /// Returns whether this kind starts one user-visible or generated turn.
61    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/// Error returned when a stored session message kind is unknown.
92#[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/// Role-attributed task-chain answer stored as
106/// [`SessionMessageKind::AgentAnswer`] content.
107///
108/// The durable encoding is one JSON object,
109/// `{"agent":"<TaskAgentRole::id>","text":"<answer>"}`, so arbitrary
110/// Markdown round-trips unchanged and new graph roles need only a new role
111/// identity rather than a new message kind.
112#[derive(Clone, Debug, Eq, PartialEq)]
113pub struct AgentAnswerContent {
114    /// Role that produced the answer.
115    pub agent: TaskAgentRole,
116    /// User-visible answer text, including any clarification questions.
117    pub text: String,
118}
119
120impl AgentAnswerContent {
121    /// Returns durable message content with outer text whitespace removed,
122    /// matching assistant-answer normalization.
123    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    /// Parses durable content, rejecting malformed JSON and unknown roles.
132    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/// One persisted transcript message for a session.
143#[derive(Clone, Debug, Eq, PartialEq)]
144pub struct SessionMessage {
145    /// Canonical transcript text for this message.
146    pub content: String,
147    /// Durable message category.
148    pub kind: SessionMessageKind,
149    /// Monotonic position within the owning session transcript.
150    pub position: i64,
151}
152
153impl SessionMessage {
154    /// Creates one transcript message at a stable transcript position.
155    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    /// Creates one raw user or assistant message using kind-specific storage
164    /// normalization.
165    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    /// Returns the decoded role answer for a well-formed
174    /// [`SessionMessageKind::AgentAnswer`] message.
175    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    /// Returns the task-chain identity referenced by a
184    /// [`SessionMessageKind::AgentGraph`] marker.
185    pub fn agent_graph_chain_id(&self) -> Option<&str> {
186        (self.kind == SessionMessageKind::AgentGraph).then_some(self.content.as_str())
187    }
188
189    /// Appends this message to a formatted transcript display buffer.
190    ///
191    /// Task-chain kinds render only in the chat UI; they never enter provider
192    /// replay or plain-text transcript projections.
193    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    /// Appends one raw user prompt using the session transcript marker and
209    /// spacing.
210    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    /// Returns true for raw clarification question rows like `1. Q: Need
248    /// tests?`.
249    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    /// Appends one raw assistant answer using session transcript spacing.
265    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/// Ordered transcript view assembled from persisted session messages.
277#[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    /// Creates an ordered transcript from persisted messages.
287    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    /// Creates an isolated projection for task-owned host effects. Messages
302    /// appended here must never enter the owning session's ordinary history.
303    pub fn ephemeral(messages: Vec<SessionMessage>) -> Self {
304        Self {
305            ephemeral: true,
306            ..Self::new(messages)
307        }
308    }
309
310    /// Whether host append operations may persist into ordinary session
311    /// history.
312    pub fn should_persist(&self) -> bool {
313        !self.ephemeral
314    }
315
316    /// Returns whether the transcript contains no saved messages.
317    pub fn is_empty(&self) -> bool {
318        self.messages.is_empty()
319    }
320
321    /// Returns the ordered transcript messages.
322    pub fn messages(&self) -> &[SessionMessage] {
323        &self.messages
324    }
325
326    /// Returns the cached content identity for render and projection caches.
327    pub fn content_hash(&self) -> u64 {
328        self.content_hash
329    }
330
331    /// Returns the total byte length of message content in this transcript.
332    pub fn total_content_len(&self) -> usize {
333        self.total_content_len
334    }
335
336    /// Appends one message after the ordered transcript tail using the same
337    /// content normalization as durable storage.
338    ///
339    /// [`Self::new`] sorts persisted input before this method derives the next
340    /// position, so the message slice and its cached content hash retain the
341    /// same ordering as a newly reconstructed transcript.
342    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    /// Returns formatted transcript text for replay when content exists.
359    ///
360    /// User and assistant rows store raw content, so replay injects the prompt
361    /// marker and transcript spacing only for display and provider replay.
362    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    /// Returns formatted user and assistant transcript text when any
372    /// conversation messages exist.
373    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    /// Formats an ordered message slice using canonical transcript display
392    /// markers and spacing.
393    ///
394    /// Unlike [`Self::new`], this method preserves the caller-provided order.
395    /// It is useful when rendering a selected subset of an existing transcript
396    /// without constructing another transcript aggregate.
397    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    /// Computes one ordered identity across message positions, kinds, and raw
408    /// content so render caches can compare transcripts without rescanning them
409    /// on every frame.
410    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
425/// Returns the durable message content for one kind.
426///
427/// User prompts preserve leading horizontal whitespace so pasted indentation
428/// survives persistence while outer line breaks and trailing whitespace are
429/// normalized. Assistant rows and role answers remove outer whitespace.
430/// Workflow notices preserve spacing, and graph markers preserve exact chain
431/// identities.
432pub 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
444/// Returns raw persisted message content with only outer whitespace removed.
445pub fn normalized_message_content(content: &str) -> String {
446    content.trim().to_string()
447}
448
449/// Wire shape behind [`AgentAnswerContent`].
450#[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
460/// Normalizes prompt boundaries without consuming indentation on the first
461/// content line.
462fn 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;