1use 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:";
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:";
32pub const SESSION_MESSAGE_TURN_COMMAND_PREFIX: &str = "session-message-turn-";
35
36#[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#[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 #[serde(default)]
55 pub summary_version: u8,
56}
57
58#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
62#[serde(tag = "kind", rename_all = "snake_case")]
63pub enum TranscriptBody {
64 Message {
66 event: Box<crate::mailbox::MailboxEvent>,
67 },
68 User {
69 content: Vec<serde_json::Value>,
70 },
71 Agent {
72 chunks: Vec<serde_json::Value>,
75 streaming: bool,
76 },
77 Thought {
78 chunks: Vec<serde_json::Value>,
81 streaming: bool,
82 },
83 Tool {
84 call: serde_json::Value,
87 #[serde(default, skip_serializing_if = "Vec::is_empty")]
92 terminal_outputs: Vec<TerminalOutputRecord>,
93 #[serde(default, skip_serializing_if = "Vec::is_empty")]
98 terminal_refs: Vec<String>,
99 #[serde(default, skip_serializing_if = "Option::is_none")]
102 presentation: Option<Box<ToolCallPresentation>>,
103 },
104 TerminalOutput {
109 record: TerminalOutputRecord,
110 },
111 Plan {
112 plan: serde_json::Value,
115 },
116 PlanProposal {
122 proposal_id: String,
124 plan: String,
126 },
127 System {
128 text: String,
129 },
130}
131
132pub 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
168pub 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
185fn 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 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 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#[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 pub fn exited_cleanly(&self) -> bool {
244 self.exit_code == Some(0) && self.signal.is_none()
245 }
246
247 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 pub position: u64,
291 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 pub fn seq(&self) -> u64 {
316 self.latest_content_event_ordinal.unwrap_or(self.position)
317 }
318
319 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 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 Thought,
406 Tool,
408 Plan,
410 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 #[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 #[serde(default, skip_serializing_if = "Option::is_none")]
436 pub tool_summary: Option<String>,
437 #[serde(default, skip_serializing_if = "Option::is_none")]
440 pub tool_presentation: Option<ToolCallPresentation>,
441 #[serde(default, skip_serializing_if = "Option::is_none")]
443 pub tool_input: Option<serde_json::Value>,
444 pub tool_content: Vec<String>,
445 pub tool_diffstats: Vec<String>,
446 pub tool_locations: Vec<String>,
447 pub plan: Vec<PlanLine>,
448 #[serde(default, skip_serializing_if = "is_false")]
449 pub leading_omitted: bool,
450 #[serde(default, skip_serializing_if = "is_false")]
454 pub raw_only: bool,
455 #[serde(default, skip_serializing_if = "is_false")]
459 pub ended_after_interrupt: bool,
460 #[serde(skip)]
464 pub source: TranscriptSource,
465}
466
467#[derive(Debug, Clone, Default)]
474pub struct TranscriptSource(pub Option<Arc<TranscriptItem>>);
475
476impl TranscriptSource {
477 pub fn is(&self, item: &Arc<TranscriptItem>) -> bool {
478 self.0
479 .as_ref()
480 .is_some_and(|source| Arc::ptr_eq(source, item))
481 }
482}
483
484impl PartialEq for TranscriptSource {
485 fn eq(&self, _other: &Self) -> bool {
486 true
487 }
488}
489
490impl Eq for TranscriptSource {}
491
492impl ChatEntry {
493 pub fn received_message(seq: u64, event: &crate::mailbox::MailboxEvent) -> Self {
494 let mut entry = Self::plain(
495 seq,
496 ChatRole::Message,
497 event
498 .message_text()
499 .expect("message entry carries a message event"),
500 );
501 entry.message_id = Some(message_item_id(&event.key));
502 entry.incoming_message = Some(Box::new(event.clone()));
503 entry
504 }
505
506 pub fn is_session_restart(&self) -> bool {
511 self.source
512 .0
513 .as_ref()
514 .is_some_and(|item| item.is_session_restart())
515 || (self.role == ChatRole::System && self.text == SESSION_RESTART_TEXT)
516 }
517
518 pub fn is_user_authored(&self) -> bool {
525 if self.role != ChatRole::User || crate::continuation::is_generated_prompt_text(&self.text)
526 {
527 return false;
528 }
529 self.source.0.as_ref().is_none_or(|item| {
532 let command_id = item
533 .stable_id
534 .strip_prefix("user:")
535 .unwrap_or(&item.stable_id);
536 !crate::continuation::is_generated_prompt(command_id)
537 && !command_id.starts_with(SESSION_MESSAGE_TURN_COMMAND_PREFIX)
538 })
539 }
540
541 pub fn plan(seq: u64, plan: Vec<PlanLine>) -> Self {
542 Self {
543 start_seq: seq,
544 seq,
545 role: ChatRole::Plan,
546 text: String::new(),
547 recorded_at_ms: None,
548 tool_ended_at_ms: None,
549 revision: 0,
550 message_id: None,
551 incoming_message: None,
552 tool_call_id: None,
553 tool_status: None,
554 tool_summary: None,
555 tool_presentation: None,
556 tool_input: None,
557 tool_content: Vec::new(),
558 tool_diffstats: Vec::new(),
559 tool_locations: Vec::new(),
560 plan,
561 leading_omitted: false,
562 raw_only: false,
563 ended_after_interrupt: false,
564 source: TranscriptSource::default(),
565 }
566 }
567
568 pub fn touch(&mut self, seq: u64) {
569 self.seq = seq;
570 self.revision = self.revision.wrapping_add(1);
571 }
572
573 #[doc(hidden)]
579 pub fn bounded_for_dashboard(mut self) -> Self {
580 self.bound_dashboard_content();
581 self
582 }
583
584 fn bound_dashboard_content(&mut self) {
585 const TEXT_BYTES: usize = 64 * 1024;
586 const DETAIL_BYTES: usize = 2 * 1024;
587 const DETAIL_COUNT: usize = 8;
588
589 self.leading_omitted |= truncate_string_start(&mut self.text, TEXT_BYTES);
590 self.tool_input = None;
592 for values in [
593 &mut self.tool_content,
594 &mut self.tool_diffstats,
595 &mut self.tool_locations,
596 ] {
597 values.truncate(DETAIL_COUNT);
598 for value in values {
599 truncate_string_start(value, DETAIL_BYTES);
600 }
601 }
602 if let Some(summary) = &mut self.tool_summary {
603 truncate_string_start(summary, DETAIL_BYTES);
604 }
605 if let Some(presentation) = &mut self.tool_presentation {
606 truncate_string_start(&mut presentation.summary, DETAIL_BYTES);
607 truncate_string_start(&mut presentation.source, TEXT_BYTES);
608 }
609 self.plan.truncate(DETAIL_COUNT);
610 for line in &mut self.plan {
611 truncate_string_start(&mut line.text, DETAIL_BYTES);
612 }
613 }
614
615 pub fn with_recorded_at(mut self, recorded_at_ms: Option<i64>) -> Self {
616 self.recorded_at_ms = recorded_at_ms;
617 self
618 }
619}
620
621impl ChatEntry {
624 pub fn plain(seq: u64, role: ChatRole, text: impl Into<String>) -> Self {
625 Self {
626 start_seq: seq,
627 seq,
628 role,
629 text: sanitize_terminal_text(&text.into()),
630 recorded_at_ms: None,
631 tool_ended_at_ms: None,
632 revision: 0,
633 message_id: None,
634 incoming_message: None,
635 tool_call_id: None,
636 tool_status: None,
637 tool_summary: None,
638 tool_presentation: None,
639 tool_input: None,
640 tool_content: Vec::new(),
641 tool_diffstats: Vec::new(),
642 tool_locations: Vec::new(),
643 plan: Vec::new(),
644 leading_omitted: false,
645 raw_only: false,
646 ended_after_interrupt: false,
647 source: TranscriptSource::default(),
648 }
649 }
650
651 pub fn tool(
652 seq: u64,
653 title: impl Into<String>,
654 tool_call_id: Option<String>,
655 tool_status: ToolStatus,
656 ) -> Self {
657 Self {
658 start_seq: seq,
659 seq,
660 role: ChatRole::Tool,
661 text: sanitize_terminal_text(&title.into()),
662 recorded_at_ms: None,
663 tool_ended_at_ms: None,
664 revision: 0,
665 message_id: None,
666 incoming_message: None,
667 tool_call_id,
668 tool_status: Some(tool_status),
669 tool_summary: None,
670 tool_presentation: None,
671 tool_input: None,
672 tool_content: Vec::new(),
673 tool_diffstats: Vec::new(),
674 tool_locations: Vec::new(),
675 plan: Vec::new(),
676 leading_omitted: false,
677 raw_only: false,
678 ended_after_interrupt: false,
679 source: TranscriptSource::default(),
680 }
681 }
682}
683
684pub(crate) fn is_false(value: &bool) -> bool {
685 !*value
686}
687
688pub fn plan_status(status: &PlanEntryStatus) -> PlanStatus {
689 match status {
690 PlanEntryStatus::InProgress => PlanStatus::Running,
691 PlanEntryStatus::Completed => PlanStatus::Completed,
692 _ => PlanStatus::Pending,
693 }
694}
695
696pub fn sanitize_terminal_text(text: &str) -> String {
698 let mut sanitized = String::with_capacity(text.len());
699 let mut chars = text.chars().peekable();
700 while let Some(ch) = chars.next() {
701 if ch == '\x1b' {
702 while consume_escape_body(&mut chars) {}
706 } else if ch == '\r' {
707 if chars.peek() != Some(&'\n') {
708 sanitized.push('\n');
709 }
710 } else if matches!(ch, '\n' | '\t') || !ch.is_control() {
711 sanitized.push(ch);
712 }
713 }
714 sanitized
715}
716
717fn consume_escape_body(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) -> bool {
724 match chars.next() {
725 Some('[') => {
727 let _ = chars.find(|ch| ('@'..='~').contains(ch));
728 false
729 }
730 Some(']' | 'P' | 'X' | '^' | '_') => consume_string_body(chars),
732 Some('(' | ')' | '*' | '+' | '-' | '.' | '/' | '#' | '%' | ' ') => {
734 chars.next();
735 false
736 }
737 _ => false,
740 }
741}
742
743fn consume_string_body(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) -> bool {
747 while let Some(&ch) = chars.peek() {
748 match ch {
749 '\n' | '\r' | '\x18' | '\x1a' => return false,
750 '\x07' => {
751 chars.next();
752 return false;
753 }
754 '\x1b' => {
755 chars.next();
756 return true;
757 }
758 _ => {
759 chars.next();
760 }
761 }
762 }
763 false
764}
765
766pub fn materialized_content_text(content: &[serde_json::Value]) -> String {
767 let text = content
768 .iter()
769 .map(materialized_value_text)
770 .filter(|text| !text.is_empty())
771 .collect::<Vec<_>>()
772 .join("\n");
773 crate::relay::strip_hidden_prompt_context(&text).to_owned()
774}
775
776#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
782#[serde(rename_all = "snake_case")]
783pub enum TranscriptRole {
784 User,
785 Agent,
786 Message,
787 Thought,
788 Tool,
789 Terminal,
790 Plan,
791 PlanProposal,
792 System,
793}
794
795impl TranscriptRole {
796 pub fn as_str(self) -> &'static str {
797 match self {
798 Self::User => "user",
799 Self::Agent => "agent",
800 Self::Message => "message",
801 Self::Thought => "thought",
802 Self::Tool => "tool",
803 Self::Terminal => "terminal",
804 Self::Plan => "plan",
805 Self::PlanProposal => "plan_proposal",
806 Self::System => "system",
807 }
808 }
809 pub fn storage_kind(self) -> &'static str {
810 match self {
811 Self::Terminal => "terminal_output",
812 other => other.as_str(),
813 }
814 }
815}
816
817pub fn transcript_item_role(body: &TranscriptBody) -> &'static str {
818 let role = match body {
819 TranscriptBody::User { .. } => TranscriptRole::User,
820 TranscriptBody::Agent { .. } => TranscriptRole::Agent,
821 TranscriptBody::Message { .. } => TranscriptRole::Message,
822 TranscriptBody::Thought { .. } => TranscriptRole::Thought,
823 TranscriptBody::Tool { .. } => TranscriptRole::Tool,
824 TranscriptBody::TerminalOutput { .. } => TranscriptRole::Terminal,
825 TranscriptBody::Plan { .. } => TranscriptRole::Plan,
826 TranscriptBody::PlanProposal { .. } => TranscriptRole::PlanProposal,
827 TranscriptBody::System { .. } => TranscriptRole::System,
828 };
829 role.as_str()
830}
831
832pub fn message_item_id(event_key: &str) -> String {
833 format!("message:{event_key}")
834}
835
836pub fn materialized_chunks_text(chunks: &[serde_json::Value]) -> String {
837 chunks
838 .iter()
839 .filter_map(|value| match ContentChunk::deserialize(value) {
840 Ok(chunk) => Some(chunk),
841 Err(error) => {
842 tracing::warn!(%error, "could not decode a stored content chunk");
843 None
844 }
845 })
846 .filter_map(|chunk| content_block_text(&chunk.content))
847 .map(|text| sanitize_terminal_text(&text))
848 .collect::<Vec<_>>()
849 .join("")
850}
851
852fn materialized_value_text(value: &serde_json::Value) -> String {
853 if let Ok(block) = ContentBlock::deserialize(value)
854 && let Some(text) = content_block_text(&block)
855 {
856 return sanitize_terminal_text(&text);
857 }
858 if let Some(text) = value.as_str() {
859 return sanitize_terminal_text(text);
860 }
861 sanitize_terminal_text(&serde_json::to_string(value).unwrap_or_else(|_| "[content]".into()))
862}
863
864pub fn tool_status(status: &ToolCallStatus) -> ToolStatus {
865 match status {
866 ToolCallStatus::InProgress => ToolStatus::Running,
867 ToolCallStatus::Completed => ToolStatus::Completed,
868 ToolCallStatus::Failed => ToolStatus::Failed,
869 _ => ToolStatus::Pending,
870 }
871}
872
873pub fn content_block_text(content: &ContentBlock) -> Option<String> {
874 match content {
875 ContentBlock::Text(text) => Some(text.text.clone()),
876 ContentBlock::Image(_) => Some("[image]".into()),
877 ContentBlock::Audio(_) => Some("[audio]".into()),
878 ContentBlock::ResourceLink(link) => Some(format!("[{}]({})", link.name, link.uri)),
879 ContentBlock::Resource(resource) => Some(match &resource.resource {
880 EmbeddedResourceResource::TextResourceContents(resource) => resource.text.clone(),
881 EmbeddedResourceResource::BlobResourceContents(resource) => {
882 format!("[embedded resource: {}]", resource.uri)
883 }
884 _ => "[embedded resource]".into(),
885 }),
886 _ => None,
887 }
888}
889
890pub fn truncate_string_start(value: &mut String, maximum_bytes: usize) -> bool {
891 if value.len() <= maximum_bytes {
892 return false;
893 }
894 let mut start = value.len() - maximum_bytes;
895 while !value.is_char_boundary(start) {
896 start += 1;
897 }
898 value.drain(..start);
899 true
900}
901
902#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
904pub enum ToolStatus {
905 Pending,
906 Running,
907 Completed,
908 Failed,
909}
910
911#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
912pub enum PlanStatus {
913 Pending,
914 Running,
915 Completed,
916}
917
918#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
919pub struct PlanLine {
920 pub text: String,
921 pub status: PlanStatus,
922}
923
924#[cfg(test)]
925mod tests {
926 use super::*;
927 use serde_json::json;
928
929 fn text_chunk(text: &str, message_id: Option<&str>) -> serde_json::Value {
930 match message_id {
931 Some(id) => json!({"content": {"type": "text", "text": text}, "messageId": id}),
932 None => json!({"content": {"type": "text", "text": text}}),
933 }
934 }
935
936 fn sourced_user_entry(stable_id: &str, text: &str) -> ChatEntry {
937 let mut entry = ChatEntry::plain(1, ChatRole::User, text);
938 entry.source = TranscriptSource(Some(Arc::new(TranscriptItem {
939 stable_id: stable_id.into(),
940 position: 1,
941 latest_content_event_ordinal: None,
942 created_at_ms: 0,
943 last_changed_at_ms: 0,
944 body: TranscriptBody::User {
945 content: vec![json!({"type": "text", "text": text})],
946 },
947 })));
948 entry
949 }
950
951 #[test]
952 fn only_messages_the_user_wrote_are_user_authored() {
953 for (stable_id, text) in [
954 ("user:prompt-7", "fix the build"),
955 ("user:2", "a prompt recovered by position"),
956 ("elicitation-reply:9", "Yes"),
957 ] {
958 assert!(
959 sourced_user_entry(stable_id, text).is_user_authored(),
960 "{stable_id}"
961 );
962 }
963 assert!(ChatEntry::plain(1, ChatRole::User, "not yet projected").is_user_authored());
964 for (stable_id, text) in [
965 ("user:auto-continue-1-1", "Continue."),
966 ("user:quota-retry-4", "Continue."),
967 ("user:server-retry-5", "Continue."),
968 ("user:review-forward-2", "Review findings"),
969 ("user:subagent-input-3", "A sub-agent finished."),
970 (
971 "user:session-message-turn-8",
972 "Message from another session",
973 ),
974 ("user:prompt-9", "[HARNESS NOTE: summarize the request]"),
975 (
976 "user:prompt-10",
977 crate::continuation::PARENT_WAIT_PROMPT_TEXT,
978 ),
979 ] {
980 assert!(
981 !sourced_user_entry(stable_id, text).is_user_authored(),
982 "{stable_id}"
983 );
984 }
985 assert!(!ChatEntry::plain(1, ChatRole::Agent, "a reply").is_user_authored());
986 }
987
988 #[test]
990 fn push_content_chunk_merges_adjacent_text_for_the_same_message_id() {
991 let mut chunks = vec![text_chunk("x", Some("m1"))];
992 for _ in 1..15_001 {
993 push_content_chunk(&mut chunks, text_chunk("x", Some("m1")));
994 }
995 assert_eq!(chunks, vec![text_chunk(&"x".repeat(15_001), Some("m1"))]);
996 }
997
998 #[test]
999 fn push_content_chunk_keeps_chunks_from_different_message_ids_apart() {
1000 let image = json!({"content": {"type": "image", "data": "abc", "mimeType": "image/png"}});
1001 let mut chunks = vec![text_chunk("first", Some("m1"))];
1002 push_content_chunk(&mut chunks, text_chunk(" more", Some("m1")));
1003 push_content_chunk(&mut chunks, text_chunk("second", Some("m2")));
1004 push_content_chunk(&mut chunks, text_chunk("third", None));
1005 push_content_chunk(&mut chunks, text_chunk(" more", None));
1006 push_content_chunk(&mut chunks, image.clone());
1007 push_content_chunk(&mut chunks, image.clone());
1008 push_content_chunk(
1009 &mut chunks,
1010 json!({"content": {"type": "text", "text": "a"}, "meta": {"source": "one"}}),
1011 );
1012 push_content_chunk(
1013 &mut chunks,
1014 json!({"content": {"type": "text", "text": "b"}, "meta": {"source": "two"}}),
1015 );
1016 push_content_chunk(
1017 &mut chunks,
1018 json!({"content": {"type": "text", "text": "c"}, "meta": {"source": "two"}}),
1019 );
1020 push_content_chunk(
1021 &mut chunks,
1022 json!({"content": {"type": "text", "text": "annotated", "annotations": {"audience": ["user"]}}}),
1023 );
1024 push_content_chunk(
1025 &mut chunks,
1026 json!({"content": {"type": "text", "text": "plain"}}),
1027 );
1028 assert_eq!(
1029 chunks,
1030 vec![
1031 text_chunk("first more", Some("m1")),
1032 text_chunk("second", Some("m2")),
1033 text_chunk("third more", None),
1034 image.clone(),
1035 image,
1036 json!({"content": {"type": "text", "text": "a"}, "meta": {"source": "one"}}),
1037 json!({"content": {"type": "text", "text": "bc"}, "meta": {"source": "two"}}),
1038 json!({"content": {"type": "text", "text": "annotated", "annotations": {"audience": ["user"]}}}),
1039 json!({"content": {"type": "text", "text": "plain"}}),
1040 ]
1041 );
1042 }
1043
1044 #[test]
1046 fn coalesce_content_chunks_collapses_runs_and_keeps_segment_boundaries() {
1047 let image = json!({"content": {"type": "image", "data": "x", "mimeType": "image/png"}});
1048 let mut chunks = (0..15_001)
1049 .map(|_| text_chunk("x", Some("m1")))
1050 .collect::<Vec<_>>();
1051 chunks.extend([
1052 text_chunk("next", Some("m2")),
1053 text_chunk(" turn", Some("m2")),
1054 image.clone(),
1055 ]);
1056 coalesce_content_chunks(&mut chunks);
1057 assert_eq!(
1058 chunks,
1059 vec![
1060 text_chunk(&"x".repeat(15_001), Some("m1")),
1061 text_chunk("next turn", Some("m2")),
1062 image
1063 ]
1064 );
1065 }
1066}