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            Ok(User::new(parts, visibility))
537        }
538
539        fn visit_map<A>(self, mut entries: A) -> Result<Self::Value, A::Error>
540        where
541            A: MapAccess<'de>,
542        {
543            let mut parts = None;
544            let mut visibility = None;
545            while let Some(field) = entries.next_key_seed(IdentifierSeed(USER_FIELDS))? {
546                match field.0.as_str() {
547                    "parts" => wire::accept(&mut parts, entries.next_value()?, "parts")?,
548                    "visibility" => {
549                        wire::accept(&mut visibility, entries.next_value()?, "visibility")?;
550                    }
551                    unknown => return Err(A::Error::unknown_field(unknown, USER_FIELDS)),
552                }
553            }
554            Ok(User::new(
555                wire::require(parts, "parts")?,
556                wire::require(visibility, "visibility")?,
557            ))
558        }
559    }
560
561    // -- Assistant -----------------------------------------------------------
562
563    impl Serialize for Assistant {
564        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
565        where
566            S: Serializer,
567        {
568            let mut record = serializer.serialize_struct("Assistant", 3)?;
569            record.serialize_field("content", &self.content)?;
570            record.serialize_field("provider_data", &self.provider_data)?;
571            record.serialize_field("visibility", &self.visibility)?;
572            record.end()
573        }
574    }
575
576    impl<'de> Deserialize<'de> for Assistant {
577        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
578        where
579            D: Deserializer<'de>,
580        {
581            deserializer.deserialize_struct("Assistant", ASSISTANT_FIELDS, AssistantVisitor)
582        }
583    }
584
585    struct AssistantVisitor;
586
587    impl<'de> Visitor<'de> for AssistantVisitor {
588        type Value = Assistant;
589
590        fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
591            formatter.write_str("an assistant record")
592        }
593
594        fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
595        where
596            A: SeqAccess<'de>,
597        {
598            let content = wire::element(&mut sequence, 0)?;
599            let provider_data = wire::element(&mut sequence, 1)?;
600            let visibility = wire::element(&mut sequence, 2)?;
601            Ok(Assistant::new(content, provider_data).with_visibility(visibility))
602        }
603
604        fn visit_map<A>(self, mut entries: A) -> Result<Self::Value, A::Error>
605        where
606            A: MapAccess<'de>,
607        {
608            let mut content = None;
609            let mut provider_data = None;
610            let mut visibility = None;
611            while let Some(field) = entries.next_key_seed(IdentifierSeed(ASSISTANT_FIELDS))? {
612                match field.0.as_str() {
613                    "content" => wire::accept(&mut content, entries.next_value()?, "content")?,
614                    "provider_data" => {
615                        wire::accept(&mut provider_data, entries.next_value()?, "provider_data")?;
616                    }
617                    "visibility" => {
618                        wire::accept(&mut visibility, entries.next_value()?, "visibility")?;
619                    }
620                    unknown => return Err(A::Error::unknown_field(unknown, ASSISTANT_FIELDS)),
621                }
622            }
623            Ok(Assistant::new(
624                wire::require(content, "content")?,
625                wire::require(provider_data, "provider_data")?,
626            )
627            .with_visibility(wire::require(visibility, "visibility")?))
628        }
629    }
630
631    // -- ToolResult ----------------------------------------------------------
632
633    impl Serialize for ToolResult {
634        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
635        where
636            S: Serializer,
637        {
638            let mut record = serializer.serialize_struct("ToolResult", 5)?;
639            record.serialize_field("call_id", &self.call_id)?;
640            record.serialize_field("tool_name", &self.tool_name)?;
641            record.serialize_field("result", &self.result)?;
642            record.serialize_field("visibility", &self.visibility)?;
643            record.serialize_field("metadata", &self.metadata)?;
644            record.end()
645        }
646    }
647
648    impl<'de> Deserialize<'de> for ToolResult {
649        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
650        where
651            D: Deserializer<'de>,
652        {
653            deserializer.deserialize_struct("ToolResult", TOOL_RESULT_FIELDS, ToolResultVisitor)
654        }
655    }
656
657    struct ToolResultVisitor;
658
659    impl<'de> Visitor<'de> for ToolResultVisitor {
660        type Value = ToolResult;
661
662        fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
663            formatter.write_str("a tool-result record")
664        }
665
666        fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
667        where
668            A: SeqAccess<'de>,
669        {
670            let call_id = wire::element(&mut sequence, 0)?;
671            let tool_name = wire::element(&mut sequence, 1)?;
672            let result = wire::element(&mut sequence, 2)?;
673            let visibility = wire::element(&mut sequence, 3)?;
674            let metadata = wire::element(&mut sequence, 4)?;
675            Ok(ToolResult::new(
676                call_id, tool_name, result, visibility, metadata,
677            ))
678        }
679
680        fn visit_map<A>(self, mut entries: A) -> Result<Self::Value, A::Error>
681        where
682            A: MapAccess<'de>,
683        {
684            let mut call_id = None;
685            let mut tool_name = None;
686            let mut result = None;
687            let mut visibility = None;
688            let mut metadata = None;
689            while let Some(field) = entries.next_key_seed(IdentifierSeed(TOOL_RESULT_FIELDS))? {
690                match field.0.as_str() {
691                    "call_id" => wire::accept(&mut call_id, entries.next_value()?, "call_id")?,
692                    "tool_name" => {
693                        wire::accept(&mut tool_name, entries.next_value()?, "tool_name")?;
694                    }
695                    "result" => wire::accept(&mut result, entries.next_value()?, "result")?,
696                    "visibility" => {
697                        wire::accept(&mut visibility, entries.next_value()?, "visibility")?;
698                    }
699                    "metadata" => wire::accept(&mut metadata, entries.next_value()?, "metadata")?,
700                    unknown => return Err(A::Error::unknown_field(unknown, TOOL_RESULT_FIELDS)),
701                }
702            }
703            Ok(ToolResult::new(
704                wire::require(call_id, "call_id")?,
705                wire::require(tool_name, "tool_name")?,
706                wire::require(result, "result")?,
707                wire::require(visibility, "visibility")?,
708                wire::require(metadata, "metadata")?,
709            ))
710        }
711    }
712
713    // -- System --------------------------------------------------------------
714
715    impl Serialize for System {
716        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
717        where
718            S: Serializer,
719        {
720            let mut record = serializer.serialize_struct("System", 3)?;
721            record.serialize_field("subtype", &self.subtype)?;
722            record.serialize_field("text", &self.text)?;
723            record.serialize_field("visibility", &self.visibility)?;
724            record.end()
725        }
726    }
727
728    impl<'de> Deserialize<'de> for System {
729        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
730        where
731            D: Deserializer<'de>,
732        {
733            deserializer.deserialize_struct("System", SYSTEM_FIELDS, SystemVisitor)
734        }
735    }
736
737    struct SystemVisitor;
738
739    impl<'de> Visitor<'de> for SystemVisitor {
740        type Value = System;
741
742        fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
743            formatter.write_str("a system record")
744        }
745
746        fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
747        where
748            A: SeqAccess<'de>,
749        {
750            let subtype = wire::element(&mut sequence, 0)?;
751            let text = wire::element(&mut sequence, 1)?;
752            let visibility = wire::element(&mut sequence, 2)?;
753            Ok(System::new(subtype, text, visibility))
754        }
755
756        fn visit_map<A>(self, mut entries: A) -> Result<Self::Value, A::Error>
757        where
758            A: MapAccess<'de>,
759        {
760            let mut subtype = None;
761            let mut text = None;
762            let mut visibility = None;
763            while let Some(field) = entries.next_key_seed(IdentifierSeed(SYSTEM_FIELDS))? {
764                match field.0.as_str() {
765                    "subtype" => wire::accept(&mut subtype, entries.next_value()?, "subtype")?,
766                    "text" => wire::accept(&mut text, entries.next_value()?, "text")?,
767                    "visibility" => {
768                        wire::accept(&mut visibility, entries.next_value()?, "visibility")?;
769                    }
770                    unknown => return Err(A::Error::unknown_field(unknown, SYSTEM_FIELDS)),
771                }
772            }
773            Ok(System::new(
774                wire::require(subtype, "subtype")?,
775                wire::require(text, "text")?,
776                wire::require(visibility, "visibility")?,
777            ))
778        }
779    }
780
781    // -- Item ----------------------------------------------------------------
782
783    impl Serialize for Item {
784        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
785        where
786            S: Serializer,
787        {
788            match self {
789                Self::User(record) => {
790                    serializer.serialize_newtype_variant(ITEM_NAME, 0, "user", record)
791                }
792                Self::Assistant(record) => {
793                    serializer.serialize_newtype_variant(ITEM_NAME, 1, "assistant", record)
794                }
795                Self::ToolResult(record) => {
796                    serializer.serialize_newtype_variant(ITEM_NAME, 2, "tool_result", record)
797                }
798                Self::System(record) => {
799                    serializer.serialize_newtype_variant(ITEM_NAME, 3, "system", record)
800                }
801            }
802        }
803    }
804
805    impl<'de> Deserialize<'de> for Item {
806        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
807        where
808            D: Deserializer<'de>,
809        {
810            deserializer.deserialize_enum(ITEM_NAME, ITEM_VARIANTS, ItemVisitor)
811        }
812    }
813
814    struct ItemVisitor;
815
816    impl<'de> Visitor<'de> for ItemVisitor {
817        type Value = Item;
818
819        fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
820            formatter.write_str("a transcript record")
821        }
822
823        fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
824        where
825            A: EnumAccess<'de>,
826        {
827            let (tag, variant) = data.variant_seed(IdentifierSeed(ITEM_VARIANTS))?;
828            match tag.0.as_str() {
829                "user" => variant.newtype_variant().map(Item::User),
830                "assistant" => variant.newtype_variant().map(Item::Assistant),
831                "tool_result" => variant.newtype_variant().map(Item::ToolResult),
832                "system" => variant.newtype_variant().map(Item::System),
833                unknown => Err(A::Error::unknown_variant(unknown, ITEM_VARIANTS)),
834            }
835        }
836    }
837}