1use crate::packed_text::PackedText;
14use std::sync::Arc;
15
16use agent_client_protocol::v1::schema::{
17 ContentBlock, ContentChunk, EmbeddedResourceResource, PlanEntryStatus, ToolCallContent,
18 ToolCallStatus, ToolKind,
19};
20use anyhow::{Result, bail};
21use serde::{Deserialize, Serialize};
22
23pub const ADOPTION_HISTORY_UNAVAILABLE_ITEM_ID: &str = "system:adoption-history-unavailable";
27
28pub const SESSION_RESTART_TEXT: &str = "[session restarted]";
29pub const SESSION_RESTART_ITEM_PREFIX: &str = "system:session-restarted:";
30pub const WORK_INTERRUPTED_ITEM_PREFIX: &str = "system:work-interrupted:";
31pub const TURN_INTERRUPTED_TEXT: &str = "Interrupted";
33pub const TURN_INTERRUPTED_ITEM_PREFIX: &str = "system:turn-interrupted:";
34pub const HARNESS_TURN_TEXT: &str = "Agent continued on its own";
36pub const HARNESS_TURN_ITEM_PREFIX: &str = "harness-turn:";
37pub const ELICITATION_REPLY_ITEM_PREFIX: &str = "elicitation-reply:";
39
40pub struct TerminalOutputs<'a, R = TerminalOutputRecord> {
43 standalone: std::collections::HashMap<&'a str, &'a R>,
44 tools: std::collections::HashMap<&'a str, (&'a [R], &'a [String])>,
45 referenced: std::collections::HashSet<&'a str>,
46}
47
48pub trait TerminalRecord: Clone {
49 fn terminal_id(&self) -> &str;
50}
51impl TerminalRecord for TerminalOutputRecord {
52 fn terminal_id(&self) -> &str {
53 &self.terminal_id
54 }
55}
56impl TerminalRecord for crate::archive::CanonicalTerminalOutput {
57 fn terminal_id(&self) -> &str {
58 &self.terminal_id
59 }
60}
61impl<R: TerminalRecord> Default for TerminalOutputs<'_, R> {
62 fn default() -> Self {
63 Self::new()
64 }
65}
66impl<'a, R: TerminalRecord> TerminalOutputs<'a, R> {
67 fn new() -> Self {
68 Self {
69 standalone: Default::default(),
70 tools: Default::default(),
71 referenced: Default::default(),
72 }
73 }
74 pub fn tool(&mut self, id: &'a str, embedded: &'a [R], refs: &'a [String]) {
75 self.tools.insert(id, (embedded, refs));
76 self.referenced.extend(refs.iter().map(String::as_str));
77 self.referenced
78 .extend(embedded.iter().map(TerminalRecord::terminal_id));
79 }
80 pub fn standalone(&mut self, record: &'a R) {
81 self.standalone.insert(record.terminal_id(), record);
82 }
83 pub fn for_tool(&self, stable_id: &str) -> std::borrow::Cow<'a, [R]> {
84 let Some((embedded, refs)) = self.tools.get(stable_id) else {
85 return std::borrow::Cow::Borrowed(&[]);
86 };
87 let mut seen = std::collections::HashSet::new();
88 if embedded.iter().all(|record| {
89 seen.insert(record.terminal_id()) && !self.standalone.contains_key(record.terminal_id())
90 }) && !refs
91 .iter()
92 .any(|id| self.standalone.contains_key(id.as_str()))
93 {
94 return std::borrow::Cow::Borrowed(embedded);
95 }
96 seen.clear();
97 let mut records = Vec::new();
98 for record in *embedded {
99 let id = record.terminal_id();
100 if seen.insert(id) {
101 records.push((*self.standalone.get(id).unwrap_or(&record)).clone());
102 }
103 }
104 for id in *refs {
105 if seen.insert(id.as_str())
106 && let Some(record) = self.standalone.get(id.as_str())
107 {
108 records.push((*record).clone());
109 }
110 }
111 std::borrow::Cow::Owned(records)
112 }
113 pub fn embedded_for_tool(&self, stable_id: &str) -> &[R] {
114 self.tools
115 .get(stable_id)
116 .map_or(&[], |(records, _)| *records)
117 }
118 pub fn referenced_terminal_ids(&self) -> impl Iterator<Item = &str> {
119 self.referenced.iter().copied()
120 }
121 pub fn has_standalone(&self) -> bool {
122 !self.standalone.is_empty()
123 }
124 pub fn shown_under_tool(&self, terminal_id: &str) -> bool {
125 self.referenced.contains(terminal_id)
126 }
127}
128impl<'a> TerminalOutputs<'a> {
129 pub fn of(items: impl IntoIterator<Item = &'a TranscriptItem>) -> Self {
130 let mut outputs = Self::new();
131 for item in items {
132 match &item.body {
133 TranscriptBody::Tool {
134 terminal_outputs,
135 terminal_refs,
136 ..
137 } => outputs.tool(&item.stable_id, terminal_outputs, terminal_refs),
138 TranscriptBody::TerminalOutput { record, .. } => {
139 outputs.standalone(record);
140 }
141 _ => {}
142 }
143 }
144 outputs
145 }
146}
147impl<'a> TerminalOutputs<'a, crate::archive::CanonicalTerminalOutput> {
148 pub fn of_canonical(
149 items: impl IntoIterator<Item = &'a crate::archive::CanonicalTranscriptItem>,
150 ) -> Self {
151 let mut outputs = Self::new();
152 for item in items {
153 match &item.body {
154 crate::archive::CanonicalTranscriptBody::Tool {
155 terminal_outputs,
156 terminal_refs,
157 ..
158 } => outputs.tool(&item.stable_id, terminal_outputs, terminal_refs),
159 crate::archive::CanonicalTranscriptBody::TerminalOutput { record, .. } => {
160 outputs.standalone(record);
161 }
162 _ => {}
163 }
164 }
165 outputs
166 }
167}
168
169#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
171#[serde(rename_all = "snake_case")]
172pub enum ToolSummarySourceKind {
173 RawInput,
174 RawOutput,
175 #[default]
176 Title,
177}
178
179#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
180#[serde(rename_all = "snake_case")]
181pub enum ToolEditKind {
182 Edit,
183 Write,
184 MultiEdit,
185 NotebookEdit,
186}
187
188#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
189pub struct ToolEditSnippet {
190 pub path: String,
191 pub kind: ToolEditKind,
192 pub snippet: String,
193}
194
195#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
197pub struct ToolCallPresentation {
198 pub summary: String,
199 #[serde(default)]
201 pub source: PackedText,
202 pub source_kind: ToolSummarySourceKind,
203 pub tool_kind: ToolKind,
204 #[serde(default)]
207 pub summary_version: u8,
208 #[serde(default, skip_serializing_if = "Option::is_none")]
209 pub output_line_count: Option<u64>,
210 #[serde(default, skip_serializing_if = "Option::is_none")]
211 pub first_error_line: Option<String>,
212 #[serde(default, skip_serializing_if = "Option::is_none")]
213 pub output_is_error: Option<bool>,
214 #[serde(default, skip_serializing_if = "Vec::is_empty")]
215 pub edit_snippets: Vec<ToolEditSnippet>,
216 #[serde(default, skip_serializing_if = "is_false")]
217 pub detail_trimmed: bool,
218}
219
220#[derive(Debug, Clone, Deserialize)]
223#[serde(from = "serde_json::Value")]
224pub struct OpaqueToolCall {
225 json: PackedText,
226 metadata: Box<ToolCallMetadata>,
227}
228
229#[derive(Debug, Clone)]
230struct ToolCallMetadata {
231 raw_status: Option<Box<str>>,
232 typed_status: Option<ToolCallStatus>,
233 id: Option<Box<str>>,
234 terminal_ids: Vec<String>,
235 fallback: bool,
236 raw_result: Option<(u32, usize, [u8; 32])>,
237 has_raw_input: bool,
238 has_raw_output: bool,
239 has_dropped_patch: bool,
240}
241
242impl Serialize for OpaqueToolCall {
243 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
244 serde_json::value::RawValue::from_string(self.json.text().into_owned())
245 .expect("opaque JSON")
246 .serialize(serializer)
247 }
248}
249impl PartialEq for OpaqueToolCall {
250 fn eq(&self, other: &Self) -> bool {
251 self.json == other.json || self.value() == other.value()
252 }
253}
254impl Eq for OpaqueToolCall {}
255
256impl From<serde_json::Value> for OpaqueToolCall {
257 fn from(value: serde_json::Value) -> Self {
258 use agent_client_protocol::v1::schema::ToolCall;
259 use sha2::{Digest, Sha256};
260 let decoded = ToolCall::deserialize(&value).ok();
261 let raw_result = (|| {
262 if !matches!(
263 value.get("status").and_then(serde_json::Value::as_str),
264 Some("completed" | "failed")
265 ) {
266 return None;
267 }
268 let raw = value.get("rawOutput")?;
269 let exit = u32::try_from(raw.get("exit_code")?.as_u64()?).ok()?;
270 let output = raw.get("output")?;
271 let (len, digest) = match output {
272 serde_json::Value::String(s) => (s.len(), Sha256::digest(s.as_bytes()).into()),
273 serde_json::Value::Array(values) => {
274 let mut hash = Sha256::new();
275 for value in values {
276 hash.update([u8::try_from(value.as_u64()?).ok()?]);
277 }
278 (values.len(), hash.finalize().into())
279 }
280 _ => return None,
281 };
282 Some((exit, len, digest))
283 })();
284 let metadata = ToolCallMetadata {
285 raw_status: value
286 .get("status")
287 .and_then(serde_json::Value::as_str)
288 .map(Into::into),
289 typed_status: decoded.as_ref().map(|call| call.status),
290 id: value
291 .get("toolCallId")
292 .and_then(serde_json::Value::as_str)
293 .map(Into::into),
294 terminal_ids: tool_call_terminal_ids(&value),
295 fallback: decoded
296 .as_ref()
297 .is_some_and(crate::acp::is_fallback_terminal_tool_call),
298 raw_result,
299 has_raw_input: value.get("rawInput").is_some(),
300 has_raw_output: value.get("rawOutput").is_some(),
301 has_dropped_patch: decoded.as_ref().is_some_and(|call| {
302 call.content.iter().any(|content| {
303 matches!(content, ToolCallContent::Diff(diff)
304 if crate::diff::stored_patch(diff)
305 .is_some_and(|patch| patch.text.is_empty() && patch.truncated))
306 })
307 }),
308 };
309 Self {
310 json: serde_json::to_string(&value)
311 .expect("JSON Value serializes")
312 .into(),
313 metadata: Box::new(metadata),
314 }
315 }
316}
317
318impl OpaqueToolCall {
319 pub fn edit<R>(&mut self, edit: impl FnOnce(&mut serde_json::Value) -> R) -> R {
320 let mut value = self.value();
321 let result = edit(&mut value);
322 *self = value.into();
323 result
324 }
325 pub fn value(&self) -> serde_json::Value {
326 serde_json::from_str(&self.json.text()).expect("opaque call contains valid JSON")
327 }
328 pub fn decode(&self) -> serde_json::Result<agent_client_protocol::v1::schema::ToolCall> {
329 serde_json::from_str(&self.json.text())
330 }
331 pub fn raw_status(&self) -> Option<&str> {
332 self.metadata.raw_status.as_deref()
333 }
334 pub fn typed_status(&self) -> ToolCallStatus {
335 self.metadata
336 .typed_status
337 .unwrap_or(ToolCallStatus::Pending)
338 }
339 pub fn typed_valid(&self) -> bool {
340 self.metadata.typed_status.is_some()
341 }
342 pub fn id(&self) -> Option<&str> {
343 self.metadata.id.as_deref()
344 }
345 pub fn terminal_ids(&self) -> &[String] {
346 &self.metadata.terminal_ids
347 }
348 pub fn is_fallback(&self) -> bool {
349 self.metadata.fallback
350 }
351 pub fn matches_raw_result(&self, record: &TerminalOutputRecord, digest: &[u8; 32]) -> bool {
352 self.metadata.raw_result.is_some_and(|(exit, len, expected)| {
353 record.exit_code == Some(exit) && record.signal.is_none() && record.output.len() == len
354 && &expected == digest
355 && record.matches_tool_raw_result(&self.value())
357 })
358 }
359}
360
361pub fn tool_call_terminal_ids(call: &serde_json::Value) -> Vec<String> {
364 use agent_client_protocol::v1::schema::ToolCallContent;
365 let Some(serde_json::Value::Array(content)) = call.get("content") else {
366 return Vec::new();
367 };
368 content.iter().filter_map(|value| match ToolCallContent::deserialize(value) {
369 Ok(ToolCallContent::Terminal(terminal)) => Some(terminal.terminal_id.0.to_string()),
370 Ok(_) => None,
371 Err(error) => { tracing::warn!(%error, "ignoring malformed tool-call content while locating terminal output"); None }
372 }).collect()
373}
374
375#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
379#[serde(tag = "kind", rename_all = "snake_case")]
380pub enum TranscriptBody {
381 Message {
383 event: Box<crate::mailbox::MailboxEvent>,
384 },
385 User {
386 content: Vec<serde_json::Value>,
387 },
388 Agent {
389 chunks: Vec<serde_json::Value>,
392 streaming: bool,
393 },
394 Thought {
395 chunks: Vec<serde_json::Value>,
398 streaming: bool,
399 },
400 Tool {
401 call: OpaqueToolCall,
404 #[serde(default, skip_serializing_if = "Vec::is_empty")]
409 terminal_outputs: Vec<TerminalOutputRecord>,
410 #[serde(default, skip_serializing_if = "Vec::is_empty")]
415 terminal_refs: Vec<String>,
416 #[serde(default, skip_serializing_if = "Option::is_none")]
419 presentation: Option<Box<ToolCallPresentation>>,
420 },
421 TerminalOutput {
426 record: TerminalOutputRecord,
427 #[serde(default, skip_serializing_if = "Option::is_none")]
428 output_line_count: Option<u64>,
429 #[serde(default, skip_serializing_if = "Option::is_none")]
430 first_error_line: Option<String>,
431 #[serde(default, skip_serializing_if = "is_false")]
432 detail_trimmed: bool,
433 },
434 Plan {
435 plan: serde_json::Value,
438 },
439 PlanProposal {
445 proposal_id: String,
447 plan: String,
449 },
450 System {
451 text: String,
452 },
453}
454
455#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
456#[serde(tag = "status", rename_all = "snake_case")]
457pub enum ToolCallDetailResult {
458 Full {
459 body: TranscriptBody,
460 },
461 Unavailable {
462 #[serde(default, skip_serializing_if = "Option::is_none")]
463 summary: Option<TranscriptBody>,
464 reason: String,
465 },
466}
467
468impl TranscriptBody {
469 pub fn role(&self) -> TranscriptRole {
470 match self {
471 Self::User { .. } => TranscriptRole::User,
472 Self::Agent { .. } => TranscriptRole::Agent,
473 Self::Message { .. } => TranscriptRole::Message,
474 Self::Thought { .. } => TranscriptRole::Thought,
475 Self::Tool { .. } => TranscriptRole::Tool,
476 Self::TerminalOutput { .. } => TranscriptRole::Terminal,
477 Self::Plan { .. } => TranscriptRole::Plan,
478 Self::PlanProposal { .. } => TranscriptRole::PlanProposal,
479 Self::System { .. } => TranscriptRole::System,
480 }
481 }
482
483 pub fn detail_trimmed(&self) -> bool {
484 match self {
485 Self::Tool { presentation, .. } => presentation
486 .as_ref()
487 .is_some_and(|value| value.detail_trimmed),
488 Self::TerminalOutput { detail_trimmed, .. } => *detail_trimmed,
489 _ => false,
490 }
491 }
492
493 pub fn is_legacy_compacted_tool(&self) -> bool {
495 let Self::Tool {
496 call, presentation, ..
497 } = self
498 else {
499 return false;
500 };
501 !presentation.as_ref().is_some_and(|p| p.detail_trimmed)
502 && (presentation.as_ref().is_some_and(|p| match p.source_kind {
503 ToolSummarySourceKind::RawInput => !call.metadata.has_raw_input,
504 ToolSummarySourceKind::RawOutput => !call.metadata.has_raw_output,
505 ToolSummarySourceKind::Title => false,
506 }) || call.metadata.has_dropped_patch)
507 }
508
509 pub fn has_trimmed_detail(&self) -> bool {
510 self.detail_trimmed() || self.is_legacy_compacted_tool()
511 }
512
513 pub fn terminal_output(record: TerminalOutputRecord) -> Self {
514 Self::TerminalOutput {
515 record,
516 output_line_count: None,
517 first_error_line: None,
518 detail_trimmed: false,
519 }
520 }
521}
522
523pub fn push_content_chunk(chunks: &mut Vec<serde_json::Value>, chunk: serde_json::Value) {
538 if chunks
539 .last()
540 .is_some_and(|last| text_chunks_mergeable(last, &chunk))
541 {
542 let addition = chunk
543 .get("content")
544 .and_then(|content| content.get("text"))
545 .and_then(serde_json::Value::as_str)
546 .unwrap_or_default()
547 .to_owned();
548 if let Some(serde_json::Value::Object(last)) = chunks.last_mut()
549 && let Some(serde_json::Value::Object(content)) = last.get_mut("content")
550 && let Some(serde_json::Value::String(text)) = content.get_mut("text")
551 {
552 text.push_str(&addition);
553 return;
554 }
555 }
556 chunks.push(chunk);
557}
558
559pub fn coalesce_content_chunks(chunks: &mut Vec<serde_json::Value>) {
565 if chunks.len() < 2 {
566 return;
567 }
568 let mut merged = Vec::with_capacity(chunks.len());
569 for chunk in std::mem::take(chunks) {
570 push_content_chunk(&mut merged, chunk);
571 }
572 merged.shrink_to_fit();
573 *chunks = merged;
574}
575
576fn text_chunks_mergeable(last: &serde_json::Value, next: &serde_json::Value) -> bool {
580 let (serde_json::Value::Object(last), serde_json::Value::Object(next)) = (last, next) else {
581 return false;
582 };
583 let (
584 Some(serde_json::Value::Object(last_content)),
585 Some(serde_json::Value::Object(next_content)),
586 ) = (last.get("content"), next.get("content"))
587 else {
588 return false;
589 };
590 let is_text = |content: &serde_json::Map<String, serde_json::Value>| {
591 content.get("type").and_then(serde_json::Value::as_str) == Some("text")
592 && content
593 .get("text")
594 .is_some_and(serde_json::Value::is_string)
595 };
596 if !is_text(last_content) || !is_text(next_content) {
597 return false;
598 }
599 if last.len() != next.len()
601 || !last
602 .iter()
603 .all(|(key, value)| key == "content" || next.get(key) == Some(value))
604 {
605 return false;
606 }
607 last_content.len() == next_content.len()
609 && last_content
610 .iter()
611 .all(|(key, value)| key == "text" || next_content.get(key) == Some(value))
612}
613
614#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
618pub struct TerminalOutputRecord {
619 pub terminal_id: String,
620 pub output: PackedText,
621 #[serde(default, skip_serializing_if = "is_false")]
622 pub truncated: bool,
623 #[serde(default, skip_serializing_if = "Option::is_none")]
624 pub exit_code: Option<u32>,
625 #[serde(default, skip_serializing_if = "Option::is_none")]
626 pub signal: Option<String>,
627}
628
629impl From<&crate::archive::CanonicalTerminalOutput> for TerminalOutputRecord {
630 fn from(record: &crate::archive::CanonicalTerminalOutput) -> Self {
631 Self {
632 terminal_id: record.terminal_id.clone(),
633 output: record.output.clone().into(),
634 truncated: record.truncated,
635 exit_code: record.exit_code,
636 signal: record.signal.clone(),
637 }
638 }
639}
640
641impl TerminalOutputRecord {
642 pub fn raw_result_digest(&self) -> [u8; 32] {
644 use sha2::{Digest, Sha256};
645 Sha256::digest(self.output.text().as_bytes()).into()
646 }
647
648 pub fn exited_cleanly(&self) -> bool {
653 self.exit_code == Some(0) && self.signal.is_none()
654 }
655
656 pub fn matches_tool_raw_result(&self, call: &serde_json::Value) -> bool {
661 if !matches!(
662 call.get("status").and_then(serde_json::Value::as_str),
663 Some("completed" | "failed")
664 ) {
665 return false;
666 }
667 let Some(raw) = call.get("rawOutput") else {
668 return false;
669 };
670 let Some(exit_code) = raw
671 .get("exit_code")
672 .and_then(serde_json::Value::as_u64)
673 .and_then(|code| u32::try_from(code).ok())
674 else {
675 return false;
676 };
677 if self.exit_code != Some(exit_code) || self.signal.is_some() {
678 return false;
679 }
680 match raw.get("output") {
681 Some(serde_json::Value::Array(bytes)) => {
682 bytes.len() == self.output.len()
683 && bytes
684 .iter()
685 .zip(self.output.text().as_bytes())
686 .all(|(value, byte)| value.as_u64() == Some(u64::from(*byte)))
687 }
688 Some(serde_json::Value::String(output)) => output == self.output.text().as_ref(),
689 _ => false,
690 }
691 }
692}
693
694#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
695#[serde(deny_unknown_fields)]
696pub struct TranscriptItem {
697 pub stable_id: String,
698 pub position: u64,
700 pub latest_content_event_ordinal: Option<u64>,
703 pub created_at_ms: i64,
704 pub last_changed_at_ms: i64,
705 pub body: TranscriptBody,
706}
707
708impl TranscriptItem {
709 pub fn is_work_interruption(&self) -> bool {
710 self.stable_id.starts_with(WORK_INTERRUPTED_ITEM_PREFIX)
711 }
712
713 pub fn is_session_restart(&self) -> bool {
714 self.stable_id.starts_with(SESSION_RESTART_ITEM_PREFIX)
715 }
716
717 pub fn seq(&self) -> u64 {
725 self.latest_content_event_ordinal.unwrap_or(self.position)
726 }
727
728 pub fn is_user_prompt(&self) -> bool {
730 matches!(self.body, TranscriptBody::User { .. })
731 && !self.stable_id.starts_with(ELICITATION_REPLY_ITEM_PREFIX)
732 }
733
734 pub fn is_turn_start(&self) -> bool {
738 self.is_user_prompt() || self.stable_id.starts_with(HARNESS_TURN_ITEM_PREFIX)
739 }
740
741 pub fn is_nonempty_agent_message(&self) -> bool {
742 let TranscriptBody::Agent { chunks, .. } = &self.body else {
743 return false;
744 };
745 chunks.iter().any(|chunk| {
746 let Some(content) = chunk.get("content") else {
747 return false;
748 };
749 match content.get("type").and_then(serde_json::Value::as_str) {
750 Some("text") => content
751 .get("text")
752 .and_then(serde_json::Value::as_str)
753 .is_some_and(|text| !text.trim().is_empty()),
754 Some(_) => true,
755 None => false,
756 }
757 })
758 }
759
760 pub fn validate(&self, through: u64) -> Result<()> {
761 if self.stable_id.trim().is_empty() {
762 bail!("materialized transcript item has an empty stable id");
763 }
764 if self.position == 0 || self.position > through {
765 bail!(
766 "materialized transcript item {:?} has invalid position {} at frontier {through}",
767 self.stable_id,
768 self.position
769 );
770 }
771 match (&self.body, self.latest_content_event_ordinal) {
772 (TranscriptBody::Agent { .. }, Some(ordinal))
773 if ordinal >= self.position && ordinal <= through => {}
774 (TranscriptBody::Agent { .. }, Some(ordinal)) => bail!(
775 "materialized agent message {:?} has invalid latest content ordinal {ordinal} at position {} and frontier {through}",
776 self.stable_id,
777 self.position
778 ),
779 (TranscriptBody::Agent { .. }, None) => bail!(
780 "materialized agent message {:?} has no latest content ordinal",
781 self.stable_id
782 ),
783 (_, Some(ordinal)) => bail!(
784 "non-agent transcript item {:?} has latest content ordinal {ordinal}",
785 self.stable_id
786 ),
787 (_, None) => {}
788 }
789 if let TranscriptBody::Message { event } = &self.body {
790 anyhow::ensure!(
791 !event.key.trim().is_empty()
792 && event.message_text().is_some()
793 && self.stable_id == message_item_id(&event.key),
794 "invalid message transcript entry {:?}",
795 self.stable_id
796 );
797 }
798 if self.last_changed_at_ms < self.created_at_ms {
799 bail!(
800 "materialized transcript item {:?} changed before it was created",
801 self.stable_id
802 );
803 }
804 Ok(())
805 }
806}
807
808#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
809pub enum ChatRole {
810 User,
811 Agent,
812 Message,
813 Thought,
815 Tool,
817 Plan,
819 PlanProposal,
821 System,
822}
823
824#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
825pub struct ChatEntry {
826 #[serde(default)]
827 pub start_seq: u64,
828 pub seq: u64,
829 pub role: ChatRole,
830 pub text: String,
831 pub recorded_at_ms: Option<i64>,
832 #[serde(default, skip_serializing_if = "Option::is_none")]
835 pub tool_ended_at_ms: Option<i64>,
836 pub revision: u64,
837 pub message_id: Option<String>,
838 #[serde(default, skip_serializing_if = "Option::is_none")]
839 pub incoming_message: Option<Box<crate::mailbox::MailboxEvent>>,
840 #[serde(default, skip_serializing_if = "Option::is_none")]
841 pub stable_id: Option<String>,
842 #[serde(default, skip_serializing_if = "is_false")]
843 pub tool_detail_trimmed: bool,
844 pub tool_call_id: Option<String>,
845 pub tool_status: Option<ToolStatus>,
846 #[serde(default, skip_serializing_if = "Option::is_none")]
849 pub tool_summary: Option<String>,
850 #[serde(default, skip_serializing_if = "Option::is_none")]
853 pub tool_presentation: Option<ToolCallPresentation>,
854 #[serde(default, skip_serializing_if = "Option::is_none")]
856 pub tool_input: Option<serde_json::Value>,
857 #[serde(default, skip_serializing_if = "Option::is_none")]
860 pub tool_error: Option<String>,
861 pub tool_content: Vec<String>,
862 pub tool_diffstats: Vec<String>,
863 pub tool_locations: Vec<String>,
864 pub plan: Vec<PlanLine>,
865 #[serde(default, skip_serializing_if = "is_false")]
866 pub leading_omitted: bool,
867 #[serde(default, skip_serializing_if = "is_false")]
871 pub raw_only: bool,
872 #[serde(default, skip_serializing_if = "is_false")]
876 pub ended_after_interrupt: bool,
877 #[serde(default, skip_serializing_if = "is_false")]
879 pub awaiting_approval: bool,
880 #[serde(skip)]
884 pub source: TranscriptSource,
885}
886
887#[derive(Debug, Clone, Default)]
894pub struct TranscriptSource(pub Option<Arc<TranscriptItem>>);
895
896impl TranscriptSource {
897 pub fn is(&self, item: &Arc<TranscriptItem>) -> bool {
898 self.0
899 .as_ref()
900 .is_some_and(|source| Arc::ptr_eq(source, item))
901 }
902}
903
904impl PartialEq for TranscriptSource {
905 fn eq(&self, _other: &Self) -> bool {
906 true
907 }
908}
909
910impl Eq for TranscriptSource {}
911
912impl ChatEntry {
913 pub fn received_message(seq: u64, event: &crate::mailbox::MailboxEvent) -> Self {
914 let mut entry = Self::plain(
915 seq,
916 ChatRole::Message,
917 event
918 .message_text()
919 .expect("message entry carries a message event"),
920 );
921 entry.message_id = Some(message_item_id(&event.key));
922 entry.incoming_message = Some(Box::new(event.clone()));
923 entry
924 }
925
926 pub fn is_session_restart(&self) -> bool {
931 self.source
932 .0
933 .as_ref()
934 .is_some_and(|item| item.is_session_restart())
935 || (self.role == ChatRole::System && self.text == SESSION_RESTART_TEXT)
936 }
937
938 pub fn is_user_authored(&self) -> bool {
944 self.role == ChatRole::User
947 && crate::continuation::is_user_authored_message(
948 self.source.0.as_ref().map(|item| item.stable_id.as_str()),
949 &self.text,
950 )
951 }
952
953 pub fn plan(seq: u64, plan: Vec<PlanLine>) -> Self {
954 Self {
955 start_seq: seq,
956 seq,
957 role: ChatRole::Plan,
958 text: String::new(),
959 recorded_at_ms: None,
960 tool_ended_at_ms: None,
961 revision: 0,
962 message_id: None,
963 incoming_message: None,
964 stable_id: None,
965 tool_detail_trimmed: false,
966 tool_call_id: None,
967 tool_status: None,
968 tool_summary: None,
969 tool_presentation: None,
970 tool_input: None,
971 tool_error: None,
972 tool_content: Vec::new(),
973 tool_diffstats: Vec::new(),
974 tool_locations: Vec::new(),
975 plan,
976 leading_omitted: false,
977 raw_only: false,
978 ended_after_interrupt: false,
979 awaiting_approval: false,
980 source: TranscriptSource::default(),
981 }
982 }
983
984 pub fn touch(&mut self, seq: u64) {
985 self.seq = seq;
986 self.revision = self.revision.wrapping_add(1);
987 }
988
989 #[doc(hidden)]
995 pub fn bounded_for_dashboard(mut self) -> Self {
996 self.bound_dashboard_content();
997 self
998 }
999
1000 fn bound_dashboard_content(&mut self) {
1001 const TEXT_BYTES: usize = 64 * 1024;
1002 const DETAIL_BYTES: usize = 2 * 1024;
1003 const DETAIL_COUNT: usize = 8;
1004
1005 self.leading_omitted |= truncate_string_start(&mut self.text, TEXT_BYTES);
1006 self.tool_input = None;
1008 if let Some(error) = &mut self.tool_error {
1009 truncate_string_start(error, DETAIL_BYTES);
1010 }
1011 for values in [
1012 &mut self.tool_content,
1013 &mut self.tool_diffstats,
1014 &mut self.tool_locations,
1015 ] {
1016 values.truncate(DETAIL_COUNT);
1017 for value in values {
1018 truncate_string_start(value, DETAIL_BYTES);
1019 }
1020 }
1021 if let Some(summary) = &mut self.tool_summary {
1022 truncate_string_start(summary, DETAIL_BYTES);
1023 }
1024 if let Some(presentation) = &mut self.tool_presentation {
1025 truncate_string_start(&mut presentation.summary, DETAIL_BYTES);
1026 let mut source = presentation.source.text().into_owned();
1027 truncate_string_start(&mut source, TEXT_BYTES);
1028 presentation.source = source.into();
1029 }
1030 self.plan.truncate(DETAIL_COUNT);
1031 for line in &mut self.plan {
1032 truncate_string_start(&mut line.text, DETAIL_BYTES);
1033 }
1034 }
1035
1036 pub fn with_recorded_at(mut self, recorded_at_ms: Option<i64>) -> Self {
1037 self.recorded_at_ms = recorded_at_ms;
1038 self
1039 }
1040}
1041
1042impl ChatEntry {
1045 pub fn plain(seq: u64, role: ChatRole, text: impl Into<String>) -> Self {
1046 Self {
1047 start_seq: seq,
1048 seq,
1049 role,
1050 text: sanitize_terminal_text(&text.into()),
1051 recorded_at_ms: None,
1052 tool_ended_at_ms: None,
1053 revision: 0,
1054 message_id: None,
1055 incoming_message: None,
1056 stable_id: None,
1057 tool_detail_trimmed: false,
1058 tool_call_id: None,
1059 tool_status: None,
1060 tool_summary: None,
1061 tool_presentation: None,
1062 tool_input: None,
1063 tool_error: None,
1064 tool_content: Vec::new(),
1065 tool_diffstats: Vec::new(),
1066 tool_locations: Vec::new(),
1067 plan: Vec::new(),
1068 leading_omitted: false,
1069 raw_only: false,
1070 ended_after_interrupt: false,
1071 awaiting_approval: false,
1072 source: TranscriptSource::default(),
1073 }
1074 }
1075
1076 pub fn tool(
1077 seq: u64,
1078 title: impl Into<String>,
1079 tool_call_id: Option<String>,
1080 tool_status: ToolStatus,
1081 ) -> Self {
1082 Self {
1083 start_seq: seq,
1084 seq,
1085 role: ChatRole::Tool,
1086 text: sanitize_terminal_text(&title.into()),
1087 recorded_at_ms: None,
1088 tool_ended_at_ms: None,
1089 revision: 0,
1090 message_id: None,
1091 incoming_message: None,
1092 stable_id: None,
1093 tool_detail_trimmed: false,
1094 tool_call_id,
1095 tool_status: Some(tool_status),
1096 tool_summary: None,
1097 tool_presentation: None,
1098 tool_input: None,
1099 tool_error: None,
1100 tool_content: Vec::new(),
1101 tool_diffstats: Vec::new(),
1102 tool_locations: Vec::new(),
1103 plan: Vec::new(),
1104 leading_omitted: false,
1105 raw_only: false,
1106 ended_after_interrupt: false,
1107 awaiting_approval: false,
1108 source: TranscriptSource::default(),
1109 }
1110 }
1111}
1112
1113pub(crate) fn is_false(value: &bool) -> bool {
1114 !*value
1115}
1116
1117pub fn plan_status(status: &PlanEntryStatus) -> PlanStatus {
1118 match status {
1119 PlanEntryStatus::InProgress => PlanStatus::Running,
1120 PlanEntryStatus::Completed => PlanStatus::Completed,
1121 _ => PlanStatus::Pending,
1122 }
1123}
1124
1125pub fn sanitize_terminal_text(text: &str) -> String {
1127 let mut sanitized = String::with_capacity(text.len());
1128 let mut chars = text.chars().peekable();
1129 while let Some(ch) = chars.next() {
1130 if ch == '\x1b' {
1131 while consume_escape_body(&mut chars) {}
1135 } else if ch == '\r' {
1136 if chars.peek() != Some(&'\n') {
1137 sanitized.push('\n');
1138 }
1139 } else if matches!(ch, '\n' | '\t') || !ch.is_control() {
1140 sanitized.push(ch);
1141 }
1142 }
1143 sanitized
1144}
1145
1146fn consume_escape_body(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) -> bool {
1153 match chars.next() {
1154 Some('[') => {
1156 let _ = chars.find(|ch| ('@'..='~').contains(ch));
1157 false
1158 }
1159 Some(']' | 'P' | 'X' | '^' | '_') => consume_string_body(chars),
1161 Some('(' | ')' | '*' | '+' | '-' | '.' | '/' | '#' | '%' | ' ') => {
1163 chars.next();
1164 false
1165 }
1166 _ => false,
1169 }
1170}
1171
1172fn consume_string_body(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) -> bool {
1176 while let Some(&ch) = chars.peek() {
1177 match ch {
1178 '\n' | '\r' | '\x18' | '\x1a' => return false,
1179 '\x07' => {
1180 chars.next();
1181 return false;
1182 }
1183 '\x1b' => {
1184 chars.next();
1185 return true;
1186 }
1187 _ => {
1188 chars.next();
1189 }
1190 }
1191 }
1192 false
1193}
1194
1195pub fn materialized_content_text(content: &[serde_json::Value]) -> String {
1196 let text = content
1197 .iter()
1198 .map(materialized_value_text)
1199 .filter(|text| !text.is_empty())
1200 .collect::<Vec<_>>()
1201 .join("\n");
1202 crate::relay::strip_hidden_prompt_context(&text).to_owned()
1203}
1204
1205#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1211#[serde(rename_all = "snake_case")]
1212pub enum TranscriptRole {
1213 User,
1214 Agent,
1215 Message,
1216 Thought,
1217 Tool,
1218 Terminal,
1219 Plan,
1220 PlanProposal,
1221 System,
1222}
1223
1224impl TranscriptRole {
1225 pub fn as_str(self) -> &'static str {
1226 match self {
1227 Self::User => "user",
1228 Self::Agent => "agent",
1229 Self::Message => "message",
1230 Self::Thought => "thought",
1231 Self::Tool => "tool",
1232 Self::Terminal => "terminal",
1233 Self::Plan => "plan",
1234 Self::PlanProposal => "plan_proposal",
1235 Self::System => "system",
1236 }
1237 }
1238 pub fn storage_kind(self) -> &'static str {
1239 match self {
1240 Self::Terminal => "terminal_output",
1241 other => other.as_str(),
1242 }
1243 }
1244}
1245
1246pub fn transcript_item_role(body: &TranscriptBody) -> &'static str {
1247 body.role().as_str()
1248}
1249
1250pub fn message_item_id(event_key: &str) -> String {
1251 format!("message:{event_key}")
1252}
1253
1254pub fn materialized_agent_message_text<'a>(
1256 mut items: impl Iterator<Item = &'a TranscriptItem>,
1257 stable_id: &str,
1258) -> Option<String> {
1259 let item = items.find(|item| item.stable_id == stable_id)?;
1260 match &item.body {
1261 TranscriptBody::Agent { chunks, .. } => Some(materialized_chunks_text(chunks)),
1262 _ => None,
1263 }
1264}
1265
1266pub fn materialized_chunks_text(chunks: &[serde_json::Value]) -> String {
1267 chunks
1268 .iter()
1269 .filter_map(|value| match ContentChunk::deserialize(value) {
1270 Ok(chunk) => Some(chunk),
1271 Err(error) => {
1272 tracing::warn!(%error, "could not decode a stored content chunk");
1273 None
1274 }
1275 })
1276 .filter_map(|chunk| content_block_text(&chunk.content))
1277 .map(|text| sanitize_terminal_text(&text))
1278 .collect::<Vec<_>>()
1279 .join("")
1280}
1281
1282fn materialized_value_text(value: &serde_json::Value) -> String {
1283 if let Ok(block) = ContentBlock::deserialize(value)
1284 && let Some(text) = content_block_text(&block)
1285 {
1286 return sanitize_terminal_text(&text);
1287 }
1288 if let Some(text) = value.as_str() {
1289 return sanitize_terminal_text(text);
1290 }
1291 sanitize_terminal_text(&serde_json::to_string(value).unwrap_or_else(|_| "[content]".into()))
1292}
1293
1294pub fn tool_status(status: &ToolCallStatus) -> ToolStatus {
1295 match status {
1296 ToolCallStatus::InProgress => ToolStatus::Running,
1297 ToolCallStatus::Completed => ToolStatus::Completed,
1298 ToolCallStatus::Failed => ToolStatus::Failed,
1299 _ => ToolStatus::Pending,
1300 }
1301}
1302
1303pub fn content_block_text(content: &ContentBlock) -> Option<String> {
1304 match content {
1305 ContentBlock::Text(text) => Some(text.text.clone()),
1306 ContentBlock::Image(_) => Some("[image]".into()),
1307 ContentBlock::Audio(_) => Some("[audio]".into()),
1308 ContentBlock::ResourceLink(link) => Some(format!("[{}]({})", link.name, link.uri)),
1309 ContentBlock::Resource(resource) => Some(match &resource.resource {
1310 EmbeddedResourceResource::TextResourceContents(resource) => resource.text.clone(),
1311 EmbeddedResourceResource::BlobResourceContents(resource) => {
1312 format!("[embedded resource: {}]", resource.uri)
1313 }
1314 _ => "[embedded resource]".into(),
1315 }),
1316 _ => None,
1317 }
1318}
1319
1320pub fn truncate_string_start(value: &mut String, maximum_bytes: usize) -> bool {
1321 if value.len() <= maximum_bytes {
1322 return false;
1323 }
1324 let mut start = value.len() - maximum_bytes;
1325 while !value.is_char_boundary(start) {
1326 start += 1;
1327 }
1328 value.drain(..start);
1329 true
1330}
1331
1332#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
1334pub enum ToolStatus {
1335 Pending,
1336 Running,
1337 Completed,
1338 Failed,
1339}
1340
1341#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
1342pub enum PlanStatus {
1343 Pending,
1344 Running,
1345 Completed,
1346}
1347
1348#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
1349pub struct PlanLine {
1350 pub text: String,
1351 pub status: PlanStatus,
1352}
1353
1354#[cfg(test)]
1355mod tests {
1356 use super::*;
1357 use serde_json::json;
1358
1359 fn text_chunk(text: &str, message_id: Option<&str>) -> serde_json::Value {
1360 match message_id {
1361 Some(id) => json!({"content": {"type": "text", "text": text}, "messageId": id}),
1362 None => json!({"content": {"type": "text", "text": text}}),
1363 }
1364 }
1365
1366 fn sourced_user_entry(stable_id: &str, text: &str) -> ChatEntry {
1367 let mut entry = ChatEntry::plain(1, ChatRole::User, text);
1368 entry.source = TranscriptSource(Some(Arc::new(TranscriptItem {
1369 stable_id: stable_id.into(),
1370 position: 1,
1371 latest_content_event_ordinal: None,
1372 created_at_ms: 0,
1373 last_changed_at_ms: 0,
1374 body: TranscriptBody::User {
1375 content: vec![json!({"type": "text", "text": text})],
1376 },
1377 })));
1378 entry
1379 }
1380
1381 #[test]
1382 fn only_messages_the_user_wrote_are_user_authored() {
1383 for (stable_id, text) in [
1384 ("user:prompt-7", "fix the build"),
1385 ("user:2", "a prompt recovered by position"),
1386 ("elicitation-reply:9", "Yes"),
1387 ] {
1388 assert!(
1389 sourced_user_entry(stable_id, text).is_user_authored(),
1390 "{stable_id}"
1391 );
1392 }
1393 assert!(ChatEntry::plain(1, ChatRole::User, "not yet projected").is_user_authored());
1394 for (stable_id, text) in [
1395 ("user:auto-continue-1-1", "Continue."),
1396 ("user:quota-retry-4", "Continue."),
1397 ("user:server-retry-5", "Continue."),
1398 ("user:review-forward-2", "Review findings"),
1399 ("user:handback-reminder-36", "Please also update the docs"),
1401 ("user:subagent-input-3", "A sub-agent finished."),
1402 (
1403 "user:session-message-turn-8",
1404 "Message from another session",
1405 ),
1406 ("user:prompt-9", "[HARNESS NOTE: summarize the request]"),
1407 (
1408 "user:prompt-10",
1409 crate::continuation::PARENT_WAIT_PROMPT_TEXT,
1410 ),
1411 ] {
1412 assert!(
1413 !sourced_user_entry(stable_id, text).is_user_authored(),
1414 "{stable_id}"
1415 );
1416 }
1417 assert!(!ChatEntry::plain(1, ChatRole::Agent, "a reply").is_user_authored());
1418 }
1419
1420 #[test]
1422 fn push_content_chunk_merges_adjacent_text_for_the_same_message_id() {
1423 let mut chunks = vec![text_chunk("x", Some("m1"))];
1424 for _ in 1..15_001 {
1425 push_content_chunk(&mut chunks, text_chunk("x", Some("m1")));
1426 }
1427 assert_eq!(chunks, vec![text_chunk(&"x".repeat(15_001), Some("m1"))]);
1428 }
1429
1430 #[test]
1431 fn push_content_chunk_keeps_chunks_from_different_message_ids_apart() {
1432 let image = json!({"content": {"type": "image", "data": "abc", "mimeType": "image/png"}});
1433 let mut chunks = vec![text_chunk("first", Some("m1"))];
1434 push_content_chunk(&mut chunks, text_chunk(" more", Some("m1")));
1435 push_content_chunk(&mut chunks, text_chunk("second", Some("m2")));
1436 push_content_chunk(&mut chunks, text_chunk("third", None));
1437 push_content_chunk(&mut chunks, text_chunk(" more", None));
1438 push_content_chunk(&mut chunks, image.clone());
1439 push_content_chunk(&mut chunks, image.clone());
1440 push_content_chunk(
1441 &mut chunks,
1442 json!({"content": {"type": "text", "text": "a"}, "meta": {"source": "one"}}),
1443 );
1444 push_content_chunk(
1445 &mut chunks,
1446 json!({"content": {"type": "text", "text": "b"}, "meta": {"source": "two"}}),
1447 );
1448 push_content_chunk(
1449 &mut chunks,
1450 json!({"content": {"type": "text", "text": "c"}, "meta": {"source": "two"}}),
1451 );
1452 push_content_chunk(
1453 &mut chunks,
1454 json!({"content": {"type": "text", "text": "annotated", "annotations": {"audience": ["user"]}}}),
1455 );
1456 push_content_chunk(
1457 &mut chunks,
1458 json!({"content": {"type": "text", "text": "plain"}}),
1459 );
1460 assert_eq!(
1461 chunks,
1462 vec![
1463 text_chunk("first more", Some("m1")),
1464 text_chunk("second", Some("m2")),
1465 text_chunk("third more", None),
1466 image.clone(),
1467 image,
1468 json!({"content": {"type": "text", "text": "a"}, "meta": {"source": "one"}}),
1469 json!({"content": {"type": "text", "text": "bc"}, "meta": {"source": "two"}}),
1470 json!({"content": {"type": "text", "text": "annotated", "annotations": {"audience": ["user"]}}}),
1471 json!({"content": {"type": "text", "text": "plain"}}),
1472 ]
1473 );
1474 }
1475
1476 #[test]
1478 fn coalesce_content_chunks_collapses_runs_and_keeps_segment_boundaries() {
1479 let image = json!({"content": {"type": "image", "data": "x", "mimeType": "image/png"}});
1480 let mut chunks = (0..15_001)
1481 .map(|_| text_chunk("x", Some("m1")))
1482 .collect::<Vec<_>>();
1483 chunks.extend([
1484 text_chunk("next", Some("m2")),
1485 text_chunk(" turn", Some("m2")),
1486 image.clone(),
1487 ]);
1488 coalesce_content_chunks(&mut chunks);
1489 assert_eq!(
1490 chunks,
1491 vec![
1492 text_chunk(&"x".repeat(15_001), Some("m1")),
1493 text_chunk("next turn", Some("m2")),
1494 image
1495 ]
1496 );
1497 }
1498}