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
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
//! Owned, provider-neutral content values.

use std::collections::{BTreeMap, btree_map};
use std::fmt::{self, Debug, Formatter};

use crate::opaque::{Envelope, Payload};
use crate::redact;

/// A known portable interpretation of a [`PartKind`].
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum KnownPartKind {
    /// Ordinary text.
    Text,
    /// Image content.
    Image,
    /// File content.
    File,
    /// Model-facing tool-result content.
    ToolResult,
    /// Reasoning or thinking replayed to the model.
    Thinking,
}

impl KnownPartKind {
    /// Returns the canonical numeric kind carrying this interpretation.
    ///
    /// The inverse of [`PartKind::known`], and the supported way to spell one of
    /// the five as a [`PartKind`]. It introduces no second representation: the
    /// value is the one [`PartKind::from_i64`] would have produced, so
    /// `kind.as_part_kind().known()` is `Some(kind)` for every variant.
    #[must_use]
    pub const fn as_part_kind(self) -> PartKind {
        PartKind::from_i64(match self {
            Self::Text => 0,
            Self::Image => 1,
            Self::File => 2,
            Self::ToolResult => 3,
            Self::Thinking => 4,
        })
    }
}

/// The canonical, open numeric kind of a [`Part`].
///
/// Every `i64` round-trips, while only values zero through four have a known
/// portable interpretation.
///
/// ```compile_fail
/// use reef_core::value::content;
/// let _forged = content::PartKind(0);
/// ```
///
/// # Kinds this crate cannot name
///
/// A producer is free to mint its own. [`PartKind::from_i64`] keeps every `i64`,
/// and transcript records, user input and ephemeral input all propagate an
/// unrecognised kind losslessly together with its complete [`PartFields`]. Two
/// boundaries narrow, and each says so where it is defined: a system-instruction
/// part must be a known [`KnownPartKind::Text`], and
/// [`tool_call::ToolPart::try_from_part`](crate::value::tool_call::ToolPart::try_from_part)
/// refuses a kind this crate cannot name, because the model acts on a tool
/// result.
///
/// What these numbers do not come with is an allocation authority. There is no
/// registry and no reserved range, so two independently written producers can
/// choose the same integer for different concepts, or different integers for the
/// same one, and this crate can neither prevent that nor notice it. A number
/// outside 0-4 therefore identifies a kind only between parties that already
/// agree — typically a codec and the consumer written against it.
///
/// When something has to be recognised by a party that did not choose the number,
/// name it in the [`Metadata`] on the same part: its keys are strings, so a
/// producer can qualify its own vocabulary the way [`Envelope`] does with
/// `(namespace, kind)` for provider data elsewhere in the crate. A `Part` carries
/// no `Envelope` of its own — [`PartFields::raw_payload`] is unnamespaced bytes —
/// so the metadata tree is where that naming goes.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct PartKind(i64);

impl PartKind {
    /// Creates a kind while preserving the numeric value exactly.
    #[must_use]
    pub const fn from_i64(value: i64) -> Self {
        Self(value)
    }

    /// Returns the original numeric value.
    #[must_use]
    pub const fn as_i64(self) -> i64 {
        self.0
    }

    /// Returns the known portable interpretation, if one exists.
    ///
    /// [`KnownPartKind::as_part_kind`] is the inverse.
    #[must_use]
    pub const fn known(self) -> Option<KnownPartKind> {
        match self.0 {
            0 => Some(KnownPartKind::Text),
            1 => Some(KnownPartKind::Image),
            2 => Some(KnownPartKind::File),
            3 => Some(KnownPartKind::ToolResult),
            4 => Some(KnownPartKind::Thinking),
            _ => None,
        }
    }
}

/// An owned, callback-free metadata object.
///
/// # Ordering
///
/// Iteration — through [`Metadata::iter`] or [`IntoIterator`] — yields entries in
/// **ascending key order**. This is a guarantee, not an artefact of the current
/// storage: ADR-004's determinism for wire codecs depends on it, so a later
/// storage change has to preserve it.
///
/// ```
/// use reef_core::value::content;
/// let values = vec![
///     content::MetadataValue::Null, content::MetadataValue::Bool(true), content::MetadataValue::Signed(-1),
///     content::MetadataValue::Unsigned(1), content::MetadataValue::Float(1.5),
///     content::MetadataValue::String("text".into()), content::MetadataValue::Bytes(vec![1].into_boxed_slice()),
///     content::MetadataValue::Array(vec![]), content::MetadataValue::Object(content::Metadata::new()),
/// ];
/// let mut metadata = content::Metadata::new();
/// metadata.insert("values".into(), content::MetadataValue::Array(values));
/// assert!(matches!(metadata.get("values"), Some(content::MetadataValue::Array(values)) if values.len() == 9));
/// assert_eq!(metadata.iter().len(), 1);
/// assert_eq!(metadata.into_iter().count(), 1);
/// ```
///
/// ```compile_fail
/// use reef_core::value::content;
/// let callback = Box::new(|| {});
/// let _invalid = content::Metadata::from_iter([("callback".to_owned(), callback)]);
/// ```
#[derive(Clone)]
pub struct Metadata(BTreeMap<String, MetadataValue>);

impl Debug for Metadata {
    /// States how many entries exist and stops there.
    ///
    /// Not iterating is what makes this implementation safe as well as
    /// discreet: keys and values are model-visible, and a
    /// [`MetadataValue`] tree nests without any depth limit, so a formatter
    /// that descended would overflow the stack on the same values
    /// `Clone` and `Drop` already survive iteratively.
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Metadata")
            .field("entries", &self.0.len())
            .finish()
    }
}

