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
15#[cfg(feature = "unstable_subagents")]
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")]
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 #[cfg(feature = "unstable_subagents")]
534 Session(SessionReference),
535 #[serde(untagged)]
545 Other(OtherToolCallContent),
546}
547
548#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
550#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
551#[cfg_attr(feature = "schemars", schemars(inline))]
552#[cfg_attr(feature = "schemars", schemars(transform = other_tool_call_content_schema))]
553#[serde(rename_all = "camelCase")]
554#[non_exhaustive]
555pub struct OtherToolCallContent {
556 #[serde(rename = "type")]
562 pub type_: String,
563 #[serde(flatten)]
565 pub fields: BTreeMap<String, serde_json::Value>,
566}
567
568impl OtherToolCallContent {
569 #[must_use]
571 pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
572 fields.remove("type");
573 Self {
574 type_: type_.into(),
575 fields,
576 }
577 }
578}
579
580impl<'de> Deserialize<'de> for OtherToolCallContent {
581 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
582 where
583 D: serde::Deserializer<'de>,
584 {
585 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
586 let type_ = fields
587 .remove("type")
588 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
589 let serde_json::Value::String(type_) = type_ else {
590 return Err(serde::de::Error::custom("`type` must be a string"));
591 };
592
593 if is_known_tool_call_content_type(&type_) {
594 return Err(serde::de::Error::custom(format!(
595 "known tool call content `{type_}` did not match its schema"
596 )));
597 }
598
599 Ok(Self { type_, fields })
600 }
601}
602
603fn is_known_tool_call_content_type(type_: &str) -> bool {
604 KNOWN_TOOL_CALL_CONTENT_TYPES.contains(&type_)
605}
606
607const KNOWN_TOOL_CALL_CONTENT_TYPES: &[&str] = &[
608 "content",
609 "diff",
610 "terminal",
611 #[cfg(feature = "unstable_subagents")]
612 "session",
613];
614
615#[cfg(feature = "schemars")]
616fn other_tool_call_content_schema(schema: &mut Schema) {
617 super::schema_util::reject_known_string_discriminators(
618 schema,
619 "type",
620 KNOWN_TOOL_CALL_CONTENT_TYPES,
621 );
622}
623
624impl<T: Into<ContentBlock>> From<T> for ToolCallContent {
625 fn from(content: T) -> Self {
626 ToolCallContent::Content(Box::new(Content::new(content)))
627 }
628}
629
630impl From<Diff> for ToolCallContent {
631 fn from(diff: Diff) -> Self {
632 ToolCallContent::Diff(diff)
633 }
634}
635
636impl From<Terminal> for ToolCallContent {
637 fn from(terminal: Terminal) -> Self {
638 ToolCallContent::Terminal(terminal)
639 }
640}
641
642#[cfg(feature = "unstable_subagents")]
654#[serde_as]
655#[skip_serializing_none]
656#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
657#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
658#[serde(rename_all = "camelCase")]
659#[non_exhaustive]
660pub struct SessionReference {
661 pub session_id: SessionId,
663 #[serde_as(deserialize_as = "DefaultOnError")]
669 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
670 #[serde(default)]
671 #[serde(rename = "_meta")]
672 pub meta: Option<Meta>,
673}
674
675#[cfg(feature = "unstable_subagents")]
676impl SessionReference {
677 #[must_use]
679 pub fn new(session_id: impl Into<SessionId>) -> Self {
680 Self {
681 session_id: session_id.into(),
682 meta: None,
683 }
684 }
685
686 #[must_use]
689 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
690 self.meta = meta.into_option();
691 self
692 }
693}
694
695#[cfg(feature = "unstable_subagents")]
696impl From<SessionReference> for ToolCallContent {
697 fn from(session: SessionReference) -> Self {
698 ToolCallContent::Session(session)
699 }
700}
701
702#[serde_as]
704#[skip_serializing_none]
705#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
706#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
707#[serde(rename_all = "camelCase")]
708#[non_exhaustive]
709pub struct Content {
710 pub content: ContentBlock,
712 #[serde_as(deserialize_as = "DefaultOnError")]
718 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
719 #[serde(default)]
720 #[serde(rename = "_meta")]
721 pub meta: Option<Meta>,
722}
723
724impl Content {
725 #[must_use]
727 pub fn new(content: impl Into<ContentBlock>) -> Self {
728 Self {
729 content: content.into(),
730 meta: None,
731 }
732 }
733
734 #[must_use]
740 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
741 self.meta = meta.into_option();
742 self
743 }
744}
745
746#[serde_as]
755#[skip_serializing_none]
756#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
757#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
758#[serde(rename_all = "camelCase")]
759#[non_exhaustive]
760pub struct Diff {
761 #[serde_as(deserialize_as = "VecSkipError<_>")]
765 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
766 pub changes: Vec<DiffChange>,
767 #[serde_as(deserialize_as = "DefaultOnError")]
772 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
773 #[serde(default)]
774 pub patch: Option<DiffPatch>,
775 #[serde_as(deserialize_as = "DefaultOnError")]
781 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
782 #[serde(default)]
783 #[serde(rename = "_meta")]
784 pub meta: Option<Meta>,
785}
786
787impl Diff {
788 #[must_use]
790 pub fn new(changes: Vec<DiffChange>) -> Self {
791 Self {
792 changes,
793 patch: None,
794 meta: None,
795 }
796 }
797
798 #[must_use]
800 pub fn patch(text: impl Into<String>, changes: Vec<DiffChange>) -> Self {
801 Self::new(changes).with_patch(DiffPatch::new(text))
802 }
803
804 #[must_use]
806 pub fn with_patch(mut self, patch: impl IntoOption<DiffPatch>) -> Self {
807 self.patch = patch.into_option();
808 self
809 }
810
811 #[must_use]
817 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
818 self.meta = meta.into_option();
819 self
820 }
821}
822
823#[serde_as]
825#[skip_serializing_none]
826#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
827#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
828#[serde(rename_all = "camelCase")]
829#[non_exhaustive]
830pub struct DiffPatch {
831 pub format: DiffPatchFormat,
833 pub text: String,
835 #[serde_as(deserialize_as = "DefaultOnError")]
841 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
842 #[serde(default)]
843 #[serde(rename = "_meta")]
844 pub meta: Option<Meta>,
845}
846
847impl DiffPatch {
848 #[must_use]
850 pub fn new(text: impl Into<String>) -> Self {
851 Self {
852 format: DiffPatchFormat::GitPatch,
853 text: text.into(),
854 meta: None,
855 }
856 }
857
858 #[must_use]
864 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
865 self.meta = meta.into_option();
866 self
867 }
868}
869
870#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
872#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
873#[serde(rename_all = "snake_case")]
874#[non_exhaustive]
875pub enum DiffPatchFormat {
876 GitPatch,
888 #[serde(untagged)]
894 Other(String),
895}
896
897#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
899#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
900#[serde(rename_all = "snake_case")]
901#[non_exhaustive]
902pub enum DiffFileType {
903 Text,
905 Binary,
907 Directory,
909 Symlink,
911 #[serde(untagged)]
917 Other(String),
918}
919
920#[serde_as]
925#[skip_serializing_none]
926#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
927#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
928#[serde(rename_all = "camelCase")]
929#[non_exhaustive]
930pub struct DiffChange {
931 #[serde_as(deserialize_as = "DefaultOnError")]
935 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
936 #[serde(default)]
937 pub file_type: Option<DiffFileType>,
938 #[serde_as(deserialize_as = "DefaultOnError")]
942 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
943 #[serde(default)]
944 pub mime_type: Option<MediaType>,
945 #[serde(flatten)]
947 pub operation: DiffChangeOperation,
948 #[serde_as(deserialize_as = "DefaultOnError")]
954 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
955 #[serde(default)]
956 #[serde(rename = "_meta")]
957 pub meta: Option<Meta>,
958}
959
960impl DiffChange {
961 #[must_use]
963 pub fn new(operation: DiffChangeOperation) -> Self {
964 Self {
965 file_type: None,
966 mime_type: None,
967 operation,
968 meta: None,
969 }
970 }
971
972 #[must_use]
974 pub fn add(path: impl Into<AbsolutePath>) -> Self {
975 Self::new(DiffChangeOperation::Add(DiffPathChange::new(path)))
976 }
977
978 #[must_use]
980 pub fn delete(path: impl Into<AbsolutePath>) -> Self {
981 Self::new(DiffChangeOperation::Delete(DiffPathChange::new(path)))
982 }
983
984 #[must_use]
986 pub fn modify(path: impl Into<AbsolutePath>) -> Self {
987 Self::new(DiffChangeOperation::Modify(DiffPathChange::new(path)))
988 }
989
990 #[must_use]
992 pub fn move_file(old_path: impl Into<AbsolutePath>, path: impl Into<AbsolutePath>) -> Self {
993 Self::new(DiffChangeOperation::Move(DiffPathPairChange::new(
994 old_path, path,
995 )))
996 }
997
998 #[must_use]
1000 pub fn copy(old_path: impl Into<AbsolutePath>, path: impl Into<AbsolutePath>) -> Self {
1001 Self::new(DiffChangeOperation::Copy(DiffPathPairChange::new(
1002 old_path, path,
1003 )))
1004 }
1005
1006 #[must_use]
1010 pub fn file_type(mut self, file_type: impl IntoOption<DiffFileType>) -> Self {
1011 self.file_type = file_type.into_option();
1012 self
1013 }
1014
1015 #[must_use]
1019 pub fn mime_type(mut self, mime_type: impl IntoOption<MediaType>) -> Self {
1020 self.mime_type = mime_type.into_option();
1021 self
1022 }
1023
1024 #[must_use]
1030 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1031 self.meta = meta.into_option();
1032 self
1033 }
1034}
1035
1036#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1038#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1039#[serde(tag = "operation", rename_all = "snake_case")]
1040#[non_exhaustive]
1041pub enum DiffChangeOperation {
1042 Add(DiffPathChange),
1044 Delete(DiffPathChange),
1046 Modify(DiffPathChange),
1048 Move(DiffPathPairChange),
1050 Copy(DiffPathPairChange),
1052 #[serde(untagged)]
1058 Other(OtherDiffChange),
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 DiffPathChange {
1067 pub path: AbsolutePath,
1069}
1070
1071impl DiffPathChange {
1072 #[must_use]
1074 pub fn new(path: impl Into<AbsolutePath>) -> Self {
1075 Self { path: path.into() }
1076 }
1077}
1078
1079#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1081#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1082#[serde(rename_all = "camelCase")]
1083#[non_exhaustive]
1084pub struct DiffPathPairChange {
1085 pub old_path: AbsolutePath,
1087 pub path: AbsolutePath,
1089}
1090
1091impl DiffPathPairChange {
1092 #[must_use]
1094 pub fn new(old_path: impl Into<AbsolutePath>, path: impl Into<AbsolutePath>) -> Self {
1095 Self {
1096 old_path: old_path.into(),
1097 path: path.into(),
1098 }
1099 }
1100}
1101
1102#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1104#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1105#[cfg_attr(feature = "schemars", schemars(inline))]
1106#[cfg_attr(feature = "schemars", schemars(transform = other_diff_change_schema))]
1107#[serde(rename_all = "camelCase")]
1108#[non_exhaustive]
1109pub struct OtherDiffChange {
1110 pub operation: String,
1116 #[serde(flatten)]
1118 pub fields: BTreeMap<String, serde_json::Value>,
1119}
1120
1121impl OtherDiffChange {
1122 #[must_use]
1124 pub fn new(
1125 operation: impl Into<String>,
1126 mut fields: BTreeMap<String, serde_json::Value>,
1127 ) -> Self {
1128 fields.remove("operation");
1129 fields.remove("fileType");
1130 fields.remove("mimeType");
1131 fields.remove("_meta");
1132 Self {
1133 operation: operation.into(),
1134 fields,
1135 }
1136 }
1137}
1138
1139impl<'de> Deserialize<'de> for OtherDiffChange {
1140 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1141 where
1142 D: serde::Deserializer<'de>,
1143 {
1144 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
1145 let operation = fields
1146 .remove("operation")
1147 .ok_or_else(|| serde::de::Error::missing_field("operation"))?;
1148 let serde_json::Value::String(operation) = operation else {
1149 return Err(serde::de::Error::custom("`operation` must be a string"));
1150 };
1151
1152 if is_known_diff_change_operation(&operation) {
1153 return Err(serde::de::Error::custom(format!(
1154 "known diff change operation `{operation}` did not match its schema"
1155 )));
1156 }
1157 fields.remove("fileType");
1158 fields.remove("mimeType");
1159 fields.remove("_meta");
1160
1161 Ok(Self { operation, fields })
1162 }
1163}
1164
1165fn is_known_diff_change_operation(operation: &str) -> bool {
1166 matches!(operation, "add" | "delete" | "modify" | "move" | "copy")
1167}
1168
1169#[cfg(feature = "schemars")]
1170fn other_diff_change_schema(schema: &mut Schema) {
1171 super::schema_util::reject_known_string_discriminators(
1172 schema,
1173 "operation",
1174 &["add", "delete", "modify", "move", "copy"],
1175 );
1176}
1177
1178#[serde_as]
1185#[skip_serializing_none]
1186#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1187#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1188#[serde(rename_all = "camelCase")]
1189#[non_exhaustive]
1190pub struct ToolCallLocation {
1191 pub path: AbsolutePath,
1193 #[serde_as(deserialize_as = "DefaultOnError")]
1196 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1197 #[serde(default)]
1198 pub line: Option<std::num::NonZeroU32>,
1199 #[serde_as(deserialize_as = "DefaultOnError")]
1205 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1206 #[serde(default)]
1207 #[serde(rename = "_meta")]
1208 pub meta: Option<Meta>,
1209}
1210
1211impl ToolCallLocation {
1212 #[must_use]
1214 pub fn new(path: impl Into<AbsolutePath>) -> Self {
1215 Self {
1216 path: path.into(),
1217 line: None,
1218 meta: None,
1219 }
1220 }
1221
1222 #[must_use]
1227 pub fn line(mut self, line: impl IntoOption<u32>) -> Self {
1228 self.line = line.into_option().and_then(std::num::NonZeroU32::new);
1229 self
1230 }
1231
1232 #[must_use]
1238 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1239 self.meta = meta.into_option();
1240 self
1241 }
1242}
1243
1244#[cfg(test)]
1245mod tests {
1246
1247 #[cfg(feature = "unstable_subagents")]
1248 #[test]
1249 fn session_reference_tool_call_content_round_trips() {
1250 use serde_json::json;
1251 let content = ToolCallContent::from(SessionReference::new("sess_child_1"));
1252 let value = serde_json::to_value(&content).unwrap();
1253 assert_eq!(
1254 value,
1255 json!({ "type": "session", "sessionId": "sess_child_1" })
1256 );
1257 assert_eq!(
1258 serde_json::from_value::<ToolCallContent>(value).unwrap(),
1259 content
1260 );
1261 assert!(serde_json::from_value::<ToolCallContent>(json!({ "type": "session" })).is_err());
1263 }
1264
1265 #[test]
1266 fn location_line_is_one_based() {
1267 let location: ToolCallLocation =
1268 serde_json::from_value(serde_json::json!({ "path": "/a.rs", "line": 0 })).unwrap();
1269 assert_eq!(location.line, None);
1270 let location: ToolCallLocation =
1271 serde_json::from_value(serde_json::json!({ "path": "/a.rs", "line": 3 })).unwrap();
1272 assert_eq!(location.line.map(std::num::NonZeroU32::get), Some(3));
1273 assert_eq!(ToolCallLocation::new("/a.rs").line(0).line, None);
1274 }
1275
1276 #[test]
1277 fn toolcall_capabilities_patch_and_tolerate_malformed_values() {
1278 use serde_json::json;
1279 let update = ToolCallUpdate::new("call_012")
1280 .capabilities(ToolCallCapabilities::new().cancel(ToolCallCancelCapabilities::new()));
1281 assert_eq!(
1282 serde_json::to_value(&update).unwrap(),
1283 json!({ "toolCallId": "call_012", "capabilities": { "cancel": {} } })
1284 );
1285
1286 let mut stored = update;
1287 stored.apply_update(ToolCallUpdate::new("call_012"));
1288 assert!(stored.capabilities.is_value());
1289 stored.apply_update(ToolCallUpdate::new("call_012").capabilities(MaybeUndefined::Null));
1290 assert!(stored.capabilities.is_null());
1291
1292 for bad in [json!("yes"), json!(1)] {
1293 let parsed: ToolCallUpdate =
1294 serde_json::from_value(json!({ "toolCallId": "call_012", "capabilities": bad }))
1295 .unwrap();
1296 assert!(parsed.capabilities.is_undefined());
1297 }
1298 let parsed: ToolCallCapabilities =
1299 serde_json::from_value(json!({ "cancel": "yes" })).unwrap();
1300 assert_eq!(parsed.cancel, None);
1301 }
1302
1303 #[test]
1304 fn paused_is_a_known_tool_call_status() {
1305 use serde_json::json;
1306 assert_eq!(
1307 serde_json::to_value(ToolCallStatus::Paused).unwrap(),
1308 json!("paused")
1309 );
1310 assert_eq!(
1311 serde_json::from_value::<ToolCallStatus>(json!("paused")).unwrap(),
1312 ToolCallStatus::Paused
1313 );
1314 }
1315
1316 use super::*;
1317 use crate::MaybeUndefined;
1318 use serde_json::{from_value, json, to_value};
1319
1320 #[test]
1321 fn tool_call_serializes_as_upsert() {
1322 let tool_call = ToolCallUpdate::new("tc_1")
1323 .title("Reading configuration")
1324 .status(ToolCallStatus::InProgress)
1325 .raw_input(serde_json::json!({"path": "settings.json"}));
1326
1327 assert_eq!(
1328 serde_json::to_value(tool_call).unwrap(),
1329 serde_json::json!({
1330 "toolCallId": "tc_1",
1331 "title": "Reading configuration",
1332 "status": "in_progress",
1333 "rawInput": {
1334 "path": "settings.json"
1335 }
1336 })
1337 );
1338 }
1339
1340 #[test]
1341 fn tool_call_update_distinguishes_omitted_null_and_value() {
1342 let tool_call = ToolCallUpdate::new("tc_1")
1343 .status(ToolCallStatus::Completed)
1344 .content(None::<Vec<ToolCallContent>>);
1345
1346 assert_eq!(
1347 serde_json::to_value(tool_call).unwrap(),
1348 serde_json::json!({
1349 "toolCallId": "tc_1",
1350 "status": "completed",
1351 "content": null
1352 })
1353 );
1354
1355 let deserialized: ToolCallUpdate = serde_json::from_value(serde_json::json!({
1356 "toolCallId": "tc_1",
1357 "status": null,
1358 "locations": []
1359 }))
1360 .unwrap();
1361 assert_eq!(deserialized.title, MaybeUndefined::Undefined);
1362 assert_eq!(deserialized.status, MaybeUndefined::Null);
1363 assert_eq!(deserialized.locations, MaybeUndefined::Value(Vec::new()));
1364 }
1365
1366 #[test]
1367 fn tool_call_name_patch_distinguishes_omitted_null_and_value() {
1368 let named = ToolCallUpdate::new("tc_1").name("read_file");
1369 assert_eq!(
1370 serde_json::to_value(named).unwrap(),
1371 serde_json::json!({
1372 "toolCallId": "tc_1",
1373 "name": "read_file"
1374 })
1375 );
1376
1377 let omitted = ToolCallUpdate::new("tc_1");
1378 assert_eq!(omitted.name, MaybeUndefined::Undefined);
1379
1380 let from_null: ToolCallUpdate = serde_json::from_value(serde_json::json!({
1381 "toolCallId": "tc_1",
1382 "name": null
1383 }))
1384 .unwrap();
1385 assert_eq!(from_null.name, MaybeUndefined::Null);
1386
1387 let mut stored = ToolCallUpdate::new("tc_1").name("read_file");
1388 stored.apply_update(ToolCallUpdate::new("tc_1"));
1389 assert_eq!(stored.name, MaybeUndefined::Value("read_file".to_string()));
1390
1391 stored.apply_update(ToolCallUpdate::new("tc_1").name(None::<String>));
1392 assert_eq!(stored.name, MaybeUndefined::Null);
1393
1394 stored.apply_update(ToolCallUpdate::new("tc_1").name("write_file"));
1395 assert_eq!(stored.name, MaybeUndefined::Value("write_file".to_string()));
1396 }
1397
1398 #[test]
1399 fn tool_call_update_distinguishes_meta_omitted_null_and_value() {
1400 let mut meta = Meta::new();
1401 meta.insert("source".to_string(), serde_json::json!("tool-call"));
1402
1403 assert_eq!(
1404 serde_json::to_value(ToolCallUpdate::new("tc_1").meta(meta.clone())).unwrap(),
1405 serde_json::json!({
1406 "toolCallId": "tc_1",
1407 "_meta": {
1408 "source": "tool-call"
1409 }
1410 })
1411 );
1412
1413 assert_eq!(
1414 serde_json::to_value(ToolCallUpdate::new("tc_1").meta(None::<Meta>)).unwrap(),
1415 serde_json::json!({
1416 "toolCallId": "tc_1",
1417 "_meta": null
1418 })
1419 );
1420
1421 let deserialized: ToolCallUpdate = serde_json::from_value(serde_json::json!({
1422 "toolCallId": "tc_1",
1423 "_meta": null
1424 }))
1425 .unwrap();
1426 assert_eq!(deserialized.meta, MaybeUndefined::Null);
1427
1428 let patch = ToolCallUpdate::new("tc_1");
1429 assert_eq!(patch.meta, MaybeUndefined::Undefined);
1430
1431 let mut stored = ToolCallUpdate::new("tc_1").meta(meta);
1432 stored.apply_update(ToolCallUpdate::new("tc_1").meta(None::<Meta>));
1433 assert_eq!(stored.meta, MaybeUndefined::Null);
1434 }
1435
1436 #[test]
1437 fn tool_call_update_patches_meta_by_top_level_key() {
1438 let mut stored: ToolCallUpdate = from_value(json!({
1439 "toolCallId": "tc_1",
1440 "_meta": {"zed.dev/a": 1, "acme.dev/b": {"x": 1}}
1441 }))
1442 .unwrap();
1443
1444 stored.apply_update(
1446 from_value(json!({"toolCallId": "tc_1", "_meta": {"proxy.dev/c": true}})).unwrap(),
1447 );
1448 stored.apply_update(
1449 from_value(json!({
1450 "toolCallId": "tc_1",
1451 "_meta": {"zed.dev/a": null, "acme.dev/b": {"y": 2}}
1452 }))
1453 .unwrap(),
1454 );
1455
1456 assert_eq!(
1457 to_value(&stored).unwrap(),
1458 json!({
1459 "toolCallId": "tc_1",
1460 "_meta": {"acme.dev/b": {"y": 2}, "proxy.dev/c": true}
1461 })
1462 );
1463 }
1464
1465 #[test]
1466 fn tool_call_wire_patches_preserve_omitted_fields_and_replace_values() {
1467 let initial = json!({
1468 "toolCallId": "tc_1",
1469 "_meta": {"source": "replay", "opaque": {"sequence": 1}}
1470 });
1471 let mut stored: ToolCallUpdate = from_value(initial.clone()).unwrap();
1472 assert_eq!(to_value(&stored).unwrap(), initial);
1474
1475 let populated = json!({
1476 "toolCallId": "tc_1",
1477 "name": "read_file",
1478 "title": "Reading configuration",
1479 "kind": "read",
1480 "status": "in_progress",
1481 "content": [{
1482 "type": "content",
1483 "content": {
1484 "type": "text",
1485 "text": "old",
1486 "_meta": {"source": "tool"}
1487 }
1488 }],
1489 "locations": [{"path": "/workspace/config.json", "line": 3}],
1490 "rawInput": {"path": "/workspace/config.json"},
1491 "rawOutput": {"text": "old"}
1492 });
1493 stored.apply_update(from_value(populated.clone()).unwrap());
1494 let mut expected = populated;
1495 expected["_meta"] = initial["_meta"].clone();
1496 assert_eq!(to_value(&stored).unwrap(), expected);
1497
1498 for (field, empty) in [
1499 ("content", json!([])),
1500 ("locations", json!([])),
1501 ("rawInput", json!({})),
1502 ("rawOutput", json!({})),
1503 ] {
1504 let original = expected[field].clone();
1505 for replacement in [empty, json!(null), original] {
1508 stored.apply_update(
1509 from_value(json!({"toolCallId": "tc_1", (field): replacement})).unwrap(),
1510 );
1511 expected[field] = replacement;
1512 assert_eq!(to_value(&stored).unwrap(), expected, "patching {field}");
1513
1514 stored.apply_update(from_value(json!({"toolCallId": "tc_1"})).unwrap());
1515 assert_eq!(to_value(&stored).unwrap(), expected, "omitting {field}");
1516 }
1517 }
1518 }
1519
1520 #[test]
1521 fn tool_call_wire_patches_preserve_unknown_statuses() {
1522 for status in ["deferred", "_awaiting_review"] {
1523 let mut stored = ToolCallUpdate::new("tc_1").status(ToolCallStatus::InProgress);
1524 stored
1525 .apply_update(from_value(json!({"toolCallId": "tc_1", "status": status})).unwrap());
1526 let expected_status = MaybeUndefined::Value(ToolCallStatus::Other(status.to_owned()));
1527 assert_eq!(stored.status, expected_status);
1528
1529 stored.apply_update(
1532 from_value(json!({"toolCallId": "tc_1", "title": "Still waiting"})).unwrap(),
1533 );
1534 assert_eq!(stored.status, expected_status);
1535 assert_eq!(
1536 to_value(&stored).unwrap(),
1537 json!({"toolCallId": "tc_1", "title": "Still waiting", "status": status})
1538 );
1539 }
1540 }
1541
1542 #[test]
1543 fn tool_call_update_skips_malformed_list_items() {
1544 let deserialized: ToolCallUpdate = serde_json::from_value(serde_json::json!({
1545 "toolCallId": "tc_1",
1546 "content": [
1547 {
1548 "type": "content",
1549 "content": {
1550 "type": "text",
1551 "text": "ok"
1552 }
1553 },
1554 {
1555 "type": "diff",
1556 "path": "/bad"
1557 }
1558 ],
1559 "locations": [
1560 {
1561 "path": "/ok",
1562 "line": 3
1563 },
1564 {
1565 "line": 4
1566 }
1567 ]
1568 }))
1569 .unwrap();
1570
1571 let MaybeUndefined::Value(content) = deserialized.content else {
1572 panic!("content should deserialize to a value");
1573 };
1574 assert_eq!(content.len(), 1);
1575
1576 let MaybeUndefined::Value(locations) = deserialized.locations else {
1577 panic!("locations should deserialize to a value");
1578 };
1579 assert_eq!(locations.len(), 1);
1580 }
1581
1582 #[test]
1583 fn tool_call_content_chunk_serializes_single_content_item() {
1584 let chunk = ToolCallContentChunk::new(
1585 "tc_1",
1586 ContentBlock::Text(crate::v2::TextContent::new("partial output")),
1587 );
1588
1589 assert_eq!(
1590 serde_json::to_value(chunk).unwrap(),
1591 serde_json::json!({
1592 "toolCallId": "tc_1",
1593 "content": {
1594 "type": "content",
1595 "content": {
1596 "type": "text",
1597 "text": "partial output"
1598 }
1599 }
1600 })
1601 );
1602 }
1603
1604 #[test]
1605 fn terminal_content_serializes_as_display_reference() {
1606 let terminal = ToolCallContent::from(Terminal::new("term_1"));
1607
1608 assert_eq!(
1609 serde_json::to_value(terminal).unwrap(),
1610 serde_json::json!({
1611 "type": "terminal",
1612 "terminalId": "term_1"
1613 })
1614 );
1615 }
1616
1617 #[test]
1618 fn diff_patch_serializes_git_patch_with_structured_changes() {
1619 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";
1620 let diff = ToolCallContent::Diff(Diff::patch(
1621 patch_text,
1622 vec![
1623 DiffChange::modify("/repo/config.json")
1624 .file_type(DiffFileType::Text)
1625 .mime_type("application/json"),
1626 ],
1627 ));
1628
1629 assert_eq!(
1630 serde_json::to_value(diff).unwrap(),
1631 serde_json::json!({
1632 "type": "diff",
1633 "changes": [
1634 {
1635 "operation": "modify",
1636 "path": "/repo/config.json",
1637 "fileType": "text",
1638 "mimeType": "application/json"
1639 }
1640 ],
1641 "patch": {
1642 "format": "git_patch",
1643 "text": patch_text
1644 }
1645 })
1646 );
1647 }
1648
1649 #[test]
1650 fn diff_patch_requires_text() {
1651 let result = serde_json::from_value::<DiffPatch>(serde_json::json!({
1652 "format": "git_patch",
1653 "diff": "diff --git /repo/config.json /repo/config.json\n"
1654 }));
1655
1656 assert!(result.is_err());
1657 }
1658
1659 #[test]
1660 fn diff_serializes_binary_modify_without_patch_text() {
1661 let diff = ToolCallContent::Diff(Diff::new(vec![
1662 DiffChange::modify("/repo/assets/logo.png")
1663 .file_type(DiffFileType::Binary)
1664 .mime_type("image/png"),
1665 ]));
1666
1667 assert_eq!(
1668 serde_json::to_value(diff).unwrap(),
1669 serde_json::json!({
1670 "type": "diff",
1671 "changes": [
1672 {
1673 "operation": "modify",
1674 "path": "/repo/assets/logo.png",
1675 "fileType": "binary",
1676 "mimeType": "image/png"
1677 }
1678 ]
1679 })
1680 );
1681 }
1682
1683 #[test]
1684 fn diff_move_serializes_shared_fields_with_operation_payload() {
1685 let diff = ToolCallContent::Diff(Diff::new(vec![
1686 DiffChange::move_file("/repo/src/old.rs", "/repo/src/new.rs")
1687 .file_type(DiffFileType::Text)
1688 .mime_type("text/rust"),
1689 ]));
1690
1691 assert_eq!(
1692 serde_json::to_value(diff).unwrap(),
1693 serde_json::json!({
1694 "type": "diff",
1695 "changes": [
1696 {
1697 "operation": "move",
1698 "oldPath": "/repo/src/old.rs",
1699 "path": "/repo/src/new.rs",
1700 "fileType": "text",
1701 "mimeType": "text/rust"
1702 }
1703 ]
1704 })
1705 );
1706 }
1707
1708 #[test]
1709 fn diff_changes_skip_malformed_list_items() {
1710 let patch_text = "diff --git /ok /ok\ndeleted file mode 100644\n--- /ok\n+++ /dev/null\n@@ -1 +0,0 @@\n-old\n";
1711 let content: ToolCallContent = serde_json::from_value(serde_json::json!({
1712 "type": "diff",
1713 "changes": [
1714 {
1715 "operation": "modify"
1716 },
1717 {
1718 "operation": "delete",
1719 "path": "/ok"
1720 }
1721 ],
1722 "patch": {
1723 "format": "git_patch",
1724 "text": patch_text
1725 }
1726 }))
1727 .unwrap();
1728
1729 let ToolCallContent::Diff(diff) = content else {
1730 panic!("expected diff content");
1731 };
1732 assert_eq!(diff.changes, vec![DiffChange::delete("/ok")]);
1733 assert_eq!(diff.patch, Some(DiffPatch::new(patch_text)));
1734 }
1735
1736 #[test]
1737 fn tool_kind_preserves_unknown_variant() {
1738 let kind: ToolKind = serde_json::from_str("\"review\"").unwrap();
1739 assert_eq!(kind, ToolKind::Unknown("review".to_string()));
1740 assert_eq!(serde_json::to_value(&kind).unwrap(), "review");
1741 }
1742
1743 #[test]
1744 fn tool_call_status_preserves_unknown_variant() {
1745 let status: ToolCallStatus = serde_json::from_str("\"deferred\"").unwrap();
1746 assert_eq!(status, ToolCallStatus::Other("deferred".to_string()));
1747 assert_eq!(serde_json::to_value(&status).unwrap(), "deferred");
1748 }
1749
1750 #[test]
1751 fn tool_call_status_recognizes_cancelled_variant() {
1752 let status: ToolCallStatus = serde_json::from_str("\"cancelled\"").unwrap();
1753 assert_eq!(status, ToolCallStatus::Cancelled);
1754 assert_eq!(serde_json::to_value(&status).unwrap(), "cancelled");
1755 }
1756
1757 #[test]
1758 fn tool_call_content_preserves_unknown_variant() {
1759 let content: ToolCallContent = serde_json::from_value(serde_json::json!({
1760 "type": "_chart",
1761 "title": "Tests",
1762 "data": [1, 2, 3]
1763 }))
1764 .unwrap();
1765
1766 let ToolCallContent::Other(unknown) = content else {
1767 panic!("expected unknown tool call content");
1768 };
1769
1770 assert_eq!(unknown.type_, "_chart");
1771 assert_eq!(
1772 unknown.fields.get("title"),
1773 Some(&serde_json::json!("Tests"))
1774 );
1775 assert_eq!(
1776 serde_json::to_value(ToolCallContent::Other(unknown)).unwrap(),
1777 serde_json::json!({
1778 "type": "_chart",
1779 "title": "Tests",
1780 "data": [1, 2, 3]
1781 })
1782 );
1783 }
1784
1785 #[test]
1786 fn tool_call_content_does_not_hide_malformed_known_variant() {
1787 assert!(
1788 serde_json::from_value::<ToolCallContent>(serde_json::json!({
1789 "type": "diff"
1790 }))
1791 .is_err()
1792 );
1793 assert!(
1794 serde_json::from_value::<ToolCallContent>(serde_json::json!({
1795 "type": "terminal"
1796 }))
1797 .is_err()
1798 );
1799 }
1800}