1use std::{borrow::Cow, collections::BTreeMap, sync::Arc};
7
8#[cfg(feature = "unstable_llm_providers")]
9use std::collections::HashMap;
10
11use derive_more::{Display, From};
12#[cfg(feature = "schemars")]
13use schemars::Schema;
14use serde::{Deserialize, Serialize};
15use serde_with::{DefaultOnError, DefaultOnNull, VecSkipError, serde_as, skip_serializing_none};
16
17use super::{
18 AbsolutePath, AvailableCommand, ClientCapabilities, ContentBlock, Error, ExtNotification,
19 ExtRequest, ExtResponse, MessageId, Meta, SessionId, TerminalId, ToolCallId,
20};
21use crate::{IntoOption, ProtocolVersion};
22
23#[cfg(all(
24 feature = "unstable_session_fork",
25 feature = "unstable_session_cursors"
26))]
27use super::CursorId;
28#[cfg(feature = "unstable_session_status")]
29use super::StateUpdate;
30
31#[cfg(all(feature = "unstable_auth_status", feature = "schemars"))]
32use super::AUTH_STATUS_UPDATE_NOTIFICATION;
33#[cfg(feature = "unstable_mcp_over_acp")]
34use super::mcp::{MCP_MESSAGE_METHOD_NAME, MessageMcpNotification};
35
36#[serde_as]
44#[skip_serializing_none]
45#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
46#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
47#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = INITIALIZE_METHOD_NAME)))]
48#[serde(rename_all = "camelCase")]
49#[non_exhaustive]
50pub struct InitializeRequest {
51 pub protocol_version: ProtocolVersion,
53 pub info: Implementation,
55 #[serde_as(deserialize_as = "DefaultOnError")]
57 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
58 #[serde(default)]
59 pub capabilities: ClientCapabilities,
60 #[serde_as(deserialize_as = "DefaultOnError")]
66 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
67 #[serde(default)]
68 #[serde(rename = "_meta")]
69 pub meta: Option<Meta>,
70}
71
72impl InitializeRequest {
73 #[must_use]
75 pub fn new(protocol_version: ProtocolVersion, info: Implementation) -> Self {
76 Self {
77 protocol_version,
78 capabilities: ClientCapabilities::default(),
79 info,
80 meta: None,
81 }
82 }
83
84 #[must_use]
86 pub fn capabilities(mut self, capabilities: ClientCapabilities) -> Self {
87 self.capabilities = capabilities;
88 self
89 }
90
91 #[must_use]
97 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
98 self.meta = meta.into_option();
99 self
100 }
101}
102
103#[serde_as]
109#[skip_serializing_none]
110#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
111#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
112#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = INITIALIZE_METHOD_NAME)))]
113#[serde(rename_all = "camelCase")]
114#[non_exhaustive]
115pub struct InitializeResponse {
116 pub protocol_version: ProtocolVersion,
123 pub info: Implementation,
125 #[serde_as(deserialize_as = "DefaultOnError")]
127 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
128 #[serde(default)]
129 pub capabilities: AgentCapabilities,
130 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
136 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
137 #[serde(default, skip_serializing_if = "Vec::is_empty")]
138 pub auth_methods: Vec<AuthMethod>,
139 #[serde_as(deserialize_as = "DefaultOnError")]
145 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
146 #[serde(default)]
147 #[serde(rename = "_meta")]
148 pub meta: Option<Meta>,
149}
150
151impl InitializeResponse {
152 #[must_use]
154 pub fn new(protocol_version: ProtocolVersion, info: Implementation) -> Self {
155 Self {
156 protocol_version,
157 capabilities: AgentCapabilities::default(),
158 auth_methods: vec![],
159 info,
160 meta: None,
161 }
162 }
163
164 #[must_use]
166 pub fn capabilities(mut self, capabilities: AgentCapabilities) -> Self {
167 self.capabilities = capabilities;
168 self
169 }
170
171 #[must_use]
176 pub fn auth_methods(mut self, auth_methods: Vec<AuthMethod>) -> Self {
177 self.auth_methods = auth_methods;
178 self
179 }
180
181 #[must_use]
187 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
188 self.meta = meta.into_option();
189 self
190 }
191}
192
193#[serde_as]
197#[skip_serializing_none]
198#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
199#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
200#[serde(rename_all = "camelCase")]
201#[non_exhaustive]
202pub struct Implementation {
203 pub name: String,
206 #[serde_as(deserialize_as = "DefaultOnError")]
213 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
214 #[serde(default)]
215 pub title: Option<String>,
216 pub version: String,
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 Implementation {
232 #[must_use]
234 pub fn new(name: impl Into<String>, version: impl Into<String>) -> Self {
235 Self {
236 name: name.into(),
237 title: None,
238 version: version.into(),
239 meta: None,
240 }
241 }
242
243 #[must_use]
248 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
249 self.title = title.into_option();
250 self
251 }
252
253 #[must_use]
259 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
260 self.meta = meta.into_option();
261 self
262 }
263}
264
265#[serde_as]
275#[skip_serializing_none]
276#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
277#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
278#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGIN_METHOD_NAME)))]
279#[serde(rename_all = "camelCase")]
280#[non_exhaustive]
281pub struct LoginAuthRequest {
282 pub method_id: AuthMethodId,
285 #[serde_as(deserialize_as = "DefaultOnError")]
291 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
292 #[serde(default)]
293 #[serde(rename = "_meta")]
294 pub meta: Option<Meta>,
295}
296
297impl LoginAuthRequest {
298 #[must_use]
300 pub fn new(method_id: impl Into<AuthMethodId>) -> Self {
301 Self {
302 method_id: method_id.into(),
303 meta: None,
304 }
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
319crate::serde_util::default_on_null! {
320 #[serde_as]
322 #[skip_serializing_none]
323 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
324 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
325 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGIN_METHOD_NAME)))]
326 #[serde(rename_all = "camelCase")]
327 #[non_exhaustive]
328 pub struct LoginAuthResponse {
329 #[serde_as(deserialize_as = "DefaultOnError")]
335 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
336 #[serde(default)]
337 #[serde(rename = "_meta")]
338 pub meta: Option<Meta>,
339 }
340}
341
342impl LoginAuthResponse {
343 #[must_use]
345 pub fn new() -> Self {
346 Self::default()
347 }
348
349 #[must_use]
355 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
356 self.meta = meta.into_option();
357 self
358 }
359}
360
361crate::serde_util::default_on_null! {
364 #[serde_as]
372 #[skip_serializing_none]
373 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
374 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
375 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGOUT_METHOD_NAME)))]
376 #[serde(rename_all = "camelCase")]
377 #[non_exhaustive]
378 pub struct LogoutAuthRequest {
379 #[serde_as(deserialize_as = "DefaultOnError")]
385 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
386 #[serde(default)]
387 #[serde(rename = "_meta")]
388 pub meta: Option<Meta>,
389 }
390}
391
392impl LogoutAuthRequest {
393 #[must_use]
395 pub fn new() -> Self {
396 Self::default()
397 }
398
399 #[must_use]
405 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
406 self.meta = meta.into_option();
407 self
408 }
409}
410
411crate::serde_util::default_on_null! {
412 #[serde_as]
414 #[skip_serializing_none]
415 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
416 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
417 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGOUT_METHOD_NAME)))]
418 #[serde(rename_all = "camelCase")]
419 #[non_exhaustive]
420 pub struct LogoutAuthResponse {
421 #[serde_as(deserialize_as = "DefaultOnError")]
427 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
428 #[serde(default)]
429 #[serde(rename = "_meta")]
430 pub meta: Option<Meta>,
431 }
432}
433
434impl LogoutAuthResponse {
435 #[must_use]
437 pub fn new() -> Self {
438 Self::default()
439 }
440
441 #[must_use]
447 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
448 self.meta = meta.into_option();
449 self
450 }
451}
452
453#[cfg(feature = "unstable_auth_status")]
456crate::serde_util::default_on_null! {
457 #[serde_as]
468 #[skip_serializing_none]
469 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
470 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
471 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_STATUS_METHOD_NAME)))]
472 #[serde(rename_all = "camelCase")]
473 #[non_exhaustive]
474 pub struct AuthStatusRequest {
475 #[serde_as(deserialize_as = "DefaultOnError")]
481 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
482 #[serde(default)]
483 #[serde(rename = "_meta")]
484 pub meta: Option<Meta>,
485 }
486}
487
488#[cfg(feature = "unstable_auth_status")]
489impl AuthStatusRequest {
490 #[must_use]
492 pub fn new() -> Self {
493 Self::default()
494 }
495
496 #[must_use]
502 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
503 self.meta = meta.into_option();
504 self
505 }
506}
507
508#[cfg(feature = "unstable_auth_status")]
514#[serde_as]
515#[skip_serializing_none]
516#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
517#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
518#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_STATUS_METHOD_NAME)))]
519#[serde(rename_all = "camelCase")]
520#[non_exhaustive]
521pub struct AuthStatusResponse {
522 pub state: AuthState,
527 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
533 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
534 #[serde(default, skip_serializing_if = "Vec::is_empty")]
535 pub accounts: Vec<AuthAccount>,
536 #[serde_as(deserialize_as = "DefaultOnError")]
542 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
543 #[serde(default)]
544 #[serde(rename = "_meta")]
545 pub meta: Option<Meta>,
546}
547
548#[cfg(feature = "unstable_auth_status")]
549impl AuthStatusResponse {
550 #[must_use]
552 pub fn new(state: AuthState) -> Self {
553 Self {
554 state,
555 accounts: vec![],
556 meta: None,
557 }
558 }
559
560 #[must_use]
562 pub fn accounts(mut self, accounts: Vec<AuthAccount>) -> Self {
563 self.accounts = accounts;
564 self
565 }
566
567 #[must_use]
573 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
574 self.meta = meta.into_option();
575 self
576 }
577}
578
579#[cfg(feature = "unstable_auth_status")]
589#[serde_as]
590#[skip_serializing_none]
591#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
592#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
593#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = AUTH_STATUS_UPDATE_NOTIFICATION)))]
594#[serde(rename_all = "camelCase")]
595#[non_exhaustive]
596pub struct AuthStatusUpdateNotification {
597 pub state: AuthState,
602 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
608 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
609 #[serde(default, skip_serializing_if = "Vec::is_empty")]
610 pub accounts: Vec<AuthAccount>,
611 #[serde_as(deserialize_as = "DefaultOnError")]
617 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
618 #[serde(default)]
619 #[serde(rename = "_meta")]
620 pub meta: Option<Meta>,
621}
622
623#[cfg(feature = "unstable_auth_status")]
624impl AuthStatusUpdateNotification {
625 #[must_use]
627 pub fn new(state: AuthState) -> Self {
628 Self {
629 state,
630 accounts: vec![],
631 meta: None,
632 }
633 }
634
635 #[must_use]
637 pub fn accounts(mut self, accounts: Vec<AuthAccount>) -> Self {
638 self.accounts = accounts;
639 self
640 }
641
642 #[must_use]
648 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
649 self.meta = meta.into_option();
650 self
651 }
652}
653
654#[cfg(feature = "unstable_auth_status")]
660#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
661#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
662#[serde(rename_all = "snake_case")]
663#[non_exhaustive]
664pub enum AuthState {
665 Authenticated,
667 Unauthenticated,
670 NotRequired,
672 Unknown,
674 #[serde(untagged)]
680 Other(String),
681}
682
683#[cfg(feature = "unstable_auth_status")]
694#[serde_as]
695#[skip_serializing_none]
696#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
697#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
698#[serde(rename_all = "camelCase")]
699#[non_exhaustive]
700pub struct AuthAccount {
701 pub label: String,
704 #[serde_as(deserialize_as = "DefaultOnError")]
709 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
710 #[serde(default)]
711 pub description: Option<String>,
712 #[serde_as(deserialize_as = "DefaultOnError")]
718 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
719 #[serde(default)]
720 pub active: Option<bool>,
721 #[serde_as(deserialize_as = "DefaultOnError")]
725 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
726 #[serde(default)]
727 pub name: Option<String>,
728 #[serde_as(deserialize_as = "DefaultOnError")]
732 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
733 #[serde(default)]
734 pub email: Option<String>,
735 #[serde_as(deserialize_as = "DefaultOnError")]
739 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
740 #[serde(default)]
741 pub organization: Option<String>,
742 #[serde_as(deserialize_as = "DefaultOnError")]
748 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
749 #[serde(default)]
750 #[serde(rename = "_meta")]
751 pub meta: Option<Meta>,
752}
753
754#[cfg(feature = "unstable_auth_status")]
755impl AuthAccount {
756 #[must_use]
758 pub fn new(label: impl Into<String>) -> Self {
759 Self {
760 label: label.into(),
761 description: None,
762 active: None,
763 name: None,
764 email: None,
765 organization: None,
766 meta: None,
767 }
768 }
769
770 #[must_use]
772 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
773 self.description = description.into_option();
774 self
775 }
776
777 #[must_use]
779 pub fn active(mut self, active: impl IntoOption<bool>) -> Self {
780 self.active = active.into_option();
781 self
782 }
783
784 #[must_use]
786 pub fn name(mut self, name: impl IntoOption<String>) -> Self {
787 self.name = name.into_option();
788 self
789 }
790
791 #[must_use]
793 pub fn email(mut self, email: impl IntoOption<String>) -> Self {
794 self.email = email.into_option();
795 self
796 }
797
798 #[must_use]
800 pub fn organization(mut self, organization: impl IntoOption<String>) -> Self {
801 self.organization = organization.into_option();
802 self
803 }
804
805 #[must_use]
811 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
812 self.meta = meta.into_option();
813 self
814 }
815}
816
817#[cfg(feature = "unstable_auth_status")]
825#[serde_as]
826#[skip_serializing_none]
827#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
828#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
829#[non_exhaustive]
830pub struct AuthStatusCapabilities {
831 #[serde_as(deserialize_as = "DefaultOnError")]
837 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
838 #[serde(default)]
839 #[serde(rename = "_meta")]
840 pub meta: Option<Meta>,
841}
842
843#[cfg(feature = "unstable_auth_status")]
844impl AuthStatusCapabilities {
845 #[must_use]
847 pub fn new() -> Self {
848 Self::default()
849 }
850
851 #[must_use]
857 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
858 self.meta = meta.into_option();
859 self
860 }
861}
862
863#[serde_as]
869#[skip_serializing_none]
870#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
871#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
872#[serde(rename_all = "camelCase")]
873#[non_exhaustive]
874pub struct AgentAuthCapabilities {
875 #[cfg(feature = "unstable_auth_status")]
884 #[serde_as(deserialize_as = "DefaultOnError")]
885 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
886 #[serde(default)]
887 pub status: Option<AuthStatusCapabilities>,
888 #[serde_as(deserialize_as = "DefaultOnError")]
894 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
895 #[serde(default)]
896 #[serde(rename = "_meta")]
897 pub meta: Option<Meta>,
898}
899
900impl AgentAuthCapabilities {
901 #[must_use]
903 pub fn new() -> Self {
904 Self::default()
905 }
906
907 #[cfg(feature = "unstable_auth_status")]
913 #[must_use]
914 pub fn status(mut self, status: impl IntoOption<AuthStatusCapabilities>) -> Self {
915 self.status = status.into_option();
916 self
917 }
918
919 #[must_use]
925 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
926 self.meta = meta.into_option();
927 self
928 }
929}
930
931#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
933#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
934#[serde(transparent)]
935#[from(forward)]
936#[non_exhaustive]
937pub struct AuthMethodId(pub Arc<str>);
938
939impl AuthMethodId {
940 #[must_use]
942 pub fn new(id: impl Into<Self>) -> Self {
943 id.into()
944 }
945}
946
947#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
951#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
952#[serde(tag = "type", rename_all = "snake_case")]
953#[non_exhaustive]
954pub enum AuthMethod {
955 Terminal(AuthMethodTerminal),
958 Agent(AuthMethodAgent),
962 #[serde(untagged)]
972 Other(OtherAuthMethod),
973}
974
975impl AuthMethod {
976 #[must_use]
978 pub fn method_id(&self) -> &AuthMethodId {
979 match self {
980 Self::Agent(a) => &a.method_id,
981 Self::Other(a) => &a.method_id,
982 Self::Terminal(t) => &t.method_id,
983 }
984 }
985
986 #[must_use]
988 pub fn name(&self) -> &str {
989 match self {
990 Self::Agent(a) => &a.name,
991 Self::Other(a) => &a.name,
992 Self::Terminal(t) => &t.name,
993 }
994 }
995
996 #[must_use]
998 pub fn description(&self) -> Option<&str> {
999 match self {
1000 Self::Agent(a) => a.description.as_deref(),
1001 Self::Other(a) => a
1002 .fields
1003 .get("description")
1004 .and_then(serde_json::Value::as_str),
1005 Self::Terminal(t) => t.description.as_deref(),
1006 }
1007 }
1008
1009 #[must_use]
1015 pub fn meta(&self) -> Option<&Meta> {
1016 match self {
1017 Self::Agent(a) => a.meta.as_ref(),
1018 Self::Other(a) => a.fields.get("_meta").and_then(serde_json::Value::as_object),
1019 Self::Terminal(t) => t.meta.as_ref(),
1020 }
1021 }
1022}
1023
1024#[serde_as]
1026#[skip_serializing_none]
1027#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1028#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1029#[cfg_attr(feature = "schemars", schemars(inline))]
1030#[cfg_attr(feature = "schemars", schemars(transform = other_auth_method_schema))]
1031#[serde(rename_all = "camelCase")]
1032#[non_exhaustive]
1033pub struct OtherAuthMethod {
1034 #[serde(rename = "type")]
1040 pub type_: String,
1041 pub method_id: AuthMethodId,
1043 pub name: String,
1045 #[serde(flatten)]
1048 pub fields: BTreeMap<String, serde_json::Value>,
1049}
1050
1051impl OtherAuthMethod {
1052 #[must_use]
1054 pub fn new(
1055 type_: impl Into<String>,
1056 method_id: impl Into<AuthMethodId>,
1057 name: impl Into<String>,
1058 mut fields: BTreeMap<String, serde_json::Value>,
1059 ) -> Self {
1060 fields.remove("type");
1061 fields.remove("methodId");
1062 fields.remove("name");
1063 Self {
1064 type_: type_.into(),
1065 method_id: method_id.into(),
1066 name: name.into(),
1067 fields,
1068 }
1069 }
1070}
1071
1072impl<'de> Deserialize<'de> for OtherAuthMethod {
1073 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1074 where
1075 D: serde::Deserializer<'de>,
1076 {
1077 #[derive(Deserialize)]
1078 #[serde(rename_all = "camelCase")]
1079 struct RawOtherAuthMethod {
1080 #[serde(rename = "type")]
1081 type_: String,
1082 method_id: AuthMethodId,
1083 name: String,
1084 #[serde(flatten)]
1085 fields: BTreeMap<String, serde_json::Value>,
1086 }
1087
1088 let raw = RawOtherAuthMethod::deserialize(deserializer)?;
1089 if is_known_auth_method_type(&raw.type_) {
1090 return Err(serde::de::Error::custom(format!(
1091 "known authentication method `{}` did not match its schema",
1092 raw.type_
1093 )));
1094 }
1095
1096 Ok(Self {
1097 type_: raw.type_,
1098 method_id: raw.method_id,
1099 name: raw.name,
1100 fields: raw.fields,
1101 })
1102 }
1103}
1104
1105fn is_known_auth_method_type(type_: &str) -> bool {
1106 matches!(type_, "agent" | "terminal")
1107}
1108
1109#[cfg(feature = "schemars")]
1110fn other_auth_method_schema(schema: &mut Schema) {
1111 super::schema_util::reject_known_string_discriminators(schema, "type", &["agent", "terminal"]);
1112}
1113
1114#[serde_as]
1118#[skip_serializing_none]
1119#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1120#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1121#[serde(rename_all = "camelCase")]
1122#[non_exhaustive]
1123pub struct AuthMethodAgent {
1124 pub method_id: AuthMethodId,
1126 pub name: String,
1128 #[serde_as(deserialize_as = "DefaultOnError")]
1132 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1133 #[serde(default)]
1134 pub description: Option<String>,
1135 #[serde_as(deserialize_as = "DefaultOnError")]
1141 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1142 #[serde(default)]
1143 #[serde(rename = "_meta")]
1144 pub meta: Option<Meta>,
1145}
1146
1147impl AuthMethodAgent {
1148 #[must_use]
1150 pub fn new(method_id: impl Into<AuthMethodId>, name: impl Into<String>) -> Self {
1151 Self {
1152 method_id: method_id.into(),
1153 name: name.into(),
1154 description: None,
1155 meta: None,
1156 }
1157 }
1158
1159 #[must_use]
1161 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
1162 self.description = description.into_option();
1163 self
1164 }
1165
1166 #[must_use]
1172 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1173 self.meta = meta.into_option();
1174 self
1175 }
1176}
1177
1178#[serde_as]
1186#[skip_serializing_none]
1187#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1188#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1189#[serde(rename_all = "camelCase")]
1190#[non_exhaustive]
1191pub struct AuthMethodTerminal {
1192 pub method_id: AuthMethodId,
1194 pub name: String,
1196 #[serde_as(deserialize_as = "DefaultOnError")]
1200 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1201 #[serde(default)]
1202 pub description: Option<String>,
1203 #[serde_as(deserialize_as = "DefaultOnNull")]
1205 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1206 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1207 pub args: Vec<String>,
1208 #[serde_as(deserialize_as = "DefaultOnNull")]
1212 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1213 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1214 pub env: Vec<EnvVariable>,
1215 #[serde_as(deserialize_as = "DefaultOnError")]
1221 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1222 #[serde(default)]
1223 #[serde(rename = "_meta")]
1224 pub meta: Option<Meta>,
1225}
1226
1227impl AuthMethodTerminal {
1228 #[must_use]
1230 pub fn new(method_id: impl Into<AuthMethodId>, name: impl Into<String>) -> Self {
1231 Self {
1232 method_id: method_id.into(),
1233 name: name.into(),
1234 description: None,
1235 args: Vec::new(),
1236 env: Vec::new(),
1237 meta: None,
1238 }
1239 }
1240
1241 #[must_use]
1243 pub fn args(mut self, args: Vec<String>) -> Self {
1244 self.args = args;
1245 self
1246 }
1247
1248 #[must_use]
1252 pub fn env(mut self, env: Vec<EnvVariable>) -> Self {
1253 self.env = env;
1254 self
1255 }
1256
1257 #[must_use]
1259 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
1260 self.description = description.into_option();
1261 self
1262 }
1263
1264 #[must_use]
1270 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1271 self.meta = meta.into_option();
1272 self
1273 }
1274}
1275
1276#[serde_as]
1282#[skip_serializing_none]
1283#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1284#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1285#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_NEW_METHOD_NAME)))]
1286#[serde(rename_all = "camelCase")]
1287#[non_exhaustive]
1288pub struct NewSessionRequest {
1289 pub cwd: AbsolutePath,
1291 #[serde_as(deserialize_as = "DefaultOnNull")]
1297 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1298 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1299 pub additional_directories: Vec<AbsolutePath>,
1300 #[serde_as(deserialize_as = "DefaultOnNull")]
1302 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1303 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1304 pub mcp_servers: Vec<McpServer>,
1305 #[serde(default)]
1311 pub system_prompt: Option<SystemPrompt>,
1312 #[cfg(feature = "unstable_session_options")]
1330 #[serde_as(deserialize_as = "DefaultOnNull")]
1331 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1332 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1333 pub config_options: Vec<InitialSessionConfigOption>,
1334 #[serde_as(deserialize_as = "DefaultOnError")]
1340 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1341 #[serde(default)]
1342 #[serde(rename = "_meta")]
1343 pub meta: Option<Meta>,
1344}
1345
1346impl NewSessionRequest {
1347 #[must_use]
1349 pub fn new(cwd: impl Into<AbsolutePath>) -> Self {
1350 Self {
1351 cwd: cwd.into(),
1352 additional_directories: vec![],
1353 mcp_servers: vec![],
1354 system_prompt: None,
1355 #[cfg(feature = "unstable_session_options")]
1356 config_options: vec![],
1357 meta: None,
1358 }
1359 }
1360
1361 #[must_use]
1363 pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1364 where
1365 I: IntoIterator<Item = P>,
1366 P: Into<AbsolutePath>,
1367 {
1368 self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1369 self
1370 }
1371
1372 #[must_use]
1374 pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1375 self.mcp_servers = mcp_servers;
1376 self
1377 }
1378
1379 #[must_use]
1381 pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1382 self.system_prompt = system_prompt.into_option();
1383 self
1384 }
1385
1386 #[cfg(feature = "unstable_session_options")]
1404 #[must_use]
1405 pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1406 self.config_options = config_options;
1407 self
1408 }
1409
1410 #[must_use]
1416 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1417 self.meta = meta.into_option();
1418 self
1419 }
1420}
1421
1422#[serde_as]
1430#[skip_serializing_none]
1431#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1432#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1433#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_NEW_METHOD_NAME)))]
1434#[serde(rename_all = "camelCase")]
1435#[non_exhaustive]
1436pub struct NewSessionResponse {
1437 pub session_id: SessionId,
1441 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1447 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1448 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1449 pub config_options: Vec<SessionConfigOption>,
1450 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1456 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1457 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1458 pub available_commands: Vec<AvailableCommand>,
1459 #[serde_as(deserialize_as = "DefaultOnError")]
1465 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1466 #[serde(default)]
1467 #[serde(rename = "_meta")]
1468 pub meta: Option<Meta>,
1469}
1470
1471impl NewSessionResponse {
1472 #[must_use]
1474 pub fn new(session_id: impl Into<SessionId>) -> Self {
1475 Self {
1476 session_id: session_id.into(),
1477 config_options: Vec::new(),
1478 available_commands: Vec::new(),
1479 meta: None,
1480 }
1481 }
1482
1483 #[must_use]
1489 pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
1490 self.config_options = config_options;
1491 self
1492 }
1493
1494 #[must_use]
1496 pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
1497 self.available_commands = available_commands;
1498 self
1499 }
1500
1501 #[must_use]
1507 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1508 self.meta = meta.into_option();
1509 self
1510 }
1511}
1512
1513#[cfg(feature = "unstable_session_fork")]
1526#[serde_as]
1527#[skip_serializing_none]
1528#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1529#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1530#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_FORK_METHOD_NAME)))]
1531#[serde(rename_all = "camelCase")]
1532#[non_exhaustive]
1533pub struct ForkSessionRequest {
1534 pub session_id: SessionId,
1536 #[cfg(feature = "unstable_session_cursors")]
1549 #[serde(default)]
1550 pub cursor_id: Option<CursorId>,
1551 pub cwd: AbsolutePath,
1553 #[serde_as(deserialize_as = "DefaultOnNull")]
1559 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1560 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1561 pub additional_directories: Vec<AbsolutePath>,
1562 #[serde_as(deserialize_as = "DefaultOnNull")]
1564 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1565 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1566 pub mcp_servers: Vec<McpServer>,
1567 #[serde(default)]
1575 pub system_prompt: Option<SystemPrompt>,
1576 #[cfg(feature = "unstable_session_options")]
1595 #[serde_as(deserialize_as = "DefaultOnNull")]
1596 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1597 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1598 pub config_options: Vec<InitialSessionConfigOption>,
1599 #[serde_as(deserialize_as = "DefaultOnError")]
1605 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1606 #[serde(default)]
1607 #[serde(rename = "_meta")]
1608 pub meta: Option<Meta>,
1609}
1610
1611#[cfg(feature = "unstable_session_fork")]
1612impl ForkSessionRequest {
1613 #[must_use]
1615 pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
1616 Self {
1617 session_id: session_id.into(),
1618 #[cfg(feature = "unstable_session_cursors")]
1619 cursor_id: None,
1620 cwd: cwd.into(),
1621 additional_directories: vec![],
1622 mcp_servers: vec![],
1623 system_prompt: None,
1624 #[cfg(feature = "unstable_session_options")]
1625 config_options: vec![],
1626 meta: None,
1627 }
1628 }
1629
1630 #[cfg(feature = "unstable_session_cursors")]
1639 #[must_use]
1640 pub fn cursor_id(mut self, cursor_id: impl IntoOption<CursorId>) -> Self {
1641 self.cursor_id = cursor_id.into_option();
1642 self
1643 }
1644
1645 #[must_use]
1647 pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1648 where
1649 I: IntoIterator<Item = P>,
1650 P: Into<AbsolutePath>,
1651 {
1652 self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1653 self
1654 }
1655
1656 #[must_use]
1658 pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1659 self.mcp_servers = mcp_servers;
1660 self
1661 }
1662
1663 #[must_use]
1665 pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1666 self.system_prompt = system_prompt.into_option();
1667 self
1668 }
1669
1670 #[cfg(feature = "unstable_session_options")]
1689 #[must_use]
1690 pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1691 self.config_options = config_options;
1692 self
1693 }
1694
1695 #[must_use]
1701 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1702 self.meta = meta.into_option();
1703 self
1704 }
1705}
1706
1707#[cfg(feature = "unstable_session_fork")]
1713#[serde_as]
1714#[skip_serializing_none]
1715#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1716#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1717#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_FORK_METHOD_NAME)))]
1718#[serde(rename_all = "camelCase")]
1719#[non_exhaustive]
1720pub struct ForkSessionResponse {
1721 pub session_id: SessionId,
1723 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1729 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1730 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1731 pub config_options: Vec<SessionConfigOption>,
1732 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1738 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1739 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1740 pub available_commands: Vec<AvailableCommand>,
1741 #[serde_as(deserialize_as = "DefaultOnError")]
1747 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1748 #[serde(default)]
1749 #[serde(rename = "_meta")]
1750 pub meta: Option<Meta>,
1751}
1752
1753#[cfg(feature = "unstable_session_fork")]
1754impl ForkSessionResponse {
1755 #[must_use]
1757 pub fn new(session_id: impl Into<SessionId>) -> Self {
1758 Self {
1759 session_id: session_id.into(),
1760 config_options: Vec::new(),
1761 available_commands: Vec::new(),
1762 meta: None,
1763 }
1764 }
1765
1766 #[must_use]
1772 pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
1773 self.config_options = config_options;
1774 self
1775 }
1776
1777 #[must_use]
1779 pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
1780 self.available_commands = available_commands;
1781 self
1782 }
1783
1784 #[must_use]
1790 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1791 self.meta = meta.into_option();
1792 self
1793 }
1794}
1795
1796#[serde_as]
1803#[skip_serializing_none]
1804#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1805#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1806#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_RESUME_METHOD_NAME)))]
1807#[serde(rename_all = "camelCase")]
1808#[non_exhaustive]
1809pub struct ResumeSessionRequest {
1810 pub session_id: SessionId,
1812 pub cwd: AbsolutePath,
1817 #[serde_as(deserialize_as = "DefaultOnNull")]
1824 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1825 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1826 pub additional_directories: Vec<AbsolutePath>,
1827 #[serde_as(deserialize_as = "DefaultOnNull")]
1832 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1833 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1834 pub mcp_servers: Vec<McpServer>,
1835 #[serde(default)]
1847 pub replay_from: Option<ReplayFrom>,
1848 #[serde(default)]
1856 pub system_prompt: Option<SystemPrompt>,
1857 #[cfg(feature = "unstable_session_options")]
1878 #[serde_as(deserialize_as = "DefaultOnNull")]
1879 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1880 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1881 pub config_options: Vec<InitialSessionConfigOption>,
1882 #[serde_as(deserialize_as = "DefaultOnError")]
1888 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1889 #[serde(default)]
1890 #[serde(rename = "_meta")]
1891 pub meta: Option<Meta>,
1892}
1893
1894impl ResumeSessionRequest {
1895 #[must_use]
1897 pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
1898 Self {
1899 session_id: session_id.into(),
1900 cwd: cwd.into(),
1901 additional_directories: vec![],
1902 mcp_servers: vec![],
1903 replay_from: None,
1904 system_prompt: None,
1905 #[cfg(feature = "unstable_session_options")]
1906 config_options: vec![],
1907 meta: None,
1908 }
1909 }
1910
1911 #[must_use]
1913 pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1914 where
1915 I: IntoIterator<Item = P>,
1916 P: Into<AbsolutePath>,
1917 {
1918 self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1919 self
1920 }
1921
1922 #[must_use]
1924 pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1925 self.mcp_servers = mcp_servers;
1926 self
1927 }
1928
1929 #[must_use]
1937 pub fn replay_from(mut self, replay_from: impl IntoOption<ReplayFrom>) -> Self {
1938 self.replay_from = replay_from.into_option();
1939 self
1940 }
1941
1942 #[must_use]
1944 pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1945 self.system_prompt = system_prompt.into_option();
1946 self
1947 }
1948
1949 #[cfg(feature = "unstable_session_options")]
1967 #[must_use]
1968 pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1969 self.config_options = config_options;
1970 self
1971 }
1972
1973 #[must_use]
1979 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1980 self.meta = meta.into_option();
1981 self
1982 }
1983}
1984
1985#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1989#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1990#[serde(tag = "type", rename_all = "snake_case")]
1991#[non_exhaustive]
1992pub enum ReplayFrom {
1993 Start(ReplayFromStart),
1995 #[serde(untagged)]
2006 Other(OtherReplayFrom),
2007}
2008
2009impl From<ReplayFromStart> for ReplayFrom {
2010 fn from(replay_from: ReplayFromStart) -> Self {
2011 Self::Start(replay_from)
2012 }
2013}
2014
2015#[serde_as]
2017#[skip_serializing_none]
2018#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2019#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2020#[serde(rename_all = "camelCase")]
2021#[non_exhaustive]
2022pub struct ReplayFromStart {
2023 #[serde_as(deserialize_as = "DefaultOnError")]
2029 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2030 #[serde(default)]
2031 #[serde(rename = "_meta")]
2032 pub meta: Option<Meta>,
2033}
2034
2035impl ReplayFromStart {
2036 #[must_use]
2038 pub fn new() -> Self {
2039 Self::default()
2040 }
2041
2042 #[must_use]
2048 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2049 self.meta = meta.into_option();
2050 self
2051 }
2052}
2053
2054#[serde_as]
2056#[skip_serializing_none]
2057#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2058#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
2059#[cfg_attr(feature = "schemars", schemars(inline))]
2060#[cfg_attr(feature = "schemars", schemars(transform = other_replay_from_schema))]
2061#[serde(rename_all = "camelCase")]
2062#[non_exhaustive]
2063pub struct OtherReplayFrom {
2064 #[serde(rename = "type")]
2070 pub type_: String,
2071 #[serde(flatten)]
2074 pub fields: BTreeMap<String, serde_json::Value>,
2075}
2076
2077impl OtherReplayFrom {
2078 #[must_use]
2080 pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
2081 fields.remove("type");
2082 Self {
2083 type_: type_.into(),
2084 fields,
2085 }
2086 }
2087}
2088
2089impl<'de> Deserialize<'de> for OtherReplayFrom {
2090 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2091 where
2092 D: serde::Deserializer<'de>,
2093 {
2094 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
2095 let type_ = fields
2096 .remove("type")
2097 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
2098 let serde_json::Value::String(type_) = type_ else {
2099 return Err(serde::de::Error::custom("`type` must be a string"));
2100 };
2101
2102 if is_known_replay_from_type(&type_) {
2103 return Err(serde::de::Error::custom(format!(
2104 "known replay cursor `{type_}` did not match its schema"
2105 )));
2106 }
2107
2108 Ok(Self { type_, fields })
2109 }
2110}
2111
2112fn is_known_replay_from_type(type_: &str) -> bool {
2113 matches!(type_, "start")
2114}
2115
2116#[cfg(feature = "schemars")]
2117fn other_replay_from_schema(schema: &mut Schema) {
2118 super::schema_util::reject_known_string_discriminators(schema, "type", &["start"]);
2119}
2120
2121crate::serde_util::default_on_null! {
2122 #[serde_as]
2130 #[skip_serializing_none]
2131 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2132 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2133 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_RESUME_METHOD_NAME)))]
2134 #[serde(rename_all = "camelCase")]
2135 #[non_exhaustive]
2136 pub struct ResumeSessionResponse {
2137 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2143 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2144 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2145 pub config_options: Vec<SessionConfigOption>,
2146 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2152 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2153 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2154 pub available_commands: Vec<AvailableCommand>,
2155 #[serde_as(deserialize_as = "DefaultOnError")]
2161 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2162 #[serde(default)]
2163 #[serde(rename = "_meta")]
2164 pub meta: Option<Meta>,
2165 }
2166}
2167
2168impl ResumeSessionResponse {
2169 #[must_use]
2171 pub fn new() -> Self {
2172 Self::default()
2173 }
2174
2175 #[must_use]
2181 pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
2182 self.config_options = config_options;
2183 self
2184 }
2185
2186 #[must_use]
2188 pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
2189 self.available_commands = available_commands;
2190 self
2191 }
2192
2193 #[must_use]
2199 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2200 self.meta = meta.into_option();
2201 self
2202 }
2203}
2204
2205#[serde_as]
2228#[skip_serializing_none]
2229#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2230#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2231#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CLOSE_METHOD_NAME)))]
2232#[serde(rename_all = "camelCase")]
2233#[non_exhaustive]
2234pub struct CloseSessionRequest {
2235 pub session_id: SessionId,
2237 #[serde_as(deserialize_as = "DefaultOnError")]
2243 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2244 #[serde(default)]
2245 #[serde(rename = "_meta")]
2246 pub meta: Option<Meta>,
2247}
2248
2249impl CloseSessionRequest {
2250 #[must_use]
2252 pub fn new(session_id: impl Into<SessionId>) -> Self {
2253 Self {
2254 session_id: session_id.into(),
2255 meta: None,
2256 }
2257 }
2258
2259 #[must_use]
2265 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2266 self.meta = meta.into_option();
2267 self
2268 }
2269}
2270
2271crate::serde_util::default_on_null! {
2272 #[serde_as]
2274 #[skip_serializing_none]
2275 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2276 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2277 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CLOSE_METHOD_NAME)))]
2278 #[serde(rename_all = "camelCase")]
2279 #[non_exhaustive]
2280 pub struct CloseSessionResponse {
2281 #[serde_as(deserialize_as = "DefaultOnError")]
2287 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2288 #[serde(default)]
2289 #[serde(rename = "_meta")]
2290 pub meta: Option<Meta>,
2291 }
2292}
2293
2294impl CloseSessionResponse {
2295 #[must_use]
2297 pub fn new() -> Self {
2298 Self::default()
2299 }
2300
2301 #[must_use]
2307 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2308 self.meta = meta.into_option();
2309 self
2310 }
2311}
2312
2313#[cfg(feature = "unstable_session_status")]
2327#[serde_as]
2328#[skip_serializing_none]
2329#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2330#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2331#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_STATUS_METHOD_NAME)))]
2332#[serde(rename_all = "camelCase")]
2333#[non_exhaustive]
2334pub struct SessionStatusRequest {
2335 pub session_id: SessionId,
2337 #[serde_as(deserialize_as = "DefaultOnError")]
2343 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2344 #[serde(default)]
2345 #[serde(rename = "_meta")]
2346 pub meta: Option<Meta>,
2347}
2348
2349#[cfg(feature = "unstable_session_status")]
2350impl SessionStatusRequest {
2351 #[must_use]
2353 pub fn new(session_id: impl Into<SessionId>) -> Self {
2354 Self {
2355 session_id: session_id.into(),
2356 meta: None,
2357 }
2358 }
2359
2360 #[must_use]
2366 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2367 self.meta = meta.into_option();
2368 self
2369 }
2370}
2371
2372#[cfg(feature = "unstable_session_status")]
2381#[serde_as]
2382#[skip_serializing_none]
2383#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2384#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2385#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_STATUS_METHOD_NAME)))]
2386#[serde(rename_all = "camelCase")]
2387#[non_exhaustive]
2388pub struct SessionStatusResponse {
2389 pub status: SessionStatus,
2393 #[serde_as(deserialize_as = "DefaultOnError")]
2401 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2402 #[serde(default)]
2403 pub state: Option<StateUpdate>,
2404 #[serde_as(deserialize_as = "DefaultOnError")]
2410 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2411 #[serde(default)]
2412 #[serde(rename = "_meta")]
2413 pub meta: Option<Meta>,
2414}
2415
2416#[cfg(feature = "unstable_session_status")]
2417impl SessionStatusResponse {
2418 #[must_use]
2420 pub fn new(status: SessionStatus) -> Self {
2421 Self {
2422 status,
2423 state: None,
2424 meta: None,
2425 }
2426 }
2427
2428 #[must_use]
2431 pub fn state(mut self, state: impl IntoOption<StateUpdate>) -> Self {
2432 self.state = state.into_option();
2433 self
2434 }
2435
2436 #[must_use]
2442 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2443 self.meta = meta.into_option();
2444 self
2445 }
2446}
2447
2448#[cfg(feature = "unstable_session_status")]
2454#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2455#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2456#[serde(rename_all = "snake_case")]
2457#[non_exhaustive]
2458pub enum SessionStatus {
2459 Open,
2466 Saved,
2470 #[serde(untagged)]
2477 Other(String),
2478}
2479
2480#[cfg(feature = "unstable_session_options")]
2494#[serde_as]
2495#[skip_serializing_none]
2496#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2497#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2498#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_OPTIONS_METHOD_NAME)))]
2499#[serde(rename_all = "camelCase")]
2500#[non_exhaustive]
2501pub struct SessionOptionsRequest {
2502 pub cwd: AbsolutePath,
2504 #[serde_as(deserialize_as = "DefaultOnNull")]
2508 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
2509 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2510 pub additional_directories: Vec<AbsolutePath>,
2511 #[serde(default)]
2518 pub session_id: Option<SessionId>,
2519 #[serde_as(deserialize_as = "DefaultOnError")]
2525 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2526 #[serde(default)]
2527 #[serde(rename = "_meta")]
2528 pub meta: Option<Meta>,
2529}
2530
2531#[cfg(feature = "unstable_session_options")]
2532impl SessionOptionsRequest {
2533 #[must_use]
2535 pub fn new(cwd: impl Into<AbsolutePath>) -> Self {
2536 Self {
2537 cwd: cwd.into(),
2538 additional_directories: vec![],
2539 session_id: None,
2540 meta: None,
2541 }
2542 }
2543
2544 #[must_use]
2546 pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
2547 where
2548 I: IntoIterator<Item = P>,
2549 P: Into<AbsolutePath>,
2550 {
2551 self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
2552 self
2553 }
2554
2555 #[must_use]
2557 pub fn session_id(mut self, session_id: impl IntoOption<SessionId>) -> Self {
2558 self.session_id = session_id.into_option();
2559 self
2560 }
2561
2562 #[must_use]
2568 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2569 self.meta = meta.into_option();
2570 self
2571 }
2572}
2573
2574#[cfg(feature = "unstable_session_options")]
2575crate::serde_util::default_on_null! {
2576 #[serde_as]
2585 #[skip_serializing_none]
2586 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2587 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2588 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_OPTIONS_METHOD_NAME)))]
2589 #[serde(rename_all = "camelCase")]
2590 #[non_exhaustive]
2591 pub struct SessionOptionsResponse {
2592 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2598 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2599 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2600 pub config_options: Vec<SessionConfigOption>,
2601 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2610 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2611 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2612 pub available_commands: Vec<AvailableCommand>,
2613 #[serde_as(deserialize_as = "DefaultOnError")]
2619 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2620 #[serde(default)]
2621 #[serde(rename = "_meta")]
2622 pub meta: Option<Meta>,
2623 }
2624}
2625
2626#[cfg(feature = "unstable_session_options")]
2627impl SessionOptionsResponse {
2628 #[must_use]
2630 pub fn new() -> Self {
2631 Self::default()
2632 }
2633
2634 #[must_use]
2636 pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
2637 self.config_options = config_options;
2638 self
2639 }
2640
2641 #[must_use]
2643 pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
2644 self.available_commands = available_commands;
2645 self
2646 }
2647
2648 #[must_use]
2654 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2655 self.meta = meta.into_option();
2656 self
2657 }
2658}
2659
2660#[cfg(feature = "unstable_session_options")]
2670#[serde_as]
2671#[skip_serializing_none]
2672#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2673#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2674#[serde(rename_all = "camelCase")]
2675#[non_exhaustive]
2676pub struct InitialSessionConfigOption {
2677 pub config_id: SessionConfigId,
2679 #[serde(flatten)]
2684 pub value: SessionConfigOptionValue,
2685 #[serde_as(deserialize_as = "DefaultOnError")]
2691 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2692 #[serde(default)]
2693 #[serde(rename = "_meta")]
2694 pub meta: Option<Meta>,
2695}
2696
2697#[cfg(feature = "unstable_session_options")]
2698impl InitialSessionConfigOption {
2699 #[must_use]
2701 pub fn new(
2702 config_id: impl Into<SessionConfigId>,
2703 value: impl Into<SessionConfigOptionValue>,
2704 ) -> Self {
2705 Self {
2706 config_id: config_id.into(),
2707 value: value.into(),
2708 meta: None,
2709 }
2710 }
2711
2712 #[must_use]
2718 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2719 self.meta = meta.into_option();
2720 self
2721 }
2722}
2723
2724#[serde_as]
2739#[skip_serializing_none]
2740#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2741#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2742#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TOOL_CALL_CANCEL_METHOD_NAME)))]
2743#[serde(rename_all = "camelCase")]
2744#[non_exhaustive]
2745pub struct CancelToolCallRequest {
2746 pub session_id: SessionId,
2748 pub tool_call_id: ToolCallId,
2750 #[serde_as(deserialize_as = "DefaultOnError")]
2756 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2757 #[serde(default)]
2758 #[serde(rename = "_meta")]
2759 pub meta: Option<Meta>,
2760}
2761
2762impl CancelToolCallRequest {
2763 #[must_use]
2765 pub fn new(session_id: impl Into<SessionId>, tool_call_id: impl Into<ToolCallId>) -> Self {
2766 Self {
2767 session_id: session_id.into(),
2768 tool_call_id: tool_call_id.into(),
2769 meta: None,
2770 }
2771 }
2772
2773 #[must_use]
2779 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2780 self.meta = meta.into_option();
2781 self
2782 }
2783}
2784
2785crate::serde_util::default_on_null! {
2786 #[serde_as]
2788 #[skip_serializing_none]
2789 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2790 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2791 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TOOL_CALL_CANCEL_METHOD_NAME)))]
2792 #[serde(rename_all = "camelCase")]
2793 #[non_exhaustive]
2794 pub struct CancelToolCallResponse {
2795 #[serde_as(deserialize_as = "DefaultOnError")]
2801 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2802 #[serde(default)]
2803 #[serde(rename = "_meta")]
2804 pub meta: Option<Meta>,
2805 }
2806}
2807
2808impl CancelToolCallResponse {
2809 #[must_use]
2811 pub fn new() -> Self {
2812 Self::default()
2813 }
2814
2815 #[must_use]
2821 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2822 self.meta = meta.into_option();
2823 self
2824 }
2825}
2826
2827#[serde_as]
2843#[skip_serializing_none]
2844#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2845#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2846#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TERMINAL_CANCEL_METHOD_NAME)))]
2847#[serde(rename_all = "camelCase")]
2848#[non_exhaustive]
2849pub struct CancelTerminalRequest {
2850 pub session_id: SessionId,
2852 pub terminal_id: TerminalId,
2854 #[serde_as(deserialize_as = "DefaultOnError")]
2860 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2861 #[serde(default)]
2862 #[serde(rename = "_meta")]
2863 pub meta: Option<Meta>,
2864}
2865
2866impl CancelTerminalRequest {
2867 #[must_use]
2869 pub fn new(session_id: impl Into<SessionId>, terminal_id: impl Into<TerminalId>) -> Self {
2870 Self {
2871 session_id: session_id.into(),
2872 terminal_id: terminal_id.into(),
2873 meta: None,
2874 }
2875 }
2876
2877 #[must_use]
2883 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2884 self.meta = meta.into_option();
2885 self
2886 }
2887}
2888
2889crate::serde_util::default_on_null! {
2890 #[serde_as]
2892 #[skip_serializing_none]
2893 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2894 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2895 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TERMINAL_CANCEL_METHOD_NAME)))]
2896 #[serde(rename_all = "camelCase")]
2897 #[non_exhaustive]
2898 pub struct CancelTerminalResponse {
2899 #[serde_as(deserialize_as = "DefaultOnError")]
2905 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2906 #[serde(default)]
2907 #[serde(rename = "_meta")]
2908 pub meta: Option<Meta>,
2909 }
2910}
2911
2912impl CancelTerminalResponse {
2913 #[must_use]
2915 pub fn new() -> Self {
2916 Self::default()
2917 }
2918
2919 #[must_use]
2925 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2926 self.meta = meta.into_option();
2927 self
2928 }
2929}
2930
2931#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2935#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
2936#[serde(transparent)]
2937#[from(Arc<str>, String, &str, &mut str, Box<str>, Cow<'_, str>)]
2938#[non_exhaustive]
2939pub struct SessionListCursor(pub Arc<str>);
2940
2941impl SessionListCursor {
2942 #[must_use]
2944 pub fn new(cursor: impl Into<Self>) -> Self {
2945 cursor.into()
2946 }
2947}
2948
2949impl AsRef<str> for SessionListCursor {
2950 fn as_ref(&self) -> &str {
2951 &self.0
2952 }
2953}
2954
2955impl From<&String> for SessionListCursor {
2956 fn from(cursor: &String) -> Self {
2957 Self(cursor.as_str().into())
2958 }
2959}
2960
2961macro_rules! impl_session_list_cursor_option_conversion {
2962 ($source:ty) => {
2963 impl IntoOption<SessionListCursor> for $source {
2964 fn into_option(self) -> Option<SessionListCursor> {
2965 Some(self.into())
2966 }
2967 }
2968 };
2969}
2970
2971impl_session_list_cursor_option_conversion!(Arc<str>);
2972impl_session_list_cursor_option_conversion!(String);
2973impl_session_list_cursor_option_conversion!(&str);
2974impl_session_list_cursor_option_conversion!(&mut str);
2975impl_session_list_cursor_option_conversion!(&String);
2976impl_session_list_cursor_option_conversion!(Box<str>);
2977impl_session_list_cursor_option_conversion!(Cow<'_, str>);
2978
2979crate::serde_util::default_on_null! {
2980 #[serde_as]
2982 #[skip_serializing_none]
2983 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2984 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2985 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LIST_METHOD_NAME)))]
2986 #[serde(rename_all = "camelCase")]
2987 #[non_exhaustive]
2988 pub struct ListSessionsRequest {
2989 #[serde(default)]
2996 pub cwd: Option<AbsolutePath>,
2997 #[serde(default)]
3001 pub cursor: Option<SessionListCursor>,
3002 #[cfg(feature = "unstable_session_archive")]
3012 #[serde(default)]
3013 pub archived: Option<SessionArchiveFilter>,
3014 #[serde_as(deserialize_as = "DefaultOnError")]
3020 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3021 #[serde(default)]
3022 #[serde(rename = "_meta")]
3023 pub meta: Option<Meta>,
3024 }
3025}
3026
3027impl ListSessionsRequest {
3028 #[must_use]
3030 pub fn new() -> Self {
3031 Self::default()
3032 }
3033
3034 #[must_use]
3036 pub fn cwd(mut self, cwd: impl IntoOption<AbsolutePath>) -> Self {
3037 self.cwd = cwd.into_option();
3038 self
3039 }
3040
3041 #[must_use]
3043 pub fn cursor(mut self, cursor: impl IntoOption<SessionListCursor>) -> Self {
3044 self.cursor = cursor.into_option();
3045 self
3046 }
3047
3048 #[cfg(feature = "unstable_session_archive")]
3054 #[must_use]
3055 pub fn archived(mut self, archived: impl IntoOption<SessionArchiveFilter>) -> Self {
3056 self.archived = archived.into_option();
3057 self
3058 }
3059
3060 #[must_use]
3066 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3067 self.meta = meta.into_option();
3068 self
3069 }
3070}
3071
3072#[serde_as]
3074#[skip_serializing_none]
3075#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3076#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3077#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LIST_METHOD_NAME)))]
3078#[serde(rename_all = "camelCase")]
3079#[non_exhaustive]
3080pub struct ListSessionsResponse {
3081 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
3083 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3084 pub sessions: Vec<SessionInfo>,
3085 #[serde(default)]
3089 pub next_cursor: Option<SessionListCursor>,
3090 #[serde_as(deserialize_as = "DefaultOnError")]
3096 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3097 #[serde(default)]
3098 #[serde(rename = "_meta")]
3099 pub meta: Option<Meta>,
3100}
3101
3102impl ListSessionsResponse {
3103 #[must_use]
3105 pub fn new(sessions: Vec<SessionInfo>) -> Self {
3106 Self {
3107 sessions,
3108 next_cursor: None,
3109 meta: None,
3110 }
3111 }
3112
3113 #[must_use]
3115 pub fn next_cursor(mut self, next_cursor: impl IntoOption<SessionListCursor>) -> Self {
3116 self.next_cursor = next_cursor.into_option();
3117 self
3118 }
3119
3120 #[must_use]
3126 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3127 self.meta = meta.into_option();
3128 self
3129 }
3130}
3131
3132#[serde_as]
3138#[skip_serializing_none]
3139#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3140#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3141#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_DELETE_METHOD_NAME)))]
3142#[serde(rename_all = "camelCase")]
3143#[non_exhaustive]
3144pub struct DeleteSessionRequest {
3145 pub session_id: SessionId,
3147 #[serde_as(deserialize_as = "DefaultOnError")]
3153 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3154 #[serde(default)]
3155 #[serde(rename = "_meta")]
3156 pub meta: Option<Meta>,
3157}
3158
3159impl DeleteSessionRequest {
3160 #[must_use]
3162 pub fn new(session_id: impl Into<SessionId>) -> Self {
3163 Self {
3164 session_id: session_id.into(),
3165 meta: None,
3166 }
3167 }
3168
3169 #[must_use]
3175 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3176 self.meta = meta.into_option();
3177 self
3178 }
3179}
3180
3181crate::serde_util::default_on_null! {
3182 #[serde_as]
3184 #[skip_serializing_none]
3185 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3186 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3187 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_DELETE_METHOD_NAME)))]
3188 #[serde(rename_all = "camelCase")]
3189 #[non_exhaustive]
3190 pub struct DeleteSessionResponse {
3191 #[serde_as(deserialize_as = "DefaultOnError")]
3197 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3198 #[serde(default)]
3199 #[serde(rename = "_meta")]
3200 pub meta: Option<Meta>,
3201 }
3202}
3203
3204impl DeleteSessionResponse {
3205 #[must_use]
3207 pub fn new() -> Self {
3208 Self::default()
3209 }
3210
3211 #[must_use]
3217 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3218 self.meta = meta.into_option();
3219 self
3220 }
3221}
3222
3223#[cfg(feature = "unstable_session_archive")]
3239#[serde_as]
3240#[skip_serializing_none]
3241#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3242#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3243#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_ARCHIVE_METHOD_NAME)))]
3244#[serde(rename_all = "camelCase")]
3245#[non_exhaustive]
3246pub struct ArchiveSessionRequest {
3247 pub session_id: SessionId,
3249 #[serde_as(deserialize_as = "DefaultOnError")]
3255 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3256 #[serde(default)]
3257 #[serde(rename = "_meta")]
3258 pub meta: Option<Meta>,
3259}
3260
3261#[cfg(feature = "unstable_session_archive")]
3262impl ArchiveSessionRequest {
3263 #[must_use]
3265 pub fn new(session_id: impl Into<SessionId>) -> Self {
3266 Self {
3267 session_id: session_id.into(),
3268 meta: None,
3269 }
3270 }
3271
3272 #[must_use]
3278 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3279 self.meta = meta.into_option();
3280 self
3281 }
3282}
3283
3284#[cfg(feature = "unstable_session_archive")]
3285crate::serde_util::default_on_null! {
3286 #[serde_as]
3292 #[skip_serializing_none]
3293 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3294 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3295 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_ARCHIVE_METHOD_NAME)))]
3296 #[serde(rename_all = "camelCase")]
3297 #[non_exhaustive]
3298 pub struct ArchiveSessionResponse {
3299 #[serde_as(deserialize_as = "DefaultOnError")]
3305 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3306 #[serde(default)]
3307 #[serde(rename = "_meta")]
3308 pub meta: Option<Meta>,
3309 }
3310}
3311
3312#[cfg(feature = "unstable_session_archive")]
3313impl ArchiveSessionResponse {
3314 #[must_use]
3316 pub fn new() -> Self {
3317 Self::default()
3318 }
3319
3320 #[must_use]
3326 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3327 self.meta = meta.into_option();
3328 self
3329 }
3330}
3331
3332#[cfg(feature = "unstable_session_archive")]
3347#[serde_as]
3348#[skip_serializing_none]
3349#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3350#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3351#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_UNARCHIVE_METHOD_NAME)))]
3352#[serde(rename_all = "camelCase")]
3353#[non_exhaustive]
3354pub struct UnarchiveSessionRequest {
3355 pub session_id: SessionId,
3357 #[serde_as(deserialize_as = "DefaultOnError")]
3363 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3364 #[serde(default)]
3365 #[serde(rename = "_meta")]
3366 pub meta: Option<Meta>,
3367}
3368
3369#[cfg(feature = "unstable_session_archive")]
3370impl UnarchiveSessionRequest {
3371 #[must_use]
3373 pub fn new(session_id: impl Into<SessionId>) -> Self {
3374 Self {
3375 session_id: session_id.into(),
3376 meta: None,
3377 }
3378 }
3379
3380 #[must_use]
3386 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3387 self.meta = meta.into_option();
3388 self
3389 }
3390}
3391
3392#[cfg(feature = "unstable_session_archive")]
3393crate::serde_util::default_on_null! {
3394 #[serde_as]
3400 #[skip_serializing_none]
3401 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3402 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3403 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_UNARCHIVE_METHOD_NAME)))]
3404 #[serde(rename_all = "camelCase")]
3405 #[non_exhaustive]
3406 pub struct UnarchiveSessionResponse {
3407 #[serde_as(deserialize_as = "DefaultOnError")]
3413 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3414 #[serde(default)]
3415 #[serde(rename = "_meta")]
3416 pub meta: Option<Meta>,
3417 }
3418}
3419
3420#[cfg(feature = "unstable_session_archive")]
3421impl UnarchiveSessionResponse {
3422 #[must_use]
3424 pub fn new() -> Self {
3425 Self::default()
3426 }
3427
3428 #[must_use]
3434 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3435 self.meta = meta.into_option();
3436 self
3437 }
3438}
3439
3440#[cfg(feature = "unstable_session_archive")]
3449#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3450#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
3451#[serde(rename_all = "snake_case")]
3452#[non_exhaustive]
3453pub enum SessionArchiveFilter {
3454 #[default]
3456 Exclude,
3457 Include,
3459 Only,
3461 #[serde(untagged)]
3467 Other(String),
3468}
3469
3470#[serde_as]
3472#[skip_serializing_none]
3473#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3474#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3475#[serde(rename_all = "camelCase")]
3476#[non_exhaustive]
3477pub struct SessionInfo {
3478 pub session_id: SessionId,
3480 pub cwd: AbsolutePath,
3482 #[serde_as(deserialize_as = "DefaultOnNull")]
3488 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
3489 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3490 pub additional_directories: Vec<AbsolutePath>,
3491
3492 #[serde_as(deserialize_as = "DefaultOnError")]
3496 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3497 #[serde(default)]
3498 pub title: Option<String>,
3499 #[serde_as(deserialize_as = "DefaultOnError")]
3503 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "format" = "date-time")))]
3504 #[serde(default)]
3505 pub updated_at: Option<String>,
3506 #[cfg(feature = "unstable_session_archive")]
3515 #[serde_as(deserialize_as = "DefaultOnError")]
3516 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3517 #[serde(default)]
3518 pub archived: Option<bool>,
3519 #[serde_as(deserialize_as = "DefaultOnError")]
3525 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3526 #[serde(default)]
3527 #[serde(rename = "_meta")]
3528 pub meta: Option<Meta>,
3529}
3530
3531impl SessionInfo {
3532 #[must_use]
3534 pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
3535 Self {
3536 session_id: session_id.into(),
3537 cwd: cwd.into(),
3538 additional_directories: vec![],
3539 title: None,
3540 updated_at: None,
3541 #[cfg(feature = "unstable_session_archive")]
3542 archived: None,
3543 meta: None,
3544 }
3545 }
3546
3547 #[must_use]
3549 pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
3550 where
3551 I: IntoIterator<Item = P>,
3552 P: Into<AbsolutePath>,
3553 {
3554 self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
3555 self
3556 }
3557
3558 #[must_use]
3560 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
3561 self.title = title.into_option();
3562 self
3563 }
3564
3565 #[must_use]
3567 pub fn updated_at(mut self, updated_at: impl IntoOption<String>) -> Self {
3568 self.updated_at = updated_at.into_option();
3569 self
3570 }
3571
3572 #[cfg(feature = "unstable_session_archive")]
3578 #[must_use]
3579 pub fn archived(mut self, archived: impl IntoOption<bool>) -> Self {
3580 self.archived = archived.into_option();
3581 self
3582 }
3583
3584 #[must_use]
3590 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3591 self.meta = meta.into_option();
3592 self
3593 }
3594}
3595
3596#[cfg(feature = "unstable_session_set_title")]
3612#[serde_as]
3613#[skip_serializing_none]
3614#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3615#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3616#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_TITLE_METHOD_NAME)))]
3617#[serde(rename_all = "camelCase")]
3618#[non_exhaustive]
3619pub struct SetSessionTitleRequest {
3620 pub session_id: SessionId,
3622 pub title: String,
3629 #[serde_as(deserialize_as = "DefaultOnError")]
3635 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3636 #[serde(default)]
3637 #[serde(rename = "_meta")]
3638 pub meta: Option<Meta>,
3639}
3640
3641#[cfg(feature = "unstable_session_set_title")]
3642impl SetSessionTitleRequest {
3643 #[must_use]
3645 pub fn new(session_id: impl Into<SessionId>, title: impl Into<String>) -> Self {
3646 Self {
3647 session_id: session_id.into(),
3648 title: title.into(),
3649 meta: None,
3650 }
3651 }
3652
3653 #[must_use]
3659 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3660 self.meta = meta.into_option();
3661 self
3662 }
3663}
3664
3665#[cfg(feature = "unstable_session_set_title")]
3671#[serde_as]
3672#[skip_serializing_none]
3673#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3674#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3675#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_TITLE_METHOD_NAME)))]
3676#[serde(rename_all = "camelCase")]
3677#[non_exhaustive]
3678pub struct SetSessionTitleResponse {
3679 pub title: String,
3684 #[serde_as(deserialize_as = "DefaultOnError")]
3690 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3691 #[serde(default)]
3692 #[serde(rename = "_meta")]
3693 pub meta: Option<Meta>,
3694}
3695
3696#[cfg(feature = "unstable_session_set_title")]
3697impl SetSessionTitleResponse {
3698 #[must_use]
3700 pub fn new(title: impl Into<String>) -> Self {
3701 Self {
3702 title: title.into(),
3703 meta: None,
3704 }
3705 }
3706
3707 #[must_use]
3713 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3714 self.meta = meta.into_option();
3715 self
3716 }
3717}
3718
3719#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3723#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3724#[serde(transparent)]
3725#[from(forward)]
3726#[non_exhaustive]
3727pub struct SessionConfigId(pub Arc<str>);
3728
3729impl SessionConfigId {
3730 #[must_use]
3732 pub fn new(id: impl Into<Self>) -> Self {
3733 id.into()
3734 }
3735}
3736
3737#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3739#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3740#[serde(transparent)]
3741#[from(forward)]
3742#[non_exhaustive]
3743pub struct SessionConfigValueId(pub Arc<str>);
3744
3745impl SessionConfigValueId {
3746 #[must_use]
3748 pub fn new(id: impl Into<Self>) -> Self {
3749 id.into()
3750 }
3751}
3752
3753#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3755#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3756#[serde(transparent)]
3757#[from(forward)]
3758#[non_exhaustive]
3759pub struct SessionConfigGroupId(pub Arc<str>);
3760
3761impl SessionConfigGroupId {
3762 #[must_use]
3764 pub fn new(id: impl Into<Self>) -> Self {
3765 id.into()
3766 }
3767}
3768
3769#[serde_as]
3771#[skip_serializing_none]
3772#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3773#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3774#[serde(rename_all = "camelCase")]
3775#[non_exhaustive]
3776pub struct SessionConfigSelectOption {
3777 pub value: SessionConfigValueId,
3779 pub name: String,
3781 #[serde_as(deserialize_as = "DefaultOnError")]
3785 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3786 #[serde(default)]
3787 pub description: Option<String>,
3788 #[serde_as(deserialize_as = "DefaultOnError")]
3794 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3795 #[serde(default)]
3796 #[serde(rename = "_meta")]
3797 pub meta: Option<Meta>,
3798}
3799
3800impl SessionConfigSelectOption {
3801 #[must_use]
3803 pub fn new(value: impl Into<SessionConfigValueId>, name: impl Into<String>) -> Self {
3804 Self {
3805 value: value.into(),
3806 name: name.into(),
3807 description: None,
3808 meta: None,
3809 }
3810 }
3811
3812 #[must_use]
3814 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
3815 self.description = description.into_option();
3816 self
3817 }
3818
3819 #[must_use]
3825 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3826 self.meta = meta.into_option();
3827 self
3828 }
3829}
3830
3831#[serde_as]
3833#[skip_serializing_none]
3834#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3835#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3836#[serde(rename_all = "camelCase")]
3837#[non_exhaustive]
3838pub struct SessionConfigSelectGroup {
3839 pub group_id: SessionConfigGroupId,
3841 pub name: String,
3843 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
3845 #[cfg_attr(feature = "schemars", schemars(length(min = 1), extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3846 pub options: Vec<SessionConfigSelectOption>,
3847 #[serde_as(deserialize_as = "DefaultOnError")]
3853 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3854 #[serde(default)]
3855 #[serde(rename = "_meta")]
3856 pub meta: Option<Meta>,
3857}
3858
3859impl SessionConfigSelectGroup {
3860 #[must_use]
3862 pub fn new(
3863 group_id: impl Into<SessionConfigGroupId>,
3864 name: impl Into<String>,
3865 options: Vec<SessionConfigSelectOption>,
3866 ) -> Self {
3867 Self {
3868 group_id: group_id.into(),
3869 name: name.into(),
3870 options,
3871 meta: None,
3872 }
3873 }
3874
3875 #[must_use]
3881 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3882 self.meta = meta.into_option();
3883 self
3884 }
3885}
3886
3887#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3889#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3890#[serde(untagged)]
3891#[non_exhaustive]
3892pub enum SessionConfigSelectOptions {
3893 Ungrouped(
3895 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))] Vec<SessionConfigSelectOption>,
3896 ),
3897 Grouped(
3899 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))] Vec<SessionConfigSelectGroup>,
3900 ),
3901}
3902
3903impl From<Vec<SessionConfigSelectOption>> for SessionConfigSelectOptions {
3904 fn from(options: Vec<SessionConfigSelectOption>) -> Self {
3905 SessionConfigSelectOptions::Ungrouped(options)
3906 }
3907}
3908
3909impl From<Vec<SessionConfigSelectGroup>> for SessionConfigSelectOptions {
3910 fn from(groups: Vec<SessionConfigSelectGroup>) -> Self {
3911 SessionConfigSelectOptions::Grouped(groups)
3912 }
3913}
3914
3915#[skip_serializing_none]
3917#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3918#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3919#[serde(rename_all = "camelCase")]
3920#[non_exhaustive]
3921pub struct SessionConfigSelect {
3922 pub current_value: SessionConfigValueId,
3924 pub options: SessionConfigSelectOptions,
3927}
3928
3929impl SessionConfigSelect {
3930 #[must_use]
3932 pub fn new(
3933 current_value: impl Into<SessionConfigValueId>,
3934 options: impl Into<SessionConfigSelectOptions>,
3935 ) -> Self {
3936 Self {
3937 current_value: current_value.into(),
3938 options: options.into(),
3939 }
3940 }
3941}
3942
3943#[skip_serializing_none]
3945#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3946#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3947#[serde(rename_all = "camelCase")]
3948#[non_exhaustive]
3949pub struct SessionConfigBoolean {
3950 pub current_value: bool,
3952}
3953
3954impl SessionConfigBoolean {
3955 #[must_use]
3957 pub fn new(current_value: bool) -> Self {
3958 Self { current_value }
3959 }
3960}
3961
3962#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3972#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3973#[serde(rename_all = "snake_case")]
3974#[non_exhaustive]
3975pub enum SessionConfigOptionCategory {
3976 Mode,
3978 Model,
3980 ModelConfig,
3982 #[cfg(feature = "unstable_speed_config_category")]
3988 Speed,
3989 ThoughtLevel,
3991 #[serde(untagged)]
3997 Other(String),
3998}
3999
4000#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4002#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4003#[serde(tag = "type", rename_all = "snake_case")]
4004#[non_exhaustive]
4005pub enum SessionConfigKind {
4006 Select(SessionConfigSelect),
4008 Boolean(SessionConfigBoolean),
4010 #[serde(untagged)]
4020 Other(OtherSessionConfigKind),
4021}
4022
4023#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4025#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4026#[cfg_attr(feature = "schemars", schemars(inline))]
4027#[cfg_attr(feature = "schemars", schemars(transform = other_session_config_kind_schema))]
4028#[serde(rename_all = "camelCase")]
4029#[non_exhaustive]
4030pub struct OtherSessionConfigKind {
4031 #[serde(rename = "type")]
4037 pub type_: String,
4038 #[serde(flatten)]
4040 pub fields: BTreeMap<String, serde_json::Value>,
4041}
4042
4043impl OtherSessionConfigKind {
4044 #[must_use]
4046 pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
4047 fields.remove("type");
4048 fields.remove("_meta");
4049 Self {
4050 type_: type_.into(),
4051 fields,
4052 }
4053 }
4054}
4055
4056impl<'de> Deserialize<'de> for OtherSessionConfigKind {
4057 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4058 where
4059 D: serde::Deserializer<'de>,
4060 {
4061 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
4062 let type_ = fields
4063 .remove("type")
4064 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4065 let serde_json::Value::String(type_) = type_ else {
4066 return Err(serde::de::Error::custom("`type` must be a string"));
4067 };
4068
4069 if is_known_session_config_kind_type(&type_) {
4070 return Err(serde::de::Error::custom(format!(
4071 "known session configuration option `{type_}` did not match its schema"
4072 )));
4073 }
4074
4075 Ok(Self { type_, fields })
4076 }
4077}
4078
4079fn is_known_session_config_kind_type(type_: &str) -> bool {
4080 matches!(type_, "select" | "boolean")
4081}
4082
4083#[cfg(feature = "schemars")]
4084fn other_session_config_kind_schema(schema: &mut Schema) {
4085 super::schema_util::reject_known_string_discriminators(schema, "type", &["select", "boolean"]);
4086}
4087
4088#[serde_as]
4090#[skip_serializing_none]
4091#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4092#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4093#[serde(rename_all = "camelCase")]
4094#[non_exhaustive]
4095pub struct SessionConfigOption {
4096 pub config_id: SessionConfigId,
4098 pub name: String,
4100 #[serde_as(deserialize_as = "DefaultOnError")]
4104 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4105 #[serde(default)]
4106 pub description: Option<String>,
4107 #[serde_as(deserialize_as = "DefaultOnError")]
4111 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4112 #[serde(default)]
4113 pub category: Option<SessionConfigOptionCategory>,
4114 #[serde(flatten)]
4116 pub kind: SessionConfigKind,
4117 #[serde_as(deserialize_as = "DefaultOnError")]
4123 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4124 #[serde(default)]
4125 #[serde(rename = "_meta")]
4126 pub meta: Option<Meta>,
4127}
4128
4129impl SessionConfigOption {
4130 #[must_use]
4132 pub fn new(
4133 config_id: impl Into<SessionConfigId>,
4134 name: impl Into<String>,
4135 kind: SessionConfigKind,
4136 ) -> Self {
4137 Self {
4138 config_id: config_id.into(),
4139 name: name.into(),
4140 description: None,
4141 category: None,
4142 kind,
4143 meta: None,
4144 }
4145 }
4146
4147 #[must_use]
4149 pub fn select(
4150 config_id: impl Into<SessionConfigId>,
4151 name: impl Into<String>,
4152 current_value: impl Into<SessionConfigValueId>,
4153 options: impl Into<SessionConfigSelectOptions>,
4154 ) -> Self {
4155 Self::new(
4156 config_id,
4157 name,
4158 SessionConfigKind::Select(SessionConfigSelect::new(current_value, options)),
4159 )
4160 }
4161
4162 #[must_use]
4164 pub fn boolean(
4165 config_id: impl Into<SessionConfigId>,
4166 name: impl Into<String>,
4167 current_value: bool,
4168 ) -> Self {
4169 Self::new(
4170 config_id,
4171 name,
4172 SessionConfigKind::Boolean(SessionConfigBoolean::new(current_value)),
4173 )
4174 }
4175
4176 #[must_use]
4178 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
4179 self.description = description.into_option();
4180 self
4181 }
4182
4183 #[must_use]
4185 pub fn category(mut self, category: impl IntoOption<SessionConfigOptionCategory>) -> Self {
4186 self.category = category.into_option();
4187 self
4188 }
4189
4190 #[must_use]
4196 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4197 self.meta = meta.into_option();
4198 self
4199 }
4200}
4201
4202#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4211#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4212#[serde(tag = "type", rename_all = "snake_case")]
4213#[non_exhaustive]
4214pub enum SessionConfigOptionValue {
4215 Id {
4217 value: SessionConfigValueId,
4219 },
4220 Boolean {
4222 value: bool,
4224 },
4225 #[serde(untagged)]
4234 Other(OtherSessionConfigOptionValue),
4235}
4236
4237#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4239#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4240#[cfg_attr(feature = "schemars", schemars(inline))]
4241#[cfg_attr(feature = "schemars", schemars(transform = other_session_config_option_value_schema))]
4242#[serde(rename_all = "camelCase")]
4243#[non_exhaustive]
4244pub struct OtherSessionConfigOptionValue {
4245 #[serde(rename = "type")]
4251 pub type_: String,
4252 pub value: serde_json::Value,
4254 #[serde(flatten)]
4256 pub fields: BTreeMap<String, serde_json::Value>,
4257}
4258
4259impl OtherSessionConfigOptionValue {
4260 #[must_use]
4262 pub fn new(
4263 type_: impl Into<String>,
4264 value: serde_json::Value,
4265 mut fields: BTreeMap<String, serde_json::Value>,
4266 ) -> Self {
4267 fields.remove("type");
4268 fields.remove("value");
4269 fields.remove("_meta");
4270 Self {
4271 type_: type_.into(),
4272 value,
4273 fields,
4274 }
4275 }
4276}
4277
4278impl<'de> Deserialize<'de> for OtherSessionConfigOptionValue {
4279 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4280 where
4281 D: serde::Deserializer<'de>,
4282 {
4283 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
4284 let type_ = fields
4285 .remove("type")
4286 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4287 let serde_json::Value::String(type_) = type_ else {
4288 return Err(serde::de::Error::custom("`type` must be a string"));
4289 };
4290
4291 if is_known_session_config_option_value_type(&type_) {
4292 return Err(serde::de::Error::custom(format!(
4293 "known session configuration option value `{type_}` did not match its schema"
4294 )));
4295 }
4296
4297 let value = fields
4298 .remove("value")
4299 .ok_or_else(|| serde::de::Error::missing_field("value"))?;
4300
4301 Ok(Self {
4302 type_,
4303 value,
4304 fields,
4305 })
4306 }
4307}
4308
4309impl<'de> Deserialize<'de> for SessionConfigOptionValue {
4310 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4311 where
4312 D: serde::Deserializer<'de>,
4313 {
4314 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
4315 let type_ = fields.remove("type");
4316 let value = fields
4317 .remove("value")
4318 .ok_or_else(|| serde::de::Error::missing_field("value"))?;
4319
4320 let type_ = type_.ok_or_else(|| serde::de::Error::missing_field("type"))?;
4321
4322 let serde_json::Value::String(type_) = type_ else {
4323 return Err(serde::de::Error::custom("`type` must be a string"));
4324 };
4325
4326 match type_.as_str() {
4327 "id" => {
4328 let value = serde_json::from_value(value).map_err(|error| {
4329 serde::de::Error::custom(format!(
4330 "`value` must be a string for `type: id`: {error}"
4331 ))
4332 })?;
4333 Ok(Self::Id { value })
4334 }
4335 "boolean" => {
4336 let value = serde_json::from_value(value).map_err(|error| {
4337 serde::de::Error::custom(format!(
4338 "`value` must be a boolean for `type: boolean`: {error}"
4339 ))
4340 })?;
4341 Ok(Self::Boolean { value })
4342 }
4343 _ => Ok(Self::Other(OtherSessionConfigOptionValue {
4344 type_,
4345 value,
4346 fields,
4347 })),
4348 }
4349 }
4350}
4351
4352fn is_known_session_config_option_value_type(type_: &str) -> bool {
4353 matches!(type_, "id" | "boolean")
4354}
4355
4356#[cfg(feature = "schemars")]
4357fn other_session_config_option_value_schema(schema: &mut Schema) {
4358 super::schema_util::reject_known_string_discriminators(schema, "type", &["id", "boolean"]);
4359}
4360
4361impl SessionConfigOptionValue {
4362 #[must_use]
4364 pub fn id(id: impl Into<SessionConfigValueId>) -> Self {
4365 Self::Id { value: id.into() }
4366 }
4367
4368 #[must_use]
4370 pub fn boolean(val: bool) -> Self {
4371 Self::Boolean { value: val }
4372 }
4373
4374 #[must_use]
4377 pub fn as_id(&self) -> Option<&SessionConfigValueId> {
4378 match self {
4379 Self::Id { value } => Some(value),
4380 _ => None,
4381 }
4382 }
4383
4384 #[must_use]
4386 pub fn as_bool(&self) -> Option<bool> {
4387 match self {
4388 Self::Boolean { value } => Some(*value),
4389 _ => None,
4390 }
4391 }
4392}
4393
4394impl From<SessionConfigValueId> for SessionConfigOptionValue {
4395 fn from(value: SessionConfigValueId) -> Self {
4396 Self::Id { value }
4397 }
4398}
4399
4400impl From<bool> for SessionConfigOptionValue {
4401 fn from(value: bool) -> Self {
4402 Self::Boolean { value }
4403 }
4404}
4405
4406impl From<&str> for SessionConfigOptionValue {
4407 fn from(value: &str) -> Self {
4408 Self::Id {
4409 value: SessionConfigValueId::new(value),
4410 }
4411 }
4412}
4413
4414#[serde_as]
4422#[skip_serializing_none]
4423#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4424#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4425#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_CONFIG_OPTION_METHOD_NAME)))]
4426#[serde(rename_all = "camelCase")]
4427#[non_exhaustive]
4428pub struct SetSessionConfigOptionRequest {
4429 pub session_id: SessionId,
4431 pub config_id: SessionConfigId,
4433 #[serde(flatten)]
4437 pub value: SessionConfigOptionValue,
4438 #[serde_as(deserialize_as = "DefaultOnError")]
4444 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4445 #[serde(default)]
4446 #[serde(rename = "_meta")]
4447 pub meta: Option<Meta>,
4448}
4449
4450impl SetSessionConfigOptionRequest {
4451 #[must_use]
4453 pub fn new(
4454 session_id: impl Into<SessionId>,
4455 config_id: impl Into<SessionConfigId>,
4456 value: impl Into<SessionConfigOptionValue>,
4457 ) -> Self {
4458 Self {
4459 session_id: session_id.into(),
4460 config_id: config_id.into(),
4461 value: value.into(),
4462 meta: None,
4463 }
4464 }
4465
4466 #[must_use]
4472 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4473 self.meta = meta.into_option();
4474 self
4475 }
4476}
4477
4478#[serde_as]
4480#[skip_serializing_none]
4481#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4482#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4483#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_CONFIG_OPTION_METHOD_NAME)))]
4484#[serde(rename_all = "camelCase")]
4485#[non_exhaustive]
4486pub struct SetSessionConfigOptionResponse {
4487 #[serde_as(deserialize_as = "VecSkipError<_>")]
4489 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
4490 pub config_options: Vec<SessionConfigOption>,
4491 #[serde_as(deserialize_as = "DefaultOnError")]
4497 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4498 #[serde(default)]
4499 #[serde(rename = "_meta")]
4500 pub meta: Option<Meta>,
4501}
4502
4503impl SetSessionConfigOptionResponse {
4504 #[must_use]
4506 pub fn new(config_options: Vec<SessionConfigOption>) -> Self {
4507 Self {
4508 config_options,
4509 meta: None,
4510 }
4511 }
4512
4513 #[must_use]
4519 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4520 self.meta = meta.into_option();
4521 self
4522 }
4523}
4524
4525#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4534#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4535#[serde(tag = "type", rename_all = "snake_case")]
4536#[non_exhaustive]
4537pub enum McpServer {
4538 Http(McpServerHttp),
4542 #[cfg(feature = "unstable_mcp_over_acp")]
4551 Acp(McpServerAcp),
4552 Stdio(McpServerStdio),
4556 #[serde(untagged)]
4567 Other(OtherMcpServer),
4568}
4569
4570#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4572#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4573#[cfg_attr(feature = "schemars", schemars(inline))]
4574#[cfg_attr(feature = "schemars", schemars(transform = other_mcp_server_schema))]
4575#[serde(rename_all = "camelCase")]
4576#[non_exhaustive]
4577pub struct OtherMcpServer {
4578 #[serde(rename = "type")]
4584 pub type_: String,
4585 #[serde(flatten)]
4587 pub fields: BTreeMap<String, serde_json::Value>,
4588}
4589
4590impl OtherMcpServer {
4591 #[must_use]
4593 pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
4594 fields.remove("type");
4595 Self {
4596 type_: type_.into(),
4597 fields,
4598 }
4599 }
4600}
4601
4602impl<'de> Deserialize<'de> for OtherMcpServer {
4603 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4604 where
4605 D: serde::Deserializer<'de>,
4606 {
4607 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
4608 let type_ = fields
4609 .remove("type")
4610 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4611 let serde_json::Value::String(type_) = type_ else {
4612 return Err(serde::de::Error::custom("`type` must be a string"));
4613 };
4614
4615 if is_known_mcp_server_type(&type_) {
4616 return Err(serde::de::Error::custom(format!(
4617 "known MCP server transport `{type_}` did not match its schema"
4618 )));
4619 }
4620
4621 Ok(Self { type_, fields })
4622 }
4623}
4624
4625fn is_known_mcp_server_type(type_: &str) -> bool {
4626 match type_ {
4627 "http" | "stdio" => true,
4628 #[cfg(feature = "unstable_mcp_over_acp")]
4629 "acp" => true,
4630 _ => false,
4631 }
4632}
4633
4634#[cfg(feature = "schemars")]
4635fn other_mcp_server_schema(schema: &mut Schema) {
4636 super::schema_util::reject_known_string_discriminators(
4637 schema,
4638 "type",
4639 &[
4640 "http",
4641 "stdio",
4642 #[cfg(feature = "unstable_mcp_over_acp")]
4643 "acp",
4644 ],
4645 );
4646}
4647
4648#[serde_as]
4650#[skip_serializing_none]
4651#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4652#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4653#[serde(rename_all = "camelCase")]
4654#[non_exhaustive]
4655pub struct McpServerHttp {
4656 pub name: String,
4658 #[cfg_attr(feature = "schemars", schemars(url))]
4660 pub url: String,
4661 #[serde_as(deserialize_as = "DefaultOnNull")]
4664 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4665 #[serde(default, skip_serializing_if = "Vec::is_empty")]
4666 pub headers: Vec<HttpHeader>,
4667 #[serde_as(deserialize_as = "DefaultOnError")]
4673 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4674 #[serde(default)]
4675 #[serde(rename = "_meta")]
4676 pub meta: Option<Meta>,
4677}
4678
4679impl McpServerHttp {
4680 #[must_use]
4682 pub fn new(name: impl Into<String>, url: impl Into<String>) -> Self {
4683 Self {
4684 name: name.into(),
4685 url: url.into(),
4686 headers: Vec::new(),
4687 meta: None,
4688 }
4689 }
4690
4691 #[must_use]
4694 pub fn headers(mut self, headers: Vec<HttpHeader>) -> Self {
4695 self.headers = headers;
4696 self
4697 }
4698
4699 #[must_use]
4705 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4706 self.meta = meta.into_option();
4707 self
4708 }
4709}
4710
4711#[cfg(feature = "unstable_mcp_over_acp")]
4720#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4721#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
4722#[serde(transparent)]
4723#[from(forward)]
4724#[non_exhaustive]
4725pub struct McpServerAcpId(pub Arc<str>);
4726
4727#[cfg(feature = "unstable_mcp_over_acp")]
4728impl McpServerAcpId {
4729 #[must_use]
4731 pub fn new(id: impl Into<Self>) -> Self {
4732 id.into()
4733 }
4734}
4735
4736#[serde_as]
4745#[skip_serializing_none]
4746#[cfg(feature = "unstable_mcp_over_acp")]
4747#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4748#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4749#[serde(rename_all = "camelCase")]
4750#[non_exhaustive]
4751pub struct McpServerAcp {
4752 pub name: String,
4754 pub server_id: McpServerAcpId,
4759 #[serde_as(deserialize_as = "DefaultOnError")]
4765 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4766 #[serde(default)]
4767 #[serde(rename = "_meta")]
4768 pub meta: Option<Meta>,
4769}
4770
4771#[cfg(feature = "unstable_mcp_over_acp")]
4772impl McpServerAcp {
4773 #[must_use]
4775 pub fn new(name: impl Into<String>, server_id: impl Into<McpServerAcpId>) -> Self {
4776 Self {
4777 name: name.into(),
4778 server_id: server_id.into(),
4779 meta: None,
4780 }
4781 }
4782
4783 #[must_use]
4789 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4790 self.meta = meta.into_option();
4791 self
4792 }
4793}
4794
4795#[serde_as]
4797#[skip_serializing_none]
4798#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4799#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4800#[serde(rename_all = "camelCase")]
4801#[non_exhaustive]
4802pub struct McpServerStdio {
4803 pub name: String,
4805 pub command: AbsolutePath,
4807 #[serde_as(deserialize_as = "DefaultOnNull")]
4809 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4810 #[serde(default, skip_serializing_if = "Vec::is_empty")]
4811 pub args: Vec<String>,
4812 #[serde_as(deserialize_as = "DefaultOnNull")]
4815 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4816 #[serde(default, skip_serializing_if = "Vec::is_empty")]
4817 pub env: Vec<EnvVariable>,
4818 #[serde_as(deserialize_as = "DefaultOnError")]
4824 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4825 #[serde(default)]
4826 #[serde(rename = "_meta")]
4827 pub meta: Option<Meta>,
4828}
4829
4830impl McpServerStdio {
4831 #[must_use]
4833 pub fn new(name: impl Into<String>, command: impl Into<AbsolutePath>) -> Self {
4834 Self {
4835 name: name.into(),
4836 command: command.into(),
4837 args: Vec::new(),
4838 env: Vec::new(),
4839 meta: None,
4840 }
4841 }
4842
4843 #[must_use]
4845 pub fn args(mut self, args: Vec<String>) -> Self {
4846 self.args = args;
4847 self
4848 }
4849
4850 #[must_use]
4853 pub fn env(mut self, env: Vec<EnvVariable>) -> Self {
4854 self.env = env;
4855 self
4856 }
4857
4858 #[must_use]
4864 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4865 self.meta = meta.into_option();
4866 self
4867 }
4868}
4869
4870#[serde_as]
4872#[skip_serializing_none]
4873#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4874#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4875#[serde(rename_all = "camelCase")]
4876#[non_exhaustive]
4877pub struct EnvVariable {
4878 pub name: String,
4880 pub value: String,
4882 #[serde_as(deserialize_as = "DefaultOnError")]
4888 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4889 #[serde(default)]
4890 #[serde(rename = "_meta")]
4891 pub meta: Option<Meta>,
4892}
4893
4894impl EnvVariable {
4895 #[must_use]
4897 pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
4898 Self {
4899 name: name.into(),
4900 value: value.into(),
4901 meta: None,
4902 }
4903 }
4904
4905 #[must_use]
4911 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4912 self.meta = meta.into_option();
4913 self
4914 }
4915}
4916
4917#[serde_as]
4919#[skip_serializing_none]
4920#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4921#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4922#[serde(rename_all = "camelCase")]
4923#[non_exhaustive]
4924pub struct HttpHeader {
4925 pub name: String,
4927 pub value: String,
4929 #[serde_as(deserialize_as = "DefaultOnError")]
4935 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4936 #[serde(default)]
4937 #[serde(rename = "_meta")]
4938 pub meta: Option<Meta>,
4939}
4940
4941impl HttpHeader {
4942 #[must_use]
4944 pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
4945 Self {
4946 name: name.into(),
4947 value: value.into(),
4948 meta: None,
4949 }
4950 }
4951
4952 #[must_use]
4958 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4959 self.meta = meta.into_option();
4960 self
4961 }
4962}
4963
4964#[serde_as]
4973#[skip_serializing_none]
4974#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4975#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4976#[serde(rename_all = "camelCase")]
4977#[non_exhaustive]
4978pub struct SystemPrompt {
4979 pub mode: SystemPromptMode,
4984 pub content: Vec<ContentBlock>,
4994 #[serde_as(deserialize_as = "DefaultOnError")]
5000 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5001 #[serde(default)]
5002 #[serde(rename = "_meta")]
5003 pub meta: Option<Meta>,
5004}
5005
5006impl SystemPrompt {
5007 #[must_use]
5012 pub fn new(content: Vec<ContentBlock>) -> Self {
5013 Self {
5014 mode: SystemPromptMode::default(),
5015 content,
5016 meta: None,
5017 }
5018 }
5019
5020 #[must_use]
5022 pub fn mode(mut self, mode: SystemPromptMode) -> Self {
5023 self.mode = mode;
5024 self
5025 }
5026
5027 #[must_use]
5033 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5034 self.meta = meta.into_option();
5035 self
5036 }
5037}
5038
5039#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5045#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
5046#[serde(rename_all = "snake_case")]
5047#[non_exhaustive]
5048pub enum SystemPromptMode {
5049 #[default]
5056 Append,
5057 Override,
5066 #[serde(untagged)]
5072 Other(String),
5073}
5074
5075#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5084#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash, Display)]
5085#[serde(transparent)]
5086pub struct IdempotencyKey(
5087 #[cfg_attr(feature = "schemars", schemars(length(min = 1, max = 255)))] Arc<str>,
5088);
5089
5090impl IdempotencyKey {
5091 pub const MAX_LENGTH: usize = 255;
5093
5094 pub fn new(key: impl Into<Arc<str>>) -> Result<Self, InvalidIdempotencyKey> {
5101 let key = key.into();
5102 if key.is_empty() {
5103 return Err(InvalidIdempotencyKey::Empty);
5104 }
5105 if key.chars().nth(Self::MAX_LENGTH).is_some() {
5107 return Err(InvalidIdempotencyKey::TooLong);
5108 }
5109 Ok(Self(key))
5110 }
5111
5112 #[cfg(feature = "uuid")]
5119 #[must_use]
5120 pub fn generate() -> Self {
5121 uuid::Uuid::new_v4().into()
5122 }
5123
5124 #[must_use]
5126 pub fn as_str(&self) -> &str {
5127 &self.0
5128 }
5129}
5130
5131impl AsRef<str> for IdempotencyKey {
5132 fn as_ref(&self) -> &str {
5133 &self.0
5134 }
5135}
5136
5137#[cfg(feature = "uuid")]
5138impl From<uuid::Uuid> for IdempotencyKey {
5139 fn from(uuid: uuid::Uuid) -> Self {
5142 Self(uuid.to_string().into())
5143 }
5144}
5145
5146impl TryFrom<String> for IdempotencyKey {
5147 type Error = InvalidIdempotencyKey;
5148
5149 fn try_from(key: String) -> Result<Self, Self::Error> {
5150 Self::new(key)
5151 }
5152}
5153
5154impl TryFrom<&str> for IdempotencyKey {
5155 type Error = InvalidIdempotencyKey;
5156
5157 fn try_from(key: &str) -> Result<Self, Self::Error> {
5158 Self::new(key)
5159 }
5160}
5161
5162impl std::str::FromStr for IdempotencyKey {
5163 type Err = InvalidIdempotencyKey;
5164
5165 fn from_str(key: &str) -> Result<Self, Self::Err> {
5166 Self::new(key)
5167 }
5168}
5169
5170impl<'de> Deserialize<'de> for IdempotencyKey {
5173 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
5174 where
5175 D: serde::Deserializer<'de>,
5176 {
5177 let key = Arc::<str>::deserialize(deserializer)?;
5178 Self::new(key).map_err(serde::de::Error::custom)
5179 }
5180}
5181
5182#[derive(Debug, Clone, Copy, PartialEq, Eq, Display)]
5184#[non_exhaustive]
5185pub enum InvalidIdempotencyKey {
5186 #[display("idempotency key must not be empty")]
5188 Empty,
5189 #[display(
5191 "idempotency key must be at most {} characters",
5192 IdempotencyKey::MAX_LENGTH
5193 )]
5194 TooLong,
5195}
5196
5197impl std::error::Error for InvalidIdempotencyKey {}
5198
5199#[serde_as]
5205#[skip_serializing_none]
5206#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5207#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5208#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_PROMPT_METHOD_NAME)))]
5209#[serde(rename_all = "camelCase")]
5210#[non_exhaustive]
5211pub struct PromptRequest {
5212 pub session_id: SessionId,
5214 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
5231 pub prompt: Vec<ContentBlock>,
5232 #[serde(default)]
5249 pub idempotency_key: Option<IdempotencyKey>,
5250 #[serde_as(deserialize_as = "DefaultOnError")]
5256 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5257 #[serde(default)]
5258 #[serde(rename = "_meta")]
5259 pub meta: Option<Meta>,
5260}
5261
5262impl PromptRequest {
5263 #[must_use]
5265 pub fn new(session_id: impl Into<SessionId>, prompt: Vec<ContentBlock>) -> Self {
5266 Self {
5267 session_id: session_id.into(),
5268 prompt,
5269 idempotency_key: None,
5270 meta: None,
5271 }
5272 }
5273
5274 #[must_use]
5282 pub fn idempotency_key(mut self, idempotency_key: impl IntoOption<IdempotencyKey>) -> Self {
5283 self.idempotency_key = idempotency_key.into_option();
5284 self
5285 }
5286
5287 #[must_use]
5293 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5294 self.meta = meta.into_option();
5295 self
5296 }
5297}
5298
5299#[serde_as]
5310#[skip_serializing_none]
5311#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5312#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5313#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_PROMPT_METHOD_NAME)))]
5314#[serde(rename_all = "camelCase")]
5315#[non_exhaustive]
5316pub struct PromptResponse {
5317 pub message_id: MessageId,
5325 #[serde_as(deserialize_as = "DefaultOnError")]
5331 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5332 #[serde(default)]
5333 #[serde(rename = "_meta")]
5334 pub meta: Option<Meta>,
5335}
5336
5337impl PromptResponse {
5338 #[must_use]
5340 pub fn new(message_id: impl Into<MessageId>) -> Self {
5341 Self {
5342 message_id: message_id.into(),
5343 meta: None,
5344 }
5345 }
5346
5347 #[must_use]
5353 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5354 self.meta = meta.into_option();
5355 self
5356 }
5357}
5358
5359#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5363#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
5364#[serde(tag = "stopReason", rename_all = "snake_case")]
5365#[non_exhaustive]
5366pub enum StopReason {
5367 EndTurn,
5370 MaxTokens,
5372 MaxTurnRequests,
5375 Refusal,
5377 Cancelled,
5388 Error(ErrorStopReason),
5394 #[serde(untagged)]
5400 Other(OtherStopReason),
5401}
5402
5403impl From<ErrorStopReason> for StopReason {
5404 fn from(value: ErrorStopReason) -> Self {
5405 Self::Error(value)
5406 }
5407}
5408
5409#[serde_as]
5411#[skip_serializing_none]
5412#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5413#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
5414#[serde(rename_all = "camelCase")]
5415#[non_exhaustive]
5416pub struct ErrorStopReason {
5417 #[serde_as(deserialize_as = "DefaultOnError")]
5422 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5423 #[serde(default)]
5424 pub error: Option<Box<Error>>,
5425}
5426
5427impl ErrorStopReason {
5428 #[must_use]
5430 pub fn new() -> Self {
5431 Self::default()
5432 }
5433
5434 #[must_use]
5436 pub fn error(mut self, error: impl IntoOption<Error>) -> Self {
5437 self.error = error.into_option().map(Box::new);
5438 self
5439 }
5440}
5441
5442#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5444#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
5445#[cfg_attr(feature = "schemars", schemars(inline))]
5446#[cfg_attr(feature = "schemars", schemars(transform = other_stop_reason_schema))]
5447#[serde(rename_all = "camelCase")]
5448#[non_exhaustive]
5449pub struct OtherStopReason {
5450 pub stop_reason: String,
5456 #[serde(flatten)]
5458 pub fields: BTreeMap<String, serde_json::Value>,
5459}
5460
5461impl OtherStopReason {
5462 #[must_use]
5464 pub fn new(
5465 stop_reason: impl Into<String>,
5466 mut fields: BTreeMap<String, serde_json::Value>,
5467 ) -> Self {
5468 remove_idle_state_update_fields(&mut fields);
5469 Self {
5470 stop_reason: stop_reason.into(),
5471 fields,
5472 }
5473 }
5474}
5475
5476impl<'de> Deserialize<'de> for OtherStopReason {
5477 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
5478 where
5479 D: serde::Deserializer<'de>,
5480 {
5481 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
5482 let stop_reason = fields
5483 .remove("stopReason")
5484 .ok_or_else(|| serde::de::Error::missing_field("stopReason"))?;
5485 let serde_json::Value::String(stop_reason) = stop_reason else {
5486 return Err(serde::de::Error::custom("`stopReason` must be a string"));
5487 };
5488
5489 if KNOWN_STOP_REASONS.contains(&stop_reason.as_str()) {
5490 return Err(serde::de::Error::custom(format!(
5491 "known stop reason `{stop_reason}` did not match its schema"
5492 )));
5493 }
5494 remove_idle_state_update_fields(&mut fields);
5495
5496 Ok(Self {
5497 stop_reason,
5498 fields,
5499 })
5500 }
5501}
5502
5503const KNOWN_STOP_REASONS: &[&str] = &[
5504 "end_turn",
5505 "max_tokens",
5506 "max_turn_requests",
5507 "refusal",
5508 "cancelled",
5509 "error",
5510];
5511
5512fn remove_idle_state_update_fields(fields: &mut BTreeMap<String, serde_json::Value>) {
5514 fields.remove("stopReason");
5515 fields.remove("usage");
5516 fields.remove("_meta");
5517}
5518
5519#[cfg(feature = "schemars")]
5520fn other_stop_reason_schema(schema: &mut Schema) {
5521 super::schema_util::reject_known_string_discriminators(
5522 schema,
5523 "stopReason",
5524 KNOWN_STOP_REASONS,
5525 );
5526}
5527
5528#[cfg(feature = "unstable_end_turn_token_usage")]
5534#[serde_as]
5535#[skip_serializing_none]
5536#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5537#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5538#[serde(rename_all = "camelCase")]
5539#[non_exhaustive]
5540pub struct Usage {
5541 pub total_tokens: u64,
5543 pub input_tokens: u64,
5545 pub output_tokens: u64,
5547 #[serde_as(deserialize_as = "DefaultOnError")]
5551 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5552 #[serde(default)]
5553 pub thought_tokens: Option<u64>,
5554 #[serde_as(deserialize_as = "DefaultOnError")]
5558 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5559 #[serde(default)]
5560 pub cached_read_tokens: Option<u64>,
5561 #[serde_as(deserialize_as = "DefaultOnError")]
5565 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5566 #[serde(default)]
5567 pub cached_write_tokens: Option<u64>,
5568 #[serde_as(deserialize_as = "DefaultOnError")]
5574 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5575 #[serde(default)]
5576 #[serde(rename = "_meta")]
5577 pub meta: Option<Meta>,
5578}
5579
5580#[cfg(feature = "unstable_end_turn_token_usage")]
5581impl Usage {
5582 #[must_use]
5584 pub fn new(total_tokens: u64, input_tokens: u64, output_tokens: u64) -> Self {
5585 Self {
5586 total_tokens,
5587 input_tokens,
5588 output_tokens,
5589 thought_tokens: None,
5590 cached_read_tokens: None,
5591 cached_write_tokens: None,
5592 meta: None,
5593 }
5594 }
5595
5596 #[must_use]
5598 pub fn thought_tokens(mut self, thought_tokens: impl IntoOption<u64>) -> Self {
5599 self.thought_tokens = thought_tokens.into_option();
5600 self
5601 }
5602
5603 #[must_use]
5605 pub fn cached_read_tokens(mut self, cached_read_tokens: impl IntoOption<u64>) -> Self {
5606 self.cached_read_tokens = cached_read_tokens.into_option();
5607 self
5608 }
5609
5610 #[must_use]
5612 pub fn cached_write_tokens(mut self, cached_write_tokens: impl IntoOption<u64>) -> Self {
5613 self.cached_write_tokens = cached_write_tokens.into_option();
5614 self
5615 }
5616
5617 #[must_use]
5623 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5624 self.meta = meta.into_option();
5625 self
5626 }
5627}
5628
5629#[cfg(feature = "unstable_llm_providers")]
5642#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5643#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5644#[serde(rename_all = "snake_case")]
5645#[non_exhaustive]
5646#[expect(clippy::doc_markdown)]
5647pub enum LlmProtocol {
5648 Anthropic,
5650 #[serde(rename = "openai")]
5652 OpenAi,
5653 Azure,
5655 Vertex,
5657 Bedrock,
5659 #[serde(untagged)]
5665 Other(String),
5666}
5667
5668#[cfg(feature = "unstable_llm_providers")]
5674#[serde_as]
5675#[skip_serializing_none]
5676#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5677#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5678#[serde(rename_all = "camelCase")]
5679#[non_exhaustive]
5680pub struct ProviderCurrentConfig {
5681 pub api_type: LlmProtocol,
5683 #[cfg_attr(feature = "schemars", schemars(url))]
5685 pub base_url: String,
5686 #[serde_as(deserialize_as = "DefaultOnError")]
5692 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5693 #[serde(default)]
5694 #[serde(rename = "_meta")]
5695 pub meta: Option<Meta>,
5696}
5697
5698#[cfg(feature = "unstable_llm_providers")]
5699impl ProviderCurrentConfig {
5700 #[must_use]
5702 pub fn new(api_type: LlmProtocol, base_url: impl Into<String>) -> Self {
5703 Self {
5704 api_type,
5705 base_url: base_url.into(),
5706 meta: None,
5707 }
5708 }
5709
5710 #[must_use]
5716 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5717 self.meta = meta.into_option();
5718 self
5719 }
5720}
5721
5722#[cfg(feature = "unstable_llm_providers")]
5728#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5729#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
5730#[serde(transparent)]
5731#[from(forward)]
5732#[non_exhaustive]
5733pub struct ProviderId(pub Arc<str>);
5734
5735#[cfg(feature = "unstable_llm_providers")]
5736impl ProviderId {
5737 #[must_use]
5739 pub fn new(id: impl Into<Self>) -> Self {
5740 id.into()
5741 }
5742}
5743
5744#[cfg(feature = "unstable_llm_providers")]
5750#[serde_as]
5751#[skip_serializing_none]
5752#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5753#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5754#[serde(rename_all = "camelCase")]
5755#[non_exhaustive]
5756pub struct ProviderInfo {
5757 pub provider_id: ProviderId,
5759 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
5761 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
5762 pub supported: Vec<LlmProtocol>,
5763 pub required: bool,
5766 #[serde(default)]
5769 pub current: Option<ProviderCurrentConfig>,
5770 #[serde_as(deserialize_as = "DefaultOnError")]
5776 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5777 #[serde(default)]
5778 #[serde(rename = "_meta")]
5779 pub meta: Option<Meta>,
5780}
5781
5782#[cfg(feature = "unstable_llm_providers")]
5783impl ProviderInfo {
5784 #[must_use]
5786 pub fn new(
5787 provider_id: impl Into<ProviderId>,
5788 supported: Vec<LlmProtocol>,
5789 required: bool,
5790 current: impl IntoOption<ProviderCurrentConfig>,
5791 ) -> Self {
5792 Self {
5793 provider_id: provider_id.into(),
5794 supported,
5795 required,
5796 current: current.into_option(),
5797 meta: None,
5798 }
5799 }
5800
5801 #[must_use]
5807 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5808 self.meta = meta.into_option();
5809 self
5810 }
5811}
5812
5813#[cfg(feature = "unstable_llm_providers")]
5814crate::serde_util::default_on_null! {
5815 #[serde_as]
5821 #[skip_serializing_none]
5822 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5823 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
5824 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_LIST_METHOD_NAME)))]
5825 #[serde(rename_all = "camelCase")]
5826 #[non_exhaustive]
5827 pub struct ListProvidersRequest {
5828 #[serde_as(deserialize_as = "DefaultOnError")]
5834 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5835 #[serde(default)]
5836 #[serde(rename = "_meta")]
5837 pub meta: Option<Meta>,
5838 }
5839}
5840
5841#[cfg(feature = "unstable_llm_providers")]
5842impl ListProvidersRequest {
5843 #[must_use]
5845 pub fn new() -> Self {
5846 Self::default()
5847 }
5848
5849 #[must_use]
5855 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5856 self.meta = meta.into_option();
5857 self
5858 }
5859}
5860
5861#[cfg(feature = "unstable_llm_providers")]
5867#[serde_as]
5868#[skip_serializing_none]
5869#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5870#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5871#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_LIST_METHOD_NAME)))]
5872#[serde(rename_all = "camelCase")]
5873#[non_exhaustive]
5874pub struct ListProvidersResponse {
5875 pub providers: Vec<ProviderInfo>,
5877 #[serde_as(deserialize_as = "DefaultOnError")]
5883 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5884 #[serde(default)]
5885 #[serde(rename = "_meta")]
5886 pub meta: Option<Meta>,
5887}
5888
5889#[cfg(feature = "unstable_llm_providers")]
5890impl ListProvidersResponse {
5891 #[must_use]
5893 pub fn new(providers: Vec<ProviderInfo>) -> Self {
5894 Self {
5895 providers,
5896 meta: None,
5897 }
5898 }
5899
5900 #[must_use]
5906 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5907 self.meta = meta.into_option();
5908 self
5909 }
5910}
5911
5912#[cfg(feature = "unstable_llm_providers")]
5920#[serde_as]
5921#[skip_serializing_none]
5922#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5923#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
5924#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_SET_METHOD_NAME)))]
5925#[serde(rename_all = "camelCase")]
5926#[non_exhaustive]
5927pub struct SetProviderRequest {
5928 pub provider_id: ProviderId,
5930 pub api_type: LlmProtocol,
5932 #[cfg_attr(feature = "schemars", schemars(url))]
5934 pub base_url: String,
5935 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
5938 pub headers: HashMap<String, String>,
5939 #[serde_as(deserialize_as = "DefaultOnError")]
5945 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5946 #[serde(default)]
5947 #[serde(rename = "_meta")]
5948 pub meta: Option<Meta>,
5949}
5950
5951#[cfg(feature = "unstable_llm_providers")]
5952impl SetProviderRequest {
5953 #[must_use]
5955 pub fn new(
5956 provider_id: impl Into<ProviderId>,
5957 api_type: LlmProtocol,
5958 base_url: impl Into<String>,
5959 ) -> Self {
5960 Self {
5961 provider_id: provider_id.into(),
5962 api_type,
5963 base_url: base_url.into(),
5964 headers: HashMap::new(),
5965 meta: None,
5966 }
5967 }
5968
5969 #[must_use]
5972 pub fn headers(mut self, headers: HashMap<String, String>) -> Self {
5973 self.headers = headers;
5974 self
5975 }
5976
5977 #[must_use]
5983 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5984 self.meta = meta.into_option();
5985 self
5986 }
5987}
5988
5989#[cfg(feature = "unstable_llm_providers")]
5990crate::serde_util::default_on_null! {
5991 #[serde_as]
5997 #[skip_serializing_none]
5998 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5999 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
6000 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_SET_METHOD_NAME)))]
6001 #[serde(rename_all = "camelCase")]
6002 #[non_exhaustive]
6003 pub struct SetProviderResponse {
6004 #[serde_as(deserialize_as = "DefaultOnError")]
6010 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6011 #[serde(default)]
6012 #[serde(rename = "_meta")]
6013 pub meta: Option<Meta>,
6014 }
6015}
6016
6017#[cfg(feature = "unstable_llm_providers")]
6018impl SetProviderResponse {
6019 #[must_use]
6021 pub fn new() -> Self {
6022 Self::default()
6023 }
6024
6025 #[must_use]
6031 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6032 self.meta = meta.into_option();
6033 self
6034 }
6035}
6036
6037#[cfg(feature = "unstable_llm_providers")]
6043#[serde_as]
6044#[skip_serializing_none]
6045#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6046#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6047#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_DISABLE_METHOD_NAME)))]
6048#[serde(rename_all = "camelCase")]
6049#[non_exhaustive]
6050pub struct DisableProviderRequest {
6051 pub provider_id: ProviderId,
6053 #[serde_as(deserialize_as = "DefaultOnError")]
6059 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6060 #[serde(default)]
6061 #[serde(rename = "_meta")]
6062 pub meta: Option<Meta>,
6063}
6064
6065#[cfg(feature = "unstable_llm_providers")]
6066impl DisableProviderRequest {
6067 #[must_use]
6069 pub fn new(provider_id: impl Into<ProviderId>) -> Self {
6070 Self {
6071 provider_id: provider_id.into(),
6072 meta: None,
6073 }
6074 }
6075
6076 #[must_use]
6082 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6083 self.meta = meta.into_option();
6084 self
6085 }
6086}
6087
6088#[cfg(feature = "unstable_llm_providers")]
6089crate::serde_util::default_on_null! {
6090 #[serde_as]
6096 #[skip_serializing_none]
6097 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6098 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
6099 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_DISABLE_METHOD_NAME)))]
6100 #[serde(rename_all = "camelCase")]
6101 #[non_exhaustive]
6102 pub struct DisableProviderResponse {
6103 #[serde_as(deserialize_as = "DefaultOnError")]
6109 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6110 #[serde(default)]
6111 #[serde(rename = "_meta")]
6112 pub meta: Option<Meta>,
6113 }
6114}
6115
6116#[cfg(feature = "unstable_llm_providers")]
6117impl DisableProviderResponse {
6118 #[must_use]
6120 pub fn new() -> Self {
6121 Self::default()
6122 }
6123
6124 #[must_use]
6130 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6131 self.meta = meta.into_option();
6132 self
6133 }
6134}
6135
6136#[serde_as]
6145#[skip_serializing_none]
6146#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6147#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6148#[serde(rename_all = "camelCase")]
6149#[non_exhaustive]
6150pub struct AgentCapabilities {
6151 #[serde_as(deserialize_as = "DefaultOnError")]
6159 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6160 #[serde(default)]
6161 pub session: Option<SessionCapabilities>,
6162 #[serde_as(deserialize_as = "DefaultOnError")]
6169 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6170 #[serde(default)]
6171 pub auth: Option<AgentAuthCapabilities>,
6172 #[cfg(feature = "unstable_llm_providers")]
6181 #[serde_as(deserialize_as = "DefaultOnError")]
6182 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6183 #[serde(default)]
6184 pub providers: Option<ProvidersCapabilities>,
6185 #[serde_as(deserialize_as = "DefaultOnError")]
6191 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6192 #[serde(default)]
6193 #[serde(rename = "_meta")]
6194 pub meta: Option<Meta>,
6195}
6196
6197impl AgentCapabilities {
6198 #[must_use]
6200 pub fn new() -> Self {
6201 Self::default()
6202 }
6203
6204 #[must_use]
6212 pub fn session(mut self, session: impl IntoOption<SessionCapabilities>) -> Self {
6213 self.session = session.into_option();
6214 self
6215 }
6216
6217 #[must_use]
6221 pub fn auth(mut self, auth: impl IntoOption<AgentAuthCapabilities>) -> Self {
6222 self.auth = auth.into_option();
6223 self
6224 }
6225
6226 #[cfg(feature = "unstable_llm_providers")]
6232 #[must_use]
6233 pub fn providers(mut self, providers: impl IntoOption<ProvidersCapabilities>) -> Self {
6234 self.providers = providers.into_option();
6235 self
6236 }
6237
6238 #[must_use]
6244 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6245 self.meta = meta.into_option();
6246 self
6247 }
6248}
6249
6250#[cfg(feature = "unstable_llm_providers")]
6258#[serde_as]
6259#[skip_serializing_none]
6260#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6261#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6262#[non_exhaustive]
6263pub struct ProvidersCapabilities {
6264 #[serde_as(deserialize_as = "DefaultOnError")]
6270 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6271 #[serde(default)]
6272 #[serde(rename = "_meta")]
6273 pub meta: Option<Meta>,
6274}
6275
6276#[cfg(feature = "unstable_llm_providers")]
6277impl ProvidersCapabilities {
6278 #[must_use]
6280 pub fn new() -> Self {
6281 Self::default()
6282 }
6283
6284 #[must_use]
6290 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6291 self.meta = meta.into_option();
6292 self
6293 }
6294}
6295
6296#[serde_as]
6308#[skip_serializing_none]
6309#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6310#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6311#[serde(rename_all = "camelCase")]
6312#[non_exhaustive]
6313pub struct SessionCapabilities {
6314 #[serde_as(deserialize_as = "DefaultOnError")]
6320 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6321 #[serde(default)]
6322 pub prompt: Option<PromptCapabilities>,
6323 #[serde_as(deserialize_as = "DefaultOnError")]
6328 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6329 #[serde(default)]
6330 pub mcp: Option<McpCapabilities>,
6331 #[serde_as(deserialize_as = "DefaultOnError")]
6336 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6337 #[serde(default)]
6338 pub delete: Option<SessionDeleteCapabilities>,
6339 #[serde_as(deserialize_as = "DefaultOnError")]
6348 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6349 #[serde(default)]
6350 pub additional_directories: Option<SessionAdditionalDirectoriesCapabilities>,
6351 #[serde_as(deserialize_as = "DefaultOnError")]
6356 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6357 #[serde(default)]
6358 pub system_prompt: Option<SessionSystemPromptCapabilities>,
6359 #[cfg(feature = "unstable_session_fork")]
6368 #[serde_as(deserialize_as = "DefaultOnError")]
6369 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6370 #[serde(default)]
6371 pub fork: Option<SessionForkCapabilities>,
6372 #[cfg(feature = "unstable_session_archive")]
6382 #[serde_as(deserialize_as = "DefaultOnError")]
6383 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6384 #[serde(default)]
6385 pub archive: Option<SessionArchiveCapabilities>,
6386 #[cfg(feature = "unstable_session_status")]
6395 #[serde_as(deserialize_as = "DefaultOnError")]
6396 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6397 #[serde(default)]
6398 pub status: Option<SessionStatusCapabilities>,
6399 #[cfg(feature = "unstable_session_options")]
6409 #[serde_as(deserialize_as = "DefaultOnError")]
6410 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6411 #[serde(default)]
6412 pub options: Option<SessionOptionsCapabilities>,
6413 #[cfg(feature = "unstable_session_set_title")]
6425 #[serde_as(deserialize_as = "DefaultOnError")]
6426 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6427 #[serde(default)]
6428 pub title: Option<SessionTitleCapabilities>,
6429 #[serde_as(deserialize_as = "DefaultOnError")]
6435 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6436 #[serde(default)]
6437 #[serde(rename = "_meta")]
6438 pub meta: Option<Meta>,
6439}
6440
6441impl SessionCapabilities {
6442 #[must_use]
6444 pub fn new() -> Self {
6445 Self::default()
6446 }
6447
6448 #[must_use]
6454 pub fn prompt(mut self, prompt: impl IntoOption<PromptCapabilities>) -> Self {
6455 self.prompt = prompt.into_option();
6456 self
6457 }
6458
6459 #[must_use]
6464 pub fn mcp(mut self, mcp: impl IntoOption<McpCapabilities>) -> Self {
6465 self.mcp = mcp.into_option();
6466 self
6467 }
6468
6469 #[must_use]
6474 pub fn delete(mut self, delete: impl IntoOption<SessionDeleteCapabilities>) -> Self {
6475 self.delete = delete.into_option();
6476 self
6477 }
6478
6479 #[must_use]
6488 pub fn additional_directories(
6489 mut self,
6490 additional_directories: impl IntoOption<SessionAdditionalDirectoriesCapabilities>,
6491 ) -> Self {
6492 self.additional_directories = additional_directories.into_option();
6493 self
6494 }
6495
6496 #[must_use]
6501 pub fn system_prompt(
6502 mut self,
6503 system_prompt: impl IntoOption<SessionSystemPromptCapabilities>,
6504 ) -> Self {
6505 self.system_prompt = system_prompt.into_option();
6506 self
6507 }
6508
6509 #[cfg(feature = "unstable_session_fork")]
6510 #[must_use]
6515 pub fn fork(mut self, fork: impl IntoOption<SessionForkCapabilities>) -> Self {
6516 self.fork = fork.into_option();
6517 self
6518 }
6519
6520 #[cfg(feature = "unstable_session_archive")]
6530 #[must_use]
6531 pub fn archive(mut self, archive: impl IntoOption<SessionArchiveCapabilities>) -> Self {
6532 self.archive = archive.into_option();
6533 self
6534 }
6535
6536 #[cfg(feature = "unstable_session_status")]
6545 #[must_use]
6546 pub fn status(mut self, status: impl IntoOption<SessionStatusCapabilities>) -> Self {
6547 self.status = status.into_option();
6548 self
6549 }
6550
6551 #[cfg(feature = "unstable_session_options")]
6561 #[must_use]
6562 pub fn options(mut self, options: impl IntoOption<SessionOptionsCapabilities>) -> Self {
6563 self.options = options.into_option();
6564 self
6565 }
6566
6567 #[cfg(feature = "unstable_session_set_title")]
6579 #[must_use]
6580 pub fn title(mut self, title: impl IntoOption<SessionTitleCapabilities>) -> Self {
6581 self.title = title.into_option();
6582 self
6583 }
6584
6585 #[must_use]
6591 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6592 self.meta = meta.into_option();
6593 self
6594 }
6595}
6596
6597#[serde_as]
6601#[skip_serializing_none]
6602#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6603#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6604#[non_exhaustive]
6605pub struct SessionDeleteCapabilities {
6606 #[serde_as(deserialize_as = "DefaultOnError")]
6612 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6613 #[serde(default)]
6614 #[serde(rename = "_meta")]
6615 pub meta: Option<Meta>,
6616}
6617
6618impl SessionDeleteCapabilities {
6619 #[must_use]
6621 pub fn new() -> Self {
6622 Self::default()
6623 }
6624
6625 #[must_use]
6631 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6632 self.meta = meta.into_option();
6633 self
6634 }
6635}
6636
6637#[serde_as]
6644#[skip_serializing_none]
6645#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6646#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6647#[non_exhaustive]
6648pub struct SessionAdditionalDirectoriesCapabilities {
6649 #[serde_as(deserialize_as = "DefaultOnError")]
6655 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6656 #[serde(default)]
6657 #[serde(rename = "_meta")]
6658 pub meta: Option<Meta>,
6659}
6660
6661impl SessionAdditionalDirectoriesCapabilities {
6662 #[must_use]
6664 pub fn new() -> Self {
6665 Self::default()
6666 }
6667
6668 #[must_use]
6674 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6675 self.meta = meta.into_option();
6676 self
6677 }
6678}
6679
6680#[serde_as]
6685#[skip_serializing_none]
6686#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6687#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6688#[serde(rename_all = "camelCase")]
6689#[non_exhaustive]
6690pub struct SessionSystemPromptCapabilities {
6691 #[serde_as(deserialize_as = "DefaultOnError")]
6695 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6696 #[serde(default)]
6697 pub mode: Option<SessionSystemPromptModeCapabilities>,
6698 #[serde_as(deserialize_as = "DefaultOnError")]
6704 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6705 #[serde(default)]
6706 #[serde(rename = "_meta")]
6707 pub meta: Option<Meta>,
6708}
6709
6710impl SessionSystemPromptCapabilities {
6711 #[must_use]
6713 pub fn new() -> Self {
6714 Self::default()
6715 }
6716
6717 #[must_use]
6721 pub fn mode(mut self, mode: impl IntoOption<SessionSystemPromptModeCapabilities>) -> Self {
6722 self.mode = mode.into_option();
6723 self
6724 }
6725
6726 #[must_use]
6732 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6733 self.meta = meta.into_option();
6734 self
6735 }
6736}
6737
6738#[serde_as]
6743#[skip_serializing_none]
6744#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6745#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6746#[serde(rename_all = "camelCase")]
6747#[non_exhaustive]
6748pub struct SessionSystemPromptModeCapabilities {
6749 #[serde_as(deserialize_as = "DefaultOnError")]
6755 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6756 #[serde(default, rename = "override")]
6757 pub override_: Option<SessionSystemPromptOverrideCapabilities>,
6758 #[serde_as(deserialize_as = "DefaultOnError")]
6764 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6765 #[serde(default)]
6766 #[serde(rename = "_meta")]
6767 pub meta: Option<Meta>,
6768}
6769
6770impl SessionSystemPromptModeCapabilities {
6771 #[must_use]
6773 pub fn new() -> Self {
6774 Self::default()
6775 }
6776
6777 #[must_use]
6783 pub fn override_(
6784 mut self,
6785 override_: impl IntoOption<SessionSystemPromptOverrideCapabilities>,
6786 ) -> Self {
6787 self.override_ = override_.into_option();
6788 self
6789 }
6790
6791 #[must_use]
6797 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6798 self.meta = meta.into_option();
6799 self
6800 }
6801}
6802
6803#[serde_as]
6808#[skip_serializing_none]
6809#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6810#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6811#[non_exhaustive]
6812pub struct SessionSystemPromptOverrideCapabilities {
6813 #[serde_as(deserialize_as = "DefaultOnError")]
6819 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6820 #[serde(default)]
6821 #[serde(rename = "_meta")]
6822 pub meta: Option<Meta>,
6823}
6824
6825impl SessionSystemPromptOverrideCapabilities {
6826 #[must_use]
6828 pub fn new() -> Self {
6829 Self::default()
6830 }
6831
6832 #[must_use]
6838 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6839 self.meta = meta.into_option();
6840 self
6841 }
6842}
6843
6844#[cfg(feature = "unstable_session_fork")]
6852#[serde_as]
6853#[skip_serializing_none]
6854#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6855#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6856#[non_exhaustive]
6857pub struct SessionForkCapabilities {
6858 #[serde_as(deserialize_as = "DefaultOnError")]
6864 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6865 #[serde(default)]
6866 #[serde(rename = "_meta")]
6867 pub meta: Option<Meta>,
6868}
6869
6870#[cfg(feature = "unstable_session_fork")]
6871impl SessionForkCapabilities {
6872 #[must_use]
6874 pub fn new() -> Self {
6875 Self::default()
6876 }
6877
6878 #[must_use]
6884 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6885 self.meta = meta.into_option();
6886 self
6887 }
6888}
6889
6890#[cfg(feature = "unstable_session_archive")]
6899#[serde_as]
6900#[skip_serializing_none]
6901#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6902#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6903#[non_exhaustive]
6904pub struct SessionArchiveCapabilities {
6905 #[serde_as(deserialize_as = "DefaultOnError")]
6911 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6912 #[serde(default)]
6913 #[serde(rename = "_meta")]
6914 pub meta: Option<Meta>,
6915}
6916
6917#[cfg(feature = "unstable_session_archive")]
6918impl SessionArchiveCapabilities {
6919 #[must_use]
6921 pub fn new() -> Self {
6922 Self::default()
6923 }
6924
6925 #[must_use]
6931 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6932 self.meta = meta.into_option();
6933 self
6934 }
6935}
6936
6937#[cfg(feature = "unstable_session_status")]
6945#[serde_as]
6946#[skip_serializing_none]
6947#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6948#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6949#[non_exhaustive]
6950pub struct SessionStatusCapabilities {
6951 #[serde_as(deserialize_as = "DefaultOnError")]
6957 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6958 #[serde(default)]
6959 #[serde(rename = "_meta")]
6960 pub meta: Option<Meta>,
6961}
6962
6963#[cfg(feature = "unstable_session_status")]
6964impl SessionStatusCapabilities {
6965 #[must_use]
6967 pub fn new() -> Self {
6968 Self::default()
6969 }
6970
6971 #[must_use]
6977 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6978 self.meta = meta.into_option();
6979 self
6980 }
6981}
6982
6983#[cfg(feature = "unstable_session_options")]
6992#[serde_as]
6993#[skip_serializing_none]
6994#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6995#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6996#[non_exhaustive]
6997pub struct SessionOptionsCapabilities {
6998 #[serde_as(deserialize_as = "DefaultOnError")]
7004 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7005 #[serde(default)]
7006 #[serde(rename = "_meta")]
7007 pub meta: Option<Meta>,
7008}
7009
7010#[cfg(feature = "unstable_session_options")]
7011impl SessionOptionsCapabilities {
7012 #[must_use]
7014 pub fn new() -> Self {
7015 Self::default()
7016 }
7017
7018 #[must_use]
7024 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7025 self.meta = meta.into_option();
7026 self
7027 }
7028}
7029
7030#[cfg(feature = "unstable_session_set_title")]
7039#[serde_as]
7040#[skip_serializing_none]
7041#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7042#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7043#[non_exhaustive]
7044pub struct SessionTitleCapabilities {
7045 #[serde_as(deserialize_as = "DefaultOnError")]
7051 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7052 #[serde(default)]
7053 #[serde(rename = "_meta")]
7054 pub meta: Option<Meta>,
7055}
7056
7057#[cfg(feature = "unstable_session_set_title")]
7058impl SessionTitleCapabilities {
7059 #[must_use]
7061 pub fn new() -> Self {
7062 Self::default()
7063 }
7064
7065 #[must_use]
7071 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7072 self.meta = meta.into_option();
7073 self
7074 }
7075}
7076
7077#[serde_as]
7090#[skip_serializing_none]
7091#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7092#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7093#[serde(rename_all = "camelCase")]
7094#[non_exhaustive]
7095pub struct PromptCapabilities {
7096 #[serde_as(deserialize_as = "DefaultOnError")]
7101 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7102 #[serde(default)]
7103 pub image: Option<PromptImageCapabilities>,
7104 #[serde_as(deserialize_as = "DefaultOnError")]
7109 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7110 #[serde(default)]
7111 pub audio: Option<PromptAudioCapabilities>,
7112 #[serde_as(deserialize_as = "DefaultOnError")]
7120 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7121 #[serde(default)]
7122 pub embedded_context: Option<PromptEmbeddedContextCapabilities>,
7123 #[cfg(feature = "unstable_agent_skills")]
7133 #[serde_as(deserialize_as = "DefaultOnError")]
7134 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7135 #[serde(default)]
7136 pub skill: Option<PromptSkillCapabilities>,
7137 #[serde_as(deserialize_as = "DefaultOnError")]
7143 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7144 #[serde(default)]
7145 #[serde(rename = "_meta")]
7146 pub meta: Option<Meta>,
7147}
7148
7149impl PromptCapabilities {
7150 #[must_use]
7152 pub fn new() -> Self {
7153 Self::default()
7154 }
7155
7156 #[must_use]
7161 pub fn image(mut self, image: impl IntoOption<PromptImageCapabilities>) -> Self {
7162 self.image = image.into_option();
7163 self
7164 }
7165
7166 #[must_use]
7171 pub fn audio(mut self, audio: impl IntoOption<PromptAudioCapabilities>) -> Self {
7172 self.audio = audio.into_option();
7173 self
7174 }
7175
7176 #[must_use]
7184 pub fn embedded_context(
7185 mut self,
7186 embedded_context: impl IntoOption<PromptEmbeddedContextCapabilities>,
7187 ) -> Self {
7188 self.embedded_context = embedded_context.into_option();
7189 self
7190 }
7191
7192 #[cfg(feature = "unstable_agent_skills")]
7201 #[must_use]
7202 pub fn skill(mut self, skill: impl IntoOption<PromptSkillCapabilities>) -> Self {
7203 self.skill = skill.into_option();
7204 self
7205 }
7206
7207 #[must_use]
7213 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7214 self.meta = meta.into_option();
7215 self
7216 }
7217}
7218
7219#[serde_as]
7223#[skip_serializing_none]
7224#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7225#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7226#[non_exhaustive]
7227pub struct PromptImageCapabilities {
7228 #[serde_as(deserialize_as = "DefaultOnError")]
7234 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7235 #[serde(default)]
7236 #[serde(rename = "_meta")]
7237 pub meta: Option<Meta>,
7238}
7239
7240impl PromptImageCapabilities {
7241 #[must_use]
7243 pub fn new() -> Self {
7244 Self::default()
7245 }
7246
7247 #[must_use]
7253 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7254 self.meta = meta.into_option();
7255 self
7256 }
7257}
7258
7259#[serde_as]
7263#[skip_serializing_none]
7264#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7265#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7266#[non_exhaustive]
7267pub struct PromptAudioCapabilities {
7268 #[serde_as(deserialize_as = "DefaultOnError")]
7274 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7275 #[serde(default)]
7276 #[serde(rename = "_meta")]
7277 pub meta: Option<Meta>,
7278}
7279
7280impl PromptAudioCapabilities {
7281 #[must_use]
7283 pub fn new() -> Self {
7284 Self::default()
7285 }
7286
7287 #[must_use]
7293 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7294 self.meta = meta.into_option();
7295 self
7296 }
7297}
7298
7299#[serde_as]
7303#[skip_serializing_none]
7304#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7305#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7306#[non_exhaustive]
7307pub struct PromptEmbeddedContextCapabilities {
7308 #[serde_as(deserialize_as = "DefaultOnError")]
7314 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7315 #[serde(default)]
7316 #[serde(rename = "_meta")]
7317 pub meta: Option<Meta>,
7318}
7319
7320impl PromptEmbeddedContextCapabilities {
7321 #[must_use]
7323 pub fn new() -> Self {
7324 Self::default()
7325 }
7326
7327 #[must_use]
7333 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7334 self.meta = meta.into_option();
7335 self
7336 }
7337}
7338
7339#[cfg(feature = "unstable_agent_skills")]
7348#[serde_as]
7349#[skip_serializing_none]
7350#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7351#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7352#[serde(rename_all = "camelCase")]
7353#[non_exhaustive]
7354pub struct PromptSkillCapabilities {
7355 #[serde_as(deserialize_as = "DefaultOnError")]
7361 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7362 #[serde(default)]
7363 pub inline: Option<PromptSkillInlineCapabilities>,
7364 #[serde_as(deserialize_as = "DefaultOnError")]
7370 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7371 #[serde(default)]
7372 #[serde(rename = "_meta")]
7373 pub meta: Option<Meta>,
7374}
7375
7376#[cfg(feature = "unstable_agent_skills")]
7377impl PromptSkillCapabilities {
7378 #[must_use]
7380 pub fn new() -> Self {
7381 Self::default()
7382 }
7383
7384 #[must_use]
7390 pub fn inline(mut self, inline: impl IntoOption<PromptSkillInlineCapabilities>) -> Self {
7391 self.inline = inline.into_option();
7392 self
7393 }
7394
7395 #[must_use]
7401 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7402 self.meta = meta.into_option();
7403 self
7404 }
7405}
7406
7407#[cfg(feature = "unstable_agent_skills")]
7416#[serde_as]
7417#[skip_serializing_none]
7418#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7419#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7420#[non_exhaustive]
7421pub struct PromptSkillInlineCapabilities {
7422 #[serde_as(deserialize_as = "DefaultOnError")]
7428 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7429 #[serde(default)]
7430 #[serde(rename = "_meta")]
7431 pub meta: Option<Meta>,
7432}
7433
7434#[cfg(feature = "unstable_agent_skills")]
7435impl PromptSkillInlineCapabilities {
7436 #[must_use]
7438 pub fn new() -> Self {
7439 Self::default()
7440 }
7441
7442 #[must_use]
7448 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7449 self.meta = meta.into_option();
7450 self
7451 }
7452}
7453
7454#[serde_as]
7456#[skip_serializing_none]
7457#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7458#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7459#[serde(rename_all = "camelCase")]
7460#[non_exhaustive]
7461pub struct McpCapabilities {
7462 #[serde_as(deserialize_as = "DefaultOnError")]
7467 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7468 #[serde(default)]
7469 pub stdio: Option<McpStdioCapabilities>,
7470 #[serde_as(deserialize_as = "DefaultOnError")]
7475 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7476 #[serde(default)]
7477 pub http: Option<McpHttpCapabilities>,
7478 #[cfg(feature = "unstable_mcp_over_acp")]
7487 #[serde_as(deserialize_as = "DefaultOnError")]
7488 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7489 #[serde(default)]
7490 pub acp: Option<McpAcpCapabilities>,
7491 #[serde_as(deserialize_as = "DefaultOnError")]
7497 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7498 #[serde(default)]
7499 #[serde(rename = "_meta")]
7500 pub meta: Option<Meta>,
7501}
7502
7503impl McpCapabilities {
7504 #[must_use]
7506 pub fn new() -> Self {
7507 Self::default()
7508 }
7509
7510 #[must_use]
7515 pub fn stdio(mut self, stdio: impl IntoOption<McpStdioCapabilities>) -> Self {
7516 self.stdio = stdio.into_option();
7517 self
7518 }
7519
7520 #[must_use]
7525 pub fn http(mut self, http: impl IntoOption<McpHttpCapabilities>) -> Self {
7526 self.http = http.into_option();
7527 self
7528 }
7529
7530 #[cfg(feature = "unstable_mcp_over_acp")]
7536 #[must_use]
7540 pub fn acp(mut self, acp: impl IntoOption<McpAcpCapabilities>) -> Self {
7541 self.acp = acp.into_option();
7542 self
7543 }
7544
7545 #[must_use]
7551 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7552 self.meta = meta.into_option();
7553 self
7554 }
7555}
7556
7557#[serde_as]
7561#[skip_serializing_none]
7562#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7563#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7564#[non_exhaustive]
7565pub struct McpStdioCapabilities {
7566 #[serde_as(deserialize_as = "DefaultOnError")]
7572 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7573 #[serde(default)]
7574 #[serde(rename = "_meta")]
7575 pub meta: Option<Meta>,
7576}
7577
7578impl McpStdioCapabilities {
7579 #[must_use]
7581 pub fn new() -> Self {
7582 Self::default()
7583 }
7584
7585 #[must_use]
7591 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7592 self.meta = meta.into_option();
7593 self
7594 }
7595}
7596
7597#[serde_as]
7601#[skip_serializing_none]
7602#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7603#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7604#[non_exhaustive]
7605pub struct McpHttpCapabilities {
7606 #[serde_as(deserialize_as = "DefaultOnError")]
7612 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7613 #[serde(default)]
7614 #[serde(rename = "_meta")]
7615 pub meta: Option<Meta>,
7616}
7617
7618impl McpHttpCapabilities {
7619 #[must_use]
7621 pub fn new() -> Self {
7622 Self::default()
7623 }
7624
7625 #[must_use]
7631 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7632 self.meta = meta.into_option();
7633 self
7634 }
7635}
7636
7637#[cfg(feature = "unstable_mcp_over_acp")]
7645#[serde_as]
7646#[skip_serializing_none]
7647#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7648#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7649#[non_exhaustive]
7650pub struct McpAcpCapabilities {
7651 #[serde_as(deserialize_as = "DefaultOnError")]
7657 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7658 #[serde(default)]
7659 #[serde(rename = "_meta")]
7660 pub meta: Option<Meta>,
7661}
7662
7663#[cfg(feature = "unstable_mcp_over_acp")]
7664impl McpAcpCapabilities {
7665 #[must_use]
7667 pub fn new() -> Self {
7668 Self::default()
7669 }
7670
7671 #[must_use]
7677 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7678 self.meta = meta.into_option();
7679 self
7680 }
7681}
7682
7683#[serde_as]
7687#[skip_serializing_none]
7688#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7689#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7690#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CANCEL_METHOD_NAME)))]
7691#[serde(rename_all = "camelCase")]
7692#[non_exhaustive]
7693pub struct CancelSessionNotification {
7694 pub session_id: SessionId,
7696 #[serde_as(deserialize_as = "DefaultOnError")]
7702 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7703 #[serde(default)]
7704 #[serde(rename = "_meta")]
7705 pub meta: Option<Meta>,
7706}
7707
7708impl CancelSessionNotification {
7709 #[must_use]
7711 pub fn new(session_id: impl Into<SessionId>) -> Self {
7712 Self {
7713 session_id: session_id.into(),
7714 meta: None,
7715 }
7716 }
7717
7718 #[must_use]
7724 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7725 self.meta = meta.into_option();
7726 self
7727 }
7728}
7729
7730#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7736#[non_exhaustive]
7737pub struct AgentMethodNames {
7738 pub initialize: &'static str,
7740 pub auth_login: &'static str,
7742 #[cfg(feature = "unstable_llm_providers")]
7744 pub providers_list: &'static str,
7745 #[cfg(feature = "unstable_llm_providers")]
7747 pub providers_set: &'static str,
7748 #[cfg(feature = "unstable_llm_providers")]
7750 pub providers_disable: &'static str,
7751 pub session_new: &'static str,
7753 pub session_set_config_option: &'static str,
7755 pub session_prompt: &'static str,
7757 pub session_cancel: &'static str,
7759 #[cfg(feature = "unstable_mcp_over_acp")]
7761 pub mcp_message: &'static str,
7762 pub session_list: &'static str,
7764 pub session_delete: &'static str,
7766 #[cfg(feature = "unstable_session_fork")]
7768 pub session_fork: &'static str,
7769 #[cfg(feature = "unstable_session_archive")]
7771 pub session_archive: &'static str,
7772 #[cfg(feature = "unstable_session_archive")]
7774 pub session_unarchive: &'static str,
7775 #[cfg(feature = "unstable_session_status")]
7777 pub session_status: &'static str,
7778 #[cfg(feature = "unstable_session_options")]
7780 pub session_options: &'static str,
7781 #[cfg(feature = "unstable_session_set_title")]
7783 pub session_set_title: &'static str,
7784 pub session_resume: &'static str,
7786 pub session_close: &'static str,
7788 pub tool_call_cancel: &'static str,
7790 pub terminal_cancel: &'static str,
7792 pub auth_logout: &'static str,
7794 #[cfg(feature = "unstable_auth_status")]
7796 pub auth_status: &'static str,
7797}
7798
7799pub const AGENT_METHOD_NAMES: AgentMethodNames = AgentMethodNames {
7801 initialize: INITIALIZE_METHOD_NAME,
7802 auth_login: AUTH_LOGIN_METHOD_NAME,
7803 #[cfg(feature = "unstable_llm_providers")]
7804 providers_list: PROVIDERS_LIST_METHOD_NAME,
7805 #[cfg(feature = "unstable_llm_providers")]
7806 providers_set: PROVIDERS_SET_METHOD_NAME,
7807 #[cfg(feature = "unstable_llm_providers")]
7808 providers_disable: PROVIDERS_DISABLE_METHOD_NAME,
7809 session_new: SESSION_NEW_METHOD_NAME,
7810 session_set_config_option: SESSION_SET_CONFIG_OPTION_METHOD_NAME,
7811 session_prompt: SESSION_PROMPT_METHOD_NAME,
7812 session_cancel: SESSION_CANCEL_METHOD_NAME,
7813 #[cfg(feature = "unstable_mcp_over_acp")]
7814 mcp_message: MCP_MESSAGE_METHOD_NAME,
7815 session_list: SESSION_LIST_METHOD_NAME,
7816 session_delete: SESSION_DELETE_METHOD_NAME,
7817 #[cfg(feature = "unstable_session_fork")]
7818 session_fork: SESSION_FORK_METHOD_NAME,
7819 #[cfg(feature = "unstable_session_archive")]
7820 session_archive: SESSION_ARCHIVE_METHOD_NAME,
7821 #[cfg(feature = "unstable_session_archive")]
7822 session_unarchive: SESSION_UNARCHIVE_METHOD_NAME,
7823 #[cfg(feature = "unstable_session_status")]
7824 session_status: SESSION_STATUS_METHOD_NAME,
7825 #[cfg(feature = "unstable_session_options")]
7826 session_options: SESSION_OPTIONS_METHOD_NAME,
7827 #[cfg(feature = "unstable_session_set_title")]
7828 session_set_title: SESSION_SET_TITLE_METHOD_NAME,
7829 session_resume: SESSION_RESUME_METHOD_NAME,
7830 session_close: SESSION_CLOSE_METHOD_NAME,
7831 tool_call_cancel: TOOL_CALL_CANCEL_METHOD_NAME,
7832 terminal_cancel: TERMINAL_CANCEL_METHOD_NAME,
7833 auth_logout: AUTH_LOGOUT_METHOD_NAME,
7834 #[cfg(feature = "unstable_auth_status")]
7835 auth_status: AUTH_STATUS_METHOD_NAME,
7836};
7837
7838pub(crate) const INITIALIZE_METHOD_NAME: &str = "initialize";
7840pub(crate) const AUTH_LOGIN_METHOD_NAME: &str = "auth/login";
7842#[cfg(feature = "unstable_llm_providers")]
7844pub(crate) const PROVIDERS_LIST_METHOD_NAME: &str = "providers/list";
7845#[cfg(feature = "unstable_llm_providers")]
7847pub(crate) const PROVIDERS_SET_METHOD_NAME: &str = "providers/set";
7848#[cfg(feature = "unstable_llm_providers")]
7850pub(crate) const PROVIDERS_DISABLE_METHOD_NAME: &str = "providers/disable";
7851pub(crate) const SESSION_NEW_METHOD_NAME: &str = "session/new";
7853pub(crate) const SESSION_SET_CONFIG_OPTION_METHOD_NAME: &str = "session/set_config_option";
7855pub(crate) const SESSION_PROMPT_METHOD_NAME: &str = "session/prompt";
7857pub(crate) const SESSION_CANCEL_METHOD_NAME: &str = "session/cancel";
7859pub(crate) const SESSION_LIST_METHOD_NAME: &str = "session/list";
7861pub(crate) const SESSION_DELETE_METHOD_NAME: &str = "session/delete";
7863#[cfg(feature = "unstable_session_fork")]
7865pub(crate) const SESSION_FORK_METHOD_NAME: &str = "session/fork";
7866#[cfg(feature = "unstable_session_archive")]
7868pub(crate) const SESSION_ARCHIVE_METHOD_NAME: &str = "session/archive";
7869#[cfg(feature = "unstable_session_archive")]
7871pub(crate) const SESSION_UNARCHIVE_METHOD_NAME: &str = "session/unarchive";
7872#[cfg(feature = "unstable_session_status")]
7874pub(crate) const SESSION_STATUS_METHOD_NAME: &str = "session/status";
7875#[cfg(feature = "unstable_session_options")]
7877pub(crate) const SESSION_OPTIONS_METHOD_NAME: &str = "session/options";
7878#[cfg(feature = "unstable_session_set_title")]
7880pub(crate) const SESSION_SET_TITLE_METHOD_NAME: &str = "session/set_title";
7881pub(crate) const SESSION_RESUME_METHOD_NAME: &str = "session/resume";
7883pub(crate) const SESSION_CLOSE_METHOD_NAME: &str = "session/close";
7885pub(crate) const TOOL_CALL_CANCEL_METHOD_NAME: &str = "tool_call/cancel";
7887pub(crate) const TERMINAL_CANCEL_METHOD_NAME: &str = "terminal/cancel";
7889pub(crate) const AUTH_LOGOUT_METHOD_NAME: &str = "auth/logout";
7891#[cfg(feature = "unstable_auth_status")]
7893pub(crate) const AUTH_STATUS_METHOD_NAME: &str = "auth/status";
7894
7895#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7902#[derive(Clone, Debug, Serialize, Deserialize)]
7903#[serde(untagged)]
7904#[cfg_attr(feature = "schemars", schemars(inline))]
7905#[non_exhaustive]
7906pub enum ClientRequest {
7907 InitializeRequest(Box<InitializeRequest>),
7921 LoginAuthRequest(Box<LoginAuthRequest>),
7936 #[cfg(feature = "unstable_llm_providers")]
7942 ListProvidersRequest(Box<ListProvidersRequest>),
7943 #[cfg(feature = "unstable_llm_providers")]
7949 SetProviderRequest(Box<SetProviderRequest>),
7950 #[cfg(feature = "unstable_llm_providers")]
7956 DisableProviderRequest(Box<DisableProviderRequest>),
7957 LogoutAuthRequest(Box<LogoutAuthRequest>),
7967 #[cfg(feature = "unstable_auth_status")]
7976 AuthStatusRequest(Box<AuthStatusRequest>),
7977 NewSessionRequest(Box<NewSessionRequest>),
7990 ListSessionsRequest(Box<ListSessionsRequest>),
7994 DeleteSessionRequest(Box<DeleteSessionRequest>),
7998 #[cfg(feature = "unstable_session_fork")]
7999 ForkSessionRequest(Box<ForkSessionRequest>),
8015 #[cfg(feature = "unstable_session_archive")]
8016 ArchiveSessionRequest(Box<ArchiveSessionRequest>),
8024 #[cfg(feature = "unstable_session_archive")]
8025 UnarchiveSessionRequest(Box<UnarchiveSessionRequest>),
8033 #[cfg(feature = "unstable_session_status")]
8034 SessionStatusRequest(Box<SessionStatusRequest>),
8042 #[cfg(feature = "unstable_session_options")]
8043 SessionOptionsRequest(Box<SessionOptionsRequest>),
8051 #[cfg(feature = "unstable_session_set_title")]
8052 SetSessionTitleRequest(Box<SetSessionTitleRequest>),
8063 ResumeSessionRequest(Box<ResumeSessionRequest>),
8069 CloseSessionRequest(Box<CloseSessionRequest>),
8074 CancelToolCallRequest(Box<CancelToolCallRequest>),
8080 CancelTerminalRequest(Box<CancelTerminalRequest>),
8086 SetSessionConfigOptionRequest(Box<SetSessionConfigOptionRequest>),
8088 PromptRequest(Box<PromptRequest>),
8110 ExtMethodRequest(Box<ExtRequest>),
8117}
8118
8119impl_request_dispatch! {
8120 ClientRequest => AgentResponse {
8121 InitializeRequest => InitializeResponse: AGENT_METHOD_NAMES.initialize,
8122 LoginAuthRequest => LoginAuthResponse: AGENT_METHOD_NAMES.auth_login,
8123 #[cfg(feature = "unstable_llm_providers")]
8124 ListProvidersRequest => ListProvidersResponse: AGENT_METHOD_NAMES.providers_list,
8125 #[cfg(feature = "unstable_llm_providers")]
8126 SetProviderRequest => SetProviderResponse: AGENT_METHOD_NAMES.providers_set,
8127 #[cfg(feature = "unstable_llm_providers")]
8128 DisableProviderRequest => DisableProviderResponse: AGENT_METHOD_NAMES.providers_disable,
8129 LogoutAuthRequest => LogoutAuthResponse: AGENT_METHOD_NAMES.auth_logout,
8130 #[cfg(feature = "unstable_auth_status")]
8131 AuthStatusRequest => AuthStatusResponse: AGENT_METHOD_NAMES.auth_status,
8132 NewSessionRequest => NewSessionResponse: AGENT_METHOD_NAMES.session_new,
8133 ListSessionsRequest => ListSessionsResponse: AGENT_METHOD_NAMES.session_list,
8134 DeleteSessionRequest => DeleteSessionResponse: AGENT_METHOD_NAMES.session_delete,
8135 #[cfg(feature = "unstable_session_fork")]
8136 ForkSessionRequest => ForkSessionResponse: AGENT_METHOD_NAMES.session_fork,
8137 #[cfg(feature = "unstable_session_archive")]
8138 ArchiveSessionRequest => ArchiveSessionResponse: AGENT_METHOD_NAMES.session_archive,
8139 #[cfg(feature = "unstable_session_archive")]
8140 UnarchiveSessionRequest => UnarchiveSessionResponse: AGENT_METHOD_NAMES.session_unarchive,
8141 #[cfg(feature = "unstable_session_status")]
8142 SessionStatusRequest => SessionStatusResponse: AGENT_METHOD_NAMES.session_status,
8143 #[cfg(feature = "unstable_session_options")]
8144 SessionOptionsRequest => SessionOptionsResponse: AGENT_METHOD_NAMES.session_options,
8145 #[cfg(feature = "unstable_session_set_title")]
8146 SetSessionTitleRequest => SetSessionTitleResponse: AGENT_METHOD_NAMES.session_set_title,
8147 ResumeSessionRequest => ResumeSessionResponse: AGENT_METHOD_NAMES.session_resume,
8148 CloseSessionRequest => CloseSessionResponse: AGENT_METHOD_NAMES.session_close,
8149 CancelToolCallRequest => CancelToolCallResponse: AGENT_METHOD_NAMES.tool_call_cancel,
8150 CancelTerminalRequest => CancelTerminalResponse: AGENT_METHOD_NAMES.terminal_cancel,
8151 SetSessionConfigOptionRequest => SetSessionConfigOptionResponse: AGENT_METHOD_NAMES.session_set_config_option,
8152 PromptRequest => PromptResponse: AGENT_METHOD_NAMES.session_prompt,
8153 }
8154 extension ExtMethodRequest(Box<ExtRequest>) => ExtMethodResponse;
8155}
8156
8157#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
8164#[derive(Clone, Debug, Serialize, Deserialize)]
8165#[serde(untagged)]
8166#[cfg_attr(feature = "schemars", schemars(inline))]
8167#[non_exhaustive]
8168pub enum AgentResponse {
8169 InitializeResponse(Box<InitializeResponse>),
8171 LoginAuthResponse(#[serde(default)] Box<LoginAuthResponse>),
8173 #[cfg(feature = "unstable_llm_providers")]
8175 ListProvidersResponse(Box<ListProvidersResponse>),
8176 #[cfg(feature = "unstable_llm_providers")]
8178 SetProviderResponse(#[serde(default)] Box<SetProviderResponse>),
8179 #[cfg(feature = "unstable_llm_providers")]
8181 DisableProviderResponse(#[serde(default)] Box<DisableProviderResponse>),
8182 LogoutAuthResponse(#[serde(default)] Box<LogoutAuthResponse>),
8184 #[cfg(feature = "unstable_auth_status")]
8186 AuthStatusResponse(Box<AuthStatusResponse>),
8187 NewSessionResponse(Box<NewSessionResponse>),
8189 ListSessionsResponse(Box<ListSessionsResponse>),
8191 DeleteSessionResponse(#[serde(default)] Box<DeleteSessionResponse>),
8193 #[cfg(feature = "unstable_session_fork")]
8195 ForkSessionResponse(Box<ForkSessionResponse>),
8196 #[cfg(feature = "unstable_session_archive")]
8198 ArchiveSessionResponse(#[serde(default)] Box<ArchiveSessionResponse>),
8199 #[cfg(feature = "unstable_session_archive")]
8201 UnarchiveSessionResponse(#[serde(default)] Box<UnarchiveSessionResponse>),
8202 #[cfg(feature = "unstable_session_status")]
8204 SessionStatusResponse(Box<SessionStatusResponse>),
8205 #[cfg(feature = "unstable_session_options")]
8207 SessionOptionsResponse(#[serde(default)] Box<SessionOptionsResponse>),
8208 #[cfg(feature = "unstable_session_set_title")]
8210 SetSessionTitleResponse(Box<SetSessionTitleResponse>),
8211 ResumeSessionResponse(#[serde(default)] Box<ResumeSessionResponse>),
8213 CloseSessionResponse(#[serde(default)] Box<CloseSessionResponse>),
8215 CancelToolCallResponse(#[serde(default)] Box<CancelToolCallResponse>),
8217 CancelTerminalResponse(#[serde(default)] Box<CancelTerminalResponse>),
8219 SetSessionConfigOptionResponse(Box<SetSessionConfigOptionResponse>),
8221 PromptResponse(Box<PromptResponse>),
8223 ExtMethodResponse(Box<ExtResponse>),
8225}
8226
8227#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
8234#[derive(Clone, Debug, Serialize, Deserialize)]
8235#[serde(untagged)]
8236#[cfg_attr(feature = "schemars", schemars(inline))]
8237#[non_exhaustive]
8238pub enum ClientNotification {
8239 CancelSessionNotification(Box<CancelSessionNotification>),
8270 #[cfg(feature = "unstable_mcp_over_acp")]
8276 MessageMcpNotification(Box<MessageMcpNotification>),
8277 ExtNotification(Box<ExtNotification>),
8284}
8285
8286impl_message_dispatch! {
8287 ClientNotification {
8288 CancelSessionNotification => AGENT_METHOD_NAMES.session_cancel,
8289 #[cfg(feature = "unstable_mcp_over_acp")]
8290 MessageMcpNotification => AGENT_METHOD_NAMES.mcp_message,
8291 }
8292 extension ExtNotification(Box<ExtNotification>);
8293}
8294
8295#[cfg(test)]
8296mod test_serialization {
8297 use std::path::PathBuf;
8298
8299 use super::*;
8300 use serde_json::json;
8301
8302 fn test_meta() -> Meta {
8303 json!({ "source": "test" }).as_object().unwrap().clone()
8304 }
8305
8306 #[test]
8307 fn list_sessions_cursor_and_session_directories_are_strict() {
8308 for cursor in [json!(null), json!("next")] {
8309 let response = json!({ "sessions": [], "nextCursor": cursor });
8310 serde_json::from_value::<ListSessionsResponse>(response).unwrap();
8311 }
8312 let malformed = json!({ "sessions": [], "nextCursor": 42 });
8313 assert!(serde_json::from_value::<ListSessionsResponse>(malformed).is_err());
8314
8315 let session = |dirs: serde_json::Value| json!({ "sessionId": "s", "cwd": "/w", "additionalDirectories": dirs });
8316 let info: SessionInfo = serde_json::from_value(session(json!(null))).unwrap();
8317 assert_eq!(info.additional_directories, Vec::<AbsolutePath>::new());
8318 for bad in [json!(["/a", 42]), json!("/a")] {
8319 assert!(serde_json::from_value::<SessionInfo>(session(bad)).is_err());
8320 }
8321 let response = json!({ "sessions": [session(json!(["/a", 42]))] });
8323 let response: ListSessionsResponse = serde_json::from_value(response).unwrap();
8324 assert_eq!(response.sessions, Vec::<SessionInfo>::new());
8325 }
8326
8327 #[test]
8328 fn other_fallbacks_preserve_optional_fields_verbatim() {
8329 let valid = json!({ "type": "_custom", "methodId": "m", "name": "M",
8330 "description": "d", "_meta": { "k": 1 } });
8331 let method: AuthMethod = serde_json::from_value(valid.clone()).unwrap();
8332 assert_eq!(method.description(), Some("d"));
8333 assert_eq!(
8334 method.meta(),
8335 Some(&json!({ "k": 1 }).as_object().unwrap().clone())
8336 );
8337 assert_eq!(serde_json::to_value(&method).unwrap(), valid);
8338
8339 let malformed = json!({ "type": "_custom", "methodId": "m", "name": "M",
8341 "description": 42, "_meta": "bad", "extra": true });
8342 let method: AuthMethod = serde_json::from_value(malformed.clone()).unwrap();
8343 assert_eq!(method.description(), None);
8344 assert_eq!(method.meta(), None);
8345 assert_eq!(serde_json::to_value(&method).unwrap(), malformed);
8346
8347 let replay = json!({ "type": "_custom", "_meta": "bad", "cursor": 3 });
8348 let decoded: ReplayFrom = serde_json::from_value(replay.clone()).unwrap();
8349 assert_eq!(serde_json::to_value(&decoded).unwrap(), replay);
8350 }
8351
8352 fn serialized_meta_key_count(value: &impl serde::Serialize) -> usize {
8353 serde_json::to_string(value)
8354 .unwrap()
8355 .matches("\"_meta\"")
8356 .count()
8357 }
8358
8359 #[test]
8360 fn prompt_response_without_metadata_round_trips() {
8361 let response = PromptResponse::new(MessageId::new("message-1"));
8362 let serialized = serde_json::to_value(&response).unwrap();
8363 assert_eq!(serialized, json!({ "messageId": "message-1" }));
8364 assert_eq!(
8365 serde_json::from_value::<PromptResponse>(serialized).unwrap(),
8366 response
8367 );
8368 assert_eq!(
8369 serde_json::from_value::<PromptResponse>(json!({
8370 "messageId": "message-1",
8371 "_meta": null
8372 }))
8373 .unwrap(),
8374 response
8375 );
8376 }
8377
8378 #[test]
8379 fn prompt_response_requires_message_id_and_preserves_metadata_tolerance() {
8380 let response = PromptResponse::new("message-1").meta(test_meta());
8381 let serialized = serde_json::to_value(&response).unwrap();
8382 assert_eq!(
8383 serialized,
8384 json!({
8385 "messageId": "message-1",
8386 "_meta": { "source": "test" }
8387 })
8388 );
8389
8390 let deserialized: PromptResponse = serde_json::from_value(serialized).unwrap();
8391 assert_eq!(deserialized.message_id, MessageId::new("message-1"));
8392 assert_eq!(deserialized.meta, Some(test_meta()));
8393
8394 let malformed_meta: PromptResponse = serde_json::from_value(json!({
8395 "messageId": "message-2",
8396 "_meta": false
8397 }))
8398 .unwrap();
8399 assert_eq!(malformed_meta.message_id, MessageId::new("message-2"));
8400 assert_eq!(malformed_meta.meta, None);
8401
8402 for invalid in [
8403 json!({}),
8404 json!({ "messageId": null }),
8405 json!({ "messageId": 1 }),
8406 json!({ "messageId": false }),
8407 json!({ "messageId": {} }),
8408 json!({ "messageId": [] }),
8409 ] {
8410 assert!(
8411 serde_json::from_value::<PromptResponse>(invalid).is_err(),
8412 "missing, null, and non-string message IDs must be rejected"
8413 );
8414 }
8415 }
8416
8417 #[cfg(feature = "schemars")]
8418 #[test]
8419 fn prompt_response_schema_requires_non_null_string_message_id_reference() {
8420 let schema = serde_json::to_value(schemars::schema_for!(PromptResponse)).unwrap();
8421
8422 assert_eq!(schema["required"], json!(["messageId"]));
8423 assert_eq!(
8424 schema["properties"]["messageId"]["$ref"],
8425 "#/$defs/MessageId"
8426 );
8427 assert_eq!(schema["$defs"]["MessageId"]["type"], "string");
8428 }
8429
8430 #[test]
8431 fn test_initialize_capabilities_default_on_malformed_values() {
8432 let request: InitializeRequest = serde_json::from_value(json!({
8433 "protocolVersion": 2,
8434 "capabilities": false,
8435 "info": {
8436 "name": "client",
8437 "version": "1.0.0"
8438 }
8439 }))
8440 .unwrap();
8441 assert_eq!(request.capabilities, ClientCapabilities::default());
8442
8443 let response: InitializeResponse = serde_json::from_value(json!({
8444 "protocolVersion": 2,
8445 "capabilities": false,
8446 "info": {
8447 "name": "agent",
8448 "version": "1.0.0"
8449 }
8450 }))
8451 .unwrap();
8452 assert_eq!(response.capabilities, AgentCapabilities::default());
8453 }
8454
8455 #[test]
8456 fn test_agent_capabilities_default_on_malformed_values() {
8457 let capabilities: AgentCapabilities = serde_json::from_value(json!({
8458 "session": false,
8459 "auth": false
8460 }))
8461 .unwrap();
8462
8463 assert!(capabilities.session.is_none());
8464 assert_eq!(capabilities.auth, None);
8465 }
8466
8467 #[test]
8468 fn test_mcp_server_stdio_serialization() {
8469 let server = McpServer::Stdio(
8470 McpServerStdio::new("test-server", "/usr/bin/server")
8471 .args(vec!["--port".to_string(), "3000".to_string()])
8472 .env(vec![EnvVariable::new("API_KEY", "secret123")]),
8473 );
8474
8475 let json = serde_json::to_value(&server).unwrap();
8476 assert_eq!(
8477 json,
8478 json!({
8479 "type": "stdio",
8480 "name": "test-server",
8481 "command": "/usr/bin/server",
8482 "args": ["--port", "3000"],
8483 "env": [
8484 {
8485 "name": "API_KEY",
8486 "value": "secret123"
8487 }
8488 ]
8489 })
8490 );
8491
8492 let deserialized: McpServer = serde_json::from_value(json).unwrap();
8493 match deserialized {
8494 McpServer::Stdio(McpServerStdio {
8495 name,
8496 command,
8497 args,
8498 env,
8499 meta: _,
8500 }) => {
8501 assert_eq!(name, "test-server");
8502 assert_eq!(command, AbsolutePath::new("/usr/bin/server"));
8503 assert_eq!(args, vec!["--port", "3000"]);
8504 assert_eq!(env.len(), 1);
8505 assert_eq!(env[0].name, "API_KEY");
8506 assert_eq!(env[0].value, "secret123");
8507 }
8508 _ => panic!("Expected Stdio variant"),
8509 }
8510 }
8511
8512 #[test]
8513 fn test_mcp_server_empty_arrays_are_optional() {
8514 let stdio = McpServer::Stdio(McpServerStdio::new("test-server", "/usr/bin/server"));
8515 assert_eq!(
8516 serde_json::to_value(&stdio).unwrap(),
8517 json!({
8518 "type": "stdio",
8519 "name": "test-server",
8520 "command": "/usr/bin/server"
8521 })
8522 );
8523
8524 let McpServer::Stdio(McpServerStdio { args, env, .. }) =
8525 serde_json::from_value::<McpServer>(json!({
8526 "type": "stdio",
8527 "name": "test-server",
8528 "command": "/usr/bin/server"
8529 }))
8530 .unwrap()
8531 else {
8532 panic!("Expected Stdio variant");
8533 };
8534 assert_eq!(args, Vec::<String>::new());
8535 assert_eq!(env, []);
8536
8537 let http = McpServer::Http(McpServerHttp::new("http-server", "https://api.example.com"));
8538 assert_eq!(
8539 serde_json::to_value(&http).unwrap(),
8540 json!({
8541 "type": "http",
8542 "name": "http-server",
8543 "url": "https://api.example.com"
8544 })
8545 );
8546
8547 let McpServer::Http(McpServerHttp { headers, .. }) =
8548 serde_json::from_value::<McpServer>(json!({
8549 "type": "http",
8550 "name": "http-server",
8551 "url": "https://api.example.com"
8552 }))
8553 .unwrap()
8554 else {
8555 panic!("Expected Http variant");
8556 };
8557 assert_eq!(headers, []);
8558 }
8559
8560 #[test]
8561 fn test_mcp_server_unknown_transport_serialization() {
8562 let json = json!({
8563 "type": "websocket",
8564 "name": "future-server",
8565 "url": "wss://example.com/mcp",
8566 "protocolVersion": "2026-01-01"
8567 });
8568
8569 let deserialized: McpServer = serde_json::from_value(json.clone()).unwrap();
8570 let McpServer::Other(OtherMcpServer { type_, fields }) = &deserialized else {
8571 panic!("Expected Other variant");
8572 };
8573
8574 assert_eq!(type_, "websocket");
8575 assert_eq!(fields["name"], "future-server");
8576 assert_eq!(fields["url"], "wss://example.com/mcp");
8577 assert_eq!(fields["protocolVersion"], "2026-01-01");
8578 assert_eq!(serde_json::to_value(&deserialized).unwrap(), json);
8579 }
8580
8581 #[test]
8582 fn test_mcp_server_stdio_requires_type() {
8583 let result = serde_json::from_value::<McpServer>(json!({
8584 "name": "test-server",
8585 "command": "/usr/bin/server",
8586 "args": [],
8587 "env": []
8588 }));
8589
8590 assert!(result.is_err());
8591 }
8592
8593 #[test]
8594 fn test_mcp_server_unknown_does_not_hide_malformed_known_transport() {
8595 let result = serde_json::from_value::<McpServer>(json!({
8596 "type": "stdio",
8597 "name": "test-server",
8598 "args": [],
8599 "env": []
8600 }));
8601
8602 assert!(result.is_err());
8603 }
8604
8605 #[test]
8606 fn test_mcp_server_http_serialization() {
8607 let server = McpServer::Http(
8608 McpServerHttp::new("http-server", "https://api.example.com").headers(vec![
8609 HttpHeader::new("Authorization", "Bearer token123"),
8610 HttpHeader::new("Content-Type", "application/json"),
8611 ]),
8612 );
8613
8614 let json = serde_json::to_value(&server).unwrap();
8615 assert_eq!(
8616 json,
8617 json!({
8618 "type": "http",
8619 "name": "http-server",
8620 "url": "https://api.example.com",
8621 "headers": [
8622 {
8623 "name": "Authorization",
8624 "value": "Bearer token123"
8625 },
8626 {
8627 "name": "Content-Type",
8628 "value": "application/json"
8629 }
8630 ]
8631 })
8632 );
8633
8634 let deserialized: McpServer = serde_json::from_value(json).unwrap();
8635 match deserialized {
8636 McpServer::Http(McpServerHttp {
8637 name,
8638 url,
8639 headers,
8640 meta: _,
8641 }) => {
8642 assert_eq!(name, "http-server");
8643 assert_eq!(url, "https://api.example.com");
8644 assert_eq!(headers.len(), 2);
8645 assert_eq!(headers[0].name, "Authorization");
8646 assert_eq!(headers[0].value, "Bearer token123");
8647 assert_eq!(headers[1].name, "Content-Type");
8648 assert_eq!(headers[1].value, "application/json");
8649 }
8650 _ => panic!("Expected Http variant"),
8651 }
8652 }
8653
8654 #[cfg(feature = "schemars")]
8655 #[test]
8656 fn mcp_server_http_schema_marks_url_as_uri() {
8657 let schema = serde_json::to_value(schemars::schema_for!(McpServerHttp)).unwrap();
8658
8659 assert_eq!(schema["properties"]["url"]["format"], "uri");
8660 }
8661
8662 #[cfg(feature = "unstable_mcp_over_acp")]
8663 #[test]
8664 fn test_client_mcp_message_method_names() {
8665 use serde_json::json;
8666
8667 assert_eq!(AGENT_METHOD_NAMES.mcp_message, "mcp/message");
8668
8669 let notification =
8670 MessageMcpNotification::new("server-1", "req-1", "notifications/progress");
8671 assert_eq!(
8672 ClientNotification::MessageMcpNotification(Box::new(notification.clone())).method(),
8673 "mcp/message"
8674 );
8675 assert_eq!(
8676 serde_json::to_value(notification).unwrap(),
8677 json!({
8678 "serverId": "server-1",
8679 "requestId": "req-1",
8680 "method": "notifications/progress"
8681 })
8682 );
8683 let notification: MessageMcpNotification = serde_json::from_value(json!({
8684 "serverId": "server-1", "requestId": "req-1", "method": "notifications/progress",
8685 "params": null, "_meta": null
8686 }))
8687 .unwrap();
8688 assert_eq!(notification.params, None);
8689 assert_eq!(notification.meta, None);
8690 for key in ["serverId", "requestId", "method"] {
8691 let mut value = json!({"serverId":"server-1", "requestId":"req-1", "method":"notifications/progress"});
8692 value.as_object_mut().unwrap().remove(key);
8693 assert!(serde_json::from_value::<MessageMcpNotification>(value).is_err());
8694 }
8695 }
8696
8697 #[test]
8698 fn test_auth_method_names() {
8699 assert_eq!(AGENT_METHOD_NAMES.auth_login, "auth/login");
8700 assert_eq!(AGENT_METHOD_NAMES.auth_logout, "auth/logout");
8701
8702 assert_eq!(
8703 ClientRequest::LoginAuthRequest(Box::new(LoginAuthRequest::new("agent-login")))
8704 .method(),
8705 "auth/login"
8706 );
8707 assert_eq!(
8708 ClientRequest::LogoutAuthRequest(Box::new(LogoutAuthRequest::new())).method(),
8709 "auth/logout"
8710 );
8711 }
8712
8713 #[test]
8714 fn test_session_config_option_category_known_variants() {
8715 assert_eq!(
8717 serde_json::to_value(&SessionConfigOptionCategory::Mode).unwrap(),
8718 json!("mode")
8719 );
8720 assert_eq!(
8721 serde_json::to_value(&SessionConfigOptionCategory::Model).unwrap(),
8722 json!("model")
8723 );
8724 assert_eq!(
8725 serde_json::to_value(&SessionConfigOptionCategory::ModelConfig).unwrap(),
8726 json!("model_config")
8727 );
8728 #[cfg(feature = "unstable_speed_config_category")]
8729 assert_eq!(
8730 serde_json::to_value(&SessionConfigOptionCategory::Speed).unwrap(),
8731 json!("speed")
8732 );
8733 assert_eq!(
8734 serde_json::to_value(&SessionConfigOptionCategory::ThoughtLevel).unwrap(),
8735 json!("thought_level")
8736 );
8737
8738 assert_eq!(
8740 serde_json::from_str::<SessionConfigOptionCategory>("\"mode\"").unwrap(),
8741 SessionConfigOptionCategory::Mode
8742 );
8743 assert_eq!(
8744 serde_json::from_str::<SessionConfigOptionCategory>("\"model\"").unwrap(),
8745 SessionConfigOptionCategory::Model
8746 );
8747 assert_eq!(
8748 serde_json::from_str::<SessionConfigOptionCategory>("\"model_config\"").unwrap(),
8749 SessionConfigOptionCategory::ModelConfig
8750 );
8751 #[cfg(feature = "unstable_speed_config_category")]
8752 assert_eq!(
8753 serde_json::from_str::<SessionConfigOptionCategory>("\"speed\"").unwrap(),
8754 SessionConfigOptionCategory::Speed
8755 );
8756 assert_eq!(
8757 serde_json::from_str::<SessionConfigOptionCategory>("\"thought_level\"").unwrap(),
8758 SessionConfigOptionCategory::ThoughtLevel
8759 );
8760 }
8761
8762 #[test]
8763 fn test_session_config_option_category_unknown_variants() {
8764 let unknown: SessionConfigOptionCategory =
8766 serde_json::from_str("\"some_future_category\"").unwrap();
8767 assert_eq!(
8768 unknown,
8769 SessionConfigOptionCategory::Other("some_future_category".to_string())
8770 );
8771
8772 let json = serde_json::to_value(&unknown).unwrap();
8774 assert_eq!(json, json!("some_future_category"));
8775 }
8776
8777 #[cfg(not(feature = "unstable_speed_config_category"))]
8778 #[test]
8779 fn test_session_config_option_speed_is_unknown_without_feature() {
8780 let unknown: SessionConfigOptionCategory = serde_json::from_str("\"speed\"").unwrap();
8781 assert_eq!(
8782 unknown,
8783 SessionConfigOptionCategory::Other("speed".to_string())
8784 );
8785 }
8786
8787 #[test]
8788 fn test_session_config_option_category_custom_categories() {
8789 let custom: SessionConfigOptionCategory =
8791 serde_json::from_str("\"_my_custom_category\"").unwrap();
8792 assert_eq!(
8793 custom,
8794 SessionConfigOptionCategory::Other("_my_custom_category".to_string())
8795 );
8796
8797 let json = serde_json::to_value(&custom).unwrap();
8799 assert_eq!(json, json!("_my_custom_category"));
8800
8801 let deserialized: SessionConfigOptionCategory = serde_json::from_value(json).unwrap();
8803 assert_eq!(
8804 deserialized,
8805 SessionConfigOptionCategory::Other("_my_custom_category".to_string()),
8806 );
8807 }
8808
8809 fn test_config_option() -> SessionConfigOption {
8810 SessionConfigOption::select(
8811 "mode",
8812 "Mode",
8813 "ask",
8814 vec![SessionConfigSelectOption::new("ask", "Ask")],
8815 )
8816 }
8817
8818 #[test]
8819 fn test_session_response_initial_state_default_empty_and_skip_serializing() {
8820 assert_eq!(
8821 serde_json::to_value(NewSessionResponse::new("sess")).unwrap(),
8822 json!({ "sessionId": "sess" })
8823 );
8824 assert_eq!(
8825 serde_json::to_value(ResumeSessionResponse::new()).unwrap(),
8826 json!({})
8827 );
8828 #[cfg(feature = "unstable_session_fork")]
8829 assert_eq!(
8830 serde_json::to_value(ForkSessionResponse::new("fork")).unwrap(),
8831 json!({ "sessionId": "fork" })
8832 );
8833
8834 let json = serde_json::to_value(
8835 NewSessionResponse::new("sess").config_options(vec![test_config_option()]),
8836 )
8837 .unwrap();
8838 assert_eq!(json["configOptions"].as_array().unwrap().len(), 1);
8839 }
8840
8841 #[test]
8842 fn test_session_response_config_options_deserialize_missing_null_and_invalid() {
8843 let missing: NewSessionResponse =
8844 serde_json::from_value(json!({ "sessionId": "sess" })).unwrap();
8845 assert_eq!(missing.config_options, []);
8846
8847 let null: NewSessionResponse = serde_json::from_value(json!({
8848 "sessionId": "sess",
8849 "configOptions": null
8850 }))
8851 .unwrap();
8852 assert_eq!(null.config_options, []);
8853
8854 let wrong_shape: NewSessionResponse = serde_json::from_value(json!({
8855 "sessionId": "sess",
8856 "configOptions": "oops"
8857 }))
8858 .unwrap();
8859 assert_eq!(wrong_shape.config_options, []);
8860
8861 let valid_option = serde_json::to_value(test_config_option()).unwrap();
8862 let mixed: NewSessionResponse = serde_json::from_value(json!({
8863 "sessionId": "sess",
8864 "configOptions": ["oops", valid_option]
8865 }))
8866 .unwrap();
8867 assert_eq!(mixed.config_options.len(), 1);
8868
8869 let resume: ResumeSessionResponse = serde_json::from_value(json!({})).unwrap();
8870 assert_eq!(resume.config_options, []);
8871 #[cfg(feature = "unstable_session_fork")]
8872 {
8873 let fork: ForkSessionResponse =
8874 serde_json::from_value(json!({ "sessionId": "fork" })).unwrap();
8875 assert_eq!(fork.config_options, []);
8876 }
8877 }
8878
8879 #[test]
8880 fn test_session_response_available_commands_roundtrip_with_config_options() {
8881 use super::super::{AvailableCommandInput, Command, TextCommandInput};
8882
8883 let commands = vec![
8884 AvailableCommand::Command(
8885 Command::new("web", "Search the web")
8886 .input(AvailableCommandInput::Text(TextCommandInput::new("Query"))),
8887 ),
8888 AvailableCommand::Command(Command::new("test", "Run project tests")),
8889 ];
8890 let mut expected = json!({
8891 "sessionId": "sess",
8892 "configOptions": [test_config_option()],
8893 "availableCommands": [
8894 {
8895 "type": "command",
8896 "name": "web",
8897 "description": "Search the web",
8898 "input": { "type": "text", "hint": "Query" }
8899 },
8900 { "type": "command", "name": "test", "description": "Run project tests" }
8901 ]
8902 });
8903
8904 let new = NewSessionResponse::new("sess")
8905 .config_options(vec![test_config_option()])
8906 .available_commands(commands.clone());
8907 assert_eq!(serde_json::to_value(&new).unwrap(), expected);
8908 assert_eq!(
8909 serde_json::from_value::<NewSessionResponse>(expected.clone()).unwrap(),
8910 new
8911 );
8912
8913 expected.as_object_mut().unwrap().remove("sessionId");
8914 let resume = ResumeSessionResponse::new()
8915 .config_options(vec![test_config_option()])
8916 .available_commands(commands.clone());
8917 assert_eq!(serde_json::to_value(&resume).unwrap(), expected);
8918 assert_eq!(
8919 serde_json::from_value::<ResumeSessionResponse>(expected.clone()).unwrap(),
8920 resume
8921 );
8922
8923 #[cfg(feature = "unstable_session_fork")]
8924 {
8925 expected["sessionId"] = json!("fork");
8926 let fork = ForkSessionResponse::new("fork")
8927 .config_options(vec![test_config_option()])
8928 .available_commands(commands);
8929 assert_eq!(serde_json::to_value(&fork).unwrap(), expected);
8930 assert_eq!(
8931 serde_json::from_value::<ForkSessionResponse>(expected).unwrap(),
8932 fork
8933 );
8934 }
8935 }
8936
8937 #[test]
8938 fn test_session_response_available_commands_deserialize_missing_null_and_invalid() {
8939 let command =
8940 AvailableCommand::Command(super::super::Command::new("test", "Run project tests"));
8941 let config_options = vec![test_config_option()];
8942
8943 for (commands, expected) in [
8944 (None, vec![]),
8945 (Some(json!(null)), vec![]),
8946 (Some(json!([])), vec![]),
8947 (Some(json!("oops")), vec![]),
8948 (Some(json!({})), vec![]),
8949 (Some(json!([null, {}, { "name": "invalid" }])), vec![]),
8950 (
8951 Some(json!([{ "name": "test", "description": "Run project tests" }])),
8952 vec![],
8953 ),
8954 (
8955 Some(json!([null, command, { "name": "invalid" }])),
8956 vec![command.clone()],
8957 ),
8958 ] {
8959 let mut value = json!({
8960 "sessionId": "sess",
8961 "configOptions": config_options
8962 });
8963 if let Some(commands) = commands {
8964 value["availableCommands"] = commands;
8965 }
8966
8967 let new: NewSessionResponse = serde_json::from_value(value.clone()).unwrap();
8968 assert_eq!(new.available_commands, expected);
8969 assert_eq!(new.config_options, config_options);
8970
8971 #[cfg(feature = "unstable_session_fork")]
8972 {
8973 let fork: ForkSessionResponse = serde_json::from_value(value.clone()).unwrap();
8974 assert_eq!(fork.available_commands, expected);
8975 assert_eq!(fork.config_options, config_options);
8976 }
8977
8978 value.as_object_mut().unwrap().remove("sessionId");
8979 let resume: ResumeSessionResponse = serde_json::from_value(value).unwrap();
8980 assert_eq!(resume.available_commands, expected);
8981 assert_eq!(resume.config_options, config_options);
8982 }
8983
8984 let resume: ResumeSessionResponse = serde_json::from_value(json!(null)).unwrap();
8985 assert_eq!(resume.available_commands, []);
8986 }
8987
8988 #[test]
8989 fn test_resume_session_replay_from_serialization() {
8990 assert_eq!(
8991 serde_json::to_value(ResumeSessionRequest::new(
8992 "sess_abc123",
8993 "/home/user/project"
8994 ))
8995 .unwrap(),
8996 json!({
8997 "sessionId": "sess_abc123",
8998 "cwd": "/home/user/project"
8999 })
9000 );
9001 assert_eq!(
9002 serde_json::to_value(
9003 ResumeSessionRequest::new("sess_abc123", "/home/user/project")
9004 .replay_from(ReplayFrom::from(ReplayFromStart::new()))
9005 )
9006 .unwrap(),
9007 json!({
9008 "sessionId": "sess_abc123",
9009 "cwd": "/home/user/project",
9010 "replayFrom": {
9011 "type": "start"
9012 }
9013 })
9014 );
9015
9016 let replay: ResumeSessionRequest = serde_json::from_value(json!({
9017 "sessionId": "sess_abc123",
9018 "cwd": "/home/user/project",
9019 "replayFrom": {
9020 "type": "start"
9021 }
9022 }))
9023 .unwrap();
9024 assert!(matches!(replay.replay_from, Some(ReplayFrom::Start(_))));
9025
9026 let none: ResumeSessionRequest = serde_json::from_value(json!({
9027 "sessionId": "sess_abc123",
9028 "cwd": "/home/user/project",
9029 "replayFrom": null
9030 }))
9031 .unwrap();
9032 assert!(none.replay_from.is_none());
9033 }
9034
9035 #[test]
9036 fn test_auth_method_agent_serialization() {
9037 let method = AuthMethod::Agent(AuthMethodAgent::new("default-auth", "Default Auth"));
9038
9039 let json = serde_json::to_value(&method).unwrap();
9040 assert_eq!(
9041 json,
9042 json!({
9043 "methodId": "default-auth",
9044 "name": "Default Auth",
9045 "type": "agent"
9046 })
9047 );
9048 assert!(!json.as_object().unwrap().contains_key("description"));
9050
9051 let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9052 match deserialized {
9053 AuthMethod::Agent(AuthMethodAgent {
9054 method_id, name, ..
9055 }) => {
9056 assert_eq!(method_id.0.as_ref(), "default-auth");
9057 assert_eq!(name, "Default Auth");
9058 }
9059 _ => panic!("Expected Agent variant"),
9060 }
9061 }
9062
9063 #[test]
9064 fn test_auth_method_agent_deserialization() {
9065 let json = json!({
9066 "methodId": "agent-auth",
9067 "name": "Agent Auth",
9068 "type": "agent"
9069 });
9070
9071 let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9072 assert!(matches!(deserialized, AuthMethod::Agent(_)));
9073 }
9074
9075 #[test]
9076 fn test_auth_method_agent_requires_type() {
9077 assert!(
9078 serde_json::from_value::<AuthMethod>(json!({
9079 "methodId": "agent-auth",
9080 "name": "Agent Auth"
9081 }))
9082 .is_err()
9083 );
9084 }
9085
9086 #[test]
9087 fn test_auth_method_agent_rejects_null_type() {
9088 assert!(
9089 serde_json::from_value::<AuthMethod>(json!({
9090 "methodId": "agent-auth",
9091 "name": "Agent Auth",
9092 "type": null
9093 }))
9094 .is_err()
9095 );
9096 }
9097
9098 #[test]
9099 fn test_auth_method_unknown_does_not_hide_malformed_agent() {
9100 assert!(
9101 serde_json::from_value::<AuthMethod>(json!({
9102 "methodId": "agent-auth",
9103 "type": "agent"
9104 }))
9105 .is_err()
9106 );
9107 assert!(
9108 serde_json::from_value::<AuthMethod>(json!({
9109 "methodId": "api-key",
9110 "type": "env_var",
9111 "vars": [{"name": "API_KEY"}]
9112 }))
9113 .is_err()
9114 );
9115 }
9116
9117 #[test]
9118 fn test_auth_method_unknown_variant_roundtrip() {
9119 let method: AuthMethod = serde_json::from_value(json!({
9120 "methodId": "oauth",
9121 "name": "OAuth",
9122 "type": "_oauth",
9123 "authorizationUrl": "https://example.com/auth"
9124 }))
9125 .unwrap();
9126
9127 assert_eq!(method.method_id().0.as_ref(), "oauth");
9128 assert_eq!(method.name(), "OAuth");
9129 let AuthMethod::Other(unknown) = method else {
9130 panic!("expected unknown auth method");
9131 };
9132 assert_eq!(unknown.type_, "_oauth");
9133 assert_eq!(
9134 unknown.fields.get("authorizationUrl"),
9135 Some(&json!("https://example.com/auth"))
9136 );
9137
9138 assert_eq!(
9139 serde_json::to_value(AuthMethod::Other(unknown)).unwrap(),
9140 json!({
9141 "methodId": "oauth",
9142 "name": "OAuth",
9143 "type": "_oauth",
9144 "authorizationUrl": "https://example.com/auth"
9145 })
9146 );
9147 }
9148
9149 #[test]
9150 fn test_auth_method_unknown_does_not_hide_malformed_known_variant() {
9151 assert!(
9152 serde_json::from_value::<AuthMethod>(json!({
9153 "methodId": "terminal-auth",
9154 "type": "terminal"
9155 }))
9156 .is_err()
9157 );
9158 }
9159
9160 #[test]
9161 fn test_tool_call_and_terminal_cancel_serialization() {
9162 assert_eq!(AGENT_METHOD_NAMES.tool_call_cancel, "tool_call/cancel");
9163 assert_eq!(AGENT_METHOD_NAMES.terminal_cancel, "terminal/cancel");
9164 assert_eq!(
9165 ClientRequest::CancelToolCallRequest(Box::new(CancelToolCallRequest::new(
9166 "sess_abc123",
9167 "call_012"
9168 )))
9169 .method(),
9170 "tool_call/cancel"
9171 );
9172 assert_eq!(
9173 ClientRequest::CancelTerminalRequest(Box::new(CancelTerminalRequest::new(
9174 "sess_abc123",
9175 "term_003"
9176 )))
9177 .method(),
9178 "terminal/cancel"
9179 );
9180 assert_eq!(
9181 serde_json::to_value(CancelToolCallRequest::new("sess_abc123", "call_012")).unwrap(),
9182 json!({"sessionId": "sess_abc123", "toolCallId": "call_012"})
9183 );
9184 assert_eq!(
9185 serde_json::to_value(CancelTerminalRequest::new("sess_abc123", "term_003")).unwrap(),
9186 json!({"sessionId": "sess_abc123", "terminalId": "term_003"})
9187 );
9188 assert!(
9189 serde_json::from_value::<CancelToolCallRequest>(json!({"sessionId": "sess_abc123"}))
9190 .is_err()
9191 );
9192 assert_eq!(
9193 serde_json::to_value(CancelTerminalResponse::new()).unwrap(),
9194 json!({})
9195 );
9196 }
9197
9198 #[test]
9199 fn test_session_delete_serialization() {
9200 assert_eq!(AGENT_METHOD_NAMES.session_delete, "session/delete");
9201 assert_eq!(
9202 ClientRequest::DeleteSessionRequest(Box::new(DeleteSessionRequest::new("sess_abc123")))
9203 .method(),
9204 "session/delete"
9205 );
9206 assert_eq!(
9207 serde_json::to_value(DeleteSessionRequest::new("sess_abc123")).unwrap(),
9208 json!({
9209 "sessionId": "sess_abc123"
9210 })
9211 );
9212 assert_eq!(
9213 serde_json::to_value(DeleteSessionResponse::new()).unwrap(),
9214 json!({})
9215 );
9216 assert_eq!(
9217 serde_json::to_value(
9218 SessionCapabilities::new().delete(SessionDeleteCapabilities::new())
9219 )
9220 .unwrap(),
9221 json!({
9222 "delete": {}
9223 })
9224 );
9225 }
9226 #[cfg(feature = "unstable_session_set_title")]
9227 #[test]
9228 fn test_session_set_title_serialization() {
9229 assert_eq!(AGENT_METHOD_NAMES.session_set_title, "session/set_title");
9230 assert_eq!(
9231 ClientRequest::SetSessionTitleRequest(Box::new(SetSessionTitleRequest::new(
9232 "sess_abc123",
9233 "Investigate OAuth timeout"
9234 )))
9235 .method(),
9236 "session/set_title"
9237 );
9238 assert_eq!(
9239 serde_json::to_value(SetSessionTitleRequest::new(
9240 "sess_abc123",
9241 "Investigate OAuth timeout"
9242 ))
9243 .unwrap(),
9244 json!({
9245 "sessionId": "sess_abc123",
9246 "title": "Investigate OAuth timeout"
9247 })
9248 );
9249 assert_eq!(
9250 serde_json::to_value(SetSessionTitleResponse::new("Investigate OAuth timeout"))
9251 .unwrap(),
9252 json!({
9253 "title": "Investigate OAuth timeout"
9254 })
9255 );
9256 assert_eq!(
9257 serde_json::to_value(SessionCapabilities::new().title(SessionTitleCapabilities::new()))
9258 .unwrap(),
9259 json!({
9260 "title": {}
9261 })
9262 );
9263 }
9264
9265 #[cfg(feature = "unstable_session_set_title")]
9266 #[test]
9267 fn test_session_set_title_requires_title() {
9268 for params in [
9269 json!({"sessionId": "sess_abc123"}),
9270 json!({"sessionId": "sess_abc123", "title": null}),
9271 json!({"sessionId": "sess_abc123", "title": 42}),
9272 ] {
9273 assert!(serde_json::from_value::<SetSessionTitleRequest>(params).is_err());
9274 }
9275 for result in [json!({}), json!({"title": null})] {
9276 assert!(serde_json::from_value::<SetSessionTitleResponse>(result).is_err());
9277 }
9278 }
9279
9280 #[cfg(feature = "unstable_session_options")]
9281 #[test]
9282 fn test_session_options_serialization() {
9283 assert_eq!(AGENT_METHOD_NAMES.session_options, "session/options");
9284 assert_eq!(
9285 ClientRequest::SessionOptionsRequest(Box::new(SessionOptionsRequest::new(
9286 "/home/user/project"
9287 )))
9288 .method(),
9289 "session/options"
9290 );
9291 assert_eq!(
9292 serde_json::to_value(
9293 SessionOptionsRequest::new("/home/user/project")
9294 .session_id(SessionId::new("sess_abc123"))
9295 )
9296 .unwrap(),
9297 json!({"cwd": "/home/user/project", "sessionId": "sess_abc123"})
9298 );
9299 assert_eq!(
9300 serde_json::from_value::<SessionOptionsRequest>(
9301 json!({"cwd": "/home/user/project", "additionalDirectories": null, "sessionId": null})
9302 )
9303 .unwrap(),
9304 SessionOptionsRequest::new("/home/user/project")
9305 );
9306 let request = NewSessionRequest::new("/home/user/project").config_options(vec![
9307 InitialSessionConfigOption::new("model", SessionConfigOptionValue::id("model-2")),
9308 InitialSessionConfigOption::new("fast", SessionConfigOptionValue::boolean(true)),
9309 ]);
9310 let value = serde_json::to_value(&request).unwrap();
9311 assert_eq!(
9312 value["configOptions"],
9313 json!([
9314 {"configId": "model", "type": "id", "value": "model-2"},
9315 {"configId": "fast", "type": "boolean", "value": true}
9316 ])
9317 );
9318 assert_eq!(
9319 serde_json::from_value::<NewSessionRequest>(value).unwrap(),
9320 request
9321 );
9322 assert!(
9323 serde_json::from_value::<NewSessionRequest>(json!({
9324 "cwd": "/home/user/project",
9325 "mcpServers": [],
9326 "configOptions": [{"type": "boolean", "value": true}]
9327 }))
9328 .is_err()
9329 );
9330 assert_eq!(
9331 serde_json::to_value(SessionOptionsResponse::new()).unwrap(),
9332 json!({})
9333 );
9334 #[cfg(feature = "unstable_session_fork")]
9335 {
9336 let fork =
9337 ForkSessionRequest::new("sess_abc123", "/home/user/project").config_options(vec![
9338 InitialSessionConfigOption::new(
9339 "model",
9340 SessionConfigOptionValue::id("model-2"),
9341 ),
9342 ]);
9343 let value = serde_json::to_value(&fork).unwrap();
9344 assert_eq!(
9345 value["configOptions"],
9346 json!([{"configId": "model", "type": "id", "value": "model-2"}])
9347 );
9348 assert_eq!(
9349 serde_json::from_value::<ForkSessionRequest>(value).unwrap(),
9350 fork
9351 );
9352 assert_eq!(
9354 serde_json::from_value::<ForkSessionRequest>(json!({
9355 "sessionId": "sess_abc123",
9356 "cwd": "/home/user/project",
9357 "configOptions": null
9358 }))
9359 .unwrap(),
9360 ForkSessionRequest::new("sess_abc123", "/home/user/project")
9361 );
9362 assert!(
9363 serde_json::from_value::<ForkSessionRequest>(json!({
9364 "sessionId": "sess_abc123",
9365 "cwd": "/home/user/project",
9366 "configOptions": [{"type": "boolean", "value": true}]
9367 }))
9368 .is_err()
9369 );
9370 }
9371 assert_eq!(
9372 serde_json::to_value(
9373 SessionCapabilities::new().options(SessionOptionsCapabilities::new())
9374 )
9375 .unwrap(),
9376 json!({"options": {}})
9377 );
9378 }
9379
9380 #[cfg(feature = "unstable_session_status")]
9381 #[test]
9382 fn test_session_status_serialization() {
9383 assert_eq!(AGENT_METHOD_NAMES.session_status, "session/status");
9384 assert_eq!(
9385 ClientRequest::SessionStatusRequest(Box::new(SessionStatusRequest::new("sess_abc123")))
9386 .method(),
9387 "session/status"
9388 );
9389 assert_eq!(
9390 serde_json::to_value(SessionStatusRequest::new("sess_abc123")).unwrap(),
9391 json!({"sessionId": "sess_abc123"})
9392 );
9393 assert_eq!(
9394 serde_json::to_value(SessionStatusResponse::new(SessionStatus::Saved)).unwrap(),
9395 json!({"status": "saved"})
9396 );
9397 assert_eq!(
9398 serde_json::to_value(
9399 SessionCapabilities::new().status(SessionStatusCapabilities::new())
9400 )
9401 .unwrap(),
9402 json!({"status": {}})
9403 );
9404 assert_eq!(
9405 serde_json::to_value(SessionStatusResponse::new(SessionStatus::Open).state(
9406 StateUpdate::RequiresAction(crate::v2::RequiresActionStateUpdate::new())
9407 ))
9408 .unwrap(),
9409 json!({
9410 "status": "open",
9411 "state": {"state": "requires_action"}
9412 })
9413 );
9414 for state in [json!(null), json!("running"), json!({"state": 7})] {
9415 let response = serde_json::from_value::<SessionStatusResponse>(
9416 json!({"status": "open", "state": state}),
9417 )
9418 .unwrap();
9419 assert_eq!(response.state, None);
9420 }
9421 }
9422
9423 #[cfg(feature = "unstable_session_status")]
9424 #[test]
9425 fn test_session_status_is_strict_and_open() {
9426 let custom =
9427 serde_json::from_value::<SessionStatusResponse>(json!({"status": "_suspended"}))
9428 .unwrap();
9429 assert_eq!(
9430 custom.status,
9431 SessionStatus::Other("_suspended".to_string())
9432 );
9433 assert_eq!(
9434 serde_json::to_value(&custom).unwrap(),
9435 json!({"status": "_suspended"})
9436 );
9437 for result in [json!({}), json!({"status": null}), json!({"status": 1})] {
9438 assert!(serde_json::from_value::<SessionStatusResponse>(result).is_err());
9439 }
9440 for params in [json!({}), json!({"sessionId": null})] {
9441 assert!(serde_json::from_value::<SessionStatusRequest>(params).is_err());
9442 }
9443 }
9444
9445 #[cfg(feature = "unstable_session_archive")]
9446 #[test]
9447 fn test_session_archive_serialization() {
9448 assert_eq!(AGENT_METHOD_NAMES.session_archive, "session/archive");
9449 assert_eq!(AGENT_METHOD_NAMES.session_unarchive, "session/unarchive");
9450 assert_eq!(
9451 ClientRequest::ArchiveSessionRequest(Box::new(ArchiveSessionRequest::new(
9452 "sess_abc123"
9453 )))
9454 .method(),
9455 "session/archive"
9456 );
9457 assert_eq!(
9458 ClientRequest::UnarchiveSessionRequest(Box::new(UnarchiveSessionRequest::new(
9459 "sess_abc123"
9460 )))
9461 .method(),
9462 "session/unarchive"
9463 );
9464 assert_eq!(
9465 serde_json::to_value(ArchiveSessionRequest::new("sess_abc123")).unwrap(),
9466 json!({"sessionId": "sess_abc123"})
9467 );
9468 assert_eq!(
9469 serde_json::to_value(UnarchiveSessionResponse::new()).unwrap(),
9470 json!({})
9471 );
9472 assert_eq!(
9473 serde_json::to_value(
9474 SessionCapabilities::new().archive(SessionArchiveCapabilities::new())
9475 )
9476 .unwrap(),
9477 json!({"archive": {}})
9478 );
9479 assert_eq!(
9480 serde_json::to_value(
9481 ListSessionsRequest::new()
9482 .cwd("/home/user/project")
9483 .archived(SessionArchiveFilter::Only)
9484 )
9485 .unwrap(),
9486 json!({"cwd": "/home/user/project", "archived": "only"})
9487 );
9488 assert_eq!(
9489 serde_json::to_value(
9490 SessionInfo::new("sess_abc123", "/home/user/project").archived(true)
9491 )
9492 .unwrap(),
9493 json!({"sessionId": "sess_abc123", "cwd": "/home/user/project", "archived": true})
9494 );
9495 }
9496
9497 #[cfg(feature = "unstable_session_archive")]
9498 #[test]
9499 fn test_session_archive_filter_is_strict_and_open() {
9500 for (value, expected) in [
9501 (json!(null), None),
9502 (json!("include"), Some(SessionArchiveFilter::Include)),
9503 (
9504 json!("_recent"),
9505 Some(SessionArchiveFilter::Other("_recent".to_string())),
9506 ),
9507 ] {
9508 let request =
9509 serde_json::from_value::<ListSessionsRequest>(json!({"archived": value})).unwrap();
9510 assert_eq!(request.archived, expected);
9511 }
9512 for value in [json!(true), json!(1), json!({})] {
9513 assert!(
9514 serde_json::from_value::<ListSessionsRequest>(json!({"archived": value})).is_err()
9515 );
9516 }
9517 let info = serde_json::from_value::<SessionInfo>(
9518 json!({"sessionId": "sess_abc123", "cwd": "/home/user/project", "archived": "yes"}),
9519 )
9520 .unwrap();
9521 assert_eq!(info.archived, None);
9522 }
9523
9524 #[test]
9525 fn test_session_additional_directories_serialization() {
9526 assert_eq!(
9527 serde_json::to_value(NewSessionRequest::new("/home/user/project")).unwrap(),
9528 json!({
9529 "cwd": "/home/user/project",
9530 })
9531 );
9532 assert_eq!(
9533 serde_json::to_value(
9534 NewSessionRequest::new("/home/user/project").additional_directories(vec![
9535 PathBuf::from("/home/user/shared-lib"),
9536 PathBuf::from("/home/user/product-docs"),
9537 ])
9538 )
9539 .unwrap(),
9540 json!({
9541 "cwd": "/home/user/project",
9542 "additionalDirectories": [
9543 "/home/user/shared-lib",
9544 "/home/user/product-docs"
9545 ],
9546 })
9547 );
9548 assert_eq!(
9549 serde_json::to_value(ResumeSessionRequest::new(
9550 "sess_abc123",
9551 "/home/user/project"
9552 ))
9553 .unwrap(),
9554 json!({
9555 "sessionId": "sess_abc123",
9556 "cwd": "/home/user/project",
9557 })
9558 );
9559 assert_eq!(
9560 serde_json::from_value::<ResumeSessionRequest>(json!({
9561 "sessionId": "sess_abc123",
9562 "cwd": "/home/user/project"
9563 }))
9564 .unwrap()
9565 .mcp_servers,
9566 Vec::<McpServer>::new()
9567 );
9568 assert_eq!(
9569 serde_json::from_value::<ResumeSessionRequest>(json!({
9570 "sessionId": "sess_abc123",
9571 "cwd": "/home/user/project",
9572 "mcpServers": null
9573 }))
9574 .unwrap()
9575 .mcp_servers,
9576 Vec::<McpServer>::new()
9577 );
9578 assert_eq!(
9579 serde_json::to_value(SessionInfo::new("sess_abc123", "/home/user/project")).unwrap(),
9580 json!({
9581 "sessionId": "sess_abc123",
9582 "cwd": "/home/user/project"
9583 })
9584 );
9585 assert_eq!(
9586 serde_json::to_value(
9587 SessionInfo::new("sess_abc123", "/home/user/project").additional_directories(vec![
9588 PathBuf::from("/home/user/shared-lib"),
9589 PathBuf::from("/home/user/product-docs"),
9590 ])
9591 )
9592 .unwrap(),
9593 json!({
9594 "sessionId": "sess_abc123",
9595 "cwd": "/home/user/project",
9596 "additionalDirectories": [
9597 "/home/user/shared-lib",
9598 "/home/user/product-docs"
9599 ]
9600 })
9601 );
9602 assert_eq!(
9603 serde_json::from_value::<SessionInfo>(json!({
9604 "sessionId": "sess_abc123",
9605 "cwd": "/home/user/project"
9606 }))
9607 .unwrap()
9608 .additional_directories,
9609 Vec::<AbsolutePath>::new()
9610 );
9611 }
9612 #[test]
9613 fn test_session_additional_directories_capabilities_serialization() {
9614 assert_eq!(
9615 serde_json::to_value(
9616 SessionCapabilities::new()
9617 .additional_directories(SessionAdditionalDirectoriesCapabilities::new())
9618 )
9619 .unwrap(),
9620 json!({
9621 "additionalDirectories": {}
9622 })
9623 );
9624 }
9625
9626 #[test]
9627 fn test_session_system_prompt_capabilities_serialization() {
9628 assert_eq!(
9629 serde_json::to_value(
9630 SessionCapabilities::new().system_prompt(SessionSystemPromptCapabilities::new())
9631 )
9632 .unwrap(),
9633 json!({ "systemPrompt": {} })
9634 );
9635 assert_eq!(
9636 serde_json::to_value(
9637 SessionCapabilities::new().system_prompt(
9638 SessionSystemPromptCapabilities::new().mode(
9639 SessionSystemPromptModeCapabilities::new()
9640 .override_(SessionSystemPromptOverrideCapabilities::new())
9641 )
9642 )
9643 )
9644 .unwrap(),
9645 json!({ "systemPrompt": { "mode": { "override": {} } } })
9646 );
9647 assert_eq!(
9648 serde_json::from_value::<SessionCapabilities>(
9649 json!({ "systemPrompt": { "mode": { "override": {} } } })
9650 )
9651 .unwrap()
9652 .system_prompt
9653 .and_then(|capabilities| capabilities.mode)
9654 .and_then(|mode| mode.override_),
9655 Some(SessionSystemPromptOverrideCapabilities::new())
9656 );
9657
9658 assert_eq!(
9660 serde_json::from_value::<SessionCapabilities>(json!({ "systemPrompt": "yes" }))
9661 .unwrap()
9662 .system_prompt,
9663 None
9664 );
9665 assert_eq!(
9666 serde_json::from_value::<SessionCapabilities>(
9667 json!({ "systemPrompt": { "mode": { "override": true } } })
9668 )
9669 .unwrap()
9670 .system_prompt,
9671 Some(
9672 SessionSystemPromptCapabilities::new()
9673 .mode(SessionSystemPromptModeCapabilities::new())
9674 )
9675 );
9676 assert_eq!(
9677 serde_json::from_value::<SessionCapabilities>(
9678 json!({ "systemPrompt": { "mode": "override" } })
9679 )
9680 .unwrap()
9681 .system_prompt,
9682 Some(SessionSystemPromptCapabilities::new())
9683 );
9684 }
9685
9686 #[test]
9687 fn test_system_prompt_lifecycle_request_serialization() {
9688 let system_prompt = SystemPrompt::new(vec![ContentBlock::from(
9689 "You are a code review specialist.",
9690 )]);
9691 let system_prompt_json = json!({
9692 "mode": "append",
9693 "content": [{ "type": "text", "text": "You are a code review specialist." }]
9694 });
9695
9696 let request =
9697 NewSessionRequest::new("/home/user/project").system_prompt(system_prompt.clone());
9698 let request_json = json!({
9699 "cwd": "/home/user/project",
9700 "systemPrompt": system_prompt_json
9701 });
9702 assert_eq!(serde_json::to_value(&request).unwrap(), request_json);
9703 assert_eq!(
9704 serde_json::from_value::<NewSessionRequest>(request_json).unwrap(),
9705 request
9706 );
9707
9708 assert_eq!(
9709 serde_json::to_value(
9710 ResumeSessionRequest::new("sess_abc123", "/home/user/project")
9711 .system_prompt(system_prompt.clone())
9712 )
9713 .unwrap()["systemPrompt"],
9714 system_prompt_json
9715 );
9716 #[cfg(feature = "unstable_session_fork")]
9717 assert_eq!(
9718 serde_json::to_value(
9719 ForkSessionRequest::new("sess_abc123", "/home/user/project")
9720 .system_prompt(system_prompt.clone())
9721 )
9722 .unwrap()["systemPrompt"],
9723 system_prompt_json
9724 );
9725
9726 let override_prompt =
9727 SystemPrompt::new(vec![ContentBlock::from("...")]).mode(SystemPromptMode::Override);
9728 let override_json = json!({
9729 "mode": "override",
9730 "content": [{ "type": "text", "text": "..." }]
9731 });
9732 assert_eq!(
9733 serde_json::to_value(&override_prompt).unwrap(),
9734 override_json
9735 );
9736 assert_eq!(
9737 serde_json::from_value::<SystemPrompt>(override_json).unwrap(),
9738 override_prompt
9739 );
9740 }
9741
9742 #[test]
9745 fn test_system_prompt_new_defaults_to_append() {
9746 let system_prompt = SystemPrompt::new(vec![ContentBlock::from("...")]);
9747 assert_eq!(system_prompt.mode, SystemPromptMode::Append);
9748 assert_eq!(
9749 serde_json::to_value(&system_prompt).unwrap(),
9750 json!({ "mode": "append", "content": [{ "type": "text", "text": "..." }] })
9751 );
9752 }
9753
9754 #[test]
9758 fn test_system_prompt_preserves_unknown_modes() {
9759 for mode in ["_vendor_mode", "prepend"] {
9760 let system_prompt_json =
9761 json!({ "mode": mode, "content": [{ "type": "text", "text": "..." }] });
9762 let system_prompt: SystemPrompt =
9763 serde_json::from_value(system_prompt_json.clone()).unwrap();
9764 assert_eq!(
9765 system_prompt.mode,
9766 SystemPromptMode::Other(mode.to_string())
9767 );
9768 assert_eq!(
9769 serde_json::to_value(&system_prompt).unwrap(),
9770 system_prompt_json
9771 );
9772 }
9773 }
9774
9775 fn assert_system_prompt_is_strict<T>(base: &serde_json::Value)
9779 where
9780 T: serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
9781 {
9782 let name = std::any::type_name::<T>();
9783 let with = |system_prompt: serde_json::Value| {
9784 let mut request = base.clone();
9785 request["systemPrompt"] = system_prompt;
9786 serde_json::from_value::<T>(request)
9787 };
9788
9789 for system_prompt in [
9790 json!("You are a code review specialist."),
9791 json!({ "content": [{ "type": "text", "text": "..." }] }),
9792 json!({ "mode": null, "content": [{ "type": "text", "text": "..." }] }),
9793 json!({ "mode": 1, "content": [{ "type": "text", "text": "..." }] }),
9794 json!({ "mode": "append" }),
9795 json!({ "mode": "append", "content": "..." }),
9796 json!({ "mode": "append", "content": [{ "type": "text" }] }),
9797 ] {
9798 assert!(
9799 with(system_prompt.clone()).is_err(),
9800 "{name}.systemPrompt: {system_prompt}"
9801 );
9802 }
9803
9804 assert_eq!(
9805 with(serde_json::Value::Null).unwrap(),
9806 serde_json::from_value::<T>(base.clone()).unwrap(),
9807 "{name}.systemPrompt"
9808 );
9809 }
9810
9811 #[test]
9812 fn test_session_setup_requests_reject_malformed_system_prompts() {
9813 assert!(
9814 serde_json::to_value(NewSessionRequest::new("/repo"))
9815 .unwrap()
9816 .get("systemPrompt")
9817 .is_none()
9818 );
9819 assert_system_prompt_is_strict::<NewSessionRequest>(&json!({ "cwd": "/repo" }));
9820 assert_system_prompt_is_strict::<ResumeSessionRequest>(&json!({
9821 "sessionId": "sess-1",
9822 "cwd": "/repo"
9823 }));
9824 #[cfg(feature = "unstable_session_fork")]
9825 assert_system_prompt_is_strict::<ForkSessionRequest>(&json!({
9826 "sessionId": "sess-1",
9827 "cwd": "/repo"
9828 }));
9829 }
9830
9831 #[test]
9834 fn test_system_prompt_preserves_unknown_content_blocks() {
9835 let request: NewSessionRequest = serde_json::from_value(json!({
9836 "cwd": "/home/user/project",
9837 "systemPrompt": {
9838 "mode": "append",
9839 "content": [{ "type": "_vendor_video", "uri": "https://example.com/intro.mp4" }]
9840 }
9841 }))
9842 .unwrap();
9843 let content = request.system_prompt.unwrap().content;
9844 assert_eq!(content.len(), 1);
9845 assert!(matches!(content[0], ContentBlock::Other(_)));
9846 }
9847
9848 #[test]
9849 fn test_auth_method_terminal_serialization() {
9850 let method = AuthMethod::Terminal(AuthMethodTerminal::new("tui-auth", "Terminal Auth"));
9851
9852 let json = serde_json::to_value(&method).unwrap();
9853 assert_eq!(
9854 json,
9855 json!({
9856 "methodId": "tui-auth",
9857 "name": "Terminal Auth",
9858 "type": "terminal"
9859 })
9860 );
9861 assert!(!json.as_object().unwrap().contains_key("args"));
9863 assert!(!json.as_object().unwrap().contains_key("env"));
9864
9865 let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9866 match deserialized {
9867 AuthMethod::Terminal(AuthMethodTerminal { args, env, .. }) => {
9868 assert_eq!(args, Vec::<String>::new());
9869 assert_eq!(env, []);
9870 }
9871 _ => panic!("Expected Terminal variant"),
9872 }
9873 }
9874
9875 #[test]
9876 fn test_auth_method_terminal_with_args_and_env_serialization() {
9877 let method = AuthMethod::Terminal(
9878 AuthMethodTerminal::new("tui-auth", "Terminal Auth")
9879 .args(vec!["--interactive".to_string(), "--color".to_string()])
9880 .env(vec![EnvVariable::new("TERM", "xterm-256color")]),
9881 );
9882
9883 let json = serde_json::to_value(&method).unwrap();
9884 assert_eq!(
9885 json,
9886 json!({
9887 "methodId": "tui-auth",
9888 "name": "Terminal Auth",
9889 "type": "terminal",
9890 "args": ["--interactive", "--color"],
9891 "env": [
9892 {
9893 "name": "TERM",
9894 "value": "xterm-256color"
9895 }
9896 ]
9897 })
9898 );
9899
9900 let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9901 match deserialized {
9902 AuthMethod::Terminal(AuthMethodTerminal { args, env, .. }) => {
9903 assert_eq!(args, vec!["--interactive", "--color"]);
9904 assert_eq!(env.len(), 1);
9905 assert_eq!(env[0].name, "TERM");
9906 assert_eq!(env[0].value, "xterm-256color");
9907 }
9908 _ => panic!("Expected Terminal variant"),
9909 }
9910 }
9911
9912 #[test]
9913 fn test_session_config_option_id_serialize() {
9914 let val = SessionConfigOptionValue::id("model-1");
9915 let json = serde_json::to_value(&val).unwrap();
9916 assert_eq!(json, json!({ "type": "id", "value": "model-1" }));
9917 }
9918
9919 #[test]
9920 fn test_session_config_option_value_boolean_serialize() {
9921 let val = SessionConfigOptionValue::boolean(true);
9922 let json = serde_json::to_value(&val).unwrap();
9923 assert_eq!(json, json!({ "type": "boolean", "value": true }));
9924 }
9925
9926 #[test]
9927 fn test_session_config_option_value_deserialize_id() {
9928 let json = json!({ "type": "id", "value": "model-1" });
9929 let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9930 assert_eq!(val, SessionConfigOptionValue::id("model-1"));
9931 assert_eq!(val.as_id().unwrap().to_string(), "model-1");
9932 }
9933
9934 #[test]
9935 fn test_session_config_option_value_deserialize_requires_type() {
9936 let json = json!({ "value": "model-1" });
9937 let result = serde_json::from_value::<SessionConfigOptionValue>(json);
9938 assert!(result.is_err());
9939 }
9940
9941 #[test]
9942 fn test_session_config_option_value_deserialize_boolean() {
9943 let json = json!({ "type": "boolean", "value": true });
9944 let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9945 assert_eq!(val, SessionConfigOptionValue::boolean(true));
9946 assert_eq!(val.as_bool(), Some(true));
9947 }
9948
9949 #[test]
9950 fn test_session_config_option_value_deserialize_boolean_false() {
9951 let json = json!({ "type": "boolean", "value": false });
9952 let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9953 assert_eq!(val, SessionConfigOptionValue::boolean(false));
9954 assert_eq!(val.as_bool(), Some(false));
9955 }
9956
9957 #[test]
9958 fn test_session_config_option_value_deserialize_unknown_type_with_string_value() {
9959 let json = json!({
9960 "type": "text",
9961 "value": "freeform input",
9962 "maxLength": 200
9963 });
9964 let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9965 let SessionConfigOptionValue::Other(unknown) = val else {
9966 panic!("Expected Other variant");
9967 };
9968 assert_eq!(unknown.type_, "text");
9969 assert_eq!(unknown.value, json!("freeform input"));
9970 assert_eq!(unknown.fields["maxLength"], json!(200));
9971 }
9972
9973 #[test]
9974 fn test_session_config_option_value_deserialize_unknown_type_with_object_value() {
9975 let json = json!({
9976 "type": "range",
9977 "value": { "min": 1, "max": 5 }
9978 });
9979 let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9980 let SessionConfigOptionValue::Other(unknown) = val else {
9981 panic!("Expected Other variant");
9982 };
9983 assert_eq!(unknown.type_, "range");
9984 assert_eq!(unknown.value, json!({ "min": 1, "max": 5 }));
9985 }
9986
9987 #[test]
9988 fn test_session_config_option_value_roundtrip_id() {
9989 let original = SessionConfigOptionValue::id("option-a");
9990 let json = serde_json::to_value(&original).unwrap();
9991 let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9992 assert_eq!(original, roundtripped);
9993 }
9994
9995 #[test]
9996 fn test_session_config_option_value_roundtrip_boolean() {
9997 let original = SessionConfigOptionValue::boolean(false);
9998 let json = serde_json::to_value(&original).unwrap();
9999 let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10000 assert_eq!(original, roundtripped);
10001 }
10002
10003 #[test]
10004 fn test_session_config_option_value_roundtrip_other() {
10005 let mut fields = BTreeMap::new();
10006 fields.insert("maxLength".to_string(), json!(200));
10007 let original = SessionConfigOptionValue::Other(OtherSessionConfigOptionValue::new(
10008 "text",
10009 json!("freeform input"),
10010 fields,
10011 ));
10012 let json = serde_json::to_value(&original).unwrap();
10013 let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10014 assert_eq!(original, roundtripped);
10015 }
10016
10017 #[test]
10018 fn test_session_config_option_value_type_mismatch_boolean_with_string() {
10019 let json = json!({ "type": "boolean", "value": "not a bool" });
10020 let result = serde_json::from_value::<SessionConfigOptionValue>(json);
10021 assert!(result.is_err());
10022 }
10023
10024 #[test]
10025 fn test_session_config_option_value_from_impls() {
10026 let from_str: SessionConfigOptionValue = "model-1".into();
10027 assert_eq!(from_str.as_id().unwrap().to_string(), "model-1");
10028
10029 let from_id: SessionConfigOptionValue = SessionConfigValueId::new("model-2").into();
10030 assert_eq!(from_id.as_id().unwrap().to_string(), "model-2");
10031
10032 let from_bool: SessionConfigOptionValue = true.into();
10033 assert_eq!(from_bool.as_bool(), Some(true));
10034 }
10035
10036 #[test]
10037 fn test_set_session_config_option_request_id() {
10038 let req = SetSessionConfigOptionRequest::new("sess_1", "model", "model-1");
10039 let json = serde_json::to_value(&req).unwrap();
10040 assert_eq!(
10041 json,
10042 json!({
10043 "sessionId": "sess_1",
10044 "configId": "model",
10045 "type": "id",
10046 "value": "model-1"
10047 })
10048 );
10049 }
10050
10051 #[test]
10052 fn test_set_session_config_option_request_boolean() {
10053 let req = SetSessionConfigOptionRequest::new("sess_1", "brave_mode", true);
10054 let json = serde_json::to_value(&req).unwrap();
10055 assert_eq!(
10056 json,
10057 json!({
10058 "sessionId": "sess_1",
10059 "configId": "brave_mode",
10060 "type": "boolean",
10061 "value": true
10062 })
10063 );
10064 }
10065
10066 #[test]
10067 fn test_set_session_config_option_request_deserialize_requires_type() {
10068 let json = json!({
10069 "sessionId": "sess_1",
10070 "configId": "model",
10071 "value": "model-1"
10072 });
10073 let result = serde_json::from_value::<SetSessionConfigOptionRequest>(json);
10074 assert!(result.is_err());
10075 }
10076
10077 #[test]
10078 fn test_set_session_config_option_request_deserialize_boolean() {
10079 let json = json!({
10080 "sessionId": "sess_1",
10081 "configId": "brave_mode",
10082 "type": "boolean",
10083 "value": true
10084 });
10085 let req: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
10086 assert_eq!(req.value.as_bool(), Some(true));
10087 }
10088
10089 #[test]
10090 fn test_set_session_config_option_request_roundtrip_id() {
10091 let original = SetSessionConfigOptionRequest::new("s", "c", "v");
10092 let json = serde_json::to_value(&original).unwrap();
10093 let roundtripped: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
10094 assert_eq!(original, roundtripped);
10095 }
10096
10097 #[test]
10098 fn test_set_session_config_option_request_roundtrip_boolean() {
10099 let original = SetSessionConfigOptionRequest::new("s", "c", false);
10100 let json = serde_json::to_value(&original).unwrap();
10101 let roundtripped: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
10102 assert_eq!(original, roundtripped);
10103 }
10104
10105 #[test]
10106 fn test_session_config_boolean_serialization() {
10107 let cfg = SessionConfigBoolean::new(true);
10108 let json = serde_json::to_value(&cfg).unwrap();
10109 assert_eq!(json, json!({ "currentValue": true }));
10110
10111 let deserialized: SessionConfigBoolean = serde_json::from_value(json).unwrap();
10112 assert!(deserialized.current_value);
10113 }
10114
10115 #[test]
10116 fn test_session_config_option_boolean_variant() {
10117 let opt = SessionConfigOption::boolean("brave_mode", "Brave Mode", false)
10118 .description("Skip confirmation prompts")
10119 .meta(test_meta());
10120 assert_eq!(serialized_meta_key_count(&opt), 1);
10121
10122 let json = serde_json::to_value(&opt).unwrap();
10123 assert_eq!(
10124 json,
10125 json!({
10126 "configId": "brave_mode",
10127 "name": "Brave Mode",
10128 "description": "Skip confirmation prompts",
10129 "type": "boolean",
10130 "currentValue": false,
10131 "_meta": {
10132 "source": "test"
10133 }
10134 })
10135 );
10136
10137 let deserialized: SessionConfigOption = serde_json::from_value(json).unwrap();
10138 assert_eq!(deserialized.config_id.to_string(), "brave_mode");
10139 assert_eq!(deserialized.name, "Brave Mode");
10140 match deserialized.kind {
10141 SessionConfigKind::Boolean(ref b) => assert!(!b.current_value),
10142 _ => panic!("Expected Boolean kind"),
10143 }
10144 }
10145
10146 #[test]
10147 fn test_session_config_option_select_still_works() {
10148 let opt = SessionConfigOption::select(
10150 "model",
10151 "Model",
10152 "model-1",
10153 vec![
10154 SessionConfigSelectOption::new("model-1", "Model 1"),
10155 SessionConfigSelectOption::new("model-2", "Model 2"),
10156 ],
10157 )
10158 .meta(test_meta());
10159 assert_eq!(serialized_meta_key_count(&opt), 1);
10160
10161 let json = serde_json::to_value(&opt).unwrap();
10162 assert_eq!(json["type"], "select");
10163 assert_eq!(json["currentValue"], "model-1");
10164 assert_eq!(json["options"].as_array().unwrap().len(), 2);
10165 assert_eq!(json["_meta"]["source"], "test");
10166
10167 let deserialized: SessionConfigOption = serde_json::from_value(json).unwrap();
10168 match deserialized.kind {
10169 SessionConfigKind::Select(ref s) => {
10170 assert_eq!(s.current_value.to_string(), "model-1");
10171 }
10172 _ => panic!("Expected Select kind"),
10173 }
10174 }
10175
10176 #[test]
10177 fn test_session_config_option_unknown_kind_roundtrip() {
10178 let option: SessionConfigOption = serde_json::from_value(json!({
10179 "configId": "verbosity",
10180 "name": "Verbosity",
10181 "type": "_slider",
10182 "currentValue": 3,
10183 "min": 0,
10184 "max": 5,
10185 "_meta": {
10186 "source": "test"
10187 }
10188 }))
10189 .unwrap();
10190
10191 assert_eq!(option.config_id.to_string(), "verbosity");
10192 assert_eq!(option.meta.as_ref().unwrap()["source"], "test");
10193 let SessionConfigKind::Other(unknown) = &option.kind else {
10194 panic!("expected unknown config kind");
10195 };
10196 assert_eq!(unknown.type_, "_slider");
10197 assert_eq!(unknown.fields.get("currentValue"), Some(&json!(3)));
10198 assert!(!unknown.fields.contains_key("_meta"));
10199 assert_eq!(serialized_meta_key_count(&option), 1);
10200
10201 let json = serde_json::to_value(&option).unwrap();
10202 assert_eq!(json["type"], "_slider");
10203 assert_eq!(json["currentValue"], 3);
10204 assert_eq!(json["min"], 0);
10205 assert_eq!(json["max"], 5);
10206 assert_eq!(json["_meta"]["source"], "test");
10207 }
10208
10209 #[test]
10210 fn test_session_config_option_unknown_kind_does_not_duplicate_flattened_meta() {
10211 let mut fields = std::collections::BTreeMap::new();
10212 fields.insert("currentValue".to_string(), json!(3));
10213 fields.insert("_meta".to_string(), json!({ "inner": "ignored" }));
10214
10215 let option = SessionConfigOption::new(
10216 "verbosity",
10217 "Verbosity",
10218 SessionConfigKind::Other(OtherSessionConfigKind::new("_slider", fields)),
10219 )
10220 .meta(test_meta());
10221
10222 let SessionConfigKind::Other(unknown) = &option.kind else {
10223 panic!("expected unknown config kind");
10224 };
10225 assert!(!unknown.fields.contains_key("_meta"));
10226 assert_eq!(serialized_meta_key_count(&option), 1);
10227
10228 let json = serde_json::to_value(&option).unwrap();
10229 assert_eq!(json["type"], "_slider");
10230 assert_eq!(json["currentValue"], 3);
10231 assert_eq!(json["_meta"]["source"], "test");
10232 }
10233
10234 #[test]
10235 fn test_session_config_option_unknown_does_not_hide_malformed_known_kind() {
10236 assert!(
10237 serde_json::from_value::<SessionConfigOption>(json!({
10238 "configId": "model",
10239 "name": "Model",
10240 "type": "select"
10241 }))
10242 .is_err()
10243 );
10244 }
10245
10246 #[cfg(feature = "unstable_llm_providers")]
10247 #[test]
10248 fn test_llm_protocol_known_variants() {
10249 assert_eq!(
10250 serde_json::to_value(&LlmProtocol::Anthropic).unwrap(),
10251 json!("anthropic")
10252 );
10253 assert_eq!(
10254 serde_json::to_value(&LlmProtocol::OpenAi).unwrap(),
10255 json!("openai")
10256 );
10257 assert_eq!(
10258 serde_json::to_value(&LlmProtocol::Azure).unwrap(),
10259 json!("azure")
10260 );
10261 assert_eq!(
10262 serde_json::to_value(&LlmProtocol::Vertex).unwrap(),
10263 json!("vertex")
10264 );
10265 assert_eq!(
10266 serde_json::to_value(&LlmProtocol::Bedrock).unwrap(),
10267 json!("bedrock")
10268 );
10269
10270 assert_eq!(
10271 serde_json::from_str::<LlmProtocol>("\"anthropic\"").unwrap(),
10272 LlmProtocol::Anthropic
10273 );
10274 assert_eq!(
10275 serde_json::from_str::<LlmProtocol>("\"openai\"").unwrap(),
10276 LlmProtocol::OpenAi
10277 );
10278 assert_eq!(
10279 serde_json::from_str::<LlmProtocol>("\"azure\"").unwrap(),
10280 LlmProtocol::Azure
10281 );
10282 assert_eq!(
10283 serde_json::from_str::<LlmProtocol>("\"vertex\"").unwrap(),
10284 LlmProtocol::Vertex
10285 );
10286 assert_eq!(
10287 serde_json::from_str::<LlmProtocol>("\"bedrock\"").unwrap(),
10288 LlmProtocol::Bedrock
10289 );
10290 }
10291
10292 #[cfg(feature = "unstable_llm_providers")]
10293 #[test]
10294 fn test_llm_protocol_unknown_variant() {
10295 let unknown: LlmProtocol = serde_json::from_str("\"cohere\"").unwrap();
10296 assert_eq!(unknown, LlmProtocol::Other("cohere".to_string()));
10297
10298 let json = serde_json::to_value(&unknown).unwrap();
10299 assert_eq!(json, json!("cohere"));
10300 }
10301
10302 #[cfg(feature = "unstable_llm_providers")]
10303 #[test]
10304 fn test_provider_current_config_serialization() {
10305 let config =
10306 ProviderCurrentConfig::new(LlmProtocol::Anthropic, "https://api.anthropic.com");
10307
10308 let json = serde_json::to_value(&config).unwrap();
10309 assert_eq!(
10310 json,
10311 json!({
10312 "apiType": "anthropic",
10313 "baseUrl": "https://api.anthropic.com"
10314 })
10315 );
10316
10317 let deserialized: ProviderCurrentConfig = serde_json::from_value(json).unwrap();
10318 assert_eq!(deserialized.api_type, LlmProtocol::Anthropic);
10319 assert_eq!(deserialized.base_url, "https://api.anthropic.com");
10320 }
10321
10322 #[cfg(feature = "unstable_llm_providers")]
10323 #[test]
10324 fn test_provider_info_with_current_config() {
10325 let info = ProviderInfo::new(
10326 "main",
10327 vec![LlmProtocol::Anthropic, LlmProtocol::OpenAi],
10328 true,
10329 Some(ProviderCurrentConfig::new(
10330 LlmProtocol::Anthropic,
10331 "https://api.anthropic.com",
10332 )),
10333 );
10334
10335 let json = serde_json::to_value(&info).unwrap();
10336 assert_eq!(
10337 json,
10338 json!({
10339 "providerId": "main",
10340 "supported": ["anthropic", "openai"],
10341 "required": true,
10342 "current": {
10343 "apiType": "anthropic",
10344 "baseUrl": "https://api.anthropic.com"
10345 }
10346 })
10347 );
10348
10349 let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10350 assert_eq!(deserialized.provider_id.to_string(), "main");
10351 assert_eq!(deserialized.supported.len(), 2);
10352 assert!(deserialized.required);
10353 assert!(deserialized.current.is_some());
10354 assert_eq!(
10355 deserialized.current.as_ref().unwrap().api_type,
10356 LlmProtocol::Anthropic
10357 );
10358 }
10359
10360 #[cfg(feature = "unstable_llm_providers")]
10361 #[test]
10362 fn test_provider_info_disabled() {
10363 let info = ProviderInfo::new(
10364 "secondary",
10365 vec![LlmProtocol::OpenAi],
10366 false,
10367 None::<ProviderCurrentConfig>,
10368 );
10369
10370 let json = serde_json::to_value(&info).unwrap();
10371 assert_eq!(
10372 json,
10373 json!({
10374 "providerId": "secondary",
10375 "supported": ["openai"],
10376 "required": false
10377 })
10378 );
10379
10380 let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10381 assert_eq!(deserialized.provider_id.to_string(), "secondary");
10382 assert!(!deserialized.required);
10383 assert!(deserialized.current.is_none());
10384 }
10385
10386 #[cfg(feature = "unstable_llm_providers")]
10387 #[test]
10388 fn test_provider_info_missing_current_defaults_to_none() {
10389 let json = json!({
10391 "providerId": "main",
10392 "supported": ["anthropic"],
10393 "required": true
10394 });
10395 let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10396 assert!(deserialized.current.is_none());
10397 }
10398
10399 #[cfg(feature = "unstable_llm_providers")]
10400 #[test]
10401 fn test_provider_info_explicit_null_current_decodes_to_none() {
10402 let json = json!({
10406 "providerId": "main",
10407 "supported": ["anthropic"],
10408 "required": true,
10409 "current": null
10410 });
10411 let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10412 assert!(deserialized.current.is_none());
10413 }
10414
10415 #[cfg(feature = "unstable_llm_providers")]
10416 #[test]
10417 fn test_list_providers_response_serialization() {
10418 let response = ListProvidersResponse::new(vec![ProviderInfo::new(
10419 "main",
10420 vec![LlmProtocol::Anthropic],
10421 true,
10422 Some(ProviderCurrentConfig::new(
10423 LlmProtocol::Anthropic,
10424 "https://api.anthropic.com",
10425 )),
10426 )]);
10427
10428 let json = serde_json::to_value(&response).unwrap();
10429 assert_eq!(json["providers"].as_array().unwrap().len(), 1);
10430 assert_eq!(json["providers"][0]["providerId"], "main");
10431
10432 let deserialized: ListProvidersResponse = serde_json::from_value(json).unwrap();
10433 assert_eq!(deserialized.providers.len(), 1);
10434 }
10435
10436 #[cfg(feature = "unstable_llm_providers")]
10437 #[test]
10438 fn test_set_provider_request_serialization() {
10439 use std::collections::HashMap;
10440
10441 let mut headers = HashMap::new();
10442 headers.insert("Authorization".to_string(), "Bearer sk-test".to_string());
10443
10444 let request =
10445 SetProviderRequest::new("main", LlmProtocol::OpenAi, "https://api.openai.com/v1")
10446 .headers(headers);
10447
10448 let json = serde_json::to_value(&request).unwrap();
10449 assert_eq!(
10450 json,
10451 json!({
10452 "providerId": "main",
10453 "apiType": "openai",
10454 "baseUrl": "https://api.openai.com/v1",
10455 "headers": {
10456 "Authorization": "Bearer sk-test"
10457 }
10458 })
10459 );
10460
10461 let deserialized: SetProviderRequest = serde_json::from_value(json).unwrap();
10462 assert_eq!(deserialized.provider_id.to_string(), "main");
10463 assert_eq!(deserialized.api_type, LlmProtocol::OpenAi);
10464 assert_eq!(deserialized.base_url, "https://api.openai.com/v1");
10465 assert_eq!(deserialized.headers.len(), 1);
10466 assert_eq!(
10467 deserialized.headers.get("Authorization").unwrap(),
10468 "Bearer sk-test"
10469 );
10470 }
10471
10472 #[cfg(feature = "unstable_llm_providers")]
10473 #[test]
10474 fn test_set_provider_request_omits_empty_headers() {
10475 let request =
10476 SetProviderRequest::new("main", LlmProtocol::Anthropic, "https://api.anthropic.com");
10477
10478 let json = serde_json::to_value(&request).unwrap();
10479 assert!(!json.as_object().unwrap().contains_key("headers"));
10481 }
10482
10483 #[cfg(feature = "unstable_llm_providers")]
10484 #[test]
10485 fn test_disable_provider_request_serialization() {
10486 let request = DisableProviderRequest::new("secondary");
10487
10488 let json = serde_json::to_value(&request).unwrap();
10489 assert_eq!(json, json!({ "providerId": "secondary" }));
10490
10491 let deserialized: DisableProviderRequest = serde_json::from_value(json).unwrap();
10492 assert_eq!(deserialized.provider_id.to_string(), "secondary");
10493 }
10494
10495 #[cfg(feature = "unstable_llm_providers")]
10496 #[test]
10497 fn test_providers_capabilities_serialization() {
10498 let caps = ProvidersCapabilities::new();
10499
10500 let json = serde_json::to_value(&caps).unwrap();
10501 assert_eq!(json, json!({}));
10502
10503 let deserialized: ProvidersCapabilities = serde_json::from_value(json).unwrap();
10504 assert!(deserialized.meta.is_none());
10505 }
10506
10507 #[cfg(feature = "unstable_llm_providers")]
10508 #[test]
10509 fn test_agent_capabilities_with_providers() {
10510 let caps = AgentCapabilities::new().providers(ProvidersCapabilities::new());
10511
10512 let json = serde_json::to_value(&caps).unwrap();
10513 assert_eq!(json["providers"], json!({}));
10514
10515 let deserialized: AgentCapabilities = serde_json::from_value(json).unwrap();
10516 assert!(deserialized.providers.is_some());
10517 }
10518
10519 #[test]
10520 fn test_agent_capabilities_session_is_explicit() {
10521 let json = serde_json::to_value(AgentCapabilities::new()).unwrap();
10522 assert!(json.get("session").is_none());
10523
10524 let caps = AgentCapabilities::new().session(
10525 SessionCapabilities::new()
10526 .prompt(PromptCapabilities::new().image(PromptImageCapabilities::new()))
10527 .mcp(McpCapabilities::new().stdio(McpStdioCapabilities::new())),
10528 );
10529
10530 assert_eq!(
10531 serde_json::to_value(&caps).unwrap(),
10532 json!({
10533 "session": {
10534 "prompt": {
10535 "image": {}
10536 },
10537 "mcp": {
10538 "stdio": {}
10539 }
10540 }
10541 })
10542 );
10543
10544 let deserialized: AgentCapabilities = serde_json::from_value(json!({
10545 "session": false
10546 }))
10547 .unwrap();
10548 assert!(deserialized.session.is_none());
10549 }
10550
10551 #[test]
10552 fn test_prompt_capabilities_serialize_supported_content_as_objects() {
10553 let caps = PromptCapabilities::new()
10554 .image(PromptImageCapabilities::new())
10555 .audio(PromptAudioCapabilities::new())
10556 .embedded_context(PromptEmbeddedContextCapabilities::new());
10557
10558 assert_eq!(
10559 serde_json::to_value(&caps).unwrap(),
10560 json!({
10561 "image": {},
10562 "audio": {},
10563 "embeddedContext": {}
10564 })
10565 );
10566
10567 let deserialized: PromptCapabilities = serde_json::from_value(json!({
10568 "image": null,
10569 "audio": false,
10570 "embeddedContext": {}
10571 }))
10572 .unwrap();
10573 assert!(deserialized.image.is_none());
10574 assert!(deserialized.audio.is_none());
10575 assert!(deserialized.embedded_context.is_some());
10576 }
10577
10578 #[cfg(feature = "unstable_agent_skills")]
10579 #[test]
10580 fn prompt_skill_capability_has_two_levels() {
10581 let leading = PromptCapabilities::new().skill(PromptSkillCapabilities::new());
10583 assert_eq!(
10584 serde_json::to_value(&leading).unwrap(),
10585 json!({ "skill": {} })
10586 );
10587
10588 let inline = PromptCapabilities::new()
10589 .skill(PromptSkillCapabilities::new().inline(PromptSkillInlineCapabilities::new()));
10590 let wire = json!({ "skill": { "inline": {} } });
10591 assert_eq!(serde_json::to_value(&inline).unwrap(), wire);
10592 assert_eq!(
10593 serde_json::from_value::<PromptCapabilities>(wire).unwrap(),
10594 inline
10595 );
10596
10597 for unsupported in [
10598 json!({}),
10599 json!({ "skill": null }),
10600 json!({ "skill": false }),
10601 json!({ "skill": true }),
10602 ] {
10603 let caps: PromptCapabilities = serde_json::from_value(unsupported).unwrap();
10604 assert!(caps.skill.is_none());
10605 }
10606
10607 for leading_only in [
10609 json!({ "skill": { "inline": null } }),
10610 json!({ "skill": { "inline": true } }),
10611 ] {
10612 assert_eq!(
10613 serde_json::from_value::<PromptCapabilities>(leading_only).unwrap(),
10614 leading
10615 );
10616 }
10617 }
10618
10619 #[test]
10620 fn test_mcp_capabilities_serialize_supported_transports_as_objects() {
10621 let caps = McpCapabilities::new()
10622 .stdio(McpStdioCapabilities::new())
10623 .http(McpHttpCapabilities::new());
10624
10625 assert_eq!(
10626 serde_json::to_value(&caps).unwrap(),
10627 json!({
10628 "stdio": {},
10629 "http": {}
10630 })
10631 );
10632
10633 let deserialized: McpCapabilities = serde_json::from_value(json!({
10634 "stdio": null,
10635 "http": false
10636 }))
10637 .unwrap();
10638 assert!(deserialized.stdio.is_none());
10639 assert!(deserialized.http.is_none());
10640 }
10641
10642 #[cfg(feature = "unstable_mcp_over_acp")]
10643 #[test]
10644 fn test_mcp_capabilities_serialize_acp_support_as_object() {
10645 let caps = McpCapabilities::new().acp(McpAcpCapabilities::new());
10646
10647 assert_eq!(
10648 serde_json::to_value(&caps).unwrap(),
10649 json!({
10650 "acp": {}
10651 })
10652 );
10653 }
10654
10655 #[test]
10656 fn prompt_request_rejects_malformed_content_block() {
10657 use serde_json::json;
10658
10659 assert!(
10660 serde_json::from_value::<PromptRequest>(json!({
10661 "sessionId": "sess-1",
10662 "prompt": [{"type": "text"}]
10663 }))
10664 .is_err()
10665 );
10666 }
10667
10668 #[test]
10669 fn prompt_request_rejects_non_array_prompt() {
10670 use serde_json::json;
10671
10672 assert!(
10673 serde_json::from_value::<PromptRequest>(json!({
10674 "sessionId": "sess-1",
10675 "prompt": "hello"
10676 }))
10677 .is_err()
10678 );
10679 }
10680
10681 fn prompt_request_with_idempotency_key(key: &serde_json::Value) -> serde_json::Value {
10682 serde_json::json!({
10683 "sessionId": "sess-1",
10684 "idempotencyKey": key,
10685 "prompt": [{"type": "text", "text": "hello"}]
10686 })
10687 }
10688
10689 #[test]
10690 fn prompt_request_idempotency_key_round_trips() {
10691 use serde_json::json;
10692
10693 let key = "0b6f3c1e-8d2a-4c57-9a41-5e2f7d90c3ab";
10694 let value = prompt_request_with_idempotency_key(&json!(key));
10695
10696 let request: PromptRequest = serde_json::from_value(value.clone()).unwrap();
10697 assert_eq!(
10698 request.idempotency_key.as_ref().map(IdempotencyKey::as_str),
10699 Some(key)
10700 );
10701 assert_eq!(serde_json::to_value(&request).unwrap(), value);
10702
10703 let built = PromptRequest::new("sess-1", vec![ContentBlock::from("hello")])
10704 .idempotency_key(IdempotencyKey::new(key).unwrap());
10705 assert_eq!(built, request);
10706 }
10707
10708 #[test]
10709 fn prompt_request_omitted_and_null_idempotency_key_mean_no_key() {
10710 use serde_json::json;
10711
10712 let omitted = json!({
10713 "sessionId": "sess-1",
10714 "prompt": [{"type": "text", "text": "hello"}]
10715 });
10716 let request: PromptRequest = serde_json::from_value(omitted.clone()).unwrap();
10717 assert_eq!(request.idempotency_key, None);
10718 assert_eq!(serde_json::to_value(&request).unwrap(), omitted);
10720
10721 let null: PromptRequest =
10722 serde_json::from_value(prompt_request_with_idempotency_key(&json!(null))).unwrap();
10723 assert_eq!(null, request);
10724 }
10725
10726 #[test]
10727 fn prompt_request_rejects_malformed_idempotency_key() {
10728 use serde_json::json;
10729
10730 let too_long = "k".repeat(IdempotencyKey::MAX_LENGTH + 1);
10731 for (name, key) in [
10732 ("an empty string", json!("")),
10733 ("a string over 255 characters", json!(too_long)),
10734 ("a number", json!(7)),
10735 ("a boolean", json!(true)),
10736 ("an object", json!({"key": "k"})),
10737 ("an array", json!(["k"])),
10738 ] {
10739 assert!(
10740 serde_json::from_value::<PromptRequest>(prompt_request_with_idempotency_key(&key))
10741 .is_err(),
10742 "{name} must fail the request instead of being treated as no key"
10743 );
10744 }
10745 }
10746
10747 #[test]
10748 fn idempotency_key_length_is_counted_in_characters() {
10749 use serde_json::json;
10750
10751 assert_eq!(IdempotencyKey::new(""), Err(InvalidIdempotencyKey::Empty));
10752 assert_eq!(IdempotencyKey::new("k").unwrap().as_str(), "k");
10753
10754 let longest = "k".repeat(IdempotencyKey::MAX_LENGTH);
10755 assert_eq!(
10756 IdempotencyKey::new(longest.as_str()).unwrap().as_str(),
10757 longest
10758 );
10759 assert_eq!(
10760 IdempotencyKey::new(format!("{longest}k")),
10761 Err(InvalidIdempotencyKey::TooLong)
10762 );
10763
10764 let multibyte = "é".repeat(IdempotencyKey::MAX_LENGTH);
10766 assert!(IdempotencyKey::new(multibyte.as_str()).is_ok());
10767 assert!(
10768 serde_json::from_value::<PromptRequest>(prompt_request_with_idempotency_key(&json!(
10769 multibyte
10770 )))
10771 .is_ok()
10772 );
10773 assert_eq!(
10774 IdempotencyKey::new(format!("{multibyte}é")),
10775 Err(InvalidIdempotencyKey::TooLong)
10776 );
10777
10778 assert_eq!("k".parse::<IdempotencyKey>().unwrap().to_string(), "k");
10779 assert_eq!(
10780 IdempotencyKey::try_from(String::new()),
10781 Err(InvalidIdempotencyKey::Empty)
10782 );
10783 assert_eq!(
10784 InvalidIdempotencyKey::TooLong.to_string(),
10785 "idempotency key must be at most 255 characters"
10786 );
10787 }
10788
10789 #[cfg(feature = "uuid")]
10790 #[test]
10791 fn generated_idempotency_keys_are_distinct_valid_v4_uuids() {
10792 let first = IdempotencyKey::generate();
10793 let second = IdempotencyKey::generate();
10794 assert_ne!(first, second);
10795
10796 for key in [&first, &second] {
10797 let uuid = uuid::Uuid::parse_str(key.as_str()).unwrap();
10798 assert_eq!(uuid.get_version_num(), 4);
10799 assert_eq!(IdempotencyKey::new(key.as_str()).as_ref(), Ok(key));
10801 let request = PromptRequest::new("sess-1", vec![ContentBlock::from("hello")])
10802 .idempotency_key(key.clone());
10803 let value = serde_json::to_value(&request).unwrap();
10804 assert_eq!(value["idempotencyKey"], key.as_str());
10805 assert_eq!(
10806 serde_json::from_value::<PromptRequest>(value).unwrap(),
10807 request
10808 );
10809 }
10810
10811 assert_eq!(
10812 IdempotencyKey::from(uuid::Uuid::nil()).as_str(),
10813 "00000000-0000-0000-0000-000000000000"
10814 );
10815 }
10816
10817 #[cfg(feature = "schemars")]
10818 #[test]
10819 fn idempotency_key_schema_is_a_strict_bounded_string() {
10820 use serde_json::json;
10821
10822 let key = serde_json::to_value(schemars::schema_for!(IdempotencyKey)).unwrap();
10823 assert_eq!(key["type"], "string");
10824 assert_eq!(key["minLength"], 1);
10825 assert_eq!(key["maxLength"], json!(IdempotencyKey::MAX_LENGTH));
10826
10827 let request = serde_json::to_value(schemars::schema_for!(PromptRequest)).unwrap();
10828 assert_eq!(request["required"], json!(["sessionId", "prompt"]));
10829 let property = &request["properties"]["idempotencyKey"];
10830 assert_eq!(
10831 property["anyOf"],
10832 json!([{"$ref": "#/$defs/IdempotencyKey"}, {"type": "null"}])
10833 );
10834 assert!(property.get("x-deserialize-default-on-error").is_none());
10837 }
10838
10839 fn assert_session_setup_lists_are_strict<T>(base: &serde_json::Value)
10840 where
10841 T: serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
10842 {
10843 let name = std::any::type_name::<T>();
10844 let with = |field: &str, value: serde_json::Value| {
10845 let mut request = base.clone();
10846 request[field] = value;
10847 serde_json::from_value::<T>(request)
10848 };
10849
10850 for (field, value) in [
10851 (
10853 "mcpServers",
10854 json!([
10855 {"type": "stdio", "name": "github", "command": "/usr/bin/gh-mcp", "env": [{"name": "GITHUB_TOKEN", "value": null}]},
10856 {"type": "stdio", "name": "fs", "command": "/usr/bin/fs-mcp"}
10857 ]),
10858 ),
10859 ("mcpServers", json!({"type": "stdio", "name": "fs"})),
10860 ("additionalDirectories", json!(["/repo/lib", 42])),
10861 ("additionalDirectories", json!("/repo/lib")),
10862 ] {
10863 assert!(
10864 with(field, value.clone()).is_err(),
10865 "{name}.{field}: {value}"
10866 );
10867 }
10868
10869 let empty = serde_json::from_value::<T>(base.clone()).unwrap();
10870 for field in ["mcpServers", "additionalDirectories"] {
10871 assert_eq!(
10872 with(field, serde_json::Value::Null).unwrap(),
10873 empty,
10874 "{name}.{field}"
10875 );
10876 }
10877 }
10878
10879 #[test]
10880 fn session_setup_requests_reject_malformed_mcp_servers_and_directories() {
10881 assert_session_setup_lists_are_strict::<NewSessionRequest>(&json!({"cwd": "/repo"}));
10882 assert_session_setup_lists_are_strict::<ResumeSessionRequest>(&json!({
10883 "sessionId": "sess-1",
10884 "cwd": "/repo"
10885 }));
10886 #[cfg(feature = "unstable_session_fork")]
10887 assert_session_setup_lists_are_strict::<ForkSessionRequest>(&json!({
10888 "sessionId": "sess-1",
10889 "cwd": "/repo"
10890 }));
10891 }
10892
10893 #[test]
10894 fn resume_session_request_rejects_malformed_replay_from() {
10895 let request = |replay_from: serde_json::Value| {
10896 serde_json::from_value::<ResumeSessionRequest>(json!({
10897 "sessionId": "sess-1",
10898 "cwd": "/repo",
10899 "replayFrom": replay_from
10900 }))
10901 };
10902
10903 assert!(request(json!("start")).is_err());
10905 assert_eq!(request(serde_json::Value::Null).unwrap().replay_from, None);
10906 assert!(matches!(
10907 request(json!({"type": "start"})).unwrap().replay_from,
10908 Some(ReplayFrom::Start(_))
10909 ));
10910 }
10911
10912 #[test]
10913 fn mcp_server_lists_treat_null_as_empty() {
10914 let servers: Vec<McpServer> = serde_json::from_value(json!([
10915 {"type": "stdio", "name": "fs", "command": "/usr/bin/fs-mcp", "args": null, "env": null},
10916 {"type": "http", "name": "api", "url": "https://example.com/mcp", "headers": null}
10917 ]))
10918 .unwrap();
10919
10920 assert_eq!(
10921 servers,
10922 vec![
10923 McpServer::Stdio(McpServerStdio::new("fs", "/usr/bin/fs-mcp")),
10924 McpServer::Http(McpServerHttp::new("api", "https://example.com/mcp")),
10925 ]
10926 );
10927 }
10928
10929 #[test]
10930 fn terminal_auth_methods_reject_malformed_launch_config() {
10931 let response: InitializeResponse = serde_json::from_value(json!({
10935 "protocolVersion": 2,
10936 "info": {"name": "agent", "version": "1.0.0"},
10937 "authMethods": [
10938 {"type": "terminal", "methodId": "bad-args", "name": "Log in", "args": ["auth", "--port", 8123]},
10939 {"type": "terminal", "methodId": "bad-env", "name": "Log in", "env": [{"name": "DEBUG", "value": 1}]},
10940 {"type": "terminal", "methodId": "null-config", "name": "Log in", "args": null, "env": null},
10941 {"type": "agent", "methodId": "agent", "name": "Agent login"}
10942 ]
10943 }))
10944 .unwrap();
10945
10946 assert_eq!(
10947 response.auth_methods,
10948 vec![
10949 AuthMethod::Terminal(AuthMethodTerminal::new("null-config", "Log in")),
10950 AuthMethod::Agent(AuthMethodAgent::new("agent", "Agent login")),
10951 ]
10952 );
10953 }
10954
10955 #[cfg(feature = "unstable_auth_status")]
10956 #[test]
10957 fn auth_status_response_round_trips() {
10958 let response = AuthStatusResponse::new(AuthState::Authenticated).accounts(vec![
10959 AuthAccount::new("Anthropic API key")
10960 .description("API key helper".to_string())
10961 .active(true),
10962 AuthAccount::new("Claude Max").email("user@example.com".to_string()),
10963 ]);
10964 let json = serde_json::to_value(&response).unwrap();
10965 assert_eq!(
10966 json,
10967 json!({
10968 "state": "authenticated",
10969 "accounts": [
10970 {
10971 "label": "Anthropic API key",
10972 "description": "API key helper",
10973 "active": true
10974 },
10975 {
10976 "label": "Claude Max",
10977 "email": "user@example.com"
10978 }
10979 ]
10980 })
10981 );
10982 assert_eq!(
10983 serde_json::from_value::<AuthStatusResponse>(json).unwrap(),
10984 response
10985 );
10986 assert_eq!(
10987 serde_json::to_value(AuthStatusResponse::new(AuthState::NotRequired)).unwrap(),
10988 json!({"state": "not_required"})
10989 );
10990 }
10991
10992 #[cfg(feature = "unstable_auth_status")]
10993 #[test]
10994 fn auth_status_state_is_strict_and_accounts_are_lenient() {
10995 assert!(serde_json::from_value::<AuthStatusResponse>(json!({})).is_err());
10996 assert!(serde_json::from_value::<AuthStatusResponse>(json!({"state": null})).is_err());
10997 assert!(serde_json::from_value::<AuthStatusResponse>(json!({"state": 1})).is_err());
10998
10999 let response: AuthStatusResponse = serde_json::from_value(json!({
11000 "state": "_vendor_state",
11001 "accounts": [
11002 {"active": true},
11003 {
11004 "label": "Vertex AI",
11005 "description": 42,
11006 "active": "yes",
11007 "email": ["not", "a", "string"]
11008 }
11009 ]
11010 }))
11011 .unwrap();
11012 assert_eq!(
11013 response,
11014 AuthStatusResponse::new(AuthState::Other("_vendor_state".to_string()))
11015 .accounts(vec![AuthAccount::new("Vertex AI")])
11016 );
11017 assert_eq!(
11018 serde_json::from_value::<AuthStatusResponse>(
11019 json!({"state": "unknown", "accounts": null})
11020 )
11021 .unwrap(),
11022 AuthStatusResponse::new(AuthState::Unknown)
11023 );
11024 }
11025
11026 #[cfg(feature = "unstable_auth_status")]
11027 #[test]
11028 fn auth_status_update_notification_routes() {
11029 use crate::v2::{AgentNotification, CLIENT_METHOD_NAMES};
11030
11031 assert_eq!(AGENT_METHOD_NAMES.auth_status, "auth/status");
11032 assert_eq!(CLIENT_METHOD_NAMES.auth_status_update, "auth/status_update");
11033 let notification = AgentNotification::AuthStatusUpdateNotification(Box::new(
11034 AuthStatusUpdateNotification::new(AuthState::Unauthenticated),
11035 ));
11036 assert_eq!(notification.method(), "auth/status_update");
11037 assert_eq!(
11038 serde_json::to_value(¬ification).unwrap(),
11039 json!({"state": "unauthenticated"})
11040 );
11041 }
11042
11043 #[cfg(all(
11044 feature = "unstable_session_fork",
11045 feature = "unstable_session_cursors"
11046 ))]
11047 #[test]
11048 fn fork_session_request_cursor_id_is_optional_and_strict() {
11049 let request = ForkSessionRequest::new("sess_abc123", "/home/user/project")
11050 .cursor_id(CursorId::new("cur_1"));
11051 let wire = json!({
11052 "sessionId": "sess_abc123",
11053 "cursorId": "cur_1",
11054 "cwd": "/home/user/project"
11055 });
11056 assert_eq!(serde_json::to_value(&request).unwrap(), wire);
11057 assert_eq!(
11058 serde_json::from_value::<ForkSessionRequest>(wire).unwrap(),
11059 request
11060 );
11061
11062 for wire in [
11064 json!({ "sessionId": "sess_abc123", "cwd": "/home/user/project" }),
11065 json!({ "sessionId": "sess_abc123", "cwd": "/home/user/project", "cursorId": null }),
11066 ] {
11067 assert_eq!(
11068 serde_json::from_value::<ForkSessionRequest>(wire)
11069 .unwrap()
11070 .cursor_id,
11071 None
11072 );
11073 }
11074
11075 assert!(
11077 serde_json::from_value::<ForkSessionRequest>(json!({
11078 "sessionId": "sess_abc123",
11079 "cwd": "/home/user/project",
11080 "cursorId": 7
11081 }))
11082 .is_err()
11083 );
11084 }
11085}