1use std::{path::PathBuf, sync::Arc};
8
9use derive_more::{Display, From};
10use serde::{Deserialize, Serialize};
11use serde_with::{DefaultOnError, VecSkipError, serde_as, skip_serializing_none};
12
13use crate::IntoOption;
14
15use super::SessionId;
16use super::{ContentBlock, Error, Meta, TerminalId};
17
18fn is_default<T: Default + PartialEq>(value: &T) -> bool {
19 *value == T::default()
20}
21
22#[serde_as]
29#[skip_serializing_none]
30#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
31#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
32#[serde(rename_all = "camelCase")]
33#[non_exhaustive]
34pub struct ToolCall {
35 pub tool_call_id: ToolCallId,
37 pub title: String,
39 #[serde_as(deserialize_as = "DefaultOnError")]
44 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
45 #[serde(default)]
46 pub name: Option<String>,
47 #[serde_as(deserialize_as = "DefaultOnError")]
50 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
51 #[serde(default, skip_serializing_if = "is_default")]
52 pub kind: ToolKind,
53 #[serde_as(deserialize_as = "DefaultOnError")]
55 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
56 #[serde(default, skip_serializing_if = "is_default")]
57 pub status: ToolCallStatus,
58 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
60 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
61 #[serde(default, skip_serializing_if = "Vec::is_empty")]
62 pub content: Vec<ToolCallContent>,
63 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
66 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
67 #[serde(default, skip_serializing_if = "Vec::is_empty")]
68 pub locations: Vec<ToolCallLocation>,
69 #[serde_as(deserialize_as = "DefaultOnError")]
71 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
72 #[serde(default)]
73 pub raw_input: Option<serde_json::Value>,
74 #[serde_as(deserialize_as = "DefaultOnError")]
76 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
77 #[serde(default)]
78 pub raw_output: Option<serde_json::Value>,
79 #[serde_as(deserialize_as = "DefaultOnError")]
85 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
86 #[serde(default)]
87 #[serde(rename = "_meta")]
88 pub meta: Option<Meta>,
89}
90
91impl ToolCall {
92 #[must_use]
94 pub fn new(tool_call_id: impl Into<ToolCallId>, title: impl Into<String>) -> Self {
95 Self {
96 tool_call_id: tool_call_id.into(),
97 title: title.into(),
98 name: None,
99 kind: ToolKind::default(),
100 status: ToolCallStatus::default(),
101 content: Vec::default(),
102 locations: Vec::default(),
103 raw_input: None,
104 raw_output: None,
105 meta: None,
106 }
107 }
108
109 #[must_use]
111 pub fn name(mut self, name: impl IntoOption<String>) -> Self {
112 self.name = name.into_option();
113 self
114 }
115
116 #[must_use]
119 pub fn kind(mut self, kind: ToolKind) -> Self {
120 self.kind = kind;
121 self
122 }
123
124 #[must_use]
126 pub fn status(mut self, status: ToolCallStatus) -> Self {
127 self.status = status;
128 self
129 }
130
131 #[must_use]
133 pub fn content(mut self, content: Vec<ToolCallContent>) -> Self {
134 self.content = content;
135 self
136 }
137
138 #[must_use]
141 pub fn locations(mut self, locations: Vec<ToolCallLocation>) -> Self {
142 self.locations = locations;
143 self
144 }
145
146 #[must_use]
148 pub fn raw_input(mut self, raw_input: impl IntoOption<serde_json::Value>) -> Self {
149 self.raw_input = raw_input.into_option();
150 self
151 }
152
153 #[must_use]
155 pub fn raw_output(mut self, raw_output: impl IntoOption<serde_json::Value>) -> Self {
156 self.raw_output = raw_output.into_option();
157 self
158 }
159
160 #[must_use]
166 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
167 self.meta = meta.into_option();
168 self
169 }
170
171 pub fn update(&mut self, fields: ToolCallUpdateFields) {
174 if let Some(title) = fields.title {
175 self.title = title;
176 }
177 if let Some(name) = fields.name {
178 self.name = Some(name);
179 }
180 if let Some(kind) = fields.kind {
181 self.kind = kind;
182 }
183 if let Some(status) = fields.status {
184 self.status = status;
185 }
186 if let Some(content) = fields.content {
187 self.content = content;
188 }
189 if let Some(locations) = fields.locations {
190 self.locations = locations;
191 }
192 if let Some(raw_input) = fields.raw_input {
193 self.raw_input = Some(raw_input);
194 }
195 if let Some(raw_output) = fields.raw_output {
196 self.raw_output = Some(raw_output);
197 }
198 }
199}
200
201#[serde_as]
208#[skip_serializing_none]
209#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
210#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
211#[serde(rename_all = "camelCase")]
212#[non_exhaustive]
213pub struct ToolCallUpdate {
214 pub tool_call_id: ToolCallId,
216 #[serde(flatten)]
218 pub fields: ToolCallUpdateFields,
219 #[serde_as(deserialize_as = "DefaultOnError")]
225 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
226 #[serde(default)]
227 #[serde(rename = "_meta")]
228 pub meta: Option<Meta>,
229}
230
231impl ToolCallUpdate {
232 #[must_use]
234 pub fn new(tool_call_id: impl Into<ToolCallId>, fields: ToolCallUpdateFields) -> Self {
235 Self {
236 tool_call_id: tool_call_id.into(),
237 fields,
238 meta: None,
239 }
240 }
241
242 #[must_use]
248 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
249 self.meta = meta.into_option();
250 self
251 }
252}
253
254#[serde_as]
261#[skip_serializing_none]
262#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
263#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
264#[serde(rename_all = "camelCase")]
265#[non_exhaustive]
266pub struct ToolCallUpdateFields {
267 #[serde_as(deserialize_as = "DefaultOnError")]
269 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
270 #[serde(default)]
271 pub kind: Option<ToolKind>,
272 #[serde_as(deserialize_as = "DefaultOnError")]
274 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
275 #[serde(default)]
276 pub status: Option<ToolCallStatus>,
277 #[serde_as(deserialize_as = "DefaultOnError")]
279 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
280 #[serde(default)]
281 pub title: Option<String>,
282 #[serde_as(deserialize_as = "DefaultOnError")]
287 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
288 #[serde(default)]
289 pub name: Option<String>,
290 #[serde_as(deserialize_as = "DefaultOnError<Option<VecSkipError<_>>>")]
292 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
293 #[serde(default)]
294 pub content: Option<Vec<ToolCallContent>>,
295 #[serde_as(deserialize_as = "DefaultOnError<Option<VecSkipError<_>>>")]
297 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
298 #[serde(default)]
299 pub locations: Option<Vec<ToolCallLocation>>,
300 #[serde_as(deserialize_as = "DefaultOnError")]
302 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
303 #[serde(default)]
304 pub raw_input: Option<serde_json::Value>,
305 #[serde_as(deserialize_as = "DefaultOnError")]
307 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
308 #[serde(default)]
309 pub raw_output: Option<serde_json::Value>,
310}
311
312impl ToolCallUpdateFields {
313 #[must_use]
315 pub fn new() -> Self {
316 Self::default()
317 }
318
319 #[must_use]
321 pub fn kind(mut self, kind: impl IntoOption<ToolKind>) -> Self {
322 self.kind = kind.into_option();
323 self
324 }
325
326 #[must_use]
328 pub fn status(mut self, status: impl IntoOption<ToolCallStatus>) -> Self {
329 self.status = status.into_option();
330 self
331 }
332
333 #[must_use]
335 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
336 self.title = title.into_option();
337 self
338 }
339
340 #[must_use]
342 pub fn name(mut self, name: impl IntoOption<String>) -> Self {
343 self.name = name.into_option();
344 self
345 }
346
347 #[must_use]
349 pub fn content(mut self, content: impl IntoOption<Vec<ToolCallContent>>) -> Self {
350 self.content = content.into_option();
351 self
352 }
353
354 #[must_use]
356 pub fn locations(mut self, locations: impl IntoOption<Vec<ToolCallLocation>>) -> Self {
357 self.locations = locations.into_option();
358 self
359 }
360
361 #[must_use]
363 pub fn raw_input(mut self, raw_input: impl IntoOption<serde_json::Value>) -> Self {
364 self.raw_input = raw_input.into_option();
365 self
366 }
367
368 #[must_use]
370 pub fn raw_output(mut self, raw_output: impl IntoOption<serde_json::Value>) -> Self {
371 self.raw_output = raw_output.into_option();
372 self
373 }
374}
375
376impl TryFrom<ToolCallUpdate> for ToolCall {
379 type Error = Error;
380
381 fn try_from(update: ToolCallUpdate) -> Result<Self, Self::Error> {
382 let ToolCallUpdate {
383 tool_call_id,
384 fields:
385 ToolCallUpdateFields {
386 kind,
387 status,
388 title,
389 name,
390 content,
391 locations,
392 raw_input,
393 raw_output,
394 },
395 meta,
396 } = update;
397
398 Ok(Self {
399 tool_call_id,
400 title: title.ok_or_else(|| {
401 Error::invalid_params().data(serde_json::json!("title is required for a tool call"))
402 })?,
403 name,
404 kind: kind.unwrap_or_default(),
405 status: status.unwrap_or_default(),
406 content: content.unwrap_or_default(),
407 locations: locations.unwrap_or_default(),
408 raw_input,
409 raw_output,
410 meta,
411 })
412 }
413}
414
415impl From<ToolCall> for ToolCallUpdate {
416 fn from(value: ToolCall) -> Self {
417 let ToolCall {
418 tool_call_id,
419 title,
420 name,
421 kind,
422 status,
423 content,
424 locations,
425 raw_input,
426 raw_output,
427 meta,
428 } = value;
429 Self {
430 tool_call_id,
431 fields: ToolCallUpdateFields {
432 kind: Some(kind),
433 status: Some(status),
434 title: Some(title),
435 name,
436 content: Some(content),
437 locations: Some(locations),
438 raw_input,
439 raw_output,
440 },
441 meta,
442 }
443 }
444}
445
446#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
448#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
449#[serde(transparent)]
450#[from(Arc<str>, String, &'static str)]
451#[non_exhaustive]
452pub struct ToolCallId(pub Arc<str>);
453
454impl ToolCallId {
455 #[must_use]
457 pub fn new(id: impl Into<Arc<str>>) -> Self {
458 Self(id.into())
459 }
460}
461
462impl IntoOption<ToolCallId> for &str {
463 fn into_option(self) -> Option<ToolCallId> {
464 Some(ToolCallId::new(self))
465 }
466}
467
468#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
475#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
476#[serde(rename_all = "snake_case")]
477#[non_exhaustive]
478pub enum ToolKind {
479 Read,
481 Edit,
483 Delete,
485 Move,
487 Search,
489 Execute,
491 Think,
493 Fetch,
495 SwitchMode,
497 #[default]
499 #[serde(other)]
500 Other,
501}
502
503#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
509#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
510#[serde(rename_all = "snake_case")]
511#[non_exhaustive]
512pub enum ToolCallStatus {
513 #[default]
516 Pending,
517 InProgress,
519 Completed,
521 Failed,
523}
524
525#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
532#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
533#[serde(tag = "type", rename_all = "snake_case")]
534#[cfg_attr(feature = "schemars", schemars(extend("discriminator" = {"propertyName": "type"})))]
535#[non_exhaustive]
536#[cfg_attr(
537 target_pointer_width = "64",
538 expect(
539 clippy::large_enum_variant,
540 reason = "TODO(next major): box Content in the v1 enum"
541 )
542)]
543pub enum ToolCallContent {
544 Content(Content),
546 Diff(Diff),
548 Terminal(Terminal),
554 Session(SessionReference),
561}
562
563impl<T: Into<ContentBlock>> From<T> for ToolCallContent {
564 fn from(content: T) -> Self {
565 ToolCallContent::Content(Content::new(content))
566 }
567}
568
569impl From<Diff> for ToolCallContent {
570 fn from(diff: Diff) -> Self {
571 ToolCallContent::Diff(diff)
572 }
573}
574
575#[serde_as]
583#[skip_serializing_none]
584#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
585#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
586#[serde(rename_all = "camelCase")]
587#[non_exhaustive]
588pub struct SessionReference {
589 pub session_id: SessionId,
591 #[serde_as(deserialize_as = "DefaultOnError")]
597 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
598 #[serde(default)]
599 #[serde(rename = "_meta")]
600 pub meta: Option<Meta>,
601}
602
603impl SessionReference {
604 #[must_use]
606 pub fn new(session_id: impl Into<SessionId>) -> Self {
607 Self {
608 session_id: session_id.into(),
609 meta: None,
610 }
611 }
612
613 #[must_use]
616 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
617 self.meta = meta.into_option();
618 self
619 }
620}
621
622impl From<SessionReference> for ToolCallContent {
623 fn from(session: SessionReference) -> Self {
624 ToolCallContent::Session(session)
625 }
626}
627
628#[serde_as]
630#[skip_serializing_none]
631#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
632#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
633#[serde(rename_all = "camelCase")]
634#[non_exhaustive]
635pub struct Content {
636 pub content: ContentBlock,
638 #[serde_as(deserialize_as = "DefaultOnError")]
644 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
645 #[serde(default)]
646 #[serde(rename = "_meta")]
647 pub meta: Option<Meta>,
648}
649
650impl Content {
651 #[must_use]
653 pub fn new(content: impl Into<ContentBlock>) -> Self {
654 Self {
655 content: content.into(),
656 meta: None,
657 }
658 }
659
660 #[must_use]
666 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
667 self.meta = meta.into_option();
668 self
669 }
670}
671
672#[serde_as]
678#[skip_serializing_none]
679#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
680#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
681#[serde(rename_all = "camelCase")]
682#[non_exhaustive]
683pub struct Terminal {
684 pub terminal_id: TerminalId,
686 #[serde_as(deserialize_as = "DefaultOnError")]
692 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
693 #[serde(default)]
694 #[serde(rename = "_meta")]
695 pub meta: Option<Meta>,
696}
697
698impl Terminal {
699 #[must_use]
701 pub fn new(terminal_id: impl Into<TerminalId>) -> Self {
702 Self {
703 terminal_id: terminal_id.into(),
704 meta: None,
705 }
706 }
707
708 #[must_use]
714 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
715 self.meta = meta.into_option();
716 self
717 }
718}
719
720#[serde_as]
726#[skip_serializing_none]
727#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
728#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
729#[serde(rename_all = "camelCase")]
730#[non_exhaustive]
731pub struct Diff {
732 pub path: PathBuf,
734 #[serde_as(deserialize_as = "DefaultOnError")]
736 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
737 #[serde(default)]
738 pub old_text: Option<String>,
739 pub new_text: String,
741 #[serde_as(deserialize_as = "DefaultOnError")]
747 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
748 #[serde(default)]
749 #[serde(rename = "_meta")]
750 pub meta: Option<Meta>,
751}
752
753impl Diff {
754 #[must_use]
756 pub fn new(path: impl Into<PathBuf>, new_text: impl Into<String>) -> Self {
757 Self {
758 path: path.into(),
759 old_text: None,
760 new_text: new_text.into(),
761 meta: None,
762 }
763 }
764
765 #[must_use]
767 pub fn old_text(mut self, old_text: impl IntoOption<String>) -> Self {
768 self.old_text = old_text.into_option();
769 self
770 }
771
772 #[must_use]
778 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
779 self.meta = meta.into_option();
780 self
781 }
782}
783
784#[serde_as]
791#[skip_serializing_none]
792#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
793#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
794#[serde(rename_all = "camelCase")]
795#[non_exhaustive]
796pub struct ToolCallLocation {
797 pub path: PathBuf,
799 #[serde_as(deserialize_as = "DefaultOnError")]
801 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
802 #[serde(default)]
803 pub line: Option<u32>,
804 #[serde_as(deserialize_as = "DefaultOnError")]
810 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
811 #[serde(default)]
812 #[serde(rename = "_meta")]
813 pub meta: Option<Meta>,
814}
815
816impl ToolCallLocation {
817 #[must_use]
819 pub fn new(path: impl Into<PathBuf>) -> Self {
820 Self {
821 path: path.into(),
822 line: None,
823 meta: None,
824 }
825 }
826
827 #[must_use]
829 pub fn line(mut self, line: impl IntoOption<u32>) -> Self {
830 self.line = line.into_option();
831 self
832 }
833
834 #[must_use]
840 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
841 self.meta = meta.into_option();
842 self
843 }
844}
845
846#[cfg(test)]
847mod tests {
848
849 #[test]
850 fn session_reference_tool_call_content_round_trips() {
851 use serde_json::json;
852 let content = ToolCallContent::from(SessionReference::new("sess_child_1"));
853 let value = serde_json::to_value(&content).unwrap();
854 assert_eq!(
855 value,
856 json!({ "type": "session", "sessionId": "sess_child_1" })
857 );
858 assert_eq!(
859 serde_json::from_value::<ToolCallContent>(value).unwrap(),
860 content
861 );
862 }
863 use super::*;
864
865 #[test]
866 fn tool_call_name_is_optional_and_null_is_equivalent_to_omission() {
867 let named = ToolCall::new("tc_1", "Reading configuration").name("read_file");
868 assert_eq!(
869 serde_json::to_value(named).unwrap(),
870 serde_json::json!({
871 "toolCallId": "tc_1",
872 "title": "Reading configuration",
873 "name": "read_file"
874 })
875 );
876
877 let unnamed = ToolCall::new("tc_1", "Reading configuration");
878 assert_eq!(unnamed.name, None);
879 assert_eq!(
880 serde_json::to_value(unnamed).unwrap(),
881 serde_json::json!({
882 "toolCallId": "tc_1",
883 "title": "Reading configuration"
884 })
885 );
886
887 let from_null: ToolCall = serde_json::from_value(serde_json::json!({
888 "toolCallId": "tc_1",
889 "title": "Reading configuration",
890 "name": null
891 }))
892 .unwrap();
893 assert_eq!(from_null.name, None);
894 }
895
896 #[test]
897 fn tool_call_name_update_replaces_a_name_but_cannot_clear_it() {
898 let mut stored = ToolCall::new("tc_1", "Reading configuration").name("read_file");
899
900 stored.update(ToolCallUpdateFields::new());
901 assert_eq!(stored.name.as_deref(), Some("read_file"));
902
903 let null_update: ToolCallUpdateFields =
904 serde_json::from_value(serde_json::json!({"name": null})).unwrap();
905 stored.update(null_update);
906 assert_eq!(stored.name.as_deref(), Some("read_file"));
907
908 stored.update(ToolCallUpdateFields::new().name("read_many_files"));
909 assert_eq!(stored.name.as_deref(), Some("read_many_files"));
910 }
911
912 #[test]
913 fn tool_call_name_survives_v1_upsert_conversion() {
914 let tool_call = ToolCall::new("tc_1", "Reading configuration").name("read_file");
915
916 let update = ToolCallUpdate::from(tool_call.clone());
917 assert_eq!(update.fields.name.as_deref(), Some("read_file"));
918
919 let rebuilt = ToolCall::try_from(update).unwrap();
920 assert_eq!(rebuilt, tool_call);
921 }
922}