#[expect(
    clippy::new_without_default,
    reason = "ADR-004 freezes Metadata::new as the sole empty constructor"
)]
impl Metadata {
    /// Creates an empty, present metadata object.
    #[must_use]
    pub const fn new() -> Self {
        Self(BTreeMap::new())
    }

    /// Returns the value associated with `key`.
    #[must_use]
    pub fn get(&self, key: &str) -> Option<&MetadataValue> {
        self.0.get(key)
    }

    /// Associates `value` with `key`, returning whatever `key` already held.
    pub fn insert(&mut self, key: String, value: MetadataValue) -> Option<MetadataValue> {
        self.0.insert(key, value)
    }

    /// Iterates over entries in ascending key order.
    #[must_use]
    pub fn iter(&self) -> MetadataIter<'_> {
        MetadataIter(self.0.iter())
    }
}

impl FromIterator<(String, MetadataValue)> for Metadata {
    /// Collects entries; a repeated key keeps the last value supplied.
    fn from_iter<I: IntoIterator<Item = (String, MetadataValue)>>(entries: I) -> Self {
        Self(entries.into_iter().collect())
    }
}

impl IntoIterator for Metadata {
    type Item = (String, MetadataValue);
    type IntoIter = MetadataIntoIter;

    /// Transfers every entry in ascending key order.
    fn into_iter(self) -> Self::IntoIter {
        MetadataIntoIter(self.0.into_iter())
    }
}

impl<'a> IntoIterator for &'a Metadata {
    type Item = (&'a str, &'a MetadataValue);
    type IntoIter = MetadataIter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

/// Borrowing iterator over [`Metadata`] entries in ascending key order.
///
/// The concrete storage stays hidden: this type names the iterator so
/// `Metadata`'s representation can change without changing its API.
pub struct MetadataIter<'a>(btree_map::Iter<'a, String, MetadataValue>);

impl Debug for MetadataIter<'_> {
    /// States how many entries are still to come, not what they are.
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("MetadataIter")
            .field("remaining", &self.0.len())
            .finish()
    }
}

impl<'a> Iterator for MetadataIter<'a> {
    type Item = (&'a str, &'a MetadataValue);

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next().map(|(key, value)| (key.as_str(), value))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

impl ExactSizeIterator for MetadataIter<'_> {
    fn len(&self) -> usize {
        self.0.len()
    }
}

/// Owning iterator over [`Metadata`] entries in ascending key order.
pub struct MetadataIntoIter(btree_map::IntoIter<String, MetadataValue>);

impl Debug for MetadataIntoIter {
    /// States how many entries are still to come, not what they are.
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("MetadataIntoIter")
            .field("remaining", &self.0.len())
            .finish()
    }
}

impl Iterator for MetadataIntoIter {
    type Item = (String, MetadataValue);

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

impl ExactSizeIterator for MetadataIntoIter {
    fn len(&self) -> usize {
        self.0.len()
    }
}

/// A value in the closed, portable metadata tree.
///
/// # Nesting depth
///
/// A value nests without any limit in memory, which is why [`Clone`] and
/// [`Drop`] are implemented iteratively here. Serialization is the one place
/// that cannot follow suit: serde expresses nesting through nested calls and
/// consumes each level's compound serializer by value, so no work stack can hold
/// the intermediates. With the `serde` feature enabled, a value nested more than
/// **128** levels deep is therefore refused in both directions with a typed
/// error — never truncated, and never allowed to overflow the stack. 128 is
/// `serde_json`'s own default recursion limit, so reef's bound is not the first
/// one a JSON caller meets; realistic metadata is under ten levels deep.
pub enum MetadataValue {
    /// A null value.
    Null,
    /// A boolean value.
    Bool(bool),
    /// A signed integer.
    Signed(i64),
    /// An unsigned integer.
    Unsigned(u64),
    /// A floating-point value, including every `f64` bit pattern.
    Float(f64),
    /// A UTF-8 string.
    String(String),
    /// Owned arbitrary bytes.
    Bytes(Box<[u8]>),
    /// An ordered array.
    Array(Vec<MetadataValue>),
    /// A nested string-keyed object.
    Object(Metadata),
}

/// A borrowed view of every closed [`MetadataValue`] variant.
///
/// This view preserves exhaustive observation even though `MetadataValue` has a
/// custom destructor and therefore cannot expose owned fields through by-value
/// pattern matching.
#[derive(Clone, Copy)]
pub enum MetadataValueRef<'a> {
    /// A null value.
    Null,
    /// A boolean value.
    Bool(bool),
    /// A signed integer.
    Signed(i64),
    /// An unsigned integer.
    Unsigned(u64),
    /// A floating-point value, including every `f64` bit pattern.
    Float(f64),
    /// A borrowed UTF-8 string.
    String(&'a str),
    /// Borrowed arbitrary bytes.
    Bytes(&'a [u8]),
    /// A borrowed ordered array.
    Array(&'a [MetadataValue]),
    /// A borrowed string-keyed object.
    Object(&'a Metadata),
}

impl MetadataValue {
    /// Borrows this value without losing its closed variant or payload.
    #[must_use]
    pub fn as_borrowed(&self) -> MetadataValueRef<'_> {
        match self {
            Self::Null => MetadataValueRef::Null,
            Self::Bool(value) => MetadataValueRef::Bool(*value),
            Self::Signed(value) => MetadataValueRef::Signed(*value),
            Self::Unsigned(value) => MetadataValueRef::Unsigned(*value),
            Self::Float(value) => MetadataValueRef::Float(*value),
            Self::String(value) => MetadataValueRef::String(value.as_str()),
            Self::Bytes(value) => MetadataValueRef::Bytes(value),
            Self::Array(value) => MetadataValueRef::Array(value),
            Self::Object(value) => MetadataValueRef::Object(value),
        }
    }
}

// The two metadata values render identically because they are the same value
// seen from two sides; a reader should never have to know which one produced a
// line of output. Both keep the discriminant, which is what makes the rendering
// useful, and neither descends: `Array` and `Object` report a length, so no
// formatter in this crate can walk a metadata tree.
fn debug_metadata_value(formatter: &mut Formatter<'_>, value: MetadataValueRef<'_>) -> fmt::Result {
    match value {
        MetadataValueRef::Null => formatter.write_str("Null"),
        // A scalar has no size to report, and reporting the scalar itself would
        // emit content: ADR-018 names a PIN and a "boolean-ish answer" as
        // exactly the low-entropy secrets a redaction must not hand back.
        MetadataValueRef::Bool(_) => formatter.write_str("Bool(..)"),
        MetadataValueRef::Signed(_) => formatter.write_str("Signed(..)"),
        MetadataValueRef::Unsigned(_) => formatter.write_str("Unsigned(..)"),
        MetadataValueRef::Float(_) => formatter.write_str("Float(..)"),
        MetadataValueRef::String(text) => formatter
            .debug_tuple("String")
            .field(&redact::Bytes(text.len()))
            .finish(),
        MetadataValueRef::Bytes(bytes) => formatter
            .debug_tuple("Bytes")
            .field(&redact::Bytes(bytes.len()))
            .finish(),
        MetadataValueRef::Array(values) => formatter
            .debug_tuple("Array")
            .field(&redact::Items(values.len()))
            .finish(),
        MetadataValueRef::Object(metadata) => {
            formatter.debug_tuple("Object").field(metadata).finish()
        }
    }
}

impl Debug for MetadataValue {
    /// Names the variant and sizes the payload, without descending.
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        debug_metadata_value(formatter, self.as_borrowed())
    }
}

impl Debug for MetadataValueRef<'_> {
    /// Renders exactly as the owned value it borrows.
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        debug_metadata_value(formatter, *self)
    }
}

