1use 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:";
24pub const TURN_INTERRUPTED_TEXT: &str = "Interrupted";
26pub const TURN_INTERRUPTED_ITEM_PREFIX: &str = "system:turn-interrupted:";
27pub const HARNESS_TURN_TEXT: &str = "Agent continued on its own";
29pub const HARNESS_TURN_ITEM_PREFIX: &str = "harness-turn:";
30pub const ELICITATION_REPLY_ITEM_PREFIX: &str = "elicitation-reply:";
32
33#[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#[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 #[serde(default)]
52 pub summary_version: u8,
53}
54
55#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
59#[serde(tag = "kind", rename_all = "snake_case")]
60pub enum TranscriptBody {
61 Message {
63 event: Box<crate::mailbox::MailboxEvent>,
64 },
65 User {
66 content: Vec<serde_json::Value>,
67 },
68 Agent {
69 chunks: Vec<serde_json::Value>,
72 streaming: bool,
73 },
74 Thought {
75 chunks: Vec<serde_json::Value>,
78 streaming: bool,
79 },
80 Tool {
81 call: serde_json::Value,
84 #[serde(default, skip_serializing_if = "Vec::is_empty")]
89 terminal_outputs: Vec<TerminalOutputRecord>,
90 #[serde(default, skip_serializing_if = "Vec::is_empty")]
95 terminal_refs: Vec<String>,
96 #[serde(default, skip_serializing_if = "Option::is_none")]
99 presentation: Option<Box<ToolCallPresentation>>,
100 },
101 TerminalOutput {
106 record: TerminalOutputRecord,
107 },
108 Plan {
109 plan: serde_json::Value,
112 },
113 PlanProposal {
119 proposal_id: String,
121 plan: String,
123 },
124 System {
125 text: String,
126 },
127}
128
129pub 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
165pub 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
182fn 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 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 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#[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 pub fn exited_cleanly(&self) -> bool {
241 self.exit_code == Some(0) && self.signal.is_none()
242 }
243
244 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 pub position: u64,
288 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 pub fn seq(&self) -> u64 {
313 self.latest_content_event_ordinal.unwrap_or(self.position)
314 }
315
316 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 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 Thought,
403 Tool,
405 Plan,
407 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 #[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 #[serde(default, skip_serializing_if = "Option::is_none")]
433 pub tool_summary: Option<String>,
434 #[serde(default, skip_serializing_if = "Option::is_none")]
437 pub tool_presentation: Option<ToolCallPresentation>,
438 #[serde(default, skip_serializing_if = "Option::is_none")]
440 pub tool_input: Option<serde_json::Value>,
441 #[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 #[serde(default, skip_serializing_if = "is_false")]
455 pub raw_only: bool,
456 #[serde(default, skip_serializing_if = "is_false")]
460 pub ended_after_interrupt: bool,
461 #[serde(skip)]
465 pub source: TranscriptSource,
466}
467
468#[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 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 pub fn is_user_authored(&self) -> bool {
525 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 #[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 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
618impl 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
695pub 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 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
716fn consume_escape_body(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) -> bool {
723 match chars.next() {
724 Some('[') => {
726 let _ = chars.find(|ch| ('@'..='~').contains(ch));
727 false
728 }
729 Some(']' | 'P' | 'X' | '^' | '_') => consume_string_body(chars),
731 Some('(' | ')' | '*' | '+' | '-' | '.' | '/' | '#' | '%' | ' ') => {
733 chars.next();
734 false
735 }
736 _ => false,
739 }
740}
741
742fn 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#[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#[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 ("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 #[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 #[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}