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
18#[serde_as]
25#[skip_serializing_none]
26#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28#[serde(rename_all = "camelCase")]
29#[non_exhaustive]
30pub struct ToolCall {
31 pub tool_call_id: ToolCallId,
33 pub title: String,
35 #[serde_as(deserialize_as = "DefaultOnError")]
40 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
41 #[serde(default)]
42 pub name: Option<String>,
43 #[serde_as(deserialize_as = "DefaultOnError")]
46 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
47 #[serde(default, skip_serializing_if = "ToolKind::is_default")]
48 pub kind: ToolKind,
49 #[serde_as(deserialize_as = "DefaultOnError")]
51 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
52 #[serde(default, skip_serializing_if = "ToolCallStatus::is_default")]
53 pub status: ToolCallStatus,
54 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
56 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
57 #[serde(default, skip_serializing_if = "Vec::is_empty")]
58 pub content: Vec<ToolCallContent>,
59 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
62 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
63 #[serde(default, skip_serializing_if = "Vec::is_empty")]
64 pub locations: Vec<ToolCallLocation>,
65 #[serde_as(deserialize_as = "DefaultOnError")]
67 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
68 #[serde(default)]
69 pub raw_input: Option<serde_json::Value>,
70 #[serde_as(deserialize_as = "DefaultOnError")]
72 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
73 #[serde(default)]
74 pub raw_output: Option<serde_json::Value>,
75 #[serde_as(deserialize_as = "DefaultOnError")]
81 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
82 #[serde(default)]
83 #[serde(rename = "_meta")]
84 pub meta: Option<Meta>,
85}
86
87impl ToolCall {
88 #[must_use]
90 pub fn new(tool_call_id: impl Into<ToolCallId>, title: impl Into<String>) -> Self {
91 Self {
92 tool_call_id: tool_call_id.into(),
93 title: title.into(),
94 name: None,
95 kind: ToolKind::default(),
96 status: ToolCallStatus::default(),
97 content: Vec::default(),
98 locations: Vec::default(),
99 raw_input: None,
100 raw_output: None,
101 meta: None,
102 }
103 }
104
105 #[must_use]
107 pub fn name(mut self, name: impl IntoOption<String>) -> Self {
108 self.name = name.into_option();
109 self
110 }
111
112 #[must_use]
115 pub fn kind(mut self, kind: ToolKind) -> Self {
116 self.kind = kind;
117 self
118 }
119
120 #[must_use]
122 pub fn status(mut self, status: ToolCallStatus) -> Self {
123 self.status = status;
124 self
125 }
126
127 #[must_use]
129 pub fn content(mut self, content: Vec<ToolCallContent>) -> Self {
130 self.content = content;
131 self
132 }
133
134 #[must_use]
137 pub fn locations(mut self, locations: Vec<ToolCallLocation>) -> Self {
138 self.locations = locations;
139 self
140 }
141
142 #[must_use]
144 pub fn raw_input(mut self, raw_input: impl IntoOption<serde_json::Value>) -> Self {
145 self.raw_input = raw_input.into_option();
146 self
147 }
148
149 #[must_use]
151 pub fn raw_output(mut self, raw_output: impl IntoOption<serde_json::Value>) -> Self {
152 self.raw_output = raw_output.into_option();
153 self
154 }
155
156 #[must_use]
162 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
163 self.meta = meta.into_option();
164 self
165 }
166
167 pub fn update(&mut self, fields: ToolCallUpdateFields) {
170 if let Some(title) = fields.title {
171 self.title = title;
172 }
173 if let Some(name) = fields.name {
174 self.name = Some(name);
175 }
176 if let Some(kind) = fields.kind {
177 self.kind = kind;
178 }
179 if let Some(status) = fields.status {
180 self.status = status;
181 }
182 if let Some(content) = fields.content {
183 self.content = content;
184 }
185 if let Some(locations) = fields.locations {
186 self.locations = locations;
187 }
188 if let Some(raw_input) = fields.raw_input {
189 self.raw_input = Some(raw_input);
190 }
191 if let Some(raw_output) = fields.raw_output {
192 self.raw_output = Some(raw_output);
193 }
194 }
195}
196
197#[serde_as]
204#[skip_serializing_none]
205#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
206#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
207#[serde(rename_all = "camelCase")]
208#[non_exhaustive]
209pub struct ToolCallUpdate {
210 pub tool_call_id: ToolCallId,
212 #[serde(flatten)]
214 pub fields: ToolCallUpdateFields,
215 #[serde_as(deserialize_as = "DefaultOnError")]
221 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
222 #[serde(default)]
223 #[serde(rename = "_meta")]
224 pub meta: Option<Meta>,
225}
226
227impl ToolCallUpdate {
228 #[must_use]
230 pub fn new(tool_call_id: impl Into<ToolCallId>, fields: ToolCallUpdateFields) -> Self {
231 Self {
232 tool_call_id: tool_call_id.into(),
233 fields,
234 meta: None,
235 }
236 }
237
238 #[must_use]
244 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
245 self.meta = meta.into_option();
246 self
247 }
248}
249
250#[serde_as]
257#[skip_serializing_none]
258#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
259#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
260#[serde(rename_all = "camelCase")]
261#[non_exhaustive]
262pub struct ToolCallUpdateFields {
263 #[serde_as(deserialize_as = "DefaultOnError")]
265 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
266 #[serde(default)]
267 pub kind: Option<ToolKind>,
268 #[serde_as(deserialize_as = "DefaultOnError")]
270 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
271 #[serde(default)]
272 pub status: Option<ToolCallStatus>,
273 #[serde_as(deserialize_as = "DefaultOnError")]
275 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
276 #[serde(default)]
277 pub title: Option<String>,
278 #[serde_as(deserialize_as = "DefaultOnError")]
283 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
284 #[serde(default)]
285 pub name: Option<String>,
286 #[serde_as(deserialize_as = "DefaultOnError<Option<VecSkipError<_>>>")]
288 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
289 #[serde(default)]
290 pub content: Option<Vec<ToolCallContent>>,
291 #[serde_as(deserialize_as = "DefaultOnError<Option<VecSkipError<_>>>")]
293 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
294 #[serde(default)]
295 pub locations: Option<Vec<ToolCallLocation>>,
296 #[serde_as(deserialize_as = "DefaultOnError")]
298 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
299 #[serde(default)]
300 pub raw_input: Option<serde_json::Value>,
301 #[serde_as(deserialize_as = "DefaultOnError")]
303 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
304 #[serde(default)]
305 pub raw_output: Option<serde_json::Value>,
306}
307
308impl ToolCallUpdateFields {
309 #[must_use]
311 pub fn new() -> Self {
312 Self::default()
313 }
314
315 #[must_use]
317 pub fn kind(mut self, kind: impl IntoOption<ToolKind>) -> Self {
318 self.kind = kind.into_option();
319 self
320 }
321
322 #[must_use]
324 pub fn status(mut self, status: impl IntoOption<ToolCallStatus>) -> Self {
325 self.status = status.into_option();
326 self
327 }
328
329 #[must_use]
331 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
332 self.title = title.into_option();
333 self
334 }
335
336 #[must_use]
338 pub fn name(mut self, name: impl IntoOption<String>) -> Self {
339 self.name = name.into_option();
340 self
341 }
342
343 #[must_use]
345 pub fn content(mut self, content: impl IntoOption<Vec<ToolCallContent>>) -> Self {
346 self.content = content.into_option();
347 self
348 }
349
350 #[must_use]
352 pub fn locations(mut self, locations: impl IntoOption<Vec<ToolCallLocation>>) -> Self {
353 self.locations = locations.into_option();
354 self
355 }
356
357 #[must_use]
359 pub fn raw_input(mut self, raw_input: impl IntoOption<serde_json::Value>) -> Self {
360 self.raw_input = raw_input.into_option();
361 self
362 }
363
364 #[must_use]
366 pub fn raw_output(mut self, raw_output: impl IntoOption<serde_json::Value>) -> Self {
367 self.raw_output = raw_output.into_option();
368 self
369 }
370}
371
372impl TryFrom<ToolCallUpdate> for ToolCall {
375 type Error = Error;
376
377 fn try_from(update: ToolCallUpdate) -> Result<Self, Self::Error> {
378 let ToolCallUpdate {
379 tool_call_id,
380 fields:
381 ToolCallUpdateFields {
382 kind,
383 status,
384 title,
385 name,
386 content,
387 locations,
388 raw_input,
389 raw_output,
390 },
391 meta,
392 } = update;
393
394 Ok(Self {
395 tool_call_id,
396 title: title.ok_or_else(|| {
397 Error::invalid_params().data(serde_json::json!("title is required for a tool call"))
398 })?,
399 name,
400 kind: kind.unwrap_or_default(),
401 status: status.unwrap_or_default(),
402 content: content.unwrap_or_default(),
403 locations: locations.unwrap_or_default(),
404 raw_input,
405 raw_output,
406 meta,
407 })
408 }
409}
410
411impl From<ToolCall> for ToolCallUpdate {
412 fn from(value: ToolCall) -> Self {
413 let ToolCall {
414 tool_call_id,
415 title,
416 name,
417 kind,
418 status,
419 content,
420 locations,
421 raw_input,
422 raw_output,
423 meta,
424 } = value;
425 Self {
426 tool_call_id,
427 fields: ToolCallUpdateFields {
428 kind: Some(kind),
429 status: Some(status),
430 title: Some(title),
431 name,
432 content: Some(content),
433 locations: Some(locations),
434 raw_input,
435 raw_output,
436 },
437 meta,
438 }
439 }
440}
441
442#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
444#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
445#[serde(transparent)]
446#[from(Arc<str>, String, &'static str)]
447#[non_exhaustive]
448pub struct ToolCallId(pub Arc<str>);
449
450impl ToolCallId {
451 #[must_use]
453 pub fn new(id: impl Into<Arc<str>>) -> Self {
454 Self(id.into())
455 }
456}
457
458impl IntoOption<ToolCallId> for &str {
459 fn into_option(self) -> Option<ToolCallId> {
460 Some(ToolCallId::new(self))
461 }
462}
463
464#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
471#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
472#[serde(rename_all = "snake_case")]
473#[non_exhaustive]
474pub enum ToolKind {
475 Read,
477 Edit,
479 Delete,
481 Move,
483 Search,
485 Execute,
487 Think,
489 Fetch,
491 SwitchMode,
493 #[default]
495 #[serde(other)]
496 Other,
497}
498
499impl ToolKind {
500 #[expect(clippy::trivially_copy_pass_by_ref, reason = "Required by serde")]
501 fn is_default(&self) -> bool {
502 matches!(self, ToolKind::Other)
503 }
504}
505
506#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
512#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
513#[serde(rename_all = "snake_case")]
514#[non_exhaustive]
515pub enum ToolCallStatus {
516 #[default]
519 Pending,
520 InProgress,
522 Completed,
524 Failed,
526}
527
528impl ToolCallStatus {
529 #[expect(clippy::trivially_copy_pass_by_ref, reason = "Required by serde")]
530 fn is_default(&self) -> bool {
531 matches!(self, ToolCallStatus::Pending)
532 }
533}
534
535#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
542#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
543#[serde(tag = "type", rename_all = "snake_case")]
544#[cfg_attr(feature = "schemars", schemars(extend("discriminator" = {"propertyName": "type"})))]
545#[non_exhaustive]
546#[expect(clippy::large_enum_variant)]
547pub enum ToolCallContent {
548 Content(Content),
550 Diff(Diff),
552 Terminal(Terminal),
558 Session(SessionReference),
565}
566
567impl<T: Into<ContentBlock>> From<T> for ToolCallContent {
568 fn from(content: T) -> Self {
569 ToolCallContent::Content(Content::new(content))
570 }
571}
572
573impl From<Diff> for ToolCallContent {
574 fn from(diff: Diff) -> Self {
575 ToolCallContent::Diff(diff)
576 }
577}
578
579#[serde_as]
587#[skip_serializing_none]
588#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
589#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
590#[serde(rename_all = "camelCase")]
591#[non_exhaustive]
592pub struct SessionReference {
593 pub session_id: SessionId,
595 #[serde_as(deserialize_as = "DefaultOnError")]
601 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
602 #[serde(default)]
603 #[serde(rename = "_meta")]
604 pub meta: Option<Meta>,
605}
606
607impl SessionReference {
608 #[must_use]
610 pub fn new(session_id: impl Into<SessionId>) -> Self {
611 Self {
612 session_id: session_id.into(),
613 meta: None,
614 }
615 }
616
617 #[must_use]
620 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
621 self.meta = meta.into_option();
622 self
623 }
624}
625
626impl From<SessionReference> for ToolCallContent {
627 fn from(session: SessionReference) -> Self {
628 ToolCallContent::Session(session)
629 }
630}
631
632#[serde_as]
634#[skip_serializing_none]
635#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
636#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
637#[serde(rename_all = "camelCase")]
638#[non_exhaustive]
639pub struct Content {
640 pub content: ContentBlock,
642 #[serde_as(deserialize_as = "DefaultOnError")]
648 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
649 #[serde(default)]
650 #[serde(rename = "_meta")]
651 pub meta: Option<Meta>,
652}
653
654impl Content {
655 #[must_use]
657 pub fn new(content: impl Into<ContentBlock>) -> Self {
658 Self {
659 content: content.into(),
660 meta: None,
661 }
662 }
663
664 #[must_use]
670 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
671 self.meta = meta.into_option();
672 self
673 }
674}
675
676#[serde_as]
682#[skip_serializing_none]
683#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
684#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
685#[serde(rename_all = "camelCase")]
686#[non_exhaustive]
687pub struct Terminal {
688 pub terminal_id: TerminalId,
690 #[serde_as(deserialize_as = "DefaultOnError")]
696 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
697 #[serde(default)]
698 #[serde(rename = "_meta")]
699 pub meta: Option<Meta>,
700}
701
702impl Terminal {
703 #[must_use]
705 pub fn new(terminal_id: impl Into<TerminalId>) -> Self {
706 Self {
707 terminal_id: terminal_id.into(),
708 meta: None,
709 }
710 }
711
712 #[must_use]
718 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
719 self.meta = meta.into_option();
720 self
721 }
722}
723
724#[serde_as]
730#[skip_serializing_none]
731#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
732#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
733#[serde(rename_all = "camelCase")]
734#[non_exhaustive]
735pub struct Diff {
736 pub path: PathBuf,
738 #[serde_as(deserialize_as = "DefaultOnError")]
740 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
741 #[serde(default)]
742 pub old_text: Option<String>,
743 pub new_text: String,
745 #[serde_as(deserialize_as = "DefaultOnError")]
751 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
752 #[serde(default)]
753 #[serde(rename = "_meta")]
754 pub meta: Option<Meta>,
755}
756
757impl Diff {
758 #[must_use]
760 pub fn new(path: impl Into<PathBuf>, new_text: impl Into<String>) -> Self {
761 Self {
762 path: path.into(),
763 old_text: None,
764 new_text: new_text.into(),
765 meta: None,
766 }
767 }
768
769 #[must_use]
771 pub fn old_text(mut self, old_text: impl IntoOption<String>) -> Self {
772 self.old_text = old_text.into_option();
773 self
774 }
775
776 #[must_use]
782 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
783 self.meta = meta.into_option();
784 self
785 }
786}
787
788#[serde_as]
795#[skip_serializing_none]
796#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
797#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
798#[serde(rename_all = "camelCase")]
799#[non_exhaustive]
800pub struct ToolCallLocation {
801 pub path: PathBuf,
803 #[serde_as(deserialize_as = "DefaultOnError")]
805 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
806 #[serde(default)]
807 pub line: Option<u32>,
808 #[serde_as(deserialize_as = "DefaultOnError")]
814 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
815 #[serde(default)]
816 #[serde(rename = "_meta")]
817 pub meta: Option<Meta>,
818}
819
820impl ToolCallLocation {
821 #[must_use]
823 pub fn new(path: impl Into<PathBuf>) -> Self {
824 Self {
825 path: path.into(),
826 line: None,
827 meta: None,
828 }
829 }
830
831 #[must_use]
833 pub fn line(mut self, line: impl IntoOption<u32>) -> Self {
834 self.line = line.into_option();
835 self
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(test)]
851mod tests {
852
853 #[test]
854 fn session_reference_tool_call_content_round_trips() {
855 use serde_json::json;
856 let content = ToolCallContent::from(SessionReference::new("sess_child_1"));
857 let value = serde_json::to_value(&content).unwrap();
858 assert_eq!(
859 value,
860 json!({ "type": "session", "sessionId": "sess_child_1" })
861 );
862 assert_eq!(
863 serde_json::from_value::<ToolCallContent>(value).unwrap(),
864 content
865 );
866 }
867 use super::*;
868
869 #[test]
870 fn tool_call_name_is_optional_and_null_is_equivalent_to_omission() {
871 let named = ToolCall::new("tc_1", "Reading configuration").name("read_file");
872 assert_eq!(
873 serde_json::to_value(named).unwrap(),
874 serde_json::json!({
875 "toolCallId": "tc_1",
876 "title": "Reading configuration",
877 "name": "read_file"
878 })
879 );
880
881 let unnamed = ToolCall::new("tc_1", "Reading configuration");
882 assert_eq!(unnamed.name, None);
883 assert_eq!(
884 serde_json::to_value(unnamed).unwrap(),
885 serde_json::json!({
886 "toolCallId": "tc_1",
887 "title": "Reading configuration"
888 })
889 );
890
891 let from_null: ToolCall = serde_json::from_value(serde_json::json!({
892 "toolCallId": "tc_1",
893 "title": "Reading configuration",
894 "name": null
895 }))
896 .unwrap();
897 assert_eq!(from_null.name, None);
898 }
899
900 #[test]
901 fn tool_call_name_update_replaces_a_name_but_cannot_clear_it() {
902 let mut stored = ToolCall::new("tc_1", "Reading configuration").name("read_file");
903
904 stored.update(ToolCallUpdateFields::new());
905 assert_eq!(stored.name.as_deref(), Some("read_file"));
906
907 let null_update: ToolCallUpdateFields =
908 serde_json::from_value(serde_json::json!({"name": null})).unwrap();
909 stored.update(null_update);
910 assert_eq!(stored.name.as_deref(), Some("read_file"));
911
912 stored.update(ToolCallUpdateFields::new().name("read_many_files"));
913 assert_eq!(stored.name.as_deref(), Some("read_many_files"));
914 }
915
916 #[test]
917 fn tool_call_name_survives_v1_upsert_conversion() {
918 let tool_call = ToolCall::new("tc_1", "Reading configuration").name("read_file");
919
920 let update = ToolCallUpdate::from(tool_call.clone());
921 assert_eq!(update.fields.name.as_deref(), Some("read_file"));
922
923 let rebuilt = ToolCall::try_from(update).unwrap();
924 assert_eq!(rebuilt, tool_call);
925 }
926}