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
//! Tool-call identities, invocations, and closed tool-result values.

use std::error::Error;
use std::fmt::{self, Debug, Display, Formatter};

use crate::opaque::Payload;
use crate::redact;

use super::content::{self, Metadata, Part};

/// A model-assigned tool-call correlation identity.
///
/// Empty and nonempty identities are both representable because validation
/// belongs to the model-stream boundary, not this leaf value.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Id(String);

impl Id {
    /// Creates an identity without interpreting its contents.
    #[must_use]
    pub const fn new(value: String) -> Self {
        Self(value)
    }

    /// Returns the identity as a string slice.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Transfers the owned identity.
    #[must_use]
    pub fn into_string(self) -> String {
        self.0
    }
}

/// The name selecting a tool to invoke.
///
/// Empty and nonempty names are both representable at this leaf boundary.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Name(String);

impl Name {
    /// Creates a name without interpreting its contents.
    #[must_use]
    pub const fn new(value: String) -> Self {
        Self(value)
    }

    /// Returns the name as a string slice.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Transfers the owned name.
    #[must_use]
    pub fn into_string(self) -> String {
        self.0
    }
}

/// A complete model-initiated tool invocation.
///
/// ```
/// use reef_core::opaque;
/// use reef_core::value::tool_call;
/// let call = tool_call::ToolCall::new(
///     tool_call::Id::new("call-1".into()),
///     tool_call::Name::new("search".into()),
///     opaque::Payload::copy_from_slice(br#"{"q":"reef"}"#),
/// );
/// assert_eq!(call.id().as_str(), "call-1");
/// assert_eq!(call.name().as_str(), "search");
/// assert_eq!(call.arguments().as_bytes(), br#"{"q":"reef"}"#);
/// ```
///
/// # Equality
///
/// Field-wise content: same [`Id`], same [`Name`], and a [`Payload`] equal by
/// the byte-wise rule that type documents. It is **not** correlation identity.
/// Correlation identity is [`Id`].
/// [`ToolCallDecision::Modify`](crate::runtime::hook::ToolCallDecision::Modify)
/// can replace the call before execution and change the name and arguments;
/// the runtime preserves the model-assigned id as correlation identity. Two values
/// that share an id are not therefore equal, and two values that differ in id are
/// not therefore "the same call in a later edit."
///
/// Empty [`Id`] and [`Name`] values compare equal at this leaf; the event layer
/// still rejects empty identities. The relation is total, so this is an [`Eq`].
/// Nothing here is normalized before the comparison: two argument payloads a
/// provider would read as the same JSON are unequal whenever their bytes
/// differ, for the same reason [`Payload`] documents.
///
/// ```
/// use reef_core::opaque;
/// use reef_core::value::tool_call;
///
/// let call = |id: &str, name: &str, arguments: &[u8]| {
///     tool_call::ToolCall::new(
///         tool_call::Id::new(id.into()),
///         tool_call::Name::new(name.into()),
///         opaque::Payload::copy_from_slice(arguments),
///     )
/// };
///
/// assert_eq!(
///     call("call-1", "search", br#"{"q":"reef"}"#),
///     call("call-1", "search", br#"{"q":"reef"}"#)
/// );
/// // Same correlation identity; different name, so a different call.
/// assert_ne!(
///     call("call-1", "search", br#"{"q":"reef"}"#),
///     call("call-1", "lookup", br#"{"q":"reef"}"#)
/// );
/// // Same JSON to a provider; different bytes, so a different call.
/// assert_ne!(
///     call("call-1", "search", br#"{"q":"reef"}"#),
///     call("call-1", "search", br#"{ "q" : "reef" }"#)
/// );
/// // Empty leaves compare equal here; the event layer still rejects empty ids.
/// assert_eq!(call("", "", b""), call("", "", b""));
/// ```
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ToolCall {
    id: Id,
    name: Name,
    arguments: Payload,
}

impl ToolCall {
    /// Creates a call from owned identity, name, and opaque arguments.
    #[must_use]
    pub const fn new(id: Id, name: Name, arguments: Payload) -> Self {
        Self {
            id,
            name,
            arguments,
        }
    }

    /// Returns the model-assigned identity.
    #[must_use]
    pub const fn id(&self) -> &Id {
        &self.id
    }

    /// Returns the selected tool name.
    #[must_use]
    pub const fn name(&self) -> &Name {
        &self.name
    }