impl Clone for MetadataValue {
    fn clone(&self) -> Self {
        enum Task<'a> {
            Clone(&'a MetadataValue),
            FinishArray(usize),
            FinishObject(Vec<String>),
        }

        let mut tasks = vec![Task::Clone(self)];
        let mut completed = Vec::new();

        while let Some(task) = tasks.pop() {
            match task {
                Task::Clone(value) => match value {
                    Self::Null => completed.push(Self::Null),
                    Self::Bool(value) => completed.push(Self::Bool(*value)),
                    Self::Signed(value) => completed.push(Self::Signed(*value)),
                    Self::Unsigned(value) => completed.push(Self::Unsigned(*value)),
                    Self::Float(value) => completed.push(Self::Float(*value)),
                    Self::String(value) => completed.push(Self::String(value.clone())),
                    Self::Bytes(value) => completed.push(Self::Bytes(value.clone())),
                    Self::Array(values) => {
                        tasks.push(Task::FinishArray(values.len()));
                        tasks.extend(values.iter().rev().map(Task::Clone));
                    }
                    Self::Object(metadata) => {
                        tasks.push(Task::FinishObject(metadata.0.keys().cloned().collect()));
                        tasks.extend(metadata.0.values().rev().map(Task::Clone));
                    }
                },
                Task::FinishArray(length) => {
                    let values = completed.split_off(completed.len() - length);
                    completed.push(Self::Array(values));
                }
                Task::FinishObject(keys) => {
                    let values = completed.split_off(completed.len() - keys.len());
                    completed.push(Self::Object(keys.into_iter().zip(values).collect()));
                }
            }
        }

        completed.remove(0)
    }
}

impl Drop for MetadataValue {
    fn drop(&mut self) {
        let mut pending = Vec::new();
        take_nested_values(self, &mut pending);
        while let Some(mut value) = pending.pop() {
            take_nested_values(&mut value, &mut pending);
        }
    }
}

fn take_nested_values(value: &mut MetadataValue, pending: &mut Vec<MetadataValue>) {
    match value {
        MetadataValue::Array(values) => pending.append(values),
        MetadataValue::Object(metadata) => {
            pending.extend(std::mem::take(&mut metadata.0).into_values());
        }
        MetadataValue::Null
        | MetadataValue::Bool(_)
        | MetadataValue::Signed(_)
        | MetadataValue::Unsigned(_)
        | MetadataValue::Float(_)
        | MetadataValue::String(_)
        | MetadataValue::Bytes(_) => {}
    }
}

/// The complete owned field set of a [`Part`].
///
/// Fields are independent of kind. `None` and `Some(empty)` remain distinct.
///
/// ```
/// use reef_core::opaque;
/// use reef_core::value::content;
/// let fields = content::PartFields::new(
///     "body".into(), "text/custom".into(), Some(Vec::new().into_boxed_slice()),
///     "ref".into(), Some(content::Metadata::new()), Some(opaque::Payload::from_vec(vec![])),
/// );
/// let part = content::Part::new(content::PartKind::from_i64(77), fields);
/// assert_eq!(part.kind().as_i64(), 77);
/// assert_eq!(part.fields().text(), "body");
/// assert_eq!(part.fields().data(), Some([].as_slice()));
/// ```
#[derive(Clone)]
pub struct PartFields {
    text: String,
    mime: String,
    data: Option<Box<[u8]>>,
    reference: String,
    metadata: Option<Metadata>,
    raw: Option<Payload>,
}

