1use std::{borrow::Cow, sync::Arc};
7
8use derive_more::{Display, From};
9use indexmap::IndexMap;
10#[cfg(feature = "schemars")]
11use schemars::Schema;
12use serde::{Deserialize, Serialize};
13use serde_with::{DefaultOnError, DefaultOnNull, VecSkipError, serde_as, skip_serializing_none};
14
15use super::{
16 AbsolutePath, AvailableCommand, ClientCapabilities, ContentBlock, Error, ExtNotification,
17 ExtRequest, ExtResponse, MessageId, Meta, SessionId, TerminalId, ToolCallId,
18};
19use crate::{IntoOption, ProtocolVersion};
20
21#[cfg(all(
22 feature = "unstable_session_fork",
23 feature = "unstable_session_cursors"
24))]
25use super::CursorId;
26#[cfg(feature = "unstable_session_status")]
27use super::StateUpdate;
28
29#[cfg(all(feature = "unstable_auth_status", feature = "schemars"))]
30use super::AUTH_STATUS_UPDATE_NOTIFICATION;
31#[cfg(feature = "unstable_mcp_over_acp")]
32use super::mcp::{MCP_MESSAGE_METHOD_NAME, MessageMcpNotification};
33
34#[serde_as]
42#[skip_serializing_none]
43#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
44#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
45#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = INITIALIZE_METHOD_NAME)))]
46#[serde(rename_all = "camelCase")]
47#[non_exhaustive]
48pub struct InitializeRequest {
49 pub protocol_version: ProtocolVersion,
51 pub info: Implementation,
53 #[serde_as(deserialize_as = "DefaultOnError")]
55 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
56 #[serde(default)]
57 pub capabilities: ClientCapabilities,
58 #[serde_as(deserialize_as = "DefaultOnError")]
64 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
65 #[serde(default)]
66 #[serde(rename = "_meta")]
67 pub meta: Option<Meta>,
68}
69
70impl InitializeRequest {
71 #[must_use]
73 pub fn new(protocol_version: ProtocolVersion, info: Implementation) -> Self {
74 Self {
75 protocol_version,
76 capabilities: ClientCapabilities::default(),
77 info,
78 meta: None,
79 }
80 }
81
82 #[must_use]
84 pub fn capabilities(mut self, capabilities: ClientCapabilities) -> Self {
85 self.capabilities = capabilities;
86 self
87 }
88
89 #[must_use]
95 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
96 self.meta = meta.into_option();
97 self
98 }
99}
100
101#[serde_as]
107#[skip_serializing_none]
108#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
109#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
110#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = INITIALIZE_METHOD_NAME)))]
111#[serde(rename_all = "camelCase")]
112#[non_exhaustive]
113pub struct InitializeResponse {
114 pub protocol_version: ProtocolVersion,
121 pub info: Implementation,
123 #[serde_as(deserialize_as = "DefaultOnError")]
125 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
126 #[serde(default)]
127 pub capabilities: AgentCapabilities,
128 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
134 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
135 #[serde(default, skip_serializing_if = "Vec::is_empty")]
136 pub auth_methods: Vec<AuthMethod>,
137 #[serde_as(deserialize_as = "DefaultOnError")]
143 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
144 #[serde(default)]
145 #[serde(rename = "_meta")]
146 pub meta: Option<Meta>,
147}
148
149impl InitializeResponse {
150 #[must_use]
152 pub fn new(protocol_version: ProtocolVersion, info: Implementation) -> Self {
153 Self {
154 protocol_version,
155 capabilities: AgentCapabilities::default(),
156 auth_methods: vec![],
157 info,
158 meta: None,
159 }
160 }
161
162 #[must_use]
164 pub fn capabilities(mut self, capabilities: AgentCapabilities) -> Self {
165 self.capabilities = capabilities;
166 self
167 }
168
169 #[must_use]
174 pub fn auth_methods(mut self, auth_methods: Vec<AuthMethod>) -> Self {
175 self.auth_methods = auth_methods;
176 self
177 }
178
179 #[must_use]
185 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
186 self.meta = meta.into_option();
187 self
188 }
189}
190
191#[serde_as]
195#[skip_serializing_none]
196#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
197#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
198#[serde(rename_all = "camelCase")]
199#[non_exhaustive]
200pub struct Implementation {
201 pub name: String,
204 #[serde_as(deserialize_as = "DefaultOnError")]
210 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
211 #[serde(default)]
212 pub title: Option<String>,
213 pub version: String,
216 #[serde_as(deserialize_as = "DefaultOnError")]
222 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
223 #[serde(default)]
224 #[serde(rename = "_meta")]
225 pub meta: Option<Meta>,
226}
227
228impl Implementation {
229 #[must_use]
231 pub fn new(name: impl Into<String>, version: impl Into<String>) -> Self {
232 Self {
233 name: name.into(),
234 title: None,
235 version: version.into(),
236 meta: None,
237 }
238 }
239
240 #[must_use]
245 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
246 self.title = title.into_option();
247 self
248 }
249
250 #[must_use]
256 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
257 self.meta = meta.into_option();
258 self
259 }
260}
261
262#[serde_as]
272#[skip_serializing_none]
273#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
274#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
275#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGIN_METHOD_NAME)))]
276#[serde(rename_all = "camelCase")]
277#[non_exhaustive]
278pub struct LoginAuthRequest {
279 pub method_id: AuthMethodId,
282 #[serde_as(deserialize_as = "DefaultOnError")]
288 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
289 #[serde(default)]
290 #[serde(rename = "_meta")]
291 pub meta: Option<Meta>,
292}
293
294impl LoginAuthRequest {
295 #[must_use]
297 pub fn new(method_id: impl Into<AuthMethodId>) -> Self {
298 Self {
299 method_id: method_id.into(),
300 meta: None,
301 }
302 }
303
304 #[must_use]
310 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
311 self.meta = meta.into_option();
312 self
313 }
314}
315
316crate::serde_util::default_on_null! {
317 #[serde_as]
319 #[skip_serializing_none]
320 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
321 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
322 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGIN_METHOD_NAME)))]
323 #[serde(rename_all = "camelCase")]
324 #[non_exhaustive]
325 pub struct LoginAuthResponse {
326 #[serde_as(deserialize_as = "DefaultOnError")]
332 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
333 #[serde(default)]
334 #[serde(rename = "_meta")]
335 pub meta: Option<Meta>,
336 }
337}
338
339impl LoginAuthResponse {
340 #[must_use]
342 pub fn new() -> Self {
343 Self::default()
344 }
345
346 #[must_use]
352 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
353 self.meta = meta.into_option();
354 self
355 }
356}
357
358crate::serde_util::default_on_null! {
361 #[serde_as]
369 #[skip_serializing_none]
370 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
371 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
372 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGOUT_METHOD_NAME)))]
373 #[serde(rename_all = "camelCase")]
374 #[non_exhaustive]
375 pub struct LogoutAuthRequest {
376 #[serde_as(deserialize_as = "DefaultOnError")]
382 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
383 #[serde(default)]
384 #[serde(rename = "_meta")]
385 pub meta: Option<Meta>,
386 }
387}
388
389impl LogoutAuthRequest {
390 #[must_use]
392 pub fn new() -> Self {
393 Self::default()
394 }
395
396 #[must_use]
402 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
403 self.meta = meta.into_option();
404 self
405 }
406}
407
408crate::serde_util::default_on_null! {
409 #[serde_as]
411 #[skip_serializing_none]
412 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
413 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
414 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGOUT_METHOD_NAME)))]
415 #[serde(rename_all = "camelCase")]
416 #[non_exhaustive]
417 pub struct LogoutAuthResponse {
418 #[serde_as(deserialize_as = "DefaultOnError")]
424 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
425 #[serde(default)]
426 #[serde(rename = "_meta")]
427 pub meta: Option<Meta>,
428 }
429}
430
431impl LogoutAuthResponse {
432 #[must_use]
434 pub fn new() -> Self {
435 Self::default()
436 }
437
438 #[must_use]
444 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
445 self.meta = meta.into_option();
446 self
447 }
448}
449
450#[cfg(feature = "unstable_auth_status")]
453crate::serde_util::default_on_null! {
454 #[serde_as]
465 #[skip_serializing_none]
466 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
467 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
468 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_STATUS_METHOD_NAME)))]
469 #[serde(rename_all = "camelCase")]
470 #[non_exhaustive]
471 pub struct AuthStatusRequest {
472 #[serde_as(deserialize_as = "DefaultOnError")]
478 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
479 #[serde(default)]
480 #[serde(rename = "_meta")]
481 pub meta: Option<Meta>,
482 }
483}
484
485#[cfg(feature = "unstable_auth_status")]
486impl AuthStatusRequest {
487 #[must_use]
489 pub fn new() -> Self {
490 Self::default()
491 }
492
493 #[must_use]
499 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
500 self.meta = meta.into_option();
501 self
502 }
503}
504
505#[cfg(feature = "unstable_auth_status")]
511#[serde_as]
512#[skip_serializing_none]
513#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
514#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
515#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_STATUS_METHOD_NAME)))]
516#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"agent": [{"action": "replace", "target": "authStatus"}]})))]
517#[serde(rename_all = "camelCase")]
518#[non_exhaustive]
519pub struct AuthStatusResponse {
520 pub state: AuthState,
525 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
531 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
532 #[serde(default, skip_serializing_if = "Vec::is_empty")]
533 pub accounts: Vec<AuthAccount>,
534 #[serde_as(deserialize_as = "DefaultOnError")]
540 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
541 #[serde(default)]
542 #[serde(rename = "_meta")]
543 pub meta: Option<Meta>,
544}
545
546#[cfg(feature = "unstable_auth_status")]
547impl AuthStatusResponse {
548 #[must_use]
550 pub fn new(state: AuthState) -> Self {
551 Self {
552 state,
553 accounts: vec![],
554 meta: None,
555 }
556 }
557
558 #[must_use]
560 pub fn accounts(mut self, accounts: Vec<AuthAccount>) -> Self {
561 self.accounts = accounts;
562 self
563 }
564
565 #[must_use]
571 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
572 self.meta = meta.into_option();
573 self
574 }
575}
576
577#[cfg(feature = "unstable_auth_status")]
587#[serde_as]
588#[skip_serializing_none]
589#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
590#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
591#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = AUTH_STATUS_UPDATE_NOTIFICATION)))]
592#[cfg_attr(feature = "schemars", schemars(extend("x-scope" = {})))]
593#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"agent": [{"action": "replace", "target": "authStatus"}]})))]
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]
999 pub fn description(&self) -> Option<&str> {
1000 match self {
1001 Self::Agent(a) => a.description.as_deref(),
1002 Self::Other(a) => a
1003 .fields
1004 .get("description")
1005 .and_then(serde_json::Value::as_str),
1006 Self::Terminal(t) => t.description.as_deref(),
1007 }
1008 }
1009
1010 #[must_use]
1016 pub fn meta(&self) -> Option<&Meta> {
1017 match self {
1018 Self::Agent(a) => a.meta.as_ref(),
1019 Self::Other(a) => a.fields.get("_meta").and_then(serde_json::Value::as_object),
1020 Self::Terminal(t) => t.meta.as_ref(),
1021 }
1022 }
1023}
1024
1025#[serde_as]
1027#[skip_serializing_none]
1028#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1029#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1030#[cfg_attr(feature = "schemars", schemars(inline))]
1031#[cfg_attr(feature = "schemars", schemars(transform = other_auth_method_schema))]
1032#[serde(rename_all = "camelCase")]
1033#[non_exhaustive]
1034pub struct OtherAuthMethod {
1035 #[serde(rename = "type")]
1041 pub type_: String,
1042 pub method_id: AuthMethodId,
1044 pub name: String,
1046 #[serde(flatten)]
1049 pub fields: IndexMap<String, serde_json::Value>,
1050}
1051
1052impl OtherAuthMethod {
1053 #[must_use]
1055 pub fn new(
1056 type_: impl Into<String>,
1057 method_id: impl Into<AuthMethodId>,
1058 name: impl Into<String>,
1059 mut fields: IndexMap<String, serde_json::Value>,
1060 ) -> Self {
1061 fields.shift_remove("type");
1062 fields.shift_remove("methodId");
1063 fields.shift_remove("name");
1064 Self {
1065 type_: type_.into(),
1066 method_id: method_id.into(),
1067 name: name.into(),
1068 fields,
1069 }
1070 }
1071}
1072
1073impl<'de> Deserialize<'de> for OtherAuthMethod {
1074 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1075 where
1076 D: serde::Deserializer<'de>,
1077 {
1078 #[derive(Deserialize)]
1079 #[serde(rename_all = "camelCase")]
1080 struct RawOtherAuthMethod {
1081 #[serde(rename = "type")]
1082 type_: String,
1083 method_id: AuthMethodId,
1084 name: String,
1085 #[serde(flatten)]
1086 fields: IndexMap<String, serde_json::Value>,
1087 }
1088
1089 let raw = RawOtherAuthMethod::deserialize(deserializer)?;
1090 if is_known_auth_method_type(&raw.type_) {
1091 return Err(serde::de::Error::custom(format!(
1092 "known authentication method `{}` did not match its schema",
1093 raw.type_
1094 )));
1095 }
1096
1097 Ok(Self {
1098 type_: raw.type_,
1099 method_id: raw.method_id,
1100 name: raw.name,
1101 fields: raw.fields,
1102 })
1103 }
1104}
1105
1106fn is_known_auth_method_type(type_: &str) -> bool {
1107 matches!(type_, "agent" | "terminal")
1108}
1109
1110#[cfg(feature = "schemars")]
1111fn other_auth_method_schema(schema: &mut Schema) {
1112 super::schema_util::reject_known_string_discriminators(schema, "type", &["agent", "terminal"]);
1113}
1114
1115#[serde_as]
1119#[skip_serializing_none]
1120#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1121#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1122#[serde(rename_all = "camelCase")]
1123#[non_exhaustive]
1124pub struct AuthMethodAgent {
1125 pub method_id: AuthMethodId,
1127 pub name: String,
1129 #[serde_as(deserialize_as = "DefaultOnError")]
1134 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1135 #[serde(default)]
1136 pub description: Option<String>,
1137 #[serde_as(deserialize_as = "DefaultOnError")]
1143 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1144 #[serde(default)]
1145 #[serde(rename = "_meta")]
1146 pub meta: Option<Meta>,
1147}
1148
1149impl AuthMethodAgent {
1150 #[must_use]
1152 pub fn new(method_id: impl Into<AuthMethodId>, name: impl Into<String>) -> Self {
1153 Self {
1154 method_id: method_id.into(),
1155 name: name.into(),
1156 description: None,
1157 meta: None,
1158 }
1159 }
1160
1161 #[must_use]
1164 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
1165 self.description = description.into_option();
1166 self
1167 }
1168
1169 #[must_use]
1175 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1176 self.meta = meta.into_option();
1177 self
1178 }
1179}
1180
1181#[serde_as]
1189#[skip_serializing_none]
1190#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1191#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1192#[serde(rename_all = "camelCase")]
1193#[non_exhaustive]
1194pub struct AuthMethodTerminal {
1195 pub method_id: AuthMethodId,
1197 pub name: String,
1199 #[serde_as(deserialize_as = "DefaultOnError")]
1204 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1205 #[serde(default)]
1206 pub description: Option<String>,
1207 #[serde_as(deserialize_as = "DefaultOnNull")]
1209 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1210 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1211 pub args: Vec<String>,
1212 #[serde_as(deserialize_as = "DefaultOnNull")]
1216 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1217 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1218 pub env: Vec<EnvVariable>,
1219 #[serde_as(deserialize_as = "DefaultOnError")]
1225 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1226 #[serde(default)]
1227 #[serde(rename = "_meta")]
1228 pub meta: Option<Meta>,
1229}
1230
1231impl AuthMethodTerminal {
1232 #[must_use]
1234 pub fn new(method_id: impl Into<AuthMethodId>, name: impl Into<String>) -> Self {
1235 Self {
1236 method_id: method_id.into(),
1237 name: name.into(),
1238 description: None,
1239 args: Vec::new(),
1240 env: Vec::new(),
1241 meta: None,
1242 }
1243 }
1244
1245 #[must_use]
1247 pub fn args(mut self, args: Vec<String>) -> Self {
1248 self.args = args;
1249 self
1250 }
1251
1252 #[must_use]
1256 pub fn env(mut self, env: Vec<EnvVariable>) -> Self {
1257 self.env = env;
1258 self
1259 }
1260
1261 #[must_use]
1264 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
1265 self.description = description.into_option();
1266 self
1267 }
1268
1269 #[must_use]
1275 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1276 self.meta = meta.into_option();
1277 self
1278 }
1279}
1280
1281#[serde_as]
1287#[skip_serializing_none]
1288#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1289#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1290#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_NEW_METHOD_NAME)))]
1291#[serde(rename_all = "camelCase")]
1292#[non_exhaustive]
1293pub struct NewSessionRequest {
1294 pub cwd: AbsolutePath,
1296 #[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 additional_directories: Vec<AbsolutePath>,
1305 #[serde_as(deserialize_as = "DefaultOnNull")]
1307 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1308 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1309 pub mcp_servers: Vec<McpServer>,
1310 #[serde(default)]
1316 pub system_prompt: Option<SystemPrompt>,
1317 #[cfg(feature = "unstable_session_options")]
1335 #[serde_as(deserialize_as = "DefaultOnNull")]
1336 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1337 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1338 pub config_options: Vec<InitialSessionConfigOption>,
1339 #[serde_as(deserialize_as = "DefaultOnError")]
1345 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1346 #[serde(default)]
1347 #[serde(rename = "_meta")]
1348 pub meta: Option<Meta>,
1349}
1350
1351impl NewSessionRequest {
1352 #[must_use]
1354 pub fn new(cwd: impl Into<AbsolutePath>) -> Self {
1355 Self {
1356 cwd: cwd.into(),
1357 additional_directories: vec![],
1358 mcp_servers: vec![],
1359 system_prompt: None,
1360 #[cfg(feature = "unstable_session_options")]
1361 config_options: vec![],
1362 meta: None,
1363 }
1364 }
1365
1366 #[must_use]
1368 pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1369 where
1370 I: IntoIterator<Item = P>,
1371 P: Into<AbsolutePath>,
1372 {
1373 self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1374 self
1375 }
1376
1377 #[must_use]
1379 pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1380 self.mcp_servers = mcp_servers;
1381 self
1382 }
1383
1384 #[must_use]
1386 pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1387 self.system_prompt = system_prompt.into_option();
1388 self
1389 }
1390
1391 #[cfg(feature = "unstable_session_options")]
1409 #[must_use]
1410 pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1411 self.config_options = config_options;
1412 self
1413 }
1414
1415 #[must_use]
1421 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1422 self.meta = meta.into_option();
1423 self
1424 }
1425}
1426
1427#[serde_as]
1438#[skip_serializing_none]
1439#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1440#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1441#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_NEW_METHOD_NAME)))]
1442#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}, {"action": "replace", "target": "availableCommands", "value": "availableCommands"}]})))]
1443#[serde(rename_all = "camelCase")]
1444#[non_exhaustive]
1445pub struct NewSessionResponse {
1446 pub session_id: SessionId,
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 config_options: Vec<SessionConfigOption>,
1459 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1465 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1466 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1467 pub available_commands: Vec<AvailableCommand>,
1468 #[serde_as(deserialize_as = "DefaultOnError")]
1474 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1475 #[serde(default)]
1476 #[serde(rename = "_meta")]
1477 pub meta: Option<Meta>,
1478}
1479
1480impl NewSessionResponse {
1481 #[must_use]
1483 pub fn new(session_id: impl Into<SessionId>) -> Self {
1484 Self {
1485 session_id: session_id.into(),
1486 config_options: Vec::new(),
1487 available_commands: Vec::new(),
1488 meta: None,
1489 }
1490 }
1491
1492 #[must_use]
1498 pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
1499 self.config_options = config_options;
1500 self
1501 }
1502
1503 #[must_use]
1505 pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
1506 self.available_commands = available_commands;
1507 self
1508 }
1509
1510 #[must_use]
1516 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1517 self.meta = meta.into_option();
1518 self
1519 }
1520}
1521
1522#[cfg(feature = "unstable_session_fork")]
1535#[serde_as]
1536#[skip_serializing_none]
1537#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1538#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1539#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_FORK_METHOD_NAME)))]
1540#[serde(rename_all = "camelCase")]
1541#[non_exhaustive]
1542pub struct ForkSessionRequest {
1543 pub session_id: SessionId,
1545 #[cfg(feature = "unstable_session_cursors")]
1558 #[serde(default)]
1559 pub cursor_id: Option<CursorId>,
1560 pub cwd: AbsolutePath,
1562 #[serde_as(deserialize_as = "DefaultOnNull")]
1568 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1569 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1570 pub additional_directories: Vec<AbsolutePath>,
1571 #[serde_as(deserialize_as = "DefaultOnNull")]
1573 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1574 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1575 pub mcp_servers: Vec<McpServer>,
1576 #[serde(default)]
1584 pub system_prompt: Option<SystemPrompt>,
1585 #[cfg(feature = "unstable_session_options")]
1604 #[serde_as(deserialize_as = "DefaultOnNull")]
1605 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1606 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1607 pub config_options: Vec<InitialSessionConfigOption>,
1608 #[serde_as(deserialize_as = "DefaultOnError")]
1614 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1615 #[serde(default)]
1616 #[serde(rename = "_meta")]
1617 pub meta: Option<Meta>,
1618}
1619
1620#[cfg(feature = "unstable_session_fork")]
1621impl ForkSessionRequest {
1622 #[must_use]
1624 pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
1625 Self {
1626 session_id: session_id.into(),
1627 #[cfg(feature = "unstable_session_cursors")]
1628 cursor_id: None,
1629 cwd: cwd.into(),
1630 additional_directories: vec![],
1631 mcp_servers: vec![],
1632 system_prompt: None,
1633 #[cfg(feature = "unstable_session_options")]
1634 config_options: vec![],
1635 meta: None,
1636 }
1637 }
1638
1639 #[cfg(feature = "unstable_session_cursors")]
1648 #[must_use]
1649 pub fn cursor_id(mut self, cursor_id: impl IntoOption<CursorId>) -> Self {
1650 self.cursor_id = cursor_id.into_option();
1651 self
1652 }
1653
1654 #[must_use]
1656 pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1657 where
1658 I: IntoIterator<Item = P>,
1659 P: Into<AbsolutePath>,
1660 {
1661 self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1662 self
1663 }
1664
1665 #[must_use]
1667 pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1668 self.mcp_servers = mcp_servers;
1669 self
1670 }
1671
1672 #[must_use]
1674 pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1675 self.system_prompt = system_prompt.into_option();
1676 self
1677 }
1678
1679 #[cfg(feature = "unstable_session_options")]
1698 #[must_use]
1699 pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1700 self.config_options = config_options;
1701 self
1702 }
1703
1704 #[must_use]
1710 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1711 self.meta = meta.into_option();
1712 self
1713 }
1714}
1715
1716#[cfg(feature = "unstable_session_fork")]
1722#[serde_as]
1723#[skip_serializing_none]
1724#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1725#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1726#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_FORK_METHOD_NAME)))]
1727#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}, {"action": "replace", "target": "availableCommands", "value": "availableCommands"}]})))]
1728#[serde(rename_all = "camelCase")]
1729#[non_exhaustive]
1730pub struct ForkSessionResponse {
1731 pub session_id: SessionId,
1733 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1739 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1740 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1741 pub config_options: Vec<SessionConfigOption>,
1742 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1748 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1749 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1750 pub available_commands: Vec<AvailableCommand>,
1751 #[serde_as(deserialize_as = "DefaultOnError")]
1757 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1758 #[serde(default)]
1759 #[serde(rename = "_meta")]
1760 pub meta: Option<Meta>,
1761}
1762
1763#[cfg(feature = "unstable_session_fork")]
1764impl ForkSessionResponse {
1765 #[must_use]
1767 pub fn new(session_id: impl Into<SessionId>) -> Self {
1768 Self {
1769 session_id: session_id.into(),
1770 config_options: Vec::new(),
1771 available_commands: Vec::new(),
1772 meta: None,
1773 }
1774 }
1775
1776 #[must_use]
1782 pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
1783 self.config_options = config_options;
1784 self
1785 }
1786
1787 #[must_use]
1789 pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
1790 self.available_commands = available_commands;
1791 self
1792 }
1793
1794 #[must_use]
1800 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1801 self.meta = meta.into_option();
1802 self
1803 }
1804}
1805
1806#[serde_as]
1813#[skip_serializing_none]
1814#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1815#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1816#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_RESUME_METHOD_NAME)))]
1817#[serde(rename_all = "camelCase")]
1818#[non_exhaustive]
1819pub struct ResumeSessionRequest {
1820 pub session_id: SessionId,
1822 pub cwd: AbsolutePath,
1827 #[serde_as(deserialize_as = "DefaultOnNull")]
1834 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1835 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1836 pub additional_directories: Vec<AbsolutePath>,
1837 #[serde_as(deserialize_as = "DefaultOnNull")]
1842 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1843 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1844 pub mcp_servers: Vec<McpServer>,
1845 #[serde(default)]
1857 pub replay_from: Option<ReplayFrom>,
1858 #[serde(default)]
1866 pub system_prompt: Option<SystemPrompt>,
1867 #[cfg(feature = "unstable_session_options")]
1888 #[serde_as(deserialize_as = "DefaultOnNull")]
1889 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1890 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1891 pub config_options: Vec<InitialSessionConfigOption>,
1892 #[serde_as(deserialize_as = "DefaultOnError")]
1898 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1899 #[serde(default)]
1900 #[serde(rename = "_meta")]
1901 pub meta: Option<Meta>,
1902}
1903
1904impl ResumeSessionRequest {
1905 #[must_use]
1907 pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
1908 Self {
1909 session_id: session_id.into(),
1910 cwd: cwd.into(),
1911 additional_directories: vec![],
1912 mcp_servers: vec![],
1913 replay_from: None,
1914 system_prompt: None,
1915 #[cfg(feature = "unstable_session_options")]
1916 config_options: vec![],
1917 meta: None,
1918 }
1919 }
1920
1921 #[must_use]
1923 pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1924 where
1925 I: IntoIterator<Item = P>,
1926 P: Into<AbsolutePath>,
1927 {
1928 self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1929 self
1930 }
1931
1932 #[must_use]
1934 pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1935 self.mcp_servers = mcp_servers;
1936 self
1937 }
1938
1939 #[must_use]
1947 pub fn replay_from(mut self, replay_from: impl IntoOption<ReplayFrom>) -> Self {
1948 self.replay_from = replay_from.into_option();
1949 self
1950 }
1951
1952 #[must_use]
1954 pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1955 self.system_prompt = system_prompt.into_option();
1956 self
1957 }
1958
1959 #[cfg(feature = "unstable_session_options")]
1977 #[must_use]
1978 pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1979 self.config_options = config_options;
1980 self
1981 }
1982
1983 #[must_use]
1989 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1990 self.meta = meta.into_option();
1991 self
1992 }
1993}
1994
1995#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1999#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2000#[serde(tag = "type", rename_all = "snake_case")]
2001#[non_exhaustive]
2002pub enum ReplayFrom {
2003 Start(ReplayFromStart),
2005 #[serde(untagged)]
2016 Other(OtherReplayFrom),
2017}
2018
2019impl From<ReplayFromStart> for ReplayFrom {
2020 fn from(replay_from: ReplayFromStart) -> Self {
2021 Self::Start(replay_from)
2022 }
2023}
2024
2025#[serde_as]
2027#[skip_serializing_none]
2028#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2029#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2030#[serde(rename_all = "camelCase")]
2031#[non_exhaustive]
2032pub struct ReplayFromStart {
2033 #[serde_as(deserialize_as = "DefaultOnError")]
2039 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2040 #[serde(default)]
2041 #[serde(rename = "_meta")]
2042 pub meta: Option<Meta>,
2043}
2044
2045impl ReplayFromStart {
2046 #[must_use]
2048 pub fn new() -> Self {
2049 Self::default()
2050 }
2051
2052 #[must_use]
2058 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2059 self.meta = meta.into_option();
2060 self
2061 }
2062}
2063
2064#[serde_as]
2066#[skip_serializing_none]
2067#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2068#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
2069#[cfg_attr(feature = "schemars", schemars(inline))]
2070#[cfg_attr(feature = "schemars", schemars(transform = other_replay_from_schema))]
2071#[serde(rename_all = "camelCase")]
2072#[non_exhaustive]
2073pub struct OtherReplayFrom {
2074 #[serde(rename = "type")]
2080 pub type_: String,
2081 #[serde(flatten)]
2084 pub fields: IndexMap<String, serde_json::Value>,
2085}
2086
2087impl OtherReplayFrom {
2088 #[must_use]
2090 pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
2091 fields.shift_remove("type");
2092 Self {
2093 type_: type_.into(),
2094 fields,
2095 }
2096 }
2097}
2098
2099impl<'de> Deserialize<'de> for OtherReplayFrom {
2100 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2101 where
2102 D: serde::Deserializer<'de>,
2103 {
2104 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
2105 let type_ = fields
2106 .shift_remove("type")
2107 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
2108 let serde_json::Value::String(type_) = type_ else {
2109 return Err(serde::de::Error::custom("`type` must be a string"));
2110 };
2111
2112 if is_known_replay_from_type(&type_) {
2113 return Err(serde::de::Error::custom(format!(
2114 "known replay cursor `{type_}` did not match its schema"
2115 )));
2116 }
2117
2118 Ok(Self { type_, fields })
2119 }
2120}
2121
2122fn is_known_replay_from_type(type_: &str) -> bool {
2123 matches!(type_, "start")
2124}
2125
2126#[cfg(feature = "schemars")]
2127fn other_replay_from_schema(schema: &mut Schema) {
2128 super::schema_util::reject_known_string_discriminators(schema, "type", &["start"]);
2129}
2130
2131crate::serde_util::default_on_null! {
2132 #[serde_as]
2140 #[skip_serializing_none]
2141 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2142 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2143 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_RESUME_METHOD_NAME)))]
2144 #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}, {"action": "replace", "target": "availableCommands", "value": "availableCommands"}]})))]
2145 #[serde(rename_all = "camelCase")]
2146 #[non_exhaustive]
2147 pub struct ResumeSessionResponse {
2148 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2154 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2155 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2156 pub config_options: Vec<SessionConfigOption>,
2157 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2163 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2164 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2165 pub available_commands: Vec<AvailableCommand>,
2166 #[serde_as(deserialize_as = "DefaultOnError")]
2172 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2173 #[serde(default)]
2174 #[serde(rename = "_meta")]
2175 pub meta: Option<Meta>,
2176 }
2177}
2178
2179impl ResumeSessionResponse {
2180 #[must_use]
2182 pub fn new() -> Self {
2183 Self::default()
2184 }
2185
2186 #[must_use]
2192 pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
2193 self.config_options = config_options;
2194 self
2195 }
2196
2197 #[must_use]
2199 pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
2200 self.available_commands = available_commands;
2201 self
2202 }
2203
2204 #[must_use]
2210 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2211 self.meta = meta.into_option();
2212 self
2213 }
2214}
2215
2216#[serde_as]
2240#[skip_serializing_none]
2241#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2242#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2243#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CLOSE_METHOD_NAME)))]
2244#[serde(rename_all = "camelCase")]
2245#[non_exhaustive]
2246pub struct CloseSessionRequest {
2247 pub session_id: SessionId,
2249 #[serde_as(deserialize_as = "DefaultOnError")]
2255 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2256 #[serde(default)]
2257 #[serde(rename = "_meta")]
2258 pub meta: Option<Meta>,
2259}
2260
2261impl CloseSessionRequest {
2262 #[must_use]
2264 pub fn new(session_id: impl Into<SessionId>) -> Self {
2265 Self {
2266 session_id: session_id.into(),
2267 meta: None,
2268 }
2269 }
2270
2271 #[must_use]
2277 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2278 self.meta = meta.into_option();
2279 self
2280 }
2281}
2282
2283crate::serde_util::default_on_null! {
2284 #[serde_as]
2286 #[skip_serializing_none]
2287 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2288 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2289 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CLOSE_METHOD_NAME)))]
2290 #[serde(rename_all = "camelCase")]
2291 #[non_exhaustive]
2292 pub struct CloseSessionResponse {
2293 #[serde_as(deserialize_as = "DefaultOnError")]
2299 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2300 #[serde(default)]
2301 #[serde(rename = "_meta")]
2302 pub meta: Option<Meta>,
2303 }
2304}
2305
2306impl CloseSessionResponse {
2307 #[must_use]
2309 pub fn new() -> Self {
2310 Self::default()
2311 }
2312
2313 #[must_use]
2319 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2320 self.meta = meta.into_option();
2321 self
2322 }
2323}
2324
2325#[cfg(feature = "unstable_session_status")]
2339#[serde_as]
2340#[skip_serializing_none]
2341#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2342#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2343#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_STATUS_METHOD_NAME)))]
2344#[serde(rename_all = "camelCase")]
2345#[non_exhaustive]
2346pub struct SessionStatusRequest {
2347 pub session_id: SessionId,
2349 #[serde_as(deserialize_as = "DefaultOnError")]
2355 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2356 #[serde(default)]
2357 #[serde(rename = "_meta")]
2358 pub meta: Option<Meta>,
2359}
2360
2361#[cfg(feature = "unstable_session_status")]
2362impl SessionStatusRequest {
2363 #[must_use]
2365 pub fn new(session_id: impl Into<SessionId>) -> Self {
2366 Self {
2367 session_id: session_id.into(),
2368 meta: None,
2369 }
2370 }
2371
2372 #[must_use]
2378 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2379 self.meta = meta.into_option();
2380 self
2381 }
2382}
2383
2384#[cfg(feature = "unstable_session_status")]
2393#[serde_as]
2394#[skip_serializing_none]
2395#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2396#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2397#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_STATUS_METHOD_NAME)))]
2398#[serde(rename_all = "camelCase")]
2399#[non_exhaustive]
2400pub struct SessionStatusResponse {
2401 pub status: SessionStatus,
2405 #[serde_as(deserialize_as = "DefaultOnError")]
2413 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2414 #[serde(default)]
2415 pub state: Option<StateUpdate>,
2416 #[serde_as(deserialize_as = "DefaultOnError")]
2422 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2423 #[serde(default)]
2424 #[serde(rename = "_meta")]
2425 pub meta: Option<Meta>,
2426}
2427
2428#[cfg(feature = "unstable_session_status")]
2429impl SessionStatusResponse {
2430 #[must_use]
2432 pub fn new(status: SessionStatus) -> Self {
2433 Self {
2434 status,
2435 state: None,
2436 meta: None,
2437 }
2438 }
2439
2440 #[must_use]
2443 pub fn state(mut self, state: impl IntoOption<StateUpdate>) -> Self {
2444 self.state = state.into_option();
2445 self
2446 }
2447
2448 #[must_use]
2454 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2455 self.meta = meta.into_option();
2456 self
2457 }
2458}
2459
2460#[cfg(feature = "unstable_session_status")]
2466#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2467#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2468#[serde(rename_all = "snake_case")]
2469#[non_exhaustive]
2470pub enum SessionStatus {
2471 Open,
2478 Saved,
2482 #[serde(untagged)]
2489 Other(String),
2490}
2491
2492#[cfg(feature = "unstable_session_options")]
2506#[serde_as]
2507#[skip_serializing_none]
2508#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2509#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2510#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_OPTIONS_METHOD_NAME)))]
2511#[serde(rename_all = "camelCase")]
2512#[non_exhaustive]
2513pub struct SessionOptionsRequest {
2514 pub cwd: AbsolutePath,
2516 #[serde_as(deserialize_as = "DefaultOnNull")]
2520 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
2521 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2522 pub additional_directories: Vec<AbsolutePath>,
2523 #[serde(default)]
2530 pub session_id: Option<SessionId>,
2531 #[serde_as(deserialize_as = "DefaultOnError")]
2537 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2538 #[serde(default)]
2539 #[serde(rename = "_meta")]
2540 pub meta: Option<Meta>,
2541}
2542
2543#[cfg(feature = "unstable_session_options")]
2544impl SessionOptionsRequest {
2545 #[must_use]
2547 pub fn new(cwd: impl Into<AbsolutePath>) -> Self {
2548 Self {
2549 cwd: cwd.into(),
2550 additional_directories: vec![],
2551 session_id: None,
2552 meta: None,
2553 }
2554 }
2555
2556 #[must_use]
2558 pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
2559 where
2560 I: IntoIterator<Item = P>,
2561 P: Into<AbsolutePath>,
2562 {
2563 self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
2564 self
2565 }
2566
2567 #[must_use]
2569 pub fn session_id(mut self, session_id: impl IntoOption<SessionId>) -> Self {
2570 self.session_id = session_id.into_option();
2571 self
2572 }
2573
2574 #[must_use]
2580 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2581 self.meta = meta.into_option();
2582 self
2583 }
2584}
2585
2586#[cfg(feature = "unstable_session_options")]
2587crate::serde_util::default_on_null! {
2588 #[serde_as]
2597 #[skip_serializing_none]
2598 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2599 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2600 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_OPTIONS_METHOD_NAME)))]
2601 #[serde(rename_all = "camelCase")]
2602 #[non_exhaustive]
2603 pub struct SessionOptionsResponse {
2604 #[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 config_options: Vec<SessionConfigOption>,
2613 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2622 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2623 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2624 pub available_commands: Vec<AvailableCommand>,
2625 #[serde_as(deserialize_as = "DefaultOnError")]
2631 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2632 #[serde(default)]
2633 #[serde(rename = "_meta")]
2634 pub meta: Option<Meta>,
2635 }
2636}
2637
2638#[cfg(feature = "unstable_session_options")]
2639impl SessionOptionsResponse {
2640 #[must_use]
2642 pub fn new() -> Self {
2643 Self::default()
2644 }
2645
2646 #[must_use]
2648 pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
2649 self.config_options = config_options;
2650 self
2651 }
2652
2653 #[must_use]
2655 pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
2656 self.available_commands = available_commands;
2657 self
2658 }
2659
2660 #[must_use]
2666 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2667 self.meta = meta.into_option();
2668 self
2669 }
2670}
2671
2672#[cfg(feature = "unstable_session_options")]
2682#[serde_as]
2683#[skip_serializing_none]
2684#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2685#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2686#[serde(rename_all = "camelCase")]
2687#[non_exhaustive]
2688pub struct InitialSessionConfigOption {
2689 pub config_id: SessionConfigId,
2691 #[serde(flatten)]
2696 pub value: SessionConfigOptionValue,
2697 #[serde_as(deserialize_as = "DefaultOnError")]
2703 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2704 #[serde(default)]
2705 #[serde(rename = "_meta")]
2706 pub meta: Option<Meta>,
2707}
2708
2709#[cfg(feature = "unstable_session_options")]
2710impl InitialSessionConfigOption {
2711 #[must_use]
2713 pub fn new(
2714 config_id: impl Into<SessionConfigId>,
2715 value: impl Into<SessionConfigOptionValue>,
2716 ) -> Self {
2717 Self {
2718 config_id: config_id.into(),
2719 value: value.into(),
2720 meta: None,
2721 }
2722 }
2723
2724 #[must_use]
2730 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2731 self.meta = meta.into_option();
2732 self
2733 }
2734}
2735
2736#[serde_as]
2751#[skip_serializing_none]
2752#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2753#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2754#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TOOL_CALL_CANCEL_METHOD_NAME)))]
2755#[serde(rename_all = "camelCase")]
2756#[non_exhaustive]
2757pub struct CancelToolCallRequest {
2758 pub session_id: SessionId,
2760 pub tool_call_id: ToolCallId,
2762 #[serde_as(deserialize_as = "DefaultOnError")]
2768 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2769 #[serde(default)]
2770 #[serde(rename = "_meta")]
2771 pub meta: Option<Meta>,
2772}
2773
2774impl CancelToolCallRequest {
2775 #[must_use]
2777 pub fn new(session_id: impl Into<SessionId>, tool_call_id: impl Into<ToolCallId>) -> Self {
2778 Self {
2779 session_id: session_id.into(),
2780 tool_call_id: tool_call_id.into(),
2781 meta: None,
2782 }
2783 }
2784
2785 #[must_use]
2791 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2792 self.meta = meta.into_option();
2793 self
2794 }
2795}
2796
2797crate::serde_util::default_on_null! {
2798 #[serde_as]
2800 #[skip_serializing_none]
2801 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2802 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2803 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TOOL_CALL_CANCEL_METHOD_NAME)))]
2804 #[serde(rename_all = "camelCase")]
2805 #[non_exhaustive]
2806 pub struct CancelToolCallResponse {
2807 #[serde_as(deserialize_as = "DefaultOnError")]
2813 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2814 #[serde(default)]
2815 #[serde(rename = "_meta")]
2816 pub meta: Option<Meta>,
2817 }
2818}
2819
2820impl CancelToolCallResponse {
2821 #[must_use]
2823 pub fn new() -> Self {
2824 Self::default()
2825 }
2826
2827 #[must_use]
2833 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2834 self.meta = meta.into_option();
2835 self
2836 }
2837}
2838
2839#[serde_as]
2855#[skip_serializing_none]
2856#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2857#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2858#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TERMINAL_CANCEL_METHOD_NAME)))]
2859#[serde(rename_all = "camelCase")]
2860#[non_exhaustive]
2861pub struct CancelTerminalRequest {
2862 pub session_id: SessionId,
2864 pub terminal_id: TerminalId,
2866 #[serde_as(deserialize_as = "DefaultOnError")]
2872 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2873 #[serde(default)]
2874 #[serde(rename = "_meta")]
2875 pub meta: Option<Meta>,
2876}
2877
2878impl CancelTerminalRequest {
2879 #[must_use]
2881 pub fn new(session_id: impl Into<SessionId>, terminal_id: impl Into<TerminalId>) -> Self {
2882 Self {
2883 session_id: session_id.into(),
2884 terminal_id: terminal_id.into(),
2885 meta: None,
2886 }
2887 }
2888
2889 #[must_use]
2895 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2896 self.meta = meta.into_option();
2897 self
2898 }
2899}
2900
2901crate::serde_util::default_on_null! {
2902 #[serde_as]
2904 #[skip_serializing_none]
2905 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2906 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2907 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TERMINAL_CANCEL_METHOD_NAME)))]
2908 #[serde(rename_all = "camelCase")]
2909 #[non_exhaustive]
2910 pub struct CancelTerminalResponse {
2911 #[serde_as(deserialize_as = "DefaultOnError")]
2917 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2918 #[serde(default)]
2919 #[serde(rename = "_meta")]
2920 pub meta: Option<Meta>,
2921 }
2922}
2923
2924impl CancelTerminalResponse {
2925 #[must_use]
2927 pub fn new() -> Self {
2928 Self::default()
2929 }
2930
2931 #[must_use]
2937 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2938 self.meta = meta.into_option();
2939 self
2940 }
2941}
2942
2943#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2947#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
2948#[serde(transparent)]
2949#[from(Arc<str>, String, &str, &mut str, Box<str>, Cow<'_, str>)]
2950#[non_exhaustive]
2951pub struct SessionListCursor(pub Arc<str>);
2952
2953impl SessionListCursor {
2954 #[must_use]
2956 pub fn new(cursor: impl Into<Self>) -> Self {
2957 cursor.into()
2958 }
2959}
2960
2961impl AsRef<str> for SessionListCursor {
2962 fn as_ref(&self) -> &str {
2963 &self.0
2964 }
2965}
2966
2967impl From<&String> for SessionListCursor {
2968 fn from(cursor: &String) -> Self {
2969 Self(cursor.as_str().into())
2970 }
2971}
2972
2973macro_rules! impl_session_list_cursor_option_conversion {
2974 ($source:ty) => {
2975 impl IntoOption<SessionListCursor> for $source {
2976 fn into_option(self) -> Option<SessionListCursor> {
2977 Some(self.into())
2978 }
2979 }
2980 };
2981}
2982
2983impl_session_list_cursor_option_conversion!(Arc<str>);
2984impl_session_list_cursor_option_conversion!(String);
2985impl_session_list_cursor_option_conversion!(&str);
2986impl_session_list_cursor_option_conversion!(&mut str);
2987impl_session_list_cursor_option_conversion!(&String);
2988impl_session_list_cursor_option_conversion!(Box<str>);
2989impl_session_list_cursor_option_conversion!(Cow<'_, str>);
2990
2991crate::serde_util::default_on_null! {
2992 #[serde_as]
2994 #[skip_serializing_none]
2995 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2996 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2997 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LIST_METHOD_NAME)))]
2998 #[serde(rename_all = "camelCase")]
2999 #[non_exhaustive]
3000 pub struct ListSessionsRequest {
3001 #[serde(default)]
3009 pub cwd: Option<AbsolutePath>,
3010 #[serde(default)]
3014 pub cursor: Option<SessionListCursor>,
3015 #[cfg(feature = "unstable_session_archive")]
3025 #[serde(default)]
3026 pub archived: Option<SessionArchiveFilter>,
3027 #[serde_as(deserialize_as = "DefaultOnError")]
3033 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3034 #[serde(default)]
3035 #[serde(rename = "_meta")]
3036 pub meta: Option<Meta>,
3037 }
3038}
3039
3040impl ListSessionsRequest {
3041 #[must_use]
3043 pub fn new() -> Self {
3044 Self::default()
3045 }
3046
3047 #[must_use]
3049 pub fn cwd(mut self, cwd: impl IntoOption<AbsolutePath>) -> Self {
3050 self.cwd = cwd.into_option();
3051 self
3052 }
3053
3054 #[must_use]
3056 pub fn cursor(mut self, cursor: impl IntoOption<SessionListCursor>) -> Self {
3057 self.cursor = cursor.into_option();
3058 self
3059 }
3060
3061 #[cfg(feature = "unstable_session_archive")]
3067 #[must_use]
3068 pub fn archived(mut self, archived: impl IntoOption<SessionArchiveFilter>) -> Self {
3069 self.archived = archived.into_option();
3070 self
3071 }
3072
3073 #[must_use]
3079 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3080 self.meta = meta.into_option();
3081 self
3082 }
3083}
3084
3085#[serde_as]
3087#[skip_serializing_none]
3088#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3089#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3090#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LIST_METHOD_NAME)))]
3091#[serde(rename_all = "camelCase")]
3092#[non_exhaustive]
3093pub struct ListSessionsResponse {
3094 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
3098 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3099 pub sessions: Vec<SessionInfo>,
3100 #[serde(default)]
3104 pub next_cursor: Option<SessionListCursor>,
3105 #[serde_as(deserialize_as = "DefaultOnError")]
3111 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3112 #[serde(default)]
3113 #[serde(rename = "_meta")]
3114 pub meta: Option<Meta>,
3115}
3116
3117impl ListSessionsResponse {
3118 #[must_use]
3120 pub fn new(sessions: Vec<SessionInfo>) -> Self {
3121 Self {
3122 sessions,
3123 next_cursor: None,
3124 meta: None,
3125 }
3126 }
3127
3128 #[must_use]
3130 pub fn next_cursor(mut self, next_cursor: impl IntoOption<SessionListCursor>) -> Self {
3131 self.next_cursor = next_cursor.into_option();
3132 self
3133 }
3134
3135 #[must_use]
3141 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3142 self.meta = meta.into_option();
3143 self
3144 }
3145}
3146
3147#[serde_as]
3153#[skip_serializing_none]
3154#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3155#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3156#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_DELETE_METHOD_NAME)))]
3157#[serde(rename_all = "camelCase")]
3158#[non_exhaustive]
3159pub struct DeleteSessionRequest {
3160 pub session_id: SessionId,
3162 #[serde_as(deserialize_as = "DefaultOnError")]
3168 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3169 #[serde(default)]
3170 #[serde(rename = "_meta")]
3171 pub meta: Option<Meta>,
3172}
3173
3174impl DeleteSessionRequest {
3175 #[must_use]
3177 pub fn new(session_id: impl Into<SessionId>) -> Self {
3178 Self {
3179 session_id: session_id.into(),
3180 meta: None,
3181 }
3182 }
3183
3184 #[must_use]
3190 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3191 self.meta = meta.into_option();
3192 self
3193 }
3194}
3195
3196crate::serde_util::default_on_null! {
3197 #[serde_as]
3199 #[skip_serializing_none]
3200 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3201 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3202 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_DELETE_METHOD_NAME)))]
3203 #[serde(rename_all = "camelCase")]
3204 #[non_exhaustive]
3205 pub struct DeleteSessionResponse {
3206 #[serde_as(deserialize_as = "DefaultOnError")]
3212 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3213 #[serde(default)]
3214 #[serde(rename = "_meta")]
3215 pub meta: Option<Meta>,
3216 }
3217}
3218
3219impl DeleteSessionResponse {
3220 #[must_use]
3222 pub fn new() -> Self {
3223 Self::default()
3224 }
3225
3226 #[must_use]
3232 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3233 self.meta = meta.into_option();
3234 self
3235 }
3236}
3237
3238#[cfg(feature = "unstable_session_archive")]
3254#[serde_as]
3255#[skip_serializing_none]
3256#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3257#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3258#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_ARCHIVE_METHOD_NAME)))]
3259#[serde(rename_all = "camelCase")]
3260#[non_exhaustive]
3261pub struct ArchiveSessionRequest {
3262 pub session_id: SessionId,
3264 #[serde_as(deserialize_as = "DefaultOnError")]
3270 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3271 #[serde(default)]
3272 #[serde(rename = "_meta")]
3273 pub meta: Option<Meta>,
3274}
3275
3276#[cfg(feature = "unstable_session_archive")]
3277impl ArchiveSessionRequest {
3278 #[must_use]
3280 pub fn new(session_id: impl Into<SessionId>) -> Self {
3281 Self {
3282 session_id: session_id.into(),
3283 meta: None,
3284 }
3285 }
3286
3287 #[must_use]
3293 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3294 self.meta = meta.into_option();
3295 self
3296 }
3297}
3298
3299#[cfg(feature = "unstable_session_archive")]
3300crate::serde_util::default_on_null! {
3301 #[serde_as]
3307 #[skip_serializing_none]
3308 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3309 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3310 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_ARCHIVE_METHOD_NAME)))]
3311 #[serde(rename_all = "camelCase")]
3312 #[non_exhaustive]
3313 pub struct ArchiveSessionResponse {
3314 #[serde_as(deserialize_as = "DefaultOnError")]
3320 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3321 #[serde(default)]
3322 #[serde(rename = "_meta")]
3323 pub meta: Option<Meta>,
3324 }
3325}
3326
3327#[cfg(feature = "unstable_session_archive")]
3328impl ArchiveSessionResponse {
3329 #[must_use]
3331 pub fn new() -> Self {
3332 Self::default()
3333 }
3334
3335 #[must_use]
3341 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3342 self.meta = meta.into_option();
3343 self
3344 }
3345}
3346
3347#[cfg(feature = "unstable_session_archive")]
3362#[serde_as]
3363#[skip_serializing_none]
3364#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3365#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3366#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_UNARCHIVE_METHOD_NAME)))]
3367#[serde(rename_all = "camelCase")]
3368#[non_exhaustive]
3369pub struct UnarchiveSessionRequest {
3370 pub session_id: SessionId,
3372 #[serde_as(deserialize_as = "DefaultOnError")]
3378 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3379 #[serde(default)]
3380 #[serde(rename = "_meta")]
3381 pub meta: Option<Meta>,
3382}
3383
3384#[cfg(feature = "unstable_session_archive")]
3385impl UnarchiveSessionRequest {
3386 #[must_use]
3388 pub fn new(session_id: impl Into<SessionId>) -> Self {
3389 Self {
3390 session_id: session_id.into(),
3391 meta: None,
3392 }
3393 }
3394
3395 #[must_use]
3401 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3402 self.meta = meta.into_option();
3403 self
3404 }
3405}
3406
3407#[cfg(feature = "unstable_session_archive")]
3408crate::serde_util::default_on_null! {
3409 #[serde_as]
3415 #[skip_serializing_none]
3416 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3417 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3418 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_UNARCHIVE_METHOD_NAME)))]
3419 #[serde(rename_all = "camelCase")]
3420 #[non_exhaustive]
3421 pub struct UnarchiveSessionResponse {
3422 #[serde_as(deserialize_as = "DefaultOnError")]
3428 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3429 #[serde(default)]
3430 #[serde(rename = "_meta")]
3431 pub meta: Option<Meta>,
3432 }
3433}
3434
3435#[cfg(feature = "unstable_session_archive")]
3436impl UnarchiveSessionResponse {
3437 #[must_use]
3439 pub fn new() -> Self {
3440 Self::default()
3441 }
3442
3443 #[must_use]
3449 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3450 self.meta = meta.into_option();
3451 self
3452 }
3453}
3454
3455#[cfg(feature = "unstable_session_archive")]
3464#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3465#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
3466#[serde(rename_all = "snake_case")]
3467#[non_exhaustive]
3468pub enum SessionArchiveFilter {
3469 #[default]
3471 Exclude,
3472 Include,
3474 Only,
3476 #[serde(untagged)]
3482 Other(String),
3483}
3484
3485#[serde_as]
3487#[skip_serializing_none]
3488#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3489#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3490#[serde(rename_all = "camelCase")]
3491#[non_exhaustive]
3492pub struct SessionInfo {
3493 pub session_id: SessionId,
3495 pub cwd: AbsolutePath,
3497 #[serde_as(deserialize_as = "DefaultOnNull")]
3503 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
3504 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3505 pub additional_directories: Vec<AbsolutePath>,
3506
3507 #[serde_as(deserialize_as = "DefaultOnError")]
3511 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3512 #[serde(default)]
3513 pub title: Option<String>,
3514 #[serde_as(deserialize_as = "DefaultOnError")]
3518 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "format" = "date-time")))]
3519 #[serde(default)]
3520 pub updated_at: Option<String>,
3521 #[cfg(feature = "unstable_session_archive")]
3530 #[serde_as(deserialize_as = "DefaultOnError")]
3531 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3532 #[serde(default)]
3533 pub archived: Option<bool>,
3534 #[serde_as(deserialize_as = "DefaultOnError")]
3540 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3541 #[serde(default)]
3542 #[serde(rename = "_meta")]
3543 pub meta: Option<Meta>,
3544}
3545
3546impl SessionInfo {
3547 #[must_use]
3549 pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
3550 Self {
3551 session_id: session_id.into(),
3552 cwd: cwd.into(),
3553 additional_directories: vec![],
3554 title: None,
3555 updated_at: None,
3556 #[cfg(feature = "unstable_session_archive")]
3557 archived: None,
3558 meta: None,
3559 }
3560 }
3561
3562 #[must_use]
3564 pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
3565 where
3566 I: IntoIterator<Item = P>,
3567 P: Into<AbsolutePath>,
3568 {
3569 self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
3570 self
3571 }
3572
3573 #[must_use]
3575 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
3576 self.title = title.into_option();
3577 self
3578 }
3579
3580 #[must_use]
3582 pub fn updated_at(mut self, updated_at: impl IntoOption<String>) -> Self {
3583 self.updated_at = updated_at.into_option();
3584 self
3585 }
3586
3587 #[cfg(feature = "unstable_session_archive")]
3593 #[must_use]
3594 pub fn archived(mut self, archived: impl IntoOption<bool>) -> Self {
3595 self.archived = archived.into_option();
3596 self
3597 }
3598
3599 #[must_use]
3605 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3606 self.meta = meta.into_option();
3607 self
3608 }
3609}
3610
3611#[cfg(feature = "unstable_session_set_title")]
3627#[serde_as]
3628#[skip_serializing_none]
3629#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3630#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3631#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_TITLE_METHOD_NAME)))]
3632#[serde(rename_all = "camelCase")]
3633#[non_exhaustive]
3634pub struct SetSessionTitleRequest {
3635 pub session_id: SessionId,
3637 pub title: String,
3644 #[serde_as(deserialize_as = "DefaultOnError")]
3650 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3651 #[serde(default)]
3652 #[serde(rename = "_meta")]
3653 pub meta: Option<Meta>,
3654}
3655
3656#[cfg(feature = "unstable_session_set_title")]
3657impl SetSessionTitleRequest {
3658 #[must_use]
3660 pub fn new(session_id: impl Into<SessionId>, title: impl Into<String>) -> Self {
3661 Self {
3662 session_id: session_id.into(),
3663 title: title.into(),
3664 meta: None,
3665 }
3666 }
3667
3668 #[must_use]
3674 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3675 self.meta = meta.into_option();
3676 self
3677 }
3678}
3679
3680#[cfg(feature = "unstable_session_set_title")]
3686#[serde_as]
3687#[skip_serializing_none]
3688#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3689#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3690#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_TITLE_METHOD_NAME)))]
3691#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "sessionInfo", "field": "title", "value": "title"}]})))]
3692#[serde(rename_all = "camelCase")]
3693#[non_exhaustive]
3694pub struct SetSessionTitleResponse {
3695 pub title: String,
3700 #[serde_as(deserialize_as = "DefaultOnError")]
3706 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3707 #[serde(default)]
3708 #[serde(rename = "_meta")]
3709 pub meta: Option<Meta>,
3710}
3711
3712#[cfg(feature = "unstable_session_set_title")]
3713impl SetSessionTitleResponse {
3714 #[must_use]
3716 pub fn new(title: impl Into<String>) -> Self {
3717 Self {
3718 title: title.into(),
3719 meta: None,
3720 }
3721 }
3722
3723 #[must_use]
3729 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3730 self.meta = meta.into_option();
3731 self
3732 }
3733}
3734
3735#[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 SessionConfigId(pub Arc<str>);
3744
3745impl SessionConfigId {
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 SessionConfigValueId(pub Arc<str>);
3760
3761impl SessionConfigValueId {
3762 #[must_use]
3764 pub fn new(id: impl Into<Self>) -> Self {
3765 id.into()
3766 }
3767}
3768
3769#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3771#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3772#[serde(transparent)]
3773#[from(forward)]
3774#[non_exhaustive]
3775pub struct SessionConfigGroupId(pub Arc<str>);
3776
3777impl SessionConfigGroupId {
3778 #[must_use]
3780 pub fn new(id: impl Into<Self>) -> Self {
3781 id.into()
3782 }
3783}
3784
3785#[serde_as]
3787#[skip_serializing_none]
3788#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3789#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3790#[serde(rename_all = "camelCase")]
3791#[non_exhaustive]
3792pub struct SessionConfigSelectOption {
3793 pub value: SessionConfigValueId,
3795 pub name: String,
3797 #[serde_as(deserialize_as = "DefaultOnError")]
3802 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3803 #[serde(default)]
3804 pub description: Option<String>,
3805 #[serde_as(deserialize_as = "DefaultOnError")]
3811 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3812 #[serde(default)]
3813 #[serde(rename = "_meta")]
3814 pub meta: Option<Meta>,
3815}
3816
3817impl SessionConfigSelectOption {
3818 #[must_use]
3820 pub fn new(value: impl Into<SessionConfigValueId>, name: impl Into<String>) -> Self {
3821 Self {
3822 value: value.into(),
3823 name: name.into(),
3824 description: None,
3825 meta: None,
3826 }
3827 }
3828
3829 #[must_use]
3832 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
3833 self.description = description.into_option();
3834 self
3835 }
3836
3837 #[must_use]
3843 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3844 self.meta = meta.into_option();
3845 self
3846 }
3847}
3848
3849#[serde_as]
3851#[skip_serializing_none]
3852#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3853#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3854#[serde(rename_all = "camelCase")]
3855#[non_exhaustive]
3856pub struct SessionConfigSelectGroup {
3857 pub group_id: SessionConfigGroupId,
3859 pub name: String,
3861 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
3863 #[cfg_attr(feature = "schemars", schemars(length(min = 1), extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3864 pub options: Vec<SessionConfigSelectOption>,
3865 #[serde_as(deserialize_as = "DefaultOnError")]
3871 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3872 #[serde(default)]
3873 #[serde(rename = "_meta")]
3874 pub meta: Option<Meta>,
3875}
3876
3877impl SessionConfigSelectGroup {
3878 #[must_use]
3880 pub fn new(
3881 group_id: impl Into<SessionConfigGroupId>,
3882 name: impl Into<String>,
3883 options: Vec<SessionConfigSelectOption>,
3884 ) -> Self {
3885 Self {
3886 group_id: group_id.into(),
3887 name: name.into(),
3888 options,
3889 meta: None,
3890 }
3891 }
3892
3893 #[must_use]
3899 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3900 self.meta = meta.into_option();
3901 self
3902 }
3903}
3904
3905#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3907#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3908#[serde(untagged)]
3909#[non_exhaustive]
3910pub enum SessionConfigSelectOptions {
3911 Ungrouped(
3913 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))] Vec<SessionConfigSelectOption>,
3914 ),
3915 Grouped(
3917 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))] Vec<SessionConfigSelectGroup>,
3918 ),
3919}
3920
3921impl From<Vec<SessionConfigSelectOption>> for SessionConfigSelectOptions {
3922 fn from(options: Vec<SessionConfigSelectOption>) -> Self {
3923 SessionConfigSelectOptions::Ungrouped(options)
3924 }
3925}
3926
3927impl From<Vec<SessionConfigSelectGroup>> for SessionConfigSelectOptions {
3928 fn from(groups: Vec<SessionConfigSelectGroup>) -> Self {
3929 SessionConfigSelectOptions::Grouped(groups)
3930 }
3931}
3932
3933#[skip_serializing_none]
3935#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3936#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3937#[serde(rename_all = "camelCase")]
3938#[non_exhaustive]
3939pub struct SessionConfigSelect {
3940 pub current_value: SessionConfigValueId,
3942 pub options: SessionConfigSelectOptions,
3945}
3946
3947impl SessionConfigSelect {
3948 #[must_use]
3950 pub fn new(
3951 current_value: impl Into<SessionConfigValueId>,
3952 options: impl Into<SessionConfigSelectOptions>,
3953 ) -> Self {
3954 Self {
3955 current_value: current_value.into(),
3956 options: options.into(),
3957 }
3958 }
3959}
3960
3961#[skip_serializing_none]
3963#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3964#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3965#[serde(rename_all = "camelCase")]
3966#[non_exhaustive]
3967pub struct SessionConfigBoolean {
3968 pub current_value: bool,
3970}
3971
3972impl SessionConfigBoolean {
3973 #[must_use]
3975 pub fn new(current_value: bool) -> Self {
3976 Self { current_value }
3977 }
3978}
3979
3980#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3990#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3991#[serde(rename_all = "snake_case")]
3992#[non_exhaustive]
3993pub enum SessionConfigOptionCategory {
3994 Mode,
3996 Model,
3998 ModelConfig,
4000 #[cfg(feature = "unstable_speed_config_category")]
4006 Speed,
4007 ThoughtLevel,
4009 #[serde(untagged)]
4015 Other(String),
4016}
4017
4018#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4020#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4021#[serde(tag = "type", rename_all = "snake_case")]
4022#[non_exhaustive]
4023pub enum SessionConfigKind {
4024 Select(SessionConfigSelect),
4026 Boolean(SessionConfigBoolean),
4028 #[serde(untagged)]
4038 Other(OtherSessionConfigKind),
4039}
4040
4041#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4043#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4044#[cfg_attr(feature = "schemars", schemars(inline))]
4045#[cfg_attr(feature = "schemars", schemars(transform = other_session_config_kind_schema))]
4046#[serde(rename_all = "camelCase")]
4047#[non_exhaustive]
4048pub struct OtherSessionConfigKind {
4049 #[serde(rename = "type")]
4055 pub type_: String,
4056 #[serde(flatten)]
4058 pub fields: IndexMap<String, serde_json::Value>,
4059}
4060
4061impl OtherSessionConfigKind {
4062 #[must_use]
4064 pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
4065 fields.shift_remove("type");
4066 fields.shift_remove("_meta");
4067 Self {
4068 type_: type_.into(),
4069 fields,
4070 }
4071 }
4072}
4073
4074impl<'de> Deserialize<'de> for OtherSessionConfigKind {
4075 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4076 where
4077 D: serde::Deserializer<'de>,
4078 {
4079 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4080 let type_ = fields
4081 .shift_remove("type")
4082 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4083 let serde_json::Value::String(type_) = type_ else {
4084 return Err(serde::de::Error::custom("`type` must be a string"));
4085 };
4086
4087 if is_known_session_config_kind_type(&type_) {
4088 return Err(serde::de::Error::custom(format!(
4089 "known session configuration option `{type_}` did not match its schema"
4090 )));
4091 }
4092
4093 Ok(Self { type_, fields })
4094 }
4095}
4096
4097fn is_known_session_config_kind_type(type_: &str) -> bool {
4098 matches!(type_, "select" | "boolean")
4099}
4100
4101#[cfg(feature = "schemars")]
4102fn other_session_config_kind_schema(schema: &mut Schema) {
4103 super::schema_util::reject_known_string_discriminators(schema, "type", &["select", "boolean"]);
4104}
4105
4106#[serde_as]
4108#[skip_serializing_none]
4109#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4110#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4111#[serde(rename_all = "camelCase")]
4112#[non_exhaustive]
4113pub struct SessionConfigOption {
4114 pub config_id: SessionConfigId,
4116 pub name: String,
4118 #[serde_as(deserialize_as = "DefaultOnError")]
4123 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4124 #[serde(default)]
4125 pub description: Option<String>,
4126 #[serde_as(deserialize_as = "DefaultOnError")]
4130 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4131 #[serde(default)]
4132 pub category: Option<SessionConfigOptionCategory>,
4133 #[serde(flatten)]
4135 pub kind: SessionConfigKind,
4136 #[serde_as(deserialize_as = "DefaultOnError")]
4142 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4143 #[serde(default)]
4144 #[serde(rename = "_meta")]
4145 pub meta: Option<Meta>,
4146}
4147
4148impl SessionConfigOption {
4149 #[must_use]
4151 pub fn new(
4152 config_id: impl Into<SessionConfigId>,
4153 name: impl Into<String>,
4154 kind: SessionConfigKind,
4155 ) -> Self {
4156 Self {
4157 config_id: config_id.into(),
4158 name: name.into(),
4159 description: None,
4160 category: None,
4161 kind,
4162 meta: None,
4163 }
4164 }
4165
4166 #[must_use]
4168 pub fn select(
4169 config_id: impl Into<SessionConfigId>,
4170 name: impl Into<String>,
4171 current_value: impl Into<SessionConfigValueId>,
4172 options: impl Into<SessionConfigSelectOptions>,
4173 ) -> Self {
4174 Self::new(
4175 config_id,
4176 name,
4177 SessionConfigKind::Select(SessionConfigSelect::new(current_value, options)),
4178 )
4179 }
4180
4181 #[must_use]
4183 pub fn boolean(
4184 config_id: impl Into<SessionConfigId>,
4185 name: impl Into<String>,
4186 current_value: bool,
4187 ) -> Self {
4188 Self::new(
4189 config_id,
4190 name,
4191 SessionConfigKind::Boolean(SessionConfigBoolean::new(current_value)),
4192 )
4193 }
4194
4195 #[must_use]
4198 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
4199 self.description = description.into_option();
4200 self
4201 }
4202
4203 #[must_use]
4205 pub fn category(mut self, category: impl IntoOption<SessionConfigOptionCategory>) -> Self {
4206 self.category = category.into_option();
4207 self
4208 }
4209
4210 #[must_use]
4216 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4217 self.meta = meta.into_option();
4218 self
4219 }
4220}
4221
4222#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4231#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4232#[serde(tag = "type", rename_all = "snake_case")]
4233#[non_exhaustive]
4234pub enum SessionConfigOptionValue {
4235 Id {
4237 value: SessionConfigValueId,
4239 },
4240 Boolean {
4242 value: bool,
4244 },
4245 #[serde(untagged)]
4254 Other(Box<OtherSessionConfigOptionValue>),
4255}
4256
4257#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4259#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4260#[cfg_attr(feature = "schemars", schemars(inline))]
4261#[cfg_attr(feature = "schemars", schemars(transform = other_session_config_option_value_schema))]
4262#[serde(rename_all = "camelCase")]
4263#[non_exhaustive]
4264pub struct OtherSessionConfigOptionValue {
4265 #[serde(rename = "type")]
4271 pub type_: String,
4272 pub value: serde_json::Value,
4274 #[serde(flatten)]
4276 pub fields: IndexMap<String, serde_json::Value>,
4277}
4278
4279impl OtherSessionConfigOptionValue {
4280 #[must_use]
4282 pub fn new(
4283 type_: impl Into<String>,
4284 value: serde_json::Value,
4285 mut fields: IndexMap<String, serde_json::Value>,
4286 ) -> Self {
4287 fields.shift_remove("type");
4288 fields.shift_remove("value");
4289 fields.shift_remove("_meta");
4290 Self {
4291 type_: type_.into(),
4292 value,
4293 fields,
4294 }
4295 }
4296}
4297
4298impl<'de> Deserialize<'de> for OtherSessionConfigOptionValue {
4299 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4300 where
4301 D: serde::Deserializer<'de>,
4302 {
4303 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4304 let type_ = fields
4305 .shift_remove("type")
4306 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4307 let serde_json::Value::String(type_) = type_ else {
4308 return Err(serde::de::Error::custom("`type` must be a string"));
4309 };
4310
4311 if is_known_session_config_option_value_type(&type_) {
4312 return Err(serde::de::Error::custom(format!(
4313 "known session configuration option value `{type_}` did not match its schema"
4314 )));
4315 }
4316
4317 let value = fields
4318 .shift_remove("value")
4319 .ok_or_else(|| serde::de::Error::missing_field("value"))?;
4320
4321 Ok(Self {
4322 type_,
4323 value,
4324 fields,
4325 })
4326 }
4327}
4328
4329impl<'de> Deserialize<'de> for SessionConfigOptionValue {
4330 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4331 where
4332 D: serde::Deserializer<'de>,
4333 {
4334 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4335 let type_ = fields.shift_remove("type");
4336 let value = fields
4337 .shift_remove("value")
4338 .ok_or_else(|| serde::de::Error::missing_field("value"))?;
4339
4340 let type_ = type_.ok_or_else(|| serde::de::Error::missing_field("type"))?;
4341
4342 let serde_json::Value::String(type_) = type_ else {
4343 return Err(serde::de::Error::custom("`type` must be a string"));
4344 };
4345
4346 match type_.as_str() {
4347 "id" => {
4348 let value = serde_json::from_value(value).map_err(|error| {
4349 serde::de::Error::custom(format!(
4350 "`value` must be a string for `type: id`: {error}"
4351 ))
4352 })?;
4353 Ok(Self::Id { value })
4354 }
4355 "boolean" => {
4356 let value = serde_json::from_value(value).map_err(|error| {
4357 serde::de::Error::custom(format!(
4358 "`value` must be a boolean for `type: boolean`: {error}"
4359 ))
4360 })?;
4361 Ok(Self::Boolean { value })
4362 }
4363 _ => Ok(OtherSessionConfigOptionValue {
4364 type_,
4365 value,
4366 fields,
4367 }
4368 .into()),
4369 }
4370 }
4371}
4372
4373fn is_known_session_config_option_value_type(type_: &str) -> bool {
4374 matches!(type_, "id" | "boolean")
4375}
4376
4377#[cfg(feature = "schemars")]
4378fn other_session_config_option_value_schema(schema: &mut Schema) {
4379 super::schema_util::reject_known_string_discriminators(schema, "type", &["id", "boolean"]);
4380}
4381
4382impl SessionConfigOptionValue {
4383 #[must_use]
4385 pub fn id(id: impl Into<SessionConfigValueId>) -> Self {
4386 Self::Id { value: id.into() }
4387 }
4388
4389 #[must_use]
4391 pub fn boolean(val: bool) -> Self {
4392 Self::Boolean { value: val }
4393 }
4394
4395 #[must_use]
4398 pub fn as_id(&self) -> Option<&SessionConfigValueId> {
4399 match self {
4400 Self::Id { value } => Some(value),
4401 _ => None,
4402 }
4403 }
4404
4405 #[must_use]
4407 pub fn as_bool(&self) -> Option<bool> {
4408 match self {
4409 Self::Boolean { value } => Some(*value),
4410 _ => None,
4411 }
4412 }
4413}
4414
4415impl From<SessionConfigValueId> for SessionConfigOptionValue {
4416 fn from(value: SessionConfigValueId) -> Self {
4417 Self::Id { value }
4418 }
4419}
4420
4421impl From<bool> for SessionConfigOptionValue {
4422 fn from(value: bool) -> Self {
4423 Self::Boolean { value }
4424 }
4425}
4426
4427impl From<OtherSessionConfigOptionValue> for SessionConfigOptionValue {
4428 fn from(value: OtherSessionConfigOptionValue) -> Self {
4429 Self::Other(Box::new(value))
4430 }
4431}
4432
4433impl From<&str> for SessionConfigOptionValue {
4434 fn from(value: &str) -> Self {
4435 Self::Id {
4436 value: SessionConfigValueId::new(value),
4437 }
4438 }
4439}
4440
4441#[serde_as]
4452#[skip_serializing_none]
4453#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4454#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4455#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_CONFIG_OPTION_METHOD_NAME)))]
4456#[serde(rename_all = "camelCase")]
4457#[non_exhaustive]
4458pub struct SetSessionConfigOptionRequest {
4459 pub session_id: SessionId,
4461 pub config_id: SessionConfigId,
4463 #[serde(flatten)]
4467 pub value: SessionConfigOptionValue,
4468 #[serde_as(deserialize_as = "DefaultOnError")]
4474 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4475 #[serde(default)]
4476 #[serde(rename = "_meta")]
4477 pub meta: Option<Meta>,
4478}
4479
4480impl SetSessionConfigOptionRequest {
4481 #[must_use]
4483 pub fn new(
4484 session_id: impl Into<SessionId>,
4485 config_id: impl Into<SessionConfigId>,
4486 value: impl Into<SessionConfigOptionValue>,
4487 ) -> Self {
4488 Self {
4489 session_id: session_id.into(),
4490 config_id: config_id.into(),
4491 value: value.into(),
4492 meta: None,
4493 }
4494 }
4495
4496 #[must_use]
4502 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4503 self.meta = meta.into_option();
4504 self
4505 }
4506}
4507
4508#[serde_as]
4510#[skip_serializing_none]
4511#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4512#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4513#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_CONFIG_OPTION_METHOD_NAME)))]
4514#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}]})))]
4515#[serde(rename_all = "camelCase")]
4516#[non_exhaustive]
4517pub struct SetSessionConfigOptionResponse {
4518 #[serde_as(deserialize_as = "VecSkipError<_>")]
4520 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
4521 pub config_options: Vec<SessionConfigOption>,
4522 #[serde_as(deserialize_as = "DefaultOnError")]
4528 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4529 #[serde(default)]
4530 #[serde(rename = "_meta")]
4531 pub meta: Option<Meta>,
4532}
4533
4534impl SetSessionConfigOptionResponse {
4535 #[must_use]
4537 pub fn new(config_options: Vec<SessionConfigOption>) -> Self {
4538 Self {
4539 config_options,
4540 meta: None,
4541 }
4542 }
4543
4544 #[must_use]
4550 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4551 self.meta = meta.into_option();
4552 self
4553 }
4554}
4555
4556#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4565#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4566#[serde(tag = "type", rename_all = "snake_case")]
4567#[non_exhaustive]
4568pub enum McpServer {
4569 Http(McpServerHttp),
4573 #[cfg(feature = "unstable_mcp_over_acp")]
4582 Acp(McpServerAcp),
4583 Stdio(McpServerStdio),
4587 #[serde(untagged)]
4598 Other(OtherMcpServer),
4599}
4600
4601#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4603#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4604#[cfg_attr(feature = "schemars", schemars(inline))]
4605#[cfg_attr(feature = "schemars", schemars(transform = other_mcp_server_schema))]
4606#[serde(rename_all = "camelCase")]
4607#[non_exhaustive]
4608pub struct OtherMcpServer {
4609 #[serde(rename = "type")]
4615 pub type_: String,
4616 #[serde(flatten)]
4618 pub fields: IndexMap<String, serde_json::Value>,
4619}
4620
4621impl OtherMcpServer {
4622 #[must_use]
4624 pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
4625 fields.shift_remove("type");
4626 Self {
4627 type_: type_.into(),
4628 fields,
4629 }
4630 }
4631}
4632
4633impl<'de> Deserialize<'de> for OtherMcpServer {
4634 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4635 where
4636 D: serde::Deserializer<'de>,
4637 {
4638 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4639 let type_ = fields
4640 .shift_remove("type")
4641 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4642 let serde_json::Value::String(type_) = type_ else {
4643 return Err(serde::de::Error::custom("`type` must be a string"));
4644 };
4645
4646 if is_known_mcp_server_type(&type_) {
4647 return Err(serde::de::Error::custom(format!(
4648 "known MCP server transport `{type_}` did not match its schema"
4649 )));
4650 }
4651
4652 Ok(Self { type_, fields })
4653 }
4654}
4655
4656fn is_known_mcp_server_type(type_: &str) -> bool {
4657 match type_ {
4658 "http" | "stdio" => true,
4659 #[cfg(feature = "unstable_mcp_over_acp")]
4660 "acp" => true,
4661 _ => false,
4662 }
4663}
4664
4665#[cfg(feature = "schemars")]
4666fn other_mcp_server_schema(schema: &mut Schema) {
4667 super::schema_util::reject_known_string_discriminators(
4668 schema,
4669 "type",
4670 &[
4671 "http",
4672 "stdio",
4673 #[cfg(feature = "unstable_mcp_over_acp")]
4674 "acp",
4675 ],
4676 );
4677}
4678
4679#[serde_as]
4681#[skip_serializing_none]
4682#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4683#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4684#[serde(rename_all = "camelCase")]
4685#[non_exhaustive]
4686pub struct McpServerHttp {
4687 pub name: String,
4691 #[cfg_attr(feature = "schemars", schemars(url))]
4693 pub url: String,
4694 #[serde_as(deserialize_as = "DefaultOnNull")]
4697 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4698 #[serde(default, skip_serializing_if = "Vec::is_empty")]
4699 pub headers: Vec<HttpHeader>,
4700 #[serde_as(deserialize_as = "DefaultOnError")]
4706 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4707 #[serde(default)]
4708 #[serde(rename = "_meta")]
4709 pub meta: Option<Meta>,
4710}
4711
4712impl McpServerHttp {
4713 #[must_use]
4715 pub fn new(name: impl Into<String>, url: impl Into<String>) -> Self {
4716 Self {
4717 name: name.into(),
4718 url: url.into(),
4719 headers: Vec::new(),
4720 meta: None,
4721 }
4722 }
4723
4724 #[must_use]
4727 pub fn headers(mut self, headers: Vec<HttpHeader>) -> Self {
4728 self.headers = headers;
4729 self
4730 }
4731
4732 #[must_use]
4738 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4739 self.meta = meta.into_option();
4740 self
4741 }
4742}
4743
4744#[cfg(feature = "unstable_mcp_over_acp")]
4753#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4754#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
4755#[serde(transparent)]
4756#[from(forward)]
4757#[non_exhaustive]
4758pub struct McpServerAcpId(pub Arc<str>);
4759
4760#[cfg(feature = "unstable_mcp_over_acp")]
4761impl McpServerAcpId {
4762 #[must_use]
4764 pub fn new(id: impl Into<Self>) -> Self {
4765 id.into()
4766 }
4767}
4768
4769#[serde_as]
4778#[skip_serializing_none]
4779#[cfg(feature = "unstable_mcp_over_acp")]
4780#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4781#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4782#[serde(rename_all = "camelCase")]
4783#[non_exhaustive]
4784pub struct McpServerAcp {
4785 pub name: String,
4789 pub server_id: McpServerAcpId,
4794 #[serde_as(deserialize_as = "DefaultOnError")]
4800 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4801 #[serde(default)]
4802 #[serde(rename = "_meta")]
4803 pub meta: Option<Meta>,
4804}
4805
4806#[cfg(feature = "unstable_mcp_over_acp")]
4807impl McpServerAcp {
4808 #[must_use]
4810 pub fn new(name: impl Into<String>, server_id: impl Into<McpServerAcpId>) -> Self {
4811 Self {
4812 name: name.into(),
4813 server_id: server_id.into(),
4814 meta: None,
4815 }
4816 }
4817
4818 #[must_use]
4824 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4825 self.meta = meta.into_option();
4826 self
4827 }
4828}
4829
4830#[serde_as]
4832#[skip_serializing_none]
4833#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4834#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4835#[serde(rename_all = "camelCase")]
4836#[non_exhaustive]
4837pub struct McpServerStdio {
4838 pub name: String,
4842 pub command: AbsolutePath,
4846 #[serde_as(deserialize_as = "DefaultOnNull")]
4848 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4849 #[serde(default, skip_serializing_if = "Vec::is_empty")]
4850 pub args: Vec<String>,
4851 #[serde_as(deserialize_as = "DefaultOnNull")]
4854 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4855 #[serde(default, skip_serializing_if = "Vec::is_empty")]
4856 pub env: Vec<EnvVariable>,
4857 #[serde_as(deserialize_as = "DefaultOnError")]
4863 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4864 #[serde(default)]
4865 #[serde(rename = "_meta")]
4866 pub meta: Option<Meta>,
4867}
4868
4869impl McpServerStdio {
4870 #[must_use]
4872 pub fn new(name: impl Into<String>, command: impl Into<AbsolutePath>) -> Self {
4873 Self {
4874 name: name.into(),
4875 command: command.into(),
4876 args: Vec::new(),
4877 env: Vec::new(),
4878 meta: None,
4879 }
4880 }
4881
4882 #[must_use]
4884 pub fn args(mut self, args: Vec<String>) -> Self {
4885 self.args = args;
4886 self
4887 }
4888
4889 #[must_use]
4892 pub fn env(mut self, env: Vec<EnvVariable>) -> Self {
4893 self.env = env;
4894 self
4895 }
4896
4897 #[must_use]
4903 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4904 self.meta = meta.into_option();
4905 self
4906 }
4907}
4908
4909#[serde_as]
4911#[skip_serializing_none]
4912#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4913#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4914#[serde(rename_all = "camelCase")]
4915#[non_exhaustive]
4916pub struct EnvVariable {
4917 pub name: String,
4919 pub value: String,
4921 #[serde_as(deserialize_as = "DefaultOnError")]
4927 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4928 #[serde(default)]
4929 #[serde(rename = "_meta")]
4930 pub meta: Option<Meta>,
4931}
4932
4933impl EnvVariable {
4934 #[must_use]
4936 pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
4937 Self {
4938 name: name.into(),
4939 value: value.into(),
4940 meta: None,
4941 }
4942 }
4943
4944 #[must_use]
4950 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4951 self.meta = meta.into_option();
4952 self
4953 }
4954}
4955
4956#[serde_as]
4958#[skip_serializing_none]
4959#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4960#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4961#[serde(rename_all = "camelCase")]
4962#[non_exhaustive]
4963pub struct HttpHeader {
4964 pub name: String,
4966 pub value: String,
4968 #[serde_as(deserialize_as = "DefaultOnError")]
4974 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4975 #[serde(default)]
4976 #[serde(rename = "_meta")]
4977 pub meta: Option<Meta>,
4978}
4979
4980impl HttpHeader {
4981 #[must_use]
4983 pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
4984 Self {
4985 name: name.into(),
4986 value: value.into(),
4987 meta: None,
4988 }
4989 }
4990
4991 #[must_use]
4997 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4998 self.meta = meta.into_option();
4999 self
5000 }
5001}
5002
5003#[serde_as]
5012#[skip_serializing_none]
5013#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5014#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5015#[serde(rename_all = "camelCase")]
5016#[non_exhaustive]
5017pub struct SystemPrompt {
5018 pub mode: SystemPromptMode,
5023 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
5033 pub content: Vec<ContentBlock>,
5034 #[serde_as(deserialize_as = "DefaultOnError")]
5040 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5041 #[serde(default)]
5042 #[serde(rename = "_meta")]
5043 pub meta: Option<Meta>,
5044}
5045
5046impl SystemPrompt {
5047 #[must_use]
5052 pub fn new(content: Vec<ContentBlock>) -> Self {
5053 Self {
5054 mode: SystemPromptMode::default(),
5055 content,
5056 meta: None,
5057 }
5058 }
5059
5060 #[must_use]
5062 pub fn mode(mut self, mode: SystemPromptMode) -> Self {
5063 self.mode = mode;
5064 self
5065 }
5066
5067 #[must_use]
5073 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5074 self.meta = meta.into_option();
5075 self
5076 }
5077}
5078
5079#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5085#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
5086#[serde(rename_all = "snake_case")]
5087#[non_exhaustive]
5088pub enum SystemPromptMode {
5089 #[default]
5096 Append,
5097 Override,
5106 #[serde(untagged)]
5112 Other(String),
5113}
5114
5115#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5124#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash, Display)]
5125#[serde(transparent)]
5126pub struct IdempotencyKey(
5127 #[cfg_attr(feature = "schemars", schemars(length(min = 1, max = 255)))] Arc<str>,
5128);
5129
5130impl IdempotencyKey {
5131 pub const MAX_LENGTH: usize = 255;
5133
5134 pub fn new(key: impl Into<Arc<str>>) -> Result<Self, InvalidIdempotencyKey> {
5141 let key = key.into();
5142 if key.is_empty() {
5143 return Err(InvalidIdempotencyKey::Empty);
5144 }
5145 if key.chars().nth(Self::MAX_LENGTH).is_some() {
5147 return Err(InvalidIdempotencyKey::TooLong);
5148 }
5149 Ok(Self(key))
5150 }
5151
5152 #[cfg(feature = "uuid")]
5159 #[must_use]
5160 pub fn generate() -> Self {
5161 uuid::Uuid::new_v4().into()
5162 }
5163
5164 #[must_use]
5166 pub fn as_str(&self) -> &str {
5167 &self.0
5168 }
5169}
5170
5171impl AsRef<str> for IdempotencyKey {
5172 fn as_ref(&self) -> &str {
5173 &self.0
5174 }
5175}
5176
5177#[cfg(feature = "uuid")]
5178impl From<uuid::Uuid> for IdempotencyKey {
5179 fn from(uuid: uuid::Uuid) -> Self {
5182 Self(uuid.to_string().into())
5183 }
5184}
5185
5186impl TryFrom<String> for IdempotencyKey {
5187 type Error = InvalidIdempotencyKey;
5188
5189 fn try_from(key: String) -> Result<Self, Self::Error> {
5190 Self::new(key)
5191 }
5192}
5193
5194impl TryFrom<&str> for IdempotencyKey {
5195 type Error = InvalidIdempotencyKey;
5196
5197 fn try_from(key: &str) -> Result<Self, Self::Error> {
5198 Self::new(key)
5199 }
5200}
5201
5202impl std::str::FromStr for IdempotencyKey {
5203 type Err = InvalidIdempotencyKey;
5204
5205 fn from_str(key: &str) -> Result<Self, Self::Err> {
5206 Self::new(key)
5207 }
5208}
5209
5210impl<'de> Deserialize<'de> for IdempotencyKey {
5213 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
5214 where
5215 D: serde::Deserializer<'de>,
5216 {
5217 let key = Arc::<str>::deserialize(deserializer)?;
5218 Self::new(key).map_err(serde::de::Error::custom)
5219 }
5220}
5221
5222#[derive(Debug, Clone, Copy, PartialEq, Eq, Display)]
5224#[non_exhaustive]
5225pub enum InvalidIdempotencyKey {
5226 #[display("idempotency key must not be empty")]
5228 Empty,
5229 #[display(
5231 "idempotency key must be at most {} characters",
5232 IdempotencyKey::MAX_LENGTH
5233 )]
5234 TooLong,
5235}
5236
5237impl std::error::Error for InvalidIdempotencyKey {}
5238
5239#[serde_as]
5245#[skip_serializing_none]
5246#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5247#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5248#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_PROMPT_METHOD_NAME)))]
5249#[serde(rename_all = "camelCase")]
5250#[non_exhaustive]
5251pub struct PromptRequest {
5252 pub session_id: SessionId,
5254 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
5271 pub prompt: Vec<ContentBlock>,
5272 #[serde(default)]
5294 pub idempotency_key: Option<IdempotencyKey>,
5295 #[serde_as(deserialize_as = "DefaultOnError")]
5301 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5302 #[serde(default)]
5303 #[serde(rename = "_meta")]
5304 pub meta: Option<Meta>,
5305}
5306
5307impl PromptRequest {
5308 #[must_use]
5310 pub fn new(session_id: impl Into<SessionId>, prompt: Vec<ContentBlock>) -> Self {
5311 Self {
5312 session_id: session_id.into(),
5313 prompt,
5314 idempotency_key: None,
5315 meta: None,
5316 }
5317 }
5318
5319 #[must_use]
5323 pub fn idempotency_key(mut self, idempotency_key: impl IntoOption<IdempotencyKey>) -> Self {
5324 self.idempotency_key = idempotency_key.into_option();
5325 self
5326 }
5327
5328 #[must_use]
5334 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5335 self.meta = meta.into_option();
5336 self
5337 }
5338}
5339
5340#[serde_as]
5351#[skip_serializing_none]
5352#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5353#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5354#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_PROMPT_METHOD_NAME)))]
5355#[serde(rename_all = "camelCase")]
5356#[non_exhaustive]
5357pub struct PromptResponse {
5358 pub message_id: MessageId,
5366 #[serde_as(deserialize_as = "DefaultOnError")]
5372 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5373 #[serde(default)]
5374 #[serde(rename = "_meta")]
5375 pub meta: Option<Meta>,
5376}
5377
5378impl PromptResponse {
5379 #[must_use]
5381 pub fn new(message_id: impl Into<MessageId>) -> Self {
5382 Self {
5383 message_id: message_id.into(),
5384 meta: None,
5385 }
5386 }
5387
5388 #[must_use]
5394 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5395 self.meta = meta.into_option();
5396 self
5397 }
5398}
5399
5400#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5404#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
5405#[serde(tag = "stopReason", rename_all = "snake_case")]
5406#[non_exhaustive]
5407pub enum StopReason {
5408 EndTurn,
5411 MaxTokens,
5413 MaxTurnRequests,
5416 Refusal,
5418 Cancelled,
5430 Error(ErrorStopReason),
5436 #[serde(untagged)]
5442 Other(OtherStopReason),
5443}
5444
5445impl From<ErrorStopReason> for StopReason {
5446 fn from(value: ErrorStopReason) -> Self {
5447 Self::Error(value)
5448 }
5449}
5450
5451#[serde_as]
5453#[skip_serializing_none]
5454#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5455#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
5456#[serde(rename_all = "camelCase")]
5457#[non_exhaustive]
5458pub struct ErrorStopReason {
5459 #[serde_as(deserialize_as = "DefaultOnError")]
5464 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5465 #[serde(default)]
5466 pub error: Option<Box<Error>>,
5467}
5468
5469impl ErrorStopReason {
5470 #[must_use]
5472 pub fn new() -> Self {
5473 Self::default()
5474 }
5475
5476 #[must_use]
5478 pub fn error(mut self, error: impl IntoOption<Error>) -> Self {
5479 self.error = error.into_option().map(Box::new);
5480 self
5481 }
5482}
5483
5484#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5486#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
5487#[cfg_attr(feature = "schemars", schemars(inline))]
5488#[cfg_attr(feature = "schemars", schemars(transform = other_stop_reason_schema))]
5489#[serde(rename_all = "camelCase")]
5490#[non_exhaustive]
5491pub struct OtherStopReason {
5492 pub stop_reason: String,
5498 #[serde(flatten)]
5500 pub fields: IndexMap<String, serde_json::Value>,
5501}
5502
5503impl OtherStopReason {
5504 #[must_use]
5506 pub fn new(
5507 stop_reason: impl Into<String>,
5508 mut fields: IndexMap<String, serde_json::Value>,
5509 ) -> Self {
5510 remove_idle_state_update_fields(&mut fields);
5511 Self {
5512 stop_reason: stop_reason.into(),
5513 fields,
5514 }
5515 }
5516}
5517
5518impl<'de> Deserialize<'de> for OtherStopReason {
5519 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
5520 where
5521 D: serde::Deserializer<'de>,
5522 {
5523 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
5524 let stop_reason = fields
5525 .shift_remove("stopReason")
5526 .ok_or_else(|| serde::de::Error::missing_field("stopReason"))?;
5527 let serde_json::Value::String(stop_reason) = stop_reason else {
5528 return Err(serde::de::Error::custom("`stopReason` must be a string"));
5529 };
5530
5531 if KNOWN_STOP_REASONS.contains(&stop_reason.as_str()) {
5532 return Err(serde::de::Error::custom(format!(
5533 "known stop reason `{stop_reason}` did not match its schema"
5534 )));
5535 }
5536 remove_idle_state_update_fields(&mut fields);
5537
5538 Ok(Self {
5539 stop_reason,
5540 fields,
5541 })
5542 }
5543}
5544
5545const KNOWN_STOP_REASONS: &[&str] = &[
5546 "end_turn",
5547 "max_tokens",
5548 "max_turn_requests",
5549 "refusal",
5550 "cancelled",
5551 "error",
5552];
5553
5554fn remove_idle_state_update_fields(fields: &mut IndexMap<String, serde_json::Value>) {
5556 fields.shift_remove("stopReason");
5557 fields.shift_remove("usage");
5558 fields.shift_remove("_meta");
5559}
5560
5561#[cfg(feature = "schemars")]
5562fn other_stop_reason_schema(schema: &mut Schema) {
5563 super::schema_util::reject_known_string_discriminators(
5564 schema,
5565 "stopReason",
5566 KNOWN_STOP_REASONS,
5567 );
5568}
5569
5570#[cfg(feature = "unstable_end_turn_token_usage")]
5576#[serde_as]
5577#[skip_serializing_none]
5578#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5579#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5580#[serde(rename_all = "camelCase")]
5581#[non_exhaustive]
5582pub struct Usage {
5583 pub total_tokens: u64,
5585 pub input_tokens: u64,
5587 pub output_tokens: u64,
5589 #[serde_as(deserialize_as = "DefaultOnError")]
5593 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5594 #[serde(default)]
5595 pub thought_tokens: Option<u64>,
5596 #[serde_as(deserialize_as = "DefaultOnError")]
5600 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5601 #[serde(default)]
5602 pub cached_read_tokens: Option<u64>,
5603 #[serde_as(deserialize_as = "DefaultOnError")]
5607 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5608 #[serde(default)]
5609 pub cached_write_tokens: Option<u64>,
5610 #[serde_as(deserialize_as = "DefaultOnError")]
5616 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5617 #[serde(default)]
5618 #[serde(rename = "_meta")]
5619 pub meta: Option<Meta>,
5620}
5621
5622#[cfg(feature = "unstable_end_turn_token_usage")]
5623impl Usage {
5624 #[must_use]
5626 pub fn new(total_tokens: u64, input_tokens: u64, output_tokens: u64) -> Self {
5627 Self {
5628 total_tokens,
5629 input_tokens,
5630 output_tokens,
5631 thought_tokens: None,
5632 cached_read_tokens: None,
5633 cached_write_tokens: None,
5634 meta: None,
5635 }
5636 }
5637
5638 #[must_use]
5640 pub fn thought_tokens(mut self, thought_tokens: impl IntoOption<u64>) -> Self {
5641 self.thought_tokens = thought_tokens.into_option();
5642 self
5643 }
5644
5645 #[must_use]
5647 pub fn cached_read_tokens(mut self, cached_read_tokens: impl IntoOption<u64>) -> Self {
5648 self.cached_read_tokens = cached_read_tokens.into_option();
5649 self
5650 }
5651
5652 #[must_use]
5654 pub fn cached_write_tokens(mut self, cached_write_tokens: impl IntoOption<u64>) -> Self {
5655 self.cached_write_tokens = cached_write_tokens.into_option();
5656 self
5657 }
5658
5659 #[must_use]
5665 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5666 self.meta = meta.into_option();
5667 self
5668 }
5669}
5670
5671#[cfg(feature = "unstable_llm_providers")]
5684#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5685#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5686#[serde(rename_all = "snake_case")]
5687#[non_exhaustive]
5688pub enum LlmProtocol {
5689 Anthropic,
5691 #[serde(rename = "openai")]
5693 OpenAi,
5694 Azure,
5696 Vertex,
5698 Bedrock,
5700 #[serde(untagged)]
5706 Other(String),
5707}
5708
5709#[cfg(feature = "unstable_llm_providers")]
5715#[serde_as]
5716#[skip_serializing_none]
5717#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5718#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5719#[serde(rename_all = "camelCase")]
5720#[non_exhaustive]
5721pub struct ProviderCurrentConfig {
5722 pub api_type: LlmProtocol,
5724 #[cfg_attr(feature = "schemars", schemars(url))]
5726 pub base_url: String,
5727 #[serde_as(deserialize_as = "DefaultOnError")]
5733 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5734 #[serde(default)]
5735 #[serde(rename = "_meta")]
5736 pub meta: Option<Meta>,
5737}
5738
5739#[cfg(feature = "unstable_llm_providers")]
5740impl ProviderCurrentConfig {
5741 #[must_use]
5743 pub fn new(api_type: LlmProtocol, base_url: impl Into<String>) -> Self {
5744 Self {
5745 api_type,
5746 base_url: base_url.into(),
5747 meta: None,
5748 }
5749 }
5750
5751 #[must_use]
5757 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5758 self.meta = meta.into_option();
5759 self
5760 }
5761}
5762
5763#[cfg(feature = "unstable_llm_providers")]
5769#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5770#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
5771#[serde(transparent)]
5772#[from(forward)]
5773#[non_exhaustive]
5774pub struct ProviderId(pub Arc<str>);
5775
5776#[cfg(feature = "unstable_llm_providers")]
5777impl ProviderId {
5778 #[must_use]
5780 pub fn new(id: impl Into<Self>) -> Self {
5781 id.into()
5782 }
5783}
5784
5785#[cfg(feature = "unstable_llm_providers")]
5791#[serde_as]
5792#[skip_serializing_none]
5793#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5794#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5795#[serde(rename_all = "camelCase")]
5796#[non_exhaustive]
5797pub struct ProviderInfo {
5798 pub provider_id: ProviderId,
5800 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
5802 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
5803 pub supported: Vec<LlmProtocol>,
5804 pub required: bool,
5807 #[serde(default)]
5810 pub current: Option<ProviderCurrentConfig>,
5811 #[serde_as(deserialize_as = "DefaultOnError")]
5817 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5818 #[serde(default)]
5819 #[serde(rename = "_meta")]
5820 pub meta: Option<Meta>,
5821}
5822
5823#[cfg(feature = "unstable_llm_providers")]
5824impl ProviderInfo {
5825 #[must_use]
5827 pub fn new(
5828 provider_id: impl Into<ProviderId>,
5829 supported: Vec<LlmProtocol>,
5830 required: bool,
5831 current: impl IntoOption<ProviderCurrentConfig>,
5832 ) -> Self {
5833 Self {
5834 provider_id: provider_id.into(),
5835 supported,
5836 required,
5837 current: current.into_option(),
5838 meta: None,
5839 }
5840 }
5841
5842 #[must_use]
5848 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5849 self.meta = meta.into_option();
5850 self
5851 }
5852}
5853
5854#[cfg(feature = "unstable_llm_providers")]
5855crate::serde_util::default_on_null! {
5856 #[serde_as]
5862 #[skip_serializing_none]
5863 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5864 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
5865 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_LIST_METHOD_NAME)))]
5866 #[serde(rename_all = "camelCase")]
5867 #[non_exhaustive]
5868 pub struct ListProvidersRequest {
5869 #[serde_as(deserialize_as = "DefaultOnError")]
5875 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5876 #[serde(default)]
5877 #[serde(rename = "_meta")]
5878 pub meta: Option<Meta>,
5879 }
5880}
5881
5882#[cfg(feature = "unstable_llm_providers")]
5883impl ListProvidersRequest {
5884 #[must_use]
5886 pub fn new() -> Self {
5887 Self::default()
5888 }
5889
5890 #[must_use]
5896 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5897 self.meta = meta.into_option();
5898 self
5899 }
5900}
5901
5902#[cfg(feature = "unstable_llm_providers")]
5908#[serde_as]
5909#[skip_serializing_none]
5910#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5911#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5912#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_LIST_METHOD_NAME)))]
5913#[serde(rename_all = "camelCase")]
5914#[non_exhaustive]
5915pub struct ListProvidersResponse {
5916 pub providers: Vec<ProviderInfo>,
5918 #[serde_as(deserialize_as = "DefaultOnError")]
5924 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5925 #[serde(default)]
5926 #[serde(rename = "_meta")]
5927 pub meta: Option<Meta>,
5928}
5929
5930#[cfg(feature = "unstable_llm_providers")]
5931impl ListProvidersResponse {
5932 #[must_use]
5934 pub fn new(providers: Vec<ProviderInfo>) -> Self {
5935 Self {
5936 providers,
5937 meta: None,
5938 }
5939 }
5940
5941 #[must_use]
5947 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5948 self.meta = meta.into_option();
5949 self
5950 }
5951}
5952
5953#[cfg(feature = "unstable_llm_providers")]
5961#[serde_as]
5962#[skip_serializing_none]
5963#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5964#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
5965#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_SET_METHOD_NAME)))]
5966#[serde(rename_all = "camelCase")]
5967#[non_exhaustive]
5968pub struct SetProviderRequest {
5969 pub provider_id: ProviderId,
5971 pub api_type: LlmProtocol,
5973 #[cfg_attr(feature = "schemars", schemars(url))]
5975 pub base_url: String,
5976 #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
5979 pub headers: IndexMap<String, String>,
5980 #[serde_as(deserialize_as = "DefaultOnError")]
5986 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5987 #[serde(default)]
5988 #[serde(rename = "_meta")]
5989 pub meta: Option<Meta>,
5990}
5991
5992#[cfg(feature = "unstable_llm_providers")]
5993impl SetProviderRequest {
5994 #[must_use]
5996 pub fn new(
5997 provider_id: impl Into<ProviderId>,
5998 api_type: LlmProtocol,
5999 base_url: impl Into<String>,
6000 ) -> Self {
6001 Self {
6002 provider_id: provider_id.into(),
6003 api_type,
6004 base_url: base_url.into(),
6005 headers: IndexMap::new(),
6006 meta: None,
6007 }
6008 }
6009
6010 #[must_use]
6013 pub fn headers(mut self, headers: IndexMap<String, String>) -> Self {
6014 self.headers = headers;
6015 self
6016 }
6017
6018 #[must_use]
6024 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6025 self.meta = meta.into_option();
6026 self
6027 }
6028}
6029
6030#[cfg(feature = "unstable_llm_providers")]
6031crate::serde_util::default_on_null! {
6032 #[serde_as]
6038 #[skip_serializing_none]
6039 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6040 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
6041 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_SET_METHOD_NAME)))]
6042 #[serde(rename_all = "camelCase")]
6043 #[non_exhaustive]
6044 pub struct SetProviderResponse {
6045 #[serde_as(deserialize_as = "DefaultOnError")]
6051 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6052 #[serde(default)]
6053 #[serde(rename = "_meta")]
6054 pub meta: Option<Meta>,
6055 }
6056}
6057
6058#[cfg(feature = "unstable_llm_providers")]
6059impl SetProviderResponse {
6060 #[must_use]
6062 pub fn new() -> Self {
6063 Self::default()
6064 }
6065
6066 #[must_use]
6072 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6073 self.meta = meta.into_option();
6074 self
6075 }
6076}
6077
6078#[cfg(feature = "unstable_llm_providers")]
6084#[serde_as]
6085#[skip_serializing_none]
6086#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6087#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6088#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_DISABLE_METHOD_NAME)))]
6089#[serde(rename_all = "camelCase")]
6090#[non_exhaustive]
6091pub struct DisableProviderRequest {
6092 pub provider_id: ProviderId,
6094 #[serde_as(deserialize_as = "DefaultOnError")]
6100 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6101 #[serde(default)]
6102 #[serde(rename = "_meta")]
6103 pub meta: Option<Meta>,
6104}
6105
6106#[cfg(feature = "unstable_llm_providers")]
6107impl DisableProviderRequest {
6108 #[must_use]
6110 pub fn new(provider_id: impl Into<ProviderId>) -> Self {
6111 Self {
6112 provider_id: provider_id.into(),
6113 meta: None,
6114 }
6115 }
6116
6117 #[must_use]
6123 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6124 self.meta = meta.into_option();
6125 self
6126 }
6127}
6128
6129#[cfg(feature = "unstable_llm_providers")]
6130crate::serde_util::default_on_null! {
6131 #[serde_as]
6137 #[skip_serializing_none]
6138 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6139 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
6140 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_DISABLE_METHOD_NAME)))]
6141 #[serde(rename_all = "camelCase")]
6142 #[non_exhaustive]
6143 pub struct DisableProviderResponse {
6144 #[serde_as(deserialize_as = "DefaultOnError")]
6150 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6151 #[serde(default)]
6152 #[serde(rename = "_meta")]
6153 pub meta: Option<Meta>,
6154 }
6155}
6156
6157#[cfg(feature = "unstable_llm_providers")]
6158impl DisableProviderResponse {
6159 #[must_use]
6161 pub fn new() -> Self {
6162 Self::default()
6163 }
6164
6165 #[must_use]
6171 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6172 self.meta = meta.into_option();
6173 self
6174 }
6175}
6176
6177#[serde_as]
6186#[skip_serializing_none]
6187#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6188#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6189#[serde(rename_all = "camelCase")]
6190#[non_exhaustive]
6191pub struct AgentCapabilities {
6192 #[serde_as(deserialize_as = "DefaultOnError")]
6200 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6201 #[serde(default)]
6202 pub session: Option<SessionCapabilities>,
6203 #[serde_as(deserialize_as = "DefaultOnError")]
6210 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6211 #[serde(default)]
6212 pub auth: Option<AgentAuthCapabilities>,
6213 #[cfg(feature = "unstable_llm_providers")]
6222 #[serde_as(deserialize_as = "DefaultOnError")]
6223 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6224 #[serde(default)]
6225 pub providers: Option<ProvidersCapabilities>,
6226 #[serde_as(deserialize_as = "DefaultOnError")]
6232 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6233 #[serde(default)]
6234 #[serde(rename = "_meta")]
6235 pub meta: Option<Meta>,
6236}
6237
6238impl AgentCapabilities {
6239 #[must_use]
6241 pub fn new() -> Self {
6242 Self::default()
6243 }
6244
6245 #[must_use]
6253 pub fn session(mut self, session: impl IntoOption<SessionCapabilities>) -> Self {
6254 self.session = session.into_option();
6255 self
6256 }
6257
6258 #[must_use]
6262 pub fn auth(mut self, auth: impl IntoOption<AgentAuthCapabilities>) -> Self {
6263 self.auth = auth.into_option();
6264 self
6265 }
6266
6267 #[cfg(feature = "unstable_llm_providers")]
6273 #[must_use]
6274 pub fn providers(mut self, providers: impl IntoOption<ProvidersCapabilities>) -> Self {
6275 self.providers = providers.into_option();
6276 self
6277 }
6278
6279 #[must_use]
6285 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6286 self.meta = meta.into_option();
6287 self
6288 }
6289}
6290
6291#[cfg(feature = "unstable_llm_providers")]
6299#[serde_as]
6300#[skip_serializing_none]
6301#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6302#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6303#[non_exhaustive]
6304pub struct ProvidersCapabilities {
6305 #[serde_as(deserialize_as = "DefaultOnError")]
6311 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6312 #[serde(default)]
6313 #[serde(rename = "_meta")]
6314 pub meta: Option<Meta>,
6315}
6316
6317#[cfg(feature = "unstable_llm_providers")]
6318impl ProvidersCapabilities {
6319 #[must_use]
6321 pub fn new() -> Self {
6322 Self::default()
6323 }
6324
6325 #[must_use]
6331 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6332 self.meta = meta.into_option();
6333 self
6334 }
6335}
6336
6337#[serde_as]
6349#[skip_serializing_none]
6350#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6351#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6352#[serde(rename_all = "camelCase")]
6353#[non_exhaustive]
6354pub struct SessionCapabilities {
6355 #[serde_as(deserialize_as = "DefaultOnError")]
6361 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6362 #[serde(default)]
6363 pub prompt: Option<PromptCapabilities>,
6364 #[serde_as(deserialize_as = "DefaultOnError")]
6369 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6370 #[serde(default)]
6371 pub mcp: Option<McpCapabilities>,
6372 #[serde_as(deserialize_as = "DefaultOnError")]
6377 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6378 #[serde(default)]
6379 pub delete: Option<SessionDeleteCapabilities>,
6380 #[serde_as(deserialize_as = "DefaultOnError")]
6389 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6390 #[serde(default)]
6391 pub additional_directories: Option<SessionAdditionalDirectoriesCapabilities>,
6392 #[serde_as(deserialize_as = "DefaultOnError")]
6397 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6398 #[serde(default)]
6399 pub system_prompt: Option<SessionSystemPromptCapabilities>,
6400 #[cfg(feature = "unstable_session_fork")]
6409 #[serde_as(deserialize_as = "DefaultOnError")]
6410 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6411 #[serde(default)]
6412 pub fork: Option<SessionForkCapabilities>,
6413 #[cfg(feature = "unstable_session_archive")]
6423 #[serde_as(deserialize_as = "DefaultOnError")]
6424 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6425 #[serde(default)]
6426 pub archive: Option<SessionArchiveCapabilities>,
6427 #[cfg(feature = "unstable_session_status")]
6436 #[serde_as(deserialize_as = "DefaultOnError")]
6437 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6438 #[serde(default)]
6439 pub status: Option<SessionStatusCapabilities>,
6440 #[cfg(feature = "unstable_session_options")]
6450 #[serde_as(deserialize_as = "DefaultOnError")]
6451 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6452 #[serde(default)]
6453 pub options: Option<SessionOptionsCapabilities>,
6454 #[cfg(feature = "unstable_session_set_title")]
6466 #[serde_as(deserialize_as = "DefaultOnError")]
6467 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6468 #[serde(default)]
6469 pub title: Option<SessionTitleCapabilities>,
6470 #[serde_as(deserialize_as = "DefaultOnError")]
6476 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6477 #[serde(default)]
6478 #[serde(rename = "_meta")]
6479 pub meta: Option<Meta>,
6480}
6481
6482impl SessionCapabilities {
6483 #[must_use]
6485 pub fn new() -> Self {
6486 Self::default()
6487 }
6488
6489 #[must_use]
6495 pub fn prompt(mut self, prompt: impl IntoOption<PromptCapabilities>) -> Self {
6496 self.prompt = prompt.into_option();
6497 self
6498 }
6499
6500 #[must_use]
6505 pub fn mcp(mut self, mcp: impl IntoOption<McpCapabilities>) -> Self {
6506 self.mcp = mcp.into_option();
6507 self
6508 }
6509
6510 #[must_use]
6515 pub fn delete(mut self, delete: impl IntoOption<SessionDeleteCapabilities>) -> Self {
6516 self.delete = delete.into_option();
6517 self
6518 }
6519
6520 #[must_use]
6529 pub fn additional_directories(
6530 mut self,
6531 additional_directories: impl IntoOption<SessionAdditionalDirectoriesCapabilities>,
6532 ) -> Self {
6533 self.additional_directories = additional_directories.into_option();
6534 self
6535 }
6536
6537 #[must_use]
6542 pub fn system_prompt(
6543 mut self,
6544 system_prompt: impl IntoOption<SessionSystemPromptCapabilities>,
6545 ) -> Self {
6546 self.system_prompt = system_prompt.into_option();
6547 self
6548 }
6549
6550 #[cfg(feature = "unstable_session_fork")]
6551 #[must_use]
6556 pub fn fork(mut self, fork: impl IntoOption<SessionForkCapabilities>) -> Self {
6557 self.fork = fork.into_option();
6558 self
6559 }
6560
6561 #[cfg(feature = "unstable_session_archive")]
6571 #[must_use]
6572 pub fn archive(mut self, archive: impl IntoOption<SessionArchiveCapabilities>) -> Self {
6573 self.archive = archive.into_option();
6574 self
6575 }
6576
6577 #[cfg(feature = "unstable_session_status")]
6586 #[must_use]
6587 pub fn status(mut self, status: impl IntoOption<SessionStatusCapabilities>) -> Self {
6588 self.status = status.into_option();
6589 self
6590 }
6591
6592 #[cfg(feature = "unstable_session_options")]
6602 #[must_use]
6603 pub fn options(mut self, options: impl IntoOption<SessionOptionsCapabilities>) -> Self {
6604 self.options = options.into_option();
6605 self
6606 }
6607
6608 #[cfg(feature = "unstable_session_set_title")]
6620 #[must_use]
6621 pub fn title(mut self, title: impl IntoOption<SessionTitleCapabilities>) -> Self {
6622 self.title = title.into_option();
6623 self
6624 }
6625
6626 #[must_use]
6632 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6633 self.meta = meta.into_option();
6634 self
6635 }
6636}
6637
6638#[serde_as]
6642#[skip_serializing_none]
6643#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6644#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6645#[non_exhaustive]
6646pub struct SessionDeleteCapabilities {
6647 #[serde_as(deserialize_as = "DefaultOnError")]
6653 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6654 #[serde(default)]
6655 #[serde(rename = "_meta")]
6656 pub meta: Option<Meta>,
6657}
6658
6659impl SessionDeleteCapabilities {
6660 #[must_use]
6662 pub fn new() -> Self {
6663 Self::default()
6664 }
6665
6666 #[must_use]
6672 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6673 self.meta = meta.into_option();
6674 self
6675 }
6676}
6677
6678#[serde_as]
6685#[skip_serializing_none]
6686#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6687#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6688#[non_exhaustive]
6689pub struct SessionAdditionalDirectoriesCapabilities {
6690 #[serde_as(deserialize_as = "DefaultOnError")]
6696 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6697 #[serde(default)]
6698 #[serde(rename = "_meta")]
6699 pub meta: Option<Meta>,
6700}
6701
6702impl SessionAdditionalDirectoriesCapabilities {
6703 #[must_use]
6705 pub fn new() -> Self {
6706 Self::default()
6707 }
6708
6709 #[must_use]
6715 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6716 self.meta = meta.into_option();
6717 self
6718 }
6719}
6720
6721#[serde_as]
6726#[skip_serializing_none]
6727#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6728#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6729#[serde(rename_all = "camelCase")]
6730#[non_exhaustive]
6731pub struct SessionSystemPromptCapabilities {
6732 #[serde_as(deserialize_as = "DefaultOnError")]
6736 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6737 #[serde(default)]
6738 pub mode: Option<SessionSystemPromptModeCapabilities>,
6739 #[serde_as(deserialize_as = "DefaultOnError")]
6745 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6746 #[serde(default)]
6747 #[serde(rename = "_meta")]
6748 pub meta: Option<Meta>,
6749}
6750
6751impl SessionSystemPromptCapabilities {
6752 #[must_use]
6754 pub fn new() -> Self {
6755 Self::default()
6756 }
6757
6758 #[must_use]
6762 pub fn mode(mut self, mode: impl IntoOption<SessionSystemPromptModeCapabilities>) -> Self {
6763 self.mode = mode.into_option();
6764 self
6765 }
6766
6767 #[must_use]
6773 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6774 self.meta = meta.into_option();
6775 self
6776 }
6777}
6778
6779#[serde_as]
6784#[skip_serializing_none]
6785#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6786#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6787#[serde(rename_all = "camelCase")]
6788#[non_exhaustive]
6789pub struct SessionSystemPromptModeCapabilities {
6790 #[serde_as(deserialize_as = "DefaultOnError")]
6796 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6797 #[serde(default, rename = "override")]
6798 pub override_: Option<SessionSystemPromptOverrideCapabilities>,
6799 #[serde_as(deserialize_as = "DefaultOnError")]
6805 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6806 #[serde(default)]
6807 #[serde(rename = "_meta")]
6808 pub meta: Option<Meta>,
6809}
6810
6811impl SessionSystemPromptModeCapabilities {
6812 #[must_use]
6814 pub fn new() -> Self {
6815 Self::default()
6816 }
6817
6818 #[must_use]
6824 pub fn override_(
6825 mut self,
6826 override_: impl IntoOption<SessionSystemPromptOverrideCapabilities>,
6827 ) -> Self {
6828 self.override_ = override_.into_option();
6829 self
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#[serde_as]
6849#[skip_serializing_none]
6850#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6851#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6852#[non_exhaustive]
6853pub struct SessionSystemPromptOverrideCapabilities {
6854 #[serde_as(deserialize_as = "DefaultOnError")]
6860 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6861 #[serde(default)]
6862 #[serde(rename = "_meta")]
6863 pub meta: Option<Meta>,
6864}
6865
6866impl SessionSystemPromptOverrideCapabilities {
6867 #[must_use]
6869 pub fn new() -> Self {
6870 Self::default()
6871 }
6872
6873 #[must_use]
6879 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6880 self.meta = meta.into_option();
6881 self
6882 }
6883}
6884
6885#[cfg(feature = "unstable_session_fork")]
6893#[serde_as]
6894#[skip_serializing_none]
6895#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6896#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6897#[non_exhaustive]
6898pub struct SessionForkCapabilities {
6899 #[serde_as(deserialize_as = "DefaultOnError")]
6905 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6906 #[serde(default)]
6907 #[serde(rename = "_meta")]
6908 pub meta: Option<Meta>,
6909}
6910
6911#[cfg(feature = "unstable_session_fork")]
6912impl SessionForkCapabilities {
6913 #[must_use]
6915 pub fn new() -> Self {
6916 Self::default()
6917 }
6918
6919 #[must_use]
6925 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6926 self.meta = meta.into_option();
6927 self
6928 }
6929}
6930
6931#[cfg(feature = "unstable_session_archive")]
6940#[serde_as]
6941#[skip_serializing_none]
6942#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6943#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6944#[non_exhaustive]
6945pub struct SessionArchiveCapabilities {
6946 #[serde_as(deserialize_as = "DefaultOnError")]
6952 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6953 #[serde(default)]
6954 #[serde(rename = "_meta")]
6955 pub meta: Option<Meta>,
6956}
6957
6958#[cfg(feature = "unstable_session_archive")]
6959impl SessionArchiveCapabilities {
6960 #[must_use]
6962 pub fn new() -> Self {
6963 Self::default()
6964 }
6965
6966 #[must_use]
6972 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6973 self.meta = meta.into_option();
6974 self
6975 }
6976}
6977
6978#[cfg(feature = "unstable_session_status")]
6986#[serde_as]
6987#[skip_serializing_none]
6988#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6989#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6990#[non_exhaustive]
6991pub struct SessionStatusCapabilities {
6992 #[serde_as(deserialize_as = "DefaultOnError")]
6998 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6999 #[serde(default)]
7000 #[serde(rename = "_meta")]
7001 pub meta: Option<Meta>,
7002}
7003
7004#[cfg(feature = "unstable_session_status")]
7005impl SessionStatusCapabilities {
7006 #[must_use]
7008 pub fn new() -> Self {
7009 Self::default()
7010 }
7011
7012 #[must_use]
7018 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7019 self.meta = meta.into_option();
7020 self
7021 }
7022}
7023
7024#[cfg(feature = "unstable_session_options")]
7033#[serde_as]
7034#[skip_serializing_none]
7035#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7036#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7037#[non_exhaustive]
7038pub struct SessionOptionsCapabilities {
7039 #[serde_as(deserialize_as = "DefaultOnError")]
7045 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7046 #[serde(default)]
7047 #[serde(rename = "_meta")]
7048 pub meta: Option<Meta>,
7049}
7050
7051#[cfg(feature = "unstable_session_options")]
7052impl SessionOptionsCapabilities {
7053 #[must_use]
7055 pub fn new() -> Self {
7056 Self::default()
7057 }
7058
7059 #[must_use]
7065 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7066 self.meta = meta.into_option();
7067 self
7068 }
7069}
7070
7071#[cfg(feature = "unstable_session_set_title")]
7080#[serde_as]
7081#[skip_serializing_none]
7082#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7083#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7084#[non_exhaustive]
7085pub struct SessionTitleCapabilities {
7086 #[serde_as(deserialize_as = "DefaultOnError")]
7092 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7093 #[serde(default)]
7094 #[serde(rename = "_meta")]
7095 pub meta: Option<Meta>,
7096}
7097
7098#[cfg(feature = "unstable_session_set_title")]
7099impl SessionTitleCapabilities {
7100 #[must_use]
7102 pub fn new() -> Self {
7103 Self::default()
7104 }
7105
7106 #[must_use]
7112 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7113 self.meta = meta.into_option();
7114 self
7115 }
7116}
7117
7118#[serde_as]
7131#[skip_serializing_none]
7132#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7133#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7134#[serde(rename_all = "camelCase")]
7135#[non_exhaustive]
7136pub struct PromptCapabilities {
7137 #[serde_as(deserialize_as = "DefaultOnError")]
7142 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7143 #[serde(default)]
7144 pub image: Option<PromptImageCapabilities>,
7145 #[serde_as(deserialize_as = "DefaultOnError")]
7150 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7151 #[serde(default)]
7152 pub audio: Option<PromptAudioCapabilities>,
7153 #[serde_as(deserialize_as = "DefaultOnError")]
7161 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7162 #[serde(default)]
7163 pub embedded_context: Option<PromptEmbeddedContextCapabilities>,
7164 #[cfg(feature = "unstable_agent_skills")]
7174 #[serde_as(deserialize_as = "DefaultOnError")]
7175 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7176 #[serde(default)]
7177 pub skill: Option<PromptSkillCapabilities>,
7178 #[serde_as(deserialize_as = "DefaultOnError")]
7184 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7185 #[serde(default)]
7186 #[serde(rename = "_meta")]
7187 pub meta: Option<Meta>,
7188}
7189
7190impl PromptCapabilities {
7191 #[must_use]
7193 pub fn new() -> Self {
7194 Self::default()
7195 }
7196
7197 #[must_use]
7202 pub fn image(mut self, image: impl IntoOption<PromptImageCapabilities>) -> Self {
7203 self.image = image.into_option();
7204 self
7205 }
7206
7207 #[must_use]
7212 pub fn audio(mut self, audio: impl IntoOption<PromptAudioCapabilities>) -> Self {
7213 self.audio = audio.into_option();
7214 self
7215 }
7216
7217 #[must_use]
7225 pub fn embedded_context(
7226 mut self,
7227 embedded_context: impl IntoOption<PromptEmbeddedContextCapabilities>,
7228 ) -> Self {
7229 self.embedded_context = embedded_context.into_option();
7230 self
7231 }
7232
7233 #[cfg(feature = "unstable_agent_skills")]
7242 #[must_use]
7243 pub fn skill(mut self, skill: impl IntoOption<PromptSkillCapabilities>) -> Self {
7244 self.skill = skill.into_option();
7245 self
7246 }
7247
7248 #[must_use]
7254 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7255 self.meta = meta.into_option();
7256 self
7257 }
7258}
7259
7260#[serde_as]
7264#[skip_serializing_none]
7265#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7266#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7267#[non_exhaustive]
7268pub struct PromptImageCapabilities {
7269 #[serde_as(deserialize_as = "DefaultOnError")]
7275 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7276 #[serde(default)]
7277 #[serde(rename = "_meta")]
7278 pub meta: Option<Meta>,
7279}
7280
7281impl PromptImageCapabilities {
7282 #[must_use]
7284 pub fn new() -> Self {
7285 Self::default()
7286 }
7287
7288 #[must_use]
7294 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7295 self.meta = meta.into_option();
7296 self
7297 }
7298}
7299
7300#[serde_as]
7304#[skip_serializing_none]
7305#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7306#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7307#[non_exhaustive]
7308pub struct PromptAudioCapabilities {
7309 #[serde_as(deserialize_as = "DefaultOnError")]
7315 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7316 #[serde(default)]
7317 #[serde(rename = "_meta")]
7318 pub meta: Option<Meta>,
7319}
7320
7321impl PromptAudioCapabilities {
7322 #[must_use]
7324 pub fn new() -> Self {
7325 Self::default()
7326 }
7327
7328 #[must_use]
7334 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7335 self.meta = meta.into_option();
7336 self
7337 }
7338}
7339
7340#[serde_as]
7344#[skip_serializing_none]
7345#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7346#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7347#[non_exhaustive]
7348pub struct PromptEmbeddedContextCapabilities {
7349 #[serde_as(deserialize_as = "DefaultOnError")]
7355 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7356 #[serde(default)]
7357 #[serde(rename = "_meta")]
7358 pub meta: Option<Meta>,
7359}
7360
7361impl PromptEmbeddedContextCapabilities {
7362 #[must_use]
7364 pub fn new() -> Self {
7365 Self::default()
7366 }
7367
7368 #[must_use]
7374 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7375 self.meta = meta.into_option();
7376 self
7377 }
7378}
7379
7380#[cfg(feature = "unstable_agent_skills")]
7389#[serde_as]
7390#[skip_serializing_none]
7391#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7392#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7393#[serde(rename_all = "camelCase")]
7394#[non_exhaustive]
7395pub struct PromptSkillCapabilities {
7396 #[serde_as(deserialize_as = "DefaultOnError")]
7402 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7403 #[serde(default)]
7404 pub inline: Option<PromptSkillInlineCapabilities>,
7405 #[serde_as(deserialize_as = "DefaultOnError")]
7411 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7412 #[serde(default)]
7413 #[serde(rename = "_meta")]
7414 pub meta: Option<Meta>,
7415}
7416
7417#[cfg(feature = "unstable_agent_skills")]
7418impl PromptSkillCapabilities {
7419 #[must_use]
7421 pub fn new() -> Self {
7422 Self::default()
7423 }
7424
7425 #[must_use]
7431 pub fn inline(mut self, inline: impl IntoOption<PromptSkillInlineCapabilities>) -> Self {
7432 self.inline = inline.into_option();
7433 self
7434 }
7435
7436 #[must_use]
7442 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7443 self.meta = meta.into_option();
7444 self
7445 }
7446}
7447
7448#[cfg(feature = "unstable_agent_skills")]
7457#[serde_as]
7458#[skip_serializing_none]
7459#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7460#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7461#[non_exhaustive]
7462pub struct PromptSkillInlineCapabilities {
7463 #[serde_as(deserialize_as = "DefaultOnError")]
7469 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7470 #[serde(default)]
7471 #[serde(rename = "_meta")]
7472 pub meta: Option<Meta>,
7473}
7474
7475#[cfg(feature = "unstable_agent_skills")]
7476impl PromptSkillInlineCapabilities {
7477 #[must_use]
7479 pub fn new() -> Self {
7480 Self::default()
7481 }
7482
7483 #[must_use]
7489 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7490 self.meta = meta.into_option();
7491 self
7492 }
7493}
7494
7495#[serde_as]
7497#[skip_serializing_none]
7498#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7499#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7500#[serde(rename_all = "camelCase")]
7501#[non_exhaustive]
7502pub struct McpCapabilities {
7503 #[serde_as(deserialize_as = "DefaultOnError")]
7508 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7509 #[serde(default)]
7510 pub stdio: Option<McpStdioCapabilities>,
7511 #[serde_as(deserialize_as = "DefaultOnError")]
7516 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7517 #[serde(default)]
7518 pub http: Option<McpHttpCapabilities>,
7519 #[cfg(feature = "unstable_mcp_over_acp")]
7528 #[serde_as(deserialize_as = "DefaultOnError")]
7529 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7530 #[serde(default)]
7531 pub acp: Option<McpAcpCapabilities>,
7532 #[serde_as(deserialize_as = "DefaultOnError")]
7538 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7539 #[serde(default)]
7540 #[serde(rename = "_meta")]
7541 pub meta: Option<Meta>,
7542}
7543
7544impl McpCapabilities {
7545 #[must_use]
7547 pub fn new() -> Self {
7548 Self::default()
7549 }
7550
7551 #[must_use]
7556 pub fn stdio(mut self, stdio: impl IntoOption<McpStdioCapabilities>) -> Self {
7557 self.stdio = stdio.into_option();
7558 self
7559 }
7560
7561 #[must_use]
7566 pub fn http(mut self, http: impl IntoOption<McpHttpCapabilities>) -> Self {
7567 self.http = http.into_option();
7568 self
7569 }
7570
7571 #[cfg(feature = "unstable_mcp_over_acp")]
7577 #[must_use]
7581 pub fn acp(mut self, acp: impl IntoOption<McpAcpCapabilities>) -> Self {
7582 self.acp = acp.into_option();
7583 self
7584 }
7585
7586 #[must_use]
7592 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7593 self.meta = meta.into_option();
7594 self
7595 }
7596}
7597
7598#[serde_as]
7602#[skip_serializing_none]
7603#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7604#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7605#[non_exhaustive]
7606pub struct McpStdioCapabilities {
7607 #[serde_as(deserialize_as = "DefaultOnError")]
7613 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7614 #[serde(default)]
7615 #[serde(rename = "_meta")]
7616 pub meta: Option<Meta>,
7617}
7618
7619impl McpStdioCapabilities {
7620 #[must_use]
7622 pub fn new() -> Self {
7623 Self::default()
7624 }
7625
7626 #[must_use]
7632 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7633 self.meta = meta.into_option();
7634 self
7635 }
7636}
7637
7638#[serde_as]
7642#[skip_serializing_none]
7643#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7644#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7645#[non_exhaustive]
7646pub struct McpHttpCapabilities {
7647 #[serde_as(deserialize_as = "DefaultOnError")]
7653 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7654 #[serde(default)]
7655 #[serde(rename = "_meta")]
7656 pub meta: Option<Meta>,
7657}
7658
7659impl McpHttpCapabilities {
7660 #[must_use]
7662 pub fn new() -> Self {
7663 Self::default()
7664 }
7665
7666 #[must_use]
7672 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7673 self.meta = meta.into_option();
7674 self
7675 }
7676}
7677
7678#[cfg(feature = "unstable_mcp_over_acp")]
7686#[serde_as]
7687#[skip_serializing_none]
7688#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7689#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7690#[non_exhaustive]
7691pub struct McpAcpCapabilities {
7692 #[serde_as(deserialize_as = "DefaultOnError")]
7698 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7699 #[serde(default)]
7700 #[serde(rename = "_meta")]
7701 pub meta: Option<Meta>,
7702}
7703
7704#[cfg(feature = "unstable_mcp_over_acp")]
7705impl McpAcpCapabilities {
7706 #[must_use]
7708 pub fn new() -> Self {
7709 Self::default()
7710 }
7711
7712 #[must_use]
7718 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7719 self.meta = meta.into_option();
7720 self
7721 }
7722}
7723
7724#[serde_as]
7729#[skip_serializing_none]
7730#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7731#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7732#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CANCEL_METHOD_NAME)))]
7733#[serde(rename_all = "camelCase")]
7734#[non_exhaustive]
7735pub struct CancelSessionNotification {
7736 pub session_id: SessionId,
7738 #[serde_as(deserialize_as = "DefaultOnError")]
7744 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7745 #[serde(default)]
7746 #[serde(rename = "_meta")]
7747 pub meta: Option<Meta>,
7748}
7749
7750impl CancelSessionNotification {
7751 #[must_use]
7753 pub fn new(session_id: impl Into<SessionId>) -> Self {
7754 Self {
7755 session_id: session_id.into(),
7756 meta: None,
7757 }
7758 }
7759
7760 #[must_use]
7766 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7767 self.meta = meta.into_option();
7768 self
7769 }
7770}
7771
7772#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7778#[non_exhaustive]
7779pub struct AgentMethodNames {
7780 pub initialize: &'static str,
7782 pub auth_login: &'static str,
7784 #[cfg(feature = "unstable_llm_providers")]
7786 pub providers_list: &'static str,
7787 #[cfg(feature = "unstable_llm_providers")]
7789 pub providers_set: &'static str,
7790 #[cfg(feature = "unstable_llm_providers")]
7792 pub providers_disable: &'static str,
7793 pub session_new: &'static str,
7795 pub session_set_config_option: &'static str,
7797 pub session_prompt: &'static str,
7799 pub session_cancel: &'static str,
7801 #[cfg(feature = "unstable_mcp_over_acp")]
7803 pub mcp_message: &'static str,
7804 pub session_list: &'static str,
7806 pub session_delete: &'static str,
7808 #[cfg(feature = "unstable_session_fork")]
7810 pub session_fork: &'static str,
7811 #[cfg(feature = "unstable_session_archive")]
7813 pub session_archive: &'static str,
7814 #[cfg(feature = "unstable_session_archive")]
7816 pub session_unarchive: &'static str,
7817 #[cfg(feature = "unstable_session_status")]
7819 pub session_status: &'static str,
7820 #[cfg(feature = "unstable_session_options")]
7822 pub session_options: &'static str,
7823 #[cfg(feature = "unstable_session_set_title")]
7825 pub session_set_title: &'static str,
7826 pub session_resume: &'static str,
7828 pub session_close: &'static str,
7830 pub tool_call_cancel: &'static str,
7832 pub terminal_cancel: &'static str,
7834 pub auth_logout: &'static str,
7836 #[cfg(feature = "unstable_auth_status")]
7838 pub auth_status: &'static str,
7839}
7840
7841pub const AGENT_METHOD_NAMES: AgentMethodNames = AgentMethodNames {
7843 initialize: INITIALIZE_METHOD_NAME,
7844 auth_login: AUTH_LOGIN_METHOD_NAME,
7845 #[cfg(feature = "unstable_llm_providers")]
7846 providers_list: PROVIDERS_LIST_METHOD_NAME,
7847 #[cfg(feature = "unstable_llm_providers")]
7848 providers_set: PROVIDERS_SET_METHOD_NAME,
7849 #[cfg(feature = "unstable_llm_providers")]
7850 providers_disable: PROVIDERS_DISABLE_METHOD_NAME,
7851 session_new: SESSION_NEW_METHOD_NAME,
7852 session_set_config_option: SESSION_SET_CONFIG_OPTION_METHOD_NAME,
7853 session_prompt: SESSION_PROMPT_METHOD_NAME,
7854 session_cancel: SESSION_CANCEL_METHOD_NAME,
7855 #[cfg(feature = "unstable_mcp_over_acp")]
7856 mcp_message: MCP_MESSAGE_METHOD_NAME,
7857 session_list: SESSION_LIST_METHOD_NAME,
7858 session_delete: SESSION_DELETE_METHOD_NAME,
7859 #[cfg(feature = "unstable_session_fork")]
7860 session_fork: SESSION_FORK_METHOD_NAME,
7861 #[cfg(feature = "unstable_session_archive")]
7862 session_archive: SESSION_ARCHIVE_METHOD_NAME,
7863 #[cfg(feature = "unstable_session_archive")]
7864 session_unarchive: SESSION_UNARCHIVE_METHOD_NAME,
7865 #[cfg(feature = "unstable_session_status")]
7866 session_status: SESSION_STATUS_METHOD_NAME,
7867 #[cfg(feature = "unstable_session_options")]
7868 session_options: SESSION_OPTIONS_METHOD_NAME,
7869 #[cfg(feature = "unstable_session_set_title")]
7870 session_set_title: SESSION_SET_TITLE_METHOD_NAME,
7871 session_resume: SESSION_RESUME_METHOD_NAME,
7872 session_close: SESSION_CLOSE_METHOD_NAME,
7873 tool_call_cancel: TOOL_CALL_CANCEL_METHOD_NAME,
7874 terminal_cancel: TERMINAL_CANCEL_METHOD_NAME,
7875 auth_logout: AUTH_LOGOUT_METHOD_NAME,
7876 #[cfg(feature = "unstable_auth_status")]
7877 auth_status: AUTH_STATUS_METHOD_NAME,
7878};
7879
7880pub(crate) const INITIALIZE_METHOD_NAME: &str = "initialize";
7882pub(crate) const AUTH_LOGIN_METHOD_NAME: &str = "auth/login";
7884#[cfg(feature = "unstable_llm_providers")]
7886pub(crate) const PROVIDERS_LIST_METHOD_NAME: &str = "providers/list";
7887#[cfg(feature = "unstable_llm_providers")]
7889pub(crate) const PROVIDERS_SET_METHOD_NAME: &str = "providers/set";
7890#[cfg(feature = "unstable_llm_providers")]
7892pub(crate) const PROVIDERS_DISABLE_METHOD_NAME: &str = "providers/disable";
7893pub(crate) const SESSION_NEW_METHOD_NAME: &str = "session/new";
7895pub(crate) const SESSION_SET_CONFIG_OPTION_METHOD_NAME: &str = "session/set_config_option";
7897pub(crate) const SESSION_PROMPT_METHOD_NAME: &str = "session/prompt";
7899pub(crate) const SESSION_CANCEL_METHOD_NAME: &str = "session/cancel";
7901pub(crate) const SESSION_LIST_METHOD_NAME: &str = "session/list";
7903pub(crate) const SESSION_DELETE_METHOD_NAME: &str = "session/delete";
7905#[cfg(feature = "unstable_session_fork")]
7907pub(crate) const SESSION_FORK_METHOD_NAME: &str = "session/fork";
7908#[cfg(feature = "unstable_session_archive")]
7910pub(crate) const SESSION_ARCHIVE_METHOD_NAME: &str = "session/archive";
7911#[cfg(feature = "unstable_session_archive")]
7913pub(crate) const SESSION_UNARCHIVE_METHOD_NAME: &str = "session/unarchive";
7914#[cfg(feature = "unstable_session_status")]
7916pub(crate) const SESSION_STATUS_METHOD_NAME: &str = "session/status";
7917#[cfg(feature = "unstable_session_options")]
7919pub(crate) const SESSION_OPTIONS_METHOD_NAME: &str = "session/options";
7920#[cfg(feature = "unstable_session_set_title")]
7922pub(crate) const SESSION_SET_TITLE_METHOD_NAME: &str = "session/set_title";
7923pub(crate) const SESSION_RESUME_METHOD_NAME: &str = "session/resume";
7925pub(crate) const SESSION_CLOSE_METHOD_NAME: &str = "session/close";
7927pub(crate) const TOOL_CALL_CANCEL_METHOD_NAME: &str = "tool_call/cancel";
7929pub(crate) const TERMINAL_CANCEL_METHOD_NAME: &str = "terminal/cancel";
7931pub(crate) const AUTH_LOGOUT_METHOD_NAME: &str = "auth/logout";
7933#[cfg(feature = "unstable_auth_status")]
7935pub(crate) const AUTH_STATUS_METHOD_NAME: &str = "auth/status";
7936
7937#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7944#[derive(Clone, Debug, Serialize, Deserialize)]
7945#[serde(untagged)]
7946#[cfg_attr(feature = "schemars", schemars(inline))]
7947#[non_exhaustive]
7948pub enum ClientRequest {
7949 InitializeRequest(Box<InitializeRequest>),
7963 LoginAuthRequest(Box<LoginAuthRequest>),
7978 #[cfg(feature = "unstable_llm_providers")]
7984 ListProvidersRequest(Box<ListProvidersRequest>),
7985 #[cfg(feature = "unstable_llm_providers")]
7991 SetProviderRequest(Box<SetProviderRequest>),
7992 #[cfg(feature = "unstable_llm_providers")]
7998 DisableProviderRequest(Box<DisableProviderRequest>),
7999 LogoutAuthRequest(Box<LogoutAuthRequest>),
8009 #[cfg(feature = "unstable_auth_status")]
8018 AuthStatusRequest(Box<AuthStatusRequest>),
8019 NewSessionRequest(Box<NewSessionRequest>),
8032 ListSessionsRequest(Box<ListSessionsRequest>),
8036 DeleteSessionRequest(Box<DeleteSessionRequest>),
8040 #[cfg(feature = "unstable_session_fork")]
8041 ForkSessionRequest(Box<ForkSessionRequest>),
8057 #[cfg(feature = "unstable_session_archive")]
8058 ArchiveSessionRequest(Box<ArchiveSessionRequest>),
8066 #[cfg(feature = "unstable_session_archive")]
8067 UnarchiveSessionRequest(Box<UnarchiveSessionRequest>),
8075 #[cfg(feature = "unstable_session_status")]
8076 SessionStatusRequest(Box<SessionStatusRequest>),
8084 #[cfg(feature = "unstable_session_options")]
8085 SessionOptionsRequest(Box<SessionOptionsRequest>),
8093 #[cfg(feature = "unstable_session_set_title")]
8094 SetSessionTitleRequest(Box<SetSessionTitleRequest>),
8105 ResumeSessionRequest(Box<ResumeSessionRequest>),
8111 CloseSessionRequest(Box<CloseSessionRequest>),
8116 CancelToolCallRequest(Box<CancelToolCallRequest>),
8122 CancelTerminalRequest(Box<CancelTerminalRequest>),
8128 SetSessionConfigOptionRequest(Box<SetSessionConfigOptionRequest>),
8130 PromptRequest(Box<PromptRequest>),
8152 ExtMethodRequest(Box<ExtRequest>),
8158}
8159
8160impl_request_dispatch! {
8161 ClientRequest => AgentResponse {
8162 InitializeRequest => InitializeResponse: AGENT_METHOD_NAMES.initialize,
8163 LoginAuthRequest => LoginAuthResponse: AGENT_METHOD_NAMES.auth_login,
8164 #[cfg(feature = "unstable_llm_providers")]
8165 ListProvidersRequest => ListProvidersResponse: AGENT_METHOD_NAMES.providers_list,
8166 #[cfg(feature = "unstable_llm_providers")]
8167 SetProviderRequest => SetProviderResponse: AGENT_METHOD_NAMES.providers_set,
8168 #[cfg(feature = "unstable_llm_providers")]
8169 DisableProviderRequest => DisableProviderResponse: AGENT_METHOD_NAMES.providers_disable,
8170 LogoutAuthRequest => LogoutAuthResponse: AGENT_METHOD_NAMES.auth_logout,
8171 #[cfg(feature = "unstable_auth_status")]
8172 AuthStatusRequest => AuthStatusResponse: AGENT_METHOD_NAMES.auth_status,
8173 NewSessionRequest => NewSessionResponse: AGENT_METHOD_NAMES.session_new,
8174 ListSessionsRequest => ListSessionsResponse: AGENT_METHOD_NAMES.session_list,
8175 DeleteSessionRequest => DeleteSessionResponse: AGENT_METHOD_NAMES.session_delete,
8176 #[cfg(feature = "unstable_session_fork")]
8177 ForkSessionRequest => ForkSessionResponse: AGENT_METHOD_NAMES.session_fork,
8178 #[cfg(feature = "unstable_session_archive")]
8179 ArchiveSessionRequest => ArchiveSessionResponse: AGENT_METHOD_NAMES.session_archive,
8180 #[cfg(feature = "unstable_session_archive")]
8181 UnarchiveSessionRequest => UnarchiveSessionResponse: AGENT_METHOD_NAMES.session_unarchive,
8182 #[cfg(feature = "unstable_session_status")]
8183 SessionStatusRequest => SessionStatusResponse: AGENT_METHOD_NAMES.session_status,
8184 #[cfg(feature = "unstable_session_options")]
8185 SessionOptionsRequest => SessionOptionsResponse: AGENT_METHOD_NAMES.session_options,
8186 #[cfg(feature = "unstable_session_set_title")]
8187 SetSessionTitleRequest => SetSessionTitleResponse: AGENT_METHOD_NAMES.session_set_title,
8188 ResumeSessionRequest => ResumeSessionResponse: AGENT_METHOD_NAMES.session_resume,
8189 CloseSessionRequest => CloseSessionResponse: AGENT_METHOD_NAMES.session_close,
8190 CancelToolCallRequest => CancelToolCallResponse: AGENT_METHOD_NAMES.tool_call_cancel,
8191 CancelTerminalRequest => CancelTerminalResponse: AGENT_METHOD_NAMES.terminal_cancel,
8192 SetSessionConfigOptionRequest => SetSessionConfigOptionResponse: AGENT_METHOD_NAMES.session_set_config_option,
8193 PromptRequest => PromptResponse: AGENT_METHOD_NAMES.session_prompt,
8194 }
8195 extension ExtMethodRequest(Box<ExtRequest>) => ExtMethodResponse;
8196}
8197
8198#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
8205#[derive(Clone, Debug, Serialize, Deserialize)]
8206#[serde(untagged)]
8207#[cfg_attr(feature = "schemars", schemars(inline))]
8208#[non_exhaustive]
8209pub enum AgentResponse {
8210 InitializeResponse(Box<InitializeResponse>),
8212 LoginAuthResponse(#[serde(default)] Box<LoginAuthResponse>),
8214 #[cfg(feature = "unstable_llm_providers")]
8216 ListProvidersResponse(Box<ListProvidersResponse>),
8217 #[cfg(feature = "unstable_llm_providers")]
8219 SetProviderResponse(#[serde(default)] Box<SetProviderResponse>),
8220 #[cfg(feature = "unstable_llm_providers")]
8222 DisableProviderResponse(#[serde(default)] Box<DisableProviderResponse>),
8223 LogoutAuthResponse(#[serde(default)] Box<LogoutAuthResponse>),
8225 #[cfg(feature = "unstable_auth_status")]
8227 AuthStatusResponse(Box<AuthStatusResponse>),
8228 NewSessionResponse(Box<NewSessionResponse>),
8230 ListSessionsResponse(Box<ListSessionsResponse>),
8232 DeleteSessionResponse(#[serde(default)] Box<DeleteSessionResponse>),
8234 #[cfg(feature = "unstable_session_fork")]
8236 ForkSessionResponse(Box<ForkSessionResponse>),
8237 #[cfg(feature = "unstable_session_archive")]
8239 ArchiveSessionResponse(#[serde(default)] Box<ArchiveSessionResponse>),
8240 #[cfg(feature = "unstable_session_archive")]
8242 UnarchiveSessionResponse(#[serde(default)] Box<UnarchiveSessionResponse>),
8243 #[cfg(feature = "unstable_session_status")]
8245 SessionStatusResponse(Box<SessionStatusResponse>),
8246 #[cfg(feature = "unstable_session_options")]
8248 SessionOptionsResponse(#[serde(default)] Box<SessionOptionsResponse>),
8249 #[cfg(feature = "unstable_session_set_title")]
8251 SetSessionTitleResponse(Box<SetSessionTitleResponse>),
8252 ResumeSessionResponse(#[serde(default)] Box<ResumeSessionResponse>),
8254 CloseSessionResponse(#[serde(default)] Box<CloseSessionResponse>),
8256 CancelToolCallResponse(#[serde(default)] Box<CancelToolCallResponse>),
8258 CancelTerminalResponse(#[serde(default)] Box<CancelTerminalResponse>),
8260 SetSessionConfigOptionResponse(Box<SetSessionConfigOptionResponse>),
8262 PromptResponse(Box<PromptResponse>),
8264 ExtMethodResponse(Box<ExtResponse>),
8266}
8267
8268#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
8275#[derive(Clone, Debug, Serialize, Deserialize)]
8276#[serde(untagged)]
8277#[cfg_attr(feature = "schemars", schemars(inline))]
8278#[non_exhaustive]
8279pub enum ClientNotification {
8280 CancelSessionNotification(Box<CancelSessionNotification>),
8310 #[cfg(feature = "unstable_mcp_over_acp")]
8316 MessageMcpNotification(Box<MessageMcpNotification>),
8317 ExtNotification(Box<ExtNotification>),
8323}
8324
8325impl_message_dispatch! {
8326 ClientNotification {
8327 CancelSessionNotification => AGENT_METHOD_NAMES.session_cancel,
8328 #[cfg(feature = "unstable_mcp_over_acp")]
8329 MessageMcpNotification => AGENT_METHOD_NAMES.mcp_message,
8330 }
8331 extension ExtNotification(Box<ExtNotification>);
8332}
8333
8334#[cfg(test)]
8335mod test_serialization {
8336 use std::path::PathBuf;
8337
8338 use super::*;
8339 use serde_json::json;
8340
8341 fn test_meta() -> Meta {
8342 json!({ "source": "test" }).as_object().unwrap().clone()
8343 }
8344
8345 #[test]
8346 fn list_sessions_cursor_and_session_directories_are_strict() {
8347 for cursor in [json!(null), json!("next")] {
8348 let response = json!({ "sessions": [], "nextCursor": cursor });
8349 serde_json::from_value::<ListSessionsResponse>(response).unwrap();
8350 }
8351 let malformed = json!({ "sessions": [], "nextCursor": 42 });
8352 assert!(serde_json::from_value::<ListSessionsResponse>(malformed).is_err());
8353
8354 let session = |dirs: serde_json::Value| json!({ "sessionId": "s", "cwd": "/w", "additionalDirectories": dirs });
8355 let info: SessionInfo = serde_json::from_value(session(json!(null))).unwrap();
8356 assert_eq!(info.additional_directories, Vec::<AbsolutePath>::new());
8357 for bad in [json!(["/a", 42]), json!("/a")] {
8358 assert!(serde_json::from_value::<SessionInfo>(session(bad)).is_err());
8359 }
8360 let response = json!({ "sessions": [session(json!(["/a", 42]))] });
8362 let response: ListSessionsResponse = serde_json::from_value(response).unwrap();
8363 assert_eq!(response.sessions, Vec::<SessionInfo>::new());
8364 }
8365
8366 #[test]
8367 fn other_fallbacks_preserve_optional_fields_verbatim() {
8368 let valid = json!({ "type": "_custom", "methodId": "m", "name": "M",
8369 "description": "d", "_meta": { "k": 1 } });
8370 let method: AuthMethod = serde_json::from_value(valid.clone()).unwrap();
8371 assert_eq!(method.description(), Some("d"));
8372 assert_eq!(
8373 method.meta(),
8374 Some(&json!({ "k": 1 }).as_object().unwrap().clone())
8375 );
8376 assert_eq!(serde_json::to_value(&method).unwrap(), valid);
8377
8378 let malformed = json!({ "type": "_custom", "methodId": "m", "name": "M",
8380 "description": 42, "_meta": "bad", "extra": true });
8381 let method: AuthMethod = serde_json::from_value(malformed.clone()).unwrap();
8382 assert_eq!(method.description(), None);
8383 assert_eq!(method.meta(), None);
8384 assert_eq!(serde_json::to_value(&method).unwrap(), malformed);
8385
8386 let replay = json!({ "type": "_custom", "_meta": "bad", "cursor": 3 });
8387 let decoded: ReplayFrom = serde_json::from_value(replay.clone()).unwrap();
8388 assert_eq!(serde_json::to_value(&decoded).unwrap(), replay);
8389 }
8390
8391 fn serialized_meta_key_count(value: &impl serde::Serialize) -> usize {
8392 serde_json::to_string(value)
8393 .unwrap()
8394 .matches("\"_meta\"")
8395 .count()
8396 }
8397
8398 #[test]
8399 fn prompt_response_without_metadata_round_trips() {
8400 let response = PromptResponse::new(MessageId::new("message-1"));
8401 let serialized = serde_json::to_value(&response).unwrap();
8402 assert_eq!(serialized, json!({ "messageId": "message-1" }));
8403 assert_eq!(
8404 serde_json::from_value::<PromptResponse>(serialized).unwrap(),
8405 response
8406 );
8407 assert_eq!(
8408 serde_json::from_value::<PromptResponse>(json!({
8409 "messageId": "message-1",
8410 "_meta": null
8411 }))
8412 .unwrap(),
8413 response
8414 );
8415 }
8416
8417 #[test]
8418 fn prompt_response_requires_message_id_and_preserves_metadata_tolerance() {
8419 let response = PromptResponse::new("message-1").meta(test_meta());
8420 let serialized = serde_json::to_value(&response).unwrap();
8421 assert_eq!(
8422 serialized,
8423 json!({
8424 "messageId": "message-1",
8425 "_meta": { "source": "test" }
8426 })
8427 );
8428
8429 let deserialized: PromptResponse = serde_json::from_value(serialized).unwrap();
8430 assert_eq!(deserialized.message_id, MessageId::new("message-1"));
8431 assert_eq!(deserialized.meta, Some(test_meta()));
8432
8433 let malformed_meta: PromptResponse = serde_json::from_value(json!({
8434 "messageId": "message-2",
8435 "_meta": false
8436 }))
8437 .unwrap();
8438 assert_eq!(malformed_meta.message_id, MessageId::new("message-2"));
8439 assert_eq!(malformed_meta.meta, None);
8440
8441 for invalid in [
8442 json!({}),
8443 json!({ "messageId": null }),
8444 json!({ "messageId": 1 }),
8445 json!({ "messageId": false }),
8446 json!({ "messageId": {} }),
8447 json!({ "messageId": [] }),
8448 ] {
8449 assert!(
8450 serde_json::from_value::<PromptResponse>(invalid).is_err(),
8451 "missing, null, and non-string message IDs must be rejected"
8452 );
8453 }
8454 }
8455
8456 #[cfg(feature = "schemars")]
8457 #[test]
8458 fn prompt_response_schema_requires_non_null_string_message_id_reference() {
8459 let schema = serde_json::to_value(schemars::schema_for!(PromptResponse)).unwrap();
8460
8461 assert_eq!(schema["required"], json!(["messageId"]));
8462 assert_eq!(
8463 schema["properties"]["messageId"]["$ref"],
8464 "#/$defs/MessageId"
8465 );
8466 assert_eq!(schema["$defs"]["MessageId"]["type"], "string");
8467 }
8468
8469 #[test]
8470 fn test_initialize_capabilities_default_on_malformed_values() {
8471 let request: InitializeRequest = serde_json::from_value(json!({
8472 "protocolVersion": 2,
8473 "capabilities": false,
8474 "info": {
8475 "name": "client",
8476 "version": "1.0.0"
8477 }
8478 }))
8479 .unwrap();
8480 assert_eq!(request.capabilities, ClientCapabilities::default());
8481
8482 let response: InitializeResponse = serde_json::from_value(json!({
8483 "protocolVersion": 2,
8484 "capabilities": false,
8485 "info": {
8486 "name": "agent",
8487 "version": "1.0.0"
8488 }
8489 }))
8490 .unwrap();
8491 assert_eq!(response.capabilities, AgentCapabilities::default());
8492 }
8493
8494 #[test]
8495 fn test_agent_capabilities_default_on_malformed_values() {
8496 let capabilities: AgentCapabilities = serde_json::from_value(json!({
8497 "session": false,
8498 "auth": false
8499 }))
8500 .unwrap();
8501
8502 assert!(capabilities.session.is_none());
8503 assert_eq!(capabilities.auth, None);
8504 }
8505
8506 #[test]
8507 fn test_mcp_server_stdio_serialization() {
8508 let server = McpServer::Stdio(
8509 McpServerStdio::new("test-server", "/usr/bin/server")
8510 .args(vec!["--port".to_string(), "3000".to_string()])
8511 .env(vec![EnvVariable::new("API_KEY", "secret123")]),
8512 );
8513
8514 let json = serde_json::to_value(&server).unwrap();
8515 assert_eq!(
8516 json,
8517 json!({
8518 "type": "stdio",
8519 "name": "test-server",
8520 "command": "/usr/bin/server",
8521 "args": ["--port", "3000"],
8522 "env": [
8523 {
8524 "name": "API_KEY",
8525 "value": "secret123"
8526 }
8527 ]
8528 })
8529 );
8530
8531 let deserialized: McpServer = serde_json::from_value(json).unwrap();
8532 match deserialized {
8533 McpServer::Stdio(McpServerStdio {
8534 name,
8535 command,
8536 args,
8537 env,
8538 meta: _,
8539 }) => {
8540 assert_eq!(name, "test-server");
8541 assert_eq!(command, AbsolutePath::new("/usr/bin/server"));
8542 assert_eq!(args, vec!["--port", "3000"]);
8543 assert_eq!(env.len(), 1);
8544 assert_eq!(env[0].name, "API_KEY");
8545 assert_eq!(env[0].value, "secret123");
8546 }
8547 _ => panic!("Expected Stdio variant"),
8548 }
8549 }
8550
8551 #[test]
8552 fn test_mcp_server_empty_arrays_are_optional() {
8553 let stdio = McpServer::Stdio(McpServerStdio::new("test-server", "/usr/bin/server"));
8554 assert_eq!(
8555 serde_json::to_value(&stdio).unwrap(),
8556 json!({
8557 "type": "stdio",
8558 "name": "test-server",
8559 "command": "/usr/bin/server"
8560 })
8561 );
8562
8563 let McpServer::Stdio(McpServerStdio { args, env, .. }) =
8564 serde_json::from_value::<McpServer>(json!({
8565 "type": "stdio",
8566 "name": "test-server",
8567 "command": "/usr/bin/server"
8568 }))
8569 .unwrap()
8570 else {
8571 panic!("Expected Stdio variant");
8572 };
8573 assert_eq!(args, Vec::<String>::new());
8574 assert_eq!(env, []);
8575
8576 let http = McpServer::Http(McpServerHttp::new("http-server", "https://api.example.com"));
8577 assert_eq!(
8578 serde_json::to_value(&http).unwrap(),
8579 json!({
8580 "type": "http",
8581 "name": "http-server",
8582 "url": "https://api.example.com"
8583 })
8584 );
8585
8586 let McpServer::Http(McpServerHttp { headers, .. }) =
8587 serde_json::from_value::<McpServer>(json!({
8588 "type": "http",
8589 "name": "http-server",
8590 "url": "https://api.example.com"
8591 }))
8592 .unwrap()
8593 else {
8594 panic!("Expected Http variant");
8595 };
8596 assert_eq!(headers, []);
8597 }
8598
8599 #[test]
8600 fn test_mcp_server_unknown_transport_serialization() {
8601 let json = json!({
8602 "type": "websocket",
8603 "name": "future-server",
8604 "url": "wss://example.com/mcp",
8605 "protocolVersion": "2026-01-01"
8606 });
8607
8608 let deserialized: McpServer = serde_json::from_value(json.clone()).unwrap();
8609 let McpServer::Other(OtherMcpServer { type_, fields }) = &deserialized else {
8610 panic!("Expected Other variant");
8611 };
8612
8613 assert_eq!(type_, "websocket");
8614 assert_eq!(fields["name"], "future-server");
8615 assert_eq!(fields["url"], "wss://example.com/mcp");
8616 assert_eq!(fields["protocolVersion"], "2026-01-01");
8617 assert_eq!(serde_json::to_value(&deserialized).unwrap(), json);
8618 }
8619
8620 #[test]
8621 fn test_mcp_server_stdio_requires_type() {
8622 let result = serde_json::from_value::<McpServer>(json!({
8623 "name": "test-server",
8624 "command": "/usr/bin/server",
8625 "args": [],
8626 "env": []
8627 }));
8628
8629 assert!(result.is_err());
8630 }
8631
8632 #[test]
8633 fn test_mcp_server_unknown_does_not_hide_malformed_known_transport() {
8634 let result = serde_json::from_value::<McpServer>(json!({
8635 "type": "stdio",
8636 "name": "test-server",
8637 "args": [],
8638 "env": []
8639 }));
8640
8641 assert!(result.is_err());
8642 }
8643
8644 #[test]
8645 fn test_mcp_server_http_serialization() {
8646 let server = McpServer::Http(
8647 McpServerHttp::new("http-server", "https://api.example.com").headers(vec![
8648 HttpHeader::new("Authorization", "Bearer token123"),
8649 HttpHeader::new("Content-Type", "application/json"),
8650 ]),
8651 );
8652
8653 let json = serde_json::to_value(&server).unwrap();
8654 assert_eq!(
8655 json,
8656 json!({
8657 "type": "http",
8658 "name": "http-server",
8659 "url": "https://api.example.com",
8660 "headers": [
8661 {
8662 "name": "Authorization",
8663 "value": "Bearer token123"
8664 },
8665 {
8666 "name": "Content-Type",
8667 "value": "application/json"
8668 }
8669 ]
8670 })
8671 );
8672
8673 let deserialized: McpServer = serde_json::from_value(json).unwrap();
8674 match deserialized {
8675 McpServer::Http(McpServerHttp {
8676 name,
8677 url,
8678 headers,
8679 meta: _,
8680 }) => {
8681 assert_eq!(name, "http-server");
8682 assert_eq!(url, "https://api.example.com");
8683 assert_eq!(headers.len(), 2);
8684 assert_eq!(headers[0].name, "Authorization");
8685 assert_eq!(headers[0].value, "Bearer token123");
8686 assert_eq!(headers[1].name, "Content-Type");
8687 assert_eq!(headers[1].value, "application/json");
8688 }
8689 _ => panic!("Expected Http variant"),
8690 }
8691 }
8692
8693 #[cfg(feature = "schemars")]
8694 #[test]
8695 fn mcp_server_http_schema_marks_url_as_uri() {
8696 let schema = serde_json::to_value(schemars::schema_for!(McpServerHttp)).unwrap();
8697
8698 assert_eq!(schema["properties"]["url"]["format"], "uri");
8699 }
8700
8701 #[cfg(feature = "unstable_mcp_over_acp")]
8702 #[test]
8703 fn test_client_mcp_message_method_names() {
8704 use serde_json::json;
8705
8706 assert_eq!(AGENT_METHOD_NAMES.mcp_message, "mcp/message");
8707
8708 let notification =
8709 MessageMcpNotification::new("server-1", "req-1", "notifications/progress");
8710 assert_eq!(
8711 ClientNotification::MessageMcpNotification(Box::new(notification.clone())).method(),
8712 "mcp/message"
8713 );
8714 assert_eq!(
8715 serde_json::to_value(notification).unwrap(),
8716 json!({
8717 "serverId": "server-1",
8718 "requestId": "req-1",
8719 "method": "notifications/progress"
8720 })
8721 );
8722 let notification: MessageMcpNotification = serde_json::from_value(json!({
8723 "serverId": "server-1", "requestId": "req-1", "method": "notifications/progress",
8724 "params": null, "_meta": null
8725 }))
8726 .unwrap();
8727 assert_eq!(notification.params, None);
8728 assert_eq!(notification.meta, None);
8729 for key in ["serverId", "requestId", "method"] {
8730 let mut value = json!({"serverId":"server-1", "requestId":"req-1", "method":"notifications/progress"});
8731 value.as_object_mut().unwrap().remove(key);
8732 assert!(serde_json::from_value::<MessageMcpNotification>(value).is_err());
8733 }
8734 }
8735
8736 #[test]
8737 fn test_auth_method_names() {
8738 assert_eq!(AGENT_METHOD_NAMES.auth_login, "auth/login");
8739 assert_eq!(AGENT_METHOD_NAMES.auth_logout, "auth/logout");
8740
8741 assert_eq!(
8742 ClientRequest::LoginAuthRequest(Box::new(LoginAuthRequest::new("agent-login")))
8743 .method(),
8744 "auth/login"
8745 );
8746 assert_eq!(
8747 ClientRequest::LogoutAuthRequest(Box::new(LogoutAuthRequest::new())).method(),
8748 "auth/logout"
8749 );
8750 }
8751
8752 #[test]
8753 fn test_session_config_option_category_known_variants() {
8754 assert_eq!(
8756 serde_json::to_value(&SessionConfigOptionCategory::Mode).unwrap(),
8757 json!("mode")
8758 );
8759 assert_eq!(
8760 serde_json::to_value(&SessionConfigOptionCategory::Model).unwrap(),
8761 json!("model")
8762 );
8763 assert_eq!(
8764 serde_json::to_value(&SessionConfigOptionCategory::ModelConfig).unwrap(),
8765 json!("model_config")
8766 );
8767 #[cfg(feature = "unstable_speed_config_category")]
8768 assert_eq!(
8769 serde_json::to_value(&SessionConfigOptionCategory::Speed).unwrap(),
8770 json!("speed")
8771 );
8772 assert_eq!(
8773 serde_json::to_value(&SessionConfigOptionCategory::ThoughtLevel).unwrap(),
8774 json!("thought_level")
8775 );
8776
8777 assert_eq!(
8779 serde_json::from_str::<SessionConfigOptionCategory>("\"mode\"").unwrap(),
8780 SessionConfigOptionCategory::Mode
8781 );
8782 assert_eq!(
8783 serde_json::from_str::<SessionConfigOptionCategory>("\"model\"").unwrap(),
8784 SessionConfigOptionCategory::Model
8785 );
8786 assert_eq!(
8787 serde_json::from_str::<SessionConfigOptionCategory>("\"model_config\"").unwrap(),
8788 SessionConfigOptionCategory::ModelConfig
8789 );
8790 #[cfg(feature = "unstable_speed_config_category")]
8791 assert_eq!(
8792 serde_json::from_str::<SessionConfigOptionCategory>("\"speed\"").unwrap(),
8793 SessionConfigOptionCategory::Speed
8794 );
8795 assert_eq!(
8796 serde_json::from_str::<SessionConfigOptionCategory>("\"thought_level\"").unwrap(),
8797 SessionConfigOptionCategory::ThoughtLevel
8798 );
8799 }
8800
8801 #[test]
8802 fn test_session_config_option_category_unknown_variants() {
8803 let unknown: SessionConfigOptionCategory =
8805 serde_json::from_str("\"some_future_category\"").unwrap();
8806 assert_eq!(
8807 unknown,
8808 SessionConfigOptionCategory::Other("some_future_category".to_string())
8809 );
8810
8811 let json = serde_json::to_value(&unknown).unwrap();
8813 assert_eq!(json, json!("some_future_category"));
8814 }
8815
8816 #[cfg(not(feature = "unstable_speed_config_category"))]
8817 #[test]
8818 fn test_session_config_option_speed_is_unknown_without_feature() {
8819 let unknown: SessionConfigOptionCategory = serde_json::from_str("\"speed\"").unwrap();
8820 assert_eq!(
8821 unknown,
8822 SessionConfigOptionCategory::Other("speed".to_string())
8823 );
8824 }
8825
8826 #[test]
8827 fn test_session_config_option_category_custom_categories() {
8828 let custom: SessionConfigOptionCategory =
8830 serde_json::from_str("\"_my_custom_category\"").unwrap();
8831 assert_eq!(
8832 custom,
8833 SessionConfigOptionCategory::Other("_my_custom_category".to_string())
8834 );
8835
8836 let json = serde_json::to_value(&custom).unwrap();
8838 assert_eq!(json, json!("_my_custom_category"));
8839
8840 let deserialized: SessionConfigOptionCategory = serde_json::from_value(json).unwrap();
8842 assert_eq!(
8843 deserialized,
8844 SessionConfigOptionCategory::Other("_my_custom_category".to_string()),
8845 );
8846 }
8847
8848 fn test_config_option() -> SessionConfigOption {
8849 SessionConfigOption::select(
8850 "mode",
8851 "Mode",
8852 "ask",
8853 vec![SessionConfigSelectOption::new("ask", "Ask")],
8854 )
8855 }
8856
8857 #[test]
8858 fn test_session_response_initial_state_default_empty_and_skip_serializing() {
8859 assert_eq!(
8860 serde_json::to_value(NewSessionResponse::new("sess")).unwrap(),
8861 json!({ "sessionId": "sess" })
8862 );
8863 assert_eq!(
8864 serde_json::to_value(ResumeSessionResponse::new()).unwrap(),
8865 json!({})
8866 );
8867 #[cfg(feature = "unstable_session_fork")]
8868 assert_eq!(
8869 serde_json::to_value(ForkSessionResponse::new("fork")).unwrap(),
8870 json!({ "sessionId": "fork" })
8871 );
8872
8873 let json = serde_json::to_value(
8874 NewSessionResponse::new("sess").config_options(vec![test_config_option()]),
8875 )
8876 .unwrap();
8877 assert_eq!(json["configOptions"].as_array().unwrap().len(), 1);
8878 }
8879
8880 #[test]
8881 fn test_session_response_config_options_deserialize_missing_null_and_invalid() {
8882 let missing: NewSessionResponse =
8883 serde_json::from_value(json!({ "sessionId": "sess" })).unwrap();
8884 assert_eq!(missing.config_options, []);
8885
8886 let null: NewSessionResponse = serde_json::from_value(json!({
8887 "sessionId": "sess",
8888 "configOptions": null
8889 }))
8890 .unwrap();
8891 assert_eq!(null.config_options, []);
8892
8893 let wrong_shape: NewSessionResponse = serde_json::from_value(json!({
8894 "sessionId": "sess",
8895 "configOptions": "oops"
8896 }))
8897 .unwrap();
8898 assert_eq!(wrong_shape.config_options, []);
8899
8900 let valid_option = serde_json::to_value(test_config_option()).unwrap();
8901 let mixed: NewSessionResponse = serde_json::from_value(json!({
8902 "sessionId": "sess",
8903 "configOptions": ["oops", valid_option]
8904 }))
8905 .unwrap();
8906 assert_eq!(mixed.config_options.len(), 1);
8907
8908 let resume: ResumeSessionResponse = serde_json::from_value(json!({})).unwrap();
8909 assert_eq!(resume.config_options, []);
8910 #[cfg(feature = "unstable_session_fork")]
8911 {
8912 let fork: ForkSessionResponse =
8913 serde_json::from_value(json!({ "sessionId": "fork" })).unwrap();
8914 assert_eq!(fork.config_options, []);
8915 }
8916 }
8917
8918 #[test]
8919 fn test_session_response_available_commands_roundtrip_with_config_options() {
8920 use super::super::{AvailableCommandInput, Command, TextCommandInput};
8921
8922 let commands = vec![
8923 AvailableCommand::Command(
8924 Command::new("web", "Search the web")
8925 .input(AvailableCommandInput::Text(TextCommandInput::new("Query"))),
8926 ),
8927 AvailableCommand::Command(Command::new("test", "Run project tests")),
8928 ];
8929 let mut expected = json!({
8930 "sessionId": "sess",
8931 "configOptions": [test_config_option()],
8932 "availableCommands": [
8933 {
8934 "type": "command",
8935 "name": "web",
8936 "description": "Search the web",
8937 "input": { "type": "text", "hint": "Query" }
8938 },
8939 { "type": "command", "name": "test", "description": "Run project tests" }
8940 ]
8941 });
8942
8943 let new = NewSessionResponse::new("sess")
8944 .config_options(vec![test_config_option()])
8945 .available_commands(commands.clone());
8946 assert_eq!(serde_json::to_value(&new).unwrap(), expected);
8947 assert_eq!(
8948 serde_json::from_value::<NewSessionResponse>(expected.clone()).unwrap(),
8949 new
8950 );
8951
8952 expected.as_object_mut().unwrap().remove("sessionId");
8953 let resume = ResumeSessionResponse::new()
8954 .config_options(vec![test_config_option()])
8955 .available_commands(commands.clone());
8956 assert_eq!(serde_json::to_value(&resume).unwrap(), expected);
8957 assert_eq!(
8958 serde_json::from_value::<ResumeSessionResponse>(expected.clone()).unwrap(),
8959 resume
8960 );
8961
8962 #[cfg(feature = "unstable_session_fork")]
8963 {
8964 expected["sessionId"] = json!("fork");
8965 let fork = ForkSessionResponse::new("fork")
8966 .config_options(vec![test_config_option()])
8967 .available_commands(commands);
8968 assert_eq!(serde_json::to_value(&fork).unwrap(), expected);
8969 assert_eq!(
8970 serde_json::from_value::<ForkSessionResponse>(expected).unwrap(),
8971 fork
8972 );
8973 }
8974 }
8975
8976 #[test]
8977 fn test_session_response_available_commands_deserialize_missing_null_and_invalid() {
8978 let command =
8979 AvailableCommand::Command(super::super::Command::new("test", "Run project tests"));
8980 let config_options = vec![test_config_option()];
8981
8982 for (commands, expected) in [
8983 (None, vec![]),
8984 (Some(json!(null)), vec![]),
8985 (Some(json!([])), vec![]),
8986 (Some(json!("oops")), vec![]),
8987 (Some(json!({})), vec![]),
8988 (Some(json!([null, {}, { "name": "invalid" }])), vec![]),
8989 (
8990 Some(json!([{ "name": "test", "description": "Run project tests" }])),
8991 vec![],
8992 ),
8993 (
8994 Some(json!([null, command, { "name": "invalid" }])),
8995 vec![command.clone()],
8996 ),
8997 ] {
8998 let mut value = json!({
8999 "sessionId": "sess",
9000 "configOptions": config_options
9001 });
9002 if let Some(commands) = commands {
9003 value["availableCommands"] = commands;
9004 }
9005
9006 let new: NewSessionResponse = serde_json::from_value(value.clone()).unwrap();
9007 assert_eq!(new.available_commands, expected);
9008 assert_eq!(new.config_options, config_options);
9009
9010 #[cfg(feature = "unstable_session_fork")]
9011 {
9012 let fork: ForkSessionResponse = serde_json::from_value(value.clone()).unwrap();
9013 assert_eq!(fork.available_commands, expected);
9014 assert_eq!(fork.config_options, config_options);
9015 }
9016
9017 value.as_object_mut().unwrap().remove("sessionId");
9018 let resume: ResumeSessionResponse = serde_json::from_value(value).unwrap();
9019 assert_eq!(resume.available_commands, expected);
9020 assert_eq!(resume.config_options, config_options);
9021 }
9022
9023 let resume: ResumeSessionResponse = serde_json::from_value(json!(null)).unwrap();
9024 assert_eq!(resume.available_commands, []);
9025 }
9026
9027 #[test]
9028 fn test_resume_session_replay_from_serialization() {
9029 assert_eq!(
9030 serde_json::to_value(ResumeSessionRequest::new(
9031 "sess_abc123",
9032 "/home/user/project"
9033 ))
9034 .unwrap(),
9035 json!({
9036 "sessionId": "sess_abc123",
9037 "cwd": "/home/user/project"
9038 })
9039 );
9040 assert_eq!(
9041 serde_json::to_value(
9042 ResumeSessionRequest::new("sess_abc123", "/home/user/project")
9043 .replay_from(ReplayFrom::from(ReplayFromStart::new()))
9044 )
9045 .unwrap(),
9046 json!({
9047 "sessionId": "sess_abc123",
9048 "cwd": "/home/user/project",
9049 "replayFrom": {
9050 "type": "start"
9051 }
9052 })
9053 );
9054
9055 let replay: ResumeSessionRequest = serde_json::from_value(json!({
9056 "sessionId": "sess_abc123",
9057 "cwd": "/home/user/project",
9058 "replayFrom": {
9059 "type": "start"
9060 }
9061 }))
9062 .unwrap();
9063 assert!(matches!(replay.replay_from, Some(ReplayFrom::Start(_))));
9064
9065 let none: ResumeSessionRequest = serde_json::from_value(json!({
9066 "sessionId": "sess_abc123",
9067 "cwd": "/home/user/project",
9068 "replayFrom": null
9069 }))
9070 .unwrap();
9071 assert!(none.replay_from.is_none());
9072 }
9073
9074 #[test]
9075 fn test_auth_method_agent_serialization() {
9076 let method = AuthMethod::Agent(AuthMethodAgent::new("default-auth", "Default Auth"));
9077
9078 let json = serde_json::to_value(&method).unwrap();
9079 assert_eq!(
9080 json,
9081 json!({
9082 "methodId": "default-auth",
9083 "name": "Default Auth",
9084 "type": "agent"
9085 })
9086 );
9087 assert!(!json.as_object().unwrap().contains_key("description"));
9089
9090 let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9091 match deserialized {
9092 AuthMethod::Agent(AuthMethodAgent {
9093 method_id, name, ..
9094 }) => {
9095 assert_eq!(method_id.0.as_ref(), "default-auth");
9096 assert_eq!(name, "Default Auth");
9097 }
9098 _ => panic!("Expected Agent variant"),
9099 }
9100 }
9101
9102 #[test]
9103 fn test_auth_method_agent_deserialization() {
9104 let json = json!({
9105 "methodId": "agent-auth",
9106 "name": "Agent Auth",
9107 "type": "agent"
9108 });
9109
9110 let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9111 assert!(matches!(deserialized, AuthMethod::Agent(_)));
9112 }
9113
9114 #[test]
9115 fn test_auth_method_agent_requires_type() {
9116 assert!(
9117 serde_json::from_value::<AuthMethod>(json!({
9118 "methodId": "agent-auth",
9119 "name": "Agent Auth"
9120 }))
9121 .is_err()
9122 );
9123 }
9124
9125 #[test]
9126 fn test_auth_method_agent_rejects_null_type() {
9127 assert!(
9128 serde_json::from_value::<AuthMethod>(json!({
9129 "methodId": "agent-auth",
9130 "name": "Agent Auth",
9131 "type": null
9132 }))
9133 .is_err()
9134 );
9135 }
9136
9137 #[test]
9138 fn test_auth_method_unknown_does_not_hide_malformed_agent() {
9139 assert!(
9140 serde_json::from_value::<AuthMethod>(json!({
9141 "methodId": "agent-auth",
9142 "type": "agent"
9143 }))
9144 .is_err()
9145 );
9146 assert!(
9147 serde_json::from_value::<AuthMethod>(json!({
9148 "methodId": "api-key",
9149 "type": "env_var",
9150 "vars": [{"name": "API_KEY"}]
9151 }))
9152 .is_err()
9153 );
9154 }
9155
9156 #[test]
9157 fn test_auth_method_unknown_variant_roundtrip() {
9158 let method: AuthMethod = serde_json::from_value(json!({
9159 "methodId": "oauth",
9160 "name": "OAuth",
9161 "type": "_oauth",
9162 "authorizationUrl": "https://example.com/auth"
9163 }))
9164 .unwrap();
9165
9166 assert_eq!(method.method_id().0.as_ref(), "oauth");
9167 assert_eq!(method.name(), "OAuth");
9168 let AuthMethod::Other(unknown) = method else {
9169 panic!("expected unknown auth method");
9170 };
9171 assert_eq!(unknown.type_, "_oauth");
9172 assert_eq!(
9173 unknown.fields.get("authorizationUrl"),
9174 Some(&json!("https://example.com/auth"))
9175 );
9176
9177 assert_eq!(
9178 serde_json::to_value(AuthMethod::Other(unknown)).unwrap(),
9179 json!({
9180 "methodId": "oauth",
9181 "name": "OAuth",
9182 "type": "_oauth",
9183 "authorizationUrl": "https://example.com/auth"
9184 })
9185 );
9186 }
9187
9188 #[test]
9189 fn test_auth_method_unknown_does_not_hide_malformed_known_variant() {
9190 assert!(
9191 serde_json::from_value::<AuthMethod>(json!({
9192 "methodId": "terminal-auth",
9193 "type": "terminal"
9194 }))
9195 .is_err()
9196 );
9197 }
9198
9199 #[test]
9200 fn test_tool_call_and_terminal_cancel_serialization() {
9201 assert_eq!(AGENT_METHOD_NAMES.tool_call_cancel, "tool_call/cancel");
9202 assert_eq!(AGENT_METHOD_NAMES.terminal_cancel, "terminal/cancel");
9203 assert_eq!(
9204 ClientRequest::CancelToolCallRequest(Box::new(CancelToolCallRequest::new(
9205 "sess_abc123",
9206 "call_012"
9207 )))
9208 .method(),
9209 "tool_call/cancel"
9210 );
9211 assert_eq!(
9212 ClientRequest::CancelTerminalRequest(Box::new(CancelTerminalRequest::new(
9213 "sess_abc123",
9214 "term_003"
9215 )))
9216 .method(),
9217 "terminal/cancel"
9218 );
9219 assert_eq!(
9220 serde_json::to_value(CancelToolCallRequest::new("sess_abc123", "call_012")).unwrap(),
9221 json!({"sessionId": "sess_abc123", "toolCallId": "call_012"})
9222 );
9223 assert_eq!(
9224 serde_json::to_value(CancelTerminalRequest::new("sess_abc123", "term_003")).unwrap(),
9225 json!({"sessionId": "sess_abc123", "terminalId": "term_003"})
9226 );
9227 assert!(
9228 serde_json::from_value::<CancelToolCallRequest>(json!({"sessionId": "sess_abc123"}))
9229 .is_err()
9230 );
9231 assert_eq!(
9232 serde_json::to_value(CancelTerminalResponse::new()).unwrap(),
9233 json!({})
9234 );
9235 }
9236
9237 #[test]
9238 fn test_session_delete_serialization() {
9239 assert_eq!(AGENT_METHOD_NAMES.session_delete, "session/delete");
9240 assert_eq!(
9241 ClientRequest::DeleteSessionRequest(Box::new(DeleteSessionRequest::new("sess_abc123")))
9242 .method(),
9243 "session/delete"
9244 );
9245 assert_eq!(
9246 serde_json::to_value(DeleteSessionRequest::new("sess_abc123")).unwrap(),
9247 json!({
9248 "sessionId": "sess_abc123"
9249 })
9250 );
9251 assert_eq!(
9252 serde_json::to_value(DeleteSessionResponse::new()).unwrap(),
9253 json!({})
9254 );
9255 assert_eq!(
9256 serde_json::to_value(
9257 SessionCapabilities::new().delete(SessionDeleteCapabilities::new())
9258 )
9259 .unwrap(),
9260 json!({
9261 "delete": {}
9262 })
9263 );
9264 }
9265 #[cfg(feature = "unstable_session_set_title")]
9266 #[test]
9267 fn test_session_set_title_serialization() {
9268 assert_eq!(AGENT_METHOD_NAMES.session_set_title, "session/set_title");
9269 assert_eq!(
9270 ClientRequest::SetSessionTitleRequest(Box::new(SetSessionTitleRequest::new(
9271 "sess_abc123",
9272 "Investigate OAuth timeout"
9273 )))
9274 .method(),
9275 "session/set_title"
9276 );
9277 assert_eq!(
9278 serde_json::to_value(SetSessionTitleRequest::new(
9279 "sess_abc123",
9280 "Investigate OAuth timeout"
9281 ))
9282 .unwrap(),
9283 json!({
9284 "sessionId": "sess_abc123",
9285 "title": "Investigate OAuth timeout"
9286 })
9287 );
9288 assert_eq!(
9289 serde_json::to_value(SetSessionTitleResponse::new("Investigate OAuth timeout"))
9290 .unwrap(),
9291 json!({
9292 "title": "Investigate OAuth timeout"
9293 })
9294 );
9295 assert_eq!(
9296 serde_json::to_value(SessionCapabilities::new().title(SessionTitleCapabilities::new()))
9297 .unwrap(),
9298 json!({
9299 "title": {}
9300 })
9301 );
9302 }
9303
9304 #[cfg(feature = "unstable_session_set_title")]
9305 #[test]
9306 fn test_session_set_title_requires_title() {
9307 for params in [
9308 json!({"sessionId": "sess_abc123"}),
9309 json!({"sessionId": "sess_abc123", "title": null}),
9310 json!({"sessionId": "sess_abc123", "title": 42}),
9311 ] {
9312 assert!(serde_json::from_value::<SetSessionTitleRequest>(params).is_err());
9313 }
9314 for result in [json!({}), json!({"title": null})] {
9315 assert!(serde_json::from_value::<SetSessionTitleResponse>(result).is_err());
9316 }
9317 }
9318
9319 #[cfg(feature = "unstable_session_options")]
9320 #[test]
9321 fn test_session_options_serialization() {
9322 assert_eq!(AGENT_METHOD_NAMES.session_options, "session/options");
9323 assert_eq!(
9324 ClientRequest::SessionOptionsRequest(Box::new(SessionOptionsRequest::new(
9325 "/home/user/project"
9326 )))
9327 .method(),
9328 "session/options"
9329 );
9330 assert_eq!(
9331 serde_json::to_value(
9332 SessionOptionsRequest::new("/home/user/project")
9333 .session_id(SessionId::new("sess_abc123"))
9334 )
9335 .unwrap(),
9336 json!({"cwd": "/home/user/project", "sessionId": "sess_abc123"})
9337 );
9338 assert_eq!(
9339 serde_json::from_value::<SessionOptionsRequest>(
9340 json!({"cwd": "/home/user/project", "additionalDirectories": null, "sessionId": null})
9341 )
9342 .unwrap(),
9343 SessionOptionsRequest::new("/home/user/project")
9344 );
9345 let request = NewSessionRequest::new("/home/user/project").config_options(vec![
9346 InitialSessionConfigOption::new("model", SessionConfigOptionValue::id("model-2")),
9347 InitialSessionConfigOption::new("fast", SessionConfigOptionValue::boolean(true)),
9348 ]);
9349 let value = serde_json::to_value(&request).unwrap();
9350 assert_eq!(
9351 value["configOptions"],
9352 json!([
9353 {"configId": "model", "type": "id", "value": "model-2"},
9354 {"configId": "fast", "type": "boolean", "value": true}
9355 ])
9356 );
9357 assert_eq!(
9358 serde_json::from_value::<NewSessionRequest>(value).unwrap(),
9359 request
9360 );
9361 assert!(
9362 serde_json::from_value::<NewSessionRequest>(json!({
9363 "cwd": "/home/user/project",
9364 "mcpServers": [],
9365 "configOptions": [{"type": "boolean", "value": true}]
9366 }))
9367 .is_err()
9368 );
9369 assert_eq!(
9370 serde_json::to_value(SessionOptionsResponse::new()).unwrap(),
9371 json!({})
9372 );
9373 #[cfg(feature = "unstable_session_fork")]
9374 {
9375 let fork =
9376 ForkSessionRequest::new("sess_abc123", "/home/user/project").config_options(vec![
9377 InitialSessionConfigOption::new(
9378 "model",
9379 SessionConfigOptionValue::id("model-2"),
9380 ),
9381 ]);
9382 let value = serde_json::to_value(&fork).unwrap();
9383 assert_eq!(
9384 value["configOptions"],
9385 json!([{"configId": "model", "type": "id", "value": "model-2"}])
9386 );
9387 assert_eq!(
9388 serde_json::from_value::<ForkSessionRequest>(value).unwrap(),
9389 fork
9390 );
9391 assert_eq!(
9393 serde_json::from_value::<ForkSessionRequest>(json!({
9394 "sessionId": "sess_abc123",
9395 "cwd": "/home/user/project",
9396 "configOptions": null
9397 }))
9398 .unwrap(),
9399 ForkSessionRequest::new("sess_abc123", "/home/user/project")
9400 );
9401 assert!(
9402 serde_json::from_value::<ForkSessionRequest>(json!({
9403 "sessionId": "sess_abc123",
9404 "cwd": "/home/user/project",
9405 "configOptions": [{"type": "boolean", "value": true}]
9406 }))
9407 .is_err()
9408 );
9409 }
9410 assert_eq!(
9411 serde_json::to_value(
9412 SessionCapabilities::new().options(SessionOptionsCapabilities::new())
9413 )
9414 .unwrap(),
9415 json!({"options": {}})
9416 );
9417 }
9418
9419 #[cfg(feature = "unstable_session_status")]
9420 #[test]
9421 fn test_session_status_serialization() {
9422 assert_eq!(AGENT_METHOD_NAMES.session_status, "session/status");
9423 assert_eq!(
9424 ClientRequest::SessionStatusRequest(Box::new(SessionStatusRequest::new("sess_abc123")))
9425 .method(),
9426 "session/status"
9427 );
9428 assert_eq!(
9429 serde_json::to_value(SessionStatusRequest::new("sess_abc123")).unwrap(),
9430 json!({"sessionId": "sess_abc123"})
9431 );
9432 assert_eq!(
9433 serde_json::to_value(SessionStatusResponse::new(SessionStatus::Saved)).unwrap(),
9434 json!({"status": "saved"})
9435 );
9436 assert_eq!(
9437 serde_json::to_value(
9438 SessionCapabilities::new().status(SessionStatusCapabilities::new())
9439 )
9440 .unwrap(),
9441 json!({"status": {}})
9442 );
9443 assert_eq!(
9444 serde_json::to_value(SessionStatusResponse::new(SessionStatus::Open).state(
9445 StateUpdate::RequiresAction(crate::v2::RequiresActionStateUpdate::new())
9446 ))
9447 .unwrap(),
9448 json!({
9449 "status": "open",
9450 "state": {"state": "requires_action"}
9451 })
9452 );
9453 for state in [json!(null), json!("running"), json!({"state": 7})] {
9454 let response = serde_json::from_value::<SessionStatusResponse>(
9455 json!({"status": "open", "state": state}),
9456 )
9457 .unwrap();
9458 assert_eq!(response.state, None);
9459 }
9460 }
9461
9462 #[cfg(feature = "unstable_session_status")]
9463 #[test]
9464 fn test_session_status_is_strict_and_open() {
9465 let custom =
9466 serde_json::from_value::<SessionStatusResponse>(json!({"status": "_suspended"}))
9467 .unwrap();
9468 assert_eq!(
9469 custom.status,
9470 SessionStatus::Other("_suspended".to_string())
9471 );
9472 assert_eq!(
9473 serde_json::to_value(&custom).unwrap(),
9474 json!({"status": "_suspended"})
9475 );
9476 for result in [json!({}), json!({"status": null}), json!({"status": 1})] {
9477 assert!(serde_json::from_value::<SessionStatusResponse>(result).is_err());
9478 }
9479 for params in [json!({}), json!({"sessionId": null})] {
9480 assert!(serde_json::from_value::<SessionStatusRequest>(params).is_err());
9481 }
9482 }
9483
9484 #[cfg(feature = "unstable_session_archive")]
9485 #[test]
9486 fn test_session_archive_serialization() {
9487 assert_eq!(AGENT_METHOD_NAMES.session_archive, "session/archive");
9488 assert_eq!(AGENT_METHOD_NAMES.session_unarchive, "session/unarchive");
9489 assert_eq!(
9490 ClientRequest::ArchiveSessionRequest(Box::new(ArchiveSessionRequest::new(
9491 "sess_abc123"
9492 )))
9493 .method(),
9494 "session/archive"
9495 );
9496 assert_eq!(
9497 ClientRequest::UnarchiveSessionRequest(Box::new(UnarchiveSessionRequest::new(
9498 "sess_abc123"
9499 )))
9500 .method(),
9501 "session/unarchive"
9502 );
9503 assert_eq!(
9504 serde_json::to_value(ArchiveSessionRequest::new("sess_abc123")).unwrap(),
9505 json!({"sessionId": "sess_abc123"})
9506 );
9507 assert_eq!(
9508 serde_json::to_value(UnarchiveSessionResponse::new()).unwrap(),
9509 json!({})
9510 );
9511 assert_eq!(
9512 serde_json::to_value(
9513 SessionCapabilities::new().archive(SessionArchiveCapabilities::new())
9514 )
9515 .unwrap(),
9516 json!({"archive": {}})
9517 );
9518 assert_eq!(
9519 serde_json::to_value(
9520 ListSessionsRequest::new()
9521 .cwd("/home/user/project")
9522 .archived(SessionArchiveFilter::Only)
9523 )
9524 .unwrap(),
9525 json!({"cwd": "/home/user/project", "archived": "only"})
9526 );
9527 assert_eq!(
9528 serde_json::to_value(
9529 SessionInfo::new("sess_abc123", "/home/user/project").archived(true)
9530 )
9531 .unwrap(),
9532 json!({"sessionId": "sess_abc123", "cwd": "/home/user/project", "archived": true})
9533 );
9534 }
9535
9536 #[cfg(feature = "unstable_session_archive")]
9537 #[test]
9538 fn test_session_archive_filter_is_strict_and_open() {
9539 for (value, expected) in [
9540 (json!(null), None),
9541 (json!("include"), Some(SessionArchiveFilter::Include)),
9542 (
9543 json!("_recent"),
9544 Some(SessionArchiveFilter::Other("_recent".to_string())),
9545 ),
9546 ] {
9547 let request =
9548 serde_json::from_value::<ListSessionsRequest>(json!({"archived": value})).unwrap();
9549 assert_eq!(request.archived, expected);
9550 }
9551 for value in [json!(true), json!(1), json!({})] {
9552 assert!(
9553 serde_json::from_value::<ListSessionsRequest>(json!({"archived": value})).is_err()
9554 );
9555 }
9556 let info = serde_json::from_value::<SessionInfo>(
9557 json!({"sessionId": "sess_abc123", "cwd": "/home/user/project", "archived": "yes"}),
9558 )
9559 .unwrap();
9560 assert_eq!(info.archived, None);
9561 }
9562
9563 #[test]
9564 fn test_session_additional_directories_serialization() {
9565 assert_eq!(
9566 serde_json::to_value(NewSessionRequest::new("/home/user/project")).unwrap(),
9567 json!({
9568 "cwd": "/home/user/project",
9569 })
9570 );
9571 assert_eq!(
9572 serde_json::to_value(
9573 NewSessionRequest::new("/home/user/project").additional_directories(vec![
9574 PathBuf::from("/home/user/shared-lib"),
9575 PathBuf::from("/home/user/product-docs"),
9576 ])
9577 )
9578 .unwrap(),
9579 json!({
9580 "cwd": "/home/user/project",
9581 "additionalDirectories": [
9582 "/home/user/shared-lib",
9583 "/home/user/product-docs"
9584 ],
9585 })
9586 );
9587 assert_eq!(
9588 serde_json::to_value(ResumeSessionRequest::new(
9589 "sess_abc123",
9590 "/home/user/project"
9591 ))
9592 .unwrap(),
9593 json!({
9594 "sessionId": "sess_abc123",
9595 "cwd": "/home/user/project",
9596 })
9597 );
9598 assert_eq!(
9599 serde_json::from_value::<ResumeSessionRequest>(json!({
9600 "sessionId": "sess_abc123",
9601 "cwd": "/home/user/project"
9602 }))
9603 .unwrap()
9604 .mcp_servers,
9605 Vec::<McpServer>::new()
9606 );
9607 assert_eq!(
9608 serde_json::from_value::<ResumeSessionRequest>(json!({
9609 "sessionId": "sess_abc123",
9610 "cwd": "/home/user/project",
9611 "mcpServers": null
9612 }))
9613 .unwrap()
9614 .mcp_servers,
9615 Vec::<McpServer>::new()
9616 );
9617 assert_eq!(
9618 serde_json::to_value(SessionInfo::new("sess_abc123", "/home/user/project")).unwrap(),
9619 json!({
9620 "sessionId": "sess_abc123",
9621 "cwd": "/home/user/project"
9622 })
9623 );
9624 assert_eq!(
9625 serde_json::to_value(
9626 SessionInfo::new("sess_abc123", "/home/user/project").additional_directories(vec![
9627 PathBuf::from("/home/user/shared-lib"),
9628 PathBuf::from("/home/user/product-docs"),
9629 ])
9630 )
9631 .unwrap(),
9632 json!({
9633 "sessionId": "sess_abc123",
9634 "cwd": "/home/user/project",
9635 "additionalDirectories": [
9636 "/home/user/shared-lib",
9637 "/home/user/product-docs"
9638 ]
9639 })
9640 );
9641 assert_eq!(
9642 serde_json::from_value::<SessionInfo>(json!({
9643 "sessionId": "sess_abc123",
9644 "cwd": "/home/user/project"
9645 }))
9646 .unwrap()
9647 .additional_directories,
9648 Vec::<AbsolutePath>::new()
9649 );
9650 }
9651 #[test]
9652 fn test_session_additional_directories_capabilities_serialization() {
9653 assert_eq!(
9654 serde_json::to_value(
9655 SessionCapabilities::new()
9656 .additional_directories(SessionAdditionalDirectoriesCapabilities::new())
9657 )
9658 .unwrap(),
9659 json!({
9660 "additionalDirectories": {}
9661 })
9662 );
9663 }
9664
9665 #[test]
9666 fn test_session_system_prompt_capabilities_serialization() {
9667 assert_eq!(
9668 serde_json::to_value(
9669 SessionCapabilities::new().system_prompt(SessionSystemPromptCapabilities::new())
9670 )
9671 .unwrap(),
9672 json!({ "systemPrompt": {} })
9673 );
9674 assert_eq!(
9675 serde_json::to_value(
9676 SessionCapabilities::new().system_prompt(
9677 SessionSystemPromptCapabilities::new().mode(
9678 SessionSystemPromptModeCapabilities::new()
9679 .override_(SessionSystemPromptOverrideCapabilities::new())
9680 )
9681 )
9682 )
9683 .unwrap(),
9684 json!({ "systemPrompt": { "mode": { "override": {} } } })
9685 );
9686 assert_eq!(
9687 serde_json::from_value::<SessionCapabilities>(
9688 json!({ "systemPrompt": { "mode": { "override": {} } } })
9689 )
9690 .unwrap()
9691 .system_prompt
9692 .and_then(|capabilities| capabilities.mode)
9693 .and_then(|mode| mode.override_),
9694 Some(SessionSystemPromptOverrideCapabilities::new())
9695 );
9696
9697 assert_eq!(
9699 serde_json::from_value::<SessionCapabilities>(json!({ "systemPrompt": "yes" }))
9700 .unwrap()
9701 .system_prompt,
9702 None
9703 );
9704 assert_eq!(
9705 serde_json::from_value::<SessionCapabilities>(
9706 json!({ "systemPrompt": { "mode": { "override": true } } })
9707 )
9708 .unwrap()
9709 .system_prompt,
9710 Some(
9711 SessionSystemPromptCapabilities::new()
9712 .mode(SessionSystemPromptModeCapabilities::new())
9713 )
9714 );
9715 assert_eq!(
9716 serde_json::from_value::<SessionCapabilities>(
9717 json!({ "systemPrompt": { "mode": "override" } })
9718 )
9719 .unwrap()
9720 .system_prompt,
9721 Some(SessionSystemPromptCapabilities::new())
9722 );
9723 }
9724
9725 #[test]
9726 fn test_system_prompt_lifecycle_request_serialization() {
9727 let system_prompt = SystemPrompt::new(vec![ContentBlock::from(
9728 "You are a code review specialist.",
9729 )]);
9730 let system_prompt_json = json!({
9731 "mode": "append",
9732 "content": [{ "type": "text", "text": "You are a code review specialist." }]
9733 });
9734
9735 let request =
9736 NewSessionRequest::new("/home/user/project").system_prompt(system_prompt.clone());
9737 let request_json = json!({
9738 "cwd": "/home/user/project",
9739 "systemPrompt": system_prompt_json
9740 });
9741 assert_eq!(serde_json::to_value(&request).unwrap(), request_json);
9742 assert_eq!(
9743 serde_json::from_value::<NewSessionRequest>(request_json).unwrap(),
9744 request
9745 );
9746
9747 assert_eq!(
9748 serde_json::to_value(
9749 ResumeSessionRequest::new("sess_abc123", "/home/user/project")
9750 .system_prompt(system_prompt.clone())
9751 )
9752 .unwrap()["systemPrompt"],
9753 system_prompt_json
9754 );
9755 #[cfg(feature = "unstable_session_fork")]
9756 assert_eq!(
9757 serde_json::to_value(
9758 ForkSessionRequest::new("sess_abc123", "/home/user/project")
9759 .system_prompt(system_prompt.clone())
9760 )
9761 .unwrap()["systemPrompt"],
9762 system_prompt_json
9763 );
9764
9765 let override_prompt =
9766 SystemPrompt::new(vec![ContentBlock::from("...")]).mode(SystemPromptMode::Override);
9767 let override_json = json!({
9768 "mode": "override",
9769 "content": [{ "type": "text", "text": "..." }]
9770 });
9771 assert_eq!(
9772 serde_json::to_value(&override_prompt).unwrap(),
9773 override_json
9774 );
9775 assert_eq!(
9776 serde_json::from_value::<SystemPrompt>(override_json).unwrap(),
9777 override_prompt
9778 );
9779 }
9780
9781 #[test]
9784 fn test_system_prompt_new_defaults_to_append() {
9785 let system_prompt = SystemPrompt::new(vec![ContentBlock::from("...")]);
9786 assert_eq!(system_prompt.mode, SystemPromptMode::Append);
9787 assert_eq!(
9788 serde_json::to_value(&system_prompt).unwrap(),
9789 json!({ "mode": "append", "content": [{ "type": "text", "text": "..." }] })
9790 );
9791 }
9792
9793 #[test]
9797 fn test_system_prompt_preserves_unknown_modes() {
9798 for mode in ["_vendor_mode", "prepend"] {
9799 let system_prompt_json =
9800 json!({ "mode": mode, "content": [{ "type": "text", "text": "..." }] });
9801 let system_prompt: SystemPrompt =
9802 serde_json::from_value(system_prompt_json.clone()).unwrap();
9803 assert_eq!(
9804 system_prompt.mode,
9805 SystemPromptMode::Other(mode.to_string())
9806 );
9807 assert_eq!(
9808 serde_json::to_value(&system_prompt).unwrap(),
9809 system_prompt_json
9810 );
9811 }
9812 }
9813
9814 fn assert_system_prompt_is_strict<T>(base: &serde_json::Value)
9818 where
9819 T: serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
9820 {
9821 let name = std::any::type_name::<T>();
9822 let with = |system_prompt: serde_json::Value| {
9823 let mut request = base.clone();
9824 request["systemPrompt"] = system_prompt;
9825 serde_json::from_value::<T>(request)
9826 };
9827
9828 for system_prompt in [
9829 json!("You are a code review specialist."),
9830 json!({ "content": [{ "type": "text", "text": "..." }] }),
9831 json!({ "mode": null, "content": [{ "type": "text", "text": "..." }] }),
9832 json!({ "mode": 1, "content": [{ "type": "text", "text": "..." }] }),
9833 json!({ "mode": "append" }),
9834 json!({ "mode": "append", "content": "..." }),
9835 json!({ "mode": "append", "content": [{ "type": "text" }] }),
9836 ] {
9837 assert!(
9838 with(system_prompt.clone()).is_err(),
9839 "{name}.systemPrompt: {system_prompt}"
9840 );
9841 }
9842
9843 assert_eq!(
9844 with(serde_json::Value::Null).unwrap(),
9845 serde_json::from_value::<T>(base.clone()).unwrap(),
9846 "{name}.systemPrompt"
9847 );
9848 }
9849
9850 #[test]
9851 fn test_session_setup_requests_reject_malformed_system_prompts() {
9852 assert!(
9853 serde_json::to_value(NewSessionRequest::new("/repo"))
9854 .unwrap()
9855 .get("systemPrompt")
9856 .is_none()
9857 );
9858 assert_system_prompt_is_strict::<NewSessionRequest>(&json!({ "cwd": "/repo" }));
9859 assert_system_prompt_is_strict::<ResumeSessionRequest>(&json!({
9860 "sessionId": "sess-1",
9861 "cwd": "/repo"
9862 }));
9863 #[cfg(feature = "unstable_session_fork")]
9864 assert_system_prompt_is_strict::<ForkSessionRequest>(&json!({
9865 "sessionId": "sess-1",
9866 "cwd": "/repo"
9867 }));
9868 }
9869
9870 #[test]
9873 fn test_system_prompt_preserves_unknown_content_blocks() {
9874 let request: NewSessionRequest = serde_json::from_value(json!({
9875 "cwd": "/home/user/project",
9876 "systemPrompt": {
9877 "mode": "append",
9878 "content": [{ "type": "_vendor_video", "uri": "https://example.com/intro.mp4" }]
9879 }
9880 }))
9881 .unwrap();
9882 let content = request.system_prompt.unwrap().content;
9883 assert_eq!(content.len(), 1);
9884 assert!(matches!(content[0], ContentBlock::Other(_)));
9885 }
9886
9887 #[test]
9888 fn test_auth_method_terminal_serialization() {
9889 let method = AuthMethod::Terminal(AuthMethodTerminal::new("tui-auth", "Terminal Auth"));
9890
9891 let json = serde_json::to_value(&method).unwrap();
9892 assert_eq!(
9893 json,
9894 json!({
9895 "methodId": "tui-auth",
9896 "name": "Terminal Auth",
9897 "type": "terminal"
9898 })
9899 );
9900 assert!(!json.as_object().unwrap().contains_key("args"));
9902 assert!(!json.as_object().unwrap().contains_key("env"));
9903
9904 let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9905 match deserialized {
9906 AuthMethod::Terminal(AuthMethodTerminal { args, env, .. }) => {
9907 assert_eq!(args, Vec::<String>::new());
9908 assert_eq!(env, []);
9909 }
9910 _ => panic!("Expected Terminal variant"),
9911 }
9912 }
9913
9914 #[test]
9915 fn test_auth_method_terminal_with_args_and_env_serialization() {
9916 let method = AuthMethod::Terminal(
9917 AuthMethodTerminal::new("tui-auth", "Terminal Auth")
9918 .args(vec!["--interactive".to_string(), "--color".to_string()])
9919 .env(vec![EnvVariable::new("TERM", "xterm-256color")]),
9920 );
9921
9922 let json = serde_json::to_value(&method).unwrap();
9923 assert_eq!(
9924 json,
9925 json!({
9926 "methodId": "tui-auth",
9927 "name": "Terminal Auth",
9928 "type": "terminal",
9929 "args": ["--interactive", "--color"],
9930 "env": [
9931 {
9932 "name": "TERM",
9933 "value": "xterm-256color"
9934 }
9935 ]
9936 })
9937 );
9938
9939 let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9940 match deserialized {
9941 AuthMethod::Terminal(AuthMethodTerminal { args, env, .. }) => {
9942 assert_eq!(args, vec!["--interactive", "--color"]);
9943 assert_eq!(env.len(), 1);
9944 assert_eq!(env[0].name, "TERM");
9945 assert_eq!(env[0].value, "xterm-256color");
9946 }
9947 _ => panic!("Expected Terminal variant"),
9948 }
9949 }
9950
9951 #[test]
9952 fn test_session_config_option_id_serialize() {
9953 let val = SessionConfigOptionValue::id("model-1");
9954 let json = serde_json::to_value(&val).unwrap();
9955 assert_eq!(json, json!({ "type": "id", "value": "model-1" }));
9956 }
9957
9958 #[test]
9959 fn test_session_config_option_value_boolean_serialize() {
9960 let val = SessionConfigOptionValue::boolean(true);
9961 let json = serde_json::to_value(&val).unwrap();
9962 assert_eq!(json, json!({ "type": "boolean", "value": true }));
9963 }
9964
9965 #[test]
9966 fn test_session_config_option_value_deserialize_id() {
9967 let json = json!({ "type": "id", "value": "model-1" });
9968 let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9969 assert_eq!(val, SessionConfigOptionValue::id("model-1"));
9970 assert_eq!(val.as_id().unwrap().to_string(), "model-1");
9971 }
9972
9973 #[test]
9974 fn test_session_config_option_value_deserialize_requires_type() {
9975 let json = json!({ "value": "model-1" });
9976 let result = serde_json::from_value::<SessionConfigOptionValue>(json);
9977 assert!(result.is_err());
9978 }
9979
9980 #[test]
9981 fn test_session_config_option_value_deserialize_boolean() {
9982 let json = json!({ "type": "boolean", "value": true });
9983 let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9984 assert_eq!(val, SessionConfigOptionValue::boolean(true));
9985 assert_eq!(val.as_bool(), Some(true));
9986 }
9987
9988 #[test]
9989 fn test_session_config_option_value_deserialize_boolean_false() {
9990 let json = json!({ "type": "boolean", "value": false });
9991 let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9992 assert_eq!(val, SessionConfigOptionValue::boolean(false));
9993 assert_eq!(val.as_bool(), Some(false));
9994 }
9995
9996 #[test]
9997 fn test_session_config_option_value_deserialize_unknown_type_with_string_value() {
9998 let json = json!({
9999 "type": "text",
10000 "value": "freeform input",
10001 "maxLength": 200
10002 });
10003 let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10004 let SessionConfigOptionValue::Other(unknown) = val else {
10005 panic!("Expected Other variant");
10006 };
10007 assert_eq!(unknown.type_, "text");
10008 assert_eq!(unknown.value, json!("freeform input"));
10009 assert_eq!(unknown.fields["maxLength"], json!(200));
10010 }
10011
10012 #[test]
10013 fn test_session_config_option_value_deserialize_unknown_type_with_object_value() {
10014 let json = json!({
10015 "type": "range",
10016 "value": { "min": 1, "max": 5 }
10017 });
10018 let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10019 let SessionConfigOptionValue::Other(unknown) = val else {
10020 panic!("Expected Other variant");
10021 };
10022 assert_eq!(unknown.type_, "range");
10023 assert_eq!(unknown.value, json!({ "min": 1, "max": 5 }));
10024 }
10025
10026 #[test]
10027 fn test_session_config_option_value_roundtrip_id() {
10028 let original = SessionConfigOptionValue::id("option-a");
10029 let json = serde_json::to_value(&original).unwrap();
10030 let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10031 assert_eq!(original, roundtripped);
10032 }
10033
10034 #[test]
10035 fn test_session_config_option_value_roundtrip_boolean() {
10036 let original = SessionConfigOptionValue::boolean(false);
10037 let json = serde_json::to_value(&original).unwrap();
10038 let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10039 assert_eq!(original, roundtripped);
10040 }
10041
10042 #[test]
10043 fn test_session_config_option_value_roundtrip_other() {
10044 let mut fields = IndexMap::new();
10045 fields.insert("maxLength".to_string(), json!(200));
10046 let original = SessionConfigOptionValue::from(OtherSessionConfigOptionValue::new(
10047 "text",
10048 json!("freeform input"),
10049 fields,
10050 ));
10051 let json = serde_json::to_value(&original).unwrap();
10052 assert_eq!(
10053 json,
10054 json!({"type": "text", "value": "freeform input", "maxLength": 200})
10055 );
10056 let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10057 assert_eq!(original, roundtripped);
10058 }
10059
10060 #[test]
10061 fn test_session_config_option_value_type_mismatch_boolean_with_string() {
10062 let json = json!({ "type": "boolean", "value": "not a bool" });
10063 let result = serde_json::from_value::<SessionConfigOptionValue>(json);
10064 assert!(result.is_err());
10065 }
10066
10067 #[test]
10068 fn test_session_config_option_value_from_impls() {
10069 let from_str: SessionConfigOptionValue = "model-1".into();
10070 assert_eq!(from_str.as_id().unwrap().to_string(), "model-1");
10071
10072 let from_id: SessionConfigOptionValue = SessionConfigValueId::new("model-2").into();
10073 assert_eq!(from_id.as_id().unwrap().to_string(), "model-2");
10074
10075 let from_bool: SessionConfigOptionValue = true.into();
10076 assert_eq!(from_bool.as_bool(), Some(true));
10077 }
10078
10079 #[test]
10080 fn test_set_session_config_option_request_id() {
10081 let req = SetSessionConfigOptionRequest::new("sess_1", "model", "model-1");
10082 let json = serde_json::to_value(&req).unwrap();
10083 assert_eq!(
10084 json,
10085 json!({
10086 "sessionId": "sess_1",
10087 "configId": "model",
10088 "type": "id",
10089 "value": "model-1"
10090 })
10091 );
10092 }
10093
10094 #[test]
10095 fn test_set_session_config_option_request_boolean() {
10096 let req = SetSessionConfigOptionRequest::new("sess_1", "brave_mode", true);
10097 let json = serde_json::to_value(&req).unwrap();
10098 assert_eq!(
10099 json,
10100 json!({
10101 "sessionId": "sess_1",
10102 "configId": "brave_mode",
10103 "type": "boolean",
10104 "value": true
10105 })
10106 );
10107 }
10108
10109 #[test]
10110 fn test_set_session_config_option_request_deserialize_requires_type() {
10111 let json = json!({
10112 "sessionId": "sess_1",
10113 "configId": "model",
10114 "value": "model-1"
10115 });
10116 let result = serde_json::from_value::<SetSessionConfigOptionRequest>(json);
10117 assert!(result.is_err());
10118 }
10119
10120 #[test]
10121 fn test_set_session_config_option_request_deserialize_boolean() {
10122 let json = json!({
10123 "sessionId": "sess_1",
10124 "configId": "brave_mode",
10125 "type": "boolean",
10126 "value": true
10127 });
10128 let req: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
10129 assert_eq!(req.value.as_bool(), Some(true));
10130 }
10131
10132 #[test]
10133 fn test_set_session_config_option_request_roundtrip_id() {
10134 let original = SetSessionConfigOptionRequest::new("s", "c", "v");
10135 let json = serde_json::to_value(&original).unwrap();
10136 let roundtripped: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
10137 assert_eq!(original, roundtripped);
10138 }
10139
10140 #[test]
10141 fn test_set_session_config_option_request_roundtrip_boolean() {
10142 let original = SetSessionConfigOptionRequest::new("s", "c", false);
10143 let json = serde_json::to_value(&original).unwrap();
10144 let roundtripped: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
10145 assert_eq!(original, roundtripped);
10146 }
10147
10148 #[test]
10149 fn test_session_config_boolean_serialization() {
10150 let cfg = SessionConfigBoolean::new(true);
10151 let json = serde_json::to_value(&cfg).unwrap();
10152 assert_eq!(json, json!({ "currentValue": true }));
10153
10154 let deserialized: SessionConfigBoolean = serde_json::from_value(json).unwrap();
10155 assert!(deserialized.current_value);
10156 }
10157
10158 #[test]
10159 fn test_session_config_option_boolean_variant() {
10160 let opt = SessionConfigOption::boolean("brave_mode", "Brave Mode", false)
10161 .description("Skip confirmation prompts")
10162 .meta(test_meta());
10163 assert_eq!(serialized_meta_key_count(&opt), 1);
10164
10165 let json = serde_json::to_value(&opt).unwrap();
10166 assert_eq!(
10167 json,
10168 json!({
10169 "configId": "brave_mode",
10170 "name": "Brave Mode",
10171 "description": "Skip confirmation prompts",
10172 "type": "boolean",
10173 "currentValue": false,
10174 "_meta": {
10175 "source": "test"
10176 }
10177 })
10178 );
10179
10180 let deserialized: SessionConfigOption = serde_json::from_value(json).unwrap();
10181 assert_eq!(deserialized.config_id.to_string(), "brave_mode");
10182 assert_eq!(deserialized.name, "Brave Mode");
10183 match deserialized.kind {
10184 SessionConfigKind::Boolean(ref b) => assert!(!b.current_value),
10185 _ => panic!("Expected Boolean kind"),
10186 }
10187 }
10188
10189 #[test]
10190 fn test_session_config_option_select_still_works() {
10191 let opt = SessionConfigOption::select(
10193 "model",
10194 "Model",
10195 "model-1",
10196 vec![
10197 SessionConfigSelectOption::new("model-1", "Model 1"),
10198 SessionConfigSelectOption::new("model-2", "Model 2"),
10199 ],
10200 )
10201 .meta(test_meta());
10202 assert_eq!(serialized_meta_key_count(&opt), 1);
10203
10204 let json = serde_json::to_value(&opt).unwrap();
10205 assert_eq!(json["type"], "select");
10206 assert_eq!(json["currentValue"], "model-1");
10207 assert_eq!(json["options"].as_array().unwrap().len(), 2);
10208 assert_eq!(json["_meta"]["source"], "test");
10209
10210 let deserialized: SessionConfigOption = serde_json::from_value(json).unwrap();
10211 match deserialized.kind {
10212 SessionConfigKind::Select(ref s) => {
10213 assert_eq!(s.current_value.to_string(), "model-1");
10214 }
10215 _ => panic!("Expected Select kind"),
10216 }
10217 }
10218
10219 #[test]
10220 fn test_session_config_option_unknown_kind_roundtrip() {
10221 let option: SessionConfigOption = serde_json::from_value(json!({
10222 "configId": "verbosity",
10223 "name": "Verbosity",
10224 "type": "_slider",
10225 "currentValue": 3,
10226 "min": 0,
10227 "max": 5,
10228 "_meta": {
10229 "source": "test"
10230 }
10231 }))
10232 .unwrap();
10233
10234 assert_eq!(option.config_id.to_string(), "verbosity");
10235 assert_eq!(option.meta.as_ref().unwrap()["source"], "test");
10236 let SessionConfigKind::Other(unknown) = &option.kind else {
10237 panic!("expected unknown config kind");
10238 };
10239 assert_eq!(unknown.type_, "_slider");
10240 assert_eq!(unknown.fields.get("currentValue"), Some(&json!(3)));
10241 assert!(!unknown.fields.contains_key("_meta"));
10242 assert_eq!(serialized_meta_key_count(&option), 1);
10243
10244 let json = serde_json::to_value(&option).unwrap();
10245 assert_eq!(json["type"], "_slider");
10246 assert_eq!(json["currentValue"], 3);
10247 assert_eq!(json["min"], 0);
10248 assert_eq!(json["max"], 5);
10249 assert_eq!(json["_meta"]["source"], "test");
10250 }
10251
10252 #[test]
10253 fn test_session_config_option_unknown_kind_does_not_duplicate_flattened_meta() {
10254 let mut fields = IndexMap::new();
10255 fields.insert("currentValue".to_string(), json!(3));
10256 fields.insert("_meta".to_string(), json!({ "inner": "ignored" }));
10257
10258 let option = SessionConfigOption::new(
10259 "verbosity",
10260 "Verbosity",
10261 SessionConfigKind::Other(OtherSessionConfigKind::new("_slider", fields)),
10262 )
10263 .meta(test_meta());
10264
10265 let SessionConfigKind::Other(unknown) = &option.kind else {
10266 panic!("expected unknown config kind");
10267 };
10268 assert!(!unknown.fields.contains_key("_meta"));
10269 assert_eq!(serialized_meta_key_count(&option), 1);
10270
10271 let json = serde_json::to_value(&option).unwrap();
10272 assert_eq!(json["type"], "_slider");
10273 assert_eq!(json["currentValue"], 3);
10274 assert_eq!(json["_meta"]["source"], "test");
10275 }
10276
10277 #[test]
10278 fn test_session_config_option_unknown_does_not_hide_malformed_known_kind() {
10279 assert!(
10280 serde_json::from_value::<SessionConfigOption>(json!({
10281 "configId": "model",
10282 "name": "Model",
10283 "type": "select"
10284 }))
10285 .is_err()
10286 );
10287 }
10288
10289 #[cfg(feature = "unstable_llm_providers")]
10290 #[test]
10291 fn test_llm_protocol_known_variants() {
10292 assert_eq!(
10293 serde_json::to_value(&LlmProtocol::Anthropic).unwrap(),
10294 json!("anthropic")
10295 );
10296 assert_eq!(
10297 serde_json::to_value(&LlmProtocol::OpenAi).unwrap(),
10298 json!("openai")
10299 );
10300 assert_eq!(
10301 serde_json::to_value(&LlmProtocol::Azure).unwrap(),
10302 json!("azure")
10303 );
10304 assert_eq!(
10305 serde_json::to_value(&LlmProtocol::Vertex).unwrap(),
10306 json!("vertex")
10307 );
10308 assert_eq!(
10309 serde_json::to_value(&LlmProtocol::Bedrock).unwrap(),
10310 json!("bedrock")
10311 );
10312
10313 assert_eq!(
10314 serde_json::from_str::<LlmProtocol>("\"anthropic\"").unwrap(),
10315 LlmProtocol::Anthropic
10316 );
10317 assert_eq!(
10318 serde_json::from_str::<LlmProtocol>("\"openai\"").unwrap(),
10319 LlmProtocol::OpenAi
10320 );
10321 assert_eq!(
10322 serde_json::from_str::<LlmProtocol>("\"azure\"").unwrap(),
10323 LlmProtocol::Azure
10324 );
10325 assert_eq!(
10326 serde_json::from_str::<LlmProtocol>("\"vertex\"").unwrap(),
10327 LlmProtocol::Vertex
10328 );
10329 assert_eq!(
10330 serde_json::from_str::<LlmProtocol>("\"bedrock\"").unwrap(),
10331 LlmProtocol::Bedrock
10332 );
10333 }
10334
10335 #[cfg(feature = "unstable_llm_providers")]
10336 #[test]
10337 fn test_llm_protocol_unknown_variant() {
10338 let unknown: LlmProtocol = serde_json::from_str("\"cohere\"").unwrap();
10339 assert_eq!(unknown, LlmProtocol::Other("cohere".to_string()));
10340
10341 let json = serde_json::to_value(&unknown).unwrap();
10342 assert_eq!(json, json!("cohere"));
10343 }
10344
10345 #[cfg(feature = "unstable_llm_providers")]
10346 #[test]
10347 fn test_provider_current_config_serialization() {
10348 let config =
10349 ProviderCurrentConfig::new(LlmProtocol::Anthropic, "https://api.anthropic.com");
10350
10351 let json = serde_json::to_value(&config).unwrap();
10352 assert_eq!(
10353 json,
10354 json!({
10355 "apiType": "anthropic",
10356 "baseUrl": "https://api.anthropic.com"
10357 })
10358 );
10359
10360 let deserialized: ProviderCurrentConfig = serde_json::from_value(json).unwrap();
10361 assert_eq!(deserialized.api_type, LlmProtocol::Anthropic);
10362 assert_eq!(deserialized.base_url, "https://api.anthropic.com");
10363 }
10364
10365 #[cfg(feature = "unstable_llm_providers")]
10366 #[test]
10367 fn test_provider_info_with_current_config() {
10368 let info = ProviderInfo::new(
10369 "main",
10370 vec![LlmProtocol::Anthropic, LlmProtocol::OpenAi],
10371 true,
10372 Some(ProviderCurrentConfig::new(
10373 LlmProtocol::Anthropic,
10374 "https://api.anthropic.com",
10375 )),
10376 );
10377
10378 let json = serde_json::to_value(&info).unwrap();
10379 assert_eq!(
10380 json,
10381 json!({
10382 "providerId": "main",
10383 "supported": ["anthropic", "openai"],
10384 "required": true,
10385 "current": {
10386 "apiType": "anthropic",
10387 "baseUrl": "https://api.anthropic.com"
10388 }
10389 })
10390 );
10391
10392 let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10393 assert_eq!(deserialized.provider_id.to_string(), "main");
10394 assert_eq!(deserialized.supported.len(), 2);
10395 assert!(deserialized.required);
10396 assert!(deserialized.current.is_some());
10397 assert_eq!(
10398 deserialized.current.as_ref().unwrap().api_type,
10399 LlmProtocol::Anthropic
10400 );
10401 }
10402
10403 #[cfg(feature = "unstable_llm_providers")]
10404 #[test]
10405 fn test_provider_info_disabled() {
10406 let info = ProviderInfo::new(
10407 "secondary",
10408 vec![LlmProtocol::OpenAi],
10409 false,
10410 None::<ProviderCurrentConfig>,
10411 );
10412
10413 let json = serde_json::to_value(&info).unwrap();
10414 assert_eq!(
10415 json,
10416 json!({
10417 "providerId": "secondary",
10418 "supported": ["openai"],
10419 "required": false
10420 })
10421 );
10422
10423 let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10424 assert_eq!(deserialized.provider_id.to_string(), "secondary");
10425 assert!(!deserialized.required);
10426 assert!(deserialized.current.is_none());
10427 }
10428
10429 #[cfg(feature = "unstable_llm_providers")]
10430 #[test]
10431 fn test_provider_info_missing_current_defaults_to_none() {
10432 let json = json!({
10434 "providerId": "main",
10435 "supported": ["anthropic"],
10436 "required": true
10437 });
10438 let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10439 assert!(deserialized.current.is_none());
10440 }
10441
10442 #[cfg(feature = "unstable_llm_providers")]
10443 #[test]
10444 fn test_provider_info_explicit_null_current_decodes_to_none() {
10445 let json = json!({
10449 "providerId": "main",
10450 "supported": ["anthropic"],
10451 "required": true,
10452 "current": null
10453 });
10454 let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10455 assert!(deserialized.current.is_none());
10456 }
10457
10458 #[cfg(feature = "unstable_llm_providers")]
10459 #[test]
10460 fn test_list_providers_response_serialization() {
10461 let response = ListProvidersResponse::new(vec![ProviderInfo::new(
10462 "main",
10463 vec![LlmProtocol::Anthropic],
10464 true,
10465 Some(ProviderCurrentConfig::new(
10466 LlmProtocol::Anthropic,
10467 "https://api.anthropic.com",
10468 )),
10469 )]);
10470
10471 let json = serde_json::to_value(&response).unwrap();
10472 assert_eq!(json["providers"].as_array().unwrap().len(), 1);
10473 assert_eq!(json["providers"][0]["providerId"], "main");
10474
10475 let deserialized: ListProvidersResponse = serde_json::from_value(json).unwrap();
10476 assert_eq!(deserialized.providers.len(), 1);
10477 }
10478
10479 #[cfg(feature = "unstable_llm_providers")]
10480 #[test]
10481 fn test_set_provider_request_serialization() {
10482 let mut headers = IndexMap::new();
10483 headers.insert("Authorization".to_string(), "Bearer sk-test".to_string());
10484
10485 let request =
10486 SetProviderRequest::new("main", LlmProtocol::OpenAi, "https://api.openai.com/v1")
10487 .headers(headers);
10488
10489 let json = serde_json::to_value(&request).unwrap();
10490 assert_eq!(
10491 json,
10492 json!({
10493 "providerId": "main",
10494 "apiType": "openai",
10495 "baseUrl": "https://api.openai.com/v1",
10496 "headers": {
10497 "Authorization": "Bearer sk-test"
10498 }
10499 })
10500 );
10501
10502 let deserialized: SetProviderRequest = serde_json::from_value(json).unwrap();
10503 assert_eq!(deserialized.provider_id.to_string(), "main");
10504 assert_eq!(deserialized.api_type, LlmProtocol::OpenAi);
10505 assert_eq!(deserialized.base_url, "https://api.openai.com/v1");
10506 assert_eq!(deserialized.headers.len(), 1);
10507 assert_eq!(
10508 deserialized.headers.get("Authorization").unwrap(),
10509 "Bearer sk-test"
10510 );
10511 }
10512
10513 #[cfg(feature = "unstable_llm_providers")]
10514 #[test]
10515 fn test_set_provider_request_omits_empty_headers() {
10516 let request =
10517 SetProviderRequest::new("main", LlmProtocol::Anthropic, "https://api.anthropic.com");
10518
10519 let json = serde_json::to_value(&request).unwrap();
10520 assert!(!json.as_object().unwrap().contains_key("headers"));
10522 }
10523
10524 #[cfg(feature = "unstable_llm_providers")]
10525 #[test]
10526 fn test_disable_provider_request_serialization() {
10527 let request = DisableProviderRequest::new("secondary");
10528
10529 let json = serde_json::to_value(&request).unwrap();
10530 assert_eq!(json, json!({ "providerId": "secondary" }));
10531
10532 let deserialized: DisableProviderRequest = serde_json::from_value(json).unwrap();
10533 assert_eq!(deserialized.provider_id.to_string(), "secondary");
10534 }
10535
10536 #[cfg(feature = "unstable_llm_providers")]
10537 #[test]
10538 fn test_providers_capabilities_serialization() {
10539 let caps = ProvidersCapabilities::new();
10540
10541 let json = serde_json::to_value(&caps).unwrap();
10542 assert_eq!(json, json!({}));
10543
10544 let deserialized: ProvidersCapabilities = serde_json::from_value(json).unwrap();
10545 assert!(deserialized.meta.is_none());
10546 }
10547
10548 #[cfg(feature = "unstable_llm_providers")]
10549 #[test]
10550 fn test_agent_capabilities_with_providers() {
10551 let caps = AgentCapabilities::new().providers(ProvidersCapabilities::new());
10552
10553 let json = serde_json::to_value(&caps).unwrap();
10554 assert_eq!(json["providers"], json!({}));
10555
10556 let deserialized: AgentCapabilities = serde_json::from_value(json).unwrap();
10557 assert!(deserialized.providers.is_some());
10558 }
10559
10560 #[test]
10561 fn test_agent_capabilities_session_is_explicit() {
10562 let json = serde_json::to_value(AgentCapabilities::new()).unwrap();
10563 assert!(json.get("session").is_none());
10564
10565 let caps = AgentCapabilities::new().session(
10566 SessionCapabilities::new()
10567 .prompt(PromptCapabilities::new().image(PromptImageCapabilities::new()))
10568 .mcp(McpCapabilities::new().stdio(McpStdioCapabilities::new())),
10569 );
10570
10571 assert_eq!(
10572 serde_json::to_value(&caps).unwrap(),
10573 json!({
10574 "session": {
10575 "prompt": {
10576 "image": {}
10577 },
10578 "mcp": {
10579 "stdio": {}
10580 }
10581 }
10582 })
10583 );
10584
10585 let deserialized: AgentCapabilities = serde_json::from_value(json!({
10586 "session": false
10587 }))
10588 .unwrap();
10589 assert!(deserialized.session.is_none());
10590 }
10591
10592 #[test]
10593 fn test_prompt_capabilities_serialize_supported_content_as_objects() {
10594 let caps = PromptCapabilities::new()
10595 .image(PromptImageCapabilities::new())
10596 .audio(PromptAudioCapabilities::new())
10597 .embedded_context(PromptEmbeddedContextCapabilities::new());
10598
10599 assert_eq!(
10600 serde_json::to_value(&caps).unwrap(),
10601 json!({
10602 "image": {},
10603 "audio": {},
10604 "embeddedContext": {}
10605 })
10606 );
10607
10608 let deserialized: PromptCapabilities = serde_json::from_value(json!({
10609 "image": null,
10610 "audio": false,
10611 "embeddedContext": {}
10612 }))
10613 .unwrap();
10614 assert!(deserialized.image.is_none());
10615 assert!(deserialized.audio.is_none());
10616 assert!(deserialized.embedded_context.is_some());
10617 }
10618
10619 #[cfg(feature = "unstable_agent_skills")]
10620 #[test]
10621 fn prompt_skill_capability_has_two_levels() {
10622 let leading = PromptCapabilities::new().skill(PromptSkillCapabilities::new());
10624 assert_eq!(
10625 serde_json::to_value(&leading).unwrap(),
10626 json!({ "skill": {} })
10627 );
10628
10629 let inline = PromptCapabilities::new()
10630 .skill(PromptSkillCapabilities::new().inline(PromptSkillInlineCapabilities::new()));
10631 let wire = json!({ "skill": { "inline": {} } });
10632 assert_eq!(serde_json::to_value(&inline).unwrap(), wire);
10633 assert_eq!(
10634 serde_json::from_value::<PromptCapabilities>(wire).unwrap(),
10635 inline
10636 );
10637
10638 for unsupported in [
10639 json!({}),
10640 json!({ "skill": null }),
10641 json!({ "skill": false }),
10642 json!({ "skill": true }),
10643 ] {
10644 let caps: PromptCapabilities = serde_json::from_value(unsupported).unwrap();
10645 assert!(caps.skill.is_none());
10646 }
10647
10648 for leading_only in [
10650 json!({ "skill": { "inline": null } }),
10651 json!({ "skill": { "inline": true } }),
10652 ] {
10653 assert_eq!(
10654 serde_json::from_value::<PromptCapabilities>(leading_only).unwrap(),
10655 leading
10656 );
10657 }
10658 }
10659
10660 #[test]
10661 fn test_mcp_capabilities_serialize_supported_transports_as_objects() {
10662 let caps = McpCapabilities::new()
10663 .stdio(McpStdioCapabilities::new())
10664 .http(McpHttpCapabilities::new());
10665
10666 assert_eq!(
10667 serde_json::to_value(&caps).unwrap(),
10668 json!({
10669 "stdio": {},
10670 "http": {}
10671 })
10672 );
10673
10674 let deserialized: McpCapabilities = serde_json::from_value(json!({
10675 "stdio": null,
10676 "http": false
10677 }))
10678 .unwrap();
10679 assert!(deserialized.stdio.is_none());
10680 assert!(deserialized.http.is_none());
10681 }
10682
10683 #[cfg(feature = "unstable_mcp_over_acp")]
10684 #[test]
10685 fn test_mcp_capabilities_serialize_acp_support_as_object() {
10686 let caps = McpCapabilities::new().acp(McpAcpCapabilities::new());
10687
10688 assert_eq!(
10689 serde_json::to_value(&caps).unwrap(),
10690 json!({
10691 "acp": {}
10692 })
10693 );
10694 }
10695
10696 #[test]
10697 fn prompt_request_rejects_malformed_content_block() {
10698 use serde_json::json;
10699
10700 assert!(
10701 serde_json::from_value::<PromptRequest>(json!({
10702 "sessionId": "sess-1",
10703 "prompt": [{"type": "text"}]
10704 }))
10705 .is_err()
10706 );
10707 }
10708
10709 #[test]
10710 fn prompt_request_rejects_non_array_prompt() {
10711 use serde_json::json;
10712
10713 assert!(
10714 serde_json::from_value::<PromptRequest>(json!({
10715 "sessionId": "sess-1",
10716 "prompt": "hello"
10717 }))
10718 .is_err()
10719 );
10720 }
10721
10722 fn prompt_request_with_idempotency_key(key: &serde_json::Value) -> serde_json::Value {
10723 serde_json::json!({
10724 "sessionId": "sess-1",
10725 "idempotencyKey": key,
10726 "prompt": [{"type": "text", "text": "hello"}]
10727 })
10728 }
10729
10730 #[test]
10731 fn prompt_request_idempotency_key_round_trips() {
10732 use serde_json::json;
10733
10734 let key = "0b6f3c1e-8d2a-4c57-9a41-5e2f7d90c3ab";
10735 let value = prompt_request_with_idempotency_key(&json!(key));
10736
10737 let request: PromptRequest = serde_json::from_value(value.clone()).unwrap();
10738 assert_eq!(
10739 request.idempotency_key.as_ref().map(IdempotencyKey::as_str),
10740 Some(key)
10741 );
10742 assert_eq!(serde_json::to_value(&request).unwrap(), value);
10743
10744 let built = PromptRequest::new("sess-1", vec![ContentBlock::from("hello")])
10745 .idempotency_key(IdempotencyKey::new(key).unwrap());
10746 assert_eq!(built, request);
10747 }
10748
10749 #[test]
10750 fn prompt_request_omitted_and_null_idempotency_key_mean_no_key() {
10751 use serde_json::json;
10752
10753 let omitted = json!({
10754 "sessionId": "sess-1",
10755 "prompt": [{"type": "text", "text": "hello"}]
10756 });
10757 let request: PromptRequest = serde_json::from_value(omitted.clone()).unwrap();
10758 assert_eq!(request.idempotency_key, None);
10759 assert_eq!(serde_json::to_value(&request).unwrap(), omitted);
10761
10762 let null: PromptRequest =
10763 serde_json::from_value(prompt_request_with_idempotency_key(&json!(null))).unwrap();
10764 assert_eq!(null, request);
10765 }
10766
10767 #[test]
10768 fn prompt_request_rejects_malformed_idempotency_key() {
10769 use serde_json::json;
10770
10771 let too_long = "k".repeat(IdempotencyKey::MAX_LENGTH + 1);
10772 for (name, key) in [
10773 ("an empty string", json!("")),
10774 ("a string over 255 characters", json!(too_long)),
10775 ("a number", json!(7)),
10776 ("a boolean", json!(true)),
10777 ("an object", json!({"key": "k"})),
10778 ("an array", json!(["k"])),
10779 ] {
10780 assert!(
10781 serde_json::from_value::<PromptRequest>(prompt_request_with_idempotency_key(&key))
10782 .is_err(),
10783 "{name} must fail the request instead of being treated as no key"
10784 );
10785 }
10786 }
10787
10788 #[test]
10789 fn idempotency_key_length_is_counted_in_characters() {
10790 use serde_json::json;
10791
10792 assert_eq!(IdempotencyKey::new(""), Err(InvalidIdempotencyKey::Empty));
10793 assert_eq!(IdempotencyKey::new("k").unwrap().as_str(), "k");
10794
10795 let longest = "k".repeat(IdempotencyKey::MAX_LENGTH);
10796 assert_eq!(
10797 IdempotencyKey::new(longest.as_str()).unwrap().as_str(),
10798 longest
10799 );
10800 assert_eq!(
10801 IdempotencyKey::new(format!("{longest}k")),
10802 Err(InvalidIdempotencyKey::TooLong)
10803 );
10804
10805 let multibyte = "é".repeat(IdempotencyKey::MAX_LENGTH);
10807 assert!(IdempotencyKey::new(multibyte.as_str()).is_ok());
10808 assert!(
10809 serde_json::from_value::<PromptRequest>(prompt_request_with_idempotency_key(&json!(
10810 multibyte
10811 )))
10812 .is_ok()
10813 );
10814 assert_eq!(
10815 IdempotencyKey::new(format!("{multibyte}é")),
10816 Err(InvalidIdempotencyKey::TooLong)
10817 );
10818
10819 assert_eq!("k".parse::<IdempotencyKey>().unwrap().to_string(), "k");
10820 assert_eq!(
10821 IdempotencyKey::try_from(String::new()),
10822 Err(InvalidIdempotencyKey::Empty)
10823 );
10824 assert_eq!(
10825 InvalidIdempotencyKey::TooLong.to_string(),
10826 "idempotency key must be at most 255 characters"
10827 );
10828 }
10829
10830 #[cfg(feature = "uuid")]
10831 #[test]
10832 fn generated_idempotency_keys_are_distinct_valid_v4_uuids() {
10833 let first = IdempotencyKey::generate();
10834 let second = IdempotencyKey::generate();
10835 assert_ne!(first, second);
10836
10837 for key in [&first, &second] {
10838 let uuid = uuid::Uuid::parse_str(key.as_str()).unwrap();
10839 assert_eq!(uuid.get_version_num(), 4);
10840 assert_eq!(IdempotencyKey::new(key.as_str()).as_ref(), Ok(key));
10842 let request = PromptRequest::new("sess-1", vec![ContentBlock::from("hello")])
10843 .idempotency_key(key.clone());
10844 let value = serde_json::to_value(&request).unwrap();
10845 assert_eq!(value["idempotencyKey"], key.as_str());
10846 assert_eq!(
10847 serde_json::from_value::<PromptRequest>(value).unwrap(),
10848 request
10849 );
10850 }
10851
10852 assert_eq!(
10853 IdempotencyKey::from(uuid::Uuid::nil()).as_str(),
10854 "00000000-0000-0000-0000-000000000000"
10855 );
10856 }
10857
10858 #[cfg(feature = "schemars")]
10859 #[test]
10860 fn idempotency_key_schema_is_a_strict_bounded_string() {
10861 use serde_json::json;
10862
10863 let key = serde_json::to_value(schemars::schema_for!(IdempotencyKey)).unwrap();
10864 assert_eq!(key["type"], "string");
10865 assert_eq!(key["minLength"], 1);
10866 assert_eq!(key["maxLength"], json!(IdempotencyKey::MAX_LENGTH));
10867
10868 let request = serde_json::to_value(schemars::schema_for!(PromptRequest)).unwrap();
10869 assert_eq!(request["required"], json!(["sessionId", "prompt"]));
10870 let property = &request["properties"]["idempotencyKey"];
10871 assert_eq!(
10872 property["anyOf"],
10873 json!([{"$ref": "#/$defs/IdempotencyKey"}, {"type": "null"}])
10874 );
10875 assert!(property.get("x-deserialize-default-on-error").is_none());
10878 }
10879
10880 fn assert_session_setup_lists_are_strict<T>(base: &serde_json::Value)
10881 where
10882 T: serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
10883 {
10884 let name = std::any::type_name::<T>();
10885 let with = |field: &str, value: serde_json::Value| {
10886 let mut request = base.clone();
10887 request[field] = value;
10888 serde_json::from_value::<T>(request)
10889 };
10890
10891 for (field, value) in [
10892 (
10894 "mcpServers",
10895 json!([
10896 {"type": "stdio", "name": "github", "command": "/usr/bin/gh-mcp", "env": [{"name": "GITHUB_TOKEN", "value": null}]},
10897 {"type": "stdio", "name": "fs", "command": "/usr/bin/fs-mcp"}
10898 ]),
10899 ),
10900 ("mcpServers", json!({"type": "stdio", "name": "fs"})),
10901 ("additionalDirectories", json!(["/repo/lib", 42])),
10902 ("additionalDirectories", json!("/repo/lib")),
10903 ] {
10904 assert!(
10905 with(field, value.clone()).is_err(),
10906 "{name}.{field}: {value}"
10907 );
10908 }
10909
10910 let empty = serde_json::from_value::<T>(base.clone()).unwrap();
10911 for field in ["mcpServers", "additionalDirectories"] {
10912 assert_eq!(
10913 with(field, serde_json::Value::Null).unwrap(),
10914 empty,
10915 "{name}.{field}"
10916 );
10917 }
10918 }
10919
10920 #[test]
10921 fn session_setup_requests_reject_malformed_mcp_servers_and_directories() {
10922 assert_session_setup_lists_are_strict::<NewSessionRequest>(&json!({"cwd": "/repo"}));
10923 assert_session_setup_lists_are_strict::<ResumeSessionRequest>(&json!({
10924 "sessionId": "sess-1",
10925 "cwd": "/repo"
10926 }));
10927 #[cfg(feature = "unstable_session_fork")]
10928 assert_session_setup_lists_are_strict::<ForkSessionRequest>(&json!({
10929 "sessionId": "sess-1",
10930 "cwd": "/repo"
10931 }));
10932 }
10933
10934 #[test]
10935 fn resume_session_request_rejects_malformed_replay_from() {
10936 let request = |replay_from: serde_json::Value| {
10937 serde_json::from_value::<ResumeSessionRequest>(json!({
10938 "sessionId": "sess-1",
10939 "cwd": "/repo",
10940 "replayFrom": replay_from
10941 }))
10942 };
10943
10944 assert!(request(json!("start")).is_err());
10946 assert_eq!(request(serde_json::Value::Null).unwrap().replay_from, None);
10947 assert!(matches!(
10948 request(json!({"type": "start"})).unwrap().replay_from,
10949 Some(ReplayFrom::Start(_))
10950 ));
10951 }
10952
10953 #[test]
10954 fn mcp_server_lists_treat_null_as_empty() {
10955 let servers: Vec<McpServer> = serde_json::from_value(json!([
10956 {"type": "stdio", "name": "fs", "command": "/usr/bin/fs-mcp", "args": null, "env": null},
10957 {"type": "http", "name": "api", "url": "https://example.com/mcp", "headers": null}
10958 ]))
10959 .unwrap();
10960
10961 assert_eq!(
10962 servers,
10963 vec![
10964 McpServer::Stdio(McpServerStdio::new("fs", "/usr/bin/fs-mcp")),
10965 McpServer::Http(McpServerHttp::new("api", "https://example.com/mcp")),
10966 ]
10967 );
10968 }
10969
10970 #[test]
10971 fn terminal_auth_methods_reject_malformed_launch_config() {
10972 let response: InitializeResponse = serde_json::from_value(json!({
10976 "protocolVersion": 2,
10977 "info": {"name": "agent", "version": "1.0.0"},
10978 "authMethods": [
10979 {"type": "terminal", "methodId": "bad-args", "name": "Log in", "args": ["auth", "--port", 8123]},
10980 {"type": "terminal", "methodId": "bad-env", "name": "Log in", "env": [{"name": "DEBUG", "value": 1}]},
10981 {"type": "terminal", "methodId": "null-config", "name": "Log in", "args": null, "env": null},
10982 {"type": "agent", "methodId": "agent", "name": "Agent login"}
10983 ]
10984 }))
10985 .unwrap();
10986
10987 assert_eq!(
10988 response.auth_methods,
10989 vec![
10990 AuthMethod::Terminal(AuthMethodTerminal::new("null-config", "Log in")),
10991 AuthMethod::Agent(AuthMethodAgent::new("agent", "Agent login")),
10992 ]
10993 );
10994 }
10995
10996 #[cfg(feature = "unstable_auth_status")]
10997 #[test]
10998 fn auth_status_response_round_trips() {
10999 let response = AuthStatusResponse::new(AuthState::Authenticated).accounts(vec![
11000 AuthAccount::new("Anthropic API key")
11001 .description("API key helper".to_string())
11002 .active(true),
11003 AuthAccount::new("Claude Max").email("user@example.com".to_string()),
11004 ]);
11005 let json = serde_json::to_value(&response).unwrap();
11006 assert_eq!(
11007 json,
11008 json!({
11009 "state": "authenticated",
11010 "accounts": [
11011 {
11012 "label": "Anthropic API key",
11013 "description": "API key helper",
11014 "active": true
11015 },
11016 {
11017 "label": "Claude Max",
11018 "email": "user@example.com"
11019 }
11020 ]
11021 })
11022 );
11023 assert_eq!(
11024 serde_json::from_value::<AuthStatusResponse>(json).unwrap(),
11025 response
11026 );
11027 assert_eq!(
11028 serde_json::to_value(AuthStatusResponse::new(AuthState::NotRequired)).unwrap(),
11029 json!({"state": "not_required"})
11030 );
11031 }
11032
11033 #[cfg(feature = "unstable_auth_status")]
11034 #[test]
11035 fn auth_status_state_is_strict_and_accounts_are_lenient() {
11036 assert!(serde_json::from_value::<AuthStatusResponse>(json!({})).is_err());
11037 assert!(serde_json::from_value::<AuthStatusResponse>(json!({"state": null})).is_err());
11038 assert!(serde_json::from_value::<AuthStatusResponse>(json!({"state": 1})).is_err());
11039
11040 let response: AuthStatusResponse = serde_json::from_value(json!({
11041 "state": "_vendor_state",
11042 "accounts": [
11043 {"active": true},
11044 {
11045 "label": "Vertex AI",
11046 "description": 42,
11047 "active": "yes",
11048 "email": ["not", "a", "string"]
11049 }
11050 ]
11051 }))
11052 .unwrap();
11053 assert_eq!(
11054 response,
11055 AuthStatusResponse::new(AuthState::Other("_vendor_state".to_string()))
11056 .accounts(vec![AuthAccount::new("Vertex AI")])
11057 );
11058 assert_eq!(
11059 serde_json::from_value::<AuthStatusResponse>(
11060 json!({"state": "unknown", "accounts": null})
11061 )
11062 .unwrap(),
11063 AuthStatusResponse::new(AuthState::Unknown)
11064 );
11065 }
11066
11067 #[cfg(feature = "unstable_auth_status")]
11068 #[test]
11069 fn auth_status_update_notification_routes() {
11070 use crate::v2::{AgentNotification, CLIENT_METHOD_NAMES};
11071
11072 assert_eq!(AGENT_METHOD_NAMES.auth_status, "auth/status");
11073 assert_eq!(CLIENT_METHOD_NAMES.auth_status_update, "auth/status_update");
11074 let notification = AgentNotification::AuthStatusUpdateNotification(Box::new(
11075 AuthStatusUpdateNotification::new(AuthState::Unauthenticated),
11076 ));
11077 assert_eq!(notification.method(), "auth/status_update");
11078 assert_eq!(
11079 serde_json::to_value(¬ification).unwrap(),
11080 json!({"state": "unauthenticated"})
11081 );
11082 }
11083
11084 #[cfg(all(
11085 feature = "unstable_session_fork",
11086 feature = "unstable_session_cursors"
11087 ))]
11088 #[test]
11089 fn fork_session_request_cursor_id_is_optional_and_strict() {
11090 let request = ForkSessionRequest::new("sess_abc123", "/home/user/project")
11091 .cursor_id(CursorId::new("cur_1"));
11092 let wire = json!({
11093 "sessionId": "sess_abc123",
11094 "cursorId": "cur_1",
11095 "cwd": "/home/user/project"
11096 });
11097 assert_eq!(serde_json::to_value(&request).unwrap(), wire);
11098 assert_eq!(
11099 serde_json::from_value::<ForkSessionRequest>(wire).unwrap(),
11100 request
11101 );
11102
11103 for wire in [
11105 json!({ "sessionId": "sess_abc123", "cwd": "/home/user/project" }),
11106 json!({ "sessionId": "sess_abc123", "cwd": "/home/user/project", "cursorId": null }),
11107 ] {
11108 assert_eq!(
11109 serde_json::from_value::<ForkSessionRequest>(wire)
11110 .unwrap()
11111 .cursor_id,
11112 None
11113 );
11114 }
11115
11116 assert!(
11118 serde_json::from_value::<ForkSessionRequest>(json!({
11119 "sessionId": "sess_abc123",
11120 "cwd": "/home/user/project",
11121 "cursorId": 7
11122 }))
11123 .is_err()
11124 );
11125 }
11126}