    /// Returns the opaque model-supplied arguments.
    #[must_use]
    pub const fn arguments(&self) -> &Payload {
        &self.arguments
    }

    /// Transfers every call field.
    #[must_use]
    pub fn into_parts(self) -> (Id, Name, Payload) {
        (self.id, self.name, self.arguments)
    }
}

/// A field-complete [`Part`] verified for use in tool output.
///
/// This wrapper can only be obtained through [`ToolPart::try_from_part`].
///
/// ```compile_fail
/// use reef_core::value::{content, tool_call};
/// let _unchecked = tool_call::ToolPart(content::Part::text("result".into()));
/// ```
#[derive(Clone, Debug)]
pub struct ToolPart(Part);

/// A stable failure from the open-Part to verified-tool-Part boundary.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ToolPartError {
    /// The numeric Part kind has no known portable interpretation.
    UnknownKind(i64),
}

impl Display for ToolPartError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnknownKind(kind) => write!(formatter, "unknown tool part kind {kind}"),
        }
    }
}

impl Error for ToolPartError {}

impl ToolPart {
    /// Verifies that `part` has one of the five known kinds without changing it.
    ///
    /// The check is deliberately narrow: ordinary Part paths remain open, and
    /// only tool output has to be one of the five interpretable kinds.
    ///
    /// # Errors
    ///
    /// [`ToolPartError::UnknownKind`], carrying the rejected number, if the
    /// part's canonical kind is not one of the five this crate can interpret.
    /// Tool output is the one Part consumer that narrows: every other path keeps
    /// an unrecognised numeric kind so a provider extension survives a round
    /// trip, but a tool result the model will act on may not carry a kind reef
    /// cannot name. Nothing else can fail here — an accepted part is retained
    /// whole, with every field and every presence distinction intact.
    pub fn try_from_part(part: Part) -> Result<Self, ToolPartError> {
        let kind = part.kind();
        if kind.known().is_some() {
            Ok(Self(part))
        } else {
            Err(ToolPartError::UnknownKind(kind.as_i64()))
        }
    }

    /// Returns the complete verified Part.
    #[must_use]
    pub const fn as_part(&self) -> &Part {
        &self.0
    }

    /// Transfers the complete verified Part.
    #[must_use]
    pub fn into_part(self) -> Part {
        self.0
    }
}

/// The presence state of tool-result metadata.
#[derive(Clone, Debug)]
pub enum MetadataPresence {
    /// Metadata is absent.
    Absent,
    /// Metadata is explicitly present as null.
    PresentNull,
    /// Metadata is present as an object, including an empty object.
    Present(Metadata),
}

/// The payload carried by an explicit successful or business-error result.
///
/// ```
/// use reef_core::value::{content, tool_call};
/// let verified = tool_call::ToolPart::try_from_part(content::Part::text("ok".into())).unwrap();
/// let output = tool_call::ToolOutput::new(
///     vec![verified], Some(String::new()), None,
///     tool_call::MetadataPresence::Present(content::Metadata::new()),
/// );
/// assert_eq!(output.model_content().len(), 1);
/// assert_eq!(output.user_view(), Some(""));
/// assert_eq!(output.log_preview(), None);
/// ```
///
/// ```compile_fail
/// use reef_core::value::{content, tool_call};
/// let _unchecked = tool_call::ToolOutput::new(
///     vec![content::Part::text("not verified".into())], None, None, tool_call::MetadataPresence::Absent,
/// );
/// ```
#[derive(Clone)]
pub struct ToolOutput {
    model_content: Vec<ToolPart>,
    user_view: Option<String>,
    log_preview: Option<String>,
    metadata: MetadataPresence,
}

impl Debug for ToolOutput {
    /// Sizes both rendered views and keeps their presence apart.
    ///
    /// `user_view` and `log_preview` are the two fields an end user sees, so
    /// they are the last place a formatter should quote. `model_content` needs
    /// no special handling: every element redacts itself.
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ToolOutput")
            .field("model_content", &self.model_content)
            .field(
                "user_view",
                &self
                    .user_view
                    .as_deref()
                    .map(|view| redact::Bytes(view.len())),
            )
            .field(
                "log_preview",
                &self
                    .log_preview
                    .as_deref()
                    .map(|preview| redact::Bytes(preview.len())),
            )
            .field("metadata", &self.metadata)
            .finish()
    }
}

