Skip to main content

reef_core/transcript/
item.rs

1//! Closed, owned records stored in a transcript.
2
3use std::fmt::{self, Debug, Formatter};
4
5use crate::opaque::Envelope;
6use crate::redact;
7use crate::value::content::{self, Metadata, Part, Segment};
8use crate::value::tool_call::{self, Id};
9
10/// Whether a record participates in model projection.
11///
12/// Persistence and a user-facing timeline may retain [`ModelVisibility::Hidden`]
13/// records even though model projection omits them. Every [`Item`] variant
14/// carries one, so the projection rule is total: there is no record shape whose
15/// model visibility is undecided.
16///
17/// # Exchange visibility
18///
19/// A tool exchange is visible as a whole or not at all. Every
20/// [`ToolResult`] reef commits for a generation takes the visibility of the
21/// [`Assistant`] record that carries its call, so hiding an assistant record
22/// hides the results answering it. A history that violates this — a visible
23/// result whose call is hidden, or a visible call whose result is hidden — is
24/// refused by
25/// [`RequestPlan::try_into_request`](crate::runtime::model::RequestPlan::try_into_request) rather
26/// than silently projected into an illegal request.
27#[derive(Clone, Copy, Debug, Eq, PartialEq)]
28pub enum ModelVisibility {
29    /// Include the record in model projection.
30    Visible,
31    /// Retain the record while omitting it from model projection.
32    Hidden,
33}
34
35/// One closed transcript record.
36///
37/// The variant set is closed by ADR-004. Lifecycle and audit facts are
38/// deliberately not transcript items.
39///
40/// ```
41/// use reef_core::transcript::item;
42/// let item = item::Item::System(item::System::new(
43///     "instruction".into(), "Be concise.".into(), item::ModelVisibility::Visible,
44/// ));
45/// assert!(matches!(item, item::Item::System(system) if system.text() == "Be concise."));
46/// ```
47#[derive(Clone, Debug)]
48pub enum Item {
49    /// User-authored ordered content.
50    User(User),
51    /// Assistant-produced ordered content.
52    Assistant(Assistant),
53    /// The result of one model tool call.
54    ToolResult(ToolResult),
55    /// System-authored text.
56    System(System),
57}
58
59impl Item {
60    /// Renders this record's text the way a reader would be shown it.
61    ///
62    /// Reading a transcript is the first thing anyone does with an agent, and
63    /// without this it takes a four-arm match plus a walk into
64    /// [`Part::fields`](crate::value::content::Part::fields) or
65    /// [`Segment`] per arm — the same twenty lines every consumer writes on
66    /// their first day.
67    ///
68    /// ```
69    /// use reef_core::transcript::item;
70    /// use reef_core::value::content;
71    ///
72    /// let extensions = || content::SegmentExtensions::new(String::new(), None, None);
73    /// let answer = item::Item::Assistant(item::Assistant::new(
74    ///     vec![
75    ///         content::Segment::Thinking { text: "the user wants a greeting".into(), extensions: extensions() },
76    ///         content::Segment::Text { text: "Hello.".into(), extensions: extensions() },
77    ///     ],
78    ///     None,
79    /// ));
80    /// assert_eq!(answer.to_plain_text(), "Hello.");
81    ///
82    /// let question = item::Item::User(item::User::new(
83    ///     vec![content::Part::text("Greet me.".into())],
84    ///     item::ModelVisibility::Visible,
85    /// ));
86    /// assert_eq!(question.to_plain_text(), "Greet me.");
87    /// ```
88    ///
89    /// # What each record renders as
90    ///
91    /// - [`User`]: the text of every part, in order. A part carrying an image or
92    ///   opaque data has no text and contributes nothing.
93    /// - [`Assistant`]: the text of every [`Segment::Text`]. Reasoning and tool
94    ///   calls are not text the reader is being shown; [`Assistant::content`]
95    ///   has them, in provider order, and always did.
96    /// - [`ToolResult`]: exactly what
97    ///   [`tool_call::ToolResult::to_plain_text`] renders, which this arm calls
98    ///   rather than restates. That rule prefers the output's
99    ///   [`user_view`](crate::value::tool_call::ToolOutput::user_view) over its
100    ///   model content, and it belongs to the closed result value rather than to
101    ///   this record: a record adds a call identity, a tool name, a visibility
102    ///   and item metadata, none of which the rendering reads.
103    /// - [`System`]: its text.
104    ///
105    /// Two blocks are separated by a single `\n` and nothing else is added, so a
106    /// record with one block renders exactly that block.
107    ///
108    /// # This is not a way around redaction
109    ///
110    /// It is an accessor, and every byte it returns is already reachable through
111    /// the typed accessor that owns it — which is precisely why ADR-018 refused
112    /// an unredacted `Debug`: there is nothing here to hide *from*, only
113    /// something to make convenient. What that ADR protects against is
114    /// *accidental* disclosure, so this stays explicit at the call site. There
115    /// is deliberately no [`Display`](std::fmt::Display) for an [`Item`]: a
116    /// `Display` can be interpolated into a log message by someone who never
117    /// decided to print a transcript, and `{item}` would look like nothing at
118    /// all. `item.to_plain_text()` cannot be written by accident.
119    #[must_use]
120    pub fn to_plain_text(&self) -> String {
121        match self {
122            Self::User(user) => {
123                content::join_blocks(user.parts().iter().map(|part| part.fields().text()))
124            }
125            Self::Assistant(assistant) => {
126                content::join_blocks(assistant.content().iter().filter_map(
127                    |segment| match segment {
128                        Segment::Text { text, .. } => Some(text.as_str()),
129                        Segment::Thinking { .. } | Segment::ToolCall { .. } => None,
130                    },
131                ))
132            }
133            Self::ToolResult(record) => record.result().to_plain_text(),
134            Self::System(system) => system.text().to_owned(),
135        }
136    }
137}
138
139/// A user-authored transcript record.
140///
141/// ```compile_fail
142/// use reef_core::transcript::item;
143/// let _forged = item::User { parts: vec![], visibility: item::ModelVisibility::Visible };
144/// ```
145#[derive(Clone, Debug)]
146pub struct User {
147    parts: Vec<Part>,
148    visibility: ModelVisibility,
149}
150
151impl User {
152    /// Creates a user record while retaining part order.
153    #[must_use]
154    pub const fn new(parts: Vec<Part>, visibility: ModelVisibility) -> Self {
155        Self { parts, visibility }
156    }
157
158    /// Returns the ordered user content.
159    #[must_use]
160    pub fn parts(&self) -> &[Part] {
161        &self.parts
162    }
163
164    /// Returns this record's model visibility.
165    #[must_use]
166    pub const fn visibility(&self) -> ModelVisibility {
167        self.visibility
168    }
169}
170
171/// An assistant-output transcript record.
172///
173/// `content` is the sole source of truth. Text, thinking, and calls remain in
174/// their original provider order rather than being flattened into parallel
175/// collections. Record-level provider data is metadata, not another segment.
176///
177/// An assistant record is [`ModelVisibility::Visible`] unless
178/// [`Assistant::with_visibility`] says otherwise: the model said it, so by
179/// default the model may see it again. [`ModelVisibility::Hidden`] is what a hook
180/// selects when it replaces the record through
181/// [`AfterModelDecision::Modify`](crate::runtime::hook::AfterModelDecision::Modify)
182/// or supplies one through
183/// [`BeforeModelDecision::ShortCircuit`](crate::runtime::hook::BeforeModelDecision::ShortCircuit),
184/// which is how a history stays complete for a user-facing timeline while the
185/// model is sent less than all of it. Because reef propagates this record's
186/// visibility onto every result committed with it, hiding a record that carries
187/// tool calls also hides their results, and the projected request stays legal.
188///
189/// ```
190/// use reef_core::transcript::item;
191/// use reef_core::value::content;
192/// let extensions = || content::SegmentExtensions::new(String::new(), None, None);
193/// let item = item::Assistant::new(vec![
194///     content::Segment::Text { text: "a".into(), extensions: extensions() },
195///     content::Segment::Thinking { text: "b".into(), extensions: extensions() },
196/// ], Some(vec![]));
197/// assert_eq!(item.content().len(), 2);
198/// assert!(item.provider_data().is_some_and(<[_]>::is_empty));
199/// assert_eq!(item.visibility(), item::ModelVisibility::Visible);
200///
201/// let hidden = item.with_visibility(item::ModelVisibility::Hidden);
202/// assert_eq!(hidden.visibility(), item::ModelVisibility::Hidden);
203/// ```
204///
205/// ```compile_fail
206/// use reef_core::transcript::item;
207/// let _forged = item::Assistant {
208///     content: vec![], provider_data: None, visibility: item::ModelVisibility::Visible,
209/// };
210/// ```
211#[derive(Clone, Debug)]
212pub struct Assistant {
213    content: Vec<Segment>,
214    provider_data: Option<Vec<Envelope>>,
215    visibility: ModelVisibility,
216}
217
218impl Assistant {
219    /// Creates a model-visible assistant record from ordered segments and
220    /// record metadata.
221    #[must_use]
222    pub const fn new(content: Vec<Segment>, provider_data: Option<Vec<Envelope>>) -> Self {
223        Self {
224            content,
225            provider_data,
226            visibility: ModelVisibility::Visible,
227        }
228    }
229
230    /// Declares whether this record participates in model projection.
231    #[must_use]
232    pub const fn with_visibility(mut self, visibility: ModelVisibility) -> Self {
233        self.visibility = visibility;
234        self
235    }
236
237    /// Returns the authoritative ordered segments.
238    #[must_use]
239    pub fn content(&self) -> &[Segment] {
240        &self.content
241    }
242
243    /// Returns ordered record-level provider metadata, preserving presence.
244    #[must_use]
245    pub fn provider_data(&self) -> Option<&[Envelope]> {
246        self.provider_data.as_deref()
247    }
248
249    /// Returns this record's model visibility.
250    #[must_use]
251    pub const fn visibility(&self) -> ModelVisibility {
252        self.visibility
253    }
254}
255
256/// A transcript record containing one closed tool result.
257///
258/// Item metadata is an independent transport channel and is never reconstructed
259/// from, or written back into, [`tool_call::ToolResult`] output metadata.
260///
261/// `ModelVisibility` is a free parameter at this constructor, because a composition
262/// layer restoring or rewriting a history owns both halves of an exchange. The
263/// records reef itself commits take the visibility of the [`Assistant`] record
264/// carrying the call, so reef never authors a half-hidden exchange.
265///
266/// ```
267/// use reef_core::transcript::item;
268/// use reef_core::value::{content, tool_call};
269/// let item = item::ToolResult::new(
270///     tool_call::Id::new("call-1".into()), tool_call::Name::new("search".into()),
271///     tool_call::ToolResult::no_output(), item::ModelVisibility::Visible, Some(content::Metadata::new()),
272/// );
273/// assert_eq!(item.call_id().as_str(), "call-1");
274/// assert!(item.metadata().is_some());
275/// assert!(!item.is_business_error());
276/// ```
277///
278/// ```compile_fail
279/// use reef_core::transcript::item;
280/// use reef_core::value::tool_call;
281/// let _forged = item::ToolResult {
282///     call_id: tool_call::Id::new("id".into()), tool_name: tool_call::Name::new("tool".into()),
283///     result: tool_call::ToolResult::no_output(), visibility: item::ModelVisibility::Visible, metadata: None,
284/// };
285/// ```
286#[derive(Clone, Debug)]
287pub struct ToolResult {
288    call_id: Id,
289    tool_name: tool_call::Name,
290    result: tool_call::ToolResult,
291    visibility: ModelVisibility,
292    metadata: Option<Metadata>,
293}
294
295impl ToolResult {
296    /// Creates a tool-result record with independent item metadata.
297    #[must_use]
298    pub const fn new(
299        call_id: Id,
300        tool_name: tool_call::Name,
301        result: tool_call::ToolResult,
302        visibility: ModelVisibility,
303        metadata: Option<Metadata>,
304    ) -> Self {
305        Self {
306            call_id,
307            tool_name,
308            result,
309            visibility,
310            metadata,
311        }
312    }
313
314    /// Returns the call identity used for correlation.
315    #[must_use]
316    pub const fn call_id(&self) -> &Id {
317        &self.call_id
318    }
319
320    /// Returns the name of the tool that produced the result.
321    #[must_use]
322    pub const fn tool_name(&self) -> &tool_call::Name {
323        &self.tool_name
324    }
325
326    /// Returns the closed tool result.
327    #[must_use]
328    pub const fn result(&self) -> &tool_call::ToolResult {
329        &self.result
330    }
331
332    /// Returns this record's model visibility.
333    #[must_use]
334    pub const fn visibility(&self) -> ModelVisibility {
335        self.visibility
336    }
337
338    /// Returns independent item-level metadata, preserving absent versus empty.
339    #[must_use]
340    pub const fn metadata(&self) -> Option<&Metadata> {
341        self.metadata.as_ref()
342    }
343
344    /// Reports whether the result is an explicit business error.
345    #[must_use]
346    pub const fn is_business_error(&self) -> bool {
347        self.result.is_business_error()
348    }
349}
350
351/// A system-authored transcript record.
352///
353/// `subtype` is a producer-owned free-form label; core assigns it no meaning.
354/// Empty subtype and text values remain representable at this leaf boundary.
355///
356/// ```compile_fail
357/// use reef_core::transcript::item;
358/// let _forged = item::System {
359///     subtype: String::new(), text: String::new(), visibility: item::ModelVisibility::Visible,
360/// };
361/// ```
362#[derive(Clone)]
363pub struct System {
364    subtype: String,
365    text: String,
366    visibility: ModelVisibility,
367}
368
369impl Debug for System {
370    /// Prints the subtype in full and sizes the instruction.
371    ///
372    /// The two strings have different provenance even though they sit side by
373    /// side: `subtype` is a producer-owned label that selects a record class,
374    /// while `text` is a system instruction on its way to the model.
375    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
376        formatter
377            .debug_struct("System")
378            .field("subtype", &self.subtype)
379            .field("text", &redact::Bytes(self.text.len()))
380            .field("visibility", &self.visibility)
381            .finish()
382    }
383}
384
385impl System {
386    /// Creates a system record without interpreting its subtype or text.
387    #[must_use]
388    pub const fn new(subtype: String, text: String, visibility: ModelVisibility) -> Self {
389        Self {
390            subtype,
391            text,
392            visibility,
393        }
394    }
395
396    /// Returns the producer-defined subtype.
397    #[must_use]
398    pub fn subtype(&self) -> &str {
399        &self.subtype
400    }
401
402    /// Returns the system-authored text.
403    #[must_use]
404    pub fn text(&self) -> &str {
405        &self.text
406    }
407
408    /// Returns this record's model visibility.
409    #[must_use]
410    pub const fn visibility(&self) -> ModelVisibility {
411        self.visibility
412    }
413}
414
415/// The serialized form of the transcript records (ADR-019 D5).
416///
417/// Every record shape carries its own [`ModelVisibility`], and the wire carries it per
418/// record for the reason ADR-022 D1 gives: a format that dropped it would restore
419/// a session by resurrecting history the composition layer had hidden. The
420/// invariant that a tool exchange is hidden whole is a property a codec can
421/// violate silently — the orphan only appears later, at projection time — so it
422/// is one a codec has to preserve deliberately, and reading a record back gives
423/// exactly the visibility that was written.
424///
425/// [`Assistant`] is the one record whose constructor does not take a visibility:
426/// it is built model-visible and then narrowed through
427/// [`Assistant::with_visibility`], which is the same path a hook takes.
428#[cfg(feature = "serde")]
429mod serde_impl {
430    use std::fmt::{self, Formatter};
431
432    use serde_core::de::{
433        Deserialize, Deserializer, EnumAccess, Error as DeError, MapAccess, SeqAccess,
434        VariantAccess, Visitor,
435    };
436    use serde_core::ser::{Serialize, SerializeStruct, Serializer};
437
438    use super::{Assistant, Item, ModelVisibility, System, ToolResult, User};
439    use crate::wire::{self, IdentifierSeed};
440
441    const VISIBILITY_NAME: &str = "ModelVisibility";
442    const VISIBILITY_VARIANTS: &[&str] = &["both", "user_only"];
443    const USER_FIELDS: &[&str] = &["parts", "visibility"];
444    const ASSISTANT_FIELDS: &[&str] = &["content", "provider_data", "visibility"];
445    const TOOL_RESULT_FIELDS: &[&str] =
446        &["call_id", "tool_name", "result", "visibility", "metadata"];
447    const SYSTEM_FIELDS: &[&str] = &["subtype", "text", "visibility"];
448    const ITEM_NAME: &str = "Item";
449    const ITEM_VARIANTS: &[&str] = &["user", "assistant", "tool_result", "system"];
450
451    // -- ModelVisibility ----------------------------------------------------------
452
453    impl Serialize for ModelVisibility {
454        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
455        where
456            S: Serializer,
457        {
458            let (index, tag) = match self {
459                Self::Visible => (0, "both"),
460                Self::Hidden => (1, "user_only"),
461            };
462            serializer.serialize_unit_variant(VISIBILITY_NAME, index, tag)
463        }
464    }
465
466    impl<'de> Deserialize<'de> for ModelVisibility {
467        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
468        where
469            D: Deserializer<'de>,
470        {
471            deserializer.deserialize_enum(VISIBILITY_NAME, VISIBILITY_VARIANTS, VisibilityVisitor)
472        }
473    }
474
475    struct VisibilityVisitor;
476
477    impl<'de> Visitor<'de> for VisibilityVisitor {
478        type Value = ModelVisibility;
479
480        fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
481            formatter.write_str("a record visibility")
482        }
483
484        fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
485        where
486            A: EnumAccess<'de>,
487        {
488            let (tag, variant) = data.variant_seed(IdentifierSeed(VISIBILITY_VARIANTS))?;
489            variant.unit_variant()?;
490            match tag.0.as_str() {
491                "both" => Ok(ModelVisibility::Visible),
492                "user_only" => Ok(ModelVisibility::Hidden),
493                unknown => Err(A::Error::unknown_variant(unknown, VISIBILITY_VARIANTS)),
494            }
495        }
496    }
497
498    // -- User ----------------------------------------------------------------
499
500    impl Serialize for User {
501        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
502        where
503            S: Serializer,
504        {
505            let mut record = serializer.serialize_struct("User", 2)?;
506            record.serialize_field("parts", &self.parts)?;
507            record.serialize_field("visibility", &self.visibility)?;
508            record.end()
509        }
510    }
511
512    impl<'de> Deserialize<'de> for User {
513        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
514        where
515            D: Deserializer<'de>,
516        {
517            deserializer.deserialize_struct("User", USER_FIELDS, UserVisitor)
518        }
519    }
520
521    struct UserVisitor;
522
523    impl<'de> Visitor<'de> for UserVisitor {
524        type Value = User;
525
526        fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
527            formatter.write_str("a user record")
528        }
529
530        fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
531        where
532            A: SeqAccess<'de>,
533        {
534            let parts = wire::element(&mut sequence, 0)?;
535            let visibility = wire::element(&mut sequence, 1)?;
536            wire::end(&mut sequence, 2)?;
537            Ok(User::new(parts, visibility))
538        }
539
540        fn visit_map<A>(self, mut entries: A) -> Result<Self::Value, A::Error>
541        where
542            A: MapAccess<'de>,
543        {
544            let mut parts = None;
545            let mut visibility = None;
546            while let Some(field) = entries.next_key_seed(IdentifierSeed(USER_FIELDS))? {
547                match field.0.as_str() {
548                    "parts" => wire::accept(&mut parts, entries.next_value()?, "parts")?,
549                    "visibility" => {
550                        wire::accept(&mut visibility, entries.next_value()?, "visibility")?;
551                    }
552                    unknown => return Err(A::Error::unknown_field(unknown, USER_FIELDS)),
553                }
554            }
555            Ok(User::new(
556                wire::require(parts, "parts")?,
557                wire::require(visibility, "visibility")?,
558            ))
559        }
560    }
561
562    // -- Assistant -----------------------------------------------------------
563
564    impl Serialize for Assistant {
565        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
566        where
567            S: Serializer,
568        {
569            let mut record = serializer.serialize_struct("Assistant", 3)?;
570            record.serialize_field("content", &self.content)?;
571            record.serialize_field("provider_data", &self.provider_data)?;
572            record.serialize_field("visibility", &self.visibility)?;
573            record.end()
574        }
575    }
576
577    impl<'de> Deserialize<'de> for Assistant {
578        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
579        where
580            D: Deserializer<'de>,
581        {
582            deserializer.deserialize_struct("Assistant", ASSISTANT_FIELDS, AssistantVisitor)
583        }
584    }
585
586    struct AssistantVisitor;
587
588    impl<'de> Visitor<'de> for AssistantVisitor {
589        type Value = Assistant;
590
591        fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
592            formatter.write_str("an assistant record")
593        }
594
595        fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
596        where
597            A: SeqAccess<'de>,
598        {
599            let content = wire::element(&mut sequence, 0)?;
600            let provider_data = wire::element(&mut sequence, 1)?;
601            let visibility = wire::element(&mut sequence, 2)?;
602            wire::end(&mut sequence, 3)?;
603            Ok(Assistant::new(content, provider_data).with_visibility(visibility))
604        }
605
606        fn visit_map<A>(self, mut entries: A) -> Result<Self::Value, A::Error>
607        where
608            A: MapAccess<'de>,
609        {
610            let mut content = None;
611            let mut provider_data = None;
612            let mut visibility = None;
613            while let Some(field) = entries.next_key_seed(IdentifierSeed(ASSISTANT_FIELDS))? {
614                match field.0.as_str() {
615                    "content" => wire::accept(&mut content, entries.next_value()?, "content")?,
616                    "provider_data" => {
617                        wire::accept(&mut provider_data, entries.next_value()?, "provider_data")?;
618                    }
619                    "visibility" => {
620                        wire::accept(&mut visibility, entries.next_value()?, "visibility")?;
621                    }
622                    unknown => return Err(A::Error::unknown_field(unknown, ASSISTANT_FIELDS)),
623                }
624            }
625            Ok(Assistant::new(
626                wire::require(content, "content")?,
627                wire::require(provider_data, "provider_data")?,
628            )
629            .with_visibility(wire::require(visibility, "visibility")?))
630        }
631    }
632
633    // -- ToolResult ----------------------------------------------------------
634
635    impl Serialize for ToolResult {
636        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
637        where
638            S: Serializer,
639        {
640            let mut record = serializer.serialize_struct("ToolResult", 5)?;
641            record.serialize_field("call_id", &self.call_id)?;
642            record.serialize_field("tool_name", &self.tool_name)?;
643            record.serialize_field("result", &self.result)?;
644            record.serialize_field("visibility", &self.visibility)?;
645            record.serialize_field("metadata", &self.metadata)?;
646            record.end()
647        }
648    }
649
650    impl<'de> Deserialize<'de> for ToolResult {
651        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
652        where
653            D: Deserializer<'de>,
654        {
655            deserializer.deserialize_struct("ToolResult", TOOL_RESULT_FIELDS, ToolResultVisitor)
656        }
657    }
658
659    struct ToolResultVisitor;
660
661    impl<'de> Visitor<'de> for ToolResultVisitor {
662        type Value = ToolResult;
663
664        fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
665            formatter.write_str("a tool-result record")
666        }
667
668        fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
669        where
670            A: SeqAccess<'de>,
671        {
672            let call_id = wire::element(&mut sequence, 0)?;
673            let tool_name = wire::element(&mut sequence, 1)?;
674            let result = wire::element(&mut sequence, 2)?;
675            let visibility = wire::element(&mut sequence, 3)?;
676            let metadata = wire::element(&mut sequence, 4)?;
677            wire::end(&mut sequence, 5)?;
678            Ok(ToolResult::new(
679                call_id, tool_name, result, visibility, metadata,
680            ))
681        }
682
683        fn visit_map<A>(self, mut entries: A) -> Result<Self::Value, A::Error>
684        where
685            A: MapAccess<'de>,
686        {
687            let mut call_id = None;
688            let mut tool_name = None;
689            let mut result = None;
690            let mut visibility = None;
691            let mut metadata = None;
692            while let Some(field) = entries.next_key_seed(IdentifierSeed(TOOL_RESULT_FIELDS))? {
693                match field.0.as_str() {
694                    "call_id" => wire::accept(&mut call_id, entries.next_value()?, "call_id")?,
695                    "tool_name" => {
696                        wire::accept(&mut tool_name, entries.next_value()?, "tool_name")?;
697                    }
698                    "result" => wire::accept(&mut result, entries.next_value()?, "result")?,
699                    "visibility" => {
700                        wire::accept(&mut visibility, entries.next_value()?, "visibility")?;
701                    }
702                    "metadata" => wire::accept(&mut metadata, entries.next_value()?, "metadata")?,
703                    unknown => return Err(A::Error::unknown_field(unknown, TOOL_RESULT_FIELDS)),
704                }
705            }
706            Ok(ToolResult::new(
707                wire::require(call_id, "call_id")?,
708                wire::require(tool_name, "tool_name")?,
709                wire::require(result, "result")?,
710                wire::require(visibility, "visibility")?,
711                wire::require(metadata, "metadata")?,
712            ))
713        }
714    }
715
716    // -- System --------------------------------------------------------------
717
718    impl Serialize for System {
719        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
720        where
721            S: Serializer,
722        {
723            let mut record = serializer.serialize_struct("System", 3)?;
724            record.serialize_field("subtype", &self.subtype)?;
725            record.serialize_field("text", &self.text)?;
726            record.serialize_field("visibility", &self.visibility)?;
727            record.end()
728        }
729    }
730
731    impl<'de> Deserialize<'de> for System {
732        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
733        where
734            D: Deserializer<'de>,
735        {
736            deserializer.deserialize_struct("System", SYSTEM_FIELDS, SystemVisitor)
737        }
738    }
739
740    struct SystemVisitor;
741
742    impl<'de> Visitor<'de> for SystemVisitor {
743        type Value = System;
744
745        fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
746            formatter.write_str("a system record")
747        }
748
749        fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
750        where
751            A: SeqAccess<'de>,
752        {
753            let subtype = wire::element(&mut sequence, 0)?;
754            let text = wire::element(&mut sequence, 1)?;
755            let visibility = wire::element(&mut sequence, 2)?;
756            wire::end(&mut sequence, 3)?;
757            Ok(System::new(subtype, text, visibility))
758        }
759
760        fn visit_map<A>(self, mut entries: A) -> Result<Self::Value, A::Error>
761        where
762            A: MapAccess<'de>,
763        {
764            let mut subtype = None;
765            let mut text = None;
766            let mut visibility = None;
767            while let Some(field) = entries.next_key_seed(IdentifierSeed(SYSTEM_FIELDS))? {
768                match field.0.as_str() {
769                    "subtype" => wire::accept(&mut subtype, entries.next_value()?, "subtype")?,
770                    "text" => wire::accept(&mut text, entries.next_value()?, "text")?,
771                    "visibility" => {
772                        wire::accept(&mut visibility, entries.next_value()?, "visibility")?;
773                    }
774                    unknown => return Err(A::Error::unknown_field(unknown, SYSTEM_FIELDS)),
775                }
776            }
777            Ok(System::new(
778                wire::require(subtype, "subtype")?,
779                wire::require(text, "text")?,
780                wire::require(visibility, "visibility")?,
781            ))
782        }
783    }
784
785    // -- Item ----------------------------------------------------------------
786
787    impl Serialize for Item {
788        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
789        where
790            S: Serializer,
791        {
792            match self {
793                Self::User(record) => {
794                    serializer.serialize_newtype_variant(ITEM_NAME, 0, "user", record)
795                }
796                Self::Assistant(record) => {
797                    serializer.serialize_newtype_variant(ITEM_NAME, 1, "assistant", record)
798                }
799                Self::ToolResult(record) => {
800                    serializer.serialize_newtype_variant(ITEM_NAME, 2, "tool_result", record)
801                }
802                Self::System(record) => {
803                    serializer.serialize_newtype_variant(ITEM_NAME, 3, "system", record)
804                }
805            }
806        }
807    }
808
809    impl<'de> Deserialize<'de> for Item {
810        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
811        where
812            D: Deserializer<'de>,
813        {
814            deserializer.deserialize_enum(ITEM_NAME, ITEM_VARIANTS, ItemVisitor)
815        }
816    }
817
818    struct ItemVisitor;
819
820    impl<'de> Visitor<'de> for ItemVisitor {
821        type Value = Item;
822
823        fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
824            formatter.write_str("a transcript record")
825        }
826
827        fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
828        where
829            A: EnumAccess<'de>,
830        {
831            let (tag, variant) = data.variant_seed(IdentifierSeed(ITEM_VARIANTS))?;
832            match tag.0.as_str() {
833                "user" => variant.newtype_variant().map(Item::User),
834                "assistant" => variant.newtype_variant().map(Item::Assistant),
835                "tool_result" => variant.newtype_variant().map(Item::ToolResult),
836                "system" => variant.newtype_variant().map(Item::System),
837                unknown => Err(A::Error::unknown_variant(unknown, ITEM_VARIANTS)),
838            }
839        }
840    }
841}