impl Debug for PartFields {
    /// Sizes every model-visible field and keeps every presence distinction.
    ///
    /// `None`, `Some(<0 bytes>)` and `Some(<7 bytes>)` stay three different
    /// renderings, because the distinction between absent and present-empty is
    /// the thing this type exists to carry.
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("PartFields")
            .field("text", &redact::Bytes(self.text.len()))
            .field("mime", &redact::Bytes(self.mime.len()))
            .field(
                "data",
                &self.data.as_deref().map(|data| redact::Bytes(data.len())),
            )
            .field("reference", &redact::Bytes(self.reference.len()))
            .field("metadata", &self.metadata)
            .field("raw", &self.raw)
            .finish()
    }
}

impl PartFields {
    /// Creates the complete field set without kind-dependent rewriting.
    #[must_use]
    pub const fn new(
        text: String,
        mime: String,
        data: Option<Box<[u8]>>,
        reference: String,
        metadata: Option<Metadata>,
        raw: Option<Payload>,
    ) -> Self {
        Self {
            text,
            mime,
            data,
            reference,
            metadata,
            raw,
        }
    }

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

    /// Returns the media-type field.
    #[must_use]
    pub fn mime(&self) -> &str {
        &self.mime
    }

    /// Returns the optional byte data while retaining its presence state.
    #[must_use]
    pub fn data(&self) -> Option<&[u8]> {
        self.data.as_deref()
    }

    /// Returns the external-reference field.
    #[must_use]
    pub fn reference(&self) -> &str {
        &self.reference
    }

    /// Returns the optional metadata object.
    #[must_use]
    pub const fn metadata(&self) -> Option<&Metadata> {
        self.metadata.as_ref()
    }

    /// Returns the optional opaque provider payload.
    #[must_use]
    pub const fn raw_payload(&self) -> Option<&Payload> {
        self.raw.as_ref()
    }
}

/// One field-complete message part with an open canonical kind.
///
/// ```compile_fail
/// use reef_core::value::content;
/// let _forged = content::Part { kind: content::PartKind::from_i64(0), fields: panic!() };
/// ```
#[derive(Clone, Debug)]
pub struct Part {
    kind: PartKind,
    fields: PartFields,
}

impl Part {
    /// Creates a part without rejecting or dropping cross-kind fields.
    #[must_use]
    pub const fn new(kind: PartKind, fields: PartFields) -> Self {
        Self { kind, fields }
    }

    /// Creates ordinary text with every other field empty or absent.
    #[must_use]
    pub const fn text(text: String) -> Self {
        Self::new(
            KnownPartKind::Text.as_part_kind(),
            PartFields::new(text, String::new(), None, String::new(), None, None),
        )
    }

    /// Returns the canonical kind.
    #[must_use]
    pub const fn kind(&self) -> PartKind {
        self.kind
    }

    /// Returns every field as one immutable value.
    #[must_use]
    pub const fn fields(&self) -> &PartFields {
        &self.fields
    }

    /// Transfers the canonical kind and complete field set.
    #[must_use]
    pub fn into_parts(self) -> (PartKind, PartFields) {
        (self.kind, self.fields)
    }
}

// Validation is a predicate so accepted field-complete Parts are never rebuilt.
pub(crate) fn is_valid_system_instruction(parts: &[Part]) -> bool {
    parts.iter().all(|part| {
        part.kind().known() == Some(KnownPartKind::Text) && !part.fields().text().is_empty()
    })
}

/// Opaque extensions shared by every [`Segment`] variant.
#[derive(Clone)]
pub struct SegmentExtensions {
    signature: String,
    raw: Option<Payload>,
    provider_data: Option<Vec<Envelope>>,
    item_id: Option<String>,
}

impl Debug for SegmentExtensions {
    /// Reports the signature's presence and withholds even its length.
    ///
    /// The signature is the crate's one credential-shaped value: a
    /// provider-issued token reef neither produces nor interprets, whose only
    /// job is to be replayed verbatim. Signature lengths are provider-stable, so
    /// a byte count would fingerprint the provider and the reasoning mode behind
    /// a transcript while helping nobody — a signature is debugged by whether it
    /// survived a round trip, which [`SegmentExtensions::signature`] answers.
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("SegmentExtensions")
            .field("signature", &redact::Presence(!self.signature.is_empty()))
            .field("raw", &self.raw)
            .field("provider_data", &self.provider_data)
            // Verbatim, like every other identifier in the crate. It is a
            // provider-assigned label for a content item, carries none of the
            // content, and is useless for correlating anything outside the one
            // generation that minted it.
            .field("item_id", &self.item_id)
            .finish()
    }
}

impl SegmentExtensions {
    /// Creates extensions while preserving raw and collection presence.
    ///
    /// The item identity is not an argument, because a provider adapter does not
    /// supply it here: reef stamps it from the identity the adapter already
    /// declared on `model::Event::ContentFinal`. See
    /// [`with_item_id`](Self::with_item_id).
    #[must_use]
    pub const fn new(
        signature: String,
        raw: Option<Payload>,
        provider_data: Option<Vec<Envelope>>,
    ) -> Self {
        Self {
            signature,
            raw,
            provider_data,
            item_id: None,
        }
    }

