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