Skip to main content

mj_core/
transcript.rs

1//! Transcript data shared by the worker, controller state, and the chat UI.
2//!
3//! [`ChatEntry`] is what a worker snapshot carries in its transcript tail and
4//! what the chat view renders, and [`TranscriptItem`] is the materialized
5//! form controller state persists, so both live below the modules that use
6//! them rather than inside any one of them.
7//!
8//! The text helpers that read one of those shapes live here for the same
9//! reason: the database, the projection, controller state, the compactor and
10//! the review host all need the plain text of a stored message, and none of
11//! them should have to reach up into the chat view to get it.
12
13use std::sync::Arc;
14
15use agent_client_protocol::v1::schema::{
16    ContentBlock, ContentChunk, EmbeddedResourceResource, PlanEntryStatus, ToolCallStatus, ToolKind,
17};
18use anyhow::{Result, bail};
19use serde::{Deserialize, Serialize};
20
21pub const SESSION_RESTART_TEXT: &str = "[session restarted]";
22pub const SESSION_RESTART_ITEM_PREFIX: &str = "system:session-restarted:";
23pub const WORK_INTERRUPTED_ITEM_PREFIX: &str = "system:work-interrupted:";
24/// Marks where a turn the user cancelled stopped.
25pub const TURN_INTERRUPTED_TEXT: &str = "Interrupted";
26pub const TURN_INTERRUPTED_ITEM_PREFIX: &str = "system:turn-interrupted:";
27/// Marks the point where the harness resumed work with no prompt in flight.
28pub const HARNESS_TURN_TEXT: &str = "Agent continued on its own";
29pub const HARNESS_TURN_ITEM_PREFIX: &str = "harness-turn:";
30/// User replies within an existing turn, rather than prompts that start one.
31pub const ELICITATION_REPLY_ITEM_PREFIX: &str = "elicitation-reply:";
32
33/// Where a tool's compact presentation source came from.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(rename_all = "snake_case")]
36pub enum ToolSummarySourceKind {
37    RawInput,
38    RawOutput,
39    Title,
40}
41
42/// Bounded presentation metadata derived from an ACP tool call.
43#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44pub struct ToolCallPresentation {
45    pub summary: String,
46    pub source: String,
47    pub source_kind: ToolSummarySourceKind,
48    pub tool_kind: ToolKind,
49    /// Version of the parser rules that produced `summary`. A missing value
50    /// identifies presentation metadata written before parser versioning.
51    #[serde(default)]
52    pub summary_version: u8,
53}
54
55/// The current value of one logical transcript item. ACP structures whose
56/// schemas can grow are kept as JSON values, while logical item identity and
57/// lifecycle remain controller-owned and stable.
58#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
59#[serde(tag = "kind", rename_all = "snake_case")]
60pub enum TranscriptBody {
61    /// A complete message at the worker's durable delivery boundary.
62    Message {
63        event: Box<crate::mailbox::MailboxEvent>,
64    },
65    User {
66        content: Vec<serde_json::Value>,
67    },
68    Agent {
69        /// Complete ACP `ContentChunk` values, including message IDs, content
70        /// metadata, and non-text content blocks.
71        chunks: Vec<serde_json::Value>,
72        streaming: bool,
73    },
74    Thought {
75        /// Complete ACP `ContentChunk` values, including message IDs, content
76        /// metadata, and non-text content blocks.
77        chunks: Vec<serde_json::Value>,
78        streaming: bool,
79    },
80    Tool {
81        /// Complete current ACP `ToolCall`, updated field-for-field as
82        /// `ToolCallUpdate` notifications arrive.
83        call: serde_json::Value,
84        /// Output of the terminals this call's content refers to. It is a
85        /// sibling of `call` rather than part of it because `ToolCall::update`
86        /// replaces `content` wholesale, which would discard anything injected
87        /// into the stored ACP value.
88        #[serde(default, skip_serializing_if = "Vec::is_empty")]
89        terminal_outputs: Vec<TerminalOutputRecord>,
90        /// Every terminal this call has ever referred to. Agents that replace
91        /// `content` wholesale can drop a terminal reference before the
92        /// terminal is reaped, so the current call is not enough to decide
93        /// where a terminal's output belongs.
94        #[serde(default, skip_serializing_if = "Vec::is_empty")]
95        terminal_refs: Vec<String>,
96        /// Cached label data used by Rich and browser projections. Older
97        /// transcript items omit this and derive it from `call` when read.
98        #[serde(default, skip_serializing_if = "Option::is_none")]
99        presentation: Option<Box<ToolCallPresentation>>,
100    },
101    /// Terminal output that no tool call refers to yet. It becomes a
102    /// `Tool` item's `terminal_outputs` entry as soon as a call naming the
103    /// terminal arrives, and stays here permanently otherwise so output is
104    /// never dropped.
105    TerminalOutput {
106        record: TerminalOutputRecord,
107    },
108    Plan {
109        /// Complete current ACP `Plan`, including entry priorities and all
110        /// plan- and entry-level metadata.
111        plan: serde_json::Value,
112    },
113    /// A plan the harness asked the user to approve, captured where the
114    /// decision happened so it renders inline and survives restart and export.
115    ///
116    /// It is a record of the proposal, not conversation input: Hel never
117    /// replays it to a model as a user or agent message.
118    PlanProposal {
119        /// Identity of the plan review that carried this proposal.
120        proposal_id: String,
121        /// Exact proposal text the harness sent.
122        plan: String,
123    },
124    System {
125        text: String,
126    },
127}
128
129/// Append one ACP `ContentChunk` value to a transcript item's chunk list,
130/// merging it into the previous chunk when the two are the same text stream.
131///
132/// Agents stream text one token at a time, so a long turn arrives as
133/// thousands of chunks that differ only in `content.text`. Stored separately
134/// they cost far more memory than the text they carry: each chunk is its own
135/// pair of nested `serde_json::Value` maps. Merging them keeps one chunk per
136/// run of text, which is what every reader of `chunks` already reconstructs.
137///
138/// Two chunks merge only when nothing but the text differs: both are objects
139/// whose `content.type` is `"text"` with a string `content.text`, their
140/// `messageId` values are equal (both absent counts as equal), and every
141/// other top-level key (such as `meta`) and every other `content` key (such
142/// as `annotations`) is identical. Anything else is pushed as its own chunk.
143pub fn push_content_chunk(chunks: &mut Vec<serde_json::Value>, chunk: serde_json::Value) {
144    if chunks
145        .last()
146        .is_some_and(|last| text_chunks_mergeable(last, &chunk))
147    {
148        let addition = chunk
149            .get("content")
150            .and_then(|content| content.get("text"))
151            .and_then(serde_json::Value::as_str)
152            .unwrap_or_default()
153            .to_owned();
154        if let Some(serde_json::Value::Object(last)) = chunks.last_mut()
155            && let Some(serde_json::Value::Object(content)) = last.get_mut("content")
156            && let Some(serde_json::Value::String(text)) = content.get_mut("text")
157        {
158            text.push_str(&addition);
159            return;
160        }
161    }
162    chunks.push(chunk);
163}
164
165/// Collapse runs of per-token text chunks that were stored before they were
166/// merged on the way in. Rebuilds the list through [`push_content_chunk`], so
167/// it applies exactly the same merge rule and leaves chunk boundaries that
168/// carry real differences (a new message ID, non-text content, differing
169/// metadata) where they are.
170pub fn coalesce_content_chunks(chunks: &mut Vec<serde_json::Value>) {
171    if chunks.len() < 2 {
172        return;
173    }
174    let mut merged = Vec::with_capacity(chunks.len());
175    for chunk in std::mem::take(chunks) {
176        push_content_chunk(&mut merged, chunk);
177    }
178    merged.shrink_to_fit();
179    *chunks = merged;
180}
181
182/// Whether `next` carries only more text for the same stream as `last`, so
183/// the two can share one chunk. The single definition of the merge rule used
184/// by both [`push_content_chunk`] and [`coalesce_content_chunks`].
185fn text_chunks_mergeable(last: &serde_json::Value, next: &serde_json::Value) -> bool {
186    let (serde_json::Value::Object(last), serde_json::Value::Object(next)) = (last, next) else {
187        return false;
188    };
189    let (
190        Some(serde_json::Value::Object(last_content)),
191        Some(serde_json::Value::Object(next_content)),
192    ) = (last.get("content"), next.get("content"))
193    else {
194        return false;
195    };
196    let is_text = |content: &serde_json::Map<String, serde_json::Value>| {
197        content.get("type").and_then(serde_json::Value::as_str) == Some("text")
198            && content
199                .get("text")
200                .is_some_and(serde_json::Value::is_string)
201    };
202    if !is_text(last_content) || !is_text(next_content) {
203        return false;
204    }
205    // Every other top-level key, `messageId` and `meta` included, must match.
206    if last.len() != next.len()
207        || !last
208            .iter()
209            .all(|(key, value)| key == "content" || next.get(key) == Some(value))
210    {
211        return false;
212    }
213    // ... as must every other content key, such as `annotations`.
214    last_content.len() == next_content.len()
215        && last_content
216            .iter()
217            .all(|(key, value)| key == "text" || next_content.get(key) == Some(value))
218}
219
220/// What one client-run terminal produced, as hel recorded it when the child
221/// was reaped. `exit_code` and `signal` mirror ACP `TerminalExitStatus`; both
222/// are `None` when the terminal was released before a status was observed.
223#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
224pub struct TerminalOutputRecord {
225    pub terminal_id: String,
226    pub output: String,
227    #[serde(default, skip_serializing_if = "is_false")]
228    pub truncated: bool,
229    #[serde(default, skip_serializing_if = "Option::is_none")]
230    pub exit_code: Option<u32>,
231    #[serde(default, skip_serializing_if = "Option::is_none")]
232    pub signal: Option<String>,
233}
234
235impl TerminalOutputRecord {
236    /// Whether the command ended the way a caller asked for: exit status zero
237    /// and no signal. Anything else — a nonzero exit, a signal, or no status at
238    /// all because the terminal was released before one was observed — is
239    /// abnormal, and stays visible in every render mode.
240    pub fn exited_cleanly(&self) -> bool {
241        self.exit_code == Some(0) && self.signal.is_none()
242    }
243
244    /// Whether a completed ACP tool's provider-specific raw result is this
245    /// child result. Kimi reports shell output as a byte array beside its exit
246    /// status but omits the ACP terminal reference, so the exact result is the
247    /// only ownership information it publishes.
248    pub fn matches_tool_raw_result(&self, call: &serde_json::Value) -> bool {
249        if !matches!(
250            call.get("status").and_then(serde_json::Value::as_str),
251            Some("completed" | "failed")
252        ) {
253            return false;
254        }
255        let Some(raw) = call.get("rawOutput") else {
256            return false;
257        };
258        let Some(exit_code) = raw
259            .get("exit_code")
260            .and_then(serde_json::Value::as_u64)
261            .and_then(|code| u32::try_from(code).ok())
262        else {
263            return false;
264        };
265        if self.exit_code != Some(exit_code) || self.signal.is_some() {
266            return false;
267        }
268        match raw.get("output") {
269            Some(serde_json::Value::Array(bytes)) => {
270                bytes.len() == self.output.len()
271                    && bytes
272                        .iter()
273                        .zip(self.output.as_bytes())
274                        .all(|(value, byte)| value.as_u64() == Some(u64::from(*byte)))
275            }
276            Some(serde_json::Value::String(output)) => output == &self.output,
277            _ => false,
278        }
279    }
280}
281
282#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
283#[serde(deny_unknown_fields)]
284pub struct TranscriptItem {
285    pub stable_id: String,
286    /// Ordinal of the relay event that first created this logical item.
287    pub position: u64,
288    /// Ordinal of the most recent content chunk for an agent message. This is
289    /// `None` for every other logical item.
290    pub latest_content_event_ordinal: Option<u64>,
291    pub created_at_ms: i64,
292    pub last_changed_at_ms: i64,
293    pub body: TranscriptBody,
294}
295
296impl TranscriptItem {
297    pub fn is_work_interruption(&self) -> bool {
298        self.stable_id.starts_with(WORK_INTERRUPTED_ITEM_PREFIX)
299    }
300
301    pub fn is_session_restart(&self) -> bool {
302        self.stable_id.starts_with(SESSION_RESTART_ITEM_PREFIX)
303    }
304
305    /// The relay ordinal a reader pages by.
306    ///
307    /// An agent message is rewritten as its content streams in, and its
308    /// `latest_content_event_ordinal` is where that stopped, so paging by it
309    /// hands a caller the finished message once instead of the partial one it
310    /// was created with. Every other body is created once, so its position is
311    /// its sequence.
312    pub fn seq(&self) -> u64 {
313        self.latest_content_event_ordinal.unwrap_or(self.position)
314    }
315
316    /// A submitted prompt, excluding replies within an existing turn.
317    pub fn is_user_prompt(&self) -> bool {
318        matches!(self.body, TranscriptBody::User { .. })
319            && !self.stable_id.starts_with(ELICITATION_REPLY_ITEM_PREFIX)
320    }
321
322    /// Whether this item begins a turn: a user prompt, or the marker for a
323    /// turn the harness started on its own. The recovery boundary and the
324    /// scope of a plan update both key on the newest of these.
325    pub fn is_turn_start(&self) -> bool {
326        self.is_user_prompt() || self.stable_id.starts_with(HARNESS_TURN_ITEM_PREFIX)
327    }
328
329    pub fn is_nonempty_agent_message(&self) -> bool {
330        let TranscriptBody::Agent { chunks, .. } = &self.body else {
331            return false;
332        };
333        chunks.iter().any(|chunk| {
334            let Some(content) = chunk.get("content") else {
335                return false;
336            };
337            match content.get("type").and_then(serde_json::Value::as_str) {
338                Some("text") => content
339                    .get("text")
340                    .and_then(serde_json::Value::as_str)
341                    .is_some_and(|text| !text.trim().is_empty()),
342                Some(_) => true,
343                None => false,
344            }
345        })
346    }
347
348    pub fn validate(&self, through: u64) -> Result<()> {
349        if self.stable_id.trim().is_empty() {
350            bail!("materialized transcript item has an empty stable id");
351        }
352        if self.position == 0 || self.position > through {
353            bail!(
354                "materialized transcript item {:?} has invalid position {} at frontier {through}",
355                self.stable_id,
356                self.position
357            );
358        }
359        match (&self.body, self.latest_content_event_ordinal) {
360            (TranscriptBody::Agent { .. }, Some(ordinal))
361                if ordinal >= self.position && ordinal <= through => {}
362            (TranscriptBody::Agent { .. }, Some(ordinal)) => bail!(
363                "materialized agent message {:?} has invalid latest content ordinal {ordinal} at position {} and frontier {through}",
364                self.stable_id,
365                self.position
366            ),
367            (TranscriptBody::Agent { .. }, None) => bail!(
368                "materialized agent message {:?} has no latest content ordinal",
369                self.stable_id
370            ),
371            (_, Some(ordinal)) => bail!(
372                "non-agent transcript item {:?} has latest content ordinal {ordinal}",
373                self.stable_id
374            ),
375            (_, None) => {}
376        }
377        if let TranscriptBody::Message { event } = &self.body {
378            anyhow::ensure!(
379                !event.key.trim().is_empty()
380                    && event.message_text().is_some()
381                    && self.stable_id == message_item_id(&event.key),
382                "invalid message transcript entry {:?}",
383                self.stable_id
384            );
385        }
386        if self.last_changed_at_ms < self.created_at_ms {
387            bail!(
388                "materialized transcript item {:?} changed before it was created",
389                self.stable_id
390            );
391        }
392        Ok(())
393    }
394}
395
396#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
397pub enum ChatRole {
398    User,
399    Agent,
400    Message,
401    /// Agent reasoning stream, rendered dimmed.
402    Thought,
403    /// Tool invocation titles.
404    Tool,
405    /// Current agent plan.
406    Plan,
407    /// A plan proposal awaiting, or already given, a decision.
408    PlanProposal,
409    System,
410}
411
412#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
413pub struct ChatEntry {
414    #[serde(default)]
415    pub start_seq: u64,
416    pub seq: u64,
417    pub role: ChatRole,
418    pub text: String,
419    pub recorded_at_ms: Option<i64>,
420    /// When a finished tool call last changed, which is when it ended.
421    /// `None` for a call still running and for every other role.
422    #[serde(default, skip_serializing_if = "Option::is_none")]
423    pub tool_ended_at_ms: Option<i64>,
424    pub revision: u64,
425    pub message_id: Option<String>,
426    #[serde(default, skip_serializing_if = "Option::is_none")]
427    pub incoming_message: Option<Box<crate::mailbox::MailboxEvent>>,
428    pub tool_call_id: Option<String>,
429    pub tool_status: Option<ToolStatus>,
430    /// Compact label used by Rich and browser projections. `text` remains the
431    /// original provider title for Raw mode.
432    #[serde(default, skip_serializing_if = "Option::is_none")]
433    pub tool_summary: Option<String>,
434    /// Selected bounded source retained so partial ACP updates can preserve a
435    /// raw-command-derived summary without retaining arbitrary raw JSON.
436    #[serde(default, skip_serializing_if = "Option::is_none")]
437    pub tool_presentation: Option<ToolCallPresentation>,
438    /// ACP arguments, kept separately so result updates cannot erase them.
439    #[serde(default, skip_serializing_if = "Option::is_none")]
440    pub tool_input: Option<serde_json::Value>,
441    /// A diagnostic reported in ACP `rawOutput.error`, kept separate from
442    /// textual tool content so partial result updates can replace it.
443    #[serde(default, skip_serializing_if = "Option::is_none")]
444    pub tool_error: Option<String>,
445    pub tool_content: Vec<String>,
446    pub tool_diffstats: Vec<String>,
447    pub tool_locations: Vec<String>,
448    pub plan: Vec<PlanLine>,
449    #[serde(default, skip_serializing_if = "is_false")]
450    pub leading_omitted: bool,
451    /// Detail the decluttered feed leaves out: the entry renders only in the
452    /// raw transcript mode. Set once, when the entry is built, because Alt-T
453    /// switches render mode without rebuilding entries.
454    #[serde(default, skip_serializing_if = "is_false")]
455    pub raw_only: bool,
456    /// A completed tool call whose turn was interrupted while it ran. The
457    /// harness kept the command going and it ended later on its own, so its
458    /// completion is not the agent's finished work.
459    #[serde(default, skip_serializing_if = "is_false")]
460    pub ended_after_interrupt: bool,
461    /// The materialized transcript item this entry was derived from, when it
462    /// came from the controller's projection. Provenance only, so it is
463    /// neither serialized nor part of the entry's value.
464    #[serde(skip)]
465    pub source: TranscriptSource,
466}
467
468/// Handle on the transcript item an entry was derived from. Unchanged items
469/// keep the same `Arc` from one projection to the next, so a pointer
470/// comparison replaces re-reading the item and re-parsing its JSON.
471///
472/// The handle records where an entry came from, not what it says, so two
473/// entries with equal content are equal whatever they were derived from.
474#[derive(Debug, Clone, Default)]
475pub struct TranscriptSource(pub Option<Arc<TranscriptItem>>);
476
477impl TranscriptSource {
478    pub fn is(&self, item: &Arc<TranscriptItem>) -> bool {
479        self.0
480            .as_ref()
481            .is_some_and(|source| Arc::ptr_eq(source, item))
482    }
483}
484
485impl PartialEq for TranscriptSource {
486    fn eq(&self, _other: &Self) -> bool {
487        true
488    }
489}
490
491impl Eq for TranscriptSource {}
492
493impl ChatEntry {
494    pub fn received_message(seq: u64, event: &crate::mailbox::MailboxEvent) -> Self {
495        let mut entry = Self::plain(
496            seq,
497            ChatRole::Message,
498            event
499                .message_text()
500                .expect("message entry carries a message event"),
501        );
502        entry.message_id = Some(message_item_id(&event.key));
503        entry.incoming_message = Some(Box::new(event.clone()));
504        entry
505    }
506
507    /// Whether this entry is the durable marker emitted when a session's
508    /// control plane restarts. The source identity is authoritative for
509    /// materialized entries; the role/text check also covers entries built
510    /// from older worker snapshots that have no materialized source handle.
511    pub fn is_session_restart(&self) -> bool {
512        self.source
513            .0
514            .as_ref()
515            .is_some_and(|item| item.is_session_restart())
516            || (self.role == ChatRole::System && self.text == SESSION_RESTART_TEXT)
517    }
518
519    /// Whether this entry is a message the user wrote, including an answer
520    /// to an agent's question. Prompts that Mjolnir submits on the user's
521    /// behalf are excluded: every [`crate::continuation::GeneratedPrompt`]
522    /// and text marked as generated. Authorization evidence asks the same
523    /// two predicates, so the two cannot disagree.
524    pub fn is_user_authored(&self) -> bool {
525        // An entry without a source is a prompt submitted from this client
526        // that the controller has not yet projected.
527        self.role == ChatRole::User
528            && crate::continuation::is_user_authored_message(
529                self.source.0.as_ref().map(|item| item.stable_id.as_str()),
530                &self.text,
531            )
532    }
533
534    pub fn plan(seq: u64, plan: Vec<PlanLine>) -> Self {
535        Self {
536            start_seq: seq,
537            seq,
538            role: ChatRole::Plan,
539            text: String::new(),
540            recorded_at_ms: None,
541            tool_ended_at_ms: None,
542            revision: 0,
543            message_id: None,
544            incoming_message: None,
545            tool_call_id: None,
546            tool_status: None,
547            tool_summary: None,
548            tool_presentation: None,
549            tool_input: None,
550            tool_error: None,
551            tool_content: Vec::new(),
552            tool_diffstats: Vec::new(),
553            tool_locations: Vec::new(),
554            plan,
555            leading_omitted: false,
556            raw_only: false,
557            ended_after_interrupt: false,
558            source: TranscriptSource::default(),
559        }
560    }
561
562    pub fn touch(&mut self, seq: u64) {
563        self.seq = seq;
564        self.revision = self.revision.wrapping_add(1);
565    }
566
567    /// Bound one entry to the sizes the dashboard's summary tolerates.
568    ///
569    /// Compiled unconditionally and hidden from the documentation because the
570    /// chat crate's tests need it, and a `#[cfg(test)]` item is invisible to
571    /// another crate.
572    #[doc(hidden)]
573    pub fn bounded_for_dashboard(mut self) -> Self {
574        self.bound_dashboard_content();
575        self
576    }
577
578    fn bound_dashboard_content(&mut self) {
579        const TEXT_BYTES: usize = 64 * 1024;
580        const DETAIL_BYTES: usize = 2 * 1024;
581        const DETAIL_COUNT: usize = 8;
582
583        self.leading_omitted |= truncate_string_start(&mut self.text, TEXT_BYTES);
584        // Dashboard summaries do not expand tool arguments.
585        self.tool_input = None;
586        if let Some(error) = &mut self.tool_error {
587            truncate_string_start(error, DETAIL_BYTES);
588        }
589        for values in [
590            &mut self.tool_content,
591            &mut self.tool_diffstats,
592            &mut self.tool_locations,
593        ] {
594            values.truncate(DETAIL_COUNT);
595            for value in values {
596                truncate_string_start(value, DETAIL_BYTES);
597            }
598        }
599        if let Some(summary) = &mut self.tool_summary {
600            truncate_string_start(summary, DETAIL_BYTES);
601        }
602        if let Some(presentation) = &mut self.tool_presentation {
603            truncate_string_start(&mut presentation.summary, DETAIL_BYTES);
604            truncate_string_start(&mut presentation.source, TEXT_BYTES);
605        }
606        self.plan.truncate(DETAIL_COUNT);
607        for line in &mut self.plan {
608            truncate_string_start(&mut line.text, DETAIL_BYTES);
609        }
610    }
611
612    pub fn with_recorded_at(mut self, recorded_at_ms: Option<i64>) -> Self {
613        self.recorded_at_ms = recorded_at_ms;
614        self
615    }
616}
617
618/// Constructors that sanitize the text they are given, so terminal escape
619/// sequences from a harness never reach a transcript entry.
620impl ChatEntry {
621    pub fn plain(seq: u64, role: ChatRole, text: impl Into<String>) -> Self {
622        Self {
623            start_seq: seq,
624            seq,
625            role,
626            text: sanitize_terminal_text(&text.into()),
627            recorded_at_ms: None,
628            tool_ended_at_ms: None,
629            revision: 0,
630            message_id: None,
631            incoming_message: None,
632            tool_call_id: None,
633            tool_status: None,
634            tool_summary: None,
635            tool_presentation: None,
636            tool_input: None,
637            tool_error: None,
638            tool_content: Vec::new(),
639            tool_diffstats: Vec::new(),
640            tool_locations: Vec::new(),
641            plan: Vec::new(),
642            leading_omitted: false,
643            raw_only: false,
644            ended_after_interrupt: false,
645            source: TranscriptSource::default(),
646        }
647    }
648
649    pub fn tool(
650        seq: u64,
651        title: impl Into<String>,
652        tool_call_id: Option<String>,
653        tool_status: ToolStatus,
654    ) -> Self {
655        Self {
656            start_seq: seq,
657            seq,
658            role: ChatRole::Tool,
659            text: sanitize_terminal_text(&title.into()),
660            recorded_at_ms: None,
661            tool_ended_at_ms: None,
662            revision: 0,
663            message_id: None,
664            incoming_message: None,
665            tool_call_id,
666            tool_status: Some(tool_status),
667            tool_summary: None,
668            tool_presentation: None,
669            tool_input: None,
670            tool_error: None,
671            tool_content: Vec::new(),
672            tool_diffstats: Vec::new(),
673            tool_locations: Vec::new(),
674            plan: Vec::new(),
675            leading_omitted: false,
676            raw_only: false,
677            ended_after_interrupt: false,
678            source: TranscriptSource::default(),
679        }
680    }
681}
682
683pub(crate) fn is_false(value: &bool) -> bool {
684    !*value
685}
686
687pub fn plan_status(status: &PlanEntryStatus) -> PlanStatus {
688    match status {
689        PlanEntryStatus::InProgress => PlanStatus::Running,
690        PlanEntryStatus::Completed => PlanStatus::Completed,
691        _ => PlanStatus::Pending,
692    }
693}
694
695/// Remove terminal controls while preserving user-visible whitespace.
696pub fn sanitize_terminal_text(text: &str) -> String {
697    let mut sanitized = String::with_capacity(text.len());
698    let mut chars = text.chars().peekable();
699    while let Some(ch) = chars.next() {
700        if ch == '\x1b' {
701            // One escape can end at the ESC introducing the next one, so keep
702            // consuming rather than recursing: transcript text is untrusted and
703            // may nest these arbitrarily deep.
704            while consume_escape_body(&mut chars) {}
705        } else if ch == '\r' {
706            if chars.peek() != Some(&'\n') {
707                sanitized.push('\n');
708            }
709        } else if matches!(ch, '\n' | '\t') || !ch.is_control() {
710            sanitized.push(ch);
711        }
712    }
713    sanitized
714}
715
716/// Consume one escape sequence's body, after its introducing ESC. Returns
717/// whether the body ended at another ESC, which introduces the next sequence.
718///
719/// Dropping the ESC alone is not enough: an OSC payload (a build tool setting
720/// the window title) or the second byte of a charset selection would otherwise
721/// reach the transcript as visible text.
722fn consume_escape_body(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) -> bool {
723    match chars.next() {
724        // CSI: parameter and intermediate bytes up to a final byte.
725        Some('[') => {
726            let _ = chars.find(|ch| ('@'..='~').contains(ch));
727            false
728        }
729        // OSC, DCS, SOS, PM, and APC all carry a string payload.
730        Some(']' | 'P' | 'X' | '^' | '_') => consume_string_body(chars),
731        // Two-byte sequences: charset selection (ESC ( B), ESC # 8, ESC SP F.
732        Some('(' | ')' | '*' | '+' | '-' | '.' | '/' | '#' | '%' | ' ') => {
733            chars.next();
734            false
735        }
736        // Everything else is a complete one-byte escape: ESC 7, ESC 8, ESC M,
737        // ESC =, and a trailing ESC with nothing after it.
738        _ => false,
739    }
740}
741
742/// Consume a string payload, which ends at BEL or at ST (ESC \). A line break
743/// or a cancel control aborts it instead, so one malformed OSC cannot swallow
744/// the rest of a transcript.
745fn consume_string_body(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) -> bool {
746    while let Some(&ch) = chars.peek() {
747        match ch {
748            '\n' | '\r' | '\x18' | '\x1a' => return false,
749            '\x07' => {
750                chars.next();
751                return false;
752            }
753            '\x1b' => {
754                chars.next();
755                return true;
756            }
757            _ => {
758                chars.next();
759            }
760        }
761    }
762    false
763}
764
765pub fn materialized_content_text(content: &[serde_json::Value]) -> String {
766    let text = content
767        .iter()
768        .map(materialized_value_text)
769        .filter(|text| !text.is_empty())
770        .collect::<Vec<_>>()
771        .join("\n");
772    crate::relay::strip_hidden_prompt_context(&text).to_owned()
773}
774
775/// What produced a transcript item, as a stable wire name.
776///
777/// The chat view has its own role enum shaped around how it renders; this is
778/// the name the HTTP API publishes, so it changes only when the transcript
779/// model does.
780#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
781#[serde(rename_all = "snake_case")]
782pub enum TranscriptRole {
783    User,
784    Agent,
785    Message,
786    Thought,
787    Tool,
788    Terminal,
789    Plan,
790    PlanProposal,
791    System,
792}
793
794impl TranscriptRole {
795    pub fn as_str(self) -> &'static str {
796        match self {
797            Self::User => "user",
798            Self::Agent => "agent",
799            Self::Message => "message",
800            Self::Thought => "thought",
801            Self::Tool => "tool",
802            Self::Terminal => "terminal",
803            Self::Plan => "plan",
804            Self::PlanProposal => "plan_proposal",
805            Self::System => "system",
806        }
807    }
808    pub fn storage_kind(self) -> &'static str {
809        match self {
810            Self::Terminal => "terminal_output",
811            other => other.as_str(),
812        }
813    }
814}
815
816pub fn transcript_item_role(body: &TranscriptBody) -> &'static str {
817    let role = match body {
818        TranscriptBody::User { .. } => TranscriptRole::User,
819        TranscriptBody::Agent { .. } => TranscriptRole::Agent,
820        TranscriptBody::Message { .. } => TranscriptRole::Message,
821        TranscriptBody::Thought { .. } => TranscriptRole::Thought,
822        TranscriptBody::Tool { .. } => TranscriptRole::Tool,
823        TranscriptBody::TerminalOutput { .. } => TranscriptRole::Terminal,
824        TranscriptBody::Plan { .. } => TranscriptRole::Plan,
825        TranscriptBody::PlanProposal { .. } => TranscriptRole::PlanProposal,
826        TranscriptBody::System { .. } => TranscriptRole::System,
827    };
828    role.as_str()
829}
830
831pub fn message_item_id(event_key: &str) -> String {
832    format!("message:{event_key}")
833}
834
835pub fn materialized_chunks_text(chunks: &[serde_json::Value]) -> String {
836    chunks
837        .iter()
838        .filter_map(|value| match ContentChunk::deserialize(value) {
839            Ok(chunk) => Some(chunk),
840            Err(error) => {
841                tracing::warn!(%error, "could not decode a stored content chunk");
842                None
843            }
844        })
845        .filter_map(|chunk| content_block_text(&chunk.content))
846        .map(|text| sanitize_terminal_text(&text))
847        .collect::<Vec<_>>()
848        .join("")
849}
850
851fn materialized_value_text(value: &serde_json::Value) -> String {
852    if let Ok(block) = ContentBlock::deserialize(value)
853        && let Some(text) = content_block_text(&block)
854    {
855        return sanitize_terminal_text(&text);
856    }
857    if let Some(text) = value.as_str() {
858        return sanitize_terminal_text(text);
859    }
860    sanitize_terminal_text(&serde_json::to_string(value).unwrap_or_else(|_| "[content]".into()))
861}
862
863pub fn tool_status(status: &ToolCallStatus) -> ToolStatus {
864    match status {
865        ToolCallStatus::InProgress => ToolStatus::Running,
866        ToolCallStatus::Completed => ToolStatus::Completed,
867        ToolCallStatus::Failed => ToolStatus::Failed,
868        _ => ToolStatus::Pending,
869    }
870}
871
872pub fn content_block_text(content: &ContentBlock) -> Option<String> {
873    match content {
874        ContentBlock::Text(text) => Some(text.text.clone()),
875        ContentBlock::Image(_) => Some("[image]".into()),
876        ContentBlock::Audio(_) => Some("[audio]".into()),
877        ContentBlock::ResourceLink(link) => Some(format!("[{}]({})", link.name, link.uri)),
878        ContentBlock::Resource(resource) => Some(match &resource.resource {
879            EmbeddedResourceResource::TextResourceContents(resource) => resource.text.clone(),
880            EmbeddedResourceResource::BlobResourceContents(resource) => {
881                format!("[embedded resource: {}]", resource.uri)
882            }
883            _ => "[embedded resource]".into(),
884        }),
885        _ => None,
886    }
887}
888
889pub fn truncate_string_start(value: &mut String, maximum_bytes: usize) -> bool {
890    if value.len() <= maximum_bytes {
891        return false;
892    }
893    let mut start = value.len() - maximum_bytes;
894    while !value.is_char_boundary(start) {
895        start += 1;
896    }
897    value.drain(..start);
898    true
899}
900
901/// The ACP tool states needed to keep a compact tool block visually useful.
902#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
903pub enum ToolStatus {
904    Pending,
905    Running,
906    Completed,
907    Failed,
908}
909
910#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
911pub enum PlanStatus {
912    Pending,
913    Running,
914    Completed,
915}
916
917#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
918pub struct PlanLine {
919    pub text: String,
920    pub status: PlanStatus,
921}
922
923#[cfg(test)]
924mod tests {
925    use super::*;
926    use serde_json::json;
927
928    fn text_chunk(text: &str, message_id: Option<&str>) -> serde_json::Value {
929        match message_id {
930            Some(id) => json!({"content": {"type": "text", "text": text}, "messageId": id}),
931            None => json!({"content": {"type": "text", "text": text}}),
932        }
933    }
934
935    fn sourced_user_entry(stable_id: &str, text: &str) -> ChatEntry {
936        let mut entry = ChatEntry::plain(1, ChatRole::User, text);
937        entry.source = TranscriptSource(Some(Arc::new(TranscriptItem {
938            stable_id: stable_id.into(),
939            position: 1,
940            latest_content_event_ordinal: None,
941            created_at_ms: 0,
942            last_changed_at_ms: 0,
943            body: TranscriptBody::User {
944                content: vec![json!({"type": "text", "text": text})],
945            },
946        })));
947        entry
948    }
949
950    #[test]
951    fn only_messages_the_user_wrote_are_user_authored() {
952        for (stable_id, text) in [
953            ("user:prompt-7", "fix the build"),
954            ("user:2", "a prompt recovered by position"),
955            ("elicitation-reply:9", "Yes"),
956        ] {
957            assert!(
958                sourced_user_entry(stable_id, text).is_user_authored(),
959                "{stable_id}"
960            );
961        }
962        assert!(ChatEntry::plain(1, ChatRole::User, "not yet projected").is_user_authored());
963        for (stable_id, text) in [
964            ("user:auto-continue-1-1", "Continue."),
965            ("user:quota-retry-4", "Continue."),
966            ("user:server-retry-5", "Continue."),
967            ("user:review-forward-2", "Review findings"),
968            // Hard-won: 8b08e8bc1: handback reminders and peer-session messages counted as user authorization
969            ("user:handback-reminder-36", "Please also update the docs"),
970            ("user:subagent-input-3", "A sub-agent finished."),
971            (
972                "user:session-message-turn-8",
973                "Message from another session",
974            ),
975            ("user:prompt-9", "[HARNESS NOTE: summarize the request]"),
976            (
977                "user:prompt-10",
978                crate::continuation::PARENT_WAIT_PROMPT_TEXT,
979            ),
980        ] {
981            assert!(
982                !sourced_user_entry(stable_id, text).is_user_authored(),
983                "{stable_id}"
984            );
985        }
986        assert!(!ChatEntry::plain(1, ChatRole::Agent, "a reply").is_user_authored());
987    }
988
989    // Hard-won: ff088d42: A 15,000-chunk thought made daemon RSS grow from gigabytes of stored JSON into many gigabytes.
990    #[test]
991    fn push_content_chunk_merges_adjacent_text_for_the_same_message_id() {
992        let mut chunks = vec![text_chunk("x", Some("m1"))];
993        for _ in 1..15_001 {
994            push_content_chunk(&mut chunks, text_chunk("x", Some("m1")));
995        }
996        assert_eq!(chunks, vec![text_chunk(&"x".repeat(15_001), Some("m1"))]);
997    }
998
999    #[test]
1000    fn push_content_chunk_keeps_chunks_from_different_message_ids_apart() {
1001        let image = json!({"content": {"type": "image", "data": "abc", "mimeType": "image/png"}});
1002        let mut chunks = vec![text_chunk("first", Some("m1"))];
1003        push_content_chunk(&mut chunks, text_chunk(" more", Some("m1")));
1004        push_content_chunk(&mut chunks, text_chunk("second", Some("m2")));
1005        push_content_chunk(&mut chunks, text_chunk("third", None));
1006        push_content_chunk(&mut chunks, text_chunk(" more", None));
1007        push_content_chunk(&mut chunks, image.clone());
1008        push_content_chunk(&mut chunks, image.clone());
1009        push_content_chunk(
1010            &mut chunks,
1011            json!({"content": {"type": "text", "text": "a"}, "meta": {"source": "one"}}),
1012        );
1013        push_content_chunk(
1014            &mut chunks,
1015            json!({"content": {"type": "text", "text": "b"}, "meta": {"source": "two"}}),
1016        );
1017        push_content_chunk(
1018            &mut chunks,
1019            json!({"content": {"type": "text", "text": "c"}, "meta": {"source": "two"}}),
1020        );
1021        push_content_chunk(
1022            &mut chunks,
1023            json!({"content": {"type": "text", "text": "annotated", "annotations": {"audience": ["user"]}}}),
1024        );
1025        push_content_chunk(
1026            &mut chunks,
1027            json!({"content": {"type": "text", "text": "plain"}}),
1028        );
1029        assert_eq!(
1030            chunks,
1031            vec![
1032                text_chunk("first more", Some("m1")),
1033                text_chunk("second", Some("m2")),
1034                text_chunk("third more", None),
1035                image.clone(),
1036                image,
1037                json!({"content": {"type": "text", "text": "a"}, "meta": {"source": "one"}}),
1038                json!({"content": {"type": "text", "text": "bc"}, "meta": {"source": "two"}}),
1039                json!({"content": {"type": "text", "text": "annotated", "annotations": {"audience": ["user"]}}}),
1040                json!({"content": {"type": "text", "text": "plain"}}),
1041            ]
1042        );
1043    }
1044
1045    // Hard-won: ff088d42: Stored 15,000-chunk transcript rows ballooned daemon RSS after restart.
1046    #[test]
1047    fn coalesce_content_chunks_collapses_runs_and_keeps_segment_boundaries() {
1048        let image = json!({"content": {"type": "image", "data": "x", "mimeType": "image/png"}});
1049        let mut chunks = (0..15_001)
1050            .map(|_| text_chunk("x", Some("m1")))
1051            .collect::<Vec<_>>();
1052        chunks.extend([
1053            text_chunk("next", Some("m2")),
1054            text_chunk(" turn", Some("m2")),
1055            image.clone(),
1056        ]);
1057        coalesce_content_chunks(&mut chunks);
1058        assert_eq!(
1059            chunks,
1060            vec![
1061                text_chunk(&"x".repeat(15_001), Some("m1")),
1062                text_chunk("next turn", Some("m2")),
1063                image
1064            ]
1065        );
1066    }
1067}