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