    /// Attaches the provider's identity for the content item this segment is.
    ///
    /// Reef calls this itself, with the `id` of the
    /// `model::Event::ContentFinal` the segment was built from, which is why an
    /// adapter never has to: the identity a provider declares on the stream is
    /// the identity the record keeps. Setting it here twice is not a way to
    /// disagree with the stream — reef overwrites whatever is present, because
    /// `model::StreamGrammar` tracks exactly one identity per item and a second
    /// place to say it would be a second thing to believe.
    ///
    /// An adapter that wants a different identity in the record declares a
    /// different one on the stream. A registration that wants to rewrite it
    /// after the fact does so in
    /// [`ModelHooks::after_model`](crate::runtime::hook::ModelHooks::after_model),
    /// which is handed the whole `item::Assistant` before it is committed and
    /// whose replacement is what both the transcript and the outward
    /// `Text`/`Thinking` events then report.
    #[must_use]
    pub fn with_item_id(mut self, id: String) -> Self {
        self.item_id = Some(id);
        self
    }

    /// Returns the provider's identity for this content item, when one is known.
    ///
    /// `None` for a segment no provider stream produced — one a hook composed,
    /// or one restored from a record written before the identity was carried.
    #[must_use]
    pub fn item_id(&self) -> Option<&str> {
        self.item_id.as_deref()
    }

    /// Returns the opaque reasoning-continuity signature.
    #[must_use]
    pub fn signature(&self) -> &str {
        &self.signature
    }

    /// Returns the optional raw provider payload.
    #[must_use]
    pub const fn raw_payload(&self) -> Option<&Payload> {
        self.raw.as_ref()
    }

    /// Returns ordered provider envelopes while retaining collection presence.
    #[must_use]
    pub fn provider_data(&self) -> Option<&[Envelope]> {
        self.provider_data.as_deref()
    }

    /// Transfers all extension fields.
    #[must_use]
    pub fn into_parts(
        self,
    ) -> (
        String,
        Option<Payload>,
        Option<Vec<Envelope>>,
        Option<String>,
    ) {
        (self.signature, self.raw, self.provider_data, self.item_id)
    }
}

/// One ordered, producer-valid assistant-content segment.
///
/// The enum excludes text/thinking segments with calls and call segments without
/// calls. Public variants are the complete construction and observation API.
///
/// ```
/// use reef_core::opaque;
/// use reef_core::value::{content, tool_call};
/// let extensions = || content::SegmentExtensions::new(String::new(), None, Some(vec![]));
/// let segments = [
///     content::Segment::Text { text: "answer".into(), extensions: extensions() },
///     content::Segment::Thinking { text: "reason".into(), extensions: extensions() },
///     content::Segment::ToolCall {
///         call: tool_call::ToolCall::new(tool_call::Id::new("id".into()), tool_call::Name::new("tool".into()), opaque::Payload::from_vec(vec![])),
///         extensions: extensions(),
///     },
/// ];
/// assert!(matches!(&segments[0], content::Segment::Text { text, extensions } if text == "answer" && extensions.provider_data().is_some_and(<[_]>::is_empty)));
/// assert!(matches!(&segments[1], content::Segment::Thinking { text, .. } if text == "reason"));
/// assert!(matches!(&segments[2], content::Segment::ToolCall { call, .. } if call.id().as_str() == "id"));
/// ```
#[derive(Clone)]
pub enum Segment {
    /// Model-visible answer text.
    Text {
        /// The text exactly as produced.
        text: String,
        /// Opaque provider extensions attached to this segment.
        extensions: SegmentExtensions,
    },
    /// Reasoning or thinking content.
    Thinking {
        /// The reasoning text exactly as produced.
        text: String,
        /// Opaque provider extensions attached to this segment.
        extensions: SegmentExtensions,
    },
    /// A model-initiated tool invocation.
    ToolCall {
        /// The complete tool invocation.
        call: super::tool_call::ToolCall,
        /// Opaque provider extensions attached to this segment.
        extensions: SegmentExtensions,
    },
}

impl Debug for Segment {
    /// Keeps the variant and sizes the text, in both content lanes alike.
    ///
    /// Reasoning is not a stricter tier than answer text. Tier 2 already emits
    /// zero content bytes, so "stricter" could only mean "emit nothing" — and a
    /// provider is free to deliver reasoning inside [`Segment::Text`] anyway, so
    /// a thinking-only rule would be a guarantee the data can walk around. What
    /// a compliance-minded operator needs survives: the discriminant states
    /// *that* the model reasoned and the size states *how much*.
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Text { text, extensions } => formatter
                .debug_struct("Text")
                .field("text", &redact::Bytes(text.len()))
                .field("extensions", extensions)
                .finish(),
            Self::Thinking { text, extensions } => formatter
                .debug_struct("Thinking")
                .field("text", &redact::Bytes(text.len()))
                .field("extensions", extensions)
                .finish(),
            Self::ToolCall { call, extensions } => formatter
                .debug_struct("ToolCall")
                .field("call", call)
                .field("extensions", extensions)
                .finish(),
        }
    }
}

/// Joins the text-bearing blocks of one record with a single newline.
///
/// Every plain-text rendering in this crate separates two blocks with one `\n`
/// and adds nothing else, so the convention lives here rather than once per
/// caller: a record with one block renders exactly that block, and a block with
/// no text contributes nothing instead of an empty line.
pub(crate) fn join_blocks<'a>(blocks: impl Iterator<Item = &'a str>) -> String {
    let mut rendered = String::new();
    for block in blocks.filter(|block| !block.is_empty()) {
        if !rendered.is_empty() {
            rendered.push('\n');
        }
        rendered.push_str(block);
    }
    rendered
}

