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