1use std::{collections::BTreeMap, sync::Arc};
8
9use derive_more::{Display, From};
10#[cfg(feature = "schemars")]
11use schemars::Schema;
12use serde::{Deserialize, Serialize};
13use serde_with::{DefaultOnError, VecSkipError, serde_as, skip_serializing_none};
14
15use super::SessionId;
16use super::{AbsolutePath, ContentBlock, MediaType, Meta, Terminal, apply_meta_update};
17use crate::{IntoMaybeUndefined, IntoOption, MaybeUndefined};
18
19#[serde_as]
34#[skip_serializing_none]
35#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(rename_all = "camelCase")]
38#[non_exhaustive]
39pub struct ToolCallUpdate {
40 pub tool_call_id: ToolCallId,
42 #[serde_as(deserialize_as = "DefaultOnError")]
49 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
50 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
51 pub name: MaybeUndefined<String>,
52 #[serde_as(deserialize_as = "DefaultOnError")]
57 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
58 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
59 pub title: MaybeUndefined<String>,
60 #[serde_as(deserialize_as = "DefaultOnError")]
66 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
67 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
68 pub kind: MaybeUndefined<ToolKind>,
69 #[serde_as(deserialize_as = "DefaultOnError")]
75 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
76 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
77 pub status: MaybeUndefined<ToolCallStatus>,
78 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
80 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
81 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
82 pub content: MaybeUndefined<Vec<ToolCallContent>>,
83 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
86 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
87 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
88 pub locations: MaybeUndefined<Vec<ToolCallLocation>>,
89 #[serde_as(deserialize_as = "DefaultOnError")]
91 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
92 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
93 pub raw_input: MaybeUndefined<serde_json::Value>,
94 #[serde_as(deserialize_as = "DefaultOnError")]
96 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
97 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
98 pub raw_output: MaybeUndefined<serde_json::Value>,
99 #[serde_as(deserialize_as = "DefaultOnError")]
104 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
105 #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
106 pub capabilities: MaybeUndefined<ToolCallCapabilities>,
107 #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
116 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
117 #[serde(
118 rename = "_meta",
119 default,
120 skip_serializing_if = "MaybeUndefined::is_undefined"
121 )]
122 pub meta: MaybeUndefined<Meta>,
123}
124
125impl ToolCallUpdate {
126 #[must_use]
128 pub fn new(tool_call_id: impl Into<ToolCallId>) -> Self {
129 Self {
130 tool_call_id: tool_call_id.into(),
131 name: MaybeUndefined::Undefined,
132 title: MaybeUndefined::Undefined,
133 kind: MaybeUndefined::Undefined,
134 status: MaybeUndefined::Undefined,
135 content: MaybeUndefined::Undefined,
136 locations: MaybeUndefined::Undefined,
137 raw_input: MaybeUndefined::Undefined,
138 raw_output: MaybeUndefined::Undefined,
139 capabilities: MaybeUndefined::Undefined,
140 meta: MaybeUndefined::Undefined,
141 }
142 }
143
144 #[must_use]
146 pub fn name(mut self, name: impl IntoMaybeUndefined<String>) -> Self {
147 self.name = name.into_maybe_undefined();
148 self
149 }
150
151 #[must_use]
153 pub fn title(mut self, title: impl IntoMaybeUndefined<String>) -> Self {
154 self.title = title.into_maybe_undefined();
155 self
156 }
157
158 #[must_use]
161 pub fn kind(mut self, kind: impl IntoMaybeUndefined<ToolKind>) -> Self {
162 self.kind = kind.into_maybe_undefined();
163 self
164 }
165
166 #[must_use]
168 pub fn status(mut self, status: impl IntoMaybeUndefined<ToolCallStatus>) -> Self {
169 self.status = status.into_maybe_undefined();
170 self
171 }
172
173 #[must_use]
175 pub fn content(mut self, content: impl IntoMaybeUndefined<Vec<ToolCallContent>>) -> Self {
176 self.content = content.into_maybe_undefined();
177 self
178 }
179
180 #[must_use]
183 pub fn locations(mut self, locations: impl IntoMaybeUndefined<Vec<ToolCallLocation>>) -> Self {
184 self.locations = locations.into_maybe_undefined();
185 self
186 }
187
188 #[must_use]
190 pub fn raw_input(mut self, raw_input: impl IntoMaybeUndefined<serde_json::Value>) -> Self {
191 self.raw_input = raw_input.into_maybe_undefined();
192 self
193 }
194
195 #[must_use]
197 pub fn raw_output(mut self, raw_output: impl IntoMaybeUndefined<serde_json::Value>) -> Self {
198 self.raw_output = raw_output.into_maybe_undefined();
199 self
200 }
201
202 #[must_use]
204 pub fn capabilities(
205 mut self,
206 capabilities: impl IntoMaybeUndefined<ToolCallCapabilities>,
207 ) -> Self {
208 self.capabilities = capabilities.into_maybe_undefined();
209 self
210 }
211
212 #[must_use]
217 pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
218 self.meta = meta.into_maybe_undefined();
219 self
220 }
221
222 pub fn apply_update(&mut self, update: ToolCallUpdate) {
228 debug_assert_eq!(self.tool_call_id, update.tool_call_id);
229 if !update.name.is_undefined() {
230 self.name = update.name;
231 }
232 if !update.title.is_undefined() {
233 self.title = update.title;
234 }
235 if !update.kind.is_undefined() {
236 self.kind = update.kind;
237 }
238 if !update.status.is_undefined() {
239 self.status = update.status;
240 }
241 if !update.content.is_undefined() {
242 self.content = update.content;
243 }
244 if !update.locations.is_undefined() {
245 self.locations = update.locations;
246 }
247 if !update.raw_input.is_undefined() {
248 self.raw_input = update.raw_input;
249 }
250 if !update.raw_output.is_undefined() {
251 self.raw_output = update.raw_output;
252 }
253 if !update.capabilities.is_undefined() {
254 self.capabilities = update.capabilities;
255 }
256 apply_meta_update(&mut self.meta, update.meta);
257 }
258}
259
260#[serde_as]
267#[skip_serializing_none]
268#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
269#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
270#[serde(rename_all = "camelCase")]
271#[non_exhaustive]
272pub struct ToolCallCapabilities {
273 #[serde_as(deserialize_as = "DefaultOnError")]
278 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
279 #[serde(default)]
280 pub cancel: Option<ToolCallCancelCapabilities>,
281 #[serde_as(deserialize_as = "DefaultOnError")]
287 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
288 #[serde(default)]
289 #[serde(rename = "_meta")]
290 pub meta: Option<Meta>,
291}
292
293impl ToolCallCapabilities {
294 #[must_use]
296 pub fn new() -> Self {
297 Self::default()
298 }
299
300 #[must_use]
302 pub fn cancel(mut self, cancel: impl IntoOption<ToolCallCancelCapabilities>) -> Self {
303 self.cancel = cancel.into_option();
304 self
305 }
306
307 #[must_use]
313 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
314 self.meta = meta.into_option();
315 self
316 }
317}
318
319#[serde_as]
323#[skip_serializing_none]
324#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
325#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
326#[non_exhaustive]
327pub struct ToolCallCancelCapabilities {
328 #[serde_as(deserialize_as = "DefaultOnError")]
334 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
335 #[serde(default)]
336 #[serde(rename = "_meta")]
337 pub meta: Option<Meta>,
338}
339
340impl ToolCallCancelCapabilities {
341 #[must_use]
343 pub fn new() -> Self {
344 Self::default()
345 }
346
347 #[must_use]
353 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
354 self.meta = meta.into_option();
355 self
356 }
357}
358
359#[serde_as]
366#[skip_serializing_none]
367#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
368#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
369#[serde(rename_all = "camelCase")]
370#[non_exhaustive]
371pub struct ToolCallContentChunk {
372 pub tool_call_id: ToolCallId,
374 pub content: ToolCallContent,
376 #[serde_as(deserialize_as = "DefaultOnError")]
383 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
384 #[serde(default)]
385 #[serde(rename = "_meta")]
386 pub meta: Option<Meta>,
387}
388
389impl ToolCallContentChunk {
390 #[must_use]
392 pub fn new(tool_call_id: impl Into<ToolCallId>, content: impl Into<ToolCallContent>) -> Self {
393 Self {
394 tool_call_id: tool_call_id.into(),
395 content: content.into(),
396 meta: None,
397 }
398 }
399
400 #[must_use]
406 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
407 self.meta = meta.into_option();
408 self
409 }
410}
411
412#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
414#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
415#[serde(transparent)]
416#[from(forward)]
417#[non_exhaustive]
418pub struct ToolCallId(pub Arc<str>);
419
420impl ToolCallId {
421 #[must_use]
423 pub fn new(id: impl Into<Self>) -> Self {
424 id.into()
425 }
426}
427
428impl IntoOption<ToolCallId> for &str {
429 fn into_option(self) -> Option<ToolCallId> {
430 Some(ToolCallId::new(self))
431 }
432}
433
434#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
441#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
442#[serde(rename_all = "snake_case")]
443#[non_exhaustive]
444pub enum ToolKind {
445 Read,
447 Edit,
449 Delete,
451 Move,
453 Search,
455 Execute,
457 Think,
459 Fetch,
461 SwitchMode,
463 #[default]
465 Other,
466 #[serde(untagged)]
472 Unknown(String),
473}
474
475#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
481#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
482#[serde(rename_all = "snake_case")]
483#[non_exhaustive]
484pub enum ToolCallStatus {
485 #[default]
488 Pending,
489 InProgress,
491 Paused,
494 Completed,
496 Failed,
498 Cancelled,
500 #[serde(untagged)]
508 Other(String),
509}
510
511#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
518#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
519#[serde(tag = "type", rename_all = "snake_case")]
520#[non_exhaustive]
521pub enum ToolCallContent {
522 Content(Box<Content>),
524 Diff(Diff),
526 Terminal(Terminal),
528 Session(SessionReference),
530 #[serde(untagged)]
540 Other(OtherToolCallContent),
541}
542
543#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
545#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
546#[cfg_attr(feature = "schemars", schemars(inline))]
547#[cfg_attr(feature = "schemars", schemars(transform = other_tool_call_content_schema))]
548#[serde(rename_all = "camelCase")]
549#[non_exhaustive]
550pub struct OtherToolCallContent {
551 #[serde(rename = "type")]
557 pub type_: String,
558 #[serde(flatten)]
560 pub fields: BTreeMap<String, serde_json::Value>,
561}
562
563impl OtherToolCallContent {
564 #[must_use]
566 pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
567 fields.remove("type");
568 Self {
569 type_: type_.into(),
570 fields,
571 }
572 }
573}
574
575impl<'de> Deserialize<'de> for OtherToolCallContent {
576 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
577 where
578 D: serde::Deserializer<'de>,
579 {
580 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
581 let type_ = fields
582 .remove("type")
583 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
584 let serde_json::Value::String(type_) = type_ else {
585 return Err(serde::de::Error::custom("`type` must be a string"));
586 };
587
588 if is_known_tool_call_content_type(&type_) {
589 return Err(serde::de::Error::custom(format!(
590 "known tool call content `{type_}` did not match its schema"
591 )));
592 }
593
594 Ok(Self { type_, fields })
595 }
596}
597
598fn is_known_tool_call_content_type(type_: &str) -> bool {
599 KNOWN_TOOL_CALL_CONTENT_TYPES.contains(&type_)
600}
601
602const KNOWN_TOOL_CALL_CONTENT_TYPES: &[&str] = &["content", "diff", "terminal", "session"];
603
604#[cfg(feature = "schemars")]
605fn other_tool_call_content_schema(schema: &mut Schema) {
606 super::schema_util::reject_known_string_discriminators(
607 schema,
608 "type",
609 KNOWN_TOOL_CALL_CONTENT_TYPES,
610 );
611}
612
613impl<T: Into<ContentBlock>> From<T> for ToolCallContent {
614 fn from(content: T) -> Self {
615 ToolCallContent::Content(Box::new(Content::new(content)))
616 }
617}
618
619impl From<Diff> for ToolCallContent {
620 fn from(diff: Diff) -> Self {
621 ToolCallContent::Diff(diff)
622 }
623}
624
625impl From<Terminal> for ToolCallContent {
626 fn from(terminal: Terminal) -> Self {
627 ToolCallContent::Terminal(terminal)
628 }
629}
630
631#[serde_as]
639#[skip_serializing_none]
640#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
641#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
642#[serde(rename_all = "camelCase")]
643#[non_exhaustive]
644pub struct SessionReference {
645 pub session_id: SessionId,
647 #[serde_as(deserialize_as = "DefaultOnError")]
653 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
654 #[serde(default)]
655 #[serde(rename = "_meta")]
656 pub meta: Option<Meta>,
657}
658
659impl SessionReference {
660 #[must_use]
662 pub fn new(session_id: impl Into<SessionId>) -> Self {
663 Self {
664 session_id: session_id.into(),
665 meta: None,
666 }
667 }
668
669 #[must_use]
672 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
673 self.meta = meta.into_option();
674 self
675 }
676}
677
678impl From<SessionReference> for ToolCallContent {
679 fn from(session: SessionReference) -> Self {
680 ToolCallContent::Session(session)
681 }
682}
683
684#[serde_as]
686#[skip_serializing_none]
687#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
688#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
689#[serde(rename_all = "camelCase")]
690#[non_exhaustive]
691pub struct Content {
692 pub content: ContentBlock,
694 #[serde_as(deserialize_as = "DefaultOnError")]
700 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
701 #[serde(default)]
702 #[serde(rename = "_meta")]
703 pub meta: Option<Meta>,
704}
705
706impl Content {
707 #[must_use]
709 pub fn new(content: impl Into<ContentBlock>) -> Self {
710 Self {
711 content: content.into(),
712 meta: None,
713 }
714 }
715
716 #[must_use]
722 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
723 self.meta = meta.into_option();
724 self
725 }
726}
727
728#[serde_as]
737#[skip_serializing_none]
738#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
739#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
740#[serde(rename_all = "camelCase")]
741#[non_exhaustive]
742pub struct Diff {
743 #[serde_as(deserialize_as = "VecSkipError<_>")]
747 #[cfg_attr(feature = "schemars", schemars(length(min = 1), extend("x-deserialize-skip-invalid-items" = true)))]
748 pub changes: Vec<DiffChange>,
749 #[serde_as(deserialize_as = "DefaultOnError")]
754 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
755 #[serde(default)]
756 pub patch: Option<DiffPatch>,
757 #[serde_as(deserialize_as = "DefaultOnError")]
763 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
764 #[serde(default)]
765 #[serde(rename = "_meta")]
766 pub meta: Option<Meta>,
767}
768
769impl Diff {
770 #[must_use]
772 pub fn new(changes: Vec<DiffChange>) -> Self {
773 Self {
774 changes,
775 patch: None,
776 meta: None,
777 }
778 }
779
780 #[must_use]
782 pub fn patch(text: impl Into<String>, changes: Vec<DiffChange>) -> Self {
783 Self::new(changes).with_patch(DiffPatch::new(text))
784 }
785
786 #[must_use]
788 pub fn with_patch(mut self, patch: impl IntoOption<DiffPatch>) -> Self {
789 self.patch = patch.into_option();
790 self
791 }
792
793 #[must_use]
799 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
800 self.meta = meta.into_option();
801 self
802 }
803}
804
805#[serde_as]
807#[skip_serializing_none]
808#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
809#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
810#[serde(rename_all = "camelCase")]
811#[non_exhaustive]
812pub struct DiffPatch {
813 pub format: DiffPatchFormat,
815 pub text: String,
817 #[serde_as(deserialize_as = "DefaultOnError")]
823 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
824 #[serde(default)]
825 #[serde(rename = "_meta")]
826 pub meta: Option<Meta>,
827}
828
829impl DiffPatch {
830 #[must_use]
832 pub fn new(text: impl Into<String>) -> Self {
833 Self {
834 format: DiffPatchFormat::GitPatch,
835 text: text.into(),
836 meta: None,
837 }
838 }
839
840 #[must_use]
846 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
847 self.meta = meta.into_option();
848 self
849 }
850}
851
852#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
854#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
855#[serde(rename_all = "snake_case")]
856#[non_exhaustive]
857pub enum DiffPatchFormat {
858 GitPatch,
870 #[serde(untagged)]
876 Other(String),
877}
878
879#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
881#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
882#[serde(rename_all = "snake_case")]
883#[non_exhaustive]
884pub enum DiffFileType {
885 Text,
887 Binary,
889 Directory,
891 Symlink,
893 #[serde(untagged)]
899 Other(String),
900}
901
902#[serde_as]
907#[skip_serializing_none]
908#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
909#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
910#[serde(rename_all = "camelCase")]
911#[non_exhaustive]
912pub struct DiffChange {
913 #[serde_as(deserialize_as = "DefaultOnError")]
917 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
918 #[serde(default)]
919 pub file_type: Option<DiffFileType>,
920 #[serde_as(deserialize_as = "DefaultOnError")]
924 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
925 #[serde(default)]
926 pub mime_type: Option<MediaType>,
927 #[serde(flatten)]
929 pub operation: DiffChangeOperation,
930 #[serde_as(deserialize_as = "DefaultOnError")]
936 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
937 #[serde(default)]
938 #[serde(rename = "_meta")]
939 pub meta: Option<Meta>,
940}
941
942impl DiffChange {
943 #[must_use]
945 pub fn new(operation: DiffChangeOperation) -> Self {
946 Self {
947 file_type: None,
948 mime_type: None,
949 operation,
950 meta: None,
951 }
952 }
953
954 #[must_use]
956 pub fn add(path: impl Into<AbsolutePath>) -> Self {
957 Self::new(DiffChangeOperation::Add(DiffPathChange::new(path)))
958 }
959
960 #[must_use]
962 pub fn delete(path: impl Into<AbsolutePath>) -> Self {
963 Self::new(DiffChangeOperation::Delete(DiffPathChange::new(path)))
964 }
965
966 #[must_use]
968 pub fn modify(path: impl Into<AbsolutePath>) -> Self {
969 Self::new(DiffChangeOperation::Modify(DiffPathChange::new(path)))
970 }
971
972 #[must_use]
974 pub fn move_file(old_path: impl Into<AbsolutePath>, path: impl Into<AbsolutePath>) -> Self {
975 Self::new(DiffChangeOperation::Move(DiffPathPairChange::new(
976 old_path, path,
977 )))
978 }
979
980 #[must_use]
982 pub fn copy(old_path: impl Into<AbsolutePath>, path: impl Into<AbsolutePath>) -> Self {
983 Self::new(DiffChangeOperation::Copy(DiffPathPairChange::new(
984 old_path, path,
985 )))
986 }
987
988 #[must_use]
992 pub fn file_type(mut self, file_type: impl IntoOption<DiffFileType>) -> Self {
993 self.file_type = file_type.into_option();
994 self
995 }
996
997 #[must_use]
1001 pub fn mime_type(mut self, mime_type: impl IntoOption<MediaType>) -> Self {
1002 self.mime_type = mime_type.into_option();
1003 self
1004 }
1005
1006 #[must_use]
1012 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1013 self.meta = meta.into_option();
1014 self
1015 }
1016}
1017
1018#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1020#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1021#[serde(tag = "operation", rename_all = "snake_case")]
1022#[non_exhaustive]
1023pub enum DiffChangeOperation {
1024 Add(DiffPathChange),
1026 Delete(DiffPathChange),
1028 Modify(DiffPathChange),
1030 Move(DiffPathPairChange),
1032 Copy(DiffPathPairChange),
1034 #[serde(untagged)]
1040 Other(OtherDiffChange),
1041}
1042
1043#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1045#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1046#[serde(rename_all = "camelCase")]
1047#[non_exhaustive]
1048pub struct DiffPathChange {
1049 pub path: AbsolutePath,
1051}
1052
1053impl DiffPathChange {
1054 #[must_use]
1056 pub fn new(path: impl Into<AbsolutePath>) -> Self {
1057 Self { path: path.into() }
1058 }
1059}
1060
1061#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1063#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1064#[serde(rename_all = "camelCase")]
1065#[non_exhaustive]
1066pub struct DiffPathPairChange {
1067 pub old_path: AbsolutePath,
1069 pub path: AbsolutePath,
1071}
1072
1073impl DiffPathPairChange {
1074 #[must_use]
1076 pub fn new(old_path: impl Into<AbsolutePath>, path: impl Into<AbsolutePath>) -> Self {
1077 Self {
1078 old_path: old_path.into(),
1079 path: path.into(),
1080 }
1081 }
1082}
1083
1084#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1086#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1087#[cfg_attr(feature = "schemars", schemars(inline))]
1088#[cfg_attr(feature = "schemars", schemars(transform = other_diff_change_schema))]
1089#[serde(rename_all = "camelCase")]
1090#[non_exhaustive]
1091pub struct OtherDiffChange {
1092 pub operation: String,
1098 #[serde(flatten)]
1100 pub fields: BTreeMap<String, serde_json::Value>,
1101}
1102
1103impl OtherDiffChange {
1104 #[must_use]
1106 pub fn new(
1107 operation: impl Into<String>,
1108 mut fields: BTreeMap<String, serde_json::Value>,
1109 ) -> Self {
1110 fields.remove("operation");
1111 fields.remove("fileType");
1112 fields.remove("mimeType");
1113 fields.remove("_meta");
1114 Self {
1115 operation: operation.into(),
1116 fields,
1117 }
1118 }
1119}
1120
1121impl<'de> Deserialize<'de> for OtherDiffChange {
1122 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1123 where
1124 D: serde::Deserializer<'de>,
1125 {
1126 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
1127 let operation = fields
1128 .remove("operation")
1129 .ok_or_else(|| serde::de::Error::missing_field("operation"))?;
1130 let serde_json::Value::String(operation) = operation else {
1131 return Err(serde::de::Error::custom("`operation` must be a string"));
1132 };
1133
1134 if is_known_diff_change_operation(&operation) {
1135 return Err(serde::de::Error::custom(format!(
1136 "known diff change operation `{operation}` did not match its schema"
1137 )));
1138 }
1139 fields.remove("fileType");
1140 fields.remove("mimeType");
1141 fields.remove("_meta");
1142
1143 Ok(Self { operation, fields })
1144 }
1145}
1146
1147fn is_known_diff_change_operation(operation: &str) -> bool {
1148 matches!(operation, "add" | "delete" | "modify" | "move" | "copy")
1149}
1150
1151#[cfg(feature = "schemars")]
1152fn other_diff_change_schema(schema: &mut Schema) {
1153 super::schema_util::reject_known_string_discriminators(
1154 schema,
1155 "operation",
1156 &["add", "delete", "modify", "move", "copy"],
1157 );
1158}
1159
1160#[serde_as]
1167#[skip_serializing_none]
1168#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1169#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1170#[serde(rename_all = "camelCase")]
1171#[non_exhaustive]
1172pub struct ToolCallLocation {
1173 pub path: AbsolutePath,
1175 #[serde_as(deserialize_as = "DefaultOnError")]
1178 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1179 #[serde(default)]
1180 pub line: Option<std::num::NonZeroU32>,
1181 #[serde_as(deserialize_as = "DefaultOnError")]
1187 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1188 #[serde(default)]
1189 #[serde(rename = "_meta")]
1190 pub meta: Option<Meta>,
1191}
1192
1193impl ToolCallLocation {
1194 #[must_use]
1196 pub fn new(path: impl Into<AbsolutePath>) -> Self {
1197 Self {
1198 path: path.into(),
1199 line: None,
1200 meta: None,
1201 }
1202 }
1203
1204 #[must_use]
1209 pub fn line(mut self, line: impl IntoOption<u32>) -> Self {
1210 self.line = line.into_option().and_then(std::num::NonZeroU32::new);
1211 self
1212 }
1213
1214 #[must_use]
1220 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1221 self.meta = meta.into_option();
1222 self
1223 }
1224}
1225
1226#[cfg(test)]
1227mod tests {
1228
1229 #[test]
1230 fn session_reference_tool_call_content_round_trips() {
1231 use serde_json::json;
1232 let content = ToolCallContent::from(SessionReference::new("sess_child_1"));
1233 let value = serde_json::to_value(&content).unwrap();
1234 assert_eq!(
1235 value,
1236 json!({ "type": "session", "sessionId": "sess_child_1" })
1237 );
1238 assert_eq!(
1239 serde_json::from_value::<ToolCallContent>(value).unwrap(),
1240 content
1241 );
1242 assert!(serde_json::from_value::<ToolCallContent>(json!({ "type": "session" })).is_err());
1244 }
1245
1246 #[test]
1247 fn location_line_is_one_based() {
1248 let location: ToolCallLocation =
1249 serde_json::from_value(serde_json::json!({ "path": "/a.rs", "line": 0 })).unwrap();
1250 assert_eq!(location.line, None);
1251 let location: ToolCallLocation =
1252 serde_json::from_value(serde_json::json!({ "path": "/a.rs", "line": 3 })).unwrap();
1253 assert_eq!(location.line.map(std::num::NonZeroU32::get), Some(3));
1254 assert_eq!(ToolCallLocation::new("/a.rs").line(0).line, None);
1255 }
1256
1257 #[test]
1258 fn toolcall_capabilities_patch_and_tolerate_malformed_values() {
1259 use serde_json::json;
1260 let update = ToolCallUpdate::new("call_012")
1261 .capabilities(ToolCallCapabilities::new().cancel(ToolCallCancelCapabilities::new()));
1262 assert_eq!(
1263 serde_json::to_value(&update).unwrap(),
1264 json!({ "toolCallId": "call_012", "capabilities": { "cancel": {} } })
1265 );
1266
1267 let mut stored = update;
1268 stored.apply_update(ToolCallUpdate::new("call_012"));
1269 assert!(stored.capabilities.is_value());
1270 stored.apply_update(ToolCallUpdate::new("call_012").capabilities(MaybeUndefined::Null));
1271 assert!(stored.capabilities.is_null());
1272
1273 for bad in [json!("yes"), json!(1)] {
1274 let parsed: ToolCallUpdate =
1275 serde_json::from_value(json!({ "toolCallId": "call_012", "capabilities": bad }))
1276 .unwrap();
1277 assert!(parsed.capabilities.is_undefined());
1278 }
1279 let parsed: ToolCallCapabilities =
1280 serde_json::from_value(json!({ "cancel": "yes" })).unwrap();
1281 assert_eq!(parsed.cancel, None);
1282 }
1283
1284 #[test]
1285 fn paused_is_a_known_tool_call_status() {
1286 use serde_json::json;
1287 assert_eq!(
1288 serde_json::to_value(ToolCallStatus::Paused).unwrap(),
1289 json!("paused")
1290 );
1291 assert_eq!(
1292 serde_json::from_value::<ToolCallStatus>(json!("paused")).unwrap(),
1293 ToolCallStatus::Paused
1294 );
1295 }
1296
1297 use super::*;
1298 use crate::MaybeUndefined;
1299 use serde_json::{from_value, json, to_value};
1300
1301 #[test]
1302 fn tool_call_serializes_as_upsert() {
1303 let tool_call = ToolCallUpdate::new("tc_1")
1304 .title("Reading configuration")
1305 .status(ToolCallStatus::InProgress)
1306 .raw_input(serde_json::json!({"path": "settings.json"}));
1307
1308 assert_eq!(
1309 serde_json::to_value(tool_call).unwrap(),
1310 serde_json::json!({
1311 "toolCallId": "tc_1",
1312 "title": "Reading configuration",
1313 "status": "in_progress",
1314 "rawInput": {
1315 "path": "settings.json"
1316 }
1317 })
1318 );
1319 }
1320
1321 #[test]
1322 fn tool_call_update_distinguishes_omitted_null_and_value() {
1323 let tool_call = ToolCallUpdate::new("tc_1")
1324 .status(ToolCallStatus::Completed)
1325 .content(None::<Vec<ToolCallContent>>);
1326
1327 assert_eq!(
1328 serde_json::to_value(tool_call).unwrap(),
1329 serde_json::json!({
1330 "toolCallId": "tc_1",
1331 "status": "completed",
1332 "content": null
1333 })
1334 );
1335
1336 let deserialized: ToolCallUpdate = serde_json::from_value(serde_json::json!({
1337 "toolCallId": "tc_1",
1338 "status": null,
1339 "locations": []
1340 }))
1341 .unwrap();
1342 assert_eq!(deserialized.title, MaybeUndefined::Undefined);
1343 assert_eq!(deserialized.status, MaybeUndefined::Null);
1344 assert_eq!(deserialized.locations, MaybeUndefined::Value(Vec::new()));
1345 }
1346
1347 #[test]
1348 fn tool_call_name_patch_distinguishes_omitted_null_and_value() {
1349 let named = ToolCallUpdate::new("tc_1").name("read_file");
1350 assert_eq!(
1351 serde_json::to_value(named).unwrap(),
1352 serde_json::json!({
1353 "toolCallId": "tc_1",
1354 "name": "read_file"
1355 })
1356 );
1357
1358 let omitted = ToolCallUpdate::new("tc_1");
1359 assert_eq!(omitted.name, MaybeUndefined::Undefined);
1360
1361 let from_null: ToolCallUpdate = serde_json::from_value(serde_json::json!({
1362 "toolCallId": "tc_1",
1363 "name": null
1364 }))
1365 .unwrap();
1366 assert_eq!(from_null.name, MaybeUndefined::Null);
1367
1368 let mut stored = ToolCallUpdate::new("tc_1").name("read_file");
1369 stored.apply_update(ToolCallUpdate::new("tc_1"));
1370 assert_eq!(stored.name, MaybeUndefined::Value("read_file".to_string()));
1371
1372 stored.apply_update(ToolCallUpdate::new("tc_1").name(None::<String>));
1373 assert_eq!(stored.name, MaybeUndefined::Null);
1374
1375 stored.apply_update(ToolCallUpdate::new("tc_1").name("write_file"));
1376 assert_eq!(stored.name, MaybeUndefined::Value("write_file".to_string()));
1377 }
1378
1379 #[test]
1380 fn tool_call_update_distinguishes_meta_omitted_null_and_value() {
1381 let mut meta = Meta::new();
1382 meta.insert("source".to_string(), serde_json::json!("tool-call"));
1383
1384 assert_eq!(
1385 serde_json::to_value(ToolCallUpdate::new("tc_1").meta(meta.clone())).unwrap(),
1386 serde_json::json!({
1387 "toolCallId": "tc_1",
1388 "_meta": {
1389 "source": "tool-call"
1390 }
1391 })
1392 );
1393
1394 assert_eq!(
1395 serde_json::to_value(ToolCallUpdate::new("tc_1").meta(None::<Meta>)).unwrap(),
1396 serde_json::json!({
1397 "toolCallId": "tc_1",
1398 "_meta": null
1399 })
1400 );
1401
1402 let deserialized: ToolCallUpdate = serde_json::from_value(serde_json::json!({
1403 "toolCallId": "tc_1",
1404 "_meta": null
1405 }))
1406 .unwrap();
1407 assert_eq!(deserialized.meta, MaybeUndefined::Null);
1408
1409 let patch = ToolCallUpdate::new("tc_1");
1410 assert_eq!(patch.meta, MaybeUndefined::Undefined);
1411
1412 let mut stored = ToolCallUpdate::new("tc_1").meta(meta);
1413 stored.apply_update(ToolCallUpdate::new("tc_1").meta(None::<Meta>));
1414 assert_eq!(stored.meta, MaybeUndefined::Null);
1415 }
1416
1417 #[test]
1418 fn tool_call_update_patches_meta_by_top_level_key() {
1419 let mut stored: ToolCallUpdate = from_value(json!({
1420 "toolCallId": "tc_1",
1421 "_meta": {"zed.dev/a": 1, "acme.dev/b": {"x": 1}}
1422 }))
1423 .unwrap();
1424
1425 stored.apply_update(
1427 from_value(json!({"toolCallId": "tc_1", "_meta": {"proxy.dev/c": true}})).unwrap(),
1428 );
1429 stored.apply_update(
1430 from_value(json!({
1431 "toolCallId": "tc_1",
1432 "_meta": {"zed.dev/a": null, "acme.dev/b": {"y": 2}}
1433 }))
1434 .unwrap(),
1435 );
1436
1437 assert_eq!(
1438 to_value(&stored).unwrap(),
1439 json!({
1440 "toolCallId": "tc_1",
1441 "_meta": {"acme.dev/b": {"y": 2}, "proxy.dev/c": true}
1442 })
1443 );
1444 }
1445
1446 #[test]
1447 fn tool_call_wire_patches_preserve_omitted_fields_and_replace_values() {
1448 let initial = json!({
1449 "toolCallId": "tc_1",
1450 "_meta": {"source": "replay", "opaque": {"sequence": 1}}
1451 });
1452 let mut stored: ToolCallUpdate = from_value(initial.clone()).unwrap();
1453 assert_eq!(to_value(&stored).unwrap(), initial);
1455
1456 let populated = json!({
1457 "toolCallId": "tc_1",
1458 "name": "read_file",
1459 "title": "Reading configuration",
1460 "kind": "read",
1461 "status": "in_progress",
1462 "content": [{
1463 "type": "content",
1464 "content": {
1465 "type": "text",
1466 "text": "old",
1467 "_meta": {"source": "tool"}
1468 }
1469 }],
1470 "locations": [{"path": "/workspace/config.json", "line": 3}],
1471 "rawInput": {"path": "/workspace/config.json"},
1472 "rawOutput": {"text": "old"}
1473 });
1474 stored.apply_update(from_value(populated.clone()).unwrap());
1475 let mut expected = populated;
1476 expected["_meta"] = initial["_meta"].clone();
1477 assert_eq!(to_value(&stored).unwrap(), expected);
1478
1479 for (field, empty) in [
1480 ("content", json!([])),
1481 ("locations", json!([])),
1482 ("rawInput", json!({})),
1483 ("rawOutput", json!({})),
1484 ] {
1485 let original = expected[field].clone();
1486 for replacement in [empty, json!(null), original] {
1489 stored.apply_update(
1490 from_value(json!({"toolCallId": "tc_1", (field): replacement})).unwrap(),
1491 );
1492 expected[field] = replacement;
1493 assert_eq!(to_value(&stored).unwrap(), expected, "patching {field}");
1494
1495 stored.apply_update(from_value(json!({"toolCallId": "tc_1"})).unwrap());
1496 assert_eq!(to_value(&stored).unwrap(), expected, "omitting {field}");
1497 }
1498 }
1499 }
1500
1501 #[test]
1502 fn tool_call_wire_patches_preserve_unknown_statuses() {
1503 for status in ["deferred", "_awaiting_review"] {
1504 let mut stored = ToolCallUpdate::new("tc_1").status(ToolCallStatus::InProgress);
1505 stored
1506 .apply_update(from_value(json!({"toolCallId": "tc_1", "status": status})).unwrap());
1507 let expected_status = MaybeUndefined::Value(ToolCallStatus::Other(status.to_owned()));
1508 assert_eq!(stored.status, expected_status);
1509
1510 stored.apply_update(
1513 from_value(json!({"toolCallId": "tc_1", "title": "Still waiting"})).unwrap(),
1514 );
1515 assert_eq!(stored.status, expected_status);
1516 assert_eq!(
1517 to_value(&stored).unwrap(),
1518 json!({"toolCallId": "tc_1", "title": "Still waiting", "status": status})
1519 );
1520 }
1521 }
1522
1523 #[test]
1524 fn tool_call_update_skips_malformed_list_items() {
1525 let deserialized: ToolCallUpdate = serde_json::from_value(serde_json::json!({
1526 "toolCallId": "tc_1",
1527 "content": [
1528 {
1529 "type": "content",
1530 "content": {
1531 "type": "text",
1532 "text": "ok"
1533 }
1534 },
1535 {
1536 "type": "diff",
1537 "path": "/bad"
1538 }
1539 ],
1540 "locations": [
1541 {
1542 "path": "/ok",
1543 "line": 3
1544 },
1545 {
1546 "line": 4
1547 }
1548 ]
1549 }))
1550 .unwrap();
1551
1552 let MaybeUndefined::Value(content) = deserialized.content else {
1553 panic!("content should deserialize to a value");
1554 };
1555 assert_eq!(content.len(), 1);
1556
1557 let MaybeUndefined::Value(locations) = deserialized.locations else {
1558 panic!("locations should deserialize to a value");
1559 };
1560 assert_eq!(locations.len(), 1);
1561 }
1562
1563 #[test]
1564 fn tool_call_content_chunk_serializes_single_content_item() {
1565 let chunk = ToolCallContentChunk::new(
1566 "tc_1",
1567 ContentBlock::Text(crate::v2::TextContent::new("partial output")),
1568 );
1569
1570 assert_eq!(
1571 serde_json::to_value(chunk).unwrap(),
1572 serde_json::json!({
1573 "toolCallId": "tc_1",
1574 "content": {
1575 "type": "content",
1576 "content": {
1577 "type": "text",
1578 "text": "partial output"
1579 }
1580 }
1581 })
1582 );
1583 }
1584
1585 #[test]
1586 fn terminal_content_serializes_as_display_reference() {
1587 let terminal = ToolCallContent::from(Terminal::new("term_1"));
1588
1589 assert_eq!(
1590 serde_json::to_value(terminal).unwrap(),
1591 serde_json::json!({
1592 "type": "terminal",
1593 "terminalId": "term_1"
1594 })
1595 );
1596 }
1597
1598 #[test]
1599 fn diff_patch_serializes_git_patch_with_structured_changes() {
1600 let patch_text = "diff --git /repo/config.json /repo/config.json\n--- /repo/config.json\n+++ /repo/config.json\n@@ -1 +1 @@\n-old\n+new\n";
1601 let diff = ToolCallContent::Diff(Diff::patch(
1602 patch_text,
1603 vec![
1604 DiffChange::modify("/repo/config.json")
1605 .file_type(DiffFileType::Text)
1606 .mime_type("application/json"),
1607 ],
1608 ));
1609
1610 assert_eq!(
1611 serde_json::to_value(diff).unwrap(),
1612 serde_json::json!({
1613 "type": "diff",
1614 "changes": [
1615 {
1616 "operation": "modify",
1617 "path": "/repo/config.json",
1618 "fileType": "text",
1619 "mimeType": "application/json"
1620 }
1621 ],
1622 "patch": {
1623 "format": "git_patch",
1624 "text": patch_text
1625 }
1626 })
1627 );
1628 }
1629
1630 #[test]
1631 fn diff_patch_requires_text() {
1632 let result = serde_json::from_value::<DiffPatch>(serde_json::json!({
1633 "format": "git_patch",
1634 "diff": "diff --git /repo/config.json /repo/config.json\n"
1635 }));
1636
1637 assert!(result.is_err());
1638 }
1639
1640 #[test]
1641 fn diff_serializes_binary_modify_without_patch_text() {
1642 let diff = ToolCallContent::Diff(Diff::new(vec![
1643 DiffChange::modify("/repo/assets/logo.png")
1644 .file_type(DiffFileType::Binary)
1645 .mime_type("image/png"),
1646 ]));
1647
1648 assert_eq!(
1649 serde_json::to_value(diff).unwrap(),
1650 serde_json::json!({
1651 "type": "diff",
1652 "changes": [
1653 {
1654 "operation": "modify",
1655 "path": "/repo/assets/logo.png",
1656 "fileType": "binary",
1657 "mimeType": "image/png"
1658 }
1659 ]
1660 })
1661 );
1662 }
1663
1664 #[test]
1665 fn diff_move_serializes_shared_fields_with_operation_payload() {
1666 let diff = ToolCallContent::Diff(Diff::new(vec![
1667 DiffChange::move_file("/repo/src/old.rs", "/repo/src/new.rs")
1668 .file_type(DiffFileType::Text)
1669 .mime_type("text/rust"),
1670 ]));
1671
1672 assert_eq!(
1673 serde_json::to_value(diff).unwrap(),
1674 serde_json::json!({
1675 "type": "diff",
1676 "changes": [
1677 {
1678 "operation": "move",
1679 "oldPath": "/repo/src/old.rs",
1680 "path": "/repo/src/new.rs",
1681 "fileType": "text",
1682 "mimeType": "text/rust"
1683 }
1684 ]
1685 })
1686 );
1687 }
1688
1689 #[test]
1690 fn diff_changes_skip_malformed_list_items() {
1691 let patch_text = "diff --git /ok /ok\ndeleted file mode 100644\n--- /ok\n+++ /dev/null\n@@ -1 +0,0 @@\n-old\n";
1692 let content: ToolCallContent = serde_json::from_value(serde_json::json!({
1693 "type": "diff",
1694 "changes": [
1695 {
1696 "operation": "modify"
1697 },
1698 {
1699 "operation": "delete",
1700 "path": "/ok"
1701 }
1702 ],
1703 "patch": {
1704 "format": "git_patch",
1705 "text": patch_text
1706 }
1707 }))
1708 .unwrap();
1709
1710 let ToolCallContent::Diff(diff) = content else {
1711 panic!("expected diff content");
1712 };
1713 assert_eq!(diff.changes, vec![DiffChange::delete("/ok")]);
1714 assert_eq!(diff.patch, Some(DiffPatch::new(patch_text)));
1715 }
1716
1717 #[cfg(feature = "schemars")]
1718 #[test]
1719 fn diff_schema_requires_at_least_one_change() {
1720 let schema = serde_json::to_value(schemars::schema_for!(Diff)).unwrap();
1721 assert_eq!(schema["properties"]["changes"]["minItems"], 1);
1722 }
1723
1724 #[test]
1725 fn diff_with_no_changes_still_deserializes() {
1726 let diff: Diff = serde_json::from_value(serde_json::json!({ "changes": [] })).unwrap();
1727 assert_eq!(diff.changes, Vec::<DiffChange>::new());
1728 }
1729
1730 #[test]
1731 fn tool_kind_preserves_unknown_variant() {
1732 let kind: ToolKind = serde_json::from_str("\"review\"").unwrap();
1733 assert_eq!(kind, ToolKind::Unknown("review".to_string()));
1734 assert_eq!(serde_json::to_value(&kind).unwrap(), "review");
1735 }
1736
1737 #[test]
1738 fn tool_call_status_preserves_unknown_variant() {
1739 let status: ToolCallStatus = serde_json::from_str("\"deferred\"").unwrap();
1740 assert_eq!(status, ToolCallStatus::Other("deferred".to_string()));
1741 assert_eq!(serde_json::to_value(&status).unwrap(), "deferred");
1742 }
1743
1744 #[test]
1745 fn tool_call_status_recognizes_cancelled_variant() {
1746 let status: ToolCallStatus = serde_json::from_str("\"cancelled\"").unwrap();
1747 assert_eq!(status, ToolCallStatus::Cancelled);
1748 assert_eq!(serde_json::to_value(&status).unwrap(), "cancelled");
1749 }
1750
1751 #[test]
1752 fn tool_call_content_preserves_unknown_variant() {
1753 let content: ToolCallContent = serde_json::from_value(serde_json::json!({
1754 "type": "_chart",
1755 "title": "Tests",
1756 "data": [1, 2, 3]
1757 }))
1758 .unwrap();
1759
1760 let ToolCallContent::Other(unknown) = content else {
1761 panic!("expected unknown tool call content");
1762 };
1763
1764 assert_eq!(unknown.type_, "_chart");
1765 assert_eq!(
1766 unknown.fields.get("title"),
1767 Some(&serde_json::json!("Tests"))
1768 );
1769 assert_eq!(
1770 serde_json::to_value(ToolCallContent::Other(unknown)).unwrap(),
1771 serde_json::json!({
1772 "type": "_chart",
1773 "title": "Tests",
1774 "data": [1, 2, 3]
1775 })
1776 );
1777 }
1778
1779 #[test]
1780 fn tool_call_content_does_not_hide_malformed_known_variant() {
1781 assert!(
1782 serde_json::from_value::<ToolCallContent>(serde_json::json!({
1783 "type": "diff"
1784 }))
1785 .is_err()
1786 );
1787 assert!(
1788 serde_json::from_value::<ToolCallContent>(serde_json::json!({
1789 "type": "terminal"
1790 }))
1791 .is_err()
1792 );
1793 }
1794}