impl ToolOutput {
    /// Creates an owned output from already verified model content.
    #[must_use]
    pub const fn new(
        model_content: Vec<ToolPart>,
        user_view: Option<String>,
        log_preview: Option<String>,
        metadata: MetadataPresence,
    ) -> Self {
        Self {
            model_content,
            user_view,
            log_preview,
            metadata,
        }
    }

    /// Returns ordered, verified model-facing content.
    #[must_use]
    pub fn model_content(&self) -> &[ToolPart] {
        &self.model_content
    }

    /// Returns the optional complete user-facing representation.
    #[must_use]
    pub fn user_view(&self) -> Option<&str> {
        self.user_view.as_deref()
    }

    /// Returns the optional bounded log representation.
    #[must_use]
    pub fn log_preview(&self) -> Option<&str> {
        self.log_preview.as_deref()
    }

    /// Returns the exact metadata presence state.
    #[must_use]
    pub const fn metadata(&self) -> &MetadataPresence {
        &self.metadata
    }

    /// Transfers every output field and its presence state.
    #[must_use]
    pub fn into_parts(
        self,
    ) -> (
        Vec<ToolPart>,
        Option<String>,
        Option<String>,
        MetadataPresence,
    ) {
        (
            self.model_content,
            self.user_view,
            self.log_preview,
            self.metadata,
        )
    }
}

/// A closed three-state tool result.
///
/// Ordinary tool failures use [`ToolResult::BusinessError`], not Rust `Err`.
///
/// ```
/// use reef_core::value::tool_call;
/// let empty = || tool_call::ToolOutput::new(vec![], None, None, tool_call::MetadataPresence::Absent);
/// let results = [tool_call::ToolResult::no_output(), tool_call::ToolResult::success(empty()), tool_call::ToolResult::business_error(empty())];
/// assert!(!results[0].has_output());
/// assert!(results[1].output().is_some());
/// assert!(results[2].is_business_error());
/// ```
///
/// ```compile_fail
/// use reef_core::value::tool_call;
/// let output = tool_call::ToolOutput::new(vec![], None, None, tool_call::MetadataPresence::Absent);
/// let _invalid = tool_call::ToolResult::NoOutput(output);
/// ```
#[derive(Clone, Debug, Default)]
pub enum ToolResult {
    /// The tool produced no output payload.
    #[default]
    NoOutput,
    /// The tool explicitly succeeded, even if model content is empty.
    Success(ToolOutput),
    /// The tool returned an ordinary model-facing business error.
    BusinessError(ToolOutput),
}

impl ToolResult {
    /// Creates the payload-free no-output state.
    #[must_use]
    pub const fn no_output() -> Self {
        Self::NoOutput
    }

    /// Creates an explicit successful result.
    #[must_use]
    pub const fn success(output: ToolOutput) -> Self {
        Self::Success(output)
    }

    /// Creates an explicit business-error result.
    #[must_use]
    pub const fn business_error(output: ToolOutput) -> Self {
        Self::BusinessError(output)
    }

    /// Creates a successful scalar text result with present user and log views.
    #[must_use]
    pub fn success_text(text: String) -> Self {
        Self::Success(text_output(text))
    }

    /// Creates a business-error scalar text result with present user and log views.
    #[must_use]
    pub fn error_text(text: String) -> Self {
        Self::BusinessError(text_output(text))
    }

    /// Reports whether this is an explicit success or business error.
    #[must_use]
    pub const fn has_output(&self) -> bool {
        !matches!(self, Self::NoOutput)
    }

    /// Reports whether this is an explicit business error.
    #[must_use]
    pub const fn is_business_error(&self) -> bool {
        matches!(self, Self::BusinessError(_))
    }

    /// Returns the explicit output, if present.
    #[must_use]
    pub const fn output(&self) -> Option<&ToolOutput> {
        match self {
            Self::NoOutput => None,
            Self::Success(output) | Self::BusinessError(output) => Some(output),
        }
    }

