reef_core/value/tool_call.rs
1//! Tool-call identities, invocations, and closed tool-result values.
2
3use std::error::Error;
4use std::fmt::{self, Debug, Display, Formatter};
5
6use crate::opaque::Payload;
7use crate::redact;
8
9use super::content::{self, Metadata, Part};
10
11/// A model-assigned tool-call correlation identity.
12///
13/// Empty and nonempty identities are both representable because validation
14/// belongs to the model-stream boundary, not this leaf value.
15#[derive(Clone, Debug, Eq, PartialEq)]
16pub struct Id(String);
17
18impl Id {
19 /// Creates an identity without interpreting its contents.
20 #[must_use]
21 pub const fn new(value: String) -> Self {
22 Self(value)
23 }
24
25 /// Returns the identity as a string slice.
26 #[must_use]
27 pub fn as_str(&self) -> &str {
28 &self.0
29 }
30
31 /// Transfers the owned identity.
32 #[must_use]
33 pub fn into_string(self) -> String {
34 self.0
35 }
36}
37
38/// The name selecting a tool to invoke.
39///
40/// Empty and nonempty names are both representable at this leaf boundary.
41#[derive(Clone, Debug, Eq, PartialEq)]
42pub struct Name(String);
43
44impl Name {
45 /// Creates a name without interpreting its contents.
46 #[must_use]
47 pub const fn new(value: String) -> Self {
48 Self(value)
49 }
50
51 /// Returns the name as a string slice.
52 #[must_use]
53 pub fn as_str(&self) -> &str {
54 &self.0
55 }
56
57 /// Transfers the owned name.
58 #[must_use]
59 pub fn into_string(self) -> String {
60 self.0
61 }
62}
63
64/// A complete model-initiated tool invocation.
65///
66/// ```
67/// use reef_core::opaque;
68/// use reef_core::value::tool_call;
69/// let call = tool_call::ToolCall::new(
70/// tool_call::Id::new("call-1".into()),
71/// tool_call::Name::new("search".into()),
72/// opaque::Payload::copy_from_slice(br#"{"q":"reef"}"#),
73/// );
74/// assert_eq!(call.id().as_str(), "call-1");
75/// assert_eq!(call.name().as_str(), "search");
76/// assert_eq!(call.arguments().as_bytes(), br#"{"q":"reef"}"#);
77/// ```
78///
79/// # Equality
80///
81/// Field-wise content: same [`Id`], same [`Name`], and a [`Payload`] equal by
82/// the byte-wise rule that type documents. It is **not** correlation identity.
83/// Correlation identity is [`Id`].
84/// [`ToolCallDecision::Modify`](crate::runtime::hook::ToolCallDecision::Modify)
85/// can replace the call before the gate plane and change the name and arguments
86/// while keeping or replacing the id; two values that share an id are not
87/// therefore equal, and two values that differ in id are not therefore "the
88/// same call in a later edit."
89///
90/// Empty [`Id`] and [`Name`] values compare equal at this leaf; the event layer
91/// still rejects empty identities. The relation is total, so this is an [`Eq`].
92/// Nothing here is normalized before the comparison: two argument payloads a
93/// provider would read as the same JSON are unequal whenever their bytes
94/// differ, for the same reason [`Payload`] documents.
95///
96/// ```
97/// use reef_core::opaque;
98/// use reef_core::value::tool_call;
99///
100/// let call = |id: &str, name: &str, arguments: &[u8]| {
101/// tool_call::ToolCall::new(
102/// tool_call::Id::new(id.into()),
103/// tool_call::Name::new(name.into()),
104/// opaque::Payload::copy_from_slice(arguments),
105/// )
106/// };
107///
108/// assert_eq!(
109/// call("call-1", "search", br#"{"q":"reef"}"#),
110/// call("call-1", "search", br#"{"q":"reef"}"#)
111/// );
112/// // Same correlation identity; different name, so a different call.
113/// assert_ne!(
114/// call("call-1", "search", br#"{"q":"reef"}"#),
115/// call("call-1", "lookup", br#"{"q":"reef"}"#)
116/// );
117/// // Same JSON to a provider; different bytes, so a different call.
118/// assert_ne!(
119/// call("call-1", "search", br#"{"q":"reef"}"#),
120/// call("call-1", "search", br#"{ "q" : "reef" }"#)
121/// );
122/// // Empty leaves compare equal here; the event layer still rejects empty ids.
123/// assert_eq!(call("", "", b""), call("", "", b""));
124/// ```
125#[derive(Clone, Debug, Eq, PartialEq)]
126pub struct ToolCall {
127 id: Id,
128 name: Name,
129 arguments: Payload,
130}
131
132impl ToolCall {
133 /// Creates a call from owned identity, name, and opaque arguments.
134 #[must_use]
135 pub const fn new(id: Id, name: Name, arguments: Payload) -> Self {
136 Self {
137 id,
138 name,
139 arguments,
140 }
141 }
142
143 /// Returns the model-assigned identity.
144 #[must_use]
145 pub const fn id(&self) -> &Id {
146 &self.id
147 }
148
149 /// Returns the selected tool name.
150 #[must_use]
151 pub const fn name(&self) -> &Name {
152 &self.name
153 }
154
155 /// Returns the opaque model-supplied arguments.
156 #[must_use]
157 pub const fn arguments(&self) -> &Payload {
158 &self.arguments
159 }
160
161 /// Transfers every call field.
162 #[must_use]
163 pub fn into_parts(self) -> (Id, Name, Payload) {
164 (self.id, self.name, self.arguments)
165 }
166}
167
168/// A field-complete [`Part`] verified for use in tool output.
169///
170/// This wrapper can only be obtained through [`ToolPart::try_from_part`].
171///
172/// ```compile_fail
173/// use reef_core::value::{content, tool_call};
174/// let _unchecked = tool_call::ToolPart(content::Part::text("result".into()));
175/// ```
176#[derive(Clone, Debug)]
177pub struct ToolPart(Part);
178
179/// A stable failure from the open-Part to verified-tool-Part boundary.
180#[derive(Clone, Copy, Debug, Eq, PartialEq)]
181#[non_exhaustive]
182pub enum ToolPartError {
183 /// The numeric Part kind has no known portable interpretation.
184 UnknownKind(i64),
185}
186
187impl Display for ToolPartError {
188 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
189 match self {
190 Self::UnknownKind(kind) => write!(formatter, "unknown tool part kind {kind}"),
191 }
192 }
193}
194
195impl Error for ToolPartError {}
196
197impl ToolPart {
198 /// Verifies that `part` has one of the five known kinds without changing it.
199 ///
200 /// The check is deliberately narrow: ordinary Part paths remain open, and
201 /// only tool output has to be one of the five interpretable kinds.
202 ///
203 /// # Errors
204 ///
205 /// [`ToolPartError::UnknownKind`], carrying the rejected number, if the
206 /// part's canonical kind is not one of the five this crate can interpret.
207 /// Tool output is the one Part consumer that narrows: every other path keeps
208 /// an unrecognised numeric kind so a provider extension survives a round
209 /// trip, but a tool result the model will act on may not carry a kind reef
210 /// cannot name. Nothing else can fail here — an accepted part is retained
211 /// whole, with every field and every presence distinction intact.
212 pub fn try_from_part(part: Part) -> Result<Self, ToolPartError> {
213 let kind = part.kind();
214 if kind.known().is_some() {
215 Ok(Self(part))
216 } else {
217 Err(ToolPartError::UnknownKind(kind.as_i64()))
218 }
219 }
220
221 /// Returns the complete verified Part.
222 #[must_use]
223 pub const fn as_part(&self) -> &Part {
224 &self.0
225 }
226
227 /// Transfers the complete verified Part.
228 #[must_use]
229 pub fn into_part(self) -> Part {
230 self.0
231 }
232}
233
234/// The presence state of tool-result metadata.
235#[derive(Clone, Debug)]
236pub enum MetadataPresence {
237 /// Metadata is absent.
238 Absent,
239 /// Metadata is explicitly present as null.
240 PresentNull,
241 /// Metadata is present as an object, including an empty object.
242 Present(Metadata),
243}
244
245/// The payload carried by an explicit successful or business-error result.
246///
247/// ```
248/// use reef_core::value::{content, tool_call};
249/// let verified = tool_call::ToolPart::try_from_part(content::Part::text("ok".into())).unwrap();
250/// let output = tool_call::ToolOutput::new(
251/// vec![verified], Some(String::new()), None,
252/// tool_call::MetadataPresence::Present(content::Metadata::new()),
253/// );
254/// assert_eq!(output.model_content().len(), 1);
255/// assert_eq!(output.user_view(), Some(""));
256/// assert_eq!(output.log_preview(), None);
257/// ```
258///
259/// ```compile_fail
260/// use reef_core::value::{content, tool_call};
261/// let _unchecked = tool_call::ToolOutput::new(
262/// vec![content::Part::text("not verified".into())], None, None, tool_call::MetadataPresence::Absent,
263/// );
264/// ```
265#[derive(Clone)]
266pub struct ToolOutput {
267 model_content: Vec<ToolPart>,
268 user_view: Option<String>,
269 log_preview: Option<String>,
270 metadata: MetadataPresence,
271}
272
273impl Debug for ToolOutput {
274 /// Sizes both rendered views and keeps their presence apart.
275 ///
276 /// `user_view` and `log_preview` are the two fields an end user sees, so
277 /// they are the last place a formatter should quote. `model_content` needs
278 /// no special handling: every element redacts itself.
279 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
280 formatter
281 .debug_struct("ToolOutput")
282 .field("model_content", &self.model_content)
283 .field(
284 "user_view",
285 &self
286 .user_view
287 .as_deref()
288 .map(|view| redact::Bytes(view.len())),
289 )
290 .field(
291 "log_preview",
292 &self
293 .log_preview
294 .as_deref()
295 .map(|preview| redact::Bytes(preview.len())),
296 )
297 .field("metadata", &self.metadata)
298 .finish()
299 }
300}
301
302impl ToolOutput {
303 /// Creates an owned output from already verified model content.
304 #[must_use]
305 pub const fn new(
306 model_content: Vec<ToolPart>,
307 user_view: Option<String>,
308 log_preview: Option<String>,
309 metadata: MetadataPresence,
310 ) -> Self {
311 Self {
312 model_content,
313 user_view,
314 log_preview,
315 metadata,
316 }
317 }
318
319 /// Returns ordered, verified model-facing content.
320 #[must_use]
321 pub fn model_content(&self) -> &[ToolPart] {
322 &self.model_content
323 }
324
325 /// Returns the optional complete user-facing representation.
326 #[must_use]
327 pub fn user_view(&self) -> Option<&str> {
328 self.user_view.as_deref()
329 }
330
331 /// Returns the optional bounded log representation.
332 #[must_use]
333 pub fn log_preview(&self) -> Option<&str> {
334 self.log_preview.as_deref()
335 }
336
337 /// Returns the exact metadata presence state.
338 #[must_use]
339 pub const fn metadata(&self) -> &MetadataPresence {
340 &self.metadata
341 }
342
343 /// Transfers every output field and its presence state.
344 #[must_use]
345 pub fn into_parts(
346 self,
347 ) -> (
348 Vec<ToolPart>,
349 Option<String>,
350 Option<String>,
351 MetadataPresence,
352 ) {
353 (
354 self.model_content,
355 self.user_view,
356 self.log_preview,
357 self.metadata,
358 )
359 }
360}
361
362/// A closed three-state tool result.
363///
364/// Ordinary tool failures use [`ToolResult::BusinessError`], not Rust `Err`.
365///
366/// ```
367/// use reef_core::value::tool_call;
368/// let empty = || tool_call::ToolOutput::new(vec![], None, None, tool_call::MetadataPresence::Absent);
369/// let results = [tool_call::ToolResult::no_output(), tool_call::ToolResult::success(empty()), tool_call::ToolResult::business_error(empty())];
370/// assert!(!results[0].has_output());
371/// assert!(results[1].output().is_some());
372/// assert!(results[2].is_business_error());
373/// ```
374///
375/// ```compile_fail
376/// use reef_core::value::tool_call;
377/// let output = tool_call::ToolOutput::new(vec![], None, None, tool_call::MetadataPresence::Absent);
378/// let _invalid = tool_call::ToolResult::NoOutput(output);
379/// ```
380#[derive(Clone, Debug, Default)]
381pub enum ToolResult {
382 /// The tool produced no output payload.
383 #[default]
384 NoOutput,
385 /// The tool explicitly succeeded, even if model content is empty.
386 Success(ToolOutput),
387 /// The tool returned an ordinary model-facing business error.
388 BusinessError(ToolOutput),
389}
390
391impl ToolResult {
392 /// Creates the payload-free no-output state.
393 #[must_use]
394 pub const fn no_output() -> Self {
395 Self::NoOutput
396 }
397
398 /// Creates an explicit successful result.
399 #[must_use]
400 pub const fn success(output: ToolOutput) -> Self {
401 Self::Success(output)
402 }
403
404 /// Creates an explicit business-error result.
405 #[must_use]
406 pub const fn business_error(output: ToolOutput) -> Self {
407 Self::BusinessError(output)
408 }
409
410 /// Creates a successful scalar text result with present user and log views.
411 #[must_use]
412 pub fn success_text(text: String) -> Self {
413 Self::Success(text_output(text))
414 }
415
416 /// Creates a business-error scalar text result with present user and log views.
417 #[must_use]
418 pub fn error_text(text: String) -> Self {
419 Self::BusinessError(text_output(text))
420 }
421
422 /// Reports whether this is an explicit success or business error.
423 #[must_use]
424 pub const fn has_output(&self) -> bool {
425 !matches!(self, Self::NoOutput)
426 }
427
428 /// Reports whether this is an explicit business error.
429 #[must_use]
430 pub const fn is_business_error(&self) -> bool {
431 matches!(self, Self::BusinessError(_))
432 }
433
434 /// Returns the explicit output, if present.
435 #[must_use]
436 pub const fn output(&self) -> Option<&ToolOutput> {
437 match self {
438 Self::NoOutput => None,
439 Self::Success(output) | Self::BusinessError(output) => Some(output),
440 }
441 }
442
443 /// Renders this result as the text a reader would be shown.
444 ///
445 /// The rule has three cases, one per state, and this is the only place it
446 /// is implemented:
447 ///
448 /// - [`ToolResult::NoOutput`] renders as nothing, not as a placeholder.
449 /// - An output carrying a [`user_view`](ToolOutput::user_view) renders as
450 /// exactly that string, empty included.
451 /// - An output without one renders the text of its
452 /// [`model_content`](ToolOutput::model_content), two blocks separated by a
453 /// single `\n` and nothing else added.
454 ///
455 /// ```
456 /// use reef_core::value::{content, tool_call};
457 ///
458 /// let part = |text: &str| {
459 /// tool_call::ToolPart::try_from_part(content::Part::text(text.to_owned())).unwrap()
460 /// };
461 /// let output = tool_call::ToolOutput::new(
462 /// vec![part("row one"), part("row two")],
463 /// Some("2 matches".to_owned()),
464 /// None,
465 /// tool_call::MetadataPresence::Absent,
466 /// );
467 ///
468 /// // The view the tool wrote for a reader, not the rows it wrote for the model.
469 /// assert_eq!(tool_call::ToolResult::success(output).to_plain_text(), "2 matches");
470 /// assert_eq!(tool_call::ToolResult::no_output().to_plain_text(), "");
471 /// ```
472 ///
473 /// # Why a consumer should not walk the output instead
474 ///
475 /// Reaching the text by hand — `output`, `model_content`, `as_part`,
476 /// `fields`, `text` — is five hops that compile and pass a test, and it
477 /// skips the case that matters: a `user_view` is *by definition* the tool's
478 /// own user-facing rendering of this result, so a renderer that ignores one
479 /// shows the model's view to the user. Nothing fails; the screen is just
480 /// wrong. Reef's own first re-implementation of this walk made exactly that
481 /// mistake, which is why the rule has a public landing point rather than a
482 /// documented convention.
483 ///
484 /// A business error renders the way a success does. Which of the two a
485 /// result is, is [`is_business_error`](ToolResult::is_business_error)'s
486 /// answer rather than a difference in text.
487 ///
488 /// # This is not a way around redaction
489 ///
490 /// Every byte returned here is already reachable through the accessor that
491 /// owns it, so there is nothing to hide *from* — the same reason ADR-018
492 /// gives for
493 /// [`Item::to_plain_text`](crate::transcript::item::Item::to_plain_text),
494 /// whose tool-result arm delegates here. What that decision protects against
495 /// is accidental disclosure, and an explicit call is not accidental; there is
496 /// deliberately no [`Display`] for a result.
497 #[must_use]
498 pub fn to_plain_text(&self) -> String {
499 match self.output() {
500 None => String::new(),
501 Some(output) => output.user_view().map_or_else(
502 || {
503 content::join_blocks(
504 output
505 .model_content()
506 .iter()
507 .map(|part| part.as_part().fields().text()),
508 )
509 },
510 ToOwned::to_owned,
511 ),
512 }
513 }
514}
515
516fn text_output(text: String) -> ToolOutput {
517 let preview = bounded_preview(&text);
518 let model_text = text.clone();
519 ToolOutput::new(
520 vec![ToolPart(Part::text(model_text))],
521 Some(text),
522 Some(preview),
523 MetadataPresence::Absent,
524 )
525}
526
527// Truncation backs up to a UTF-8 boundary as required by ADR-005 instead of
528// creating invalid text.
529fn bounded_preview(text: &str) -> String {
530 const LIMIT: usize = 200;
531 if text.len() <= LIMIT {
532 return text.to_owned();
533 }
534
535 let mut end = LIMIT;
536 while !text.is_char_boundary(end) {
537 end -= 1;
538 }
539 let mut preview = text[..end].to_owned();
540 preview.push('…');
541 preview
542}
543
544/// The serialized form of the tool-call value tree (ADR-019 D5).
545///
546/// [`Id`] and [`Name`] are bare strings and [`ToolPart`] is a bare [`Part`],
547/// because each wrapper is a Rust representation detail. Reading a `ToolPart`
548/// re-runs [`ToolPart::try_from_part`]: a part whose kind reef cannot name may
549/// not enter a [`ToolOutput`] from a file any more than from a call site.
550///
551/// [`MetadataPresence`] is the reason the format writes every field. Its three
552/// states are the whole point of the type, and they collapse into one the moment
553/// an encoder is allowed to omit an absent value.
554#[cfg(feature = "serde")]
555mod serde_impl {
556 use std::fmt::{self, Formatter};
557
558 use serde_core::de::{
559 Deserialize, Deserializer, EnumAccess, Error as DeError, MapAccess, SeqAccess,
560 VariantAccess, Visitor,
561 };
562 use serde_core::ser::{Serialize, SerializeStruct, Serializer};
563
564 use super::{Id, MetadataPresence, Name, ToolCall, ToolOutput, ToolPart, ToolResult};
565 use crate::value::content::Part;
566 use crate::wire::{self, IdentifierSeed};
567
568 const CALL_FIELDS: &[&str] = &["id", "name", "arguments"];
569 const OUTPUT_FIELDS: &[&str] = &["model_content", "user_view", "log_preview", "metadata"];
570 const PRESENCE_NAME: &str = "MetadataPresence";
571 const PRESENCE_VARIANTS: &[&str] = &["absent", "present_null", "present"];
572 const RESULT_NAME: &str = "ToolResult";
573 const RESULT_VARIANTS: &[&str] = &["no_output", "success", "business_error"];
574
575 // -- Id and Name ---------------------------------------------------------
576
577 impl Serialize for Id {
578 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
579 where
580 S: Serializer,
581 {
582 serializer.serialize_str(&self.0)
583 }
584 }
585
586 impl<'de> Deserialize<'de> for Id {
587 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
588 where
589 D: Deserializer<'de>,
590 {
591 String::deserialize(deserializer).map(Self::new)
592 }
593 }
594
595 impl Serialize for Name {
596 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
597 where
598 S: Serializer,
599 {
600 serializer.serialize_str(&self.0)
601 }
602 }
603
604 impl<'de> Deserialize<'de> for Name {
605 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
606 where
607 D: Deserializer<'de>,
608 {
609 String::deserialize(deserializer).map(Self::new)
610 }
611 }
612
613 // -- ToolCall ------------------------------------------------------------
614
615 impl Serialize for ToolCall {
616 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
617 where
618 S: Serializer,
619 {
620 let mut record = serializer.serialize_struct("ToolCall", 3)?;
621 record.serialize_field("id", &self.id)?;
622 record.serialize_field("name", &self.name)?;
623 record.serialize_field("arguments", &self.arguments)?;
624 record.end()
625 }
626 }
627
628 impl<'de> Deserialize<'de> for ToolCall {
629 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
630 where
631 D: Deserializer<'de>,
632 {
633 deserializer.deserialize_struct("ToolCall", CALL_FIELDS, CallVisitor)
634 }
635 }
636
637 struct CallVisitor;
638
639 impl<'de> Visitor<'de> for CallVisitor {
640 type Value = ToolCall;
641
642 fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
643 formatter.write_str("a tool invocation")
644 }
645
646 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
647 where
648 A: SeqAccess<'de>,
649 {
650 let id = wire::element(&mut sequence, 0)?;
651 let name = wire::element(&mut sequence, 1)?;
652 let arguments = wire::element(&mut sequence, 2)?;
653 Ok(ToolCall::new(id, name, arguments))
654 }
655
656 fn visit_map<A>(self, mut entries: A) -> Result<Self::Value, A::Error>
657 where
658 A: MapAccess<'de>,
659 {
660 let mut id = None;
661 let mut name = None;
662 let mut arguments = None;
663 while let Some(field) = entries.next_key_seed(IdentifierSeed(CALL_FIELDS))? {
664 match field.0.as_str() {
665 "id" => wire::accept(&mut id, entries.next_value()?, "id")?,
666 "name" => wire::accept(&mut name, entries.next_value()?, "name")?,
667 "arguments" => {
668 wire::accept(&mut arguments, entries.next_value()?, "arguments")?;
669 }
670 unknown => return Err(A::Error::unknown_field(unknown, CALL_FIELDS)),
671 }
672 }
673 Ok(ToolCall::new(
674 wire::require(id, "id")?,
675 wire::require(name, "name")?,
676 wire::require(arguments, "arguments")?,
677 ))
678 }
679 }
680
681 // -- ToolPart ------------------------------------------------------------
682
683 impl Serialize for ToolPart {
684 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
685 where
686 S: Serializer,
687 {
688 self.0.serialize(serializer)
689 }
690 }
691
692 impl<'de> Deserialize<'de> for ToolPart {
693 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
694 where
695 D: Deserializer<'de>,
696 {
697 let part = Part::deserialize(deserializer)?;
698 Self::try_from_part(part).map_err(D::Error::custom)
699 }
700 }
701
702 // -- MetadataPresence ----------------------------------------------------
703
704 impl Serialize for MetadataPresence {
705 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
706 where
707 S: Serializer,
708 {
709 match self {
710 Self::Absent => serializer.serialize_unit_variant(PRESENCE_NAME, 0, "absent"),
711 Self::PresentNull => {
712 serializer.serialize_unit_variant(PRESENCE_NAME, 1, "present_null")
713 }
714 Self::Present(metadata) => {
715 serializer.serialize_newtype_variant(PRESENCE_NAME, 2, "present", metadata)
716 }
717 }
718 }
719 }
720
721 impl<'de> Deserialize<'de> for MetadataPresence {
722 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
723 where
724 D: Deserializer<'de>,
725 {
726 deserializer.deserialize_enum(PRESENCE_NAME, PRESENCE_VARIANTS, PresenceVisitor)
727 }
728 }
729
730 struct PresenceVisitor;
731
732 impl<'de> Visitor<'de> for PresenceVisitor {
733 type Value = MetadataPresence;
734
735 fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
736 formatter.write_str("a tool-result metadata presence state")
737 }
738
739 fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
740 where
741 A: EnumAccess<'de>,
742 {
743 let (tag, variant) = data.variant_seed(IdentifierSeed(PRESENCE_VARIANTS))?;
744 match tag.0.as_str() {
745 "absent" => {
746 variant.unit_variant()?;
747 Ok(MetadataPresence::Absent)
748 }
749 "present_null" => {
750 variant.unit_variant()?;
751 Ok(MetadataPresence::PresentNull)
752 }
753 "present" => variant.newtype_variant().map(MetadataPresence::Present),
754 unknown => Err(A::Error::unknown_variant(unknown, PRESENCE_VARIANTS)),
755 }
756 }
757 }
758
759 // -- ToolOutput ----------------------------------------------------------
760
761 impl Serialize for ToolOutput {
762 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
763 where
764 S: Serializer,
765 {
766 let mut record = serializer.serialize_struct("ToolOutput", 4)?;
767 record.serialize_field("model_content", &self.model_content)?;
768 record.serialize_field("user_view", &self.user_view)?;
769 record.serialize_field("log_preview", &self.log_preview)?;
770 record.serialize_field("metadata", &self.metadata)?;
771 record.end()
772 }
773 }
774
775 impl<'de> Deserialize<'de> for ToolOutput {
776 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
777 where
778 D: Deserializer<'de>,
779 {
780 deserializer.deserialize_struct("ToolOutput", OUTPUT_FIELDS, OutputVisitor)
781 }
782 }
783
784 struct OutputVisitor;
785
786 impl<'de> Visitor<'de> for OutputVisitor {
787 type Value = ToolOutput;
788
789 fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
790 formatter.write_str("a tool output payload")
791 }
792
793 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
794 where
795 A: SeqAccess<'de>,
796 {
797 let model_content = wire::element(&mut sequence, 0)?;
798 let user_view = wire::element(&mut sequence, 1)?;
799 let log_preview = wire::element(&mut sequence, 2)?;
800 let metadata = wire::element(&mut sequence, 3)?;
801 Ok(ToolOutput::new(
802 model_content,
803 user_view,
804 log_preview,
805 metadata,
806 ))
807 }
808
809 fn visit_map<A>(self, mut entries: A) -> Result<Self::Value, A::Error>
810 where
811 A: MapAccess<'de>,
812 {
813 let mut model_content = None;
814 let mut user_view = None;
815 let mut log_preview = None;
816 let mut metadata = None;
817 while let Some(field) = entries.next_key_seed(IdentifierSeed(OUTPUT_FIELDS))? {
818 match field.0.as_str() {
819 "model_content" => {
820 wire::accept(&mut model_content, entries.next_value()?, "model_content")?;
821 }
822 "user_view" => {
823 wire::accept(&mut user_view, entries.next_value()?, "user_view")?;
824 }
825 "log_preview" => {
826 wire::accept(&mut log_preview, entries.next_value()?, "log_preview")?;
827 }
828 "metadata" => wire::accept(&mut metadata, entries.next_value()?, "metadata")?,
829 unknown => return Err(A::Error::unknown_field(unknown, OUTPUT_FIELDS)),
830 }
831 }
832 Ok(ToolOutput::new(
833 wire::require(model_content, "model_content")?,
834 wire::require(user_view, "user_view")?,
835 wire::require(log_preview, "log_preview")?,
836 wire::require(metadata, "metadata")?,
837 ))
838 }
839 }
840
841 // -- ToolResult ----------------------------------------------------------
842
843 impl Serialize for ToolResult {
844 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
845 where
846 S: Serializer,
847 {
848 match self {
849 Self::NoOutput => serializer.serialize_unit_variant(RESULT_NAME, 0, "no_output"),
850 Self::Success(output) => {
851 serializer.serialize_newtype_variant(RESULT_NAME, 1, "success", output)
852 }
853 Self::BusinessError(output) => {
854 serializer.serialize_newtype_variant(RESULT_NAME, 2, "business_error", output)
855 }
856 }
857 }
858 }
859
860 impl<'de> Deserialize<'de> for ToolResult {
861 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
862 where
863 D: Deserializer<'de>,
864 {
865 deserializer.deserialize_enum(RESULT_NAME, RESULT_VARIANTS, ResultVisitor)
866 }
867 }
868
869 struct ResultVisitor;
870
871 impl<'de> Visitor<'de> for ResultVisitor {
872 type Value = ToolResult;
873
874 fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
875 formatter.write_str("a closed tool result")
876 }
877
878 fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
879 where
880 A: EnumAccess<'de>,
881 {
882 let (tag, variant) = data.variant_seed(IdentifierSeed(RESULT_VARIANTS))?;
883 match tag.0.as_str() {
884 "no_output" => {
885 variant.unit_variant()?;
886 Ok(ToolResult::no_output())
887 }
888 "success" => variant.newtype_variant().map(ToolResult::success),
889 "business_error" => variant.newtype_variant().map(ToolResult::business_error),
890 unknown => Err(A::Error::unknown_variant(unknown, RESULT_VARIANTS)),
891 }
892 }
893 }
894}