/// The serialized form of the content value tree (ADR-019 D5).
///
/// Three shapes are worth naming before reading the code.
///
/// **`PartKind` is a bare integer.** ADR-004's own fixtures already show it that
/// way, and the newtype is a Rust representation detail rather than something the
/// wire should learn about. The same is true of the byte payloads: they travel as
/// serde byte strings, never base64, because core may not re-encode bytes it
/// never parsed.
///
/// **Nothing is omitted.** `None` is written as the format's null and
/// `Some(empty)` as an empty string, array or object, so the absent-versus-
/// present-empty distinction that [`PartFields`] exists to carry survives a round
/// trip. `PartFields::reference` is spelled `reference` in full; abbreviating it
/// to `ref` for some other wire is a separate adapter's business.
///
/// **[`MetadataValue`] carries a depth.** Every nested value is serialized
/// through a private wrapper that knows how deep it is and refuses to go past
/// [`MAX_METADATA_DEPTH`], in both directions. See that constant for why a bound
/// is the only available answer here.
#[cfg(feature = "serde")]
mod serde_impl {
    use std::fmt::{self, Formatter};

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

    use super::{Metadata, MetadataValue, Part, PartFields, PartKind, Segment, SegmentExtensions};
    use crate::opaque::{Envelope, Payload};
    use crate::wire::{self, ByteBuf, Bytes, IdentifierSeed};

    /// The nesting depth beyond which a [`MetadataValue`] is refused.
    ///
    /// `MetadataValue`'s own documentation states the bound and why serde is the
    /// one traversal in this crate that cannot be made iterative; this is where
    /// the bound is enforced.
    pub(super) const MAX_METADATA_DEPTH: usize = 128;

    const VALUE_NAME: &str = "MetadataValue";
    const VALUE_VARIANTS: &[&str] = &[
        "null", "bool", "signed", "unsigned", "float", "string", "bytes", "array", "object",
    ];
    const PART_FIELDS: &[&str] = &["kind", "fields"];
    const FIELDS_FIELDS: &[&str] = &["text", "mime", "data", "reference", "metadata", "raw"];
    const EXTENSIONS_FIELDS: &[&str] = &["signature", "raw", "provider_data", "item_id"];
    const SEGMENT_NAME: &str = "Segment";
    const SEGMENT_VARIANTS: &[&str] = &["text", "thinking", "tool_call"];
    const TEXT_SEGMENT_FIELDS: &[&str] = &["text", "extensions"];
    const TOOL_CALL_SEGMENT_FIELDS: &[&str] = &["call", "extensions"];

    /// Names the depth bound in the one sentence a caller can act on.
    struct TooDeep;