    /// Renders this result as the text a reader would be shown.
    ///
    /// The rule has three cases, one per state, and this is the only place it
    /// is implemented:
    ///
    /// - [`ToolResult::NoOutput`] renders as nothing, not as a placeholder.
    /// - An output carrying a [`user_view`](ToolOutput::user_view) renders as
    ///   exactly that string, empty included.
    /// - An output without one renders the text of its
    ///   [`model_content`](ToolOutput::model_content), two blocks separated by a
    ///   single `\n` and nothing else added.
    ///
    /// ```
    /// use reef_core::value::{content, tool_call};
    ///
    /// let part = |text: &str| {
    ///     tool_call::ToolPart::try_from_part(content::Part::text(text.to_owned())).unwrap()
    /// };
    /// let output = tool_call::ToolOutput::new(
    ///     vec![part("row one"), part("row two")],
    ///     Some("2 matches".to_owned()),
    ///     None,
    ///     tool_call::MetadataPresence::Absent,
    /// );
    ///
    /// // The view the tool wrote for a reader, not the rows it wrote for the model.
    /// assert_eq!(tool_call::ToolResult::success(output).to_plain_text(), "2 matches");
    /// assert_eq!(tool_call::ToolResult::no_output().to_plain_text(), "");
    /// ```
    ///
    /// # Why a consumer should not walk the output instead
    ///
    /// Reaching the text by hand — `output`, `model_content`, `as_part`,
    /// `fields`, `text` — is five hops that compile and pass a test, and it
    /// skips the case that matters: a `user_view` is *by definition* the tool's
    /// own user-facing rendering of this result, so a renderer that ignores one
    /// shows the model's view to the user. Nothing fails; the screen is just
    /// wrong. Reef's own first re-implementation of this walk made exactly that
    /// mistake, which is why the rule has a public landing point rather than a
    /// documented convention.
    ///
    /// A business error renders the way a success does. Which of the two a
    /// result is, is [`is_business_error`](ToolResult::is_business_error)'s
    /// answer rather than a difference in text.
    ///
    /// # This is not a way around redaction
    ///
    /// Every byte returned here is already reachable through the accessor that
    /// owns it, so there is nothing to hide *from* — the same reason ADR-018
    /// gives for
    /// [`Item::to_plain_text`](crate::transcript::item::Item::to_plain_text),
    /// whose tool-result arm delegates here. What that decision protects against
    /// is accidental disclosure, and an explicit call is not accidental; there is
    /// deliberately no [`Display`] for a result.
    #[must_use]
    pub fn to_plain_text(&self) -> String {
        match self.output() {
            None => String::new(),
            Some(output) => output.user_view().map_or_else(
                || {
                    content::join_blocks(
                        output
                            .model_content()
                            .iter()
                            .map(|part| part.as_part().fields().text()),
                    )
                },
                ToOwned::to_owned,
            ),
        }
    }
}

fn text_output(text: String) -> ToolOutput {
    let preview = bounded_preview(&text);
    let model_text = text.clone();
    ToolOutput::new(
        vec![ToolPart(Part::text(model_text))],
        Some(text),
        Some(preview),
        MetadataPresence::Absent,
    )
}

// Truncation backs up to a UTF-8 boundary as required by ADR-005 instead of
// creating invalid text.
fn bounded_preview(text: &str) -> String {
    const LIMIT: usize = 200;
    if text.len() <= LIMIT {
        return text.to_owned();
    }

    let mut end = LIMIT;
    while !text.is_char_boundary(end) {
        end -= 1;
    }
    let mut preview = text[..end].to_owned();
    preview.push('…');
    preview
}

