reef-core 0.4.0

Provider-neutral primitives for building LLM agents: run lifecycle, transcript, tools, hooks
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
//! Closed, owned records stored in a transcript.

use std::fmt::{self, Debug, Formatter};

use crate::opaque::Envelope;
use crate::redact;
use crate::value::content::{self, Metadata, Part, Segment};
use crate::value::tool_call::{self, Id};

/// Whether a record participates in model projection.
///
/// Persistence and a user-facing timeline may retain [`ModelVisibility::Hidden`]
/// records even though model projection omits them. Every [`Item`] variant
/// carries one, so the projection rule is total: there is no record shape whose
/// model visibility is undecided.
///
/// # Exchange visibility
///
/// A tool exchange is visible as a whole or not at all. Every
/// [`ToolResult`] reef commits for a generation takes the visibility of the
/// [`Assistant`] record that carries its call, so hiding an assistant record
/// hides the results answering it. A history that violates this — a visible
/// result whose call is hidden, or a visible call whose result is hidden — is
/// refused by
/// [`RequestPlan::try_into_request`](crate::runtime::model::RequestPlan::try_into_request) rather
/// than silently projected into an illegal request.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ModelVisibility {
    /// Include the record in model projection.
    Visible,
    /// Retain the record while omitting it from model projection.
    Hidden,
}

/// One closed transcript record.
///
/// The variant set is closed by ADR-004. Lifecycle and audit facts are
/// deliberately not transcript items.
///
/// ```
/// use reef_core::transcript::item;
/// let item = item::Item::System(item::System::new(
///     "instruction".into(), "Be concise.".into(), item::ModelVisibility::Visible,
/// ));
/// assert!(matches!(item, item::Item::System(system) if system.text() == "Be concise."));
/// ```
#[derive(Clone, Debug)]
pub enum Item {
    /// User-authored ordered content.
    User(User),
    /// Assistant-produced ordered content.
    Assistant(Assistant),
    /// The result of one model tool call.
    ToolResult(ToolResult),
    /// System-authored text.
    System(System),
}

impl Item {
    /// Renders this record's text the way a reader would be shown it.
    ///
    /// Reading a transcript is the first thing anyone does with an agent, and
    /// without this it takes a four-arm match plus a walk into
    /// [`Part::fields`](crate::value::content::Part::fields) or
    /// [`Segment`] per arm — the same twenty lines every consumer writes on
    /// their first day.
    ///
    /// ```
    /// use reef_core::transcript::item;
    /// use reef_core::value::content;
    ///
    /// let extensions = || content::SegmentExtensions::new(String::new(), None, None);
    /// let answer = item::Item::Assistant(item::Assistant::new(
    ///     vec![
    ///         content::Segment::Thinking { text: "the user wants a greeting".into(), extensions: extensions() },
    ///         content::Segment::Text { text: "Hello.".into(), extensions: extensions() },
    ///     ],
    ///     None,
    /// ));
    /// assert_eq!(answer.to_plain_text(), "Hello.");
    ///
    /// let question = item::Item::User(item::User::new(
    ///     vec![content::Part::text("Greet me.".into())],
    ///     item::ModelVisibility::Visible,
    /// ));
    /// assert_eq!(question.to_plain_text(), "Greet me.");
    /// ```
    ///
    /// # What each record renders as
    ///
    /// - [`User`]: the text of every part, in order. A part carrying an image or
    ///   opaque data has no text and contributes nothing.
    /// - [`Assistant`]: the text of every [`Segment::Text`]. Reasoning and tool
    ///   calls are not text the reader is being shown; [`Assistant::content`]
    ///   has them, in provider order, and always did.
    /// - [`ToolResult`]: exactly what
    ///   [`tool_call::ToolResult::to_plain_text`] renders, which this arm calls
    ///   rather than restates. That rule prefers the output's
    ///   [`user_view`](crate::value::tool_call::ToolOutput::user_view) over its
    ///   model content, and it belongs to the closed result value rather than to
    ///   this record: a record adds a call identity, a tool name, a visibility
    ///   and item metadata, none of which the rendering reads.
    /// - [`System`]: its text.
    ///
    /// Two blocks are separated by a single `\n` and nothing else is added, so a
    /// record with one block renders exactly that block.
    ///
    /// # This is not a way around redaction
    ///
    /// It is an accessor, and every byte it returns is already reachable through
    /// the typed accessor that owns it — which is precisely why ADR-018 refused
    /// an unredacted `Debug`: there is nothing here to hide *from*, only
    /// something to make convenient. What that ADR protects against is
    /// *accidental* disclosure, so this stays explicit at the call site. There
    /// is deliberately no [`Display`](std::fmt::Display) for an [`Item`]: a
    /// `Display` can be interpolated into a log message by someone who never
    /// decided to print a transcript, and `{item}` would look like nothing at
    /// all. `item.to_plain_text()` cannot be written by accident.
    #[must_use]
    pub fn to_plain_text(&self) -> String {
        match self {
            Self::User(user) => {
                content::join_blocks(user.parts().iter().map(|part| part.fields().text()))
            }
            Self::Assistant(assistant) => {
                content::join_blocks(assistant.content().iter().filter_map(
                    |segment| match segment {
                        Segment::Text { text, .. } => Some(text.as_str()),
                        Segment::Thinking { .. } | Segment::ToolCall { .. } => None,
                    },
                ))
            }
            Self::ToolResult(record) => record.result().to_plain_text(),
            Self::System(system) => system.text().to_owned(),
        }
    }
}

