1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
use std::fmt;
use std::hash::Hasher;
use std::str::FromStr;
use rustc_hash::FxHasher;
use serde::{Deserialize, Serialize};
use crate::BuiltinAgentDefinition;
/// Durable category for one saved session transcript message.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SessionMessageKind {
/// Observed tool and skill usage, displayed but excluded from provider
/// replay.
ActivitySummary,
/// Raw user prompt text without TUI prompt markers or transcript padding.
UserPrompt,
/// Generated agent-facing prompt retained for replay but hidden from chat.
AgentPrompt,
/// Task-chain role answer encoded by [`AgentAnswerContent`]. Displayed in
/// chat but excluded from ordinary provider replay because the role keeps
/// its own isolated conversation.
AgentAnswer,
/// Live execution-graph marker whose content is only the owning task-chain
/// identity. Renderers project current chain state, so stored content
/// never goes stale; excluded from provider replay.
AgentGraph,
/// Raw assistant answer text without transcript padding.
AssistantAnswer,
/// Generic workflow notice emitted by Agentty session workflows.
WorkflowNotice,
}
impl SessionMessageKind {
/// Returns the stable database string for this message kind.
pub fn as_str(self) -> &'static str {
match self {
Self::ActivitySummary => "activity_summary",
Self::UserPrompt => "user_prompt",
Self::AgentPrompt => "agent_prompt",
Self::AgentAnswer => "agent_answer",
Self::AgentGraph => "agent_graph",
Self::AssistantAnswer => "assistant_answer",
Self::WorkflowNotice => "workflow_notice",
}
}
/// Returns whether this kind represents a raw conversation message that
/// belongs in the normal `session_message` store.
///
/// Task-chain kinds are excluded: role answers belong to their own task
/// conversations, and graph markers carry no conversation text.
pub fn is_conversation_message(self) -> bool {
matches!(
self,
Self::UserPrompt | Self::AgentPrompt | Self::AssistantAnswer
)
}
/// Returns whether this kind starts one user-visible or generated turn.
pub fn is_prompt(self) -> bool {
matches!(self, Self::UserPrompt | Self::AgentPrompt)
}
}
impl fmt::Display for SessionMessageKind {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
impl FromStr for SessionMessageKind {
type Err = SessionMessageKindParseError;
fn from_str(value: &str) -> Result<Self, Self::Err> {
match value {
"activity_summary" => Ok(Self::ActivitySummary),
"user_prompt" => Ok(Self::UserPrompt),
"agent_prompt" => Ok(Self::AgentPrompt),
"agent_answer" => Ok(Self::AgentAnswer),
"agent_graph" => Ok(Self::AgentGraph),
"assistant_answer" => Ok(Self::AssistantAnswer),
"workflow_notice" => Ok(Self::WorkflowNotice),
_ => Err(SessionMessageKindParseError {
value: value.to_string(),
}),
}
}
}
/// Error returned when a stored session message kind is unknown.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SessionMessageKindParseError {
value: String,
}
impl fmt::Display for SessionMessageKindParseError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "unknown session message kind `{}`", self.value)
}
}
impl std::error::Error for SessionMessageKindParseError {}
/// Role-attributed task-chain answer stored as
/// [`SessionMessageKind::AgentAnswer`] content.
///
/// The durable encoding is one JSON object,
/// `{"agent":"<BuiltinAgentDefinition::id>","text":"<answer>"}`, so arbitrary
/// Markdown round-trips unchanged and new graph roles need only a new role
/// identity rather than a new message kind.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AgentAnswerContent {
/// Role that produced the answer.
pub agent: BuiltinAgentDefinition,
/// User-visible answer text, including any clarification questions.
pub text: String,
}
impl AgentAnswerContent {
/// Returns durable message content with outer text whitespace removed,
/// matching assistant-answer normalization.
pub fn encode(&self) -> String {
serde_json::json!(EncodedAgentAnswer {
agent: self.agent.id().to_string(),
text: self.text.trim().to_string(),
})
.to_string()
}
/// Parses durable content, rejecting malformed JSON and unknown roles.
pub fn decode(content: &str) -> Option<Self> {
let encoded = serde_json::from_str::<EncodedAgentAnswer>(content).ok()?;
Some(Self {
agent: BuiltinAgentDefinition::from_id(&encoded.agent)?,
text: encoded.text,
})
}
}
/// One persisted transcript message for a session.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SessionMessage {
/// Canonical transcript text for this message.
pub content: String,
/// Durable message category.
pub kind: SessionMessageKind,
/// Monotonic position within the owning session transcript.
pub position: i64,
}
impl SessionMessage {
/// Creates one transcript message at a stable transcript position.
pub fn new(position: i64, kind: SessionMessageKind, content: impl Into<String>) -> Self {
Self {
content: content.into(),
kind,
position,
}
}
/// Creates one raw user or assistant message using kind-specific storage
/// normalization.
pub fn conversation(position: i64, kind: SessionMessageKind, content: impl AsRef<str>) -> Self {
Self {
content: stored_message_content(kind, content.as_ref()),
kind,
position,
}
}
/// Returns the decoded role answer for a well-formed
/// [`SessionMessageKind::AgentAnswer`] message.
pub fn agent_answer(&self) -> Option<AgentAnswerContent> {
if self.kind != SessionMessageKind::AgentAnswer {
return None;
}
AgentAnswerContent::decode(&self.content)
}
/// Returns the task-chain identity referenced by a
/// [`SessionMessageKind::AgentGraph`] marker.
pub fn agent_graph_chain_id(&self) -> Option<&str> {
(self.kind == SessionMessageKind::AgentGraph).then_some(self.content.as_str())
}
/// Appends this message to a formatted transcript display buffer.
///
/// Task-chain kinds render only in the chat UI; they never enter provider
/// replay or plain-text transcript projections.
fn append_display_text(&self, output: &mut String) {
match self.kind {
SessionMessageKind::ActivitySummary
| SessionMessageKind::AgentAnswer
| SessionMessageKind::AgentGraph => {}
SessionMessageKind::UserPrompt | SessionMessageKind::AgentPrompt => {
Self::append_user_prompt_display_text(output, &self.content);
}
SessionMessageKind::AssistantAnswer => {
Self::append_assistant_answer_display_text(output, &self.content);
}
SessionMessageKind::WorkflowNotice => output.push_str(&self.content),
}
}
/// Appends one raw user prompt using the session transcript marker and
/// spacing.
fn append_user_prompt_display_text(output: &mut String, content: &str) {
let content = normalized_user_prompt_content(content);
if content.trim().is_empty() {
return;
}
if !output.is_empty() {
output.push('\n');
}
let is_clarification_prompt = content
.lines()
.next()
.is_some_and(|line| line.trim() == CLARIFICATION_HEADER);
for (line_index, prompt_line) in content.split('\n').enumerate() {
if is_clarification_prompt
&& line_index > 0
&& Self::is_clarification_question_line(prompt_line)
{
output.push_str(USER_PROMPT_CONTINUATION_PREFIX);
output.push('\n');
}
if line_index == 0 {
output.push_str(USER_PROMPT_PREFIX);
} else {
output.push_str(USER_PROMPT_CONTINUATION_PREFIX);
}
output.push_str(prompt_line);
output.push('\n');
}
output.push('\n');
}
/// Returns true for raw clarification question rows like `1. Q: Need
/// tests?`.
fn is_clarification_question_line(line: &str) -> bool {
let trimmed_line = line.trim_start();
let digit_count = trimmed_line
.chars()
.take_while(char::is_ascii_digit)
.count();
if digit_count == 0 {
return false;
}
let (_, suffix) = trimmed_line.split_at(digit_count);
suffix.starts_with(". Q: ")
}
/// Appends one raw assistant answer using session transcript spacing.
fn append_assistant_answer_display_text(output: &mut String, content: &str) {
let content = content.trim();
if content.is_empty() {
return;
}
output.push_str(content);
output.push_str("\n\n");
}
}
/// Ordered transcript view assembled from persisted session messages.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct SessionTranscript {
content_hash: u64,
messages: Vec<SessionMessage>,
total_content_len: usize,
ephemeral: bool,
}
impl SessionTranscript {
/// Creates an ordered transcript from persisted messages.
pub fn new(mut messages: Vec<SessionMessage>) -> Self {
messages.sort_by_key(|message| message.position);
let content_hash = Self::content_hash_for_messages(&messages);
let total_content_len = messages.iter().map(|message| message.content.len()).sum();
Self {
content_hash,
messages,
total_content_len,
ephemeral: false,
}
}
/// Creates an isolated projection for task-owned host effects. Messages
/// appended here must never enter the owning session's ordinary history.
pub fn ephemeral(messages: Vec<SessionMessage>) -> Self {
Self {
ephemeral: true,
..Self::new(messages)
}
}
/// Whether host append operations may persist into ordinary session
/// history.
pub fn should_persist(&self) -> bool {
!self.ephemeral
}
/// Returns whether the transcript contains no saved messages.
pub fn is_empty(&self) -> bool {
self.messages.is_empty()
}
/// Returns the ordered transcript messages.
pub fn messages(&self) -> &[SessionMessage] {
&self.messages
}
/// Returns the cached content identity for render and projection caches.
pub fn content_hash(&self) -> u64 {
self.content_hash
}
/// Returns the total byte length of message content in this transcript.
pub fn total_content_len(&self) -> usize {
self.total_content_len
}
/// Appends one message after the ordered transcript tail using the same
/// content normalization as durable storage.
///
/// [`Self::new`] sorts persisted input before this method derives the next
/// position, so the message slice and its cached content hash retain the
/// same ordering as a newly reconstructed transcript.
pub fn append_message(&mut self, kind: SessionMessageKind, content: &str) {
let content = stored_message_content(kind, content);
if content.trim().is_empty() {
return;
}
let position = self
.messages
.last()
.map_or(0, |message| message.position.saturating_add(1));
self.total_content_len = self.total_content_len.saturating_add(content.len());
self.messages
.push(SessionMessage::new(position, kind, content));
self.content_hash = Self::content_hash_for_messages(&self.messages);
}
/// Returns formatted transcript text for replay when content exists.
///
/// User and assistant rows store raw content, so replay injects the prompt
/// marker and transcript spacing only for display and provider replay.
pub fn replay_text(&self) -> Option<String> {
let output = Self::display_text_for_messages(&self.messages);
if output.trim().is_empty() {
return None;
}
Some(output)
}
/// Returns formatted user and assistant transcript text when any
/// conversation messages exist.
pub fn conversation_replay_text(&self) -> Option<String> {
let mut output = String::new();
for message in self
.messages
.iter()
.filter(|message| message.kind.is_conversation_message())
{
message.append_display_text(&mut output);
}
if output.trim().is_empty() {
return None;
}
Some(output)
}
/// Formats an ordered message slice using canonical transcript display
/// markers and spacing.
///
/// Unlike [`Self::new`], this method preserves the caller-provided order.
/// It is useful when rendering a selected subset of an existing transcript
/// without constructing another transcript aggregate.
pub fn display_text_for_messages(messages: &[SessionMessage]) -> String {
let mut output = String::new();
for message in messages {
message.append_display_text(&mut output);
}
output
}
/// Computes one ordered identity across message positions, kinds, and raw
/// content so render caches can compare transcripts without rescanning them
/// on every frame.
fn content_hash_for_messages(messages: &[SessionMessage]) -> u64 {
let mut hasher = FxHasher::default();
for message in messages {
hasher.write_i64(message.position);
hasher.write(message.kind.as_str().as_bytes());
hasher.write_u8(0xff);
hasher.write(message.content.as_bytes());
hasher.write_u8(0xfe);
}
hasher.finish()
}
}
/// Returns the durable message content for one kind.
///
/// User prompts preserve leading horizontal whitespace so pasted indentation
/// survives persistence while outer line breaks and trailing whitespace are
/// normalized. Assistant rows and role answers remove outer whitespace.
/// Workflow notices preserve spacing, and graph markers preserve exact chain
/// identities.
pub fn stored_message_content(kind: SessionMessageKind, content: &str) -> String {
match kind {
SessionMessageKind::UserPrompt | SessionMessageKind::AgentPrompt => {
normalized_user_prompt_content(content)
}
SessionMessageKind::AssistantAnswer
| SessionMessageKind::ActivitySummary
| SessionMessageKind::AgentAnswer => normalized_message_content(content),
SessionMessageKind::AgentGraph | SessionMessageKind::WorkflowNotice => content.to_string(),
}
}
/// Returns raw persisted message content with only outer whitespace removed.
pub fn normalized_message_content(content: &str) -> String {
content.trim().to_string()
}
/// Wire shape behind [`AgentAnswerContent`].
#[derive(Deserialize, Serialize)]
struct EncodedAgentAnswer {
agent: String,
text: String,
}
const CLARIFICATION_HEADER: &str = "Clarifications:";
const USER_PROMPT_CONTINUATION_PREFIX: &str = " ";
const USER_PROMPT_PREFIX: &str = " › ";
/// Normalizes prompt boundaries without consuming indentation on the first
/// content line.
fn normalized_user_prompt_content(content: &str) -> String {
content
.trim_end()
.trim_start_matches(['\r', '\n'])
.to_string()
}
#[cfg(test)]
#[path = "message_test.rs"]
mod tests;