    impl fmt::Display for TooDeep {
        fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
            write!(
                formatter,
                "metadata value nests deeper than the {MAX_METADATA_DEPTH}-level serialization limit"
            )
        }
    }

    // -- PartKind ------------------------------------------------------------

    impl Serialize for PartKind {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            serializer.serialize_i64(self.0)
        }
    }

    impl<'de> Deserialize<'de> for PartKind {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            i64::deserialize(deserializer).map(Self::from_i64)
        }
    }

    // -- MetadataValue and Metadata ------------------------------------------

    /// One metadata value that knows how deeply it is nested.
    struct DepthValue<'a>(&'a MetadataValue, usize);

    /// Array elements whose own nesting depth is one below their array's.
    struct DepthElements<'a>(&'a [MetadataValue], usize);

    /// Object entries whose values' nesting depth is one below their object's.
    struct DepthEntries<'a>(&'a Metadata, usize);

    impl Serialize for DepthValue<'_> {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            if self.1 > MAX_METADATA_DEPTH {
                return Err(S::Error::custom(TooDeep));
            }
            let nested = self.1 + 1;
            match self.0 {
                MetadataValue::Null => serializer.serialize_unit_variant(VALUE_NAME, 0, "null"),
                MetadataValue::Bool(value) => {
                    serializer.serialize_newtype_variant(VALUE_NAME, 1, "bool", value)
                }
                MetadataValue::Signed(value) => {
                    serializer.serialize_newtype_variant(VALUE_NAME, 2, "signed", value)
                }
                MetadataValue::Unsigned(value) => {
                    serializer.serialize_newtype_variant(VALUE_NAME, 3, "unsigned", value)
                }
                MetadataValue::Float(value) => {
                    serializer.serialize_newtype_variant(VALUE_NAME, 4, "float", value)
                }
                MetadataValue::String(value) => {
                    serializer.serialize_newtype_variant(VALUE_NAME, 5, "string", value)
                }
                MetadataValue::Bytes(value) => {
                    serializer.serialize_newtype_variant(VALUE_NAME, 6, "bytes", &Bytes(value))
                }
                MetadataValue::Array(values) => serializer.serialize_newtype_variant(
                    VALUE_NAME,
                    7,
                    "array",
                    &DepthElements(values, nested),
                ),
                MetadataValue::Object(metadata) => serializer.serialize_newtype_variant(
                    VALUE_NAME,
                    8,
                    "object",
                    &DepthEntries(metadata, nested),
                ),
            }
        }
    }

    impl Serialize for DepthElements<'_> {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            let mut sequence = serializer.serialize_seq(Some(self.0.len()))?;
            for value in self.0 {
                sequence.serialize_element(&DepthValue(value, self.1))?;
            }
            sequence.end()
        }
    }

    impl Serialize for DepthEntries<'_> {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            let mut entries = serializer.serialize_map(Some(self.0.iter().len()))?;
            for (key, value) in self.0 {
                entries.serialize_entry(key, &DepthValue(value, self.1))?;
            }
            entries.end()
        }
    }

    impl Serialize for MetadataValue {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            DepthValue(self, 1).serialize(serializer)
        }
    }

    impl Serialize for Metadata {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            DepthEntries(self, 1).serialize(serializer)
        }
    }

    /// Reads one metadata value, refusing to descend past the depth bound.
    struct ValueSeed(usize);

    impl<'de> DeserializeSeed<'de> for ValueSeed {
        type Value = MetadataValue;

        fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
        where
            D: Deserializer<'de>,
        {
            if self.0 > MAX_METADATA_DEPTH {
                return Err(D::Error::custom(TooDeep));
            }
            deserializer.deserialize_enum(VALUE_NAME, VALUE_VARIANTS, ValueVisitor(self.0))
        }
    }

    struct ValueVisitor(usize);

    impl<'de> Visitor<'de> for ValueVisitor {
        type Value = MetadataValue;

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

        fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
        where
            A: EnumAccess<'de>,
        {
            let (tag, variant) = data.variant_seed(IdentifierSeed(VALUE_VARIANTS))?;
            let nested = self.0 + 1;
            match tag.0.as_str() {
                "null" => {
                    variant.unit_variant()?;
                    Ok(MetadataValue::Null)
                }
                "bool" => variant.newtype_variant().map(MetadataValue::Bool),
                "signed" => variant.newtype_variant().map(MetadataValue::Signed),
                "unsigned" => variant.newtype_variant().map(MetadataValue::Unsigned),
                "float" => variant.newtype_variant().map(MetadataValue::Float),
                "string" => variant.newtype_variant().map(MetadataValue::String),
                "bytes" => variant
                    .newtype_variant::<ByteBuf>()
                    .map(|buffer| MetadataValue::Bytes(buffer.0)),
                "array" => variant
                    .newtype_variant_seed(ElementsSeed(nested))
                    .map(MetadataValue::Array),
                "object" => variant
                    .newtype_variant_seed(EntriesSeed(nested))
                    .map(MetadataValue::Object),
                unknown => Err(A::Error::unknown_variant(unknown, VALUE_VARIANTS)),
            }
        }
    }

    struct ElementsSeed(usize);

    impl<'de> DeserializeSeed<'de> for ElementsSeed {
        type Value = Vec<MetadataValue>;

        fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
        where
            D: Deserializer<'de>,
        {
            deserializer.deserialize_seq(ElementsVisitor(self.0))
        }
    }

    struct ElementsVisitor(usize);

    impl<'de> Visitor<'de> for ElementsVisitor {
        type Value = Vec<MetadataValue>;

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

        fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
        where
            A: SeqAccess<'de>,
        {
            let mut values = Vec::new();
            while let Some(value) = sequence.next_element_seed(ValueSeed(self.0))? {
                values.push(value);
            }
            Ok(values)
        }
    }

    struct EntriesSeed(usize);

    impl<'de> DeserializeSeed<'de> for EntriesSeed {
        type Value = Metadata;

        fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
        where
            D: Deserializer<'de>,
        {
            deserializer.deserialize_map(EntriesVisitor(self.0))
        }
    }

    struct EntriesVisitor(usize);

    impl<'de> Visitor<'de> for EntriesVisitor {
        type Value = Metadata;

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

        /// Builds through the public constructor, so a repeated key keeps the
        /// last value exactly as [`Metadata::from_iter`] documents.
        fn visit_map<A>(self, mut entries: A) -> Result<Self::Value, A::Error>
        where
            A: MapAccess<'de>,
        {
            let mut metadata = Metadata::new();
            while let Some(key) = entries.next_key::<String>()? {
                let value = entries.next_value_seed(ValueSeed(self.0))?;
                drop(metadata.insert(key, value));
            }
            Ok(metadata)
        }
    }

    impl<'de> Deserialize<'de> for MetadataValue {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            ValueSeed(1).deserialize(deserializer)
        }
    }

    impl<'de> Deserialize<'de> for Metadata {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            EntriesSeed(1).deserialize(deserializer)
        }
    }

    // -- PartFields ----------------------------------------------------------

    impl Serialize for PartFields {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            let mut record = serializer.serialize_struct("PartFields", 6)?;
            record.serialize_field("text", &self.text)?;
            record.serialize_field("mime", &self.mime)?;
            record.serialize_field("data", &self.data.as_deref().map(Bytes))?;
            record.serialize_field("reference", &self.reference)?;
            record.serialize_field("metadata", &self.metadata)?;
            record.serialize_field("raw", &self.raw)?;
            record.end()
        }
    }

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

    struct FieldsVisitor;

    impl<'de> Visitor<'de> for FieldsVisitor {
        type Value = PartFields;

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

        fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
        where
            A: SeqAccess<'de>,
        {
            let text = wire::element(&mut sequence, 0)?;
            let mime = wire::element(&mut sequence, 1)?;
            let data = wire::element::<Option<ByteBuf>, _>(&mut sequence, 2)?;
            let reference = wire::element(&mut sequence, 3)?;
            let metadata = wire::element(&mut sequence, 4)?;
            let raw = wire::element(&mut sequence, 5)?;
            wire::end(&mut sequence, 6)?;
            Ok(PartFields::new(
                text,
                mime,
                ByteBuf::into_optional(data),
                reference,
                metadata,
                raw,
            ))
        }

        fn visit_map<A>(self, mut entries: A) -> Result<Self::Value, A::Error>
        where
            A: MapAccess<'de>,
        {
            let mut text = None;
            let mut mime = None;
            let mut data = None::<Option<ByteBuf>>;
            let mut reference = None;
            let mut metadata = None;
            let mut raw = None;
            while let Some(field) = entries.next_key_seed(IdentifierSeed(FIELDS_FIELDS))? {
                match field.0.as_str() {
                    "text" => wire::accept(&mut text, entries.next_value()?, "text")?,
                    "mime" => wire::accept(&mut mime, entries.next_value()?, "mime")?,
                    "data" => wire::accept(&mut data, entries.next_value()?, "data")?,
                    "reference" => {
                        wire::accept(&mut reference, entries.next_value()?, "reference")?;
                    }
                    "metadata" => wire::accept(&mut metadata, entries.next_value()?, "metadata")?,
                    "raw" => wire::accept(&mut raw, entries.next_value()?, "raw")?,
                    unknown => return Err(A::Error::unknown_field(unknown, FIELDS_FIELDS)),
                }
            }
            Ok(PartFields::new(
                wire::require(text, "text")?,
                wire::require(mime, "mime")?,
                ByteBuf::into_optional(wire::require(data, "data")?),
                wire::require(reference, "reference")?,
                wire::require(metadata, "metadata")?,
                wire::require(raw, "raw")?,
            ))
        }
    }

    // -- Part ----------------------------------------------------------------

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

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

    struct PartVisitor;

    impl<'de> Visitor<'de> for PartVisitor {
        type Value = Part;

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

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

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

    // -- SegmentExtensions ---------------------------------------------------

    /// Rebuilds extensions from the complete field set, identity included.
    ///
    /// `SegmentExtensions::new` deliberately takes no identity, because a
    /// provider adapter does not supply one there. Reading a record is the one
    /// place that has to restore every field it wrote, so it goes through the
    /// builder rather than through a constructor an adapter would misread.
    fn extensions(
        signature: String,
        raw: Option<Payload>,
        provider_data: Option<Vec<Envelope>>,
        item_id: Option<String>,
    ) -> SegmentExtensions {
        let extensions = SegmentExtensions::new(signature, raw, provider_data);
        match item_id {
            Some(id) => extensions.with_item_id(id),
            None => extensions,
        }
    }

    impl Serialize for SegmentExtensions {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            let mut record = serializer.serialize_struct("SegmentExtensions", 4)?;
            record.serialize_field("signature", &self.signature)?;
            record.serialize_field("raw", &self.raw)?;
            record.serialize_field("provider_data", &self.provider_data)?;
            record.serialize_field("item_id", &self.item_id)?;
            record.end()
        }
    }

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

    struct ExtensionsVisitor;

    impl<'de> Visitor<'de> for ExtensionsVisitor {
        type Value = SegmentExtensions;

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

        fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
        where
            A: SeqAccess<'de>,
        {
            let signature = wire::element(&mut sequence, 0)?;
            let raw = wire::element(&mut sequence, 1)?;
            let provider_data = wire::element(&mut sequence, 2)?;
            let item_id = wire::element(&mut sequence, 3)?;
            wire::end(&mut sequence, 4)?;
            Ok(extensions(signature, raw, provider_data, item_id))
        }

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

    // -- Segment -------------------------------------------------------------

    const fn text_segment(text: String, extensions: SegmentExtensions) -> Segment {
        Segment::Text { text, extensions }
    }

    const fn thinking_segment(text: String, extensions: SegmentExtensions) -> Segment {
        Segment::Thinking { text, extensions }
    }

    impl Serialize for Segment {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            match self {
                Self::Text { text, extensions } => {
                    let mut record =
                        serializer.serialize_struct_variant(SEGMENT_NAME, 0, "text", 2)?;
                    record.serialize_field("text", text)?;
                    record.serialize_field("extensions", extensions)?;
                    record.end()
                }
                Self::Thinking { text, extensions } => {
                    let mut record =
                        serializer.serialize_struct_variant(SEGMENT_NAME, 1, "thinking", 2)?;
                    record.serialize_field("text", text)?;
                    record.serialize_field("extensions", extensions)?;
                    record.end()
                }
                Self::ToolCall { call, extensions } => {
                    let mut record =
                        serializer.serialize_struct_variant(SEGMENT_NAME, 2, "tool_call", 2)?;
                    record.serialize_field("call", call)?;
                    record.serialize_field("extensions", extensions)?;
                    record.end()
                }
            }
        }
    }

    impl<'de> Deserialize<'de> for Segment {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            deserializer.deserialize_enum(SEGMENT_NAME, SEGMENT_VARIANTS, SegmentVisitor)
        }
    }

    struct SegmentVisitor;

    impl<'de> Visitor<'de> for SegmentVisitor {
        type Value = Segment;

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

        fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
        where
            A: EnumAccess<'de>,
        {
            let (tag, variant) = data.variant_seed(IdentifierSeed(SEGMENT_VARIANTS))?;
            match tag.0.as_str() {
                "text" => variant.struct_variant(TEXT_SEGMENT_FIELDS, TextVisitor(text_segment)),
                "thinking" => {
                    variant.struct_variant(TEXT_SEGMENT_FIELDS, TextVisitor(thinking_segment))
                }
                "tool_call" => {
                    variant.struct_variant(TOOL_CALL_SEGMENT_FIELDS, ToolCallSegmentVisitor)
                }
                unknown => Err(A::Error::unknown_variant(unknown, SEGMENT_VARIANTS)),
            }
        }
    }

    /// Reads the two text-bearing segment variants, which differ only in which
    /// one they build.
    struct TextVisitor(fn(String, SegmentExtensions) -> Segment);

    impl<'de> Visitor<'de> for TextVisitor {
        type Value = Segment;

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

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

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

    struct ToolCallSegmentVisitor;

    impl<'de> Visitor<'de> for ToolCallSegmentVisitor {
        type Value = Segment;

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

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

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