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")]
211 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
212 #[serde(default)]
213 pub title: Option<String>,
214 pub version: String,
217 #[serde_as(deserialize_as = "DefaultOnError")]
223 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
224 #[serde(default)]
225 #[serde(rename = "_meta")]
226 pub meta: Option<Meta>,
227}
228
229impl Implementation {
230 #[must_use]
232 pub fn new(name: impl Into<String>, version: impl Into<String>) -> Self {
233 Self {
234 name: name.into(),
235 title: None,
236 version: version.into(),
237 meta: None,
238 }
239 }
240
241 #[must_use]
246 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
247 self.title = title.into_option();
248 self
249 }
250
251 #[must_use]
257 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
258 self.meta = meta.into_option();
259 self
260 }
261}
262
263#[serde_as]
273#[skip_serializing_none]
274#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
275#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
276#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGIN_METHOD_NAME)))]
277#[serde(rename_all = "camelCase")]
278#[non_exhaustive]
279pub struct LoginAuthRequest {
280 pub method_id: AuthMethodId,
283 #[serde_as(deserialize_as = "DefaultOnError")]
289 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
290 #[serde(default)]
291 #[serde(rename = "_meta")]
292 pub meta: Option<Meta>,
293}
294
295impl LoginAuthRequest {
296 #[must_use]
298 pub fn new(method_id: impl Into<AuthMethodId>) -> Self {
299 Self {
300 method_id: method_id.into(),
301 meta: None,
302 }
303 }
304
305 #[must_use]
311 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
312 self.meta = meta.into_option();
313 self
314 }
315}
316
317crate::serde_util::default_on_null! {
318 #[serde_as]
320 #[skip_serializing_none]
321 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
322 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
323 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGIN_METHOD_NAME)))]
324 #[serde(rename_all = "camelCase")]
325 #[non_exhaustive]
326 pub struct LoginAuthResponse {
327 #[serde_as(deserialize_as = "DefaultOnError")]
333 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
334 #[serde(default)]
335 #[serde(rename = "_meta")]
336 pub meta: Option<Meta>,
337 }
338}
339
340impl LoginAuthResponse {
341 #[must_use]
343 pub fn new() -> Self {
344 Self::default()
345 }
346
347 #[must_use]
353 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
354 self.meta = meta.into_option();
355 self
356 }
357}
358
359crate::serde_util::default_on_null! {
362 #[serde_as]
370 #[skip_serializing_none]
371 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
372 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
373 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGOUT_METHOD_NAME)))]
374 #[serde(rename_all = "camelCase")]
375 #[non_exhaustive]
376 pub struct LogoutAuthRequest {
377 #[serde_as(deserialize_as = "DefaultOnError")]
383 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
384 #[serde(default)]
385 #[serde(rename = "_meta")]
386 pub meta: Option<Meta>,
387 }
388}
389
390impl LogoutAuthRequest {
391 #[must_use]
393 pub fn new() -> Self {
394 Self::default()
395 }
396
397 #[must_use]
403 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
404 self.meta = meta.into_option();
405 self
406 }
407}
408
409crate::serde_util::default_on_null! {
410 #[serde_as]
412 #[skip_serializing_none]
413 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
414 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
415 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGOUT_METHOD_NAME)))]
416 #[serde(rename_all = "camelCase")]
417 #[non_exhaustive]
418 pub struct LogoutAuthResponse {
419 #[serde_as(deserialize_as = "DefaultOnError")]
425 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
426 #[serde(default)]
427 #[serde(rename = "_meta")]
428 pub meta: Option<Meta>,
429 }
430}
431
432impl LogoutAuthResponse {
433 #[must_use]
435 pub fn new() -> Self {
436 Self::default()
437 }
438
439 #[must_use]
445 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
446 self.meta = meta.into_option();
447 self
448 }
449}
450
451#[cfg(feature = "unstable_auth_status")]
454crate::serde_util::default_on_null! {
455 #[serde_as]
466 #[skip_serializing_none]
467 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
468 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
469 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_STATUS_METHOD_NAME)))]
470 #[serde(rename_all = "camelCase")]
471 #[non_exhaustive]
472 pub struct AuthStatusRequest {
473 #[serde_as(deserialize_as = "DefaultOnError")]
479 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
480 #[serde(default)]
481 #[serde(rename = "_meta")]
482 pub meta: Option<Meta>,
483 }
484}
485
486#[cfg(feature = "unstable_auth_status")]
487impl AuthStatusRequest {
488 #[must_use]
490 pub fn new() -> Self {
491 Self::default()
492 }
493
494 #[must_use]
500 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
501 self.meta = meta.into_option();
502 self
503 }
504}
505
506#[cfg(feature = "unstable_auth_status")]
512#[serde_as]
513#[skip_serializing_none]
514#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
515#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
516#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_STATUS_METHOD_NAME)))]
517#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"agent": [{"action": "replace", "target": "authStatus"}]})))]
518#[serde(rename_all = "camelCase")]
519#[non_exhaustive]
520pub struct AuthStatusResponse {
521 pub state: AuthState,
526 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
532 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
533 #[serde(default, skip_serializing_if = "Vec::is_empty")]
534 pub accounts: Vec<AuthAccount>,
535 #[serde_as(deserialize_as = "DefaultOnError")]
541 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
542 #[serde(default)]
543 #[serde(rename = "_meta")]
544 pub meta: Option<Meta>,
545}
546
547#[cfg(feature = "unstable_auth_status")]
548impl AuthStatusResponse {
549 #[must_use]
551 pub fn new(state: AuthState) -> Self {
552 Self {
553 state,
554 accounts: vec![],
555 meta: None,
556 }
557 }
558
559 #[must_use]
561 pub fn accounts(mut self, accounts: Vec<AuthAccount>) -> Self {
562 self.accounts = accounts;
563 self
564 }
565
566 #[must_use]
572 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
573 self.meta = meta.into_option();
574 self
575 }
576}
577
578#[cfg(feature = "unstable_auth_status")]
588#[serde_as]
589#[skip_serializing_none]
590#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
591#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
592#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = AUTH_STATUS_UPDATE_NOTIFICATION)))]
593#[cfg_attr(feature = "schemars", schemars(extend("x-scope" = {})))]
594#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"agent": [{"action": "replace", "target": "authStatus"}]})))]
595#[serde(rename_all = "camelCase")]
596#[non_exhaustive]
597pub struct AuthStatusUpdateNotification {
598 pub state: AuthState,
603 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
609 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
610 #[serde(default, skip_serializing_if = "Vec::is_empty")]
611 pub accounts: Vec<AuthAccount>,
612 #[serde_as(deserialize_as = "DefaultOnError")]
618 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
619 #[serde(default)]
620 #[serde(rename = "_meta")]
621 pub meta: Option<Meta>,
622}
623
624#[cfg(feature = "unstable_auth_status")]
625impl AuthStatusUpdateNotification {
626 #[must_use]
628 pub fn new(state: AuthState) -> Self {
629 Self {
630 state,
631 accounts: vec![],
632 meta: None,
633 }
634 }
635
636 #[must_use]
638 pub fn accounts(mut self, accounts: Vec<AuthAccount>) -> Self {
639 self.accounts = accounts;
640 self
641 }
642
643 #[must_use]
649 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
650 self.meta = meta.into_option();
651 self
652 }
653}
654
655#[cfg(feature = "unstable_auth_status")]
661#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
662#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
663#[serde(rename_all = "snake_case")]
664#[non_exhaustive]
665pub enum AuthState {
666 Authenticated,
668 Unauthenticated,
671 NotRequired,
673 Unknown,
675 #[serde(untagged)]
681 Other(String),
682}
683
684#[cfg(feature = "unstable_auth_status")]
695#[serde_as]
696#[skip_serializing_none]
697#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
698#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
699#[serde(rename_all = "camelCase")]
700#[non_exhaustive]
701pub struct AuthAccount {
702 pub label: String,
705 #[serde_as(deserialize_as = "DefaultOnError")]
710 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
711 #[serde(default)]
712 pub description: Option<String>,
713 #[serde_as(deserialize_as = "DefaultOnError")]
719 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
720 #[serde(default)]
721 pub active: Option<bool>,
722 #[serde_as(deserialize_as = "DefaultOnError")]
726 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
727 #[serde(default)]
728 pub name: Option<String>,
729 #[serde_as(deserialize_as = "DefaultOnError")]
733 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
734 #[serde(default)]
735 pub email: Option<String>,
736 #[serde_as(deserialize_as = "DefaultOnError")]
740 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
741 #[serde(default)]
742 pub organization: Option<String>,
743 #[serde_as(deserialize_as = "DefaultOnError")]
749 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
750 #[serde(default)]
751 #[serde(rename = "_meta")]
752 pub meta: Option<Meta>,
753}
754
755#[cfg(feature = "unstable_auth_status")]
756impl AuthAccount {
757 #[must_use]
759 pub fn new(label: impl Into<String>) -> Self {
760 Self {
761 label: label.into(),
762 description: None,
763 active: None,
764 name: None,
765 email: None,
766 organization: None,
767 meta: None,
768 }
769 }
770
771 #[must_use]
773 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
774 self.description = description.into_option();
775 self
776 }
777
778 #[must_use]
780 pub fn active(mut self, active: impl IntoOption<bool>) -> Self {
781 self.active = active.into_option();
782 self
783 }
784
785 #[must_use]
787 pub fn name(mut self, name: impl IntoOption<String>) -> Self {
788 self.name = name.into_option();
789 self
790 }
791
792 #[must_use]
794 pub fn email(mut self, email: impl IntoOption<String>) -> Self {
795 self.email = email.into_option();
796 self
797 }
798
799 #[must_use]
801 pub fn organization(mut self, organization: impl IntoOption<String>) -> Self {
802 self.organization = organization.into_option();
803 self
804 }
805
806 #[must_use]
812 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
813 self.meta = meta.into_option();
814 self
815 }
816}
817
818#[cfg(feature = "unstable_auth_status")]
826#[serde_as]
827#[skip_serializing_none]
828#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
829#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
830#[non_exhaustive]
831pub struct AuthStatusCapabilities {
832 #[serde_as(deserialize_as = "DefaultOnError")]
838 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
839 #[serde(default)]
840 #[serde(rename = "_meta")]
841 pub meta: Option<Meta>,
842}
843
844#[cfg(feature = "unstable_auth_status")]
845impl AuthStatusCapabilities {
846 #[must_use]
848 pub fn new() -> Self {
849 Self::default()
850 }
851
852 #[must_use]
858 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
859 self.meta = meta.into_option();
860 self
861 }
862}
863
864#[serde_as]
870#[skip_serializing_none]
871#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
872#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
873#[serde(rename_all = "camelCase")]
874#[non_exhaustive]
875pub struct AgentAuthCapabilities {
876 #[cfg(feature = "unstable_auth_status")]
885 #[serde_as(deserialize_as = "DefaultOnError")]
886 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
887 #[serde(default)]
888 pub status: Option<AuthStatusCapabilities>,
889 #[serde_as(deserialize_as = "DefaultOnError")]
895 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
896 #[serde(default)]
897 #[serde(rename = "_meta")]
898 pub meta: Option<Meta>,
899}
900
901impl AgentAuthCapabilities {
902 #[must_use]
904 pub fn new() -> Self {
905 Self::default()
906 }
907
908 #[cfg(feature = "unstable_auth_status")]
914 #[must_use]
915 pub fn status(mut self, status: impl IntoOption<AuthStatusCapabilities>) -> Self {
916 self.status = status.into_option();
917 self
918 }
919
920 #[must_use]
926 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
927 self.meta = meta.into_option();
928 self
929 }
930}
931
932#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
934#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
935#[serde(transparent)]
936#[from(forward)]
937#[non_exhaustive]
938pub struct AuthMethodId(pub Arc<str>);
939
940impl AuthMethodId {
941 #[must_use]
943 pub fn new(id: impl Into<Self>) -> Self {
944 id.into()
945 }
946}
947
948#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
952#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
953#[serde(tag = "type", rename_all = "snake_case")]
954#[non_exhaustive]
955pub enum AuthMethod {
956 Terminal(AuthMethodTerminal),
959 Agent(AuthMethodAgent),
963 #[serde(untagged)]
973 Other(OtherAuthMethod),
974}
975
976impl AuthMethod {
977 #[must_use]
979 pub fn method_id(&self) -> &AuthMethodId {
980 match self {
981 Self::Agent(a) => &a.method_id,
982 Self::Other(a) => &a.method_id,
983 Self::Terminal(t) => &t.method_id,
984 }
985 }
986
987 #[must_use]
989 pub fn name(&self) -> &str {
990 match self {
991 Self::Agent(a) => &a.name,
992 Self::Other(a) => &a.name,
993 Self::Terminal(t) => &t.name,
994 }
995 }
996
997 #[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")]
1133 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1134 #[serde(default)]
1135 pub description: Option<String>,
1136 #[serde_as(deserialize_as = "DefaultOnError")]
1142 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1143 #[serde(default)]
1144 #[serde(rename = "_meta")]
1145 pub meta: Option<Meta>,
1146}
1147
1148impl AuthMethodAgent {
1149 #[must_use]
1151 pub fn new(method_id: impl Into<AuthMethodId>, name: impl Into<String>) -> Self {
1152 Self {
1153 method_id: method_id.into(),
1154 name: name.into(),
1155 description: None,
1156 meta: None,
1157 }
1158 }
1159
1160 #[must_use]
1162 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
1163 self.description = description.into_option();
1164 self
1165 }
1166
1167 #[must_use]
1173 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1174 self.meta = meta.into_option();
1175 self
1176 }
1177}
1178
1179#[serde_as]
1187#[skip_serializing_none]
1188#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1189#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1190#[serde(rename_all = "camelCase")]
1191#[non_exhaustive]
1192pub struct AuthMethodTerminal {
1193 pub method_id: AuthMethodId,
1195 pub name: String,
1197 #[serde_as(deserialize_as = "DefaultOnError")]
1201 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1202 #[serde(default)]
1203 pub description: Option<String>,
1204 #[serde_as(deserialize_as = "DefaultOnNull")]
1206 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1207 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1208 pub args: Vec<String>,
1209 #[serde_as(deserialize_as = "DefaultOnNull")]
1213 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1214 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1215 pub env: Vec<EnvVariable>,
1216 #[serde_as(deserialize_as = "DefaultOnError")]
1222 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1223 #[serde(default)]
1224 #[serde(rename = "_meta")]
1225 pub meta: Option<Meta>,
1226}
1227
1228impl AuthMethodTerminal {
1229 #[must_use]
1231 pub fn new(method_id: impl Into<AuthMethodId>, name: impl Into<String>) -> Self {
1232 Self {
1233 method_id: method_id.into(),
1234 name: name.into(),
1235 description: None,
1236 args: Vec::new(),
1237 env: Vec::new(),
1238 meta: None,
1239 }
1240 }
1241
1242 #[must_use]
1244 pub fn args(mut self, args: Vec<String>) -> Self {
1245 self.args = args;
1246 self
1247 }
1248
1249 #[must_use]
1253 pub fn env(mut self, env: Vec<EnvVariable>) -> Self {
1254 self.env = env;
1255 self
1256 }
1257
1258 #[must_use]
1260 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
1261 self.description = description.into_option();
1262 self
1263 }
1264
1265 #[must_use]
1271 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1272 self.meta = meta.into_option();
1273 self
1274 }
1275}
1276
1277#[serde_as]
1283#[skip_serializing_none]
1284#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1285#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1286#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_NEW_METHOD_NAME)))]
1287#[serde(rename_all = "camelCase")]
1288#[non_exhaustive]
1289pub struct NewSessionRequest {
1290 pub cwd: AbsolutePath,
1292 #[serde_as(deserialize_as = "DefaultOnNull")]
1298 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1299 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1300 pub additional_directories: Vec<AbsolutePath>,
1301 #[serde_as(deserialize_as = "DefaultOnNull")]
1303 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1304 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1305 pub mcp_servers: Vec<McpServer>,
1306 #[serde(default)]
1312 pub system_prompt: Option<SystemPrompt>,
1313 #[cfg(feature = "unstable_session_options")]
1331 #[serde_as(deserialize_as = "DefaultOnNull")]
1332 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1333 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1334 pub config_options: Vec<InitialSessionConfigOption>,
1335 #[serde_as(deserialize_as = "DefaultOnError")]
1341 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1342 #[serde(default)]
1343 #[serde(rename = "_meta")]
1344 pub meta: Option<Meta>,
1345}
1346
1347impl NewSessionRequest {
1348 #[must_use]
1350 pub fn new(cwd: impl Into<AbsolutePath>) -> Self {
1351 Self {
1352 cwd: cwd.into(),
1353 additional_directories: vec![],
1354 mcp_servers: vec![],
1355 system_prompt: None,
1356 #[cfg(feature = "unstable_session_options")]
1357 config_options: vec![],
1358 meta: None,
1359 }
1360 }
1361
1362 #[must_use]
1364 pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1365 where
1366 I: IntoIterator<Item = P>,
1367 P: Into<AbsolutePath>,
1368 {
1369 self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1370 self
1371 }
1372
1373 #[must_use]
1375 pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1376 self.mcp_servers = mcp_servers;
1377 self
1378 }
1379
1380 #[must_use]
1382 pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1383 self.system_prompt = system_prompt.into_option();
1384 self
1385 }
1386
1387 #[cfg(feature = "unstable_session_options")]
1405 #[must_use]
1406 pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1407 self.config_options = config_options;
1408 self
1409 }
1410
1411 #[must_use]
1417 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1418 self.meta = meta.into_option();
1419 self
1420 }
1421}
1422
1423#[serde_as]
1434#[skip_serializing_none]
1435#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1436#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1437#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_NEW_METHOD_NAME)))]
1438#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}, {"action": "replace", "target": "availableCommands", "value": "availableCommands"}]})))]
1439#[serde(rename_all = "camelCase")]
1440#[non_exhaustive]
1441pub struct NewSessionResponse {
1442 pub session_id: SessionId,
1446 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1452 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1453 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1454 pub config_options: Vec<SessionConfigOption>,
1455 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1461 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1462 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1463 pub available_commands: Vec<AvailableCommand>,
1464 #[serde_as(deserialize_as = "DefaultOnError")]
1470 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1471 #[serde(default)]
1472 #[serde(rename = "_meta")]
1473 pub meta: Option<Meta>,
1474}
1475
1476impl NewSessionResponse {
1477 #[must_use]
1479 pub fn new(session_id: impl Into<SessionId>) -> Self {
1480 Self {
1481 session_id: session_id.into(),
1482 config_options: Vec::new(),
1483 available_commands: Vec::new(),
1484 meta: None,
1485 }
1486 }
1487
1488 #[must_use]
1494 pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
1495 self.config_options = config_options;
1496 self
1497 }
1498
1499 #[must_use]
1501 pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
1502 self.available_commands = available_commands;
1503 self
1504 }
1505
1506 #[must_use]
1512 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1513 self.meta = meta.into_option();
1514 self
1515 }
1516}
1517
1518#[cfg(feature = "unstable_session_fork")]
1531#[serde_as]
1532#[skip_serializing_none]
1533#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1534#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1535#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_FORK_METHOD_NAME)))]
1536#[serde(rename_all = "camelCase")]
1537#[non_exhaustive]
1538pub struct ForkSessionRequest {
1539 pub session_id: SessionId,
1541 #[cfg(feature = "unstable_session_cursors")]
1554 #[serde(default)]
1555 pub cursor_id: Option<CursorId>,
1556 pub cwd: AbsolutePath,
1558 #[serde_as(deserialize_as = "DefaultOnNull")]
1564 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1565 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1566 pub additional_directories: Vec<AbsolutePath>,
1567 #[serde_as(deserialize_as = "DefaultOnNull")]
1569 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1570 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1571 pub mcp_servers: Vec<McpServer>,
1572 #[serde(default)]
1580 pub system_prompt: Option<SystemPrompt>,
1581 #[cfg(feature = "unstable_session_options")]
1600 #[serde_as(deserialize_as = "DefaultOnNull")]
1601 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1602 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1603 pub config_options: Vec<InitialSessionConfigOption>,
1604 #[serde_as(deserialize_as = "DefaultOnError")]
1610 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1611 #[serde(default)]
1612 #[serde(rename = "_meta")]
1613 pub meta: Option<Meta>,
1614}
1615
1616#[cfg(feature = "unstable_session_fork")]
1617impl ForkSessionRequest {
1618 #[must_use]
1620 pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
1621 Self {
1622 session_id: session_id.into(),
1623 #[cfg(feature = "unstable_session_cursors")]
1624 cursor_id: None,
1625 cwd: cwd.into(),
1626 additional_directories: vec![],
1627 mcp_servers: vec![],
1628 system_prompt: None,
1629 #[cfg(feature = "unstable_session_options")]
1630 config_options: vec![],
1631 meta: None,
1632 }
1633 }
1634
1635 #[cfg(feature = "unstable_session_cursors")]
1644 #[must_use]
1645 pub fn cursor_id(mut self, cursor_id: impl IntoOption<CursorId>) -> Self {
1646 self.cursor_id = cursor_id.into_option();
1647 self
1648 }
1649
1650 #[must_use]
1652 pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1653 where
1654 I: IntoIterator<Item = P>,
1655 P: Into<AbsolutePath>,
1656 {
1657 self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1658 self
1659 }
1660
1661 #[must_use]
1663 pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1664 self.mcp_servers = mcp_servers;
1665 self
1666 }
1667
1668 #[must_use]
1670 pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1671 self.system_prompt = system_prompt.into_option();
1672 self
1673 }
1674
1675 #[cfg(feature = "unstable_session_options")]
1694 #[must_use]
1695 pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1696 self.config_options = config_options;
1697 self
1698 }
1699
1700 #[must_use]
1706 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1707 self.meta = meta.into_option();
1708 self
1709 }
1710}
1711
1712#[cfg(feature = "unstable_session_fork")]
1718#[serde_as]
1719#[skip_serializing_none]
1720#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1721#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1722#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_FORK_METHOD_NAME)))]
1723#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}, {"action": "replace", "target": "availableCommands", "value": "availableCommands"}]})))]
1724#[serde(rename_all = "camelCase")]
1725#[non_exhaustive]
1726pub struct ForkSessionResponse {
1727 pub session_id: SessionId,
1729 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1735 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1736 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1737 pub config_options: Vec<SessionConfigOption>,
1738 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1744 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1745 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1746 pub available_commands: Vec<AvailableCommand>,
1747 #[serde_as(deserialize_as = "DefaultOnError")]
1753 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1754 #[serde(default)]
1755 #[serde(rename = "_meta")]
1756 pub meta: Option<Meta>,
1757}
1758
1759#[cfg(feature = "unstable_session_fork")]
1760impl ForkSessionResponse {
1761 #[must_use]
1763 pub fn new(session_id: impl Into<SessionId>) -> Self {
1764 Self {
1765 session_id: session_id.into(),
1766 config_options: Vec::new(),
1767 available_commands: Vec::new(),
1768 meta: None,
1769 }
1770 }
1771
1772 #[must_use]
1778 pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
1779 self.config_options = config_options;
1780 self
1781 }
1782
1783 #[must_use]
1785 pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
1786 self.available_commands = available_commands;
1787 self
1788 }
1789
1790 #[must_use]
1796 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1797 self.meta = meta.into_option();
1798 self
1799 }
1800}
1801
1802#[serde_as]
1809#[skip_serializing_none]
1810#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1811#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1812#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_RESUME_METHOD_NAME)))]
1813#[serde(rename_all = "camelCase")]
1814#[non_exhaustive]
1815pub struct ResumeSessionRequest {
1816 pub session_id: SessionId,
1818 pub cwd: AbsolutePath,
1823 #[serde_as(deserialize_as = "DefaultOnNull")]
1830 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1831 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1832 pub additional_directories: Vec<AbsolutePath>,
1833 #[serde_as(deserialize_as = "DefaultOnNull")]
1838 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1839 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1840 pub mcp_servers: Vec<McpServer>,
1841 #[serde(default)]
1853 pub replay_from: Option<ReplayFrom>,
1854 #[serde(default)]
1862 pub system_prompt: Option<SystemPrompt>,
1863 #[cfg(feature = "unstable_session_options")]
1884 #[serde_as(deserialize_as = "DefaultOnNull")]
1885 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1886 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1887 pub config_options: Vec<InitialSessionConfigOption>,
1888 #[serde_as(deserialize_as = "DefaultOnError")]
1894 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1895 #[serde(default)]
1896 #[serde(rename = "_meta")]
1897 pub meta: Option<Meta>,
1898}
1899
1900impl ResumeSessionRequest {
1901 #[must_use]
1903 pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
1904 Self {
1905 session_id: session_id.into(),
1906 cwd: cwd.into(),
1907 additional_directories: vec![],
1908 mcp_servers: vec![],
1909 replay_from: None,
1910 system_prompt: None,
1911 #[cfg(feature = "unstable_session_options")]
1912 config_options: vec![],
1913 meta: None,
1914 }
1915 }
1916
1917 #[must_use]
1919 pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1920 where
1921 I: IntoIterator<Item = P>,
1922 P: Into<AbsolutePath>,
1923 {
1924 self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1925 self
1926 }
1927
1928 #[must_use]
1930 pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1931 self.mcp_servers = mcp_servers;
1932 self
1933 }
1934
1935 #[must_use]
1943 pub fn replay_from(mut self, replay_from: impl IntoOption<ReplayFrom>) -> Self {
1944 self.replay_from = replay_from.into_option();
1945 self
1946 }
1947
1948 #[must_use]
1950 pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1951 self.system_prompt = system_prompt.into_option();
1952 self
1953 }
1954
1955 #[cfg(feature = "unstable_session_options")]
1973 #[must_use]
1974 pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1975 self.config_options = config_options;
1976 self
1977 }
1978
1979 #[must_use]
1985 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1986 self.meta = meta.into_option();
1987 self
1988 }
1989}
1990
1991#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1995#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1996#[serde(tag = "type", rename_all = "snake_case")]
1997#[non_exhaustive]
1998pub enum ReplayFrom {
1999 Start(ReplayFromStart),
2001 #[serde(untagged)]
2012 Other(OtherReplayFrom),
2013}
2014
2015impl From<ReplayFromStart> for ReplayFrom {
2016 fn from(replay_from: ReplayFromStart) -> Self {
2017 Self::Start(replay_from)
2018 }
2019}
2020
2021#[serde_as]
2023#[skip_serializing_none]
2024#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2025#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2026#[serde(rename_all = "camelCase")]
2027#[non_exhaustive]
2028pub struct ReplayFromStart {
2029 #[serde_as(deserialize_as = "DefaultOnError")]
2035 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2036 #[serde(default)]
2037 #[serde(rename = "_meta")]
2038 pub meta: Option<Meta>,
2039}
2040
2041impl ReplayFromStart {
2042 #[must_use]
2044 pub fn new() -> Self {
2045 Self::default()
2046 }
2047
2048 #[must_use]
2054 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2055 self.meta = meta.into_option();
2056 self
2057 }
2058}
2059
2060#[serde_as]
2062#[skip_serializing_none]
2063#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2064#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
2065#[cfg_attr(feature = "schemars", schemars(inline))]
2066#[cfg_attr(feature = "schemars", schemars(transform = other_replay_from_schema))]
2067#[serde(rename_all = "camelCase")]
2068#[non_exhaustive]
2069pub struct OtherReplayFrom {
2070 #[serde(rename = "type")]
2076 pub type_: String,
2077 #[serde(flatten)]
2080 pub fields: IndexMap<String, serde_json::Value>,
2081}
2082
2083impl OtherReplayFrom {
2084 #[must_use]
2086 pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
2087 fields.shift_remove("type");
2088 Self {
2089 type_: type_.into(),
2090 fields,
2091 }
2092 }
2093}
2094
2095impl<'de> Deserialize<'de> for OtherReplayFrom {
2096 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2097 where
2098 D: serde::Deserializer<'de>,
2099 {
2100 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
2101 let type_ = fields
2102 .shift_remove("type")
2103 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
2104 let serde_json::Value::String(type_) = type_ else {
2105 return Err(serde::de::Error::custom("`type` must be a string"));
2106 };
2107
2108 if is_known_replay_from_type(&type_) {
2109 return Err(serde::de::Error::custom(format!(
2110 "known replay cursor `{type_}` did not match its schema"
2111 )));
2112 }
2113
2114 Ok(Self { type_, fields })
2115 }
2116}
2117
2118fn is_known_replay_from_type(type_: &str) -> bool {
2119 matches!(type_, "start")
2120}
2121
2122#[cfg(feature = "schemars")]
2123fn other_replay_from_schema(schema: &mut Schema) {
2124 super::schema_util::reject_known_string_discriminators(schema, "type", &["start"]);
2125}
2126
2127crate::serde_util::default_on_null! {
2128 #[serde_as]
2136 #[skip_serializing_none]
2137 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2138 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2139 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_RESUME_METHOD_NAME)))]
2140 #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}, {"action": "replace", "target": "availableCommands", "value": "availableCommands"}]})))]
2141 #[serde(rename_all = "camelCase")]
2142 #[non_exhaustive]
2143 pub struct ResumeSessionResponse {
2144 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2150 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2151 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2152 pub config_options: Vec<SessionConfigOption>,
2153 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2159 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2160 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2161 pub available_commands: Vec<AvailableCommand>,
2162 #[serde_as(deserialize_as = "DefaultOnError")]
2168 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2169 #[serde(default)]
2170 #[serde(rename = "_meta")]
2171 pub meta: Option<Meta>,
2172 }
2173}
2174
2175impl ResumeSessionResponse {
2176 #[must_use]
2178 pub fn new() -> Self {
2179 Self::default()
2180 }
2181
2182 #[must_use]
2188 pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
2189 self.config_options = config_options;
2190 self
2191 }
2192
2193 #[must_use]
2195 pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
2196 self.available_commands = available_commands;
2197 self
2198 }
2199
2200 #[must_use]
2206 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2207 self.meta = meta.into_option();
2208 self
2209 }
2210}
2211
2212#[serde_as]
2236#[skip_serializing_none]
2237#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2238#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2239#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CLOSE_METHOD_NAME)))]
2240#[serde(rename_all = "camelCase")]
2241#[non_exhaustive]
2242pub struct CloseSessionRequest {
2243 pub session_id: SessionId,
2245 #[serde_as(deserialize_as = "DefaultOnError")]
2251 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2252 #[serde(default)]
2253 #[serde(rename = "_meta")]
2254 pub meta: Option<Meta>,
2255}
2256
2257impl CloseSessionRequest {
2258 #[must_use]
2260 pub fn new(session_id: impl Into<SessionId>) -> Self {
2261 Self {
2262 session_id: session_id.into(),
2263 meta: None,
2264 }
2265 }
2266
2267 #[must_use]
2273 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2274 self.meta = meta.into_option();
2275 self
2276 }
2277}
2278
2279crate::serde_util::default_on_null! {
2280 #[serde_as]
2282 #[skip_serializing_none]
2283 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2284 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2285 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CLOSE_METHOD_NAME)))]
2286 #[serde(rename_all = "camelCase")]
2287 #[non_exhaustive]
2288 pub struct CloseSessionResponse {
2289 #[serde_as(deserialize_as = "DefaultOnError")]
2295 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2296 #[serde(default)]
2297 #[serde(rename = "_meta")]
2298 pub meta: Option<Meta>,
2299 }
2300}
2301
2302impl CloseSessionResponse {
2303 #[must_use]
2305 pub fn new() -> Self {
2306 Self::default()
2307 }
2308
2309 #[must_use]
2315 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2316 self.meta = meta.into_option();
2317 self
2318 }
2319}
2320
2321#[cfg(feature = "unstable_session_status")]
2335#[serde_as]
2336#[skip_serializing_none]
2337#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2338#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2339#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_STATUS_METHOD_NAME)))]
2340#[serde(rename_all = "camelCase")]
2341#[non_exhaustive]
2342pub struct SessionStatusRequest {
2343 pub session_id: SessionId,
2345 #[serde_as(deserialize_as = "DefaultOnError")]
2351 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2352 #[serde(default)]
2353 #[serde(rename = "_meta")]
2354 pub meta: Option<Meta>,
2355}
2356
2357#[cfg(feature = "unstable_session_status")]
2358impl SessionStatusRequest {
2359 #[must_use]
2361 pub fn new(session_id: impl Into<SessionId>) -> Self {
2362 Self {
2363 session_id: session_id.into(),
2364 meta: None,
2365 }
2366 }
2367
2368 #[must_use]
2374 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2375 self.meta = meta.into_option();
2376 self
2377 }
2378}
2379
2380#[cfg(feature = "unstable_session_status")]
2389#[serde_as]
2390#[skip_serializing_none]
2391#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2392#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2393#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_STATUS_METHOD_NAME)))]
2394#[serde(rename_all = "camelCase")]
2395#[non_exhaustive]
2396pub struct SessionStatusResponse {
2397 pub status: SessionStatus,
2401 #[serde_as(deserialize_as = "DefaultOnError")]
2409 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2410 #[serde(default)]
2411 pub state: Option<StateUpdate>,
2412 #[serde_as(deserialize_as = "DefaultOnError")]
2418 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2419 #[serde(default)]
2420 #[serde(rename = "_meta")]
2421 pub meta: Option<Meta>,
2422}
2423
2424#[cfg(feature = "unstable_session_status")]
2425impl SessionStatusResponse {
2426 #[must_use]
2428 pub fn new(status: SessionStatus) -> Self {
2429 Self {
2430 status,
2431 state: None,
2432 meta: None,
2433 }
2434 }
2435
2436 #[must_use]
2439 pub fn state(mut self, state: impl IntoOption<StateUpdate>) -> Self {
2440 self.state = state.into_option();
2441 self
2442 }
2443
2444 #[must_use]
2450 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2451 self.meta = meta.into_option();
2452 self
2453 }
2454}
2455
2456#[cfg(feature = "unstable_session_status")]
2462#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2463#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2464#[serde(rename_all = "snake_case")]
2465#[non_exhaustive]
2466pub enum SessionStatus {
2467 Open,
2474 Saved,
2478 #[serde(untagged)]
2485 Other(String),
2486}
2487
2488#[cfg(feature = "unstable_session_options")]
2502#[serde_as]
2503#[skip_serializing_none]
2504#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2505#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2506#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_OPTIONS_METHOD_NAME)))]
2507#[serde(rename_all = "camelCase")]
2508#[non_exhaustive]
2509pub struct SessionOptionsRequest {
2510 pub cwd: AbsolutePath,
2512 #[serde_as(deserialize_as = "DefaultOnNull")]
2516 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
2517 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2518 pub additional_directories: Vec<AbsolutePath>,
2519 #[serde(default)]
2526 pub session_id: Option<SessionId>,
2527 #[serde_as(deserialize_as = "DefaultOnError")]
2533 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2534 #[serde(default)]
2535 #[serde(rename = "_meta")]
2536 pub meta: Option<Meta>,
2537}
2538
2539#[cfg(feature = "unstable_session_options")]
2540impl SessionOptionsRequest {
2541 #[must_use]
2543 pub fn new(cwd: impl Into<AbsolutePath>) -> Self {
2544 Self {
2545 cwd: cwd.into(),
2546 additional_directories: vec![],
2547 session_id: None,
2548 meta: None,
2549 }
2550 }
2551
2552 #[must_use]
2554 pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
2555 where
2556 I: IntoIterator<Item = P>,
2557 P: Into<AbsolutePath>,
2558 {
2559 self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
2560 self
2561 }
2562
2563 #[must_use]
2565 pub fn session_id(mut self, session_id: impl IntoOption<SessionId>) -> Self {
2566 self.session_id = session_id.into_option();
2567 self
2568 }
2569
2570 #[must_use]
2576 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2577 self.meta = meta.into_option();
2578 self
2579 }
2580}
2581
2582#[cfg(feature = "unstable_session_options")]
2583crate::serde_util::default_on_null! {
2584 #[serde_as]
2593 #[skip_serializing_none]
2594 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2595 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2596 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_OPTIONS_METHOD_NAME)))]
2597 #[serde(rename_all = "camelCase")]
2598 #[non_exhaustive]
2599 pub struct SessionOptionsResponse {
2600 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2606 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2607 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2608 pub config_options: Vec<SessionConfigOption>,
2609 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2618 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2619 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2620 pub available_commands: Vec<AvailableCommand>,
2621 #[serde_as(deserialize_as = "DefaultOnError")]
2627 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2628 #[serde(default)]
2629 #[serde(rename = "_meta")]
2630 pub meta: Option<Meta>,
2631 }
2632}
2633
2634#[cfg(feature = "unstable_session_options")]
2635impl SessionOptionsResponse {
2636 #[must_use]
2638 pub fn new() -> Self {
2639 Self::default()
2640 }
2641
2642 #[must_use]
2644 pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
2645 self.config_options = config_options;
2646 self
2647 }
2648
2649 #[must_use]
2651 pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
2652 self.available_commands = available_commands;
2653 self
2654 }
2655
2656 #[must_use]
2662 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2663 self.meta = meta.into_option();
2664 self
2665 }
2666}
2667
2668#[cfg(feature = "unstable_session_options")]
2678#[serde_as]
2679#[skip_serializing_none]
2680#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2681#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2682#[serde(rename_all = "camelCase")]
2683#[non_exhaustive]
2684pub struct InitialSessionConfigOption {
2685 pub config_id: SessionConfigId,
2687 #[serde(flatten)]
2692 pub value: SessionConfigOptionValue,
2693 #[serde_as(deserialize_as = "DefaultOnError")]
2699 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2700 #[serde(default)]
2701 #[serde(rename = "_meta")]
2702 pub meta: Option<Meta>,
2703}
2704
2705#[cfg(feature = "unstable_session_options")]
2706impl InitialSessionConfigOption {
2707 #[must_use]
2709 pub fn new(
2710 config_id: impl Into<SessionConfigId>,
2711 value: impl Into<SessionConfigOptionValue>,
2712 ) -> Self {
2713 Self {
2714 config_id: config_id.into(),
2715 value: value.into(),
2716 meta: None,
2717 }
2718 }
2719
2720 #[must_use]
2726 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2727 self.meta = meta.into_option();
2728 self
2729 }
2730}
2731
2732#[serde_as]
2747#[skip_serializing_none]
2748#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2749#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2750#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TOOL_CALL_CANCEL_METHOD_NAME)))]
2751#[serde(rename_all = "camelCase")]
2752#[non_exhaustive]
2753pub struct CancelToolCallRequest {
2754 pub session_id: SessionId,
2756 pub tool_call_id: ToolCallId,
2758 #[serde_as(deserialize_as = "DefaultOnError")]
2764 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2765 #[serde(default)]
2766 #[serde(rename = "_meta")]
2767 pub meta: Option<Meta>,
2768}
2769
2770impl CancelToolCallRequest {
2771 #[must_use]
2773 pub fn new(session_id: impl Into<SessionId>, tool_call_id: impl Into<ToolCallId>) -> Self {
2774 Self {
2775 session_id: session_id.into(),
2776 tool_call_id: tool_call_id.into(),
2777 meta: None,
2778 }
2779 }
2780
2781 #[must_use]
2787 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2788 self.meta = meta.into_option();
2789 self
2790 }
2791}
2792
2793crate::serde_util::default_on_null! {
2794 #[serde_as]
2796 #[skip_serializing_none]
2797 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2798 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2799 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TOOL_CALL_CANCEL_METHOD_NAME)))]
2800 #[serde(rename_all = "camelCase")]
2801 #[non_exhaustive]
2802 pub struct CancelToolCallResponse {
2803 #[serde_as(deserialize_as = "DefaultOnError")]
2809 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2810 #[serde(default)]
2811 #[serde(rename = "_meta")]
2812 pub meta: Option<Meta>,
2813 }
2814}
2815
2816impl CancelToolCallResponse {
2817 #[must_use]
2819 pub fn new() -> Self {
2820 Self::default()
2821 }
2822
2823 #[must_use]
2829 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2830 self.meta = meta.into_option();
2831 self
2832 }
2833}
2834
2835#[serde_as]
2851#[skip_serializing_none]
2852#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2853#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2854#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TERMINAL_CANCEL_METHOD_NAME)))]
2855#[serde(rename_all = "camelCase")]
2856#[non_exhaustive]
2857pub struct CancelTerminalRequest {
2858 pub session_id: SessionId,
2860 pub terminal_id: TerminalId,
2862 #[serde_as(deserialize_as = "DefaultOnError")]
2868 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2869 #[serde(default)]
2870 #[serde(rename = "_meta")]
2871 pub meta: Option<Meta>,
2872}
2873
2874impl CancelTerminalRequest {
2875 #[must_use]
2877 pub fn new(session_id: impl Into<SessionId>, terminal_id: impl Into<TerminalId>) -> Self {
2878 Self {
2879 session_id: session_id.into(),
2880 terminal_id: terminal_id.into(),
2881 meta: None,
2882 }
2883 }
2884
2885 #[must_use]
2891 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2892 self.meta = meta.into_option();
2893 self
2894 }
2895}
2896
2897crate::serde_util::default_on_null! {
2898 #[serde_as]
2900 #[skip_serializing_none]
2901 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2902 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2903 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TERMINAL_CANCEL_METHOD_NAME)))]
2904 #[serde(rename_all = "camelCase")]
2905 #[non_exhaustive]
2906 pub struct CancelTerminalResponse {
2907 #[serde_as(deserialize_as = "DefaultOnError")]
2913 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2914 #[serde(default)]
2915 #[serde(rename = "_meta")]
2916 pub meta: Option<Meta>,
2917 }
2918}
2919
2920impl CancelTerminalResponse {
2921 #[must_use]
2923 pub fn new() -> Self {
2924 Self::default()
2925 }
2926
2927 #[must_use]
2933 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2934 self.meta = meta.into_option();
2935 self
2936 }
2937}
2938
2939#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2943#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
2944#[serde(transparent)]
2945#[from(Arc<str>, String, &str, &mut str, Box<str>, Cow<'_, str>)]
2946#[non_exhaustive]
2947pub struct SessionListCursor(pub Arc<str>);
2948
2949impl SessionListCursor {
2950 #[must_use]
2952 pub fn new(cursor: impl Into<Self>) -> Self {
2953 cursor.into()
2954 }
2955}
2956
2957impl AsRef<str> for SessionListCursor {
2958 fn as_ref(&self) -> &str {
2959 &self.0
2960 }
2961}
2962
2963impl From<&String> for SessionListCursor {
2964 fn from(cursor: &String) -> Self {
2965 Self(cursor.as_str().into())
2966 }
2967}
2968
2969macro_rules! impl_session_list_cursor_option_conversion {
2970 ($source:ty) => {
2971 impl IntoOption<SessionListCursor> for $source {
2972 fn into_option(self) -> Option<SessionListCursor> {
2973 Some(self.into())
2974 }
2975 }
2976 };
2977}
2978
2979impl_session_list_cursor_option_conversion!(Arc<str>);
2980impl_session_list_cursor_option_conversion!(String);
2981impl_session_list_cursor_option_conversion!(&str);
2982impl_session_list_cursor_option_conversion!(&mut str);
2983impl_session_list_cursor_option_conversion!(&String);
2984impl_session_list_cursor_option_conversion!(Box<str>);
2985impl_session_list_cursor_option_conversion!(Cow<'_, str>);
2986
2987crate::serde_util::default_on_null! {
2988 #[serde_as]
2990 #[skip_serializing_none]
2991 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2992 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2993 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LIST_METHOD_NAME)))]
2994 #[serde(rename_all = "camelCase")]
2995 #[non_exhaustive]
2996 pub struct ListSessionsRequest {
2997 #[serde(default)]
3005 pub cwd: Option<AbsolutePath>,
3006 #[serde(default)]
3010 pub cursor: Option<SessionListCursor>,
3011 #[cfg(feature = "unstable_session_archive")]
3021 #[serde(default)]
3022 pub archived: Option<SessionArchiveFilter>,
3023 #[serde_as(deserialize_as = "DefaultOnError")]
3029 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3030 #[serde(default)]
3031 #[serde(rename = "_meta")]
3032 pub meta: Option<Meta>,
3033 }
3034}
3035
3036impl ListSessionsRequest {
3037 #[must_use]
3039 pub fn new() -> Self {
3040 Self::default()
3041 }
3042
3043 #[must_use]
3045 pub fn cwd(mut self, cwd: impl IntoOption<AbsolutePath>) -> Self {
3046 self.cwd = cwd.into_option();
3047 self
3048 }
3049
3050 #[must_use]
3052 pub fn cursor(mut self, cursor: impl IntoOption<SessionListCursor>) -> Self {
3053 self.cursor = cursor.into_option();
3054 self
3055 }
3056
3057 #[cfg(feature = "unstable_session_archive")]
3063 #[must_use]
3064 pub fn archived(mut self, archived: impl IntoOption<SessionArchiveFilter>) -> Self {
3065 self.archived = archived.into_option();
3066 self
3067 }
3068
3069 #[must_use]
3075 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3076 self.meta = meta.into_option();
3077 self
3078 }
3079}
3080
3081#[serde_as]
3083#[skip_serializing_none]
3084#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3085#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3086#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LIST_METHOD_NAME)))]
3087#[serde(rename_all = "camelCase")]
3088#[non_exhaustive]
3089pub struct ListSessionsResponse {
3090 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
3094 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3095 pub sessions: Vec<SessionInfo>,
3096 #[serde(default)]
3100 pub next_cursor: Option<SessionListCursor>,
3101 #[serde_as(deserialize_as = "DefaultOnError")]
3107 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3108 #[serde(default)]
3109 #[serde(rename = "_meta")]
3110 pub meta: Option<Meta>,
3111}
3112
3113impl ListSessionsResponse {
3114 #[must_use]
3116 pub fn new(sessions: Vec<SessionInfo>) -> Self {
3117 Self {
3118 sessions,
3119 next_cursor: None,
3120 meta: None,
3121 }
3122 }
3123
3124 #[must_use]
3126 pub fn next_cursor(mut self, next_cursor: impl IntoOption<SessionListCursor>) -> Self {
3127 self.next_cursor = next_cursor.into_option();
3128 self
3129 }
3130
3131 #[must_use]
3137 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3138 self.meta = meta.into_option();
3139 self
3140 }
3141}
3142
3143#[serde_as]
3149#[skip_serializing_none]
3150#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3151#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3152#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_DELETE_METHOD_NAME)))]
3153#[serde(rename_all = "camelCase")]
3154#[non_exhaustive]
3155pub struct DeleteSessionRequest {
3156 pub session_id: SessionId,
3158 #[serde_as(deserialize_as = "DefaultOnError")]
3164 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3165 #[serde(default)]
3166 #[serde(rename = "_meta")]
3167 pub meta: Option<Meta>,
3168}
3169
3170impl DeleteSessionRequest {
3171 #[must_use]
3173 pub fn new(session_id: impl Into<SessionId>) -> Self {
3174 Self {
3175 session_id: session_id.into(),
3176 meta: None,
3177 }
3178 }
3179
3180 #[must_use]
3186 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3187 self.meta = meta.into_option();
3188 self
3189 }
3190}
3191
3192crate::serde_util::default_on_null! {
3193 #[serde_as]
3195 #[skip_serializing_none]
3196 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3197 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3198 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_DELETE_METHOD_NAME)))]
3199 #[serde(rename_all = "camelCase")]
3200 #[non_exhaustive]
3201 pub struct DeleteSessionResponse {
3202 #[serde_as(deserialize_as = "DefaultOnError")]
3208 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3209 #[serde(default)]
3210 #[serde(rename = "_meta")]
3211 pub meta: Option<Meta>,
3212 }
3213}
3214
3215impl DeleteSessionResponse {
3216 #[must_use]
3218 pub fn new() -> Self {
3219 Self::default()
3220 }
3221
3222 #[must_use]
3228 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3229 self.meta = meta.into_option();
3230 self
3231 }
3232}
3233
3234#[cfg(feature = "unstable_session_archive")]
3250#[serde_as]
3251#[skip_serializing_none]
3252#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3253#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3254#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_ARCHIVE_METHOD_NAME)))]
3255#[serde(rename_all = "camelCase")]
3256#[non_exhaustive]
3257pub struct ArchiveSessionRequest {
3258 pub session_id: SessionId,
3260 #[serde_as(deserialize_as = "DefaultOnError")]
3266 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3267 #[serde(default)]
3268 #[serde(rename = "_meta")]
3269 pub meta: Option<Meta>,
3270}
3271
3272#[cfg(feature = "unstable_session_archive")]
3273impl ArchiveSessionRequest {
3274 #[must_use]
3276 pub fn new(session_id: impl Into<SessionId>) -> Self {
3277 Self {
3278 session_id: session_id.into(),
3279 meta: None,
3280 }
3281 }
3282
3283 #[must_use]
3289 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3290 self.meta = meta.into_option();
3291 self
3292 }
3293}
3294
3295#[cfg(feature = "unstable_session_archive")]
3296crate::serde_util::default_on_null! {
3297 #[serde_as]
3303 #[skip_serializing_none]
3304 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3305 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3306 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_ARCHIVE_METHOD_NAME)))]
3307 #[serde(rename_all = "camelCase")]
3308 #[non_exhaustive]
3309 pub struct ArchiveSessionResponse {
3310 #[serde_as(deserialize_as = "DefaultOnError")]
3316 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3317 #[serde(default)]
3318 #[serde(rename = "_meta")]
3319 pub meta: Option<Meta>,
3320 }
3321}
3322
3323#[cfg(feature = "unstable_session_archive")]
3324impl ArchiveSessionResponse {
3325 #[must_use]
3327 pub fn new() -> Self {
3328 Self::default()
3329 }
3330
3331 #[must_use]
3337 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3338 self.meta = meta.into_option();
3339 self
3340 }
3341}
3342
3343#[cfg(feature = "unstable_session_archive")]
3358#[serde_as]
3359#[skip_serializing_none]
3360#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3361#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3362#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_UNARCHIVE_METHOD_NAME)))]
3363#[serde(rename_all = "camelCase")]
3364#[non_exhaustive]
3365pub struct UnarchiveSessionRequest {
3366 pub session_id: SessionId,
3368 #[serde_as(deserialize_as = "DefaultOnError")]
3374 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3375 #[serde(default)]
3376 #[serde(rename = "_meta")]
3377 pub meta: Option<Meta>,
3378}
3379
3380#[cfg(feature = "unstable_session_archive")]
3381impl UnarchiveSessionRequest {
3382 #[must_use]
3384 pub fn new(session_id: impl Into<SessionId>) -> Self {
3385 Self {
3386 session_id: session_id.into(),
3387 meta: None,
3388 }
3389 }
3390
3391 #[must_use]
3397 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3398 self.meta = meta.into_option();
3399 self
3400 }
3401}
3402
3403#[cfg(feature = "unstable_session_archive")]
3404crate::serde_util::default_on_null! {
3405 #[serde_as]
3411 #[skip_serializing_none]
3412 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3413 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3414 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_UNARCHIVE_METHOD_NAME)))]
3415 #[serde(rename_all = "camelCase")]
3416 #[non_exhaustive]
3417 pub struct UnarchiveSessionResponse {
3418 #[serde_as(deserialize_as = "DefaultOnError")]
3424 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3425 #[serde(default)]
3426 #[serde(rename = "_meta")]
3427 pub meta: Option<Meta>,
3428 }
3429}
3430
3431#[cfg(feature = "unstable_session_archive")]
3432impl UnarchiveSessionResponse {
3433 #[must_use]
3435 pub fn new() -> Self {
3436 Self::default()
3437 }
3438
3439 #[must_use]
3445 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3446 self.meta = meta.into_option();
3447 self
3448 }
3449}
3450
3451#[cfg(feature = "unstable_session_archive")]
3460#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3461#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
3462#[serde(rename_all = "snake_case")]
3463#[non_exhaustive]
3464pub enum SessionArchiveFilter {
3465 #[default]
3467 Exclude,
3468 Include,
3470 Only,
3472 #[serde(untagged)]
3478 Other(String),
3479}
3480
3481#[serde_as]
3483#[skip_serializing_none]
3484#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3485#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3486#[serde(rename_all = "camelCase")]
3487#[non_exhaustive]
3488pub struct SessionInfo {
3489 pub session_id: SessionId,
3491 pub cwd: AbsolutePath,
3493 #[serde_as(deserialize_as = "DefaultOnNull")]
3499 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
3500 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3501 pub additional_directories: Vec<AbsolutePath>,
3502
3503 #[serde_as(deserialize_as = "DefaultOnError")]
3507 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3508 #[serde(default)]
3509 pub title: Option<String>,
3510 #[serde_as(deserialize_as = "DefaultOnError")]
3514 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "format" = "date-time")))]
3515 #[serde(default)]
3516 pub updated_at: Option<String>,
3517 #[cfg(feature = "unstable_session_archive")]
3526 #[serde_as(deserialize_as = "DefaultOnError")]
3527 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3528 #[serde(default)]
3529 pub archived: Option<bool>,
3530 #[serde_as(deserialize_as = "DefaultOnError")]
3536 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3537 #[serde(default)]
3538 #[serde(rename = "_meta")]
3539 pub meta: Option<Meta>,
3540}
3541
3542impl SessionInfo {
3543 #[must_use]
3545 pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
3546 Self {
3547 session_id: session_id.into(),
3548 cwd: cwd.into(),
3549 additional_directories: vec![],
3550 title: None,
3551 updated_at: None,
3552 #[cfg(feature = "unstable_session_archive")]
3553 archived: None,
3554 meta: None,
3555 }
3556 }
3557
3558 #[must_use]
3560 pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
3561 where
3562 I: IntoIterator<Item = P>,
3563 P: Into<AbsolutePath>,
3564 {
3565 self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
3566 self
3567 }
3568
3569 #[must_use]
3571 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
3572 self.title = title.into_option();
3573 self
3574 }
3575
3576 #[must_use]
3578 pub fn updated_at(mut self, updated_at: impl IntoOption<String>) -> Self {
3579 self.updated_at = updated_at.into_option();
3580 self
3581 }
3582
3583 #[cfg(feature = "unstable_session_archive")]
3589 #[must_use]
3590 pub fn archived(mut self, archived: impl IntoOption<bool>) -> Self {
3591 self.archived = archived.into_option();
3592 self
3593 }
3594
3595 #[must_use]
3601 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3602 self.meta = meta.into_option();
3603 self
3604 }
3605}
3606
3607#[cfg(feature = "unstable_session_set_title")]
3623#[serde_as]
3624#[skip_serializing_none]
3625#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3626#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3627#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_TITLE_METHOD_NAME)))]
3628#[serde(rename_all = "camelCase")]
3629#[non_exhaustive]
3630pub struct SetSessionTitleRequest {
3631 pub session_id: SessionId,
3633 pub title: String,
3640 #[serde_as(deserialize_as = "DefaultOnError")]
3646 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3647 #[serde(default)]
3648 #[serde(rename = "_meta")]
3649 pub meta: Option<Meta>,
3650}
3651
3652#[cfg(feature = "unstable_session_set_title")]
3653impl SetSessionTitleRequest {
3654 #[must_use]
3656 pub fn new(session_id: impl Into<SessionId>, title: impl Into<String>) -> Self {
3657 Self {
3658 session_id: session_id.into(),
3659 title: title.into(),
3660 meta: None,
3661 }
3662 }
3663
3664 #[must_use]
3670 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3671 self.meta = meta.into_option();
3672 self
3673 }
3674}
3675
3676#[cfg(feature = "unstable_session_set_title")]
3682#[serde_as]
3683#[skip_serializing_none]
3684#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3685#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3686#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_TITLE_METHOD_NAME)))]
3687#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "sessionInfo", "field": "title", "value": "title"}]})))]
3688#[serde(rename_all = "camelCase")]
3689#[non_exhaustive]
3690pub struct SetSessionTitleResponse {
3691 pub title: String,
3696 #[serde_as(deserialize_as = "DefaultOnError")]
3702 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3703 #[serde(default)]
3704 #[serde(rename = "_meta")]
3705 pub meta: Option<Meta>,
3706}
3707
3708#[cfg(feature = "unstable_session_set_title")]
3709impl SetSessionTitleResponse {
3710 #[must_use]
3712 pub fn new(title: impl Into<String>) -> Self {
3713 Self {
3714 title: title.into(),
3715 meta: None,
3716 }
3717 }
3718
3719 #[must_use]
3725 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3726 self.meta = meta.into_option();
3727 self
3728 }
3729}
3730
3731#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3735#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3736#[serde(transparent)]
3737#[from(forward)]
3738#[non_exhaustive]
3739pub struct SessionConfigId(pub Arc<str>);
3740
3741impl SessionConfigId {
3742 #[must_use]
3744 pub fn new(id: impl Into<Self>) -> Self {
3745 id.into()
3746 }
3747}
3748
3749#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3751#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3752#[serde(transparent)]
3753#[from(forward)]
3754#[non_exhaustive]
3755pub struct SessionConfigValueId(pub Arc<str>);
3756
3757impl SessionConfigValueId {
3758 #[must_use]
3760 pub fn new(id: impl Into<Self>) -> Self {
3761 id.into()
3762 }
3763}
3764
3765#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3767#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3768#[serde(transparent)]
3769#[from(forward)]
3770#[non_exhaustive]
3771pub struct SessionConfigGroupId(pub Arc<str>);
3772
3773impl SessionConfigGroupId {
3774 #[must_use]
3776 pub fn new(id: impl Into<Self>) -> Self {
3777 id.into()
3778 }
3779}
3780
3781#[serde_as]
3783#[skip_serializing_none]
3784#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3785#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3786#[serde(rename_all = "camelCase")]
3787#[non_exhaustive]
3788pub struct SessionConfigSelectOption {
3789 pub value: SessionConfigValueId,
3791 pub name: String,
3793 #[serde_as(deserialize_as = "DefaultOnError")]
3797 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3798 #[serde(default)]
3799 pub description: Option<String>,
3800 #[serde_as(deserialize_as = "DefaultOnError")]
3806 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3807 #[serde(default)]
3808 #[serde(rename = "_meta")]
3809 pub meta: Option<Meta>,
3810}
3811
3812impl SessionConfigSelectOption {
3813 #[must_use]
3815 pub fn new(value: impl Into<SessionConfigValueId>, name: impl Into<String>) -> Self {
3816 Self {
3817 value: value.into(),
3818 name: name.into(),
3819 description: None,
3820 meta: None,
3821 }
3822 }
3823
3824 #[must_use]
3826 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
3827 self.description = description.into_option();
3828 self
3829 }
3830
3831 #[must_use]
3837 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3838 self.meta = meta.into_option();
3839 self
3840 }
3841}
3842
3843#[serde_as]
3845#[skip_serializing_none]
3846#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3847#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3848#[serde(rename_all = "camelCase")]
3849#[non_exhaustive]
3850pub struct SessionConfigSelectGroup {
3851 pub group_id: SessionConfigGroupId,
3853 pub name: String,
3855 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
3857 #[cfg_attr(feature = "schemars", schemars(length(min = 1), extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3858 pub options: Vec<SessionConfigSelectOption>,
3859 #[serde_as(deserialize_as = "DefaultOnError")]
3865 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3866 #[serde(default)]
3867 #[serde(rename = "_meta")]
3868 pub meta: Option<Meta>,
3869}
3870
3871impl SessionConfigSelectGroup {
3872 #[must_use]
3874 pub fn new(
3875 group_id: impl Into<SessionConfigGroupId>,
3876 name: impl Into<String>,
3877 options: Vec<SessionConfigSelectOption>,
3878 ) -> Self {
3879 Self {
3880 group_id: group_id.into(),
3881 name: name.into(),
3882 options,
3883 meta: None,
3884 }
3885 }
3886
3887 #[must_use]
3893 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3894 self.meta = meta.into_option();
3895 self
3896 }
3897}
3898
3899#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3901#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3902#[serde(untagged)]
3903#[non_exhaustive]
3904pub enum SessionConfigSelectOptions {
3905 Ungrouped(
3907 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))] Vec<SessionConfigSelectOption>,
3908 ),
3909 Grouped(
3911 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))] Vec<SessionConfigSelectGroup>,
3912 ),
3913}
3914
3915impl From<Vec<SessionConfigSelectOption>> for SessionConfigSelectOptions {
3916 fn from(options: Vec<SessionConfigSelectOption>) -> Self {
3917 SessionConfigSelectOptions::Ungrouped(options)
3918 }
3919}
3920
3921impl From<Vec<SessionConfigSelectGroup>> for SessionConfigSelectOptions {
3922 fn from(groups: Vec<SessionConfigSelectGroup>) -> Self {
3923 SessionConfigSelectOptions::Grouped(groups)
3924 }
3925}
3926
3927#[skip_serializing_none]
3929#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3930#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3931#[serde(rename_all = "camelCase")]
3932#[non_exhaustive]
3933pub struct SessionConfigSelect {
3934 pub current_value: SessionConfigValueId,
3936 pub options: SessionConfigSelectOptions,
3939}
3940
3941impl SessionConfigSelect {
3942 #[must_use]
3944 pub fn new(
3945 current_value: impl Into<SessionConfigValueId>,
3946 options: impl Into<SessionConfigSelectOptions>,
3947 ) -> Self {
3948 Self {
3949 current_value: current_value.into(),
3950 options: options.into(),
3951 }
3952 }
3953}
3954
3955#[skip_serializing_none]
3957#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3958#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3959#[serde(rename_all = "camelCase")]
3960#[non_exhaustive]
3961pub struct SessionConfigBoolean {
3962 pub current_value: bool,
3964}
3965
3966impl SessionConfigBoolean {
3967 #[must_use]
3969 pub fn new(current_value: bool) -> Self {
3970 Self { current_value }
3971 }
3972}
3973
3974#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3984#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3985#[serde(rename_all = "snake_case")]
3986#[non_exhaustive]
3987pub enum SessionConfigOptionCategory {
3988 Mode,
3990 Model,
3992 ModelConfig,
3994 #[cfg(feature = "unstable_speed_config_category")]
4000 Speed,
4001 ThoughtLevel,
4003 #[serde(untagged)]
4009 Other(String),
4010}
4011
4012#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4014#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4015#[serde(tag = "type", rename_all = "snake_case")]
4016#[non_exhaustive]
4017pub enum SessionConfigKind {
4018 Select(SessionConfigSelect),
4020 Boolean(SessionConfigBoolean),
4022 #[serde(untagged)]
4032 Other(OtherSessionConfigKind),
4033}
4034
4035#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4037#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4038#[cfg_attr(feature = "schemars", schemars(inline))]
4039#[cfg_attr(feature = "schemars", schemars(transform = other_session_config_kind_schema))]
4040#[serde(rename_all = "camelCase")]
4041#[non_exhaustive]
4042pub struct OtherSessionConfigKind {
4043 #[serde(rename = "type")]
4049 pub type_: String,
4050 #[serde(flatten)]
4052 pub fields: IndexMap<String, serde_json::Value>,
4053}
4054
4055impl OtherSessionConfigKind {
4056 #[must_use]
4058 pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
4059 fields.shift_remove("type");
4060 fields.shift_remove("_meta");
4061 Self {
4062 type_: type_.into(),
4063 fields,
4064 }
4065 }
4066}
4067
4068impl<'de> Deserialize<'de> for OtherSessionConfigKind {
4069 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4070 where
4071 D: serde::Deserializer<'de>,
4072 {
4073 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4074 let type_ = fields
4075 .shift_remove("type")
4076 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4077 let serde_json::Value::String(type_) = type_ else {
4078 return Err(serde::de::Error::custom("`type` must be a string"));
4079 };
4080
4081 if is_known_session_config_kind_type(&type_) {
4082 return Err(serde::de::Error::custom(format!(
4083 "known session configuration option `{type_}` did not match its schema"
4084 )));
4085 }
4086
4087 Ok(Self { type_, fields })
4088 }
4089}
4090
4091fn is_known_session_config_kind_type(type_: &str) -> bool {
4092 matches!(type_, "select" | "boolean")
4093}
4094
4095#[cfg(feature = "schemars")]
4096fn other_session_config_kind_schema(schema: &mut Schema) {
4097 super::schema_util::reject_known_string_discriminators(schema, "type", &["select", "boolean"]);
4098}
4099
4100#[serde_as]
4102#[skip_serializing_none]
4103#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4104#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4105#[serde(rename_all = "camelCase")]
4106#[non_exhaustive]
4107pub struct SessionConfigOption {
4108 pub config_id: SessionConfigId,
4110 pub name: String,
4112 #[serde_as(deserialize_as = "DefaultOnError")]
4116 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4117 #[serde(default)]
4118 pub description: Option<String>,
4119 #[serde_as(deserialize_as = "DefaultOnError")]
4123 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4124 #[serde(default)]
4125 pub category: Option<SessionConfigOptionCategory>,
4126 #[serde(flatten)]
4128 pub kind: SessionConfigKind,
4129 #[serde_as(deserialize_as = "DefaultOnError")]
4135 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4136 #[serde(default)]
4137 #[serde(rename = "_meta")]
4138 pub meta: Option<Meta>,
4139}
4140
4141impl SessionConfigOption {
4142 #[must_use]
4144 pub fn new(
4145 config_id: impl Into<SessionConfigId>,
4146 name: impl Into<String>,
4147 kind: SessionConfigKind,
4148 ) -> Self {
4149 Self {
4150 config_id: config_id.into(),
4151 name: name.into(),
4152 description: None,
4153 category: None,
4154 kind,
4155 meta: None,
4156 }
4157 }
4158
4159 #[must_use]
4161 pub fn select(
4162 config_id: impl Into<SessionConfigId>,
4163 name: impl Into<String>,
4164 current_value: impl Into<SessionConfigValueId>,
4165 options: impl Into<SessionConfigSelectOptions>,
4166 ) -> Self {
4167 Self::new(
4168 config_id,
4169 name,
4170 SessionConfigKind::Select(SessionConfigSelect::new(current_value, options)),
4171 )
4172 }
4173
4174 #[must_use]
4176 pub fn boolean(
4177 config_id: impl Into<SessionConfigId>,
4178 name: impl Into<String>,
4179 current_value: bool,
4180 ) -> Self {
4181 Self::new(
4182 config_id,
4183 name,
4184 SessionConfigKind::Boolean(SessionConfigBoolean::new(current_value)),
4185 )
4186 }
4187
4188 #[must_use]
4190 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
4191 self.description = description.into_option();
4192 self
4193 }
4194
4195 #[must_use]
4197 pub fn category(mut self, category: impl IntoOption<SessionConfigOptionCategory>) -> Self {
4198 self.category = category.into_option();
4199 self
4200 }
4201
4202 #[must_use]
4208 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4209 self.meta = meta.into_option();
4210 self
4211 }
4212}
4213
4214#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4223#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4224#[serde(tag = "type", rename_all = "snake_case")]
4225#[non_exhaustive]
4226pub enum SessionConfigOptionValue {
4227 Id {
4229 value: SessionConfigValueId,
4231 },
4232 Boolean {
4234 value: bool,
4236 },
4237 #[serde(untagged)]
4246 Other(Box<OtherSessionConfigOptionValue>),
4247}
4248
4249#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4251#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4252#[cfg_attr(feature = "schemars", schemars(inline))]
4253#[cfg_attr(feature = "schemars", schemars(transform = other_session_config_option_value_schema))]
4254#[serde(rename_all = "camelCase")]
4255#[non_exhaustive]
4256pub struct OtherSessionConfigOptionValue {
4257 #[serde(rename = "type")]
4263 pub type_: String,
4264 pub value: serde_json::Value,
4266 #[serde(flatten)]
4268 pub fields: IndexMap<String, serde_json::Value>,
4269}
4270
4271impl OtherSessionConfigOptionValue {
4272 #[must_use]
4274 pub fn new(
4275 type_: impl Into<String>,
4276 value: serde_json::Value,
4277 mut fields: IndexMap<String, serde_json::Value>,
4278 ) -> Self {
4279 fields.shift_remove("type");
4280 fields.shift_remove("value");
4281 fields.shift_remove("_meta");
4282 Self {
4283 type_: type_.into(),
4284 value,
4285 fields,
4286 }
4287 }
4288}
4289
4290impl<'de> Deserialize<'de> for OtherSessionConfigOptionValue {
4291 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4292 where
4293 D: serde::Deserializer<'de>,
4294 {
4295 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4296 let type_ = fields
4297 .shift_remove("type")
4298 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4299 let serde_json::Value::String(type_) = type_ else {
4300 return Err(serde::de::Error::custom("`type` must be a string"));
4301 };
4302
4303 if is_known_session_config_option_value_type(&type_) {
4304 return Err(serde::de::Error::custom(format!(
4305 "known session configuration option value `{type_}` did not match its schema"
4306 )));
4307 }
4308
4309 let value = fields
4310 .shift_remove("value")
4311 .ok_or_else(|| serde::de::Error::missing_field("value"))?;
4312
4313 Ok(Self {
4314 type_,
4315 value,
4316 fields,
4317 })
4318 }
4319}
4320
4321impl<'de> Deserialize<'de> for SessionConfigOptionValue {
4322 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4323 where
4324 D: serde::Deserializer<'de>,
4325 {
4326 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4327 let type_ = fields.shift_remove("type");
4328 let value = fields
4329 .shift_remove("value")
4330 .ok_or_else(|| serde::de::Error::missing_field("value"))?;
4331
4332 let type_ = type_.ok_or_else(|| serde::de::Error::missing_field("type"))?;
4333
4334 let serde_json::Value::String(type_) = type_ else {
4335 return Err(serde::de::Error::custom("`type` must be a string"));
4336 };
4337
4338 match type_.as_str() {
4339 "id" => {
4340 let value = serde_json::from_value(value).map_err(|error| {
4341 serde::de::Error::custom(format!(
4342 "`value` must be a string for `type: id`: {error}"
4343 ))
4344 })?;
4345 Ok(Self::Id { value })
4346 }
4347 "boolean" => {
4348 let value = serde_json::from_value(value).map_err(|error| {
4349 serde::de::Error::custom(format!(
4350 "`value` must be a boolean for `type: boolean`: {error}"
4351 ))
4352 })?;
4353 Ok(Self::Boolean { value })
4354 }
4355 _ => Ok(OtherSessionConfigOptionValue {
4356 type_,
4357 value,
4358 fields,
4359 }
4360 .into()),
4361 }
4362 }
4363}
4364
4365fn is_known_session_config_option_value_type(type_: &str) -> bool {
4366 matches!(type_, "id" | "boolean")
4367}
4368
4369#[cfg(feature = "schemars")]
4370fn other_session_config_option_value_schema(schema: &mut Schema) {
4371 super::schema_util::reject_known_string_discriminators(schema, "type", &["id", "boolean"]);
4372}
4373
4374impl SessionConfigOptionValue {
4375 #[must_use]
4377 pub fn id(id: impl Into<SessionConfigValueId>) -> Self {
4378 Self::Id { value: id.into() }
4379 }
4380
4381 #[must_use]
4383 pub fn boolean(val: bool) -> Self {
4384 Self::Boolean { value: val }
4385 }
4386
4387 #[must_use]
4390 pub fn as_id(&self) -> Option<&SessionConfigValueId> {
4391 match self {
4392 Self::Id { value } => Some(value),
4393 _ => None,
4394 }
4395 }
4396
4397 #[must_use]
4399 pub fn as_bool(&self) -> Option<bool> {
4400 match self {
4401 Self::Boolean { value } => Some(*value),
4402 _ => None,
4403 }
4404 }
4405}
4406
4407impl From<SessionConfigValueId> for SessionConfigOptionValue {
4408 fn from(value: SessionConfigValueId) -> Self {
4409 Self::Id { value }
4410 }
4411}
4412
4413impl From<bool> for SessionConfigOptionValue {
4414 fn from(value: bool) -> Self {
4415 Self::Boolean { value }
4416 }
4417}
4418
4419impl From<OtherSessionConfigOptionValue> for SessionConfigOptionValue {
4420 fn from(value: OtherSessionConfigOptionValue) -> Self {
4421 Self::Other(Box::new(value))
4422 }
4423}
4424
4425impl From<&str> for SessionConfigOptionValue {
4426 fn from(value: &str) -> Self {
4427 Self::Id {
4428 value: SessionConfigValueId::new(value),
4429 }
4430 }
4431}
4432
4433#[serde_as]
4444#[skip_serializing_none]
4445#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4446#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4447#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_CONFIG_OPTION_METHOD_NAME)))]
4448#[serde(rename_all = "camelCase")]
4449#[non_exhaustive]
4450pub struct SetSessionConfigOptionRequest {
4451 pub session_id: SessionId,
4453 pub config_id: SessionConfigId,
4455 #[serde(flatten)]
4459 pub value: SessionConfigOptionValue,
4460 #[serde_as(deserialize_as = "DefaultOnError")]
4466 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4467 #[serde(default)]
4468 #[serde(rename = "_meta")]
4469 pub meta: Option<Meta>,
4470}
4471
4472impl SetSessionConfigOptionRequest {
4473 #[must_use]
4475 pub fn new(
4476 session_id: impl Into<SessionId>,
4477 config_id: impl Into<SessionConfigId>,
4478 value: impl Into<SessionConfigOptionValue>,
4479 ) -> Self {
4480 Self {
4481 session_id: session_id.into(),
4482 config_id: config_id.into(),
4483 value: value.into(),
4484 meta: None,
4485 }
4486 }
4487
4488 #[must_use]
4494 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4495 self.meta = meta.into_option();
4496 self
4497 }
4498}
4499
4500#[serde_as]
4502#[skip_serializing_none]
4503#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4504#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4505#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_CONFIG_OPTION_METHOD_NAME)))]
4506#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}]})))]
4507#[serde(rename_all = "camelCase")]
4508#[non_exhaustive]
4509pub struct SetSessionConfigOptionResponse {
4510 #[serde_as(deserialize_as = "VecSkipError<_>")]
4512 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
4513 pub config_options: Vec<SessionConfigOption>,
4514 #[serde_as(deserialize_as = "DefaultOnError")]
4520 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4521 #[serde(default)]
4522 #[serde(rename = "_meta")]
4523 pub meta: Option<Meta>,
4524}
4525
4526impl SetSessionConfigOptionResponse {
4527 #[must_use]
4529 pub fn new(config_options: Vec<SessionConfigOption>) -> Self {
4530 Self {
4531 config_options,
4532 meta: None,
4533 }
4534 }
4535
4536 #[must_use]
4542 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4543 self.meta = meta.into_option();
4544 self
4545 }
4546}
4547
4548#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4557#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4558#[serde(tag = "type", rename_all = "snake_case")]
4559#[non_exhaustive]
4560pub enum McpServer {
4561 Http(McpServerHttp),
4565 #[cfg(feature = "unstable_mcp_over_acp")]
4574 Acp(McpServerAcp),
4575 Stdio(McpServerStdio),
4579 #[serde(untagged)]
4590 Other(OtherMcpServer),
4591}
4592
4593#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4595#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4596#[cfg_attr(feature = "schemars", schemars(inline))]
4597#[cfg_attr(feature = "schemars", schemars(transform = other_mcp_server_schema))]
4598#[serde(rename_all = "camelCase")]
4599#[non_exhaustive]
4600pub struct OtherMcpServer {
4601 #[serde(rename = "type")]
4607 pub type_: String,
4608 #[serde(flatten)]
4610 pub fields: IndexMap<String, serde_json::Value>,
4611}
4612
4613impl OtherMcpServer {
4614 #[must_use]
4616 pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
4617 fields.shift_remove("type");
4618 Self {
4619 type_: type_.into(),
4620 fields,
4621 }
4622 }
4623}
4624
4625impl<'de> Deserialize<'de> for OtherMcpServer {
4626 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4627 where
4628 D: serde::Deserializer<'de>,
4629 {
4630 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4631 let type_ = fields
4632 .shift_remove("type")
4633 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4634 let serde_json::Value::String(type_) = type_ else {
4635 return Err(serde::de::Error::custom("`type` must be a string"));
4636 };
4637
4638 if is_known_mcp_server_type(&type_) {
4639 return Err(serde::de::Error::custom(format!(
4640 "known MCP server transport `{type_}` did not match its schema"
4641 )));
4642 }
4643
4644 Ok(Self { type_, fields })
4645 }
4646}
4647
4648fn is_known_mcp_server_type(type_: &str) -> bool {
4649 match type_ {
4650 "http" | "stdio" => true,
4651 #[cfg(feature = "unstable_mcp_over_acp")]
4652 "acp" => true,
4653 _ => false,
4654 }
4655}
4656
4657#[cfg(feature = "schemars")]
4658fn other_mcp_server_schema(schema: &mut Schema) {
4659 super::schema_util::reject_known_string_discriminators(
4660 schema,
4661 "type",
4662 &[
4663 "http",
4664 "stdio",
4665 #[cfg(feature = "unstable_mcp_over_acp")]
4666 "acp",
4667 ],
4668 );
4669}
4670
4671#[serde_as]
4673#[skip_serializing_none]
4674#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4675#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4676#[serde(rename_all = "camelCase")]
4677#[non_exhaustive]
4678pub struct McpServerHttp {
4679 pub name: String,
4683 #[cfg_attr(feature = "schemars", schemars(url))]
4685 pub url: String,
4686 #[serde_as(deserialize_as = "DefaultOnNull")]
4689 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4690 #[serde(default, skip_serializing_if = "Vec::is_empty")]
4691 pub headers: Vec<HttpHeader>,
4692 #[serde_as(deserialize_as = "DefaultOnError")]
4698 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4699 #[serde(default)]
4700 #[serde(rename = "_meta")]
4701 pub meta: Option<Meta>,
4702}
4703
4704impl McpServerHttp {
4705 #[must_use]
4707 pub fn new(name: impl Into<String>, url: impl Into<String>) -> Self {
4708 Self {
4709 name: name.into(),
4710 url: url.into(),
4711 headers: Vec::new(),
4712 meta: None,
4713 }
4714 }
4715
4716 #[must_use]
4719 pub fn headers(mut self, headers: Vec<HttpHeader>) -> Self {
4720 self.headers = headers;
4721 self
4722 }
4723
4724 #[must_use]
4730 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4731 self.meta = meta.into_option();
4732 self
4733 }
4734}
4735
4736#[cfg(feature = "unstable_mcp_over_acp")]
4745#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4746#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
4747#[serde(transparent)]
4748#[from(forward)]
4749#[non_exhaustive]
4750pub struct McpServerAcpId(pub Arc<str>);
4751
4752#[cfg(feature = "unstable_mcp_over_acp")]
4753impl McpServerAcpId {
4754 #[must_use]
4756 pub fn new(id: impl Into<Self>) -> Self {
4757 id.into()
4758 }
4759}
4760
4761#[serde_as]
4770#[skip_serializing_none]
4771#[cfg(feature = "unstable_mcp_over_acp")]
4772#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4773#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4774#[serde(rename_all = "camelCase")]
4775#[non_exhaustive]
4776pub struct McpServerAcp {
4777 pub name: String,
4781 pub server_id: McpServerAcpId,
4786 #[serde_as(deserialize_as = "DefaultOnError")]
4792 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4793 #[serde(default)]
4794 #[serde(rename = "_meta")]
4795 pub meta: Option<Meta>,
4796}
4797
4798#[cfg(feature = "unstable_mcp_over_acp")]
4799impl McpServerAcp {
4800 #[must_use]
4802 pub fn new(name: impl Into<String>, server_id: impl Into<McpServerAcpId>) -> Self {
4803 Self {
4804 name: name.into(),
4805 server_id: server_id.into(),
4806 meta: None,
4807 }
4808 }
4809
4810 #[must_use]
4816 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4817 self.meta = meta.into_option();
4818 self
4819 }
4820}
4821
4822#[serde_as]
4824#[skip_serializing_none]
4825#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4826#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4827#[serde(rename_all = "camelCase")]
4828#[non_exhaustive]
4829pub struct McpServerStdio {
4830 pub name: String,
4834 pub command: AbsolutePath,
4838 #[serde_as(deserialize_as = "DefaultOnNull")]
4840 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4841 #[serde(default, skip_serializing_if = "Vec::is_empty")]
4842 pub args: Vec<String>,
4843 #[serde_as(deserialize_as = "DefaultOnNull")]
4846 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4847 #[serde(default, skip_serializing_if = "Vec::is_empty")]
4848 pub env: Vec<EnvVariable>,
4849 #[serde_as(deserialize_as = "DefaultOnError")]
4855 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4856 #[serde(default)]
4857 #[serde(rename = "_meta")]
4858 pub meta: Option<Meta>,
4859}
4860
4861impl McpServerStdio {
4862 #[must_use]
4864 pub fn new(name: impl Into<String>, command: impl Into<AbsolutePath>) -> Self {
4865 Self {
4866 name: name.into(),
4867 command: command.into(),
4868 args: Vec::new(),
4869 env: Vec::new(),
4870 meta: None,
4871 }
4872 }
4873
4874 #[must_use]
4876 pub fn args(mut self, args: Vec<String>) -> Self {
4877 self.args = args;
4878 self
4879 }
4880
4881 #[must_use]
4884 pub fn env(mut self, env: Vec<EnvVariable>) -> Self {
4885 self.env = env;
4886 self
4887 }
4888
4889 #[must_use]
4895 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4896 self.meta = meta.into_option();
4897 self
4898 }
4899}
4900
4901#[serde_as]
4903#[skip_serializing_none]
4904#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4905#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4906#[serde(rename_all = "camelCase")]
4907#[non_exhaustive]
4908pub struct EnvVariable {
4909 pub name: String,
4911 pub value: String,
4913 #[serde_as(deserialize_as = "DefaultOnError")]
4919 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4920 #[serde(default)]
4921 #[serde(rename = "_meta")]
4922 pub meta: Option<Meta>,
4923}
4924
4925impl EnvVariable {
4926 #[must_use]
4928 pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
4929 Self {
4930 name: name.into(),
4931 value: value.into(),
4932 meta: None,
4933 }
4934 }
4935
4936 #[must_use]
4942 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4943 self.meta = meta.into_option();
4944 self
4945 }
4946}
4947
4948#[serde_as]
4950#[skip_serializing_none]
4951#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4952#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4953#[serde(rename_all = "camelCase")]
4954#[non_exhaustive]
4955pub struct HttpHeader {
4956 pub name: String,
4958 pub value: String,
4960 #[serde_as(deserialize_as = "DefaultOnError")]
4966 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4967 #[serde(default)]
4968 #[serde(rename = "_meta")]
4969 pub meta: Option<Meta>,
4970}
4971
4972impl HttpHeader {
4973 #[must_use]
4975 pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
4976 Self {
4977 name: name.into(),
4978 value: value.into(),
4979 meta: None,
4980 }
4981 }
4982
4983 #[must_use]
4989 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4990 self.meta = meta.into_option();
4991 self
4992 }
4993}
4994
4995#[serde_as]
5004#[skip_serializing_none]
5005#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5006#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5007#[serde(rename_all = "camelCase")]
5008#[non_exhaustive]
5009pub struct SystemPrompt {
5010 pub mode: SystemPromptMode,
5015 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
5025 pub content: Vec<ContentBlock>,
5026 #[serde_as(deserialize_as = "DefaultOnError")]
5032 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5033 #[serde(default)]
5034 #[serde(rename = "_meta")]
5035 pub meta: Option<Meta>,
5036}
5037
5038impl SystemPrompt {
5039 #[must_use]
5044 pub fn new(content: Vec<ContentBlock>) -> Self {
5045 Self {
5046 mode: SystemPromptMode::default(),
5047 content,
5048 meta: None,
5049 }
5050 }
5051
5052 #[must_use]
5054 pub fn mode(mut self, mode: SystemPromptMode) -> Self {
5055 self.mode = mode;
5056 self
5057 }
5058
5059 #[must_use]
5065 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5066 self.meta = meta.into_option();
5067 self
5068 }
5069}
5070
5071#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5077#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
5078#[serde(rename_all = "snake_case")]
5079#[non_exhaustive]
5080pub enum SystemPromptMode {
5081 #[default]
5088 Append,
5089 Override,
5098 #[serde(untagged)]
5104 Other(String),
5105}
5106
5107#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5116#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash, Display)]
5117#[serde(transparent)]
5118pub struct IdempotencyKey(
5119 #[cfg_attr(feature = "schemars", schemars(length(min = 1, max = 255)))] Arc<str>,
5120);
5121
5122impl IdempotencyKey {
5123 pub const MAX_LENGTH: usize = 255;
5125
5126 pub fn new(key: impl Into<Arc<str>>) -> Result<Self, InvalidIdempotencyKey> {
5133 let key = key.into();
5134 if key.is_empty() {
5135 return Err(InvalidIdempotencyKey::Empty);
5136 }
5137 if key.chars().nth(Self::MAX_LENGTH).is_some() {
5139 return Err(InvalidIdempotencyKey::TooLong);
5140 }
5141 Ok(Self(key))
5142 }
5143
5144 #[cfg(feature = "uuid")]
5151 #[must_use]
5152 pub fn generate() -> Self {
5153 uuid::Uuid::new_v4().into()
5154 }
5155
5156 #[must_use]
5158 pub fn as_str(&self) -> &str {
5159 &self.0
5160 }
5161}
5162
5163impl AsRef<str> for IdempotencyKey {
5164 fn as_ref(&self) -> &str {
5165 &self.0
5166 }
5167}
5168
5169#[cfg(feature = "uuid")]
5170impl From<uuid::Uuid> for IdempotencyKey {
5171 fn from(uuid: uuid::Uuid) -> Self {
5174 Self(uuid.to_string().into())
5175 }
5176}
5177
5178impl TryFrom<String> for IdempotencyKey {
5179 type Error = InvalidIdempotencyKey;
5180
5181 fn try_from(key: String) -> Result<Self, Self::Error> {
5182 Self::new(key)
5183 }
5184}
5185
5186impl TryFrom<&str> for IdempotencyKey {
5187 type Error = InvalidIdempotencyKey;
5188
5189 fn try_from(key: &str) -> Result<Self, Self::Error> {
5190 Self::new(key)
5191 }
5192}
5193
5194impl std::str::FromStr for IdempotencyKey {
5195 type Err = InvalidIdempotencyKey;
5196
5197 fn from_str(key: &str) -> Result<Self, Self::Err> {
5198 Self::new(key)
5199 }
5200}
5201
5202impl<'de> Deserialize<'de> for IdempotencyKey {
5205 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
5206 where
5207 D: serde::Deserializer<'de>,
5208 {
5209 let key = Arc::<str>::deserialize(deserializer)?;
5210 Self::new(key).map_err(serde::de::Error::custom)
5211 }
5212}
5213
5214#[derive(Debug, Clone, Copy, PartialEq, Eq, Display)]
5216#[non_exhaustive]
5217pub enum InvalidIdempotencyKey {
5218 #[display("idempotency key must not be empty")]
5220 Empty,
5221 #[display(
5223 "idempotency key must be at most {} characters",
5224 IdempotencyKey::MAX_LENGTH
5225 )]
5226 TooLong,
5227}
5228
5229impl std::error::Error for InvalidIdempotencyKey {}
5230
5231#[serde_as]
5237#[skip_serializing_none]
5238#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5239#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5240#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_PROMPT_METHOD_NAME)))]
5241#[serde(rename_all = "camelCase")]
5242#[non_exhaustive]
5243pub struct PromptRequest {
5244 pub session_id: SessionId,
5246 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
5263 pub prompt: Vec<ContentBlock>,
5264 #[serde(default)]
5286 pub idempotency_key: Option<IdempotencyKey>,
5287 #[serde_as(deserialize_as = "DefaultOnError")]
5293 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5294 #[serde(default)]
5295 #[serde(rename = "_meta")]
5296 pub meta: Option<Meta>,
5297}
5298
5299impl PromptRequest {
5300 #[must_use]
5302 pub fn new(session_id: impl Into<SessionId>, prompt: Vec<ContentBlock>) -> Self {
5303 Self {
5304 session_id: session_id.into(),
5305 prompt,
5306 idempotency_key: None,
5307 meta: None,
5308 }
5309 }
5310
5311 #[must_use]
5315 pub fn idempotency_key(mut self, idempotency_key: impl IntoOption<IdempotencyKey>) -> Self {
5316 self.idempotency_key = idempotency_key.into_option();
5317 self
5318 }
5319
5320 #[must_use]
5326 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5327 self.meta = meta.into_option();
5328 self
5329 }
5330}
5331
5332#[serde_as]
5343#[skip_serializing_none]
5344#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5345#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5346#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_PROMPT_METHOD_NAME)))]
5347#[serde(rename_all = "camelCase")]
5348#[non_exhaustive]
5349pub struct PromptResponse {
5350 pub message_id: MessageId,
5358 #[serde_as(deserialize_as = "DefaultOnError")]
5364 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5365 #[serde(default)]
5366 #[serde(rename = "_meta")]
5367 pub meta: Option<Meta>,
5368}
5369
5370impl PromptResponse {
5371 #[must_use]
5373 pub fn new(message_id: impl Into<MessageId>) -> Self {
5374 Self {
5375 message_id: message_id.into(),
5376 meta: None,
5377 }
5378 }
5379
5380 #[must_use]
5386 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5387 self.meta = meta.into_option();
5388 self
5389 }
5390}
5391
5392#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5396#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
5397#[serde(tag = "stopReason", rename_all = "snake_case")]
5398#[non_exhaustive]
5399pub enum StopReason {
5400 EndTurn,
5403 MaxTokens,
5405 MaxTurnRequests,
5408 Refusal,
5410 Cancelled,
5422 Error(ErrorStopReason),
5428 #[serde(untagged)]
5434 Other(OtherStopReason),
5435}
5436
5437impl From<ErrorStopReason> for StopReason {
5438 fn from(value: ErrorStopReason) -> Self {
5439 Self::Error(value)
5440 }
5441}
5442
5443#[serde_as]
5445#[skip_serializing_none]
5446#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5447#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
5448#[serde(rename_all = "camelCase")]
5449#[non_exhaustive]
5450pub struct ErrorStopReason {
5451 #[serde_as(deserialize_as = "DefaultOnError")]
5456 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5457 #[serde(default)]
5458 pub error: Option<Box<Error>>,
5459}
5460
5461impl ErrorStopReason {
5462 #[must_use]
5464 pub fn new() -> Self {
5465 Self::default()
5466 }
5467
5468 #[must_use]
5470 pub fn error(mut self, error: impl IntoOption<Error>) -> Self {
5471 self.error = error.into_option().map(Box::new);
5472 self
5473 }
5474}
5475
5476#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5478#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
5479#[cfg_attr(feature = "schemars", schemars(inline))]
5480#[cfg_attr(feature = "schemars", schemars(transform = other_stop_reason_schema))]
5481#[serde(rename_all = "camelCase")]
5482#[non_exhaustive]
5483pub struct OtherStopReason {
5484 pub stop_reason: String,
5490 #[serde(flatten)]
5492 pub fields: IndexMap<String, serde_json::Value>,
5493}
5494
5495impl OtherStopReason {
5496 #[must_use]
5498 pub fn new(
5499 stop_reason: impl Into<String>,
5500 mut fields: IndexMap<String, serde_json::Value>,
5501 ) -> Self {
5502 remove_idle_state_update_fields(&mut fields);
5503 Self {
5504 stop_reason: stop_reason.into(),
5505 fields,
5506 }
5507 }
5508}
5509
5510impl<'de> Deserialize<'de> for OtherStopReason {
5511 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
5512 where
5513 D: serde::Deserializer<'de>,
5514 {
5515 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
5516 let stop_reason = fields
5517 .shift_remove("stopReason")
5518 .ok_or_else(|| serde::de::Error::missing_field("stopReason"))?;
5519 let serde_json::Value::String(stop_reason) = stop_reason else {
5520 return Err(serde::de::Error::custom("`stopReason` must be a string"));
5521 };
5522
5523 if KNOWN_STOP_REASONS.contains(&stop_reason.as_str()) {
5524 return Err(serde::de::Error::custom(format!(
5525 "known stop reason `{stop_reason}` did not match its schema"
5526 )));
5527 }
5528 remove_idle_state_update_fields(&mut fields);
5529
5530 Ok(Self {
5531 stop_reason,
5532 fields,
5533 })
5534 }
5535}
5536
5537const KNOWN_STOP_REASONS: &[&str] = &[
5538 "end_turn",
5539 "max_tokens",
5540 "max_turn_requests",
5541 "refusal",
5542 "cancelled",
5543 "error",
5544];
5545
5546fn remove_idle_state_update_fields(fields: &mut IndexMap<String, serde_json::Value>) {
5548 fields.shift_remove("stopReason");
5549 fields.shift_remove("usage");
5550 fields.shift_remove("_meta");
5551}
5552
5553#[cfg(feature = "schemars")]
5554fn other_stop_reason_schema(schema: &mut Schema) {
5555 super::schema_util::reject_known_string_discriminators(
5556 schema,
5557 "stopReason",
5558 KNOWN_STOP_REASONS,
5559 );
5560}
5561
5562#[cfg(feature = "unstable_end_turn_token_usage")]
5568#[serde_as]
5569#[skip_serializing_none]
5570#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5571#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5572#[serde(rename_all = "camelCase")]
5573#[non_exhaustive]
5574pub struct Usage {
5575 pub total_tokens: u64,
5577 pub input_tokens: u64,
5579 pub output_tokens: u64,
5581 #[serde_as(deserialize_as = "DefaultOnError")]
5585 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5586 #[serde(default)]
5587 pub thought_tokens: Option<u64>,
5588 #[serde_as(deserialize_as = "DefaultOnError")]
5592 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5593 #[serde(default)]
5594 pub cached_read_tokens: Option<u64>,
5595 #[serde_as(deserialize_as = "DefaultOnError")]
5599 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5600 #[serde(default)]
5601 pub cached_write_tokens: Option<u64>,
5602 #[serde_as(deserialize_as = "DefaultOnError")]
5608 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5609 #[serde(default)]
5610 #[serde(rename = "_meta")]
5611 pub meta: Option<Meta>,
5612}
5613
5614#[cfg(feature = "unstable_end_turn_token_usage")]
5615impl Usage {
5616 #[must_use]
5618 pub fn new(total_tokens: u64, input_tokens: u64, output_tokens: u64) -> Self {
5619 Self {
5620 total_tokens,
5621 input_tokens,
5622 output_tokens,
5623 thought_tokens: None,
5624 cached_read_tokens: None,
5625 cached_write_tokens: None,
5626 meta: None,
5627 }
5628 }
5629
5630 #[must_use]
5632 pub fn thought_tokens(mut self, thought_tokens: impl IntoOption<u64>) -> Self {
5633 self.thought_tokens = thought_tokens.into_option();
5634 self
5635 }
5636
5637 #[must_use]
5639 pub fn cached_read_tokens(mut self, cached_read_tokens: impl IntoOption<u64>) -> Self {
5640 self.cached_read_tokens = cached_read_tokens.into_option();
5641 self
5642 }
5643
5644 #[must_use]
5646 pub fn cached_write_tokens(mut self, cached_write_tokens: impl IntoOption<u64>) -> Self {
5647 self.cached_write_tokens = cached_write_tokens.into_option();
5648 self
5649 }
5650
5651 #[must_use]
5657 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5658 self.meta = meta.into_option();
5659 self
5660 }
5661}
5662
5663#[cfg(feature = "unstable_llm_providers")]
5676#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5677#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5678#[serde(rename_all = "snake_case")]
5679#[non_exhaustive]
5680pub enum LlmProtocol {
5681 Anthropic,
5683 #[serde(rename = "openai")]
5685 OpenAi,
5686 Azure,
5688 Vertex,
5690 Bedrock,
5692 #[serde(untagged)]
5698 Other(String),
5699}
5700
5701#[cfg(feature = "unstable_llm_providers")]
5707#[serde_as]
5708#[skip_serializing_none]
5709#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5710#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5711#[serde(rename_all = "camelCase")]
5712#[non_exhaustive]
5713pub struct ProviderCurrentConfig {
5714 pub api_type: LlmProtocol,
5716 #[cfg_attr(feature = "schemars", schemars(url))]
5718 pub base_url: String,
5719 #[serde_as(deserialize_as = "DefaultOnError")]
5725 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5726 #[serde(default)]
5727 #[serde(rename = "_meta")]
5728 pub meta: Option<Meta>,
5729}
5730
5731#[cfg(feature = "unstable_llm_providers")]
5732impl ProviderCurrentConfig {
5733 #[must_use]
5735 pub fn new(api_type: LlmProtocol, base_url: impl Into<String>) -> Self {
5736 Self {
5737 api_type,
5738 base_url: base_url.into(),
5739 meta: None,
5740 }
5741 }
5742
5743 #[must_use]
5749 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5750 self.meta = meta.into_option();
5751 self
5752 }
5753}
5754
5755#[cfg(feature = "unstable_llm_providers")]
5761#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5762#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
5763#[serde(transparent)]
5764#[from(forward)]
5765#[non_exhaustive]
5766pub struct ProviderId(pub Arc<str>);
5767
5768#[cfg(feature = "unstable_llm_providers")]
5769impl ProviderId {
5770 #[must_use]
5772 pub fn new(id: impl Into<Self>) -> Self {
5773 id.into()
5774 }
5775}
5776
5777#[cfg(feature = "unstable_llm_providers")]
5783#[serde_as]
5784#[skip_serializing_none]
5785#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5786#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5787#[serde(rename_all = "camelCase")]
5788#[non_exhaustive]
5789pub struct ProviderInfo {
5790 pub provider_id: ProviderId,
5792 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
5794 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
5795 pub supported: Vec<LlmProtocol>,
5796 pub required: bool,
5799 #[serde(default)]
5802 pub current: Option<ProviderCurrentConfig>,
5803 #[serde_as(deserialize_as = "DefaultOnError")]
5809 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5810 #[serde(default)]
5811 #[serde(rename = "_meta")]
5812 pub meta: Option<Meta>,
5813}
5814
5815#[cfg(feature = "unstable_llm_providers")]
5816impl ProviderInfo {
5817 #[must_use]
5819 pub fn new(
5820 provider_id: impl Into<ProviderId>,
5821 supported: Vec<LlmProtocol>,
5822 required: bool,
5823 current: impl IntoOption<ProviderCurrentConfig>,
5824 ) -> Self {
5825 Self {
5826 provider_id: provider_id.into(),
5827 supported,
5828 required,
5829 current: current.into_option(),
5830 meta: None,
5831 }
5832 }
5833
5834 #[must_use]
5840 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5841 self.meta = meta.into_option();
5842 self
5843 }
5844}
5845
5846#[cfg(feature = "unstable_llm_providers")]
5847crate::serde_util::default_on_null! {
5848 #[serde_as]
5854 #[skip_serializing_none]
5855 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5856 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
5857 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_LIST_METHOD_NAME)))]
5858 #[serde(rename_all = "camelCase")]
5859 #[non_exhaustive]
5860 pub struct ListProvidersRequest {
5861 #[serde_as(deserialize_as = "DefaultOnError")]
5867 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5868 #[serde(default)]
5869 #[serde(rename = "_meta")]
5870 pub meta: Option<Meta>,
5871 }
5872}
5873
5874#[cfg(feature = "unstable_llm_providers")]
5875impl ListProvidersRequest {
5876 #[must_use]
5878 pub fn new() -> Self {
5879 Self::default()
5880 }
5881
5882 #[must_use]
5888 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5889 self.meta = meta.into_option();
5890 self
5891 }
5892}
5893
5894#[cfg(feature = "unstable_llm_providers")]
5900#[serde_as]
5901#[skip_serializing_none]
5902#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5903#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5904#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_LIST_METHOD_NAME)))]
5905#[serde(rename_all = "camelCase")]
5906#[non_exhaustive]
5907pub struct ListProvidersResponse {
5908 pub providers: Vec<ProviderInfo>,
5910 #[serde_as(deserialize_as = "DefaultOnError")]
5916 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5917 #[serde(default)]
5918 #[serde(rename = "_meta")]
5919 pub meta: Option<Meta>,
5920}
5921
5922#[cfg(feature = "unstable_llm_providers")]
5923impl ListProvidersResponse {
5924 #[must_use]
5926 pub fn new(providers: Vec<ProviderInfo>) -> Self {
5927 Self {
5928 providers,
5929 meta: None,
5930 }
5931 }
5932
5933 #[must_use]
5939 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5940 self.meta = meta.into_option();
5941 self
5942 }
5943}
5944
5945#[cfg(feature = "unstable_llm_providers")]
5953#[serde_as]
5954#[skip_serializing_none]
5955#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5956#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
5957#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_SET_METHOD_NAME)))]
5958#[serde(rename_all = "camelCase")]
5959#[non_exhaustive]
5960pub struct SetProviderRequest {
5961 pub provider_id: ProviderId,
5963 pub api_type: LlmProtocol,
5965 #[cfg_attr(feature = "schemars", schemars(url))]
5967 pub base_url: String,
5968 #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
5971 pub headers: IndexMap<String, String>,
5972 #[serde_as(deserialize_as = "DefaultOnError")]
5978 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5979 #[serde(default)]
5980 #[serde(rename = "_meta")]
5981 pub meta: Option<Meta>,
5982}
5983
5984#[cfg(feature = "unstable_llm_providers")]
5985impl SetProviderRequest {
5986 #[must_use]
5988 pub fn new(
5989 provider_id: impl Into<ProviderId>,
5990 api_type: LlmProtocol,
5991 base_url: impl Into<String>,
5992 ) -> Self {
5993 Self {
5994 provider_id: provider_id.into(),
5995 api_type,
5996 base_url: base_url.into(),
5997 headers: IndexMap::new(),
5998 meta: None,
5999 }
6000 }
6001
6002 #[must_use]
6005 pub fn headers(mut self, headers: IndexMap<String, String>) -> Self {
6006 self.headers = headers;
6007 self
6008 }
6009
6010 #[must_use]
6016 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6017 self.meta = meta.into_option();
6018 self
6019 }
6020}
6021
6022#[cfg(feature = "unstable_llm_providers")]
6023crate::serde_util::default_on_null! {
6024 #[serde_as]
6030 #[skip_serializing_none]
6031 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6032 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
6033 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_SET_METHOD_NAME)))]
6034 #[serde(rename_all = "camelCase")]
6035 #[non_exhaustive]
6036 pub struct SetProviderResponse {
6037 #[serde_as(deserialize_as = "DefaultOnError")]
6043 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6044 #[serde(default)]
6045 #[serde(rename = "_meta")]
6046 pub meta: Option<Meta>,
6047 }
6048}
6049
6050#[cfg(feature = "unstable_llm_providers")]
6051impl SetProviderResponse {
6052 #[must_use]
6054 pub fn new() -> Self {
6055 Self::default()
6056 }
6057
6058 #[must_use]
6064 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6065 self.meta = meta.into_option();
6066 self
6067 }
6068}
6069
6070#[cfg(feature = "unstable_llm_providers")]
6076#[serde_as]
6077#[skip_serializing_none]
6078#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6079#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6080#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_DISABLE_METHOD_NAME)))]
6081#[serde(rename_all = "camelCase")]
6082#[non_exhaustive]
6083pub struct DisableProviderRequest {
6084 pub provider_id: ProviderId,
6086 #[serde_as(deserialize_as = "DefaultOnError")]
6092 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6093 #[serde(default)]
6094 #[serde(rename = "_meta")]
6095 pub meta: Option<Meta>,
6096}
6097
6098#[cfg(feature = "unstable_llm_providers")]
6099impl DisableProviderRequest {
6100 #[must_use]
6102 pub fn new(provider_id: impl Into<ProviderId>) -> Self {
6103 Self {
6104 provider_id: provider_id.into(),
6105 meta: None,
6106 }
6107 }
6108
6109 #[must_use]
6115 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6116 self.meta = meta.into_option();
6117 self
6118 }
6119}
6120
6121#[cfg(feature = "unstable_llm_providers")]
6122crate::serde_util::default_on_null! {
6123 #[serde_as]
6129 #[skip_serializing_none]
6130 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6131 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
6132 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_DISABLE_METHOD_NAME)))]
6133 #[serde(rename_all = "camelCase")]
6134 #[non_exhaustive]
6135 pub struct DisableProviderResponse {
6136 #[serde_as(deserialize_as = "DefaultOnError")]
6142 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6143 #[serde(default)]
6144 #[serde(rename = "_meta")]
6145 pub meta: Option<Meta>,
6146 }
6147}
6148
6149#[cfg(feature = "unstable_llm_providers")]
6150impl DisableProviderResponse {
6151 #[must_use]
6153 pub fn new() -> Self {
6154 Self::default()
6155 }
6156
6157 #[must_use]
6163 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6164 self.meta = meta.into_option();
6165 self
6166 }
6167}
6168
6169#[serde_as]
6178#[skip_serializing_none]
6179#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6180#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6181#[serde(rename_all = "camelCase")]
6182#[non_exhaustive]
6183pub struct AgentCapabilities {
6184 #[serde_as(deserialize_as = "DefaultOnError")]
6192 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6193 #[serde(default)]
6194 pub session: Option<SessionCapabilities>,
6195 #[serde_as(deserialize_as = "DefaultOnError")]
6202 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6203 #[serde(default)]
6204 pub auth: Option<AgentAuthCapabilities>,
6205 #[cfg(feature = "unstable_llm_providers")]
6214 #[serde_as(deserialize_as = "DefaultOnError")]
6215 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6216 #[serde(default)]
6217 pub providers: Option<ProvidersCapabilities>,
6218 #[serde_as(deserialize_as = "DefaultOnError")]
6224 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6225 #[serde(default)]
6226 #[serde(rename = "_meta")]
6227 pub meta: Option<Meta>,
6228}
6229
6230impl AgentCapabilities {
6231 #[must_use]
6233 pub fn new() -> Self {
6234 Self::default()
6235 }
6236
6237 #[must_use]
6245 pub fn session(mut self, session: impl IntoOption<SessionCapabilities>) -> Self {
6246 self.session = session.into_option();
6247 self
6248 }
6249
6250 #[must_use]
6254 pub fn auth(mut self, auth: impl IntoOption<AgentAuthCapabilities>) -> Self {
6255 self.auth = auth.into_option();
6256 self
6257 }
6258
6259 #[cfg(feature = "unstable_llm_providers")]
6265 #[must_use]
6266 pub fn providers(mut self, providers: impl IntoOption<ProvidersCapabilities>) -> Self {
6267 self.providers = providers.into_option();
6268 self
6269 }
6270
6271 #[must_use]
6277 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6278 self.meta = meta.into_option();
6279 self
6280 }
6281}
6282
6283#[cfg(feature = "unstable_llm_providers")]
6291#[serde_as]
6292#[skip_serializing_none]
6293#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6294#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6295#[non_exhaustive]
6296pub struct ProvidersCapabilities {
6297 #[serde_as(deserialize_as = "DefaultOnError")]
6303 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6304 #[serde(default)]
6305 #[serde(rename = "_meta")]
6306 pub meta: Option<Meta>,
6307}
6308
6309#[cfg(feature = "unstable_llm_providers")]
6310impl ProvidersCapabilities {
6311 #[must_use]
6313 pub fn new() -> Self {
6314 Self::default()
6315 }
6316
6317 #[must_use]
6323 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6324 self.meta = meta.into_option();
6325 self
6326 }
6327}
6328
6329#[serde_as]
6341#[skip_serializing_none]
6342#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6343#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6344#[serde(rename_all = "camelCase")]
6345#[non_exhaustive]
6346pub struct SessionCapabilities {
6347 #[serde_as(deserialize_as = "DefaultOnError")]
6353 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6354 #[serde(default)]
6355 pub prompt: Option<PromptCapabilities>,
6356 #[serde_as(deserialize_as = "DefaultOnError")]
6361 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6362 #[serde(default)]
6363 pub mcp: Option<McpCapabilities>,
6364 #[serde_as(deserialize_as = "DefaultOnError")]
6369 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6370 #[serde(default)]
6371 pub delete: Option<SessionDeleteCapabilities>,
6372 #[serde_as(deserialize_as = "DefaultOnError")]
6381 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6382 #[serde(default)]
6383 pub additional_directories: Option<SessionAdditionalDirectoriesCapabilities>,
6384 #[serde_as(deserialize_as = "DefaultOnError")]
6389 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6390 #[serde(default)]
6391 pub system_prompt: Option<SessionSystemPromptCapabilities>,
6392 #[cfg(feature = "unstable_session_fork")]
6401 #[serde_as(deserialize_as = "DefaultOnError")]
6402 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6403 #[serde(default)]
6404 pub fork: Option<SessionForkCapabilities>,
6405 #[cfg(feature = "unstable_session_archive")]
6415 #[serde_as(deserialize_as = "DefaultOnError")]
6416 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6417 #[serde(default)]
6418 pub archive: Option<SessionArchiveCapabilities>,
6419 #[cfg(feature = "unstable_session_status")]
6428 #[serde_as(deserialize_as = "DefaultOnError")]
6429 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6430 #[serde(default)]
6431 pub status: Option<SessionStatusCapabilities>,
6432 #[cfg(feature = "unstable_session_options")]
6442 #[serde_as(deserialize_as = "DefaultOnError")]
6443 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6444 #[serde(default)]
6445 pub options: Option<SessionOptionsCapabilities>,
6446 #[cfg(feature = "unstable_session_set_title")]
6458 #[serde_as(deserialize_as = "DefaultOnError")]
6459 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6460 #[serde(default)]
6461 pub title: Option<SessionTitleCapabilities>,
6462 #[serde_as(deserialize_as = "DefaultOnError")]
6468 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6469 #[serde(default)]
6470 #[serde(rename = "_meta")]
6471 pub meta: Option<Meta>,
6472}
6473
6474impl SessionCapabilities {
6475 #[must_use]
6477 pub fn new() -> Self {
6478 Self::default()
6479 }
6480
6481 #[must_use]
6487 pub fn prompt(mut self, prompt: impl IntoOption<PromptCapabilities>) -> Self {
6488 self.prompt = prompt.into_option();
6489 self
6490 }
6491
6492 #[must_use]
6497 pub fn mcp(mut self, mcp: impl IntoOption<McpCapabilities>) -> Self {
6498 self.mcp = mcp.into_option();
6499 self
6500 }
6501
6502 #[must_use]
6507 pub fn delete(mut self, delete: impl IntoOption<SessionDeleteCapabilities>) -> Self {
6508 self.delete = delete.into_option();
6509 self
6510 }
6511
6512 #[must_use]
6521 pub fn additional_directories(
6522 mut self,
6523 additional_directories: impl IntoOption<SessionAdditionalDirectoriesCapabilities>,
6524 ) -> Self {
6525 self.additional_directories = additional_directories.into_option();
6526 self
6527 }
6528
6529 #[must_use]
6534 pub fn system_prompt(
6535 mut self,
6536 system_prompt: impl IntoOption<SessionSystemPromptCapabilities>,
6537 ) -> Self {
6538 self.system_prompt = system_prompt.into_option();
6539 self
6540 }
6541
6542 #[cfg(feature = "unstable_session_fork")]
6543 #[must_use]
6548 pub fn fork(mut self, fork: impl IntoOption<SessionForkCapabilities>) -> Self {
6549 self.fork = fork.into_option();
6550 self
6551 }
6552
6553 #[cfg(feature = "unstable_session_archive")]
6563 #[must_use]
6564 pub fn archive(mut self, archive: impl IntoOption<SessionArchiveCapabilities>) -> Self {
6565 self.archive = archive.into_option();
6566 self
6567 }
6568
6569 #[cfg(feature = "unstable_session_status")]
6578 #[must_use]
6579 pub fn status(mut self, status: impl IntoOption<SessionStatusCapabilities>) -> Self {
6580 self.status = status.into_option();
6581 self
6582 }
6583
6584 #[cfg(feature = "unstable_session_options")]
6594 #[must_use]
6595 pub fn options(mut self, options: impl IntoOption<SessionOptionsCapabilities>) -> Self {
6596 self.options = options.into_option();
6597 self
6598 }
6599
6600 #[cfg(feature = "unstable_session_set_title")]
6612 #[must_use]
6613 pub fn title(mut self, title: impl IntoOption<SessionTitleCapabilities>) -> Self {
6614 self.title = title.into_option();
6615 self
6616 }
6617
6618 #[must_use]
6624 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6625 self.meta = meta.into_option();
6626 self
6627 }
6628}
6629
6630#[serde_as]
6634#[skip_serializing_none]
6635#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6636#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6637#[non_exhaustive]
6638pub struct SessionDeleteCapabilities {
6639 #[serde_as(deserialize_as = "DefaultOnError")]
6645 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6646 #[serde(default)]
6647 #[serde(rename = "_meta")]
6648 pub meta: Option<Meta>,
6649}
6650
6651impl SessionDeleteCapabilities {
6652 #[must_use]
6654 pub fn new() -> Self {
6655 Self::default()
6656 }
6657
6658 #[must_use]
6664 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6665 self.meta = meta.into_option();
6666 self
6667 }
6668}
6669
6670#[serde_as]
6677#[skip_serializing_none]
6678#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6679#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6680#[non_exhaustive]
6681pub struct SessionAdditionalDirectoriesCapabilities {
6682 #[serde_as(deserialize_as = "DefaultOnError")]
6688 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6689 #[serde(default)]
6690 #[serde(rename = "_meta")]
6691 pub meta: Option<Meta>,
6692}
6693
6694impl SessionAdditionalDirectoriesCapabilities {
6695 #[must_use]
6697 pub fn new() -> Self {
6698 Self::default()
6699 }
6700
6701 #[must_use]
6707 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6708 self.meta = meta.into_option();
6709 self
6710 }
6711}
6712
6713#[serde_as]
6718#[skip_serializing_none]
6719#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6720#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6721#[serde(rename_all = "camelCase")]
6722#[non_exhaustive]
6723pub struct SessionSystemPromptCapabilities {
6724 #[serde_as(deserialize_as = "DefaultOnError")]
6728 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6729 #[serde(default)]
6730 pub mode: Option<SessionSystemPromptModeCapabilities>,
6731 #[serde_as(deserialize_as = "DefaultOnError")]
6737 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6738 #[serde(default)]
6739 #[serde(rename = "_meta")]
6740 pub meta: Option<Meta>,
6741}
6742
6743impl SessionSystemPromptCapabilities {
6744 #[must_use]
6746 pub fn new() -> Self {
6747 Self::default()
6748 }
6749
6750 #[must_use]
6754 pub fn mode(mut self, mode: impl IntoOption<SessionSystemPromptModeCapabilities>) -> Self {
6755 self.mode = mode.into_option();
6756 self
6757 }
6758
6759 #[must_use]
6765 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6766 self.meta = meta.into_option();
6767 self
6768 }
6769}
6770
6771#[serde_as]
6776#[skip_serializing_none]
6777#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6778#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6779#[serde(rename_all = "camelCase")]
6780#[non_exhaustive]
6781pub struct SessionSystemPromptModeCapabilities {
6782 #[serde_as(deserialize_as = "DefaultOnError")]
6788 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6789 #[serde(default, rename = "override")]
6790 pub override_: Option<SessionSystemPromptOverrideCapabilities>,
6791 #[serde_as(deserialize_as = "DefaultOnError")]
6797 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6798 #[serde(default)]
6799 #[serde(rename = "_meta")]
6800 pub meta: Option<Meta>,
6801}
6802
6803impl SessionSystemPromptModeCapabilities {
6804 #[must_use]
6806 pub fn new() -> Self {
6807 Self::default()
6808 }
6809
6810 #[must_use]
6816 pub fn override_(
6817 mut self,
6818 override_: impl IntoOption<SessionSystemPromptOverrideCapabilities>,
6819 ) -> Self {
6820 self.override_ = override_.into_option();
6821 self
6822 }
6823
6824 #[must_use]
6830 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6831 self.meta = meta.into_option();
6832 self
6833 }
6834}
6835
6836#[serde_as]
6841#[skip_serializing_none]
6842#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6843#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6844#[non_exhaustive]
6845pub struct SessionSystemPromptOverrideCapabilities {
6846 #[serde_as(deserialize_as = "DefaultOnError")]
6852 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6853 #[serde(default)]
6854 #[serde(rename = "_meta")]
6855 pub meta: Option<Meta>,
6856}
6857
6858impl SessionSystemPromptOverrideCapabilities {
6859 #[must_use]
6861 pub fn new() -> Self {
6862 Self::default()
6863 }
6864
6865 #[must_use]
6871 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6872 self.meta = meta.into_option();
6873 self
6874 }
6875}
6876
6877#[cfg(feature = "unstable_session_fork")]
6885#[serde_as]
6886#[skip_serializing_none]
6887#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6888#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6889#[non_exhaustive]
6890pub struct SessionForkCapabilities {
6891 #[serde_as(deserialize_as = "DefaultOnError")]
6897 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6898 #[serde(default)]
6899 #[serde(rename = "_meta")]
6900 pub meta: Option<Meta>,
6901}
6902
6903#[cfg(feature = "unstable_session_fork")]
6904impl SessionForkCapabilities {
6905 #[must_use]
6907 pub fn new() -> Self {
6908 Self::default()
6909 }
6910
6911 #[must_use]
6917 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6918 self.meta = meta.into_option();
6919 self
6920 }
6921}
6922
6923#[cfg(feature = "unstable_session_archive")]
6932#[serde_as]
6933#[skip_serializing_none]
6934#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6935#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6936#[non_exhaustive]
6937pub struct SessionArchiveCapabilities {
6938 #[serde_as(deserialize_as = "DefaultOnError")]
6944 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6945 #[serde(default)]
6946 #[serde(rename = "_meta")]
6947 pub meta: Option<Meta>,
6948}
6949
6950#[cfg(feature = "unstable_session_archive")]
6951impl SessionArchiveCapabilities {
6952 #[must_use]
6954 pub fn new() -> Self {
6955 Self::default()
6956 }
6957
6958 #[must_use]
6964 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6965 self.meta = meta.into_option();
6966 self
6967 }
6968}
6969
6970#[cfg(feature = "unstable_session_status")]
6978#[serde_as]
6979#[skip_serializing_none]
6980#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6981#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6982#[non_exhaustive]
6983pub struct SessionStatusCapabilities {
6984 #[serde_as(deserialize_as = "DefaultOnError")]
6990 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6991 #[serde(default)]
6992 #[serde(rename = "_meta")]
6993 pub meta: Option<Meta>,
6994}
6995
6996#[cfg(feature = "unstable_session_status")]
6997impl SessionStatusCapabilities {
6998 #[must_use]
7000 pub fn new() -> Self {
7001 Self::default()
7002 }
7003
7004 #[must_use]
7010 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7011 self.meta = meta.into_option();
7012 self
7013 }
7014}
7015
7016#[cfg(feature = "unstable_session_options")]
7025#[serde_as]
7026#[skip_serializing_none]
7027#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7028#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7029#[non_exhaustive]
7030pub struct SessionOptionsCapabilities {
7031 #[serde_as(deserialize_as = "DefaultOnError")]
7037 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7038 #[serde(default)]
7039 #[serde(rename = "_meta")]
7040 pub meta: Option<Meta>,
7041}
7042
7043#[cfg(feature = "unstable_session_options")]
7044impl SessionOptionsCapabilities {
7045 #[must_use]
7047 pub fn new() -> Self {
7048 Self::default()
7049 }
7050
7051 #[must_use]
7057 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7058 self.meta = meta.into_option();
7059 self
7060 }
7061}
7062
7063#[cfg(feature = "unstable_session_set_title")]
7072#[serde_as]
7073#[skip_serializing_none]
7074#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7075#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7076#[non_exhaustive]
7077pub struct SessionTitleCapabilities {
7078 #[serde_as(deserialize_as = "DefaultOnError")]
7084 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7085 #[serde(default)]
7086 #[serde(rename = "_meta")]
7087 pub meta: Option<Meta>,
7088}
7089
7090#[cfg(feature = "unstable_session_set_title")]
7091impl SessionTitleCapabilities {
7092 #[must_use]
7094 pub fn new() -> Self {
7095 Self::default()
7096 }
7097
7098 #[must_use]
7104 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7105 self.meta = meta.into_option();
7106 self
7107 }
7108}
7109
7110#[serde_as]
7123#[skip_serializing_none]
7124#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7125#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7126#[serde(rename_all = "camelCase")]
7127#[non_exhaustive]
7128pub struct PromptCapabilities {
7129 #[serde_as(deserialize_as = "DefaultOnError")]
7134 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7135 #[serde(default)]
7136 pub image: Option<PromptImageCapabilities>,
7137 #[serde_as(deserialize_as = "DefaultOnError")]
7142 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7143 #[serde(default)]
7144 pub audio: Option<PromptAudioCapabilities>,
7145 #[serde_as(deserialize_as = "DefaultOnError")]
7153 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7154 #[serde(default)]
7155 pub embedded_context: Option<PromptEmbeddedContextCapabilities>,
7156 #[cfg(feature = "unstable_agent_skills")]
7166 #[serde_as(deserialize_as = "DefaultOnError")]
7167 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7168 #[serde(default)]
7169 pub skill: Option<PromptSkillCapabilities>,
7170 #[serde_as(deserialize_as = "DefaultOnError")]
7176 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7177 #[serde(default)]
7178 #[serde(rename = "_meta")]
7179 pub meta: Option<Meta>,
7180}
7181
7182impl PromptCapabilities {
7183 #[must_use]
7185 pub fn new() -> Self {
7186 Self::default()
7187 }
7188
7189 #[must_use]
7194 pub fn image(mut self, image: impl IntoOption<PromptImageCapabilities>) -> Self {
7195 self.image = image.into_option();
7196 self
7197 }
7198
7199 #[must_use]
7204 pub fn audio(mut self, audio: impl IntoOption<PromptAudioCapabilities>) -> Self {
7205 self.audio = audio.into_option();
7206 self
7207 }
7208
7209 #[must_use]
7217 pub fn embedded_context(
7218 mut self,
7219 embedded_context: impl IntoOption<PromptEmbeddedContextCapabilities>,
7220 ) -> Self {
7221 self.embedded_context = embedded_context.into_option();
7222 self
7223 }
7224
7225 #[cfg(feature = "unstable_agent_skills")]
7234 #[must_use]
7235 pub fn skill(mut self, skill: impl IntoOption<PromptSkillCapabilities>) -> Self {
7236 self.skill = skill.into_option();
7237 self
7238 }
7239
7240 #[must_use]
7246 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7247 self.meta = meta.into_option();
7248 self
7249 }
7250}
7251
7252#[serde_as]
7256#[skip_serializing_none]
7257#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7258#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7259#[non_exhaustive]
7260pub struct PromptImageCapabilities {
7261 #[serde_as(deserialize_as = "DefaultOnError")]
7267 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7268 #[serde(default)]
7269 #[serde(rename = "_meta")]
7270 pub meta: Option<Meta>,
7271}
7272
7273impl PromptImageCapabilities {
7274 #[must_use]
7276 pub fn new() -> Self {
7277 Self::default()
7278 }
7279
7280 #[must_use]
7286 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7287 self.meta = meta.into_option();
7288 self
7289 }
7290}
7291
7292#[serde_as]
7296#[skip_serializing_none]
7297#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7298#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7299#[non_exhaustive]
7300pub struct PromptAudioCapabilities {
7301 #[serde_as(deserialize_as = "DefaultOnError")]
7307 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7308 #[serde(default)]
7309 #[serde(rename = "_meta")]
7310 pub meta: Option<Meta>,
7311}
7312
7313impl PromptAudioCapabilities {
7314 #[must_use]
7316 pub fn new() -> Self {
7317 Self::default()
7318 }
7319
7320 #[must_use]
7326 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7327 self.meta = meta.into_option();
7328 self
7329 }
7330}
7331
7332#[serde_as]
7336#[skip_serializing_none]
7337#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7338#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7339#[non_exhaustive]
7340pub struct PromptEmbeddedContextCapabilities {
7341 #[serde_as(deserialize_as = "DefaultOnError")]
7347 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7348 #[serde(default)]
7349 #[serde(rename = "_meta")]
7350 pub meta: Option<Meta>,
7351}
7352
7353impl PromptEmbeddedContextCapabilities {
7354 #[must_use]
7356 pub fn new() -> Self {
7357 Self::default()
7358 }
7359
7360 #[must_use]
7366 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7367 self.meta = meta.into_option();
7368 self
7369 }
7370}
7371
7372#[cfg(feature = "unstable_agent_skills")]
7381#[serde_as]
7382#[skip_serializing_none]
7383#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7384#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7385#[serde(rename_all = "camelCase")]
7386#[non_exhaustive]
7387pub struct PromptSkillCapabilities {
7388 #[serde_as(deserialize_as = "DefaultOnError")]
7394 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7395 #[serde(default)]
7396 pub inline: Option<PromptSkillInlineCapabilities>,
7397 #[serde_as(deserialize_as = "DefaultOnError")]
7403 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7404 #[serde(default)]
7405 #[serde(rename = "_meta")]
7406 pub meta: Option<Meta>,
7407}
7408
7409#[cfg(feature = "unstable_agent_skills")]
7410impl PromptSkillCapabilities {
7411 #[must_use]
7413 pub fn new() -> Self {
7414 Self::default()
7415 }
7416
7417 #[must_use]
7423 pub fn inline(mut self, inline: impl IntoOption<PromptSkillInlineCapabilities>) -> Self {
7424 self.inline = inline.into_option();
7425 self
7426 }
7427
7428 #[must_use]
7434 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7435 self.meta = meta.into_option();
7436 self
7437 }
7438}
7439
7440#[cfg(feature = "unstable_agent_skills")]
7449#[serde_as]
7450#[skip_serializing_none]
7451#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7452#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7453#[non_exhaustive]
7454pub struct PromptSkillInlineCapabilities {
7455 #[serde_as(deserialize_as = "DefaultOnError")]
7461 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7462 #[serde(default)]
7463 #[serde(rename = "_meta")]
7464 pub meta: Option<Meta>,
7465}
7466
7467#[cfg(feature = "unstable_agent_skills")]
7468impl PromptSkillInlineCapabilities {
7469 #[must_use]
7471 pub fn new() -> Self {
7472 Self::default()
7473 }
7474
7475 #[must_use]
7481 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7482 self.meta = meta.into_option();
7483 self
7484 }
7485}
7486
7487#[serde_as]
7489#[skip_serializing_none]
7490#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7491#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7492#[serde(rename_all = "camelCase")]
7493#[non_exhaustive]
7494pub struct McpCapabilities {
7495 #[serde_as(deserialize_as = "DefaultOnError")]
7500 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7501 #[serde(default)]
7502 pub stdio: Option<McpStdioCapabilities>,
7503 #[serde_as(deserialize_as = "DefaultOnError")]
7508 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7509 #[serde(default)]
7510 pub http: Option<McpHttpCapabilities>,
7511 #[cfg(feature = "unstable_mcp_over_acp")]
7520 #[serde_as(deserialize_as = "DefaultOnError")]
7521 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7522 #[serde(default)]
7523 pub acp: Option<McpAcpCapabilities>,
7524 #[serde_as(deserialize_as = "DefaultOnError")]
7530 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7531 #[serde(default)]
7532 #[serde(rename = "_meta")]
7533 pub meta: Option<Meta>,
7534}
7535
7536impl McpCapabilities {
7537 #[must_use]
7539 pub fn new() -> Self {
7540 Self::default()
7541 }
7542
7543 #[must_use]
7548 pub fn stdio(mut self, stdio: impl IntoOption<McpStdioCapabilities>) -> Self {
7549 self.stdio = stdio.into_option();
7550 self
7551 }
7552
7553 #[must_use]
7558 pub fn http(mut self, http: impl IntoOption<McpHttpCapabilities>) -> Self {
7559 self.http = http.into_option();
7560 self
7561 }
7562
7563 #[cfg(feature = "unstable_mcp_over_acp")]
7569 #[must_use]
7573 pub fn acp(mut self, acp: impl IntoOption<McpAcpCapabilities>) -> Self {
7574 self.acp = acp.into_option();
7575 self
7576 }
7577
7578 #[must_use]
7584 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7585 self.meta = meta.into_option();
7586 self
7587 }
7588}
7589
7590#[serde_as]
7594#[skip_serializing_none]
7595#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7596#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7597#[non_exhaustive]
7598pub struct McpStdioCapabilities {
7599 #[serde_as(deserialize_as = "DefaultOnError")]
7605 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7606 #[serde(default)]
7607 #[serde(rename = "_meta")]
7608 pub meta: Option<Meta>,
7609}
7610
7611impl McpStdioCapabilities {
7612 #[must_use]
7614 pub fn new() -> Self {
7615 Self::default()
7616 }
7617
7618 #[must_use]
7624 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7625 self.meta = meta.into_option();
7626 self
7627 }
7628}
7629
7630#[serde_as]
7634#[skip_serializing_none]
7635#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7636#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7637#[non_exhaustive]
7638pub struct McpHttpCapabilities {
7639 #[serde_as(deserialize_as = "DefaultOnError")]
7645 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7646 #[serde(default)]
7647 #[serde(rename = "_meta")]
7648 pub meta: Option<Meta>,
7649}
7650
7651impl McpHttpCapabilities {
7652 #[must_use]
7654 pub fn new() -> Self {
7655 Self::default()
7656 }
7657
7658 #[must_use]
7664 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7665 self.meta = meta.into_option();
7666 self
7667 }
7668}
7669
7670#[cfg(feature = "unstable_mcp_over_acp")]
7678#[serde_as]
7679#[skip_serializing_none]
7680#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7681#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7682#[non_exhaustive]
7683pub struct McpAcpCapabilities {
7684 #[serde_as(deserialize_as = "DefaultOnError")]
7690 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7691 #[serde(default)]
7692 #[serde(rename = "_meta")]
7693 pub meta: Option<Meta>,
7694}
7695
7696#[cfg(feature = "unstable_mcp_over_acp")]
7697impl McpAcpCapabilities {
7698 #[must_use]
7700 pub fn new() -> Self {
7701 Self::default()
7702 }
7703
7704 #[must_use]
7710 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7711 self.meta = meta.into_option();
7712 self
7713 }
7714}
7715
7716#[serde_as]
7721#[skip_serializing_none]
7722#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7723#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7724#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CANCEL_METHOD_NAME)))]
7725#[serde(rename_all = "camelCase")]
7726#[non_exhaustive]
7727pub struct CancelSessionNotification {
7728 pub session_id: SessionId,
7730 #[serde_as(deserialize_as = "DefaultOnError")]
7736 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7737 #[serde(default)]
7738 #[serde(rename = "_meta")]
7739 pub meta: Option<Meta>,
7740}
7741
7742impl CancelSessionNotification {
7743 #[must_use]
7745 pub fn new(session_id: impl Into<SessionId>) -> Self {
7746 Self {
7747 session_id: session_id.into(),
7748 meta: None,
7749 }
7750 }
7751
7752 #[must_use]
7758 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7759 self.meta = meta.into_option();
7760 self
7761 }
7762}
7763
7764#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7770#[non_exhaustive]
7771pub struct AgentMethodNames {
7772 pub initialize: &'static str,
7774 pub auth_login: &'static str,
7776 #[cfg(feature = "unstable_llm_providers")]
7778 pub providers_list: &'static str,
7779 #[cfg(feature = "unstable_llm_providers")]
7781 pub providers_set: &'static str,
7782 #[cfg(feature = "unstable_llm_providers")]
7784 pub providers_disable: &'static str,
7785 pub session_new: &'static str,
7787 pub session_set_config_option: &'static str,
7789 pub session_prompt: &'static str,
7791 pub session_cancel: &'static str,
7793 #[cfg(feature = "unstable_mcp_over_acp")]
7795 pub mcp_message: &'static str,
7796 pub session_list: &'static str,
7798 pub session_delete: &'static str,
7800 #[cfg(feature = "unstable_session_fork")]
7802 pub session_fork: &'static str,
7803 #[cfg(feature = "unstable_session_archive")]
7805 pub session_archive: &'static str,
7806 #[cfg(feature = "unstable_session_archive")]
7808 pub session_unarchive: &'static str,
7809 #[cfg(feature = "unstable_session_status")]
7811 pub session_status: &'static str,
7812 #[cfg(feature = "unstable_session_options")]
7814 pub session_options: &'static str,
7815 #[cfg(feature = "unstable_session_set_title")]
7817 pub session_set_title: &'static str,
7818 pub session_resume: &'static str,
7820 pub session_close: &'static str,
7822 pub tool_call_cancel: &'static str,
7824 pub terminal_cancel: &'static str,
7826 pub auth_logout: &'static str,
7828 #[cfg(feature = "unstable_auth_status")]
7830 pub auth_status: &'static str,
7831}
7832
7833pub const AGENT_METHOD_NAMES: AgentMethodNames = AgentMethodNames {
7835 initialize: INITIALIZE_METHOD_NAME,
7836 auth_login: AUTH_LOGIN_METHOD_NAME,
7837 #[cfg(feature = "unstable_llm_providers")]
7838 providers_list: PROVIDERS_LIST_METHOD_NAME,
7839 #[cfg(feature = "unstable_llm_providers")]
7840 providers_set: PROVIDERS_SET_METHOD_NAME,
7841 #[cfg(feature = "unstable_llm_providers")]
7842 providers_disable: PROVIDERS_DISABLE_METHOD_NAME,
7843 session_new: SESSION_NEW_METHOD_NAME,
7844 session_set_config_option: SESSION_SET_CONFIG_OPTION_METHOD_NAME,
7845 session_prompt: SESSION_PROMPT_METHOD_NAME,
7846 session_cancel: SESSION_CANCEL_METHOD_NAME,
7847 #[cfg(feature = "unstable_mcp_over_acp")]
7848 mcp_message: MCP_MESSAGE_METHOD_NAME,
7849 session_list: SESSION_LIST_METHOD_NAME,
7850 session_delete: SESSION_DELETE_METHOD_NAME,
7851 #[cfg(feature = "unstable_session_fork")]
7852 session_fork: SESSION_FORK_METHOD_NAME,
7853 #[cfg(feature = "unstable_session_archive")]
7854 session_archive: SESSION_ARCHIVE_METHOD_NAME,
7855 #[cfg(feature = "unstable_session_archive")]
7856 session_unarchive: SESSION_UNARCHIVE_METHOD_NAME,
7857 #[cfg(feature = "unstable_session_status")]
7858 session_status: SESSION_STATUS_METHOD_NAME,
7859 #[cfg(feature = "unstable_session_options")]
7860 session_options: SESSION_OPTIONS_METHOD_NAME,
7861 #[cfg(feature = "unstable_session_set_title")]
7862 session_set_title: SESSION_SET_TITLE_METHOD_NAME,
7863 session_resume: SESSION_RESUME_METHOD_NAME,
7864 session_close: SESSION_CLOSE_METHOD_NAME,
7865 tool_call_cancel: TOOL_CALL_CANCEL_METHOD_NAME,
7866 terminal_cancel: TERMINAL_CANCEL_METHOD_NAME,
7867 auth_logout: AUTH_LOGOUT_METHOD_NAME,
7868 #[cfg(feature = "unstable_auth_status")]
7869 auth_status: AUTH_STATUS_METHOD_NAME,
7870};
7871
7872pub(crate) const INITIALIZE_METHOD_NAME: &str = "initialize";
7874pub(crate) const AUTH_LOGIN_METHOD_NAME: &str = "auth/login";
7876#[cfg(feature = "unstable_llm_providers")]
7878pub(crate) const PROVIDERS_LIST_METHOD_NAME: &str = "providers/list";
7879#[cfg(feature = "unstable_llm_providers")]
7881pub(crate) const PROVIDERS_SET_METHOD_NAME: &str = "providers/set";
7882#[cfg(feature = "unstable_llm_providers")]
7884pub(crate) const PROVIDERS_DISABLE_METHOD_NAME: &str = "providers/disable";
7885pub(crate) const SESSION_NEW_METHOD_NAME: &str = "session/new";
7887pub(crate) const SESSION_SET_CONFIG_OPTION_METHOD_NAME: &str = "session/set_config_option";
7889pub(crate) const SESSION_PROMPT_METHOD_NAME: &str = "session/prompt";
7891pub(crate) const SESSION_CANCEL_METHOD_NAME: &str = "session/cancel";
7893pub(crate) const SESSION_LIST_METHOD_NAME: &str = "session/list";
7895pub(crate) const SESSION_DELETE_METHOD_NAME: &str = "session/delete";
7897#[cfg(feature = "unstable_session_fork")]
7899pub(crate) const SESSION_FORK_METHOD_NAME: &str = "session/fork";
7900#[cfg(feature = "unstable_session_archive")]
7902pub(crate) const SESSION_ARCHIVE_METHOD_NAME: &str = "session/archive";
7903#[cfg(feature = "unstable_session_archive")]
7905pub(crate) const SESSION_UNARCHIVE_METHOD_NAME: &str = "session/unarchive";
7906#[cfg(feature = "unstable_session_status")]
7908pub(crate) const SESSION_STATUS_METHOD_NAME: &str = "session/status";
7909#[cfg(feature = "unstable_session_options")]
7911pub(crate) const SESSION_OPTIONS_METHOD_NAME: &str = "session/options";
7912#[cfg(feature = "unstable_session_set_title")]
7914pub(crate) const SESSION_SET_TITLE_METHOD_NAME: &str = "session/set_title";
7915pub(crate) const SESSION_RESUME_METHOD_NAME: &str = "session/resume";
7917pub(crate) const SESSION_CLOSE_METHOD_NAME: &str = "session/close";
7919pub(crate) const TOOL_CALL_CANCEL_METHOD_NAME: &str = "tool_call/cancel";
7921pub(crate) const TERMINAL_CANCEL_METHOD_NAME: &str = "terminal/cancel";
7923pub(crate) const AUTH_LOGOUT_METHOD_NAME: &str = "auth/logout";
7925#[cfg(feature = "unstable_auth_status")]
7927pub(crate) const AUTH_STATUS_METHOD_NAME: &str = "auth/status";
7928
7929#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7936#[derive(Clone, Debug, Serialize, Deserialize)]
7937#[serde(untagged)]
7938#[cfg_attr(feature = "schemars", schemars(inline))]
7939#[non_exhaustive]
7940pub enum ClientRequest {
7941 InitializeRequest(Box<InitializeRequest>),
7955 LoginAuthRequest(Box<LoginAuthRequest>),
7970 #[cfg(feature = "unstable_llm_providers")]
7976 ListProvidersRequest(Box<ListProvidersRequest>),
7977 #[cfg(feature = "unstable_llm_providers")]
7983 SetProviderRequest(Box<SetProviderRequest>),
7984 #[cfg(feature = "unstable_llm_providers")]
7990 DisableProviderRequest(Box<DisableProviderRequest>),
7991 LogoutAuthRequest(Box<LogoutAuthRequest>),
8001 #[cfg(feature = "unstable_auth_status")]
8010 AuthStatusRequest(Box<AuthStatusRequest>),
8011 NewSessionRequest(Box<NewSessionRequest>),
8024 ListSessionsRequest(Box<ListSessionsRequest>),
8028 DeleteSessionRequest(Box<DeleteSessionRequest>),
8032 #[cfg(feature = "unstable_session_fork")]
8033 ForkSessionRequest(Box<ForkSessionRequest>),
8049 #[cfg(feature = "unstable_session_archive")]
8050 ArchiveSessionRequest(Box<ArchiveSessionRequest>),
8058 #[cfg(feature = "unstable_session_archive")]
8059 UnarchiveSessionRequest(Box<UnarchiveSessionRequest>),
8067 #[cfg(feature = "unstable_session_status")]
8068 SessionStatusRequest(Box<SessionStatusRequest>),
8076 #[cfg(feature = "unstable_session_options")]
8077 SessionOptionsRequest(Box<SessionOptionsRequest>),
8085 #[cfg(feature = "unstable_session_set_title")]
8086 SetSessionTitleRequest(Box<SetSessionTitleRequest>),
8097 ResumeSessionRequest(Box<ResumeSessionRequest>),
8103 CloseSessionRequest(Box<CloseSessionRequest>),
8108 CancelToolCallRequest(Box<CancelToolCallRequest>),
8114 CancelTerminalRequest(Box<CancelTerminalRequest>),
8120 SetSessionConfigOptionRequest(Box<SetSessionConfigOptionRequest>),
8122 PromptRequest(Box<PromptRequest>),
8144 ExtMethodRequest(Box<ExtRequest>),
8150}
8151
8152impl_request_dispatch! {
8153 ClientRequest => AgentResponse {
8154 InitializeRequest => InitializeResponse: AGENT_METHOD_NAMES.initialize,
8155 LoginAuthRequest => LoginAuthResponse: AGENT_METHOD_NAMES.auth_login,
8156 #[cfg(feature = "unstable_llm_providers")]
8157 ListProvidersRequest => ListProvidersResponse: AGENT_METHOD_NAMES.providers_list,
8158 #[cfg(feature = "unstable_llm_providers")]
8159 SetProviderRequest => SetProviderResponse: AGENT_METHOD_NAMES.providers_set,
8160 #[cfg(feature = "unstable_llm_providers")]
8161 DisableProviderRequest => DisableProviderResponse: AGENT_METHOD_NAMES.providers_disable,
8162 LogoutAuthRequest => LogoutAuthResponse: AGENT_METHOD_NAMES.auth_logout,
8163 #[cfg(feature = "unstable_auth_status")]
8164 AuthStatusRequest => AuthStatusResponse: AGENT_METHOD_NAMES.auth_status,
8165 NewSessionRequest => NewSessionResponse: AGENT_METHOD_NAMES.session_new,
8166 ListSessionsRequest => ListSessionsResponse: AGENT_METHOD_NAMES.session_list,
8167 DeleteSessionRequest => DeleteSessionResponse: AGENT_METHOD_NAMES.session_delete,
8168 #[cfg(feature = "unstable_session_fork")]
8169 ForkSessionRequest => ForkSessionResponse: AGENT_METHOD_NAMES.session_fork,
8170 #[cfg(feature = "unstable_session_archive")]
8171 ArchiveSessionRequest => ArchiveSessionResponse: AGENT_METHOD_NAMES.session_archive,
8172 #[cfg(feature = "unstable_session_archive")]
8173 UnarchiveSessionRequest => UnarchiveSessionResponse: AGENT_METHOD_NAMES.session_unarchive,
8174 #[cfg(feature = "unstable_session_status")]
8175 SessionStatusRequest => SessionStatusResponse: AGENT_METHOD_NAMES.session_status,
8176 #[cfg(feature = "unstable_session_options")]
8177 SessionOptionsRequest => SessionOptionsResponse: AGENT_METHOD_NAMES.session_options,
8178 #[cfg(feature = "unstable_session_set_title")]
8179 SetSessionTitleRequest => SetSessionTitleResponse: AGENT_METHOD_NAMES.session_set_title,
8180 ResumeSessionRequest => ResumeSessionResponse: AGENT_METHOD_NAMES.session_resume,
8181 CloseSessionRequest => CloseSessionResponse: AGENT_METHOD_NAMES.session_close,
8182 CancelToolCallRequest => CancelToolCallResponse: AGENT_METHOD_NAMES.tool_call_cancel,
8183 CancelTerminalRequest => CancelTerminalResponse: AGENT_METHOD_NAMES.terminal_cancel,
8184 SetSessionConfigOptionRequest => SetSessionConfigOptionResponse: AGENT_METHOD_NAMES.session_set_config_option,
8185 PromptRequest => PromptResponse: AGENT_METHOD_NAMES.session_prompt,
8186 }
8187 extension ExtMethodRequest(Box<ExtRequest>) => ExtMethodResponse;
8188}
8189
8190#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
8197#[derive(Clone, Debug, Serialize, Deserialize)]
8198#[serde(untagged)]
8199#[cfg_attr(feature = "schemars", schemars(inline))]
8200#[non_exhaustive]
8201pub enum AgentResponse {
8202 InitializeResponse(Box<InitializeResponse>),
8204 LoginAuthResponse(#[serde(default)] Box<LoginAuthResponse>),
8206 #[cfg(feature = "unstable_llm_providers")]
8208 ListProvidersResponse(Box<ListProvidersResponse>),
8209 #[cfg(feature = "unstable_llm_providers")]
8211 SetProviderResponse(#[serde(default)] Box<SetProviderResponse>),
8212 #[cfg(feature = "unstable_llm_providers")]
8214 DisableProviderResponse(#[serde(default)] Box<DisableProviderResponse>),
8215 LogoutAuthResponse(#[serde(default)] Box<LogoutAuthResponse>),
8217 #[cfg(feature = "unstable_auth_status")]
8219 AuthStatusResponse(Box<AuthStatusResponse>),
8220 NewSessionResponse(Box<NewSessionResponse>),
8222 ListSessionsResponse(Box<ListSessionsResponse>),
8224 DeleteSessionResponse(#[serde(default)] Box<DeleteSessionResponse>),
8226 #[cfg(feature = "unstable_session_fork")]
8228 ForkSessionResponse(Box<ForkSessionResponse>),
8229 #[cfg(feature = "unstable_session_archive")]
8231 ArchiveSessionResponse(#[serde(default)] Box<ArchiveSessionResponse>),
8232 #[cfg(feature = "unstable_session_archive")]
8234 UnarchiveSessionResponse(#[serde(default)] Box<UnarchiveSessionResponse>),
8235 #[cfg(feature = "unstable_session_status")]
8237 SessionStatusResponse(Box<SessionStatusResponse>),
8238 #[cfg(feature = "unstable_session_options")]
8240 SessionOptionsResponse(#[serde(default)] Box<SessionOptionsResponse>),
8241 #[cfg(feature = "unstable_session_set_title")]
8243 SetSessionTitleResponse(Box<SetSessionTitleResponse>),
8244 ResumeSessionResponse(#[serde(default)] Box<ResumeSessionResponse>),
8246 CloseSessionResponse(#[serde(default)] Box<CloseSessionResponse>),
8248 CancelToolCallResponse(#[serde(default)] Box<CancelToolCallResponse>),
8250 CancelTerminalResponse(#[serde(default)] Box<CancelTerminalResponse>),
8252 SetSessionConfigOptionResponse(Box<SetSessionConfigOptionResponse>),
8254 PromptResponse(Box<PromptResponse>),
8256 ExtMethodResponse(Box<ExtResponse>),
8258}
8259
8260#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
8267#[derive(Clone, Debug, Serialize, Deserialize)]
8268#[serde(untagged)]
8269#[cfg_attr(feature = "schemars", schemars(inline))]
8270#[non_exhaustive]
8271pub enum ClientNotification {
8272 CancelSessionNotification(Box<CancelSessionNotification>),
8302 #[cfg(feature = "unstable_mcp_over_acp")]
8308 MessageMcpNotification(Box<MessageMcpNotification>),
8309 ExtNotification(Box<ExtNotification>),
8315}
8316
8317impl_message_dispatch! {
8318 ClientNotification {
8319 CancelSessionNotification => AGENT_METHOD_NAMES.session_cancel,
8320 #[cfg(feature = "unstable_mcp_over_acp")]
8321 MessageMcpNotification => AGENT_METHOD_NAMES.mcp_message,
8322 }
8323 extension ExtNotification(Box<ExtNotification>);
8324}
8325
8326#[cfg(test)]
8327mod test_serialization {
8328 use std::path::PathBuf;
8329
8330 use super::*;
8331 use serde_json::json;
8332
8333 fn test_meta() -> Meta {
8334 json!({ "source": "test" }).as_object().unwrap().clone()
8335 }
8336
8337 #[test]
8338 fn list_sessions_cursor_and_session_directories_are_strict() {
8339 for cursor in [json!(null), json!("next")] {
8340 let response = json!({ "sessions": [], "nextCursor": cursor });
8341 serde_json::from_value::<ListSessionsResponse>(response).unwrap();
8342 }
8343 let malformed = json!({ "sessions": [], "nextCursor": 42 });
8344 assert!(serde_json::from_value::<ListSessionsResponse>(malformed).is_err());
8345
8346 let session = |dirs: serde_json::Value| json!({ "sessionId": "s", "cwd": "/w", "additionalDirectories": dirs });
8347 let info: SessionInfo = serde_json::from_value(session(json!(null))).unwrap();
8348 assert_eq!(info.additional_directories, Vec::<AbsolutePath>::new());
8349 for bad in [json!(["/a", 42]), json!("/a")] {
8350 assert!(serde_json::from_value::<SessionInfo>(session(bad)).is_err());
8351 }
8352 let response = json!({ "sessions": [session(json!(["/a", 42]))] });
8354 let response: ListSessionsResponse = serde_json::from_value(response).unwrap();
8355 assert_eq!(response.sessions, Vec::<SessionInfo>::new());
8356 }
8357
8358 #[test]
8359 fn other_fallbacks_preserve_optional_fields_verbatim() {
8360 let valid = json!({ "type": "_custom", "methodId": "m", "name": "M",
8361 "description": "d", "_meta": { "k": 1 } });
8362 let method: AuthMethod = serde_json::from_value(valid.clone()).unwrap();
8363 assert_eq!(method.description(), Some("d"));
8364 assert_eq!(
8365 method.meta(),
8366 Some(&json!({ "k": 1 }).as_object().unwrap().clone())
8367 );
8368 assert_eq!(serde_json::to_value(&method).unwrap(), valid);
8369
8370 let malformed = json!({ "type": "_custom", "methodId": "m", "name": "M",
8372 "description": 42, "_meta": "bad", "extra": true });
8373 let method: AuthMethod = serde_json::from_value(malformed.clone()).unwrap();
8374 assert_eq!(method.description(), None);
8375 assert_eq!(method.meta(), None);
8376 assert_eq!(serde_json::to_value(&method).unwrap(), malformed);
8377
8378 let replay = json!({ "type": "_custom", "_meta": "bad", "cursor": 3 });
8379 let decoded: ReplayFrom = serde_json::from_value(replay.clone()).unwrap();
8380 assert_eq!(serde_json::to_value(&decoded).unwrap(), replay);
8381 }
8382
8383 fn serialized_meta_key_count(value: &impl serde::Serialize) -> usize {
8384 serde_json::to_string(value)
8385 .unwrap()
8386 .matches("\"_meta\"")
8387 .count()
8388 }
8389
8390 #[test]
8391 fn prompt_response_without_metadata_round_trips() {
8392 let response = PromptResponse::new(MessageId::new("message-1"));
8393 let serialized = serde_json::to_value(&response).unwrap();
8394 assert_eq!(serialized, json!({ "messageId": "message-1" }));
8395 assert_eq!(
8396 serde_json::from_value::<PromptResponse>(serialized).unwrap(),
8397 response
8398 );
8399 assert_eq!(
8400 serde_json::from_value::<PromptResponse>(json!({
8401 "messageId": "message-1",
8402 "_meta": null
8403 }))
8404 .unwrap(),
8405 response
8406 );
8407 }
8408
8409 #[test]
8410 fn prompt_response_requires_message_id_and_preserves_metadata_tolerance() {
8411 let response = PromptResponse::new("message-1").meta(test_meta());
8412 let serialized = serde_json::to_value(&response).unwrap();
8413 assert_eq!(
8414 serialized,
8415 json!({
8416 "messageId": "message-1",
8417 "_meta": { "source": "test" }
8418 })
8419 );
8420
8421 let deserialized: PromptResponse = serde_json::from_value(serialized).unwrap();
8422 assert_eq!(deserialized.message_id, MessageId::new("message-1"));
8423 assert_eq!(deserialized.meta, Some(test_meta()));
8424
8425 let malformed_meta: PromptResponse = serde_json::from_value(json!({
8426 "messageId": "message-2",
8427 "_meta": false
8428 }))
8429 .unwrap();
8430 assert_eq!(malformed_meta.message_id, MessageId::new("message-2"));
8431 assert_eq!(malformed_meta.meta, None);
8432
8433 for invalid in [
8434 json!({}),
8435 json!({ "messageId": null }),
8436 json!({ "messageId": 1 }),
8437 json!({ "messageId": false }),
8438 json!({ "messageId": {} }),
8439 json!({ "messageId": [] }),
8440 ] {
8441 assert!(
8442 serde_json::from_value::<PromptResponse>(invalid).is_err(),
8443 "missing, null, and non-string message IDs must be rejected"
8444 );
8445 }
8446 }
8447
8448 #[cfg(feature = "schemars")]
8449 #[test]
8450 fn prompt_response_schema_requires_non_null_string_message_id_reference() {
8451 let schema = serde_json::to_value(schemars::schema_for!(PromptResponse)).unwrap();
8452
8453 assert_eq!(schema["required"], json!(["messageId"]));
8454 assert_eq!(
8455 schema["properties"]["messageId"]["$ref"],
8456 "#/$defs/MessageId"
8457 );
8458 assert_eq!(schema["$defs"]["MessageId"]["type"], "string");
8459 }
8460
8461 #[test]
8462 fn test_initialize_capabilities_default_on_malformed_values() {
8463 let request: InitializeRequest = serde_json::from_value(json!({
8464 "protocolVersion": 2,
8465 "capabilities": false,
8466 "info": {
8467 "name": "client",
8468 "version": "1.0.0"
8469 }
8470 }))
8471 .unwrap();
8472 assert_eq!(request.capabilities, ClientCapabilities::default());
8473
8474 let response: InitializeResponse = serde_json::from_value(json!({
8475 "protocolVersion": 2,
8476 "capabilities": false,
8477 "info": {
8478 "name": "agent",
8479 "version": "1.0.0"
8480 }
8481 }))
8482 .unwrap();
8483 assert_eq!(response.capabilities, AgentCapabilities::default());
8484 }
8485
8486 #[test]
8487 fn test_agent_capabilities_default_on_malformed_values() {
8488 let capabilities: AgentCapabilities = serde_json::from_value(json!({
8489 "session": false,
8490 "auth": false
8491 }))
8492 .unwrap();
8493
8494 assert!(capabilities.session.is_none());
8495 assert_eq!(capabilities.auth, None);
8496 }
8497
8498 #[test]
8499 fn test_mcp_server_stdio_serialization() {
8500 let server = McpServer::Stdio(
8501 McpServerStdio::new("test-server", "/usr/bin/server")
8502 .args(vec!["--port".to_string(), "3000".to_string()])
8503 .env(vec![EnvVariable::new("API_KEY", "secret123")]),
8504 );
8505
8506 let json = serde_json::to_value(&server).unwrap();
8507 assert_eq!(
8508 json,
8509 json!({
8510 "type": "stdio",
8511 "name": "test-server",
8512 "command": "/usr/bin/server",
8513 "args": ["--port", "3000"],
8514 "env": [
8515 {
8516 "name": "API_KEY",
8517 "value": "secret123"
8518 }
8519 ]
8520 })
8521 );
8522
8523 let deserialized: McpServer = serde_json::from_value(json).unwrap();
8524 match deserialized {
8525 McpServer::Stdio(McpServerStdio {
8526 name,
8527 command,
8528 args,
8529 env,
8530 meta: _,
8531 }) => {
8532 assert_eq!(name, "test-server");
8533 assert_eq!(command, AbsolutePath::new("/usr/bin/server"));
8534 assert_eq!(args, vec!["--port", "3000"]);
8535 assert_eq!(env.len(), 1);
8536 assert_eq!(env[0].name, "API_KEY");
8537 assert_eq!(env[0].value, "secret123");
8538 }
8539 _ => panic!("Expected Stdio variant"),
8540 }
8541 }
8542
8543 #[test]
8544 fn test_mcp_server_empty_arrays_are_optional() {
8545 let stdio = McpServer::Stdio(McpServerStdio::new("test-server", "/usr/bin/server"));
8546 assert_eq!(
8547 serde_json::to_value(&stdio).unwrap(),
8548 json!({
8549 "type": "stdio",
8550 "name": "test-server",
8551 "command": "/usr/bin/server"
8552 })
8553 );
8554
8555 let McpServer::Stdio(McpServerStdio { args, env, .. }) =
8556 serde_json::from_value::<McpServer>(json!({
8557 "type": "stdio",
8558 "name": "test-server",
8559 "command": "/usr/bin/server"
8560 }))
8561 .unwrap()
8562 else {
8563 panic!("Expected Stdio variant");
8564 };
8565 assert_eq!(args, Vec::<String>::new());
8566 assert_eq!(env, []);
8567
8568 let http = McpServer::Http(McpServerHttp::new("http-server", "https://api.example.com"));
8569 assert_eq!(
8570 serde_json::to_value(&http).unwrap(),
8571 json!({
8572 "type": "http",
8573 "name": "http-server",
8574 "url": "https://api.example.com"
8575 })
8576 );
8577
8578 let McpServer::Http(McpServerHttp { headers, .. }) =
8579 serde_json::from_value::<McpServer>(json!({
8580 "type": "http",
8581 "name": "http-server",
8582 "url": "https://api.example.com"
8583 }))
8584 .unwrap()
8585 else {
8586 panic!("Expected Http variant");
8587 };
8588 assert_eq!(headers, []);
8589 }
8590
8591 #[test]
8592 fn test_mcp_server_unknown_transport_serialization() {
8593 let json = json!({
8594 "type": "websocket",
8595 "name": "future-server",
8596 "url": "wss://example.com/mcp",
8597 "protocolVersion": "2026-01-01"
8598 });
8599
8600 let deserialized: McpServer = serde_json::from_value(json.clone()).unwrap();
8601 let McpServer::Other(OtherMcpServer { type_, fields }) = &deserialized else {
8602 panic!("Expected Other variant");
8603 };
8604
8605 assert_eq!(type_, "websocket");
8606 assert_eq!(fields["name"], "future-server");
8607 assert_eq!(fields["url"], "wss://example.com/mcp");
8608 assert_eq!(fields["protocolVersion"], "2026-01-01");
8609 assert_eq!(serde_json::to_value(&deserialized).unwrap(), json);
8610 }
8611
8612 #[test]
8613 fn test_mcp_server_stdio_requires_type() {
8614 let result = serde_json::from_value::<McpServer>(json!({
8615 "name": "test-server",
8616 "command": "/usr/bin/server",
8617 "args": [],
8618 "env": []
8619 }));
8620
8621 assert!(result.is_err());
8622 }
8623
8624 #[test]
8625 fn test_mcp_server_unknown_does_not_hide_malformed_known_transport() {
8626 let result = serde_json::from_value::<McpServer>(json!({
8627 "type": "stdio",
8628 "name": "test-server",
8629 "args": [],
8630 "env": []
8631 }));
8632
8633 assert!(result.is_err());
8634 }
8635
8636 #[test]
8637 fn test_mcp_server_http_serialization() {
8638 let server = McpServer::Http(
8639 McpServerHttp::new("http-server", "https://api.example.com").headers(vec![
8640 HttpHeader::new("Authorization", "Bearer token123"),
8641 HttpHeader::new("Content-Type", "application/json"),
8642 ]),
8643 );
8644
8645 let json = serde_json::to_value(&server).unwrap();
8646 assert_eq!(
8647 json,
8648 json!({
8649 "type": "http",
8650 "name": "http-server",
8651 "url": "https://api.example.com",
8652 "headers": [
8653 {
8654 "name": "Authorization",
8655 "value": "Bearer token123"
8656 },
8657 {
8658 "name": "Content-Type",
8659 "value": "application/json"
8660 }
8661 ]
8662 })
8663 );
8664
8665 let deserialized: McpServer = serde_json::from_value(json).unwrap();
8666 match deserialized {
8667 McpServer::Http(McpServerHttp {
8668 name,
8669 url,
8670 headers,
8671 meta: _,
8672 }) => {
8673 assert_eq!(name, "http-server");
8674 assert_eq!(url, "https://api.example.com");
8675 assert_eq!(headers.len(), 2);
8676 assert_eq!(headers[0].name, "Authorization");
8677 assert_eq!(headers[0].value, "Bearer token123");
8678 assert_eq!(headers[1].name, "Content-Type");
8679 assert_eq!(headers[1].value, "application/json");
8680 }
8681 _ => panic!("Expected Http variant"),
8682 }
8683 }
8684
8685 #[cfg(feature = "schemars")]
8686 #[test]
8687 fn mcp_server_http_schema_marks_url_as_uri() {
8688 let schema = serde_json::to_value(schemars::schema_for!(McpServerHttp)).unwrap();
8689
8690 assert_eq!(schema["properties"]["url"]["format"], "uri");
8691 }
8692
8693 #[cfg(feature = "unstable_mcp_over_acp")]
8694 #[test]
8695 fn test_client_mcp_message_method_names() {
8696 use serde_json::json;
8697
8698 assert_eq!(AGENT_METHOD_NAMES.mcp_message, "mcp/message");
8699
8700 let notification =
8701 MessageMcpNotification::new("server-1", "req-1", "notifications/progress");
8702 assert_eq!(
8703 ClientNotification::MessageMcpNotification(Box::new(notification.clone())).method(),
8704 "mcp/message"
8705 );
8706 assert_eq!(
8707 serde_json::to_value(notification).unwrap(),
8708 json!({
8709 "serverId": "server-1",
8710 "requestId": "req-1",
8711 "method": "notifications/progress"
8712 })
8713 );
8714 let notification: MessageMcpNotification = serde_json::from_value(json!({
8715 "serverId": "server-1", "requestId": "req-1", "method": "notifications/progress",
8716 "params": null, "_meta": null
8717 }))
8718 .unwrap();
8719 assert_eq!(notification.params, None);
8720 assert_eq!(notification.meta, None);
8721 for key in ["serverId", "requestId", "method"] {
8722 let mut value = json!({"serverId":"server-1", "requestId":"req-1", "method":"notifications/progress"});
8723 value.as_object_mut().unwrap().remove(key);
8724 assert!(serde_json::from_value::<MessageMcpNotification>(value).is_err());
8725 }
8726 }
8727
8728 #[test]
8729 fn test_auth_method_names() {
8730 assert_eq!(AGENT_METHOD_NAMES.auth_login, "auth/login");
8731 assert_eq!(AGENT_METHOD_NAMES.auth_logout, "auth/logout");
8732
8733 assert_eq!(
8734 ClientRequest::LoginAuthRequest(Box::new(LoginAuthRequest::new("agent-login")))
8735 .method(),
8736 "auth/login"
8737 );
8738 assert_eq!(
8739 ClientRequest::LogoutAuthRequest(Box::new(LogoutAuthRequest::new())).method(),
8740 "auth/logout"
8741 );
8742 }
8743
8744 #[test]
8745 fn test_session_config_option_category_known_variants() {
8746 assert_eq!(
8748 serde_json::to_value(&SessionConfigOptionCategory::Mode).unwrap(),
8749 json!("mode")
8750 );
8751 assert_eq!(
8752 serde_json::to_value(&SessionConfigOptionCategory::Model).unwrap(),
8753 json!("model")
8754 );
8755 assert_eq!(
8756 serde_json::to_value(&SessionConfigOptionCategory::ModelConfig).unwrap(),
8757 json!("model_config")
8758 );
8759 #[cfg(feature = "unstable_speed_config_category")]
8760 assert_eq!(
8761 serde_json::to_value(&SessionConfigOptionCategory::Speed).unwrap(),
8762 json!("speed")
8763 );
8764 assert_eq!(
8765 serde_json::to_value(&SessionConfigOptionCategory::ThoughtLevel).unwrap(),
8766 json!("thought_level")
8767 );
8768
8769 assert_eq!(
8771 serde_json::from_str::<SessionConfigOptionCategory>("\"mode\"").unwrap(),
8772 SessionConfigOptionCategory::Mode
8773 );
8774 assert_eq!(
8775 serde_json::from_str::<SessionConfigOptionCategory>("\"model\"").unwrap(),
8776 SessionConfigOptionCategory::Model
8777 );
8778 assert_eq!(
8779 serde_json::from_str::<SessionConfigOptionCategory>("\"model_config\"").unwrap(),
8780 SessionConfigOptionCategory::ModelConfig
8781 );
8782 #[cfg(feature = "unstable_speed_config_category")]
8783 assert_eq!(
8784 serde_json::from_str::<SessionConfigOptionCategory>("\"speed\"").unwrap(),
8785 SessionConfigOptionCategory::Speed
8786 );
8787 assert_eq!(
8788 serde_json::from_str::<SessionConfigOptionCategory>("\"thought_level\"").unwrap(),
8789 SessionConfigOptionCategory::ThoughtLevel
8790 );
8791 }
8792
8793 #[test]
8794 fn test_session_config_option_category_unknown_variants() {
8795 let unknown: SessionConfigOptionCategory =
8797 serde_json::from_str("\"some_future_category\"").unwrap();
8798 assert_eq!(
8799 unknown,
8800 SessionConfigOptionCategory::Other("some_future_category".to_string())
8801 );
8802
8803 let json = serde_json::to_value(&unknown).unwrap();
8805 assert_eq!(json, json!("some_future_category"));
8806 }
8807
8808 #[cfg(not(feature = "unstable_speed_config_category"))]
8809 #[test]
8810 fn test_session_config_option_speed_is_unknown_without_feature() {
8811 let unknown: SessionConfigOptionCategory = serde_json::from_str("\"speed\"").unwrap();
8812 assert_eq!(
8813 unknown,
8814 SessionConfigOptionCategory::Other("speed".to_string())
8815 );
8816 }
8817
8818 #[test]
8819 fn test_session_config_option_category_custom_categories() {
8820 let custom: SessionConfigOptionCategory =
8822 serde_json::from_str("\"_my_custom_category\"").unwrap();
8823 assert_eq!(
8824 custom,
8825 SessionConfigOptionCategory::Other("_my_custom_category".to_string())
8826 );
8827
8828 let json = serde_json::to_value(&custom).unwrap();
8830 assert_eq!(json, json!("_my_custom_category"));
8831
8832 let deserialized: SessionConfigOptionCategory = serde_json::from_value(json).unwrap();
8834 assert_eq!(
8835 deserialized,
8836 SessionConfigOptionCategory::Other("_my_custom_category".to_string()),
8837 );
8838 }
8839
8840 fn test_config_option() -> SessionConfigOption {
8841 SessionConfigOption::select(
8842 "mode",
8843 "Mode",
8844 "ask",
8845 vec![SessionConfigSelectOption::new("ask", "Ask")],
8846 )
8847 }
8848
8849 #[test]
8850 fn test_session_response_initial_state_default_empty_and_skip_serializing() {
8851 assert_eq!(
8852 serde_json::to_value(NewSessionResponse::new("sess")).unwrap(),
8853 json!({ "sessionId": "sess" })
8854 );
8855 assert_eq!(
8856 serde_json::to_value(ResumeSessionResponse::new()).unwrap(),
8857 json!({})
8858 );
8859 #[cfg(feature = "unstable_session_fork")]
8860 assert_eq!(
8861 serde_json::to_value(ForkSessionResponse::new("fork")).unwrap(),
8862 json!({ "sessionId": "fork" })
8863 );
8864
8865 let json = serde_json::to_value(
8866 NewSessionResponse::new("sess").config_options(vec![test_config_option()]),
8867 )
8868 .unwrap();
8869 assert_eq!(json["configOptions"].as_array().unwrap().len(), 1);
8870 }
8871
8872 #[test]
8873 fn test_session_response_config_options_deserialize_missing_null_and_invalid() {
8874 let missing: NewSessionResponse =
8875 serde_json::from_value(json!({ "sessionId": "sess" })).unwrap();
8876 assert_eq!(missing.config_options, []);
8877
8878 let null: NewSessionResponse = serde_json::from_value(json!({
8879 "sessionId": "sess",
8880 "configOptions": null
8881 }))
8882 .unwrap();
8883 assert_eq!(null.config_options, []);
8884
8885 let wrong_shape: NewSessionResponse = serde_json::from_value(json!({
8886 "sessionId": "sess",
8887 "configOptions": "oops"
8888 }))
8889 .unwrap();
8890 assert_eq!(wrong_shape.config_options, []);
8891
8892 let valid_option = serde_json::to_value(test_config_option()).unwrap();
8893 let mixed: NewSessionResponse = serde_json::from_value(json!({
8894 "sessionId": "sess",
8895 "configOptions": ["oops", valid_option]
8896 }))
8897 .unwrap();
8898 assert_eq!(mixed.config_options.len(), 1);
8899
8900 let resume: ResumeSessionResponse = serde_json::from_value(json!({})).unwrap();
8901 assert_eq!(resume.config_options, []);
8902 #[cfg(feature = "unstable_session_fork")]
8903 {
8904 let fork: ForkSessionResponse =
8905 serde_json::from_value(json!({ "sessionId": "fork" })).unwrap();
8906 assert_eq!(fork.config_options, []);
8907 }
8908 }
8909
8910 #[test]
8911 fn test_session_response_available_commands_roundtrip_with_config_options() {
8912 use super::super::{AvailableCommandInput, Command, TextCommandInput};
8913
8914 let commands = vec![
8915 AvailableCommand::Command(
8916 Command::new("web", "Search the web")
8917 .input(AvailableCommandInput::Text(TextCommandInput::new("Query"))),
8918 ),
8919 AvailableCommand::Command(Command::new("test", "Run project tests")),
8920 ];
8921 let mut expected = json!({
8922 "sessionId": "sess",
8923 "configOptions": [test_config_option()],
8924 "availableCommands": [
8925 {
8926 "type": "command",
8927 "name": "web",
8928 "description": "Search the web",
8929 "input": { "type": "text", "hint": "Query" }
8930 },
8931 { "type": "command", "name": "test", "description": "Run project tests" }
8932 ]
8933 });
8934
8935 let new = NewSessionResponse::new("sess")
8936 .config_options(vec![test_config_option()])
8937 .available_commands(commands.clone());
8938 assert_eq!(serde_json::to_value(&new).unwrap(), expected);
8939 assert_eq!(
8940 serde_json::from_value::<NewSessionResponse>(expected.clone()).unwrap(),
8941 new
8942 );
8943
8944 expected.as_object_mut().unwrap().remove("sessionId");
8945 let resume = ResumeSessionResponse::new()
8946 .config_options(vec![test_config_option()])
8947 .available_commands(commands.clone());
8948 assert_eq!(serde_json::to_value(&resume).unwrap(), expected);
8949 assert_eq!(
8950 serde_json::from_value::<ResumeSessionResponse>(expected.clone()).unwrap(),
8951 resume
8952 );
8953
8954 #[cfg(feature = "unstable_session_fork")]
8955 {
8956 expected["sessionId"] = json!("fork");
8957 let fork = ForkSessionResponse::new("fork")
8958 .config_options(vec![test_config_option()])
8959 .available_commands(commands);
8960 assert_eq!(serde_json::to_value(&fork).unwrap(), expected);
8961 assert_eq!(
8962 serde_json::from_value::<ForkSessionResponse>(expected).unwrap(),
8963 fork
8964 );
8965 }
8966 }
8967
8968 #[test]
8969 fn test_session_response_available_commands_deserialize_missing_null_and_invalid() {
8970 let command =
8971 AvailableCommand::Command(super::super::Command::new("test", "Run project tests"));
8972 let config_options = vec![test_config_option()];
8973
8974 for (commands, expected) in [
8975 (None, vec![]),
8976 (Some(json!(null)), vec![]),
8977 (Some(json!([])), vec![]),
8978 (Some(json!("oops")), vec![]),
8979 (Some(json!({})), vec![]),
8980 (Some(json!([null, {}, { "name": "invalid" }])), vec![]),
8981 (
8982 Some(json!([{ "name": "test", "description": "Run project tests" }])),
8983 vec![],
8984 ),
8985 (
8986 Some(json!([null, command, { "name": "invalid" }])),
8987 vec![command.clone()],
8988 ),
8989 ] {
8990 let mut value = json!({
8991 "sessionId": "sess",
8992 "configOptions": config_options
8993 });
8994 if let Some(commands) = commands {
8995 value["availableCommands"] = commands;
8996 }
8997
8998 let new: NewSessionResponse = serde_json::from_value(value.clone()).unwrap();
8999 assert_eq!(new.available_commands, expected);
9000 assert_eq!(new.config_options, config_options);
9001
9002 #[cfg(feature = "unstable_session_fork")]
9003 {
9004 let fork: ForkSessionResponse = serde_json::from_value(value.clone()).unwrap();
9005 assert_eq!(fork.available_commands, expected);
9006 assert_eq!(fork.config_options, config_options);
9007 }
9008
9009 value.as_object_mut().unwrap().remove("sessionId");
9010 let resume: ResumeSessionResponse = serde_json::from_value(value).unwrap();
9011 assert_eq!(resume.available_commands, expected);
9012 assert_eq!(resume.config_options, config_options);
9013 }
9014
9015 let resume: ResumeSessionResponse = serde_json::from_value(json!(null)).unwrap();
9016 assert_eq!(resume.available_commands, []);
9017 }
9018
9019 #[test]
9020 fn test_resume_session_replay_from_serialization() {
9021 assert_eq!(
9022 serde_json::to_value(ResumeSessionRequest::new(
9023 "sess_abc123",
9024 "/home/user/project"
9025 ))
9026 .unwrap(),
9027 json!({
9028 "sessionId": "sess_abc123",
9029 "cwd": "/home/user/project"
9030 })
9031 );
9032 assert_eq!(
9033 serde_json::to_value(
9034 ResumeSessionRequest::new("sess_abc123", "/home/user/project")
9035 .replay_from(ReplayFrom::from(ReplayFromStart::new()))
9036 )
9037 .unwrap(),
9038 json!({
9039 "sessionId": "sess_abc123",
9040 "cwd": "/home/user/project",
9041 "replayFrom": {
9042 "type": "start"
9043 }
9044 })
9045 );
9046
9047 let replay: ResumeSessionRequest = serde_json::from_value(json!({
9048 "sessionId": "sess_abc123",
9049 "cwd": "/home/user/project",
9050 "replayFrom": {
9051 "type": "start"
9052 }
9053 }))
9054 .unwrap();
9055 assert!(matches!(replay.replay_from, Some(ReplayFrom::Start(_))));
9056
9057 let none: ResumeSessionRequest = serde_json::from_value(json!({
9058 "sessionId": "sess_abc123",
9059 "cwd": "/home/user/project",
9060 "replayFrom": null
9061 }))
9062 .unwrap();
9063 assert!(none.replay_from.is_none());
9064 }
9065
9066 #[test]
9067 fn test_auth_method_agent_serialization() {
9068 let method = AuthMethod::Agent(AuthMethodAgent::new("default-auth", "Default Auth"));
9069
9070 let json = serde_json::to_value(&method).unwrap();
9071 assert_eq!(
9072 json,
9073 json!({
9074 "methodId": "default-auth",
9075 "name": "Default Auth",
9076 "type": "agent"
9077 })
9078 );
9079 assert!(!json.as_object().unwrap().contains_key("description"));
9081
9082 let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9083 match deserialized {
9084 AuthMethod::Agent(AuthMethodAgent {
9085 method_id, name, ..
9086 }) => {
9087 assert_eq!(method_id.0.as_ref(), "default-auth");
9088 assert_eq!(name, "Default Auth");
9089 }
9090 _ => panic!("Expected Agent variant"),
9091 }
9092 }
9093
9094 #[test]
9095 fn test_auth_method_agent_deserialization() {
9096 let json = json!({
9097 "methodId": "agent-auth",
9098 "name": "Agent Auth",
9099 "type": "agent"
9100 });
9101
9102 let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9103 assert!(matches!(deserialized, AuthMethod::Agent(_)));
9104 }
9105
9106 #[test]
9107 fn test_auth_method_agent_requires_type() {
9108 assert!(
9109 serde_json::from_value::<AuthMethod>(json!({
9110 "methodId": "agent-auth",
9111 "name": "Agent Auth"
9112 }))
9113 .is_err()
9114 );
9115 }
9116
9117 #[test]
9118 fn test_auth_method_agent_rejects_null_type() {
9119 assert!(
9120 serde_json::from_value::<AuthMethod>(json!({
9121 "methodId": "agent-auth",
9122 "name": "Agent Auth",
9123 "type": null
9124 }))
9125 .is_err()
9126 );
9127 }
9128
9129 #[test]
9130 fn test_auth_method_unknown_does_not_hide_malformed_agent() {
9131 assert!(
9132 serde_json::from_value::<AuthMethod>(json!({
9133 "methodId": "agent-auth",
9134 "type": "agent"
9135 }))
9136 .is_err()
9137 );
9138 assert!(
9139 serde_json::from_value::<AuthMethod>(json!({
9140 "methodId": "api-key",
9141 "type": "env_var",
9142 "vars": [{"name": "API_KEY"}]
9143 }))
9144 .is_err()
9145 );
9146 }
9147
9148 #[test]
9149 fn test_auth_method_unknown_variant_roundtrip() {
9150 let method: AuthMethod = serde_json::from_value(json!({
9151 "methodId": "oauth",
9152 "name": "OAuth",
9153 "type": "_oauth",
9154 "authorizationUrl": "https://example.com/auth"
9155 }))
9156 .unwrap();
9157
9158 assert_eq!(method.method_id().0.as_ref(), "oauth");
9159 assert_eq!(method.name(), "OAuth");
9160 let AuthMethod::Other(unknown) = method else {
9161 panic!("expected unknown auth method");
9162 };
9163 assert_eq!(unknown.type_, "_oauth");
9164 assert_eq!(
9165 unknown.fields.get("authorizationUrl"),
9166 Some(&json!("https://example.com/auth"))
9167 );
9168
9169 assert_eq!(
9170 serde_json::to_value(AuthMethod::Other(unknown)).unwrap(),
9171 json!({
9172 "methodId": "oauth",
9173 "name": "OAuth",
9174 "type": "_oauth",
9175 "authorizationUrl": "https://example.com/auth"
9176 })
9177 );
9178 }
9179
9180 #[test]
9181 fn test_auth_method_unknown_does_not_hide_malformed_known_variant() {
9182 assert!(
9183 serde_json::from_value::<AuthMethod>(json!({
9184 "methodId": "terminal-auth",
9185 "type": "terminal"
9186 }))
9187 .is_err()
9188 );
9189 }
9190
9191 #[test]
9192 fn test_tool_call_and_terminal_cancel_serialization() {
9193 assert_eq!(AGENT_METHOD_NAMES.tool_call_cancel, "tool_call/cancel");
9194 assert_eq!(AGENT_METHOD_NAMES.terminal_cancel, "terminal/cancel");
9195 assert_eq!(
9196 ClientRequest::CancelToolCallRequest(Box::new(CancelToolCallRequest::new(
9197 "sess_abc123",
9198 "call_012"
9199 )))
9200 .method(),
9201 "tool_call/cancel"
9202 );
9203 assert_eq!(
9204 ClientRequest::CancelTerminalRequest(Box::new(CancelTerminalRequest::new(
9205 "sess_abc123",
9206 "term_003"
9207 )))
9208 .method(),
9209 "terminal/cancel"
9210 );
9211 assert_eq!(
9212 serde_json::to_value(CancelToolCallRequest::new("sess_abc123", "call_012")).unwrap(),
9213 json!({"sessionId": "sess_abc123", "toolCallId": "call_012"})
9214 );
9215 assert_eq!(
9216 serde_json::to_value(CancelTerminalRequest::new("sess_abc123", "term_003")).unwrap(),
9217 json!({"sessionId": "sess_abc123", "terminalId": "term_003"})
9218 );
9219 assert!(
9220 serde_json::from_value::<CancelToolCallRequest>(json!({"sessionId": "sess_abc123"}))
9221 .is_err()
9222 );
9223 assert_eq!(
9224 serde_json::to_value(CancelTerminalResponse::new()).unwrap(),
9225 json!({})
9226 );
9227 }
9228
9229 #[test]
9230 fn test_session_delete_serialization() {
9231 assert_eq!(AGENT_METHOD_NAMES.session_delete, "session/delete");
9232 assert_eq!(
9233 ClientRequest::DeleteSessionRequest(Box::new(DeleteSessionRequest::new("sess_abc123")))
9234 .method(),
9235 "session/delete"
9236 );
9237 assert_eq!(
9238 serde_json::to_value(DeleteSessionRequest::new("sess_abc123")).unwrap(),
9239 json!({
9240 "sessionId": "sess_abc123"
9241 })
9242 );
9243 assert_eq!(
9244 serde_json::to_value(DeleteSessionResponse::new()).unwrap(),
9245 json!({})
9246 );
9247 assert_eq!(
9248 serde_json::to_value(
9249 SessionCapabilities::new().delete(SessionDeleteCapabilities::new())
9250 )
9251 .unwrap(),
9252 json!({
9253 "delete": {}
9254 })
9255 );
9256 }
9257 #[cfg(feature = "unstable_session_set_title")]
9258 #[test]
9259 fn test_session_set_title_serialization() {
9260 assert_eq!(AGENT_METHOD_NAMES.session_set_title, "session/set_title");
9261 assert_eq!(
9262 ClientRequest::SetSessionTitleRequest(Box::new(SetSessionTitleRequest::new(
9263 "sess_abc123",
9264 "Investigate OAuth timeout"
9265 )))
9266 .method(),
9267 "session/set_title"
9268 );
9269 assert_eq!(
9270 serde_json::to_value(SetSessionTitleRequest::new(
9271 "sess_abc123",
9272 "Investigate OAuth timeout"
9273 ))
9274 .unwrap(),
9275 json!({
9276 "sessionId": "sess_abc123",
9277 "title": "Investigate OAuth timeout"
9278 })
9279 );
9280 assert_eq!(
9281 serde_json::to_value(SetSessionTitleResponse::new("Investigate OAuth timeout"))
9282 .unwrap(),
9283 json!({
9284 "title": "Investigate OAuth timeout"
9285 })
9286 );
9287 assert_eq!(
9288 serde_json::to_value(SessionCapabilities::new().title(SessionTitleCapabilities::new()))
9289 .unwrap(),
9290 json!({
9291 "title": {}
9292 })
9293 );
9294 }
9295
9296 #[cfg(feature = "unstable_session_set_title")]
9297 #[test]
9298 fn test_session_set_title_requires_title() {
9299 for params in [
9300 json!({"sessionId": "sess_abc123"}),
9301 json!({"sessionId": "sess_abc123", "title": null}),
9302 json!({"sessionId": "sess_abc123", "title": 42}),
9303 ] {
9304 assert!(serde_json::from_value::<SetSessionTitleRequest>(params).is_err());
9305 }
9306 for result in [json!({}), json!({"title": null})] {
9307 assert!(serde_json::from_value::<SetSessionTitleResponse>(result).is_err());
9308 }
9309 }
9310
9311 #[cfg(feature = "unstable_session_options")]
9312 #[test]
9313 fn test_session_options_serialization() {
9314 assert_eq!(AGENT_METHOD_NAMES.session_options, "session/options");
9315 assert_eq!(
9316 ClientRequest::SessionOptionsRequest(Box::new(SessionOptionsRequest::new(
9317 "/home/user/project"
9318 )))
9319 .method(),
9320 "session/options"
9321 );
9322 assert_eq!(
9323 serde_json::to_value(
9324 SessionOptionsRequest::new("/home/user/project")
9325 .session_id(SessionId::new("sess_abc123"))
9326 )
9327 .unwrap(),
9328 json!({"cwd": "/home/user/project", "sessionId": "sess_abc123"})
9329 );
9330 assert_eq!(
9331 serde_json::from_value::<SessionOptionsRequest>(
9332 json!({"cwd": "/home/user/project", "additionalDirectories": null, "sessionId": null})
9333 )
9334 .unwrap(),
9335 SessionOptionsRequest::new("/home/user/project")
9336 );
9337 let request = NewSessionRequest::new("/home/user/project").config_options(vec![
9338 InitialSessionConfigOption::new("model", SessionConfigOptionValue::id("model-2")),
9339 InitialSessionConfigOption::new("fast", SessionConfigOptionValue::boolean(true)),
9340 ]);
9341 let value = serde_json::to_value(&request).unwrap();
9342 assert_eq!(
9343 value["configOptions"],
9344 json!([
9345 {"configId": "model", "type": "id", "value": "model-2"},
9346 {"configId": "fast", "type": "boolean", "value": true}
9347 ])
9348 );
9349 assert_eq!(
9350 serde_json::from_value::<NewSessionRequest>(value).unwrap(),
9351 request
9352 );
9353 assert!(
9354 serde_json::from_value::<NewSessionRequest>(json!({
9355 "cwd": "/home/user/project",
9356 "mcpServers": [],
9357 "configOptions": [{"type": "boolean", "value": true}]
9358 }))
9359 .is_err()
9360 );
9361 assert_eq!(
9362 serde_json::to_value(SessionOptionsResponse::new()).unwrap(),
9363 json!({})
9364 );
9365 #[cfg(feature = "unstable_session_fork")]
9366 {
9367 let fork =
9368 ForkSessionRequest::new("sess_abc123", "/home/user/project").config_options(vec![
9369 InitialSessionConfigOption::new(
9370 "model",
9371 SessionConfigOptionValue::id("model-2"),
9372 ),
9373 ]);
9374 let value = serde_json::to_value(&fork).unwrap();
9375 assert_eq!(
9376 value["configOptions"],
9377 json!([{"configId": "model", "type": "id", "value": "model-2"}])
9378 );
9379 assert_eq!(
9380 serde_json::from_value::<ForkSessionRequest>(value).unwrap(),
9381 fork
9382 );
9383 assert_eq!(
9385 serde_json::from_value::<ForkSessionRequest>(json!({
9386 "sessionId": "sess_abc123",
9387 "cwd": "/home/user/project",
9388 "configOptions": null
9389 }))
9390 .unwrap(),
9391 ForkSessionRequest::new("sess_abc123", "/home/user/project")
9392 );
9393 assert!(
9394 serde_json::from_value::<ForkSessionRequest>(json!({
9395 "sessionId": "sess_abc123",
9396 "cwd": "/home/user/project",
9397 "configOptions": [{"type": "boolean", "value": true}]
9398 }))
9399 .is_err()
9400 );
9401 }
9402 assert_eq!(
9403 serde_json::to_value(
9404 SessionCapabilities::new().options(SessionOptionsCapabilities::new())
9405 )
9406 .unwrap(),
9407 json!({"options": {}})
9408 );
9409 }
9410
9411 #[cfg(feature = "unstable_session_status")]
9412 #[test]
9413 fn test_session_status_serialization() {
9414 assert_eq!(AGENT_METHOD_NAMES.session_status, "session/status");
9415 assert_eq!(
9416 ClientRequest::SessionStatusRequest(Box::new(SessionStatusRequest::new("sess_abc123")))
9417 .method(),
9418 "session/status"
9419 );
9420 assert_eq!(
9421 serde_json::to_value(SessionStatusRequest::new("sess_abc123")).unwrap(),
9422 json!({"sessionId": "sess_abc123"})
9423 );
9424 assert_eq!(
9425 serde_json::to_value(SessionStatusResponse::new(SessionStatus::Saved)).unwrap(),
9426 json!({"status": "saved"})
9427 );
9428 assert_eq!(
9429 serde_json::to_value(
9430 SessionCapabilities::new().status(SessionStatusCapabilities::new())
9431 )
9432 .unwrap(),
9433 json!({"status": {}})
9434 );
9435 assert_eq!(
9436 serde_json::to_value(SessionStatusResponse::new(SessionStatus::Open).state(
9437 StateUpdate::RequiresAction(crate::v2::RequiresActionStateUpdate::new())
9438 ))
9439 .unwrap(),
9440 json!({
9441 "status": "open",
9442 "state": {"state": "requires_action"}
9443 })
9444 );
9445 for state in [json!(null), json!("running"), json!({"state": 7})] {
9446 let response = serde_json::from_value::<SessionStatusResponse>(
9447 json!({"status": "open", "state": state}),
9448 )
9449 .unwrap();
9450 assert_eq!(response.state, None);
9451 }
9452 }
9453
9454 #[cfg(feature = "unstable_session_status")]
9455 #[test]
9456 fn test_session_status_is_strict_and_open() {
9457 let custom =
9458 serde_json::from_value::<SessionStatusResponse>(json!({"status": "_suspended"}))
9459 .unwrap();
9460 assert_eq!(
9461 custom.status,
9462 SessionStatus::Other("_suspended".to_string())
9463 );
9464 assert_eq!(
9465 serde_json::to_value(&custom).unwrap(),
9466 json!({"status": "_suspended"})
9467 );
9468 for result in [json!({}), json!({"status": null}), json!({"status": 1})] {
9469 assert!(serde_json::from_value::<SessionStatusResponse>(result).is_err());
9470 }
9471 for params in [json!({}), json!({"sessionId": null})] {
9472 assert!(serde_json::from_value::<SessionStatusRequest>(params).is_err());
9473 }
9474 }
9475
9476 #[cfg(feature = "unstable_session_archive")]
9477 #[test]
9478 fn test_session_archive_serialization() {
9479 assert_eq!(AGENT_METHOD_NAMES.session_archive, "session/archive");
9480 assert_eq!(AGENT_METHOD_NAMES.session_unarchive, "session/unarchive");
9481 assert_eq!(
9482 ClientRequest::ArchiveSessionRequest(Box::new(ArchiveSessionRequest::new(
9483 "sess_abc123"
9484 )))
9485 .method(),
9486 "session/archive"
9487 );
9488 assert_eq!(
9489 ClientRequest::UnarchiveSessionRequest(Box::new(UnarchiveSessionRequest::new(
9490 "sess_abc123"
9491 )))
9492 .method(),
9493 "session/unarchive"
9494 );
9495 assert_eq!(
9496 serde_json::to_value(ArchiveSessionRequest::new("sess_abc123")).unwrap(),
9497 json!({"sessionId": "sess_abc123"})
9498 );
9499 assert_eq!(
9500 serde_json::to_value(UnarchiveSessionResponse::new()).unwrap(),
9501 json!({})
9502 );
9503 assert_eq!(
9504 serde_json::to_value(
9505 SessionCapabilities::new().archive(SessionArchiveCapabilities::new())
9506 )
9507 .unwrap(),
9508 json!({"archive": {}})
9509 );
9510 assert_eq!(
9511 serde_json::to_value(
9512 ListSessionsRequest::new()
9513 .cwd("/home/user/project")
9514 .archived(SessionArchiveFilter::Only)
9515 )
9516 .unwrap(),
9517 json!({"cwd": "/home/user/project", "archived": "only"})
9518 );
9519 assert_eq!(
9520 serde_json::to_value(
9521 SessionInfo::new("sess_abc123", "/home/user/project").archived(true)
9522 )
9523 .unwrap(),
9524 json!({"sessionId": "sess_abc123", "cwd": "/home/user/project", "archived": true})
9525 );
9526 }
9527
9528 #[cfg(feature = "unstable_session_archive")]
9529 #[test]
9530 fn test_session_archive_filter_is_strict_and_open() {
9531 for (value, expected) in [
9532 (json!(null), None),
9533 (json!("include"), Some(SessionArchiveFilter::Include)),
9534 (
9535 json!("_recent"),
9536 Some(SessionArchiveFilter::Other("_recent".to_string())),
9537 ),
9538 ] {
9539 let request =
9540 serde_json::from_value::<ListSessionsRequest>(json!({"archived": value})).unwrap();
9541 assert_eq!(request.archived, expected);
9542 }
9543 for value in [json!(true), json!(1), json!({})] {
9544 assert!(
9545 serde_json::from_value::<ListSessionsRequest>(json!({"archived": value})).is_err()
9546 );
9547 }
9548 let info = serde_json::from_value::<SessionInfo>(
9549 json!({"sessionId": "sess_abc123", "cwd": "/home/user/project", "archived": "yes"}),
9550 )
9551 .unwrap();
9552 assert_eq!(info.archived, None);
9553 }
9554
9555 #[test]
9556 fn test_session_additional_directories_serialization() {
9557 assert_eq!(
9558 serde_json::to_value(NewSessionRequest::new("/home/user/project")).unwrap(),
9559 json!({
9560 "cwd": "/home/user/project",
9561 })
9562 );
9563 assert_eq!(
9564 serde_json::to_value(
9565 NewSessionRequest::new("/home/user/project").additional_directories(vec![
9566 PathBuf::from("/home/user/shared-lib"),
9567 PathBuf::from("/home/user/product-docs"),
9568 ])
9569 )
9570 .unwrap(),
9571 json!({
9572 "cwd": "/home/user/project",
9573 "additionalDirectories": [
9574 "/home/user/shared-lib",
9575 "/home/user/product-docs"
9576 ],
9577 })
9578 );
9579 assert_eq!(
9580 serde_json::to_value(ResumeSessionRequest::new(
9581 "sess_abc123",
9582 "/home/user/project"
9583 ))
9584 .unwrap(),
9585 json!({
9586 "sessionId": "sess_abc123",
9587 "cwd": "/home/user/project",
9588 })
9589 );
9590 assert_eq!(
9591 serde_json::from_value::<ResumeSessionRequest>(json!({
9592 "sessionId": "sess_abc123",
9593 "cwd": "/home/user/project"
9594 }))
9595 .unwrap()
9596 .mcp_servers,
9597 Vec::<McpServer>::new()
9598 );
9599 assert_eq!(
9600 serde_json::from_value::<ResumeSessionRequest>(json!({
9601 "sessionId": "sess_abc123",
9602 "cwd": "/home/user/project",
9603 "mcpServers": null
9604 }))
9605 .unwrap()
9606 .mcp_servers,
9607 Vec::<McpServer>::new()
9608 );
9609 assert_eq!(
9610 serde_json::to_value(SessionInfo::new("sess_abc123", "/home/user/project")).unwrap(),
9611 json!({
9612 "sessionId": "sess_abc123",
9613 "cwd": "/home/user/project"
9614 })
9615 );
9616 assert_eq!(
9617 serde_json::to_value(
9618 SessionInfo::new("sess_abc123", "/home/user/project").additional_directories(vec![
9619 PathBuf::from("/home/user/shared-lib"),
9620 PathBuf::from("/home/user/product-docs"),
9621 ])
9622 )
9623 .unwrap(),
9624 json!({
9625 "sessionId": "sess_abc123",
9626 "cwd": "/home/user/project",
9627 "additionalDirectories": [
9628 "/home/user/shared-lib",
9629 "/home/user/product-docs"
9630 ]
9631 })
9632 );
9633 assert_eq!(
9634 serde_json::from_value::<SessionInfo>(json!({
9635 "sessionId": "sess_abc123",
9636 "cwd": "/home/user/project"
9637 }))
9638 .unwrap()
9639 .additional_directories,
9640 Vec::<AbsolutePath>::new()
9641 );
9642 }
9643 #[test]
9644 fn test_session_additional_directories_capabilities_serialization() {
9645 assert_eq!(
9646 serde_json::to_value(
9647 SessionCapabilities::new()
9648 .additional_directories(SessionAdditionalDirectoriesCapabilities::new())
9649 )
9650 .unwrap(),
9651 json!({
9652 "additionalDirectories": {}
9653 })
9654 );
9655 }
9656
9657 #[test]
9658 fn test_session_system_prompt_capabilities_serialization() {
9659 assert_eq!(
9660 serde_json::to_value(
9661 SessionCapabilities::new().system_prompt(SessionSystemPromptCapabilities::new())
9662 )
9663 .unwrap(),
9664 json!({ "systemPrompt": {} })
9665 );
9666 assert_eq!(
9667 serde_json::to_value(
9668 SessionCapabilities::new().system_prompt(
9669 SessionSystemPromptCapabilities::new().mode(
9670 SessionSystemPromptModeCapabilities::new()
9671 .override_(SessionSystemPromptOverrideCapabilities::new())
9672 )
9673 )
9674 )
9675 .unwrap(),
9676 json!({ "systemPrompt": { "mode": { "override": {} } } })
9677 );
9678 assert_eq!(
9679 serde_json::from_value::<SessionCapabilities>(
9680 json!({ "systemPrompt": { "mode": { "override": {} } } })
9681 )
9682 .unwrap()
9683 .system_prompt
9684 .and_then(|capabilities| capabilities.mode)
9685 .and_then(|mode| mode.override_),
9686 Some(SessionSystemPromptOverrideCapabilities::new())
9687 );
9688
9689 assert_eq!(
9691 serde_json::from_value::<SessionCapabilities>(json!({ "systemPrompt": "yes" }))
9692 .unwrap()
9693 .system_prompt,
9694 None
9695 );
9696 assert_eq!(
9697 serde_json::from_value::<SessionCapabilities>(
9698 json!({ "systemPrompt": { "mode": { "override": true } } })
9699 )
9700 .unwrap()
9701 .system_prompt,
9702 Some(
9703 SessionSystemPromptCapabilities::new()
9704 .mode(SessionSystemPromptModeCapabilities::new())
9705 )
9706 );
9707 assert_eq!(
9708 serde_json::from_value::<SessionCapabilities>(
9709 json!({ "systemPrompt": { "mode": "override" } })
9710 )
9711 .unwrap()
9712 .system_prompt,
9713 Some(SessionSystemPromptCapabilities::new())
9714 );
9715 }
9716
9717 #[test]
9718 fn test_system_prompt_lifecycle_request_serialization() {
9719 let system_prompt = SystemPrompt::new(vec![ContentBlock::from(
9720 "You are a code review specialist.",
9721 )]);
9722 let system_prompt_json = json!({
9723 "mode": "append",
9724 "content": [{ "type": "text", "text": "You are a code review specialist." }]
9725 });
9726
9727 let request =
9728 NewSessionRequest::new("/home/user/project").system_prompt(system_prompt.clone());
9729 let request_json = json!({
9730 "cwd": "/home/user/project",
9731 "systemPrompt": system_prompt_json
9732 });
9733 assert_eq!(serde_json::to_value(&request).unwrap(), request_json);
9734 assert_eq!(
9735 serde_json::from_value::<NewSessionRequest>(request_json).unwrap(),
9736 request
9737 );
9738
9739 assert_eq!(
9740 serde_json::to_value(
9741 ResumeSessionRequest::new("sess_abc123", "/home/user/project")
9742 .system_prompt(system_prompt.clone())
9743 )
9744 .unwrap()["systemPrompt"],
9745 system_prompt_json
9746 );
9747 #[cfg(feature = "unstable_session_fork")]
9748 assert_eq!(
9749 serde_json::to_value(
9750 ForkSessionRequest::new("sess_abc123", "/home/user/project")
9751 .system_prompt(system_prompt.clone())
9752 )
9753 .unwrap()["systemPrompt"],
9754 system_prompt_json
9755 );
9756
9757 let override_prompt =
9758 SystemPrompt::new(vec![ContentBlock::from("...")]).mode(SystemPromptMode::Override);
9759 let override_json = json!({
9760 "mode": "override",
9761 "content": [{ "type": "text", "text": "..." }]
9762 });
9763 assert_eq!(
9764 serde_json::to_value(&override_prompt).unwrap(),
9765 override_json
9766 );
9767 assert_eq!(
9768 serde_json::from_value::<SystemPrompt>(override_json).unwrap(),
9769 override_prompt
9770 );
9771 }
9772
9773 #[test]
9776 fn test_system_prompt_new_defaults_to_append() {
9777 let system_prompt = SystemPrompt::new(vec![ContentBlock::from("...")]);
9778 assert_eq!(system_prompt.mode, SystemPromptMode::Append);
9779 assert_eq!(
9780 serde_json::to_value(&system_prompt).unwrap(),
9781 json!({ "mode": "append", "content": [{ "type": "text", "text": "..." }] })
9782 );
9783 }
9784
9785 #[test]
9789 fn test_system_prompt_preserves_unknown_modes() {
9790 for mode in ["_vendor_mode", "prepend"] {
9791 let system_prompt_json =
9792 json!({ "mode": mode, "content": [{ "type": "text", "text": "..." }] });
9793 let system_prompt: SystemPrompt =
9794 serde_json::from_value(system_prompt_json.clone()).unwrap();
9795 assert_eq!(
9796 system_prompt.mode,
9797 SystemPromptMode::Other(mode.to_string())
9798 );
9799 assert_eq!(
9800 serde_json::to_value(&system_prompt).unwrap(),
9801 system_prompt_json
9802 );
9803 }
9804 }
9805
9806 fn assert_system_prompt_is_strict<T>(base: &serde_json::Value)
9810 where
9811 T: serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
9812 {
9813 let name = std::any::type_name::<T>();
9814 let with = |system_prompt: serde_json::Value| {
9815 let mut request = base.clone();
9816 request["systemPrompt"] = system_prompt;
9817 serde_json::from_value::<T>(request)
9818 };
9819
9820 for system_prompt in [
9821 json!("You are a code review specialist."),
9822 json!({ "content": [{ "type": "text", "text": "..." }] }),
9823 json!({ "mode": null, "content": [{ "type": "text", "text": "..." }] }),
9824 json!({ "mode": 1, "content": [{ "type": "text", "text": "..." }] }),
9825 json!({ "mode": "append" }),
9826 json!({ "mode": "append", "content": "..." }),
9827 json!({ "mode": "append", "content": [{ "type": "text" }] }),
9828 ] {
9829 assert!(
9830 with(system_prompt.clone()).is_err(),
9831 "{name}.systemPrompt: {system_prompt}"
9832 );
9833 }
9834
9835 assert_eq!(
9836 with(serde_json::Value::Null).unwrap(),
9837 serde_json::from_value::<T>(base.clone()).unwrap(),
9838 "{name}.systemPrompt"
9839 );
9840 }
9841
9842 #[test]
9843 fn test_session_setup_requests_reject_malformed_system_prompts() {
9844 assert!(
9845 serde_json::to_value(NewSessionRequest::new("/repo"))
9846 .unwrap()
9847 .get("systemPrompt")
9848 .is_none()
9849 );
9850 assert_system_prompt_is_strict::<NewSessionRequest>(&json!({ "cwd": "/repo" }));
9851 assert_system_prompt_is_strict::<ResumeSessionRequest>(&json!({
9852 "sessionId": "sess-1",
9853 "cwd": "/repo"
9854 }));
9855 #[cfg(feature = "unstable_session_fork")]
9856 assert_system_prompt_is_strict::<ForkSessionRequest>(&json!({
9857 "sessionId": "sess-1",
9858 "cwd": "/repo"
9859 }));
9860 }
9861
9862 #[test]
9865 fn test_system_prompt_preserves_unknown_content_blocks() {
9866 let request: NewSessionRequest = serde_json::from_value(json!({
9867 "cwd": "/home/user/project",
9868 "systemPrompt": {
9869 "mode": "append",
9870 "content": [{ "type": "_vendor_video", "uri": "https://example.com/intro.mp4" }]
9871 }
9872 }))
9873 .unwrap();
9874 let content = request.system_prompt.unwrap().content;
9875 assert_eq!(content.len(), 1);
9876 assert!(matches!(content[0], ContentBlock::Other(_)));
9877 }
9878
9879 #[test]
9880 fn test_auth_method_terminal_serialization() {
9881 let method = AuthMethod::Terminal(AuthMethodTerminal::new("tui-auth", "Terminal Auth"));
9882
9883 let json = serde_json::to_value(&method).unwrap();
9884 assert_eq!(
9885 json,
9886 json!({
9887 "methodId": "tui-auth",
9888 "name": "Terminal Auth",
9889 "type": "terminal"
9890 })
9891 );
9892 assert!(!json.as_object().unwrap().contains_key("args"));
9894 assert!(!json.as_object().unwrap().contains_key("env"));
9895
9896 let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9897 match deserialized {
9898 AuthMethod::Terminal(AuthMethodTerminal { args, env, .. }) => {
9899 assert_eq!(args, Vec::<String>::new());
9900 assert_eq!(env, []);
9901 }
9902 _ => panic!("Expected Terminal variant"),
9903 }
9904 }
9905
9906 #[test]
9907 fn test_auth_method_terminal_with_args_and_env_serialization() {
9908 let method = AuthMethod::Terminal(
9909 AuthMethodTerminal::new("tui-auth", "Terminal Auth")
9910 .args(vec!["--interactive".to_string(), "--color".to_string()])
9911 .env(vec![EnvVariable::new("TERM", "xterm-256color")]),
9912 );
9913
9914 let json = serde_json::to_value(&method).unwrap();
9915 assert_eq!(
9916 json,
9917 json!({
9918 "methodId": "tui-auth",
9919 "name": "Terminal Auth",
9920 "type": "terminal",
9921 "args": ["--interactive", "--color"],
9922 "env": [
9923 {
9924 "name": "TERM",
9925 "value": "xterm-256color"
9926 }
9927 ]
9928 })
9929 );
9930
9931 let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9932 match deserialized {
9933 AuthMethod::Terminal(AuthMethodTerminal { args, env, .. }) => {
9934 assert_eq!(args, vec!["--interactive", "--color"]);
9935 assert_eq!(env.len(), 1);
9936 assert_eq!(env[0].name, "TERM");
9937 assert_eq!(env[0].value, "xterm-256color");
9938 }
9939 _ => panic!("Expected Terminal variant"),
9940 }
9941 }
9942
9943 #[test]
9944 fn test_session_config_option_id_serialize() {
9945 let val = SessionConfigOptionValue::id("model-1");
9946 let json = serde_json::to_value(&val).unwrap();
9947 assert_eq!(json, json!({ "type": "id", "value": "model-1" }));
9948 }
9949
9950 #[test]
9951 fn test_session_config_option_value_boolean_serialize() {
9952 let val = SessionConfigOptionValue::boolean(true);
9953 let json = serde_json::to_value(&val).unwrap();
9954 assert_eq!(json, json!({ "type": "boolean", "value": true }));
9955 }
9956
9957 #[test]
9958 fn test_session_config_option_value_deserialize_id() {
9959 let json = json!({ "type": "id", "value": "model-1" });
9960 let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9961 assert_eq!(val, SessionConfigOptionValue::id("model-1"));
9962 assert_eq!(val.as_id().unwrap().to_string(), "model-1");
9963 }
9964
9965 #[test]
9966 fn test_session_config_option_value_deserialize_requires_type() {
9967 let json = json!({ "value": "model-1" });
9968 let result = serde_json::from_value::<SessionConfigOptionValue>(json);
9969 assert!(result.is_err());
9970 }
9971
9972 #[test]
9973 fn test_session_config_option_value_deserialize_boolean() {
9974 let json = json!({ "type": "boolean", "value": true });
9975 let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9976 assert_eq!(val, SessionConfigOptionValue::boolean(true));
9977 assert_eq!(val.as_bool(), Some(true));
9978 }
9979
9980 #[test]
9981 fn test_session_config_option_value_deserialize_boolean_false() {
9982 let json = json!({ "type": "boolean", "value": false });
9983 let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9984 assert_eq!(val, SessionConfigOptionValue::boolean(false));
9985 assert_eq!(val.as_bool(), Some(false));
9986 }
9987
9988 #[test]
9989 fn test_session_config_option_value_deserialize_unknown_type_with_string_value() {
9990 let json = json!({
9991 "type": "text",
9992 "value": "freeform input",
9993 "maxLength": 200
9994 });
9995 let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9996 let SessionConfigOptionValue::Other(unknown) = val else {
9997 panic!("Expected Other variant");
9998 };
9999 assert_eq!(unknown.type_, "text");
10000 assert_eq!(unknown.value, json!("freeform input"));
10001 assert_eq!(unknown.fields["maxLength"], json!(200));
10002 }
10003
10004 #[test]
10005 fn test_session_config_option_value_deserialize_unknown_type_with_object_value() {
10006 let json = json!({
10007 "type": "range",
10008 "value": { "min": 1, "max": 5 }
10009 });
10010 let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10011 let SessionConfigOptionValue::Other(unknown) = val else {
10012 panic!("Expected Other variant");
10013 };
10014 assert_eq!(unknown.type_, "range");
10015 assert_eq!(unknown.value, json!({ "min": 1, "max": 5 }));
10016 }
10017
10018 #[test]
10019 fn test_session_config_option_value_roundtrip_id() {
10020 let original = SessionConfigOptionValue::id("option-a");
10021 let json = serde_json::to_value(&original).unwrap();
10022 let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10023 assert_eq!(original, roundtripped);
10024 }
10025
10026 #[test]
10027 fn test_session_config_option_value_roundtrip_boolean() {
10028 let original = SessionConfigOptionValue::boolean(false);
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_other() {
10036 let mut fields = IndexMap::new();
10037 fields.insert("maxLength".to_string(), json!(200));
10038 let original = SessionConfigOptionValue::from(OtherSessionConfigOptionValue::new(
10039 "text",
10040 json!("freeform input"),
10041 fields,
10042 ));
10043 let json = serde_json::to_value(&original).unwrap();
10044 assert_eq!(
10045 json,
10046 json!({"type": "text", "value": "freeform input", "maxLength": 200})
10047 );
10048 let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10049 assert_eq!(original, roundtripped);
10050 }
10051
10052 #[test]
10053 fn test_session_config_option_value_type_mismatch_boolean_with_string() {
10054 let json = json!({ "type": "boolean", "value": "not a bool" });
10055 let result = serde_json::from_value::<SessionConfigOptionValue>(json);
10056 assert!(result.is_err());
10057 }
10058
10059 #[test]
10060 fn test_session_config_option_value_from_impls() {
10061 let from_str: SessionConfigOptionValue = "model-1".into();
10062 assert_eq!(from_str.as_id().unwrap().to_string(), "model-1");
10063
10064 let from_id: SessionConfigOptionValue = SessionConfigValueId::new("model-2").into();
10065 assert_eq!(from_id.as_id().unwrap().to_string(), "model-2");
10066
10067 let from_bool: SessionConfigOptionValue = true.into();
10068 assert_eq!(from_bool.as_bool(), Some(true));
10069 }
10070
10071 #[test]
10072 fn test_set_session_config_option_request_id() {
10073 let req = SetSessionConfigOptionRequest::new("sess_1", "model", "model-1");
10074 let json = serde_json::to_value(&req).unwrap();
10075 assert_eq!(
10076 json,
10077 json!({
10078 "sessionId": "sess_1",
10079 "configId": "model",
10080 "type": "id",
10081 "value": "model-1"
10082 })
10083 );
10084 }
10085
10086 #[test]
10087 fn test_set_session_config_option_request_boolean() {
10088 let req = SetSessionConfigOptionRequest::new("sess_1", "brave_mode", true);
10089 let json = serde_json::to_value(&req).unwrap();
10090 assert_eq!(
10091 json,
10092 json!({
10093 "sessionId": "sess_1",
10094 "configId": "brave_mode",
10095 "type": "boolean",
10096 "value": true
10097 })
10098 );
10099 }
10100
10101 #[test]
10102 fn test_set_session_config_option_request_deserialize_requires_type() {
10103 let json = json!({
10104 "sessionId": "sess_1",
10105 "configId": "model",
10106 "value": "model-1"
10107 });
10108 let result = serde_json::from_value::<SetSessionConfigOptionRequest>(json);
10109 assert!(result.is_err());
10110 }
10111
10112 #[test]
10113 fn test_set_session_config_option_request_deserialize_boolean() {
10114 let json = json!({
10115 "sessionId": "sess_1",
10116 "configId": "brave_mode",
10117 "type": "boolean",
10118 "value": true
10119 });
10120 let req: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
10121 assert_eq!(req.value.as_bool(), Some(true));
10122 }
10123
10124 #[test]
10125 fn test_set_session_config_option_request_roundtrip_id() {
10126 let original = SetSessionConfigOptionRequest::new("s", "c", "v");
10127 let json = serde_json::to_value(&original).unwrap();
10128 let roundtripped: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
10129 assert_eq!(original, roundtripped);
10130 }
10131
10132 #[test]
10133 fn test_set_session_config_option_request_roundtrip_boolean() {
10134 let original = SetSessionConfigOptionRequest::new("s", "c", false);
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_session_config_boolean_serialization() {
10142 let cfg = SessionConfigBoolean::new(true);
10143 let json = serde_json::to_value(&cfg).unwrap();
10144 assert_eq!(json, json!({ "currentValue": true }));
10145
10146 let deserialized: SessionConfigBoolean = serde_json::from_value(json).unwrap();
10147 assert!(deserialized.current_value);
10148 }
10149
10150 #[test]
10151 fn test_session_config_option_boolean_variant() {
10152 let opt = SessionConfigOption::boolean("brave_mode", "Brave Mode", false)
10153 .description("Skip confirmation prompts")
10154 .meta(test_meta());
10155 assert_eq!(serialized_meta_key_count(&opt), 1);
10156
10157 let json = serde_json::to_value(&opt).unwrap();
10158 assert_eq!(
10159 json,
10160 json!({
10161 "configId": "brave_mode",
10162 "name": "Brave Mode",
10163 "description": "Skip confirmation prompts",
10164 "type": "boolean",
10165 "currentValue": false,
10166 "_meta": {
10167 "source": "test"
10168 }
10169 })
10170 );
10171
10172 let deserialized: SessionConfigOption = serde_json::from_value(json).unwrap();
10173 assert_eq!(deserialized.config_id.to_string(), "brave_mode");
10174 assert_eq!(deserialized.name, "Brave Mode");
10175 match deserialized.kind {
10176 SessionConfigKind::Boolean(ref b) => assert!(!b.current_value),
10177 _ => panic!("Expected Boolean kind"),
10178 }
10179 }
10180
10181 #[test]
10182 fn test_session_config_option_select_still_works() {
10183 let opt = SessionConfigOption::select(
10185 "model",
10186 "Model",
10187 "model-1",
10188 vec![
10189 SessionConfigSelectOption::new("model-1", "Model 1"),
10190 SessionConfigSelectOption::new("model-2", "Model 2"),
10191 ],
10192 )
10193 .meta(test_meta());
10194 assert_eq!(serialized_meta_key_count(&opt), 1);
10195
10196 let json = serde_json::to_value(&opt).unwrap();
10197 assert_eq!(json["type"], "select");
10198 assert_eq!(json["currentValue"], "model-1");
10199 assert_eq!(json["options"].as_array().unwrap().len(), 2);
10200 assert_eq!(json["_meta"]["source"], "test");
10201
10202 let deserialized: SessionConfigOption = serde_json::from_value(json).unwrap();
10203 match deserialized.kind {
10204 SessionConfigKind::Select(ref s) => {
10205 assert_eq!(s.current_value.to_string(), "model-1");
10206 }
10207 _ => panic!("Expected Select kind"),
10208 }
10209 }
10210
10211 #[test]
10212 fn test_session_config_option_unknown_kind_roundtrip() {
10213 let option: SessionConfigOption = serde_json::from_value(json!({
10214 "configId": "verbosity",
10215 "name": "Verbosity",
10216 "type": "_slider",
10217 "currentValue": 3,
10218 "min": 0,
10219 "max": 5,
10220 "_meta": {
10221 "source": "test"
10222 }
10223 }))
10224 .unwrap();
10225
10226 assert_eq!(option.config_id.to_string(), "verbosity");
10227 assert_eq!(option.meta.as_ref().unwrap()["source"], "test");
10228 let SessionConfigKind::Other(unknown) = &option.kind else {
10229 panic!("expected unknown config kind");
10230 };
10231 assert_eq!(unknown.type_, "_slider");
10232 assert_eq!(unknown.fields.get("currentValue"), Some(&json!(3)));
10233 assert!(!unknown.fields.contains_key("_meta"));
10234 assert_eq!(serialized_meta_key_count(&option), 1);
10235
10236 let json = serde_json::to_value(&option).unwrap();
10237 assert_eq!(json["type"], "_slider");
10238 assert_eq!(json["currentValue"], 3);
10239 assert_eq!(json["min"], 0);
10240 assert_eq!(json["max"], 5);
10241 assert_eq!(json["_meta"]["source"], "test");
10242 }
10243
10244 #[test]
10245 fn test_session_config_option_unknown_kind_does_not_duplicate_flattened_meta() {
10246 let mut fields = IndexMap::new();
10247 fields.insert("currentValue".to_string(), json!(3));
10248 fields.insert("_meta".to_string(), json!({ "inner": "ignored" }));
10249
10250 let option = SessionConfigOption::new(
10251 "verbosity",
10252 "Verbosity",
10253 SessionConfigKind::Other(OtherSessionConfigKind::new("_slider", fields)),
10254 )
10255 .meta(test_meta());
10256
10257 let SessionConfigKind::Other(unknown) = &option.kind else {
10258 panic!("expected unknown config kind");
10259 };
10260 assert!(!unknown.fields.contains_key("_meta"));
10261 assert_eq!(serialized_meta_key_count(&option), 1);
10262
10263 let json = serde_json::to_value(&option).unwrap();
10264 assert_eq!(json["type"], "_slider");
10265 assert_eq!(json["currentValue"], 3);
10266 assert_eq!(json["_meta"]["source"], "test");
10267 }
10268
10269 #[test]
10270 fn test_session_config_option_unknown_does_not_hide_malformed_known_kind() {
10271 assert!(
10272 serde_json::from_value::<SessionConfigOption>(json!({
10273 "configId": "model",
10274 "name": "Model",
10275 "type": "select"
10276 }))
10277 .is_err()
10278 );
10279 }
10280
10281 #[cfg(feature = "unstable_llm_providers")]
10282 #[test]
10283 fn test_llm_protocol_known_variants() {
10284 assert_eq!(
10285 serde_json::to_value(&LlmProtocol::Anthropic).unwrap(),
10286 json!("anthropic")
10287 );
10288 assert_eq!(
10289 serde_json::to_value(&LlmProtocol::OpenAi).unwrap(),
10290 json!("openai")
10291 );
10292 assert_eq!(
10293 serde_json::to_value(&LlmProtocol::Azure).unwrap(),
10294 json!("azure")
10295 );
10296 assert_eq!(
10297 serde_json::to_value(&LlmProtocol::Vertex).unwrap(),
10298 json!("vertex")
10299 );
10300 assert_eq!(
10301 serde_json::to_value(&LlmProtocol::Bedrock).unwrap(),
10302 json!("bedrock")
10303 );
10304
10305 assert_eq!(
10306 serde_json::from_str::<LlmProtocol>("\"anthropic\"").unwrap(),
10307 LlmProtocol::Anthropic
10308 );
10309 assert_eq!(
10310 serde_json::from_str::<LlmProtocol>("\"openai\"").unwrap(),
10311 LlmProtocol::OpenAi
10312 );
10313 assert_eq!(
10314 serde_json::from_str::<LlmProtocol>("\"azure\"").unwrap(),
10315 LlmProtocol::Azure
10316 );
10317 assert_eq!(
10318 serde_json::from_str::<LlmProtocol>("\"vertex\"").unwrap(),
10319 LlmProtocol::Vertex
10320 );
10321 assert_eq!(
10322 serde_json::from_str::<LlmProtocol>("\"bedrock\"").unwrap(),
10323 LlmProtocol::Bedrock
10324 );
10325 }
10326
10327 #[cfg(feature = "unstable_llm_providers")]
10328 #[test]
10329 fn test_llm_protocol_unknown_variant() {
10330 let unknown: LlmProtocol = serde_json::from_str("\"cohere\"").unwrap();
10331 assert_eq!(unknown, LlmProtocol::Other("cohere".to_string()));
10332
10333 let json = serde_json::to_value(&unknown).unwrap();
10334 assert_eq!(json, json!("cohere"));
10335 }
10336
10337 #[cfg(feature = "unstable_llm_providers")]
10338 #[test]
10339 fn test_provider_current_config_serialization() {
10340 let config =
10341 ProviderCurrentConfig::new(LlmProtocol::Anthropic, "https://api.anthropic.com");
10342
10343 let json = serde_json::to_value(&config).unwrap();
10344 assert_eq!(
10345 json,
10346 json!({
10347 "apiType": "anthropic",
10348 "baseUrl": "https://api.anthropic.com"
10349 })
10350 );
10351
10352 let deserialized: ProviderCurrentConfig = serde_json::from_value(json).unwrap();
10353 assert_eq!(deserialized.api_type, LlmProtocol::Anthropic);
10354 assert_eq!(deserialized.base_url, "https://api.anthropic.com");
10355 }
10356
10357 #[cfg(feature = "unstable_llm_providers")]
10358 #[test]
10359 fn test_provider_info_with_current_config() {
10360 let info = ProviderInfo::new(
10361 "main",
10362 vec![LlmProtocol::Anthropic, LlmProtocol::OpenAi],
10363 true,
10364 Some(ProviderCurrentConfig::new(
10365 LlmProtocol::Anthropic,
10366 "https://api.anthropic.com",
10367 )),
10368 );
10369
10370 let json = serde_json::to_value(&info).unwrap();
10371 assert_eq!(
10372 json,
10373 json!({
10374 "providerId": "main",
10375 "supported": ["anthropic", "openai"],
10376 "required": true,
10377 "current": {
10378 "apiType": "anthropic",
10379 "baseUrl": "https://api.anthropic.com"
10380 }
10381 })
10382 );
10383
10384 let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10385 assert_eq!(deserialized.provider_id.to_string(), "main");
10386 assert_eq!(deserialized.supported.len(), 2);
10387 assert!(deserialized.required);
10388 assert!(deserialized.current.is_some());
10389 assert_eq!(
10390 deserialized.current.as_ref().unwrap().api_type,
10391 LlmProtocol::Anthropic
10392 );
10393 }
10394
10395 #[cfg(feature = "unstable_llm_providers")]
10396 #[test]
10397 fn test_provider_info_disabled() {
10398 let info = ProviderInfo::new(
10399 "secondary",
10400 vec![LlmProtocol::OpenAi],
10401 false,
10402 None::<ProviderCurrentConfig>,
10403 );
10404
10405 let json = serde_json::to_value(&info).unwrap();
10406 assert_eq!(
10407 json,
10408 json!({
10409 "providerId": "secondary",
10410 "supported": ["openai"],
10411 "required": false
10412 })
10413 );
10414
10415 let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10416 assert_eq!(deserialized.provider_id.to_string(), "secondary");
10417 assert!(!deserialized.required);
10418 assert!(deserialized.current.is_none());
10419 }
10420
10421 #[cfg(feature = "unstable_llm_providers")]
10422 #[test]
10423 fn test_provider_info_missing_current_defaults_to_none() {
10424 let json = json!({
10426 "providerId": "main",
10427 "supported": ["anthropic"],
10428 "required": true
10429 });
10430 let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10431 assert!(deserialized.current.is_none());
10432 }
10433
10434 #[cfg(feature = "unstable_llm_providers")]
10435 #[test]
10436 fn test_provider_info_explicit_null_current_decodes_to_none() {
10437 let json = json!({
10441 "providerId": "main",
10442 "supported": ["anthropic"],
10443 "required": true,
10444 "current": null
10445 });
10446 let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10447 assert!(deserialized.current.is_none());
10448 }
10449
10450 #[cfg(feature = "unstable_llm_providers")]
10451 #[test]
10452 fn test_list_providers_response_serialization() {
10453 let response = ListProvidersResponse::new(vec![ProviderInfo::new(
10454 "main",
10455 vec![LlmProtocol::Anthropic],
10456 true,
10457 Some(ProviderCurrentConfig::new(
10458 LlmProtocol::Anthropic,
10459 "https://api.anthropic.com",
10460 )),
10461 )]);
10462
10463 let json = serde_json::to_value(&response).unwrap();
10464 assert_eq!(json["providers"].as_array().unwrap().len(), 1);
10465 assert_eq!(json["providers"][0]["providerId"], "main");
10466
10467 let deserialized: ListProvidersResponse = serde_json::from_value(json).unwrap();
10468 assert_eq!(deserialized.providers.len(), 1);
10469 }
10470
10471 #[cfg(feature = "unstable_llm_providers")]
10472 #[test]
10473 fn test_set_provider_request_serialization() {
10474 let mut headers = IndexMap::new();
10475 headers.insert("Authorization".to_string(), "Bearer sk-test".to_string());
10476
10477 let request =
10478 SetProviderRequest::new("main", LlmProtocol::OpenAi, "https://api.openai.com/v1")
10479 .headers(headers);
10480
10481 let json = serde_json::to_value(&request).unwrap();
10482 assert_eq!(
10483 json,
10484 json!({
10485 "providerId": "main",
10486 "apiType": "openai",
10487 "baseUrl": "https://api.openai.com/v1",
10488 "headers": {
10489 "Authorization": "Bearer sk-test"
10490 }
10491 })
10492 );
10493
10494 let deserialized: SetProviderRequest = serde_json::from_value(json).unwrap();
10495 assert_eq!(deserialized.provider_id.to_string(), "main");
10496 assert_eq!(deserialized.api_type, LlmProtocol::OpenAi);
10497 assert_eq!(deserialized.base_url, "https://api.openai.com/v1");
10498 assert_eq!(deserialized.headers.len(), 1);
10499 assert_eq!(
10500 deserialized.headers.get("Authorization").unwrap(),
10501 "Bearer sk-test"
10502 );
10503 }
10504
10505 #[cfg(feature = "unstable_llm_providers")]
10506 #[test]
10507 fn test_set_provider_request_omits_empty_headers() {
10508 let request =
10509 SetProviderRequest::new("main", LlmProtocol::Anthropic, "https://api.anthropic.com");
10510
10511 let json = serde_json::to_value(&request).unwrap();
10512 assert!(!json.as_object().unwrap().contains_key("headers"));
10514 }
10515
10516 #[cfg(feature = "unstable_llm_providers")]
10517 #[test]
10518 fn test_disable_provider_request_serialization() {
10519 let request = DisableProviderRequest::new("secondary");
10520
10521 let json = serde_json::to_value(&request).unwrap();
10522 assert_eq!(json, json!({ "providerId": "secondary" }));
10523
10524 let deserialized: DisableProviderRequest = serde_json::from_value(json).unwrap();
10525 assert_eq!(deserialized.provider_id.to_string(), "secondary");
10526 }
10527
10528 #[cfg(feature = "unstable_llm_providers")]
10529 #[test]
10530 fn test_providers_capabilities_serialization() {
10531 let caps = ProvidersCapabilities::new();
10532
10533 let json = serde_json::to_value(&caps).unwrap();
10534 assert_eq!(json, json!({}));
10535
10536 let deserialized: ProvidersCapabilities = serde_json::from_value(json).unwrap();
10537 assert!(deserialized.meta.is_none());
10538 }
10539
10540 #[cfg(feature = "unstable_llm_providers")]
10541 #[test]
10542 fn test_agent_capabilities_with_providers() {
10543 let caps = AgentCapabilities::new().providers(ProvidersCapabilities::new());
10544
10545 let json = serde_json::to_value(&caps).unwrap();
10546 assert_eq!(json["providers"], json!({}));
10547
10548 let deserialized: AgentCapabilities = serde_json::from_value(json).unwrap();
10549 assert!(deserialized.providers.is_some());
10550 }
10551
10552 #[test]
10553 fn test_agent_capabilities_session_is_explicit() {
10554 let json = serde_json::to_value(AgentCapabilities::new()).unwrap();
10555 assert!(json.get("session").is_none());
10556
10557 let caps = AgentCapabilities::new().session(
10558 SessionCapabilities::new()
10559 .prompt(PromptCapabilities::new().image(PromptImageCapabilities::new()))
10560 .mcp(McpCapabilities::new().stdio(McpStdioCapabilities::new())),
10561 );
10562
10563 assert_eq!(
10564 serde_json::to_value(&caps).unwrap(),
10565 json!({
10566 "session": {
10567 "prompt": {
10568 "image": {}
10569 },
10570 "mcp": {
10571 "stdio": {}
10572 }
10573 }
10574 })
10575 );
10576
10577 let deserialized: AgentCapabilities = serde_json::from_value(json!({
10578 "session": false
10579 }))
10580 .unwrap();
10581 assert!(deserialized.session.is_none());
10582 }
10583
10584 #[test]
10585 fn test_prompt_capabilities_serialize_supported_content_as_objects() {
10586 let caps = PromptCapabilities::new()
10587 .image(PromptImageCapabilities::new())
10588 .audio(PromptAudioCapabilities::new())
10589 .embedded_context(PromptEmbeddedContextCapabilities::new());
10590
10591 assert_eq!(
10592 serde_json::to_value(&caps).unwrap(),
10593 json!({
10594 "image": {},
10595 "audio": {},
10596 "embeddedContext": {}
10597 })
10598 );
10599
10600 let deserialized: PromptCapabilities = serde_json::from_value(json!({
10601 "image": null,
10602 "audio": false,
10603 "embeddedContext": {}
10604 }))
10605 .unwrap();
10606 assert!(deserialized.image.is_none());
10607 assert!(deserialized.audio.is_none());
10608 assert!(deserialized.embedded_context.is_some());
10609 }
10610
10611 #[cfg(feature = "unstable_agent_skills")]
10612 #[test]
10613 fn prompt_skill_capability_has_two_levels() {
10614 let leading = PromptCapabilities::new().skill(PromptSkillCapabilities::new());
10616 assert_eq!(
10617 serde_json::to_value(&leading).unwrap(),
10618 json!({ "skill": {} })
10619 );
10620
10621 let inline = PromptCapabilities::new()
10622 .skill(PromptSkillCapabilities::new().inline(PromptSkillInlineCapabilities::new()));
10623 let wire = json!({ "skill": { "inline": {} } });
10624 assert_eq!(serde_json::to_value(&inline).unwrap(), wire);
10625 assert_eq!(
10626 serde_json::from_value::<PromptCapabilities>(wire).unwrap(),
10627 inline
10628 );
10629
10630 for unsupported in [
10631 json!({}),
10632 json!({ "skill": null }),
10633 json!({ "skill": false }),
10634 json!({ "skill": true }),
10635 ] {
10636 let caps: PromptCapabilities = serde_json::from_value(unsupported).unwrap();
10637 assert!(caps.skill.is_none());
10638 }
10639
10640 for leading_only in [
10642 json!({ "skill": { "inline": null } }),
10643 json!({ "skill": { "inline": true } }),
10644 ] {
10645 assert_eq!(
10646 serde_json::from_value::<PromptCapabilities>(leading_only).unwrap(),
10647 leading
10648 );
10649 }
10650 }
10651
10652 #[test]
10653 fn test_mcp_capabilities_serialize_supported_transports_as_objects() {
10654 let caps = McpCapabilities::new()
10655 .stdio(McpStdioCapabilities::new())
10656 .http(McpHttpCapabilities::new());
10657
10658 assert_eq!(
10659 serde_json::to_value(&caps).unwrap(),
10660 json!({
10661 "stdio": {},
10662 "http": {}
10663 })
10664 );
10665
10666 let deserialized: McpCapabilities = serde_json::from_value(json!({
10667 "stdio": null,
10668 "http": false
10669 }))
10670 .unwrap();
10671 assert!(deserialized.stdio.is_none());
10672 assert!(deserialized.http.is_none());
10673 }
10674
10675 #[cfg(feature = "unstable_mcp_over_acp")]
10676 #[test]
10677 fn test_mcp_capabilities_serialize_acp_support_as_object() {
10678 let caps = McpCapabilities::new().acp(McpAcpCapabilities::new());
10679
10680 assert_eq!(
10681 serde_json::to_value(&caps).unwrap(),
10682 json!({
10683 "acp": {}
10684 })
10685 );
10686 }
10687
10688 #[test]
10689 fn prompt_request_rejects_malformed_content_block() {
10690 use serde_json::json;
10691
10692 assert!(
10693 serde_json::from_value::<PromptRequest>(json!({
10694 "sessionId": "sess-1",
10695 "prompt": [{"type": "text"}]
10696 }))
10697 .is_err()
10698 );
10699 }
10700
10701 #[test]
10702 fn prompt_request_rejects_non_array_prompt() {
10703 use serde_json::json;
10704
10705 assert!(
10706 serde_json::from_value::<PromptRequest>(json!({
10707 "sessionId": "sess-1",
10708 "prompt": "hello"
10709 }))
10710 .is_err()
10711 );
10712 }
10713
10714 fn prompt_request_with_idempotency_key(key: &serde_json::Value) -> serde_json::Value {
10715 serde_json::json!({
10716 "sessionId": "sess-1",
10717 "idempotencyKey": key,
10718 "prompt": [{"type": "text", "text": "hello"}]
10719 })
10720 }
10721
10722 #[test]
10723 fn prompt_request_idempotency_key_round_trips() {
10724 use serde_json::json;
10725
10726 let key = "0b6f3c1e-8d2a-4c57-9a41-5e2f7d90c3ab";
10727 let value = prompt_request_with_idempotency_key(&json!(key));
10728
10729 let request: PromptRequest = serde_json::from_value(value.clone()).unwrap();
10730 assert_eq!(
10731 request.idempotency_key.as_ref().map(IdempotencyKey::as_str),
10732 Some(key)
10733 );
10734 assert_eq!(serde_json::to_value(&request).unwrap(), value);
10735
10736 let built = PromptRequest::new("sess-1", vec![ContentBlock::from("hello")])
10737 .idempotency_key(IdempotencyKey::new(key).unwrap());
10738 assert_eq!(built, request);
10739 }
10740
10741 #[test]
10742 fn prompt_request_omitted_and_null_idempotency_key_mean_no_key() {
10743 use serde_json::json;
10744
10745 let omitted = json!({
10746 "sessionId": "sess-1",
10747 "prompt": [{"type": "text", "text": "hello"}]
10748 });
10749 let request: PromptRequest = serde_json::from_value(omitted.clone()).unwrap();
10750 assert_eq!(request.idempotency_key, None);
10751 assert_eq!(serde_json::to_value(&request).unwrap(), omitted);
10753
10754 let null: PromptRequest =
10755 serde_json::from_value(prompt_request_with_idempotency_key(&json!(null))).unwrap();
10756 assert_eq!(null, request);
10757 }
10758
10759 #[test]
10760 fn prompt_request_rejects_malformed_idempotency_key() {
10761 use serde_json::json;
10762
10763 let too_long = "k".repeat(IdempotencyKey::MAX_LENGTH + 1);
10764 for (name, key) in [
10765 ("an empty string", json!("")),
10766 ("a string over 255 characters", json!(too_long)),
10767 ("a number", json!(7)),
10768 ("a boolean", json!(true)),
10769 ("an object", json!({"key": "k"})),
10770 ("an array", json!(["k"])),
10771 ] {
10772 assert!(
10773 serde_json::from_value::<PromptRequest>(prompt_request_with_idempotency_key(&key))
10774 .is_err(),
10775 "{name} must fail the request instead of being treated as no key"
10776 );
10777 }
10778 }
10779
10780 #[test]
10781 fn idempotency_key_length_is_counted_in_characters() {
10782 use serde_json::json;
10783
10784 assert_eq!(IdempotencyKey::new(""), Err(InvalidIdempotencyKey::Empty));
10785 assert_eq!(IdempotencyKey::new("k").unwrap().as_str(), "k");
10786
10787 let longest = "k".repeat(IdempotencyKey::MAX_LENGTH);
10788 assert_eq!(
10789 IdempotencyKey::new(longest.as_str()).unwrap().as_str(),
10790 longest
10791 );
10792 assert_eq!(
10793 IdempotencyKey::new(format!("{longest}k")),
10794 Err(InvalidIdempotencyKey::TooLong)
10795 );
10796
10797 let multibyte = "é".repeat(IdempotencyKey::MAX_LENGTH);
10799 assert!(IdempotencyKey::new(multibyte.as_str()).is_ok());
10800 assert!(
10801 serde_json::from_value::<PromptRequest>(prompt_request_with_idempotency_key(&json!(
10802 multibyte
10803 )))
10804 .is_ok()
10805 );
10806 assert_eq!(
10807 IdempotencyKey::new(format!("{multibyte}é")),
10808 Err(InvalidIdempotencyKey::TooLong)
10809 );
10810
10811 assert_eq!("k".parse::<IdempotencyKey>().unwrap().to_string(), "k");
10812 assert_eq!(
10813 IdempotencyKey::try_from(String::new()),
10814 Err(InvalidIdempotencyKey::Empty)
10815 );
10816 assert_eq!(
10817 InvalidIdempotencyKey::TooLong.to_string(),
10818 "idempotency key must be at most 255 characters"
10819 );
10820 }
10821
10822 #[cfg(feature = "uuid")]
10823 #[test]
10824 fn generated_idempotency_keys_are_distinct_valid_v4_uuids() {
10825 let first = IdempotencyKey::generate();
10826 let second = IdempotencyKey::generate();
10827 assert_ne!(first, second);
10828
10829 for key in [&first, &second] {
10830 let uuid = uuid::Uuid::parse_str(key.as_str()).unwrap();
10831 assert_eq!(uuid.get_version_num(), 4);
10832 assert_eq!(IdempotencyKey::new(key.as_str()).as_ref(), Ok(key));
10834 let request = PromptRequest::new("sess-1", vec![ContentBlock::from("hello")])
10835 .idempotency_key(key.clone());
10836 let value = serde_json::to_value(&request).unwrap();
10837 assert_eq!(value["idempotencyKey"], key.as_str());
10838 assert_eq!(
10839 serde_json::from_value::<PromptRequest>(value).unwrap(),
10840 request
10841 );
10842 }
10843
10844 assert_eq!(
10845 IdempotencyKey::from(uuid::Uuid::nil()).as_str(),
10846 "00000000-0000-0000-0000-000000000000"
10847 );
10848 }
10849
10850 #[cfg(feature = "schemars")]
10851 #[test]
10852 fn idempotency_key_schema_is_a_strict_bounded_string() {
10853 use serde_json::json;
10854
10855 let key = serde_json::to_value(schemars::schema_for!(IdempotencyKey)).unwrap();
10856 assert_eq!(key["type"], "string");
10857 assert_eq!(key["minLength"], 1);
10858 assert_eq!(key["maxLength"], json!(IdempotencyKey::MAX_LENGTH));
10859
10860 let request = serde_json::to_value(schemars::schema_for!(PromptRequest)).unwrap();
10861 assert_eq!(request["required"], json!(["sessionId", "prompt"]));
10862 let property = &request["properties"]["idempotencyKey"];
10863 assert_eq!(
10864 property["anyOf"],
10865 json!([{"$ref": "#/$defs/IdempotencyKey"}, {"type": "null"}])
10866 );
10867 assert!(property.get("x-deserialize-default-on-error").is_none());
10870 }
10871
10872 fn assert_session_setup_lists_are_strict<T>(base: &serde_json::Value)
10873 where
10874 T: serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
10875 {
10876 let name = std::any::type_name::<T>();
10877 let with = |field: &str, value: serde_json::Value| {
10878 let mut request = base.clone();
10879 request[field] = value;
10880 serde_json::from_value::<T>(request)
10881 };
10882
10883 for (field, value) in [
10884 (
10886 "mcpServers",
10887 json!([
10888 {"type": "stdio", "name": "github", "command": "/usr/bin/gh-mcp", "env": [{"name": "GITHUB_TOKEN", "value": null}]},
10889 {"type": "stdio", "name": "fs", "command": "/usr/bin/fs-mcp"}
10890 ]),
10891 ),
10892 ("mcpServers", json!({"type": "stdio", "name": "fs"})),
10893 ("additionalDirectories", json!(["/repo/lib", 42])),
10894 ("additionalDirectories", json!("/repo/lib")),
10895 ] {
10896 assert!(
10897 with(field, value.clone()).is_err(),
10898 "{name}.{field}: {value}"
10899 );
10900 }
10901
10902 let empty = serde_json::from_value::<T>(base.clone()).unwrap();
10903 for field in ["mcpServers", "additionalDirectories"] {
10904 assert_eq!(
10905 with(field, serde_json::Value::Null).unwrap(),
10906 empty,
10907 "{name}.{field}"
10908 );
10909 }
10910 }
10911
10912 #[test]
10913 fn session_setup_requests_reject_malformed_mcp_servers_and_directories() {
10914 assert_session_setup_lists_are_strict::<NewSessionRequest>(&json!({"cwd": "/repo"}));
10915 assert_session_setup_lists_are_strict::<ResumeSessionRequest>(&json!({
10916 "sessionId": "sess-1",
10917 "cwd": "/repo"
10918 }));
10919 #[cfg(feature = "unstable_session_fork")]
10920 assert_session_setup_lists_are_strict::<ForkSessionRequest>(&json!({
10921 "sessionId": "sess-1",
10922 "cwd": "/repo"
10923 }));
10924 }
10925
10926 #[test]
10927 fn resume_session_request_rejects_malformed_replay_from() {
10928 let request = |replay_from: serde_json::Value| {
10929 serde_json::from_value::<ResumeSessionRequest>(json!({
10930 "sessionId": "sess-1",
10931 "cwd": "/repo",
10932 "replayFrom": replay_from
10933 }))
10934 };
10935
10936 assert!(request(json!("start")).is_err());
10938 assert_eq!(request(serde_json::Value::Null).unwrap().replay_from, None);
10939 assert!(matches!(
10940 request(json!({"type": "start"})).unwrap().replay_from,
10941 Some(ReplayFrom::Start(_))
10942 ));
10943 }
10944
10945 #[test]
10946 fn mcp_server_lists_treat_null_as_empty() {
10947 let servers: Vec<McpServer> = serde_json::from_value(json!([
10948 {"type": "stdio", "name": "fs", "command": "/usr/bin/fs-mcp", "args": null, "env": null},
10949 {"type": "http", "name": "api", "url": "https://example.com/mcp", "headers": null}
10950 ]))
10951 .unwrap();
10952
10953 assert_eq!(
10954 servers,
10955 vec![
10956 McpServer::Stdio(McpServerStdio::new("fs", "/usr/bin/fs-mcp")),
10957 McpServer::Http(McpServerHttp::new("api", "https://example.com/mcp")),
10958 ]
10959 );
10960 }
10961
10962 #[test]
10963 fn terminal_auth_methods_reject_malformed_launch_config() {
10964 let response: InitializeResponse = serde_json::from_value(json!({
10968 "protocolVersion": 2,
10969 "info": {"name": "agent", "version": "1.0.0"},
10970 "authMethods": [
10971 {"type": "terminal", "methodId": "bad-args", "name": "Log in", "args": ["auth", "--port", 8123]},
10972 {"type": "terminal", "methodId": "bad-env", "name": "Log in", "env": [{"name": "DEBUG", "value": 1}]},
10973 {"type": "terminal", "methodId": "null-config", "name": "Log in", "args": null, "env": null},
10974 {"type": "agent", "methodId": "agent", "name": "Agent login"}
10975 ]
10976 }))
10977 .unwrap();
10978
10979 assert_eq!(
10980 response.auth_methods,
10981 vec![
10982 AuthMethod::Terminal(AuthMethodTerminal::new("null-config", "Log in")),
10983 AuthMethod::Agent(AuthMethodAgent::new("agent", "Agent login")),
10984 ]
10985 );
10986 }
10987
10988 #[cfg(feature = "unstable_auth_status")]
10989 #[test]
10990 fn auth_status_response_round_trips() {
10991 let response = AuthStatusResponse::new(AuthState::Authenticated).accounts(vec![
10992 AuthAccount::new("Anthropic API key")
10993 .description("API key helper".to_string())
10994 .active(true),
10995 AuthAccount::new("Claude Max").email("user@example.com".to_string()),
10996 ]);
10997 let json = serde_json::to_value(&response).unwrap();
10998 assert_eq!(
10999 json,
11000 json!({
11001 "state": "authenticated",
11002 "accounts": [
11003 {
11004 "label": "Anthropic API key",
11005 "description": "API key helper",
11006 "active": true
11007 },
11008 {
11009 "label": "Claude Max",
11010 "email": "user@example.com"
11011 }
11012 ]
11013 })
11014 );
11015 assert_eq!(
11016 serde_json::from_value::<AuthStatusResponse>(json).unwrap(),
11017 response
11018 );
11019 assert_eq!(
11020 serde_json::to_value(AuthStatusResponse::new(AuthState::NotRequired)).unwrap(),
11021 json!({"state": "not_required"})
11022 );
11023 }
11024
11025 #[cfg(feature = "unstable_auth_status")]
11026 #[test]
11027 fn auth_status_state_is_strict_and_accounts_are_lenient() {
11028 assert!(serde_json::from_value::<AuthStatusResponse>(json!({})).is_err());
11029 assert!(serde_json::from_value::<AuthStatusResponse>(json!({"state": null})).is_err());
11030 assert!(serde_json::from_value::<AuthStatusResponse>(json!({"state": 1})).is_err());
11031
11032 let response: AuthStatusResponse = serde_json::from_value(json!({
11033 "state": "_vendor_state",
11034 "accounts": [
11035 {"active": true},
11036 {
11037 "label": "Vertex AI",
11038 "description": 42,
11039 "active": "yes",
11040 "email": ["not", "a", "string"]
11041 }
11042 ]
11043 }))
11044 .unwrap();
11045 assert_eq!(
11046 response,
11047 AuthStatusResponse::new(AuthState::Other("_vendor_state".to_string()))
11048 .accounts(vec![AuthAccount::new("Vertex AI")])
11049 );
11050 assert_eq!(
11051 serde_json::from_value::<AuthStatusResponse>(
11052 json!({"state": "unknown", "accounts": null})
11053 )
11054 .unwrap(),
11055 AuthStatusResponse::new(AuthState::Unknown)
11056 );
11057 }
11058
11059 #[cfg(feature = "unstable_auth_status")]
11060 #[test]
11061 fn auth_status_update_notification_routes() {
11062 use crate::v2::{AgentNotification, CLIENT_METHOD_NAMES};
11063
11064 assert_eq!(AGENT_METHOD_NAMES.auth_status, "auth/status");
11065 assert_eq!(CLIENT_METHOD_NAMES.auth_status_update, "auth/status_update");
11066 let notification = AgentNotification::AuthStatusUpdateNotification(Box::new(
11067 AuthStatusUpdateNotification::new(AuthState::Unauthenticated),
11068 ));
11069 assert_eq!(notification.method(), "auth/status_update");
11070 assert_eq!(
11071 serde_json::to_value(¬ification).unwrap(),
11072 json!({"state": "unauthenticated"})
11073 );
11074 }
11075
11076 #[cfg(all(
11077 feature = "unstable_session_fork",
11078 feature = "unstable_session_cursors"
11079 ))]
11080 #[test]
11081 fn fork_session_request_cursor_id_is_optional_and_strict() {
11082 let request = ForkSessionRequest::new("sess_abc123", "/home/user/project")
11083 .cursor_id(CursorId::new("cur_1"));
11084 let wire = json!({
11085 "sessionId": "sess_abc123",
11086 "cursorId": "cur_1",
11087 "cwd": "/home/user/project"
11088 });
11089 assert_eq!(serde_json::to_value(&request).unwrap(), wire);
11090 assert_eq!(
11091 serde_json::from_value::<ForkSessionRequest>(wire).unwrap(),
11092 request
11093 );
11094
11095 for wire in [
11097 json!({ "sessionId": "sess_abc123", "cwd": "/home/user/project" }),
11098 json!({ "sessionId": "sess_abc123", "cwd": "/home/user/project", "cursorId": null }),
11099 ] {
11100 assert_eq!(
11101 serde_json::from_value::<ForkSessionRequest>(wire)
11102 .unwrap()
11103 .cursor_id,
11104 None
11105 );
11106 }
11107
11108 assert!(
11110 serde_json::from_value::<ForkSessionRequest>(json!({
11111 "sessionId": "sess_abc123",
11112 "cwd": "/home/user/project",
11113 "cursorId": 7
11114 }))
11115 .is_err()
11116 );
11117 }
11118}