/// A user-authored transcript record.
///
/// ```compile_fail
/// use reef_core::transcript::item;
/// let _forged = item::User { parts: vec![], visibility: item::ModelVisibility::Visible };
/// ```
#[derive(Clone, Debug)]
pub struct User {
    parts: Vec<Part>,
    visibility: ModelVisibility,
}

impl User {
    /// Creates a user record while retaining part order.
    #[must_use]
    pub const fn new(parts: Vec<Part>, visibility: ModelVisibility) -> Self {
        Self { parts, visibility }
    }

    /// Returns the ordered user content.
    #[must_use]
    pub fn parts(&self) -> &[Part] {
        &self.parts
    }

    /// Returns this record's model visibility.
    #[must_use]
    pub const fn visibility(&self) -> ModelVisibility {
        self.visibility
    }
}

/// An assistant-output transcript record.
///
/// `content` is the sole source of truth. Text, thinking, and calls remain in
/// their original provider order rather than being flattened into parallel
/// collections. Record-level provider data is metadata, not another segment.
///
/// An assistant record is [`ModelVisibility::Visible`] unless
/// [`Assistant::with_visibility`] says otherwise: the model said it, so by
/// default the model may see it again. [`ModelVisibility::Hidden`] is what a hook
/// selects when it replaces the record through
/// [`AfterModelDecision::Modify`](crate::runtime::hook::AfterModelDecision::Modify)
/// or supplies one through
/// [`BeforeModelDecision::ShortCircuit`](crate::runtime::hook::BeforeModelDecision::ShortCircuit),
/// which is how a history stays complete for a user-facing timeline while the
/// model is sent less than all of it. Because reef propagates this record's
/// visibility onto every result committed with it, hiding a record that carries
/// tool calls also hides their results, and the projected request stays legal.
///
/// ```
/// use reef_core::transcript::item;
/// use reef_core::value::content;
/// let extensions = || content::SegmentExtensions::new(String::new(), None, None);
/// let item = item::Assistant::new(vec![
///     content::Segment::Text { text: "a".into(), extensions: extensions() },
///     content::Segment::Thinking { text: "b".into(), extensions: extensions() },
/// ], Some(vec![]));
/// assert_eq!(item.content().len(), 2);
/// assert!(item.provider_data().is_some_and(<[_]>::is_empty));
/// assert_eq!(item.visibility(), item::ModelVisibility::Visible);
///
/// let hidden = item.with_visibility(item::ModelVisibility::Hidden);
/// assert_eq!(hidden.visibility(), item::ModelVisibility::Hidden);
/// ```
///
/// ```compile_fail
/// use reef_core::transcript::item;
/// let _forged = item::Assistant {
///     content: vec![], provider_data: None, visibility: item::ModelVisibility::Visible,
/// };
/// ```
#[derive(Clone, Debug)]
pub struct Assistant {
    content: Vec<Segment>,
    provider_data: Option<Vec<Envelope>>,
    visibility: ModelVisibility,
}