/// The serialized form of the tool-call value tree (ADR-019 D5).
///
/// [`Id`] and [`Name`] are bare strings and [`ToolPart`] is a bare [`Part`],
/// because each wrapper is a Rust representation detail. Reading a `ToolPart`
/// re-runs [`ToolPart::try_from_part`]: a part whose kind reef cannot name may
/// not enter a [`ToolOutput`] from a file any more than from a call site.
///
/// [`MetadataPresence`] is the reason the format writes every field. Its three
/// states are the whole point of the type, and they collapse into one the moment
/// an encoder is allowed to omit an absent value.
#[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::{Id, MetadataPresence, Name, ToolCall, ToolOutput, ToolPart, ToolResult};
    use crate::value::content::Part;
    use crate::wire::{self, IdentifierSeed};

    const CALL_FIELDS: &[&str] = &["id", "name", "arguments"];
    const OUTPUT_FIELDS: &[&str] = &["model_content", "user_view", "log_preview", "metadata"];
    const PRESENCE_NAME: &str = "MetadataPresence";
    const PRESENCE_VARIANTS: &[&str] = &["absent", "present_null", "present"];
    const RESULT_NAME: &str = "ToolResult";
    const RESULT_VARIANTS: &[&str] = &["no_output", "success", "business_error"];

    // -- Id and Name ---------------------------------------------------------

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

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

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

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

    // -- ToolCall ------------------------------------------------------------

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

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

    struct CallVisitor;

    impl<'de> Visitor<'de> for CallVisitor {
        type Value = ToolCall;

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

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

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

    // -- ToolPart ------------------------------------------------------------

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

    impl<'de> Deserialize<'de> for ToolPart {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            let part = Part::deserialize(deserializer)?;
            Self::try_from_part(part).map_err(D::Error::custom)
        }
    }

    // -- MetadataPresence ----------------------------------------------------

    impl Serialize for MetadataPresence {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            match self {
                Self::Absent => serializer.serialize_unit_variant(PRESENCE_NAME, 0, "absent"),
                Self::PresentNull => {
                    serializer.serialize_unit_variant(PRESENCE_NAME, 1, "present_null")
                }
                Self::Present(metadata) => {
                    serializer.serialize_newtype_variant(PRESENCE_NAME, 2, "present", metadata)
                }
            }
        }
    }

    impl<'de> Deserialize<'de> for MetadataPresence {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            deserializer.deserialize_enum(PRESENCE_NAME, PRESENCE_VARIANTS, PresenceVisitor)
        }
    }

    struct PresenceVisitor;

    impl<'de> Visitor<'de> for PresenceVisitor {
        type Value = MetadataPresence;

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

        fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
        where
            A: EnumAccess<'de>,
        {
            let (tag, variant) = data.variant_seed(IdentifierSeed(PRESENCE_VARIANTS))?;
            match tag.0.as_str() {
                "absent" => {
                    variant.unit_variant()?;
                    Ok(MetadataPresence::Absent)
                }
                "present_null" => {
                    variant.unit_variant()?;
                    Ok(MetadataPresence::PresentNull)
                }
                "present" => variant.newtype_variant().map(MetadataPresence::Present),
                unknown => Err(A::Error::unknown_variant(unknown, PRESENCE_VARIANTS)),
            }
        }
    }

    // -- ToolOutput ----------------------------------------------------------

    impl Serialize for ToolOutput {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            let mut record = serializer.serialize_struct("ToolOutput", 4)?;
            record.serialize_field("model_content", &self.model_content)?;
            record.serialize_field("user_view", &self.user_view)?;
            record.serialize_field("log_preview", &self.log_preview)?;
            record.serialize_field("metadata", &self.metadata)?;
            record.end()
        }
    }

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

    struct OutputVisitor;

    impl<'de> Visitor<'de> for OutputVisitor {
        type Value = ToolOutput;

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

        fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
        where
            A: SeqAccess<'de>,
        {
            let model_content = wire::element(&mut sequence, 0)?;
            let user_view = wire::element(&mut sequence, 1)?;
            let log_preview = wire::element(&mut sequence, 2)?;
            let metadata = wire::element(&mut sequence, 3)?;
            wire::end(&mut sequence, 4)?;
            Ok(ToolOutput::new(
                model_content,
                user_view,
                log_preview,
                metadata,
            ))
        }

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

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

    impl Serialize for ToolResult {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            match self {
                Self::NoOutput => serializer.serialize_unit_variant(RESULT_NAME, 0, "no_output"),
                Self::Success(output) => {
                    serializer.serialize_newtype_variant(RESULT_NAME, 1, "success", output)
                }
                Self::BusinessError(output) => {
                    serializer.serialize_newtype_variant(RESULT_NAME, 2, "business_error", output)
                }
            }
        }
    }

    impl<'de> Deserialize<'de> for ToolResult {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            deserializer.deserialize_enum(RESULT_NAME, RESULT_VARIANTS, ResultVisitor)
        }
    }

    struct ResultVisitor;

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

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

        fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
        where
            A: EnumAccess<'de>,
        {
            let (tag, variant) = data.variant_seed(IdentifierSeed(RESULT_VARIANTS))?;
            match tag.0.as_str() {
                "no_output" => {
                    variant.unit_variant()?;
                    Ok(ToolResult::no_output())
                }
                "success" => variant.newtype_variant().map(ToolResult::success),
                "business_error" => variant.newtype_variant().map(ToolResult::business_error),
                unknown => Err(A::Error::unknown_variant(unknown, RESULT_VARIANTS)),
            }
        }
    }
}