Skip to main content

strands/types/
messages.rs

1//! Messages and content blocks.
2//!
3//! Content blocks use the Bedrock Converse JSON shape: one key per block (`{"toolUse": {...}}`),
4//! except text, which is a bare `{"text": "..."}`, and [`UnknownBlock`], which keeps the raw data.
5
6use std::error::Error as StdError;
7use std::fmt;
8use std::sync::Arc;
9
10use serde::de::Error as _;
11use serde::ser::SerializeMap;
12use serde::{Deserialize, Deserializer, Serialize, Serializer};
13
14use super::citations::CitationsBlock;
15use super::json::{JsonObject, JsonValue};
16use super::media::{AudioBlock, DocumentBlock, ImageBlock, VideoBlock, base64_bytes};
17use super::tools::ToolResultStatus;
18use crate::models::streaming::{Metrics, Usage};
19
20/// The role of a message sender (`Role`).
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
22#[serde(rename_all = "lowercase")]
23#[non_exhaustive]
24pub enum Role {
25    /// Human input and tool results.
26    User,
27    /// Model responses.
28    Assistant,
29}
30
31/// Metadata attached to a message (`MessageMetadata`). Persisted with the message, never sent to
32/// model providers.
33#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
34#[serde(rename_all = "camelCase")]
35#[non_exhaustive]
36pub struct MessageMetadata {
37    /// Token usage of the model response.
38    #[serde(default, skip_serializing_if = "Option::is_none")]
39    pub usage: Option<Usage>,
40    /// Performance metrics of the model response.
41    #[serde(default, skip_serializing_if = "Option::is_none")]
42    pub metrics: Option<Metrics>,
43    /// Arbitrary user or framework metadata, such as compression provenance.
44    #[serde(default, skip_serializing_if = "Option::is_none")]
45    pub custom: Option<JsonObject>,
46}
47
48impl MessageMetadata {
49    /// Creates empty metadata.
50    pub fn new() -> Self {
51        Self::default()
52    }
53
54    /// Sets the token usage.
55    #[must_use]
56    pub fn with_usage(mut self, usage: Usage) -> Self {
57        self.usage = Some(usage);
58        self
59    }
60
61    /// Sets the metrics.
62    #[must_use]
63    pub fn with_metrics(mut self, metrics: Metrics) -> Self {
64        self.metrics = Some(metrics);
65        self
66    }
67
68    /// Sets the custom metadata.
69    #[must_use]
70    pub fn with_custom(mut self, custom: JsonObject) -> Self {
71        self.custom = Some(custom);
72        self
73    }
74}
75
76/// Generates a durable tracking id for a message: a UUID v4.
77#[must_use]
78pub(crate) fn generate_tracking_id() -> String {
79    #[cfg(test)]
80    if let Some(id) = test_ids::next() {
81        return id;
82    }
83    uuid::Uuid::new_v4().to_string()
84}
85
86/// A crate-internal override of the tracking id generator, for tests that compare against
87/// fixtures written with a counting UUID generator.
88#[cfg(test)]
89pub(crate) mod test_ids {
90    use std::cell::Cell;
91
92    thread_local! {
93        static COUNTER: Cell<Option<u64>> = const { Cell::new(None) };
94    }
95
96    pub(super) fn next() -> Option<String> {
97        COUNTER.with(|counter| {
98            let value = counter.get()? + 1;
99            counter.set(Some(value));
100            Some(format!("00000000-0000-4000-8000-{value:012x}"))
101        })
102    }
103
104    /// Makes tracking ids on this thread count up from `start + 1` until the guard drops.
105    pub(crate) fn count_from(start: u64) -> Guard {
106        COUNTER.with(|counter| counter.set(Some(start)));
107        Guard
108    }
109
110    pub(crate) struct Guard;
111
112    impl Drop for Guard {
113        fn drop(&mut self) {
114            COUNTER.with(|counter| counter.set(None));
115        }
116    }
117}
118
119/// A message in a conversation (`Message`).
120///
121/// Every message has a `tracking_id`. One supplied by the caller or by saved data is kept;
122/// otherwise, or when it is empty, a fresh UUID is minted.
123#[derive(Debug, Clone, PartialEq, Serialize)]
124#[serde(rename_all = "camelCase")]
125#[non_exhaustive]
126pub struct Message {
127    /// The role of the sender.
128    pub role: Role,
129    /// The content blocks.
130    pub content: Vec<ContentBlock>,
131    tracking_id: String,
132    /// Metadata, not sent to model providers.
133    #[serde(skip_serializing_if = "Option::is_none")]
134    pub metadata: Option<MessageMetadata>,
135}
136
137impl Message {
138    /// Creates a message with a fresh tracking id.
139    pub fn new(role: Role, content: Vec<ContentBlock>) -> Self {
140        Self {
141            role,
142            content,
143            tracking_id: generate_tracking_id(),
144            metadata: None,
145        }
146    }
147
148    /// Creates a user message with one text block.
149    pub fn user(text: impl Into<String>) -> Self {
150        Self::new(Role::User, vec![ContentBlock::text(text)])
151    }
152
153    /// Creates an assistant message with one text block.
154    pub fn assistant(text: impl Into<String>) -> Self {
155        Self::new(Role::Assistant, vec![ContentBlock::text(text)])
156    }
157
158    /// Durable id that survives session save and restore; stripped before model calls. Read-only:
159    /// set it at construction with [`Message::with_tracking_id`].
160    #[must_use]
161    pub fn tracking_id(&self) -> &str {
162        &self.tracking_id
163    }
164
165    /// Sets the tracking id. An empty id is replaced with a fresh one.
166    #[must_use]
167    pub fn with_tracking_id(mut self, tracking_id: impl Into<String>) -> Self {
168        self.tracking_id = tracking_id_or_new(Some(tracking_id.into()));
169        self
170    }
171
172    /// Sets the metadata.
173    #[must_use]
174    pub fn with_metadata(mut self, metadata: MessageMetadata) -> Self {
175        self.metadata = Some(metadata);
176        self
177    }
178
179    /// Replaces the content, keeping the role, tracking id and metadata (`with({ content })`).
180    #[must_use]
181    pub fn with_content(mut self, content: Vec<ContentBlock>) -> Self {
182        self.content = content;
183        self
184    }
185
186    /// Parses caller-supplied message data (`Message.fromMessageData`).
187    ///
188    /// Unlike deserialization, which keeps unknown block types as [`UnknownBlock`] so data a newer
189    /// SDK saved still loads, this rejects them with `Unknown ContentBlockData type` (or
190    /// `Unknown ToolResultContentData type` inside a tool result).
191    ///
192    /// # Errors
193    ///
194    /// Returns an error when the data is not a message or holds an unknown block type.
195    pub fn from_message_data(data: JsonValue) -> crate::Result<Self> {
196        Ok(MessageData::deserialize(data)?.into_message(OnUnknown::Reject)?)
197    }
198
199    /// The concatenated text of the message's text blocks.
200    #[must_use]
201    pub fn text(&self) -> String {
202        self.content.iter().filter_map(ContentBlock::as_text).collect()
203    }
204}
205
206#[derive(Deserialize)]
207#[serde(rename_all = "camelCase")]
208struct MessageData {
209    role: Role,
210    content: Vec<JsonValue>,
211    #[serde(default)]
212    tracking_id: Option<String>,
213    #[serde(default)]
214    metadata: Option<MessageMetadata>,
215}
216
217impl MessageData {
218    fn into_message(self, on_unknown: OnUnknown) -> Result<Message, serde_json::Error> {
219        let content = self
220            .content
221            .into_iter()
222            .map(|block| parse_content_block(block, on_unknown))
223            .collect::<Result<_, _>>()?;
224        Ok(Message {
225            role: self.role,
226            content,
227            tracking_id: tracking_id_or_new(self.tracking_id),
228            metadata: self.metadata,
229        })
230    }
231}
232
233impl<'de> Deserialize<'de> for Message {
234    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
235        MessageData::deserialize(deserializer)?
236            .into_message(OnUnknown::Keep)
237            .map_err(D::Error::custom)
238    }
239}
240
241fn tracking_id_or_new(tracking_id: Option<String>) -> String {
242    tracking_id
243        .filter(|id| !id.is_empty())
244        .unwrap_or_else(generate_tracking_id)
245}
246
247/// A block of content within a message (`ContentBlock`).
248#[derive(Debug, Clone, PartialEq)]
249#[non_exhaustive]
250pub enum ContentBlock {
251    /// Plain text, `{"text": "..."}`.
252    Text(TextBlock),
253    /// A tool use request, `{"toolUse": {...}}`.
254    ToolUse(ToolUseBlock),
255    /// A tool result, `{"toolResult": {...}}`.
256    ToolResult(ToolResultBlock),
257    /// Model reasoning, `{"reasoning": {...}}`.
258    Reasoning(ReasoningBlock),
259    /// A prompt cache point, `{"cachePoint": {...}}`.
260    CachePoint(CachePointBlock),
261    /// Content for guardrail evaluation, `{"guardContent": {...}}`.
262    GuardContent(GuardContentBlock),
263    /// Audio, `{"audio": {...}}`.
264    Audio(AudioBlock),
265    /// An image, `{"image": {...}}`.
266    Image(ImageBlock),
267    /// A video, `{"video": {...}}`.
268    Video(VideoBlock),
269    /// A document, `{"document": {...}}`.
270    Document(DocumentBlock),
271    /// Citations, `{"citations": {...}}`.
272    Citations(CitationsBlock),
273    /// Text the app adds to a user turn, `{"injected": {...}}`.
274    Injected(InjectedBlock),
275    /// A summary of earlier history, `{"summary": {...}}`.
276    Summary(SummaryBlock),
277    /// A block of a type this version does not recognize, kept unchanged.
278    Unknown(UnknownBlock),
279}
280
281impl ContentBlock {
282    /// Creates a text block.
283    pub fn text(text: impl Into<String>) -> Self {
284        Self::Text(TextBlock::new(text))
285    }
286
287    /// Parses caller-supplied block data, rejecting unknown block types.
288    ///
289    /// # Errors
290    ///
291    /// Returns `Unknown ContentBlockData type` for an unrecognized block, or a decoding error.
292    pub fn from_data(data: JsonValue) -> crate::Result<Self> {
293        Ok(parse_content_block(data, OnUnknown::Reject)?)
294    }
295
296    /// The text of a text block.
297    #[must_use]
298    pub fn as_text(&self) -> Option<&str> {
299        match self {
300            Self::Text(block) => Some(&block.text),
301            _ => None,
302        }
303    }
304}
305
306impl From<TextBlock> for ContentBlock {
307    fn from(block: TextBlock) -> Self {
308        Self::Text(block)
309    }
310}
311
312impl From<&str> for ContentBlock {
313    fn from(text: &str) -> Self {
314        Self::text(text)
315    }
316}
317
318impl From<String> for ContentBlock {
319    fn from(text: String) -> Self {
320        Self::text(text)
321    }
322}
323
324macro_rules! content_block_from {
325    ($($variant:ident($block:ty)),* $(,)?) => {
326        $(impl From<$block> for ContentBlock {
327            fn from(block: $block) -> Self {
328                Self::$variant(block)
329            }
330        })*
331    };
332}
333
334content_block_from!(
335    ToolUse(ToolUseBlock),
336    ToolResult(ToolResultBlock),
337    Reasoning(ReasoningBlock),
338    CachePoint(CachePointBlock),
339    GuardContent(GuardContentBlock),
340    Audio(AudioBlock),
341    Image(ImageBlock),
342    Video(VideoBlock),
343    Document(DocumentBlock),
344    Citations(CitationsBlock),
345    Injected(InjectedBlock),
346    Summary(SummaryBlock),
347    Unknown(UnknownBlock),
348);
349
350fn serialize_wrapped<S: Serializer, T: Serialize + ?Sized>(
351    serializer: S,
352    key: &str,
353    value: &T,
354) -> Result<S::Ok, S::Error> {
355    let mut map = serializer.serialize_map(Some(1))?;
356    map.serialize_entry(key, value)?;
357    map.end()
358}
359
360impl Serialize for ContentBlock {
361    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
362        match self {
363            Self::Text(block) => block.serialize(serializer),
364            Self::ToolUse(block) => serialize_wrapped(serializer, "toolUse", block),
365            Self::ToolResult(block) => serialize_wrapped(serializer, "toolResult", block),
366            Self::Reasoning(block) => serialize_wrapped(serializer, "reasoning", block),
367            Self::CachePoint(block) => serialize_wrapped(serializer, "cachePoint", block),
368            Self::GuardContent(block) => serialize_wrapped(serializer, "guardContent", block),
369            Self::Audio(block) => serialize_wrapped(serializer, "audio", block),
370            Self::Image(block) => serialize_wrapped(serializer, "image", block),
371            Self::Video(block) => serialize_wrapped(serializer, "video", block),
372            Self::Document(block) => serialize_wrapped(serializer, "document", block),
373            Self::Citations(block) => serialize_wrapped(serializer, "citations", block),
374            Self::Injected(block) => serialize_wrapped(serializer, "injected", block),
375            Self::Summary(block) => serialize_wrapped(serializer, "summary", block),
376            Self::Unknown(block) => block.data.serialize(serializer),
377        }
378    }
379}
380
381impl<'de> Deserialize<'de> for ContentBlock {
382    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
383        parse_content_block(JsonValue::deserialize(deserializer)?, OnUnknown::Keep).map_err(D::Error::custom)
384    }
385}
386
387/// What parsing does with a block this version cannot read: caller input is rejected, and saved
388/// data keeps it as an [`UnknownBlock`] so data a newer SDK wrote still loads and round-trips.
389///
390/// A block is unreadable when its type key is unknown, or when its key is known but its body does
391/// not decode, for example a media format this version does not list.
392#[derive(Debug, Clone, Copy)]
393enum OnUnknown {
394    Keep,
395    Reject,
396}
397
398impl OnUnknown {
399    fn unrecognized(self, data: JsonObject, kind: &str) -> Result<UnknownBlock, serde_json::Error> {
400        match self {
401            Self::Reject => Err(serde_json::Error::custom(format!("Unknown {kind} type"))),
402            Self::Keep => Ok(keep_unknown(data)),
403        }
404    }
405
406    fn undecodable(self, data: JsonObject, error: serde_json::Error) -> Result<UnknownBlock, serde_json::Error> {
407        match self {
408            Self::Reject => Err(error),
409            Self::Keep => Ok(keep_unknown(data)),
410        }
411    }
412}
413
414fn keep_unknown(data: JsonObject) -> UnknownBlock {
415    let keys = data.keys().map(String::as_str).collect::<Vec<_>>().join(",");
416    tracing::warn!(
417        "block_keys=<{keys}> | unrecognized content block type | keeping it in history and leaving it out of model requests | if a newer sdk version saved it, upgrade to use it"
418    );
419    UnknownBlock::new(data)
420}
421
422type BlockParser = fn(&JsonValue, OnUnknown) -> Result<ContentBlock, serde_json::Error>;
423
424const CONTENT_BLOCK_PARSERS: [(&str, BlockParser); 12] = [
425    ("toolUse", |value, _| {
426        ToolUseBlock::deserialize(value).map(ContentBlock::ToolUse)
427    }),
428    ("toolResult", |value, on_unknown| {
429        parse_tool_result(value, on_unknown).map(ContentBlock::ToolResult)
430    }),
431    ("reasoning", |value, _| {
432        ReasoningBlock::deserialize(value).map(ContentBlock::Reasoning)
433    }),
434    ("cachePoint", |value, _| {
435        CachePointBlock::deserialize(value).map(ContentBlock::CachePoint)
436    }),
437    ("guardContent", |value, _| {
438        GuardContentBlock::deserialize(value).map(ContentBlock::GuardContent)
439    }),
440    ("audio", |value, _| {
441        AudioBlock::deserialize(value).map(ContentBlock::Audio)
442    }),
443    ("image", |value, _| {
444        ImageBlock::deserialize(value).map(ContentBlock::Image)
445    }),
446    ("video", |value, _| {
447        VideoBlock::deserialize(value).map(ContentBlock::Video)
448    }),
449    ("document", |value, _| {
450        DocumentBlock::deserialize(value).map(ContentBlock::Document)
451    }),
452    ("citations", |value, _| {
453        CitationsBlock::deserialize(value).map(ContentBlock::Citations)
454    }),
455    ("injected", |value, _| {
456        InjectedBlock::deserialize(value).map(ContentBlock::Injected)
457    }),
458    ("summary", |value, _| {
459        SummaryBlock::deserialize(value).map(ContentBlock::Summary)
460    }),
461];
462
463/// A text block from its data, with the placeholder provenance under `offloaded` when stored data
464/// records one (`OffloadedBlock.fromJSON`).
465fn parse_text_block(map: &JsonObject) -> Option<Result<TextBlock, serde_json::Error>> {
466    let text = map.get("text")?;
467    Some((|| {
468        let mut block = TextBlock::new(String::deserialize(text)?);
469        block.offloaded = map.get("offloaded").map(Offloaded::deserialize).transpose()?;
470        Ok(block)
471    })())
472}
473
474fn parse_content_block(data: JsonValue, on_unknown: OnUnknown) -> Result<ContentBlock, serde_json::Error> {
475    let JsonValue::Object(map) = data else {
476        return Err(serde_json::Error::custom("content block must be a JSON object"));
477    };
478    let parsed = parse_text_block(&map)
479        .map(|parsed| parsed.map(ContentBlock::Text))
480        .or_else(|| {
481            CONTENT_BLOCK_PARSERS
482                .iter()
483                .find_map(|(key, parse)| map.get(*key).map(|value| parse(value, on_unknown)))
484        });
485    let Some(parsed) = parsed else {
486        return on_unknown
487            .unrecognized(map, "ContentBlockData")
488            .map(ContentBlock::Unknown);
489    };
490    parsed.or_else(|error| on_unknown.undecodable(map, error).map(ContentBlock::Unknown))
491}
492
493/// Plain text content (`TextBlock`).
494///
495/// A block whose [`offloaded`](Self::offloaded) is set is the placeholder a context-manager
496/// strategy left where it offloaded content (`OffloadedBlock`). It is text to every reader and
497/// every model provider; only code that cares about the provenance reads `offloaded`.
498#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
499#[non_exhaustive]
500pub struct TextBlock {
501    /// The text.
502    pub text: String,
503    /// What the placeholder stands for, when this block replaced offloaded content. Serialized
504    /// under one `offloaded` key, whose presence alone marks stored data as a placeholder.
505    #[serde(default, skip_serializing_if = "Option::is_none")]
506    pub offloaded: Option<Offloaded>,
507}
508
509impl TextBlock {
510    /// Creates a text block.
511    pub fn new(text: impl Into<String>) -> Self {
512        Self {
513            text: text.into(),
514            offloaded: None,
515        }
516    }
517
518    /// Creates the placeholder an offload strategy leaves where it replaced content
519    /// (`new OffloadedBlock`).
520    pub fn offloaded(text: impl Into<String>, offloaded: Offloaded) -> Self {
521        Self {
522            text: text.into(),
523            offloaded: Some(offloaded),
524        }
525    }
526
527    /// Whether this block is an offload placeholder.
528    #[must_use]
529    pub fn is_offloaded(&self) -> bool {
530        self.offloaded.is_some()
531    }
532}
533
534/// The offload method that replaced content with a placeholder (`OffloadMethod`).
535#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
536#[serde(rename_all = "lowercase")]
537#[non_exhaustive]
538pub enum OffloadMethod {
539    /// Removed (`'drop'`).
540    Drop,
541    /// Shortened to a preview (`'truncate'`).
542    Truncate,
543    /// Replaced with a summary (`'summarize'`).
544    Summarize,
545}
546
547impl OffloadMethod {
548    /// The method's name, such as `drop`.
549    #[must_use]
550    pub fn as_str(self) -> &'static str {
551        match self {
552            Self::Drop => "drop",
553            Self::Truncate => "truncate",
554            Self::Summarize => "summarize",
555        }
556    }
557}
558
559impl fmt::Display for OffloadMethod {
560    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
561        f.write_str(self.as_str())
562    }
563}
564
565/// What an offload placeholder stands for (the provenance of an `OffloadedBlock`).
566#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
567#[non_exhaustive]
568pub struct Offloaded {
569    /// The offload method that left the placeholder.
570    pub method: OffloadMethod,
571    /// The archive reference the original is retrievable under; `None` when it was not archived
572    /// (`ref`).
573    #[serde(rename = "ref", default, skip_serializing_if = "Option::is_none")]
574    pub reference: Option<String>,
575    /// The size of the content the placeholder stands for, in tokens, including any placeholder it
576    /// replaced; `None` when the token count could not measure it.
577    #[serde(default, skip_serializing_if = "Option::is_none")]
578    pub tokens: Option<u64>,
579}
580
581impl Offloaded {
582    /// The provenance of a placeholder left by `method`, with no reference or size.
583    #[must_use]
584    pub fn new(method: OffloadMethod) -> Self {
585        Self {
586            method,
587            reference: None,
588            tokens: None,
589        }
590    }
591
592    /// Sets the archive reference.
593    #[must_use]
594    pub fn with_reference(mut self, reference: impl Into<String>) -> Self {
595        self.reference = Some(reference.into());
596        self
597    }
598
599    /// Sets the size in tokens.
600    #[must_use]
601    pub fn with_tokens(mut self, tokens: u64) -> Self {
602        self.tokens = Some(tokens);
603        self
604    }
605}
606
607impl From<&str> for TextBlock {
608    fn from(text: &str) -> Self {
609        Self::new(text)
610    }
611}
612
613impl From<String> for TextBlock {
614    fn from(text: String) -> Self {
615        Self::new(text)
616    }
617}
618
619/// A tool use request from the model (`ToolUseBlock`).
620#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
621#[serde(rename_all = "camelCase")]
622#[non_exhaustive]
623pub struct ToolUseBlock {
624    /// The name of the tool to execute.
625    pub name: String,
626    /// Identifier for this tool use.
627    pub tool_use_id: String,
628    /// The tool input.
629    pub input: JsonValue,
630    /// Reasoning signature from thinking models, sent back unchanged for multi-turn tool use.
631    #[serde(default, skip_serializing_if = "Option::is_none")]
632    pub reasoning_signature: Option<String>,
633}
634
635impl ToolUseBlock {
636    /// Creates a tool use block.
637    pub fn new(name: impl Into<String>, tool_use_id: impl Into<String>, input: JsonValue) -> Self {
638        Self {
639            name: name.into(),
640            tool_use_id: tool_use_id.into(),
641            input,
642            reasoning_signature: None,
643        }
644    }
645
646    /// Sets the reasoning signature.
647    #[must_use]
648    pub fn with_reasoning_signature(mut self, signature: impl Into<String>) -> Self {
649        self.reasoning_signature = Some(signature.into());
650        self
651    }
652}
653
654/// Structured JSON content, used in tool results (`JsonBlock`), `{"json": ...}`.
655#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
656#[non_exhaustive]
657pub struct JsonBlock {
658    /// The JSON data.
659    pub json: JsonValue,
660}
661
662impl JsonBlock {
663    /// Creates a JSON block.
664    pub fn new(json: JsonValue) -> Self {
665        Self { json }
666    }
667}
668
669/// A tool whose input schema a tool result loads (`ToolReferenceBlock`), `{"toolReference": {"name": ...}}`.
670///
671/// `load_tools` returns one for each tool it loads, and any tool can return them too, such as a
672/// custom loader that searches a tool catalog. It reaches the model as a reference only when the
673/// model defers tools natively (`ModelCapabilities::deferred_tool_loading` is
674/// [`DeferredToolLoading::Native`](crate::models::DeferredToolLoading::Native)), the request
675/// defers this tool, and the tool result holds only such references; the provider then sends a
676/// reference its API expands into the tool's definition. Otherwise the model gets the parameters
677/// of the request's tool with this name as text, so a tool that changed is shown as it is now.
678#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
679#[non_exhaustive]
680pub struct ToolReferenceBlock {
681    /// Name of the tool the result loads.
682    pub name: String,
683}
684
685impl ToolReferenceBlock {
686    /// Creates a reference to the tool named `name`.
687    pub fn new(name: impl Into<String>) -> Self {
688        Self { name: name.into() }
689    }
690}
691
692/// Content within a tool result (`ToolResultContent`).
693#[derive(Debug, Clone, PartialEq)]
694#[non_exhaustive]
695pub enum ToolResultContent {
696    /// Plain text, `{"text": "..."}`.
697    Text(TextBlock),
698    /// Structured JSON, `{"json": ...}`.
699    Json(JsonBlock),
700    /// An image, `{"image": {...}}`.
701    Image(ImageBlock),
702    /// A video, `{"video": {...}}`.
703    Video(VideoBlock),
704    /// A document, `{"document": {...}}`.
705    Document(DocumentBlock),
706    /// A tool whose input schema the result loads, `{"toolReference": {"name": ...}}`.
707    ToolReference(ToolReferenceBlock),
708    /// Content of a type this version does not recognize, kept unchanged.
709    Unknown(UnknownBlock),
710}
711
712impl ToolResultContent {
713    /// Creates text content.
714    pub fn text(text: impl Into<String>) -> Self {
715        Self::Text(TextBlock::new(text))
716    }
717
718    /// Creates JSON content.
719    pub fn json(json: JsonValue) -> Self {
720        Self::Json(JsonBlock::new(json))
721    }
722
723    /// Parses caller-supplied content, rejecting unknown types.
724    ///
725    /// # Errors
726    ///
727    /// Returns `Unknown ToolResultContentData type` for an unrecognized entry, or a decoding error.
728    pub fn from_data(data: JsonValue) -> crate::Result<Self> {
729        Ok(parse_tool_result_content(data, OnUnknown::Reject)?)
730    }
731}
732
733impl From<TextBlock> for ToolResultContent {
734    fn from(block: TextBlock) -> Self {
735        Self::Text(block)
736    }
737}
738
739impl From<JsonBlock> for ToolResultContent {
740    fn from(block: JsonBlock) -> Self {
741        Self::Json(block)
742    }
743}
744
745impl From<&str> for ToolResultContent {
746    fn from(text: &str) -> Self {
747        Self::text(text)
748    }
749}
750
751impl From<String> for ToolResultContent {
752    fn from(text: String) -> Self {
753        Self::text(text)
754    }
755}
756
757impl From<ImageBlock> for ToolResultContent {
758    fn from(block: ImageBlock) -> Self {
759        Self::Image(block)
760    }
761}
762
763impl From<VideoBlock> for ToolResultContent {
764    fn from(block: VideoBlock) -> Self {
765        Self::Video(block)
766    }
767}
768
769impl From<ToolReferenceBlock> for ToolResultContent {
770    fn from(block: ToolReferenceBlock) -> Self {
771        Self::ToolReference(block)
772    }
773}
774
775impl From<DocumentBlock> for ToolResultContent {
776    fn from(block: DocumentBlock) -> Self {
777        Self::Document(block)
778    }
779}
780
781impl Serialize for ToolResultContent {
782    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
783        match self {
784            Self::Text(block) => block.serialize(serializer),
785            Self::Json(block) => block.serialize(serializer),
786            Self::Image(block) => serialize_wrapped(serializer, "image", block),
787            Self::Video(block) => serialize_wrapped(serializer, "video", block),
788            Self::Document(block) => serialize_wrapped(serializer, "document", block),
789            Self::ToolReference(block) => serialize_wrapped(serializer, "toolReference", block),
790            Self::Unknown(block) => block.data.serialize(serializer),
791        }
792    }
793}
794
795impl<'de> Deserialize<'de> for ToolResultContent {
796    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
797        parse_tool_result_content(JsonValue::deserialize(deserializer)?, OnUnknown::Keep).map_err(D::Error::custom)
798    }
799}
800
801type ContentParser = fn(&JsonValue) -> Result<ToolResultContent, serde_json::Error>;
802
803const TOOL_RESULT_CONTENT_PARSERS: [(&str, ContentParser); 5] = [
804    ("json", |value| Ok(ToolResultContent::json(value.clone()))),
805    ("image", |value| {
806        ImageBlock::deserialize(value).map(ToolResultContent::Image)
807    }),
808    ("video", |value| {
809        VideoBlock::deserialize(value).map(ToolResultContent::Video)
810    }),
811    ("document", |value| {
812        DocumentBlock::deserialize(value).map(ToolResultContent::Document)
813    }),
814    ("toolReference", |value| {
815        ToolReferenceBlock::deserialize(value).map(ToolResultContent::ToolReference)
816    }),
817];
818
819fn parse_tool_result_content(data: JsonValue, on_unknown: OnUnknown) -> Result<ToolResultContent, serde_json::Error> {
820    let JsonValue::Object(map) = data else {
821        return Err(serde_json::Error::custom("tool result content must be a JSON object"));
822    };
823    let parsed = parse_text_block(&map)
824        .map(|parsed| parsed.map(ToolResultContent::Text))
825        .or_else(|| {
826            TOOL_RESULT_CONTENT_PARSERS
827                .iter()
828                .find_map(|(key, parse)| map.get(*key).map(parse))
829        });
830    let Some(parsed) = parsed else {
831        return on_unknown
832            .unrecognized(map, "ToolResultContentData")
833            .map(ToolResultContent::Unknown);
834    };
835    parsed.or_else(|error| on_unknown.undecodable(map, error).map(ToolResultContent::Unknown))
836}
837
838/// The error behind an error tool result. Shared, so results stay cheap to clone.
839pub type ToolResultError = Arc<dyn StdError + Send + Sync + 'static>;
840
841/// The result of a tool execution (`ToolResultBlock`).
842///
843/// `error` is available to hooks and the agent loop but is never serialized. Equality compares
844/// `tool_use_id`, `status` and `content` and ignores `error`, so a restored result equals the
845/// original.
846#[derive(Debug, Clone, Serialize)]
847#[serde(rename_all = "camelCase")]
848#[non_exhaustive]
849pub struct ToolResultBlock {
850    /// The id of the tool use this result answers.
851    pub tool_use_id: String,
852    /// Status of the tool execution.
853    pub status: ToolResultStatus,
854    /// The content the tool returned.
855    pub content: Vec<ToolResultContent>,
856    /// The original error when `status` is [`ToolResultStatus::Error`].
857    #[serde(skip)]
858    pub error: Option<ToolResultError>,
859}
860
861impl ToolResultBlock {
862    /// Creates a tool result.
863    pub fn new(tool_use_id: impl Into<String>, status: ToolResultStatus, content: Vec<ToolResultContent>) -> Self {
864        Self {
865            tool_use_id: tool_use_id.into(),
866            status,
867            content,
868            error: None,
869        }
870    }
871
872    /// Creates a successful tool result.
873    pub fn success(tool_use_id: impl Into<String>, content: Vec<ToolResultContent>) -> Self {
874        Self::new(tool_use_id, ToolResultStatus::Success, content)
875    }
876
877    /// Creates a failed tool result.
878    pub fn error(tool_use_id: impl Into<String>, content: Vec<ToolResultContent>) -> Self {
879        Self::new(tool_use_id, ToolResultStatus::Error, content)
880    }
881
882    /// Attaches the error that caused the result.
883    #[must_use]
884    pub fn with_error(mut self, error: impl Into<Box<dyn StdError + Send + Sync + 'static>>) -> Self {
885        self.error = Some(Arc::from(error.into()));
886        self
887    }
888
889    /// Replaces the content, keeping the tool use id, status and error (`with({ content })`).
890    #[must_use]
891    pub fn with_content(mut self, content: Vec<ToolResultContent>) -> Self {
892        self.content = content;
893        self
894    }
895}
896
897impl PartialEq for ToolResultBlock {
898    fn eq(&self, other: &Self) -> bool {
899        self.tool_use_id == other.tool_use_id && self.status == other.status && self.content == other.content
900    }
901}
902
903#[derive(Deserialize)]
904#[serde(rename_all = "camelCase")]
905struct ToolResultBlockData {
906    tool_use_id: String,
907    status: ToolResultStatus,
908    content: Vec<JsonValue>,
909}
910
911fn parse_tool_result(data: &JsonValue, on_unknown: OnUnknown) -> Result<ToolResultBlock, serde_json::Error> {
912    let data = ToolResultBlockData::deserialize(data)?;
913    let content = data
914        .content
915        .into_iter()
916        .map(|entry| parse_tool_result_content(entry, on_unknown))
917        .collect::<Result<_, _>>()?;
918    Ok(ToolResultBlock::new(data.tool_use_id, data.status, content))
919}
920
921impl<'de> Deserialize<'de> for ToolResultBlock {
922    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
923        parse_tool_result(&JsonValue::deserialize(deserializer)?, OnUnknown::Keep).map_err(D::Error::custom)
924    }
925}
926
927/// Model reasoning content (`ReasoningBlock`). `redacted_content` is base64 on the wire.
928#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
929#[serde(rename_all = "camelCase")]
930#[non_exhaustive]
931pub struct ReasoningBlock {
932    /// The reasoning text.
933    #[serde(default, skip_serializing_if = "Option::is_none")]
934    pub text: Option<String>,
935    /// A cryptographic signature for verification.
936    #[serde(default, skip_serializing_if = "Option::is_none")]
937    pub signature: Option<String>,
938    /// Redacted reasoning bytes.
939    #[serde(default, skip_serializing_if = "Option::is_none", with = "base64_bytes::option")]
940    pub redacted_content: Option<Vec<u8>>,
941    /// Provider-native reasoning, sent only to the provider and model that produced it.
942    #[serde(default, skip_serializing_if = "Option::is_none")]
943    pub provider_data: Option<ReasoningProviderData>,
944}
945
946/// Provider-native reasoning that only the provider and model that produced it can replay
947/// (`ReasoningProviderData`).
948///
949/// Written and read only by the SDK model provider named in `provider`; other models never
950/// receive the block.
951#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
952#[serde(rename_all = "camelCase")]
953#[non_exhaustive]
954pub struct ReasoningProviderData {
955    /// The format tag of the provider that wrote it, such as `openai_responses`.
956    pub provider: String,
957    /// The model that produced the reasoning.
958    pub model_id: String,
959    /// The provider's own JSON payload; private to that provider and not a stable shape.
960    pub data: JsonObject,
961}
962
963impl ReasoningProviderData {
964    /// Creates the provider data.
965    pub fn new(provider: impl Into<String>, model_id: impl Into<String>, data: JsonObject) -> Self {
966        Self {
967            provider: provider.into(),
968            model_id: model_id.into(),
969            data,
970        }
971    }
972}
973
974impl ReasoningBlock {
975    /// Creates an empty reasoning block.
976    pub fn new() -> Self {
977        Self::default()
978    }
979
980    /// Sets the reasoning text.
981    #[must_use]
982    pub fn with_text(mut self, text: impl Into<String>) -> Self {
983        self.text = Some(text.into());
984        self
985    }
986
987    /// Sets the signature.
988    #[must_use]
989    pub fn with_signature(mut self, signature: impl Into<String>) -> Self {
990        self.signature = Some(signature.into());
991        self
992    }
993
994    /// Sets the redacted content.
995    #[must_use]
996    pub fn with_redacted_content(mut self, redacted_content: Vec<u8>) -> Self {
997        self.redacted_content = Some(redacted_content);
998        self
999    }
1000
1001    /// Sets the provider-native reasoning.
1002    #[must_use]
1003    pub fn with_provider_data(mut self, provider_data: ReasoningProviderData) -> Self {
1004        self.provider_data = Some(provider_data);
1005        self
1006    }
1007}
1008
1009/// The cache type of a cache point. Only `default` is supported.
1010#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
1011#[serde(rename_all = "lowercase")]
1012#[non_exhaustive]
1013pub enum CacheType {
1014    /// The provider's default cache.
1015    #[default]
1016    Default,
1017}
1018
1019/// Marks where prompt caching should occur (`CachePointBlock`).
1020#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1021#[serde(rename_all = "camelCase")]
1022#[non_exhaustive]
1023pub struct CachePointBlock {
1024    /// The cache type.
1025    pub cache_type: CacheType,
1026    /// Cache entry TTL; the accepted values are provider-specific (Bedrock takes `5m` and `1h`).
1027    #[serde(default, skip_serializing_if = "Option::is_none")]
1028    pub ttl: Option<String>,
1029}
1030
1031impl CachePointBlock {
1032    /// Creates a default cache point.
1033    pub fn new() -> Self {
1034        Self::default()
1035    }
1036
1037    /// Sets the TTL.
1038    #[must_use]
1039    pub fn with_ttl(mut self, ttl: impl Into<String>) -> Self {
1040        self.ttl = Some(ttl.into());
1041        self
1042    }
1043}
1044
1045/// How guardrails evaluate guard content (`GuardQualifier`).
1046#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1047#[serde(rename_all = "snake_case")]
1048#[non_exhaustive]
1049pub enum GuardQualifier {
1050    /// Content to check for grounding.
1051    GroundingSource,
1052    /// A user query to evaluate.
1053    Query,
1054    /// General content for guardrail evaluation.
1055    GuardContent,
1056}
1057
1058/// Image format for guard content (`GuardImageFormat`).
1059#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1060#[serde(rename_all = "lowercase")]
1061#[non_exhaustive]
1062pub enum GuardImageFormat {
1063    /// PNG.
1064    Png,
1065    /// JPEG.
1066    Jpeg,
1067}
1068
1069/// Text evaluated by guardrails (`GuardContentText`).
1070#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1071#[non_exhaustive]
1072pub struct GuardContentText {
1073    /// How this content is evaluated.
1074    pub qualifiers: Vec<GuardQualifier>,
1075    /// The text.
1076    pub text: String,
1077}
1078
1079impl GuardContentText {
1080    /// Creates guard text.
1081    pub fn new(qualifiers: Vec<GuardQualifier>, text: impl Into<String>) -> Self {
1082        Self {
1083            qualifiers,
1084            text: text.into(),
1085        }
1086    }
1087}
1088
1089/// Image bytes for guard content (`GuardImageSource`), base64 on the wire.
1090#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1091#[non_exhaustive]
1092pub struct GuardImageSource {
1093    /// The raw image bytes.
1094    #[serde(with = "base64_bytes")]
1095    pub bytes: Vec<u8>,
1096}
1097
1098impl GuardImageSource {
1099    /// Creates an image source from bytes.
1100    pub fn new(bytes: Vec<u8>) -> Self {
1101        Self { bytes }
1102    }
1103}
1104
1105/// An image evaluated by guardrails (`GuardContentImage`).
1106#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1107#[non_exhaustive]
1108pub struct GuardContentImage {
1109    /// The image format.
1110    pub format: GuardImageFormat,
1111    /// The image source.
1112    pub source: GuardImageSource,
1113}
1114
1115impl GuardContentImage {
1116    /// Creates a guard image from bytes.
1117    pub fn new(format: GuardImageFormat, bytes: Vec<u8>) -> Self {
1118        Self {
1119            format,
1120            source: GuardImageSource::new(bytes),
1121        }
1122    }
1123}
1124
1125/// Content for guardrail evaluation (`GuardContentBlock`): either text or an image.
1126///
1127/// Wire shape: `{"text": {...}}` or `{"image": {...}}`.
1128#[derive(Debug, Clone, PartialEq, Eq)]
1129#[non_exhaustive]
1130pub enum GuardContentBlock {
1131    /// Text with evaluation qualifiers.
1132    Text(GuardContentText),
1133    /// An image.
1134    Image(GuardContentImage),
1135}
1136
1137impl GuardContentBlock {
1138    /// The text content, if this is a text block.
1139    #[must_use]
1140    pub fn text(&self) -> Option<&GuardContentText> {
1141        match self {
1142            Self::Text(text) => Some(text),
1143            Self::Image(_) => None,
1144        }
1145    }
1146
1147    /// The image content, if this is an image block.
1148    #[must_use]
1149    pub fn image(&self) -> Option<&GuardContentImage> {
1150        match self {
1151            Self::Image(image) => Some(image),
1152            Self::Text(_) => None,
1153        }
1154    }
1155}
1156
1157impl From<GuardContentText> for GuardContentBlock {
1158    fn from(text: GuardContentText) -> Self {
1159        Self::Text(text)
1160    }
1161}
1162
1163impl From<GuardContentImage> for GuardContentBlock {
1164    fn from(image: GuardContentImage) -> Self {
1165        Self::Image(image)
1166    }
1167}
1168
1169impl Serialize for GuardContentBlock {
1170    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1171        match self {
1172            Self::Text(text) => serialize_wrapped(serializer, "text", text),
1173            Self::Image(image) => serialize_wrapped(serializer, "image", image),
1174        }
1175    }
1176}
1177
1178#[derive(Deserialize)]
1179struct GuardContentBlockData {
1180    #[serde(default)]
1181    text: Option<GuardContentText>,
1182    #[serde(default)]
1183    image: Option<GuardContentImage>,
1184}
1185
1186impl<'de> Deserialize<'de> for GuardContentBlock {
1187    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1188        let data = GuardContentBlockData::deserialize(deserializer)?;
1189        match (data.text, data.image) {
1190            (Some(text), None) => Ok(Self::Text(text)),
1191            (None, Some(image)) => Ok(Self::Image(image)),
1192            (None, None) => Err(D::Error::custom(
1193                "GuardContentBlock must have either text or image content",
1194            )),
1195            (Some(_), Some(_)) => Err(D::Error::custom(
1196                "GuardContentBlock cannot have both text and image content",
1197            )),
1198        }
1199    }
1200}
1201
1202/// Text the app adds to a user turn, kept apart from the user's own words (`InjectedBlock`).
1203///
1204/// Wire shape: `{"injected": {"text": "...", "source": "..."}}`.
1205#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1206#[non_exhaustive]
1207pub struct InjectedBlock {
1208    /// The text added to the user turn.
1209    pub text: String,
1210    /// The component that added it, such as a `ContextInjector`'s name.
1211    pub source: String,
1212}
1213
1214impl InjectedBlock {
1215    /// Creates an injected block.
1216    pub fn new(text: impl Into<String>, source: impl Into<String>) -> Self {
1217        Self {
1218            text: text.into(),
1219            source: source.into(),
1220        }
1221    }
1222}
1223
1224/// A summary of earlier conversation history (`SummaryBlock`).
1225#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1226#[non_exhaustive]
1227pub struct SummaryBlock {
1228    /// The provider that wrote the summary server-side, for example `anthropic`.
1229    #[serde(default, skip_serializing_if = "Option::is_none")]
1230    pub provider: Option<String>,
1231    /// The signature the provider returned with the summary, sent back unchanged.
1232    #[serde(default, skip_serializing_if = "Option::is_none")]
1233    pub signature: Option<String>,
1234    /// The summary text.
1235    pub text: String,
1236}
1237
1238impl SummaryBlock {
1239    /// Creates a summary block.
1240    pub fn new(text: impl Into<String>) -> Self {
1241        Self {
1242            provider: None,
1243            signature: None,
1244            text: text.into(),
1245        }
1246    }
1247
1248    /// Sets the provider that wrote the summary.
1249    #[must_use]
1250    pub fn with_provider(mut self, provider: impl Into<String>) -> Self {
1251        self.provider = Some(provider.into());
1252        self
1253    }
1254
1255    /// Sets the provider signature.
1256    #[must_use]
1257    pub fn with_signature(mut self, signature: impl Into<String>) -> Self {
1258        self.signature = Some(signature.into());
1259        self
1260    }
1261}
1262
1263/// A content block of a type this version does not recognize (`UnknownBlock`).
1264///
1265/// Holds the raw data so it serializes back unchanged. Model providers skip it.
1266#[derive(Debug, Clone, Default, PartialEq)]
1267#[non_exhaustive]
1268pub struct UnknownBlock {
1269    /// The raw block data.
1270    pub data: JsonObject,
1271}
1272
1273impl UnknownBlock {
1274    /// Wraps raw block data.
1275    pub fn new(data: JsonObject) -> Self {
1276        Self { data }
1277    }
1278}
1279
1280/// A block of a system prompt (`SystemContentBlock`).
1281#[derive(Debug, Clone, PartialEq)]
1282#[non_exhaustive]
1283pub enum SystemContentBlock {
1284    /// Plain text, `{"text": "..."}`.
1285    Text(TextBlock),
1286    /// A cache point, `{"cachePoint": {...}}`.
1287    CachePoint(CachePointBlock),
1288    /// Guard content, `{"guardContent": {...}}`.
1289    GuardContent(GuardContentBlock),
1290}
1291
1292impl SystemContentBlock {
1293    /// Creates a text block.
1294    pub fn text(text: impl Into<String>) -> Self {
1295        Self::Text(TextBlock::new(text))
1296    }
1297}
1298
1299impl From<TextBlock> for SystemContentBlock {
1300    fn from(block: TextBlock) -> Self {
1301        Self::Text(block)
1302    }
1303}
1304
1305impl From<CachePointBlock> for SystemContentBlock {
1306    fn from(block: CachePointBlock) -> Self {
1307        Self::CachePoint(block)
1308    }
1309}
1310
1311impl From<GuardContentBlock> for SystemContentBlock {
1312    fn from(block: GuardContentBlock) -> Self {
1313        Self::GuardContent(block)
1314    }
1315}
1316
1317impl From<&str> for SystemContentBlock {
1318    fn from(text: &str) -> Self {
1319        Self::text(text)
1320    }
1321}
1322
1323impl From<String> for SystemContentBlock {
1324    fn from(text: String) -> Self {
1325        Self::text(text)
1326    }
1327}
1328
1329impl Serialize for SystemContentBlock {
1330    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1331        match self {
1332            Self::Text(block) => block.serialize(serializer),
1333            Self::CachePoint(block) => serialize_wrapped(serializer, "cachePoint", block),
1334            Self::GuardContent(block) => serialize_wrapped(serializer, "guardContent", block),
1335        }
1336    }
1337}
1338
1339impl<'de> Deserialize<'de> for SystemContentBlock {
1340    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1341        let mut map = JsonObject::deserialize(deserializer)?;
1342        if let Some(value) = map.remove("cachePoint") {
1343            return CachePointBlock::deserialize(value)
1344                .map(Self::CachePoint)
1345                .map_err(D::Error::custom);
1346        }
1347        if let Some(value) = map.remove("guardContent") {
1348            return GuardContentBlock::deserialize(value)
1349                .map(Self::GuardContent)
1350                .map_err(D::Error::custom);
1351        }
1352        let Some(value) = map.remove("text") else {
1353            return Err(D::Error::custom("Unknown SystemContentBlockData type"));
1354        };
1355        String::deserialize(value)
1356            .map(|text| Self::Text(TextBlock::new(text)))
1357            .map_err(D::Error::custom)
1358    }
1359}
1360
1361/// The system prompt (`SystemPrompt`): a string, or blocks for caching and guardrails.
1362#[derive(Debug, Clone, PartialEq)]
1363#[non_exhaustive]
1364pub enum SystemPrompt {
1365    /// A plain string.
1366    Text(String),
1367    /// Content blocks.
1368    Blocks(Vec<SystemContentBlock>),
1369}
1370
1371impl From<&str> for SystemPrompt {
1372    fn from(text: &str) -> Self {
1373        Self::Text(text.to_owned())
1374    }
1375}
1376
1377impl From<String> for SystemPrompt {
1378    fn from(text: String) -> Self {
1379        Self::Text(text)
1380    }
1381}
1382
1383impl From<Vec<SystemContentBlock>> for SystemPrompt {
1384    fn from(blocks: Vec<SystemContentBlock>) -> Self {
1385        Self::Blocks(blocks)
1386    }
1387}
1388
1389impl Serialize for SystemPrompt {
1390    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1391        match self {
1392            Self::Text(text) => serializer.serialize_str(text),
1393            Self::Blocks(blocks) => blocks.serialize(serializer),
1394        }
1395    }
1396}
1397
1398impl<'de> Deserialize<'de> for SystemPrompt {
1399    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1400        match JsonValue::deserialize(deserializer)? {
1401            JsonValue::String(text) => Ok(Self::Text(text)),
1402            blocks @ JsonValue::Array(_) => Vec::deserialize(blocks).map(Self::Blocks).map_err(D::Error::custom),
1403            _ => Err(D::Error::custom("system prompt must be a string or an array of blocks")),
1404        }
1405    }
1406}
1407
1408#[cfg(test)]
1409mod tests {
1410    use std::io;
1411    use std::sync::Mutex;
1412
1413    use serde_json::json;
1414
1415    use super::*;
1416    use crate::types::VideoSource;
1417    use crate::types::{AudioFormat, AudioSource, Citation, CitationGeneratedContent, DocumentCharLocation};
1418    use crate::types::{CitationSourceContent, DocumentFormat, DocumentSource, ImageFormat, ImageSource, VideoFormat};
1419
1420    fn round_trip_block(block: &ContentBlock) {
1421        let json = serde_json::to_value(block).unwrap();
1422        assert_eq!(&serde_json::from_value::<ContentBlock>(json).unwrap(), block);
1423    }
1424
1425    fn usage(input: u64, output: u64) -> Usage {
1426        Usage::new(input, output, input + output)
1427    }
1428
1429    #[derive(Clone, Default)]
1430    struct Captured(Arc<Mutex<Vec<u8>>>);
1431
1432    impl io::Write for Captured {
1433        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1434            self.0.lock().unwrap().extend_from_slice(buf);
1435            Ok(buf.len())
1436        }
1437
1438        fn flush(&mut self) -> io::Result<()> {
1439            Ok(())
1440        }
1441    }
1442
1443    fn capture_warnings<T>(f: impl FnOnce() -> T) -> (T, String) {
1444        let captured = Captured::default();
1445        let writer = captured.clone();
1446        let subscriber = tracing_subscriber::fmt()
1447            .with_writer(move || writer.clone())
1448            .with_ansi(false)
1449            .without_time()
1450            .with_level(false)
1451            .with_target(false)
1452            .finish();
1453        let result = tracing::subscriber::with_default(subscriber, f);
1454        let output = String::from_utf8(captured.0.lock().unwrap().clone()).unwrap();
1455        (result, output)
1456    }
1457
1458    #[test]
1459    fn creates_message_with_role_and_content() {
1460        let message = Message::new(Role::User, vec![TextBlock::new("test").into()]);
1461        assert_eq!(message.role, Role::User);
1462        assert_eq!(message.content, vec![ContentBlock::text("test")]);
1463        assert!(!message.tracking_id.is_empty());
1464    }
1465
1466    #[test]
1467    fn creates_message_without_metadata() {
1468        assert_eq!(Message::user("test").metadata, None);
1469    }
1470
1471    #[test]
1472    fn creates_message_with_metadata() {
1473        let metadata = MessageMetadata::new()
1474            .with_usage(usage(10, 5))
1475            .with_metrics(Metrics::new(100));
1476        let message = Message::assistant("hello").with_metadata(metadata.clone());
1477        assert_eq!(message.metadata, Some(metadata));
1478    }
1479
1480    #[test]
1481    fn creates_message_with_custom_metadata() {
1482        let custom = json!({"source": "summarization", "originalTurns": [5, 6, 7]});
1483        let metadata = MessageMetadata::new().with_custom(custom.as_object().unwrap().clone());
1484        let message = Message::assistant("summary").with_metadata(metadata);
1485        assert_eq!(
1486            serde_json::to_value(&message.metadata).unwrap(),
1487            json!({"custom": {"source": "summarization", "originalTurns": [5, 6, 7]}})
1488        );
1489    }
1490
1491    #[test]
1492    fn to_json_includes_metadata_when_present() {
1493        let metadata = MessageMetadata::new()
1494            .with_usage(usage(42, 10))
1495            .with_metrics(Metrics::new(200));
1496        let json = serde_json::to_value(Message::assistant("test").with_metadata(metadata)).unwrap();
1497        assert_eq!(
1498            json["metadata"],
1499            json!({"usage": {"inputTokens": 42, "outputTokens": 10, "totalTokens": 52}, "metrics": {"latencyMs": 200}})
1500        );
1501    }
1502
1503    #[test]
1504    fn to_json_omits_metadata_when_not_present() {
1505        let json = serde_json::to_value(Message::user("test")).unwrap();
1506        assert!(json.get("metadata").is_none());
1507    }
1508
1509    #[test]
1510    fn from_message_data_preserves_metadata() {
1511        let message = Message::from_message_data(json!({
1512            "role": "assistant",
1513            "content": [{"text": "hello"}],
1514            "metadata": {"usage": {"inputTokens": 10, "outputTokens": 5, "totalTokens": 15}, "metrics": {"latencyMs": 100}}
1515        }))
1516        .unwrap();
1517        let metadata = MessageMetadata::new()
1518            .with_usage(usage(10, 5))
1519            .with_metrics(Metrics::new(100));
1520        assert_eq!(message.metadata, Some(metadata));
1521    }
1522
1523    #[test]
1524    fn from_message_data_works_without_metadata() {
1525        let message = Message::from_message_data(json!({"role": "user", "content": [{"text": "hello"}]})).unwrap();
1526        assert_eq!(message.metadata, None);
1527    }
1528
1529    #[test]
1530    fn round_trips_metadata_through_to_json_from_json() {
1531        let metadata = MessageMetadata::new()
1532            .with_usage(usage(42, 10))
1533            .with_metrics(Metrics::new(200))
1534            .with_custom(json!({"source": "test"}).as_object().unwrap().clone());
1535        let original = Message::assistant("test").with_metadata(metadata.clone());
1536        let restored: Message = serde_json::from_value(serde_json::to_value(&original).unwrap()).unwrap();
1537        assert_eq!(restored.metadata, Some(metadata));
1538    }
1539
1540    #[test]
1541    fn round_trips_metadata_through_json_stringify_parse() {
1542        let original = Message::assistant("test").with_metadata(MessageMetadata::new().with_usage(usage(1, 1)));
1543        let restored: Message = serde_json::from_str(&serde_json::to_string(&original).unwrap()).unwrap();
1544        assert_eq!(restored, original);
1545    }
1546
1547    #[test]
1548    fn constructor_mints_a_uuid_tracking_id_by_default() {
1549        let id = uuid::Uuid::parse_str(&Message::user("test").tracking_id).unwrap();
1550        assert_eq!(id.get_version_num(), 4);
1551    }
1552
1553    #[test]
1554    fn two_messages_get_distinct_tracking_ids() {
1555        assert_ne!(Message::user("test").tracking_id, Message::user("test").tracking_id);
1556    }
1557
1558    #[test]
1559    fn constructor_preserves_an_explicit_id() {
1560        assert_eq!(Message::user("test").with_tracking_id("abc123").tracking_id, "abc123");
1561    }
1562
1563    #[test]
1564    fn constructor_mints_when_given_an_empty_string_id() {
1565        assert!(!Message::user("test").with_tracking_id("").tracking_id.is_empty());
1566        let restored: Message =
1567            serde_json::from_value(json!({"role": "user", "content": [], "trackingId": ""})).unwrap();
1568        assert!(!restored.tracking_id.is_empty());
1569    }
1570
1571    #[test]
1572    fn generate_tracking_id_produces_unique_strings() {
1573        let ids: std::collections::HashSet<_> = (0..1000).map(|_| generate_tracking_id()).collect();
1574        assert_eq!(ids.len(), 1000);
1575    }
1576
1577    #[test]
1578    fn to_json_includes_the_tracking_id() {
1579        let json = serde_json::to_value(Message::assistant("test").with_tracking_id("abc123")).unwrap();
1580        assert_eq!(json["trackingId"], "abc123");
1581    }
1582
1583    #[test]
1584    fn from_message_data_preserves_id() {
1585        let data = json!({"role": "assistant", "content": [{"text": "hello"}], "trackingId": "abc123"});
1586        assert_eq!(Message::from_message_data(data).unwrap().tracking_id, "abc123");
1587    }
1588
1589    #[test]
1590    fn from_message_data_backfills_a_tracking_id_when_serialized_data_omits_it() {
1591        let data = json!({"role": "assistant", "content": [{"text": "hello"}]});
1592        assert!(!Message::from_message_data(data).unwrap().tracking_id.is_empty());
1593    }
1594
1595    #[test]
1596    fn round_trips_id_through_to_json_from_json() {
1597        let original = Message::assistant("test").with_tracking_id("durable-1");
1598        let restored: Message = serde_json::from_value(serde_json::to_value(&original).unwrap()).unwrap();
1599        assert_eq!(restored.tracking_id, "durable-1");
1600    }
1601
1602    #[test]
1603    fn clone_preserves_id() {
1604        let original = Message::assistant("test").with_tracking_id("durable-1");
1605        let copy = original.clone();
1606        assert_eq!(copy.tracking_id, "durable-1");
1607        assert_eq!(copy, original);
1608    }
1609
1610    #[test]
1611    fn creates_text_block_with_text() {
1612        assert_eq!(TextBlock::new("hello").text, "hello");
1613        assert_eq!(TextBlock::from("hello"), TextBlock::new("hello"));
1614    }
1615
1616    #[test]
1617    fn creates_tool_use_block() {
1618        let block = ToolUseBlock::new("test-tool", "123", json!({"param": "value"}));
1619        assert_eq!(
1620            serde_json::to_value(ContentBlock::ToolUse(block)).unwrap(),
1621            json!({"toolUse": {"name": "test-tool", "toolUseId": "123", "input": {"param": "value"}}})
1622        );
1623    }
1624
1625    #[test]
1626    fn creates_tool_result_block() {
1627        let block = ToolResultBlock::success("123", vec![ToolResultContent::text("result")]);
1628        assert_eq!(block.status, ToolResultStatus::Success);
1629        assert_eq!(block.content, vec![ToolResultContent::text("result")]);
1630    }
1631
1632    #[test]
1633    fn creates_reasoning_block_with_text() {
1634        let block = ReasoningBlock::new().with_text("thinking...");
1635        assert_eq!(block.text.as_deref(), Some("thinking..."));
1636        assert_eq!((block.signature, block.redacted_content), (None, None));
1637    }
1638
1639    #[test]
1640    fn creates_cache_point_block() {
1641        assert_eq!(CachePointBlock::new().cache_type, CacheType::Default);
1642    }
1643
1644    #[test]
1645    fn creates_cache_point_block_with_ttl() {
1646        assert_eq!(CachePointBlock::new().with_ttl("1h").ttl.as_deref(), Some("1h"));
1647    }
1648
1649    #[test]
1650    fn serializes_ttl_in_to_json() {
1651        assert_eq!(
1652            serde_json::to_value(ContentBlock::CachePoint(CachePointBlock::new().with_ttl("5m"))).unwrap(),
1653            json!({"cachePoint": {"cacheType": "default", "ttl": "5m"}})
1654        );
1655    }
1656
1657    #[test]
1658    fn omits_ttl_in_to_json_when_not_set() {
1659        assert_eq!(
1660            serde_json::to_value(ContentBlock::CachePoint(CachePointBlock::new())).unwrap(),
1661            json!({"cachePoint": {"cacheType": "default"}})
1662        );
1663    }
1664
1665    #[test]
1666    fn roundtrips_ttl_via_from_json() {
1667        let block: ContentBlock =
1668            serde_json::from_value(json!({"cachePoint": {"cacheType": "default", "ttl": "1h"}})).unwrap();
1669        assert_eq!(block, ContentBlock::CachePoint(CachePointBlock::new().with_ttl("1h")));
1670    }
1671
1672    #[test]
1673    fn roundtrips_through_to_json_and_content_block_from_data() {
1674        let block = ContentBlock::Summary(
1675            SummaryBlock::new("summary")
1676                .with_provider("anthropic")
1677                .with_signature("sig"),
1678        );
1679        let json = serde_json::to_value(&block).unwrap();
1680        assert_eq!(
1681            json,
1682            json!({"summary": {"provider": "anthropic", "signature": "sig", "text": "summary"}})
1683        );
1684        assert_eq!(ContentBlock::from_data(json).unwrap(), block);
1685    }
1686
1687    #[test]
1688    fn omits_unset_provider_and_signature_in_to_json() {
1689        assert_eq!(
1690            serde_json::to_value(ContentBlock::Summary(SummaryBlock::new("summary"))).unwrap(),
1691            json!({"summary": {"text": "summary"}})
1692        );
1693    }
1694
1695    #[test]
1696    fn drops_a_null_signature_written_by_the_python_sdk() {
1697        let block = ContentBlock::from_data(
1698            json!({"summary": {"provider": "anthropic", "signature": null, "text": "summary"}}),
1699        )
1700        .unwrap();
1701        let ContentBlock::Summary(summary) = &block else {
1702            panic!("expected a summary block");
1703        };
1704        assert_eq!(summary.signature, None);
1705        assert_eq!(
1706            serde_json::to_value(&block).unwrap(),
1707            json!({"summary": {"provider": "anthropic", "text": "summary"}})
1708        );
1709    }
1710
1711    #[test]
1712    fn creates_json_block() {
1713        assert_eq!(JsonBlock::new(json!({"key": "value"})).json, json!({"key": "value"}));
1714    }
1715
1716    #[test]
1717    fn creates_injected_block_with_text() {
1718        let block = InjectedBlock::new("reminder", "test");
1719        assert_eq!((block.text.as_str(), block.source.as_str()), ("reminder", "test"));
1720    }
1721
1722    #[test]
1723    fn creates_unknown_block_holding_the_raw_data() {
1724        let data = json!({"futureBlock": {"value": 1}}).as_object().unwrap().clone();
1725        assert_eq!(UnknownBlock::new(data.clone()).data, data);
1726    }
1727
1728    #[test]
1729    fn converts_text_block_data_to_text_block() {
1730        let message = Message::from_message_data(json!({"role": "user", "content": [{"text": "hello"}]})).unwrap();
1731        assert_eq!(message.content, vec![ContentBlock::text("hello")]);
1732    }
1733
1734    #[test]
1735    fn converts_tool_use_block_data_to_tool_use_block() {
1736        let message = Message::from_message_data(json!({
1737            "role": "assistant",
1738            "content": [{"toolUse": {"toolUseId": "tool-123", "name": "test-tool", "input": {"key": "value"}}}]
1739        }))
1740        .unwrap();
1741        assert_eq!(
1742            message.content,
1743            vec![ToolUseBlock::new("test-tool", "tool-123", json!({"key": "value"})).into()]
1744        );
1745    }
1746
1747    #[test]
1748    fn converts_tool_result_block_data_to_tool_result_block_with_text_content() {
1749        let message = Message::from_message_data(json!({
1750            "role": "user",
1751            "content": [{"toolResult": {"toolUseId": "tool-123", "status": "success", "content": [{"text": "Result text"}]}}]
1752        }))
1753        .unwrap();
1754        assert_eq!(
1755            message.content,
1756            vec![ToolResultBlock::success("tool-123", vec![ToolResultContent::text("Result text")]).into()]
1757        );
1758    }
1759
1760    #[test]
1761    fn converts_tool_result_block_data_to_tool_result_block_with_json_content() {
1762        let message = Message::from_message_data(json!({
1763            "role": "user",
1764            "content": [{"toolResult": {"toolUseId": "tool-123", "status": "success", "content": [{"json": {"result": "data"}}]}}]
1765        }))
1766        .unwrap();
1767        assert_eq!(
1768            message.content,
1769            vec![ToolResultBlock::success("tool-123", vec![ToolResultContent::json(json!({"result": "data"}))]).into()]
1770        );
1771    }
1772
1773    #[test]
1774    fn converts_reasoning_block_data_to_reasoning_block() {
1775        let message = Message::from_message_data(
1776            json!({"role": "assistant", "content": [{"reasoning": {"text": "Let me think"}}]}),
1777        )
1778        .unwrap();
1779        assert_eq!(
1780            message.content,
1781            vec![ReasoningBlock::new().with_text("Let me think").into()]
1782        );
1783    }
1784
1785    #[test]
1786    fn converts_cache_point_block_data_to_cache_point_block() {
1787        let message =
1788            Message::from_message_data(json!({"role": "user", "content": [{"cachePoint": {"cacheType": "default"}}]}))
1789                .unwrap();
1790        assert_eq!(message.content, vec![CachePointBlock::new().into()]);
1791    }
1792
1793    #[test]
1794    fn converts_guard_content_block_data_to_guard_content_block() {
1795        let message = Message::from_message_data(json!({
1796            "role": "user",
1797            "content": [{"guardContent": {"text": {"text": "guard this content", "qualifiers": ["guard_content"]}}}]
1798        }))
1799        .unwrap();
1800        let expected = GuardContentBlock::Text(GuardContentText::new(
1801            vec![GuardQualifier::GuardContent],
1802            "guard this content",
1803        ));
1804        assert_eq!(message.content, vec![expected.into()]);
1805    }
1806
1807    #[test]
1808    fn converts_injected_block_data_to_injected_block() {
1809        let message = Message::from_message_data(json!({
1810            "role": "user",
1811            "content": [{"injected": {"text": "reminder", "source": "test"}}]
1812        }))
1813        .unwrap();
1814        assert_eq!(message.content, vec![InjectedBlock::new("reminder", "test").into()]);
1815    }
1816
1817    #[test]
1818    fn keeps_an_injected_block_passed_inside_message_data_an_injected_block() {
1819        let block = ContentBlock::Injected(InjectedBlock::new("reminder", "test"));
1820        let data = json!({"role": "user", "content": [serde_json::to_value(&block).unwrap()]});
1821        assert_eq!(Message::from_message_data(data).unwrap().content, vec![block]);
1822    }
1823
1824    #[test]
1825    fn converts_audio_block_data_to_audio_block() {
1826        let message = Message::from_message_data(json!({
1827            "role": "user",
1828            "content": [{"audio": {"format": "mp3", "source": {"bytes": [1, 2, 3]}}}]
1829        }))
1830        .unwrap();
1831        assert_eq!(
1832            message.content,
1833            vec![AudioBlock::new(AudioFormat::Mp3, AudioSource::Bytes(vec![1, 2, 3])).into()]
1834        );
1835    }
1836
1837    #[test]
1838    fn converts_image_block_data_to_image_block() {
1839        let message = Message::from_message_data(json!({
1840            "role": "user",
1841            "content": [{"image": {"format": "png", "source": {"bytes": "AQID"}}}]
1842        }))
1843        .unwrap();
1844        assert_eq!(
1845            message.content,
1846            vec![ImageBlock::new(ImageFormat::Png, ImageSource::Bytes(vec![1, 2, 3])).into()]
1847        );
1848    }
1849
1850    #[test]
1851    fn converts_video_block_data_to_video_block() {
1852        let message = Message::from_message_data(json!({
1853            "role": "user",
1854            "content": [{"video": {"format": "mp4", "source": {"bytes": "AQID"}}}]
1855        }))
1856        .unwrap();
1857        assert_eq!(
1858            message.content,
1859            vec![VideoBlock::new(VideoFormat::Mp4, VideoSource::Bytes(vec![1, 2, 3])).into()]
1860        );
1861    }
1862
1863    #[test]
1864    fn converts_document_block_data_to_document_block() {
1865        let message = Message::from_message_data(json!({
1866            "role": "user",
1867            "content": [{"document": {"name": "test.pdf", "format": "pdf", "source": {"bytes": "AQID"}}}]
1868        }))
1869        .unwrap();
1870        assert_eq!(
1871            message.content,
1872            vec![DocumentBlock::new("test.pdf", DocumentFormat::Pdf, DocumentSource::Bytes(vec![1, 2, 3])).into()]
1873        );
1874    }
1875
1876    #[test]
1877    fn converts_citations_content_block_data_to_citations_block() {
1878        let message = Message::from_message_data(json!({
1879            "role": "assistant",
1880            "content": [{"citations": {
1881                "citations": [{
1882                    "location": {"type": "documentChar", "documentIndex": 0, "start": 0, "end": 10},
1883                    "source": "doc-0",
1884                    "sourceContent": [{"text": "source"}],
1885                    "title": "Test Doc"
1886                }],
1887                "content": [{"text": "generated"}]
1888            }}]
1889        }))
1890        .unwrap();
1891        let expected = CitationsBlock::new(
1892            vec![Citation::new(
1893                DocumentCharLocation::new(0, 0, 10),
1894                "doc-0",
1895                vec![CitationSourceContent::new("source")],
1896                "Test Doc",
1897            )],
1898            vec![CitationGeneratedContent::new("generated")],
1899        );
1900        assert_eq!(message.content, vec![expected.into()]);
1901    }
1902
1903    #[test]
1904    fn converts_multiple_content_blocks() {
1905        let message = Message::from_message_data(json!({
1906            "role": "user",
1907            "content": [
1908                {"text": "First block"},
1909                {"toolUse": {"toolUseId": "tool-1", "name": "test-tool", "input": {}}},
1910                {"text": "Second block"}
1911            ]
1912        }))
1913        .unwrap();
1914        assert_eq!(message.content.len(), 3);
1915        assert_eq!(message.text(), "First blockSecond block");
1916    }
1917
1918    #[test]
1919    fn throws_error_for_unknown_content_block_type() {
1920        let error =
1921            Message::from_message_data(json!({"role": "user", "content": [{"unknownType": {"data": "value"}}]}))
1922                .unwrap_err();
1923        assert_eq!(error.to_string(), "Unknown ContentBlockData type");
1924    }
1925
1926    #[test]
1927    fn content_block_from_saved_data_keeps_it_as_an_unknown_block_and_warns() {
1928        let (block, logs) =
1929            capture_warnings(|| serde_json::from_value::<ContentBlock>(json!({"futureBlock": {"value": 1}})));
1930        assert_eq!(
1931            block.unwrap(),
1932            ContentBlock::Unknown(UnknownBlock::new(
1933                json!({"futureBlock": {"value": 1}}).as_object().unwrap().clone()
1934            ))
1935        );
1936        assert_eq!(
1937            logs.trim(),
1938            "block_keys=<futureBlock> | unrecognized content block type | keeping it in history and leaving it out of model requests | if a newer sdk version saved it, upgrade to use it"
1939        );
1940    }
1941
1942    #[test]
1943    fn content_block_from_saved_data_keeps_unknown_content_inside_a_tool_result_and_serializes_it_back_unchanged() {
1944        let saved = json!({"toolResult": {
1945            "toolUseId": "tool-1",
1946            "status": "success",
1947            "content": [{"text": "loaded"}, {"futureBlock": {"name": "shell"}}]
1948        }});
1949        let block: ContentBlock = serde_json::from_value(saved.clone()).unwrap();
1950        let unknown = UnknownBlock::new(json!({"futureBlock": {"name": "shell"}}).as_object().unwrap().clone());
1951        assert_eq!(
1952            block,
1953            ToolResultBlock::success(
1954                "tool-1",
1955                vec![ToolResultContent::text("loaded"), ToolResultContent::Unknown(unknown)]
1956            )
1957            .into()
1958        );
1959        assert_eq!(serde_json::to_value(&block).unwrap(), saved);
1960    }
1961
1962    #[test]
1963    fn tool_reference_block_roundtrips_inside_a_tool_result_through_to_json_and_message_from_json() {
1964        let message = Message::new(
1965            Role::User,
1966            vec![ToolResultBlock::success("tool-1", vec![ToolReferenceBlock::new("shell").into()]).into()],
1967        );
1968        let data = serde_json::to_value(&message).unwrap();
1969        assert_eq!(
1970            data["content"][0],
1971            json!({"toolResult": {"toolUseId": "tool-1", "status": "success", "content": [{"toolReference": {"name": "shell"}}]}})
1972        );
1973        let restored: Message = serde_json::from_value(data).unwrap();
1974        assert_eq!(restored, message);
1975    }
1976
1977    #[test]
1978    fn tool_reference_block_is_converted_by_tool_result_content_from_data() {
1979        assert_eq!(
1980            ToolResultContent::from_data(json!({"toolReference": {"name": "shell"}})).unwrap(),
1981            ToolResultContent::ToolReference(ToolReferenceBlock::new("shell"))
1982        );
1983    }
1984
1985    #[test]
1986    fn content_block_from_data_still_throws_on_unknown_content_inside_a_tool_result() {
1987        let data =
1988            json!({"toolResult": {"toolUseId": "tool-1", "status": "success", "content": [{"futureBlock": {}}]}});
1989        assert_eq!(
1990            ContentBlock::from_data(data).unwrap_err().to_string(),
1991            "Unknown ToolResultContentData type"
1992        );
1993    }
1994
1995    #[test]
1996    fn tool_result_block_from_json_keeps_unknown_content() {
1997        let block: ToolResultBlock = serde_json::from_value(
1998            json!({"toolUseId": "tool-1", "status": "success", "content": [{"futureBlock": {}}]}),
1999        )
2000        .unwrap();
2001        assert_eq!(
2002            block.content,
2003            vec![ToolResultContent::Unknown(UnknownBlock::new(
2004                json!({"futureBlock": {}}).as_object().unwrap().clone()
2005            ))]
2006        );
2007    }
2008
2009    #[test]
2010    fn content_block_from_saved_data_converts_known_types_as_usual_without_a_warning() {
2011        let (block, logs) = capture_warnings(|| serde_json::from_value::<ContentBlock>(json!({"text": "Hello"})));
2012        assert_eq!(block.unwrap(), ContentBlock::text("Hello"));
2013        assert_eq!(logs, "");
2014    }
2015
2016    #[test]
2017    fn message_from_json_restores_the_message_and_serializes_it_back_unchanged() {
2018        let saved = json!({
2019            "role": "assistant",
2020            "content": [{"text": "Hello"}, {"futureBlock": {"nested": {"a": 1}, "items": [1, "two", null]}}],
2021            "trackingId": "durable-1"
2022        });
2023        let message: Message = serde_json::from_value(saved.clone()).unwrap();
2024        assert!(matches!(message.content[1], ContentBlock::Unknown(_)));
2025        assert_eq!(serde_json::to_value(&message).unwrap(), saved);
2026        assert_eq!(
2027            serde_json::to_string(&message).unwrap(),
2028            serde_json::to_string(&saved).unwrap()
2029        );
2030    }
2031
2032    #[test]
2033    fn message_clone_keeps_the_unknown_block_without_warning_again() {
2034        let message: Message = serde_json::from_value(json!({
2035            "role": "assistant",
2036            "content": [{"futureBlock": {"a": 1}}],
2037            "trackingId": "durable-1"
2038        }))
2039        .unwrap();
2040        let (copy, logs) = capture_warnings(|| message.clone());
2041        assert_eq!(copy, message);
2042        assert_eq!(logs, "");
2043    }
2044
2045    #[test]
2046    fn system_prompt_returns_the_string_unchanged() {
2047        let prompt: SystemPrompt = serde_json::from_value(json!("You are a helpful assistant")).unwrap();
2048        assert_eq!(prompt, SystemPrompt::from("You are a helpful assistant"));
2049        assert_eq!(
2050            serde_json::to_value(&prompt).unwrap(),
2051            json!("You are a helpful assistant")
2052        );
2053    }
2054
2055    #[test]
2056    fn system_prompt_converts_all_block_types_correctly() {
2057        let data = json!([
2058            {"text": "System prompt"},
2059            {"cachePoint": {"cacheType": "default"}},
2060            {"guardContent": {"text": {"text": "guard", "qualifiers": ["guard_content"]}}}
2061        ]);
2062        let prompt: SystemPrompt = serde_json::from_value(data.clone()).unwrap();
2063        assert_eq!(
2064            prompt,
2065            SystemPrompt::Blocks(vec![
2066                SystemContentBlock::Text(TextBlock::new("System prompt")),
2067                SystemContentBlock::CachePoint(CachePointBlock::new()),
2068                SystemContentBlock::GuardContent(GuardContentBlock::Text(GuardContentText::new(
2069                    vec![GuardQualifier::GuardContent],
2070                    "guard"
2071                ))),
2072            ])
2073        );
2074        assert_eq!(serde_json::to_value(&prompt).unwrap(), data);
2075    }
2076
2077    #[test]
2078    fn system_prompt_returns_empty_array() {
2079        let prompt: SystemPrompt = serde_json::from_value(json!([])).unwrap();
2080        assert_eq!(prompt, SystemPrompt::Blocks(Vec::new()));
2081        assert_eq!(serde_json::to_value(&prompt).unwrap(), json!([]));
2082    }
2083
2084    #[test]
2085    fn system_prompt_throws_error_for_unknown_block_type() {
2086        let error = serde_json::from_value::<SystemPrompt>(json!([{"unknown": "x"}])).unwrap_err();
2087        assert_eq!(error.to_string(), "Unknown SystemContentBlockData type");
2088    }
2089
2090    #[test]
2091    fn round_trips_every_block_type() {
2092        let blocks: Vec<ContentBlock> = vec![
2093            ContentBlock::text("Hello world"),
2094            ToolUseBlock::new("test-tool", "123", json!({"param": "value"})).into(),
2095            ToolUseBlock::new("test-tool", "123", json!({"param": "value"}))
2096                .with_reasoning_signature("sig123")
2097                .into(),
2098            ToolResultBlock::success("123", vec![ToolResultContent::text("Result text")]).into(),
2099            ToolResultBlock::success("456", vec![ToolResultContent::json(json!({"result": "data"}))]).into(),
2100            ToolResultBlock::error("789", vec![ToolResultContent::text("Error message")]).into(),
2101            ReasoningBlock::new().with_text("Thinking...").into(),
2102            ReasoningBlock::new()
2103                .with_text("Thinking...")
2104                .with_signature("sig123")
2105                .into(),
2106            ReasoningBlock::new().with_redacted_content(vec![1, 2, 3]).into(),
2107            CachePointBlock::new().into(),
2108            InjectedBlock::new("reminder", "test").into(),
2109            GuardContentBlock::Text(GuardContentText::new(vec![GuardQualifier::GuardContent], "Guard this")).into(),
2110            GuardContentBlock::Image(GuardContentImage::new(GuardImageFormat::Png, vec![1, 2, 3])).into(),
2111            AudioBlock::new(AudioFormat::Mp3, AudioSource::Bytes(vec![1, 2, 3])).into(),
2112            UnknownBlock::new(
2113                json!({"futureBlock": {"nested": {"a": 1}}})
2114                    .as_object()
2115                    .unwrap()
2116                    .clone(),
2117            )
2118            .into(),
2119            ImageBlock::new(ImageFormat::Png, ImageSource::Bytes(vec![1, 2, 3])).into(),
2120            CitationsBlock::new(
2121                vec![Citation::new(
2122                    DocumentCharLocation::new(0, 0, 10),
2123                    "doc-0",
2124                    vec![CitationSourceContent::new("source")],
2125                    "Test",
2126                )],
2127                vec![CitationGeneratedContent::new("generated")],
2128            )
2129            .into(),
2130        ];
2131        for block in &blocks {
2132            round_trip_block(block);
2133        }
2134        let messages = [
2135            Message::user("Hello"),
2136            Message::new(
2137                Role::Assistant,
2138                vec![
2139                    ContentBlock::text("Here is the result"),
2140                    ToolUseBlock::new("test-tool", "123", json!({"key": "value"})).into(),
2141                ],
2142            ),
2143            Message::new(
2144                Role::User,
2145                vec![
2146                    ContentBlock::text("Check this image"),
2147                    ImageBlock::new(ImageFormat::Png, ImageSource::Bytes(vec![1, 2, 3])).into(),
2148                ],
2149            ),
2150        ];
2151        for message in &messages {
2152            let restored: Message = serde_json::from_value(serde_json::to_value(message).unwrap()).unwrap();
2153            assert_eq!(&restored, message);
2154        }
2155    }
2156
2157    #[test]
2158    fn message_works_with_json_stringify() {
2159        let original = Message::user("Test");
2160        let restored: Message = serde_json::from_str(&serde_json::to_string(&original).unwrap()).unwrap();
2161        assert_eq!(restored, original);
2162    }
2163
2164    #[test]
2165    fn reasoning_block_from_json_accepts_base64_string_for_redacted_content() {
2166        let block: ContentBlock =
2167            serde_json::from_value(json!({"reasoning": {"redactedContent": "AQIDBAU="}})).unwrap();
2168        assert_eq!(
2169            block,
2170            ReasoningBlock::new().with_redacted_content(vec![1, 2, 3, 4, 5]).into()
2171        );
2172    }
2173
2174    #[test]
2175    fn guard_content_block_from_json_accepts_base64_string_for_image_bytes() {
2176        let block: GuardContentBlock =
2177            serde_json::from_value(json!({"image": {"format": "png", "source": {"bytes": "ChQe"}}})).unwrap();
2178        assert_eq!(block.image().unwrap().source.bytes, vec![10, 20, 30]);
2179    }
2180
2181    #[test]
2182    fn guard_content_block_requires_exactly_one_of_text_or_image() {
2183        let neither = serde_json::from_value::<GuardContentBlock>(json!({})).unwrap_err();
2184        assert_eq!(
2185            neither.to_string(),
2186            "GuardContentBlock must have either text or image content"
2187        );
2188        let both = serde_json::from_value::<GuardContentBlock>(json!({
2189            "text": {"qualifiers": [], "text": "t"},
2190            "image": {"format": "png", "source": {"bytes": ""}}
2191        }))
2192        .unwrap_err();
2193        assert_eq!(
2194            both.to_string(),
2195            "GuardContentBlock cannot have both text and image content"
2196        );
2197    }
2198
2199    #[test]
2200    fn text_block_returns_unwrapped_format() {
2201        assert_eq!(
2202            serde_json::to_value(ContentBlock::text("Test")).unwrap(),
2203            json!({"text": "Test"})
2204        );
2205    }
2206
2207    #[test]
2208    fn json_block_returns_unwrapped_format() {
2209        assert_eq!(
2210            serde_json::to_value(ToolResultContent::json(json!({"test": true}))).unwrap(),
2211            json!({"json": {"test": true}})
2212        );
2213    }
2214
2215    #[test]
2216    fn injected_block_returns_wrapped_format() {
2217        assert_eq!(
2218            serde_json::to_value(ContentBlock::Injected(InjectedBlock::new("reminder", "test"))).unwrap(),
2219            json!({"injected": {"text": "reminder", "source": "test"}})
2220        );
2221    }
2222
2223    #[test]
2224    fn tool_use_block_omits_undefined_reasoning_signature() {
2225        let json = serde_json::to_value(ToolUseBlock::new("test-tool", "123", json!({}))).unwrap();
2226        assert!(json.get("reasoningSignature").is_none());
2227    }
2228
2229    #[test]
2230    fn tool_result_block_does_not_serialize_error_field() {
2231        let block = ToolResultBlock::error("123", vec![ToolResultContent::text("Error")])
2232            .with_error(io::Error::other("Test error"));
2233        let json = serde_json::to_value(&block).unwrap();
2234        assert!(json.get("error").is_none());
2235        assert_eq!(block.error.unwrap().to_string(), "Test error");
2236    }
2237
2238    #[test]
2239    fn reasoning_block_encodes_redacted_content_as_base64() {
2240        let json = serde_json::to_value(ReasoningBlock::new().with_redacted_content(vec![1, 2, 3])).unwrap();
2241        assert_eq!(json, json!({"redactedContent": "AQID"}));
2242    }
2243
2244    #[test]
2245    fn reasoning_block_omits_undefined_fields() {
2246        assert_eq!(
2247            serde_json::to_value(ReasoningBlock::new().with_text("Test")).unwrap(),
2248            json!({"text": "Test"})
2249        );
2250    }
2251
2252    #[test]
2253    fn guard_content_block_encodes_image_bytes_as_base64() {
2254        let block = GuardContentBlock::Image(GuardContentImage::new(GuardImageFormat::Jpeg, vec![1, 2, 3]));
2255        assert_eq!(
2256            serde_json::to_value(&block).unwrap(),
2257            json!({"image": {"format": "jpeg", "source": {"bytes": "AQID"}}})
2258        );
2259    }
2260
2261    #[test]
2262    fn saved_blocks_that_fail_to_decode_load_as_unknown_and_round_trip() {
2263        let saved = json!({
2264            "role": "user",
2265            "content": [
2266                {"image": {"format": "heic", "source": {"bytes": "AQID"}}},
2267                {"toolResult": {"toolUseId": "t-1", "status": "success", "content": [
2268                    {"text": "ok"},
2269                    {"video": {"format": "avi", "source": {"bytes": "AQID"}}}
2270                ]}}
2271            ],
2272            "trackingId": "m-1"
2273        });
2274        let (message, logs) = capture_warnings(|| serde_json::from_value::<Message>(saved.clone()).unwrap());
2275        assert!(matches!(message.content[0], ContentBlock::Unknown(_)));
2276        let ContentBlock::ToolResult(result) = &message.content[1] else {
2277            panic!("expected a tool result");
2278        };
2279        assert!(matches!(result.content[1], ToolResultContent::Unknown(_)));
2280        assert_eq!(serde_json::to_value(&message).unwrap(), saved);
2281        assert!(logs.contains("block_keys=<image> | unrecognized content block type"));
2282        assert!(logs.contains("block_keys=<video> | unrecognized content block type"));
2283    }
2284
2285    #[test]
2286    fn from_data_rejects_a_known_block_that_fails_to_decode() {
2287        let error =
2288            ContentBlock::from_data(json!({"image": {"format": "heic", "source": {"bytes": "AQID"}}})).unwrap_err();
2289        assert!(error.to_string().contains("heic"));
2290    }
2291
2292    #[test]
2293    fn conversions_build_every_block_kind() {
2294        assert_eq!(ToolResultContent::from("a"), ToolResultContent::text("a"));
2295        assert_eq!(ToolResultContent::from(String::from("a")), ToolResultContent::text("a"));
2296        let image = ImageBlock::new(ImageFormat::Png, ImageSource::Url("https://example.com/a.png".into()));
2297        assert_eq!(ToolResultContent::from(image.clone()), ToolResultContent::Image(image));
2298        let text = GuardContentText::new(vec![GuardQualifier::Query], "q");
2299        assert_eq!(GuardContentBlock::from(text.clone()), GuardContentBlock::Text(text));
2300        assert_eq!(SystemContentBlock::from("p"), SystemContentBlock::text("p"));
2301        assert_eq!(
2302            SystemContentBlock::from(CachePointBlock::new()),
2303            SystemContentBlock::CachePoint(CachePointBlock::new())
2304        );
2305    }
2306
2307    #[test]
2308    fn message_text_concatenates_text_blocks() {
2309        let message = Message::new(
2310            Role::Assistant,
2311            vec!["a".into(), ToolUseBlock::new("t", "1", json!({})).into(), "b".into()],
2312        );
2313        assert_eq!(message.text(), "ab");
2314    }
2315
2316    fn dropped(reference: Option<&str>, tokens: Option<u64>) -> TextBlock {
2317        let mut offloaded = Offloaded::new(OffloadMethod::Drop);
2318        offloaded.reference = reference.map(str::to_owned);
2319        offloaded.tokens = tokens;
2320        TextBlock::offloaded("[Dropped] [ref: tu-1]", offloaded)
2321    }
2322
2323    #[test]
2324    fn an_offloaded_block_is_a_text_block_that_serializes_what_it_stands_in_for_beside_the_text() {
2325        let block = ContentBlock::Text(dropped(Some("tu-1"), None));
2326        assert_eq!(block.as_text(), Some("[Dropped] [ref: tu-1]"));
2327        let data = serde_json::to_value(&block).unwrap();
2328        assert_eq!(
2329            data,
2330            json!({"text": "[Dropped] [ref: tu-1]", "offloaded": {"method": "drop", "ref": "tu-1"}})
2331        );
2332        assert_eq!(ContentBlock::from_data(data).unwrap(), block);
2333    }
2334
2335    #[test]
2336    fn an_offloaded_block_omits_a_ref_and_token_count_it_was_not_given() {
2337        let block = TextBlock::offloaded("[Dropped]", Offloaded::new(OffloadMethod::Drop));
2338        assert_eq!(
2339            serde_json::to_value(&block).unwrap(),
2340            json!({"text": "[Dropped]", "offloaded": {"method": "drop"}})
2341        );
2342    }
2343
2344    #[test]
2345    fn a_plain_text_block_carries_and_serializes_no_offloaded_field() {
2346        let block = TextBlock::new("hello");
2347        assert_eq!(serde_json::to_value(&block).unwrap(), json!({"text": "hello"}));
2348        assert!(!block.is_offloaded());
2349        let parsed = ContentBlock::from_data(json!({"text": "hello"})).unwrap();
2350        assert_eq!(parsed, ContentBlock::Text(block));
2351    }
2352
2353    #[test]
2354    fn an_offloaded_block_round_trips_through_message_data_at_top_level_and_inside_a_tool_result() {
2355        let truncated = TextBlock::offloaded(
2356            "row-1 [ref: tu-1]",
2357            Offloaded::new(OffloadMethod::Truncate).with_reference("tu-1"),
2358        );
2359        let message = Message::new(
2360            Role::User,
2361            vec![
2362                ContentBlock::Text(TextBlock::offloaded(
2363                    "[Dropped] [ref: msg-1_0]",
2364                    Offloaded::new(OffloadMethod::Drop).with_reference("msg-1_0"),
2365                )),
2366                ContentBlock::ToolResult(ToolResultBlock::success(
2367                    "tu-1",
2368                    vec![ToolResultContent::Text(truncated)],
2369                )),
2370            ],
2371        )
2372        .with_tracking_id("msg-1");
2373        let data = serde_json::to_value(&message).unwrap();
2374        assert_eq!(
2375            data["content"],
2376            json!([
2377                {"text": "[Dropped] [ref: msg-1_0]", "offloaded": {"method": "drop", "ref": "msg-1_0"}},
2378                {"toolResult": {"toolUseId": "tu-1", "status": "success", "content": [
2379                    {"text": "row-1 [ref: tu-1]", "offloaded": {"method": "truncate", "ref": "tu-1"}}
2380                ]}}
2381            ])
2382        );
2383        assert_eq!(Message::from_message_data(data.clone()).unwrap(), message);
2384        assert_eq!(serde_json::from_value::<Message>(data).unwrap(), message);
2385    }
2386
2387    #[test]
2388    fn with_content_replaces_content_keeping_role_tracking_id_and_metadata() {
2389        let mut custom = JsonObject::new();
2390        custom.insert("pinned".to_owned(), JsonValue::Bool(true));
2391        let metadata = MessageMetadata::new().with_custom(custom);
2392        let message = Message::user("a")
2393            .with_tracking_id("m1")
2394            .with_metadata(metadata.clone());
2395        let copy = message.clone().with_content(vec![ContentBlock::text("b")]);
2396        assert_eq!(copy, Message::user("b").with_tracking_id("m1").with_metadata(metadata));
2397        assert_eq!(message.content, [ContentBlock::text("a")]);
2398    }
2399
2400    #[test]
2401    fn tool_result_with_content_replaces_content_keeping_tool_use_id_status_and_error() {
2402        let block =
2403            ToolResultBlock::error("t", vec![ToolResultContent::text("a")]).with_error(std::io::Error::other("boom"));
2404        let copy = block.with_content(vec![ToolResultContent::text("b")]);
2405        assert_eq!(copy, ToolResultBlock::error("t", vec![ToolResultContent::text("b")]));
2406        assert!(copy.error.is_some());
2407    }
2408}