impl Assistant {
    /// Creates a model-visible assistant record from ordered segments and
    /// record metadata.
    #[must_use]
    pub const fn new(content: Vec<Segment>, provider_data: Option<Vec<Envelope>>) -> Self {
        Self {
            content,
            provider_data,
            visibility: ModelVisibility::Visible,
        }
    }

    /// Declares whether this record participates in model projection.
    #[must_use]
    pub const fn with_visibility(mut self, visibility: ModelVisibility) -> Self {
        self.visibility = visibility;
        self
    }

    /// Returns the authoritative ordered segments.
    #[must_use]
    pub fn content(&self) -> &[Segment] {
        &self.content
    }

    /// Returns ordered record-level provider metadata, preserving presence.
    #[must_use]
    pub fn provider_data(&self) -> Option<&[Envelope]> {
        self.provider_data.as_deref()
    }

    /// Returns this record's model visibility.
    #[must_use]
    pub const fn visibility(&self) -> ModelVisibility {
        self.visibility
    }
}

/// A transcript record containing one closed tool result.
///
/// Item metadata is an independent transport channel and is never reconstructed
/// from, or written back into, [`tool_call::ToolResult`] output metadata.
///
/// `ModelVisibility` is a free parameter at this constructor, because a composition
/// layer restoring or rewriting a history owns both halves of an exchange. The
/// records reef itself commits take the visibility of the [`Assistant`] record
/// carrying the call, so reef never authors a half-hidden exchange.
///
/// ```
/// use reef_core::transcript::item;
/// use reef_core::value::{content, tool_call};
/// let item = item::ToolResult::new(
///     tool_call::Id::new("call-1".into()), tool_call::Name::new("search".into()),
///     tool_call::ToolResult::no_output(), item::ModelVisibility::Visible, Some(content::Metadata::new()),
/// );
/// assert_eq!(item.call_id().as_str(), "call-1");
/// assert!(item.metadata().is_some());
/// assert!(!item.is_business_error());
/// ```
///
/// ```compile_fail
/// use reef_core::transcript::item;
/// use reef_core::value::tool_call;
/// let _forged = item::ToolResult {
///     call_id: tool_call::Id::new("id".into()), tool_name: tool_call::Name::new("tool".into()),
///     result: tool_call::ToolResult::no_output(), visibility: item::ModelVisibility::Visible, metadata: None,
/// };
/// ```
#[derive(Clone, Debug)]
pub struct ToolResult {
    call_id: Id,
    tool_name: tool_call::Name,
    result: tool_call::ToolResult,
    visibility: ModelVisibility,
    metadata: Option<Metadata>,
}

impl ToolResult {
    /// Creates a tool-result record with independent item metadata.
    #[must_use]
    pub const fn new(
        call_id: Id,
        tool_name: tool_call::Name,
        result: tool_call::ToolResult,
        visibility: ModelVisibility,
        metadata: Option<Metadata>,
    ) -> Self {
        Self {
            call_id,
            tool_name,
            result,
            visibility,
            metadata,
        }
    }

    /// Returns the call identity used for correlation.
    #[must_use]
    pub const fn call_id(&self) -> &Id {
        &self.call_id
    }

    /// Returns the name of the tool that produced the result.
    #[must_use]
    pub const fn tool_name(&self) -> &tool_call::Name {
        &self.tool_name
    }

    /// Returns the closed tool result.
    #[must_use]
    pub const fn result(&self) -> &tool_call::ToolResult {
        &self.result
    }

    /// Returns this record's model visibility.
    #[must_use]
    pub const fn visibility(&self) -> ModelVisibility {
        self.visibility
    }

    /// Returns independent item-level metadata, preserving absent versus empty.
    #[must_use]
    pub const fn metadata(&self) -> Option<&Metadata> {
        self.metadata.as_ref()
    }

    /// Reports whether the result is an explicit business error.
    #[must_use]
    pub const fn is_business_error(&self) -> bool {
        self.result.is_business_error()
    }
}

/// A system-authored transcript record.
///
/// `subtype` is a producer-owned free-form label; core assigns it no meaning.
/// Empty subtype and text values remain representable at this leaf boundary.
///
/// ```compile_fail
/// use reef_core::transcript::item;
/// let _forged = item::System {
///     subtype: String::new(), text: String::new(), visibility: item::ModelVisibility::Visible,
/// };
/// ```
#[derive(Clone)]
pub struct System {
    subtype: String,
    text: String,
    visibility: ModelVisibility,
}

impl Debug for System {
    /// Prints the subtype in full and sizes the instruction.
    ///
    /// The two strings have different provenance even though they sit side by
    /// side: `subtype` is a producer-owned label that selects a record class,
    /// while `text` is a system instruction on its way to the model.
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("System")
            .field("subtype", &self.subtype)
            .field("text", &redact::Bytes(self.text.len()))
            .field("visibility", &self.visibility)
            .finish()
    }
}

impl System {
    /// Creates a system record without interpreting its subtype or text.
    #[must_use]
    pub const fn new(subtype: String, text: String, visibility: ModelVisibility) -> Self {
        Self {
            subtype,
            text,
            visibility,
        }
    }

    /// Returns the producer-defined subtype.
    #[must_use]
    pub fn subtype(&self) -> &str {
        &self.subtype
    }

    /// Returns the system-authored text.
    #[must_use]
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Returns this record's model visibility.
    #[must_use]
    pub const fn visibility(&self) -> ModelVisibility {
        self.visibility
    }
}

/// The serialized form of the transcript records (ADR-019 D5).
///
/// Every record shape carries its own [`ModelVisibility`], and the wire carries it per
/// record for the reason ADR-022 D1 gives: a format that dropped it would restore
/// a session by resurrecting history the composition layer had hidden. The
/// invariant that a tool exchange is hidden whole is a property a codec can
/// violate silently — the orphan only appears later, at projection time — so it
/// is one a codec has to preserve deliberately, and reading a record back gives
/// exactly the visibility that was written.
///
/// [`Assistant`] is the one record whose constructor does not take a visibility:
/// it is built model-visible and then narrowed through
/// [`Assistant::with_visibility`], which is the same path a hook takes.
#[cfg(feature = "serde")]
mod serde_impl {
    use std::fmt::{self, Formatter};

    use serde_core::de::{
        Deserialize, Deserializer, EnumAccess, Error as DeError, MapAccess, SeqAccess,
        VariantAccess, Visitor,
    };
    use serde_core::ser::{Serialize, SerializeStruct, Serializer};

    use super::{Assistant, Item, ModelVisibility, System, ToolResult, User};
    use crate::wire::{self, IdentifierSeed};

    const VISIBILITY_NAME: &str = "ModelVisibility";
    const VISIBILITY_VARIANTS: &[&str] = &["both", "user_only"];
    const USER_FIELDS: &[&str] = &["parts", "visibility"];
    const ASSISTANT_FIELDS: &[&str] = &["content", "provider_data", "visibility"];
    const TOOL_RESULT_FIELDS: &[&str] =
        &["call_id", "tool_name", "result", "visibility", "metadata"];
    const SYSTEM_FIELDS: &[&str] = &["subtype", "text", "visibility"];
    const ITEM_NAME: &str = "Item";
    const ITEM_VARIANTS: &[&str] = &["user", "assistant", "tool_result", "system"];

    // -- ModelVisibility ----------------------------------------------------------

    impl Serialize for ModelVisibility {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            let (index, tag) = match self {
                Self::Visible => (0, "both"),
                Self::Hidden => (1, "user_only"),
            };
            serializer.serialize_unit_variant(VISIBILITY_NAME, index, tag)
        }
    }

    impl<'de> Deserialize<'de> for ModelVisibility {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            deserializer.deserialize_enum(VISIBILITY_NAME, VISIBILITY_VARIANTS, VisibilityVisitor)
        }
    }

    struct VisibilityVisitor;

    impl<'de> Visitor<'de> for VisibilityVisitor {
        type Value = ModelVisibility;

        fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
            formatter.write_str("a record visibility")
        }

        fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
        where
            A: EnumAccess<'de>,
        {
            let (tag, variant) = data.variant_seed(IdentifierSeed(VISIBILITY_VARIANTS))?;
            variant.unit_variant()?;
            match tag.0.as_str() {
                "both" => Ok(ModelVisibility::Visible),
                "user_only" => Ok(ModelVisibility::Hidden),
                unknown => Err(A::Error::unknown_variant(unknown, VISIBILITY_VARIANTS)),
            }
        }
    }

    // -- User ----------------------------------------------------------------

    impl Serialize for User {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            let mut record = serializer.serialize_struct("User", 2)?;
            record.serialize_field("parts", &self.parts)?;
            record.serialize_field("visibility", &self.visibility)?;
            record.end()
        }
    }

    impl<'de> Deserialize<'de> for User {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            deserializer.deserialize_struct("User", USER_FIELDS, UserVisitor)
        }
    }

    struct UserVisitor;

    impl<'de> Visitor<'de> for UserVisitor {
        type Value = User;

        fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
            formatter.write_str("a user record")
        }

        fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
        where
            A: SeqAccess<'de>,
        {
            let parts = wire::element(&mut sequence, 0)?;
            let visibility = wire::element(&mut sequence, 1)?;
            wire::end(&mut sequence, 2)?;
            Ok(User::new(parts, visibility))
        }

        fn visit_map<A>(self, mut entries: A) -> Result<Self::Value, A::Error>
        where
            A: MapAccess<'de>,
        {
            let mut parts = None;
            let mut visibility = None;
            while let Some(field) = entries.next_key_seed(IdentifierSeed(USER_FIELDS))? {
                match field.0.as_str() {
                    "parts" => wire::accept(&mut parts, entries.next_value()?, "parts")?,
                    "visibility" => {
                        wire::accept(&mut visibility, entries.next_value()?, "visibility")?;
                    }
                    unknown => return Err(A::Error::unknown_field(unknown, USER_FIELDS)),
                }
            }
            Ok(User::new(
                wire::require(parts, "parts")?,
                wire::require(visibility, "visibility")?,
            ))
        }
    }

    // -- Assistant -----------------------------------------------------------

    impl Serialize for Assistant {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            let mut record = serializer.serialize_struct("Assistant", 3)?;
            record.serialize_field("content", &self.content)?;
            record.serialize_field("provider_data", &self.provider_data)?;
            record.serialize_field("visibility", &self.visibility)?;
            record.end()
        }
    }

    impl<'de> Deserialize<'de> for Assistant {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            deserializer.deserialize_struct("Assistant", ASSISTANT_FIELDS, AssistantVisitor)
        }
    }

    struct AssistantVisitor;

    impl<'de> Visitor<'de> for AssistantVisitor {
        type Value = Assistant;

        fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
            formatter.write_str("an assistant record")
        }

        fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
        where
            A: SeqAccess<'de>,
        {
            let content = wire::element(&mut sequence, 0)?;
            let provider_data = wire::element(&mut sequence, 1)?;
            let visibility = wire::element(&mut sequence, 2)?;
            wire::end(&mut sequence, 3)?;
            Ok(Assistant::new(content, provider_data).with_visibility(visibility))
        }

        fn visit_map<A>(self, mut entries: A) -> Result<Self::Value, A::Error>
        where
            A: MapAccess<'de>,
        {
            let mut content = None;
            let mut provider_data = None;
            let mut visibility = None;
            while let Some(field) = entries.next_key_seed(IdentifierSeed(ASSISTANT_FIELDS))? {
                match field.0.as_str() {
                    "content" => wire::accept(&mut content, entries.next_value()?, "content")?,
                    "provider_data" => {
                        wire::accept(&mut provider_data, entries.next_value()?, "provider_data")?;
                    }
                    "visibility" => {
                        wire::accept(&mut visibility, entries.next_value()?, "visibility")?;
                    }
                    unknown => return Err(A::Error::unknown_field(unknown, ASSISTANT_FIELDS)),
                }
            }
            Ok(Assistant::new(
                wire::require(content, "content")?,
                wire::require(provider_data, "provider_data")?,
            )
            .with_visibility(wire::require(visibility, "visibility")?))
        }
    }

    // -- ToolResult ----------------------------------------------------------

    impl Serialize for ToolResult {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            let mut record = serializer.serialize_struct("ToolResult", 5)?;
            record.serialize_field("call_id", &self.call_id)?;
            record.serialize_field("tool_name", &self.tool_name)?;
            record.serialize_field("result", &self.result)?;
            record.serialize_field("visibility", &self.visibility)?;
            record.serialize_field("metadata", &self.metadata)?;
            record.end()
        }
    }

    impl<'de> Deserialize<'de> for ToolResult {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            deserializer.deserialize_struct("ToolResult", TOOL_RESULT_FIELDS, ToolResultVisitor)
        }
    }

    struct ToolResultVisitor;

    impl<'de> Visitor<'de> for ToolResultVisitor {
        type Value = ToolResult;

        fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
            formatter.write_str("a tool-result record")
        }

        fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
        where
            A: SeqAccess<'de>,
        {
            let call_id = wire::element(&mut sequence, 0)?;
            let tool_name = wire::element(&mut sequence, 1)?;
            let result = wire::element(&mut sequence, 2)?;
            let visibility = wire::element(&mut sequence, 3)?;
            let metadata = wire::element(&mut sequence, 4)?;
            wire::end(&mut sequence, 5)?;
            Ok(ToolResult::new(
                call_id, tool_name, result, visibility, metadata,
            ))
        }

        fn visit_map<A>(self, mut entries: A) -> Result<Self::Value, A::Error>
        where
            A: MapAccess<'de>,
        {
            let mut call_id = None;
            let mut tool_name = None;
            let mut result = None;
            let mut visibility = None;
            let mut metadata = None;
            while let Some(field) = entries.next_key_seed(IdentifierSeed(TOOL_RESULT_FIELDS))? {
                match field.0.as_str() {
                    "call_id" => wire::accept(&mut call_id, entries.next_value()?, "call_id")?,
                    "tool_name" => {
                        wire::accept(&mut tool_name, entries.next_value()?, "tool_name")?;
                    }
                    "result" => wire::accept(&mut result, entries.next_value()?, "result")?,
                    "visibility" => {
                        wire::accept(&mut visibility, entries.next_value()?, "visibility")?;
                    }
                    "metadata" => wire::accept(&mut metadata, entries.next_value()?, "metadata")?,
                    unknown => return Err(A::Error::unknown_field(unknown, TOOL_RESULT_FIELDS)),
                }
            }
            Ok(ToolResult::new(
                wire::require(call_id, "call_id")?,
                wire::require(tool_name, "tool_name")?,
                wire::require(result, "result")?,
                wire::require(visibility, "visibility")?,
                wire::require(metadata, "metadata")?,
            ))
        }
    }

    // -- System --------------------------------------------------------------

    impl Serialize for System {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            let mut record = serializer.serialize_struct("System", 3)?;
            record.serialize_field("subtype", &self.subtype)?;
            record.serialize_field("text", &self.text)?;
            record.serialize_field("visibility", &self.visibility)?;
            record.end()
        }
    }

    impl<'de> Deserialize<'de> for System {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            deserializer.deserialize_struct("System", SYSTEM_FIELDS, SystemVisitor)
        }
    }

    struct SystemVisitor;

    impl<'de> Visitor<'de> for SystemVisitor {
        type Value = System;

        fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
            formatter.write_str("a system record")
        }

        fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
        where
            A: SeqAccess<'de>,
        {
            let subtype = wire::element(&mut sequence, 0)?;
            let text = wire::element(&mut sequence, 1)?;
            let visibility = wire::element(&mut sequence, 2)?;
            wire::end(&mut sequence, 3)?;
            Ok(System::new(subtype, text, visibility))
        }

        fn visit_map<A>(self, mut entries: A) -> Result<Self::Value, A::Error>
        where
            A: MapAccess<'de>,
        {
            let mut subtype = None;
            let mut text = None;
            let mut visibility = None;
            while let Some(field) = entries.next_key_seed(IdentifierSeed(SYSTEM_FIELDS))? {
                match field.0.as_str() {
                    "subtype" => wire::accept(&mut subtype, entries.next_value()?, "subtype")?,
                    "text" => wire::accept(&mut text, entries.next_value()?, "text")?,
                    "visibility" => {
                        wire::accept(&mut visibility, entries.next_value()?, "visibility")?;
                    }
                    unknown => return Err(A::Error::unknown_field(unknown, SYSTEM_FIELDS)),
                }
            }
            Ok(System::new(
                wire::require(subtype, "subtype")?,
                wire::require(text, "text")?,
                wire::require(visibility, "visibility")?,
            ))
        }
    }

    // -- Item ----------------------------------------------------------------

    impl Serialize for Item {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            match self {
                Self::User(record) => {
                    serializer.serialize_newtype_variant(ITEM_NAME, 0, "user", record)
                }
                Self::Assistant(record) => {
                    serializer.serialize_newtype_variant(ITEM_NAME, 1, "assistant", record)
                }
                Self::ToolResult(record) => {
                    serializer.serialize_newtype_variant(ITEM_NAME, 2, "tool_result", record)
                }
                Self::System(record) => {
                    serializer.serialize_newtype_variant(ITEM_NAME, 3, "system", record)
                }
            }
        }
    }

    impl<'de> Deserialize<'de> for Item {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            deserializer.deserialize_enum(ITEM_NAME, ITEM_VARIANTS, ItemVisitor)
        }
    }

    struct ItemVisitor;

    impl<'de> Visitor<'de> for ItemVisitor {
        type Value = Item;

        fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
            formatter.write_str("a transcript record")
        }

        fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
        where
            A: EnumAccess<'de>,
        {
            let (tag, variant) = data.variant_seed(IdentifierSeed(ITEM_VARIANTS))?;
            match tag.0.as_str() {
                "user" => variant.newtype_variant().map(Item::User),
                "assistant" => variant.newtype_variant().map(Item::Assistant),
                "tool_result" => variant.newtype_variant().map(Item::ToolResult),
                "system" => variant.newtype_variant().map(Item::System),
                unknown => Err(A::Error::unknown_variant(unknown, ITEM_VARIANTS)),
            }
        }
    }
}