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]
1000 pub fn description(&self) -> Option<&str> {
1001 match self {
1002 Self::Agent(a) => a.description.as_deref(),
1003 Self::Other(a) => a
1004 .fields
1005 .get("description")
1006 .and_then(serde_json::Value::as_str),
1007 Self::Terminal(t) => t.description.as_deref(),
1008 }
1009 }
1010
1011 #[must_use]
1017 pub fn meta(&self) -> Option<&Meta> {
1018 match self {
1019 Self::Agent(a) => a.meta.as_ref(),
1020 Self::Other(a) => a.fields.get("_meta").and_then(serde_json::Value::as_object),
1021 Self::Terminal(t) => t.meta.as_ref(),
1022 }
1023 }
1024}
1025
1026#[serde_as]
1028#[skip_serializing_none]
1029#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1030#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1031#[cfg_attr(feature = "schemars", schemars(inline))]
1032#[cfg_attr(feature = "schemars", schemars(transform = other_auth_method_schema))]
1033#[serde(rename_all = "camelCase")]
1034#[non_exhaustive]
1035pub struct OtherAuthMethod {
1036 #[serde(rename = "type")]
1042 pub type_: String,
1043 pub method_id: AuthMethodId,
1045 pub name: String,
1047 #[serde(flatten)]
1050 pub fields: IndexMap<String, serde_json::Value>,
1051}
1052
1053impl OtherAuthMethod {
1054 #[must_use]
1056 pub fn new(
1057 type_: impl Into<String>,
1058 method_id: impl Into<AuthMethodId>,
1059 name: impl Into<String>,
1060 mut fields: IndexMap<String, serde_json::Value>,
1061 ) -> Self {
1062 fields.shift_remove("type");
1063 fields.shift_remove("methodId");
1064 fields.shift_remove("name");
1065 Self {
1066 type_: type_.into(),
1067 method_id: method_id.into(),
1068 name: name.into(),
1069 fields,
1070 }
1071 }
1072}
1073
1074impl<'de> Deserialize<'de> for OtherAuthMethod {
1075 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1076 where
1077 D: serde::Deserializer<'de>,
1078 {
1079 #[derive(Deserialize)]
1080 #[serde(rename_all = "camelCase")]
1081 struct RawOtherAuthMethod {
1082 #[serde(rename = "type")]
1083 type_: String,
1084 method_id: AuthMethodId,
1085 name: String,
1086 #[serde(flatten)]
1087 fields: IndexMap<String, serde_json::Value>,
1088 }
1089
1090 let raw = RawOtherAuthMethod::deserialize(deserializer)?;
1091 if is_known_auth_method_type(&raw.type_) {
1092 return Err(serde::de::Error::custom(format!(
1093 "known authentication method `{}` did not match its schema",
1094 raw.type_
1095 )));
1096 }
1097
1098 Ok(Self {
1099 type_: raw.type_,
1100 method_id: raw.method_id,
1101 name: raw.name,
1102 fields: raw.fields,
1103 })
1104 }
1105}
1106
1107fn is_known_auth_method_type(type_: &str) -> bool {
1108 matches!(type_, "agent" | "terminal")
1109}
1110
1111#[cfg(feature = "schemars")]
1112fn other_auth_method_schema(schema: &mut Schema) {
1113 super::schema_util::reject_known_string_discriminators(schema, "type", &["agent", "terminal"]);
1114}
1115
1116#[serde_as]
1120#[skip_serializing_none]
1121#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1122#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1123#[serde(rename_all = "camelCase")]
1124#[non_exhaustive]
1125pub struct AuthMethodAgent {
1126 pub method_id: AuthMethodId,
1128 pub name: String,
1130 #[serde_as(deserialize_as = "DefaultOnError")]
1135 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1136 #[serde(default)]
1137 pub description: Option<String>,
1138 #[serde_as(deserialize_as = "DefaultOnError")]
1144 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1145 #[serde(default)]
1146 #[serde(rename = "_meta")]
1147 pub meta: Option<Meta>,
1148}
1149
1150impl AuthMethodAgent {
1151 #[must_use]
1153 pub fn new(method_id: impl Into<AuthMethodId>, name: impl Into<String>) -> Self {
1154 Self {
1155 method_id: method_id.into(),
1156 name: name.into(),
1157 description: None,
1158 meta: None,
1159 }
1160 }
1161
1162 #[must_use]
1165 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
1166 self.description = description.into_option();
1167 self
1168 }
1169
1170 #[must_use]
1176 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1177 self.meta = meta.into_option();
1178 self
1179 }
1180}
1181
1182#[serde_as]
1190#[skip_serializing_none]
1191#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1192#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1193#[serde(rename_all = "camelCase")]
1194#[non_exhaustive]
1195pub struct AuthMethodTerminal {
1196 pub method_id: AuthMethodId,
1198 pub name: String,
1200 #[serde_as(deserialize_as = "DefaultOnError")]
1205 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1206 #[serde(default)]
1207 pub description: Option<String>,
1208 #[serde_as(deserialize_as = "DefaultOnNull")]
1210 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1211 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1212 pub args: Vec<String>,
1213 #[serde_as(deserialize_as = "DefaultOnNull")]
1217 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1218 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1219 pub env: Vec<EnvVariable>,
1220 #[serde_as(deserialize_as = "DefaultOnError")]
1226 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1227 #[serde(default)]
1228 #[serde(rename = "_meta")]
1229 pub meta: Option<Meta>,
1230}
1231
1232impl AuthMethodTerminal {
1233 #[must_use]
1235 pub fn new(method_id: impl Into<AuthMethodId>, name: impl Into<String>) -> Self {
1236 Self {
1237 method_id: method_id.into(),
1238 name: name.into(),
1239 description: None,
1240 args: Vec::new(),
1241 env: Vec::new(),
1242 meta: None,
1243 }
1244 }
1245
1246 #[must_use]
1248 pub fn args(mut self, args: Vec<String>) -> Self {
1249 self.args = args;
1250 self
1251 }
1252
1253 #[must_use]
1257 pub fn env(mut self, env: Vec<EnvVariable>) -> Self {
1258 self.env = env;
1259 self
1260 }
1261
1262 #[must_use]
1265 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
1266 self.description = description.into_option();
1267 self
1268 }
1269
1270 #[must_use]
1276 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1277 self.meta = meta.into_option();
1278 self
1279 }
1280}
1281
1282#[serde_as]
1288#[skip_serializing_none]
1289#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1290#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1291#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_NEW_METHOD_NAME)))]
1292#[serde(rename_all = "camelCase")]
1293#[non_exhaustive]
1294pub struct NewSessionRequest {
1295 pub cwd: AbsolutePath,
1297 #[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 additional_directories: Vec<AbsolutePath>,
1306 #[serde_as(deserialize_as = "DefaultOnNull")]
1308 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1309 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1310 pub mcp_servers: Vec<McpServer>,
1311 #[serde(default)]
1317 pub system_prompt: Option<SystemPrompt>,
1318 #[cfg(feature = "unstable_session_options")]
1336 #[serde_as(deserialize_as = "DefaultOnNull")]
1337 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1338 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1339 pub config_options: Vec<InitialSessionConfigOption>,
1340 #[serde_as(deserialize_as = "DefaultOnError")]
1346 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1347 #[serde(default)]
1348 #[serde(rename = "_meta")]
1349 pub meta: Option<Meta>,
1350}
1351
1352impl NewSessionRequest {
1353 #[must_use]
1355 pub fn new(cwd: impl Into<AbsolutePath>) -> Self {
1356 Self {
1357 cwd: cwd.into(),
1358 additional_directories: vec![],
1359 mcp_servers: vec![],
1360 system_prompt: None,
1361 #[cfg(feature = "unstable_session_options")]
1362 config_options: vec![],
1363 meta: None,
1364 }
1365 }
1366
1367 #[must_use]
1369 pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1370 where
1371 I: IntoIterator<Item = P>,
1372 P: Into<AbsolutePath>,
1373 {
1374 self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1375 self
1376 }
1377
1378 #[must_use]
1380 pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1381 self.mcp_servers = mcp_servers;
1382 self
1383 }
1384
1385 #[must_use]
1387 pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1388 self.system_prompt = system_prompt.into_option();
1389 self
1390 }
1391
1392 #[cfg(feature = "unstable_session_options")]
1410 #[must_use]
1411 pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1412 self.config_options = config_options;
1413 self
1414 }
1415
1416 #[must_use]
1422 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1423 self.meta = meta.into_option();
1424 self
1425 }
1426}
1427
1428#[serde_as]
1439#[skip_serializing_none]
1440#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1441#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1442#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_NEW_METHOD_NAME)))]
1443#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}, {"action": "replace", "target": "availableCommands", "value": "availableCommands"}]})))]
1444#[serde(rename_all = "camelCase")]
1445#[non_exhaustive]
1446pub struct NewSessionResponse {
1447 pub session_id: SessionId,
1451 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1457 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1458 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1459 pub config_options: Vec<SessionConfigOption>,
1460 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1466 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1467 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1468 pub available_commands: Vec<AvailableCommand>,
1469 #[serde_as(deserialize_as = "DefaultOnError")]
1475 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1476 #[serde(default)]
1477 #[serde(rename = "_meta")]
1478 pub meta: Option<Meta>,
1479}
1480
1481impl NewSessionResponse {
1482 #[must_use]
1484 pub fn new(session_id: impl Into<SessionId>) -> Self {
1485 Self {
1486 session_id: session_id.into(),
1487 config_options: Vec::new(),
1488 available_commands: Vec::new(),
1489 meta: None,
1490 }
1491 }
1492
1493 #[must_use]
1499 pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
1500 self.config_options = config_options;
1501 self
1502 }
1503
1504 #[must_use]
1506 pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
1507 self.available_commands = available_commands;
1508 self
1509 }
1510
1511 #[must_use]
1517 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1518 self.meta = meta.into_option();
1519 self
1520 }
1521}
1522
1523#[cfg(feature = "unstable_session_fork")]
1536#[serde_as]
1537#[skip_serializing_none]
1538#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1539#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1540#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_FORK_METHOD_NAME)))]
1541#[serde(rename_all = "camelCase")]
1542#[non_exhaustive]
1543pub struct ForkSessionRequest {
1544 pub session_id: SessionId,
1546 #[cfg(feature = "unstable_session_cursors")]
1559 #[serde(default)]
1560 pub cursor_id: Option<CursorId>,
1561 pub cwd: AbsolutePath,
1563 #[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 additional_directories: Vec<AbsolutePath>,
1572 #[serde_as(deserialize_as = "DefaultOnNull")]
1574 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1575 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1576 pub mcp_servers: Vec<McpServer>,
1577 #[serde(default)]
1585 pub system_prompt: Option<SystemPrompt>,
1586 #[cfg(feature = "unstable_session_options")]
1605 #[serde_as(deserialize_as = "DefaultOnNull")]
1606 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1607 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1608 pub config_options: Vec<InitialSessionConfigOption>,
1609 #[serde_as(deserialize_as = "DefaultOnError")]
1615 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1616 #[serde(default)]
1617 #[serde(rename = "_meta")]
1618 pub meta: Option<Meta>,
1619}
1620
1621#[cfg(feature = "unstable_session_fork")]
1622impl ForkSessionRequest {
1623 #[must_use]
1625 pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
1626 Self {
1627 session_id: session_id.into(),
1628 #[cfg(feature = "unstable_session_cursors")]
1629 cursor_id: None,
1630 cwd: cwd.into(),
1631 additional_directories: vec![],
1632 mcp_servers: vec![],
1633 system_prompt: None,
1634 #[cfg(feature = "unstable_session_options")]
1635 config_options: vec![],
1636 meta: None,
1637 }
1638 }
1639
1640 #[cfg(feature = "unstable_session_cursors")]
1649 #[must_use]
1650 pub fn cursor_id(mut self, cursor_id: impl IntoOption<CursorId>) -> Self {
1651 self.cursor_id = cursor_id.into_option();
1652 self
1653 }
1654
1655 #[must_use]
1657 pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1658 where
1659 I: IntoIterator<Item = P>,
1660 P: Into<AbsolutePath>,
1661 {
1662 self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1663 self
1664 }
1665
1666 #[must_use]
1668 pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1669 self.mcp_servers = mcp_servers;
1670 self
1671 }
1672
1673 #[must_use]
1675 pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1676 self.system_prompt = system_prompt.into_option();
1677 self
1678 }
1679
1680 #[cfg(feature = "unstable_session_options")]
1699 #[must_use]
1700 pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1701 self.config_options = config_options;
1702 self
1703 }
1704
1705 #[must_use]
1711 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1712 self.meta = meta.into_option();
1713 self
1714 }
1715}
1716
1717#[cfg(feature = "unstable_session_fork")]
1723#[serde_as]
1724#[skip_serializing_none]
1725#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1726#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1727#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_FORK_METHOD_NAME)))]
1728#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}, {"action": "replace", "target": "availableCommands", "value": "availableCommands"}]})))]
1729#[serde(rename_all = "camelCase")]
1730#[non_exhaustive]
1731pub struct ForkSessionResponse {
1732 pub session_id: SessionId,
1734 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1740 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1741 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1742 pub config_options: Vec<SessionConfigOption>,
1743 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1749 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1750 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1751 pub available_commands: Vec<AvailableCommand>,
1752 #[serde_as(deserialize_as = "DefaultOnError")]
1758 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1759 #[serde(default)]
1760 #[serde(rename = "_meta")]
1761 pub meta: Option<Meta>,
1762}
1763
1764#[cfg(feature = "unstable_session_fork")]
1765impl ForkSessionResponse {
1766 #[must_use]
1768 pub fn new(session_id: impl Into<SessionId>) -> Self {
1769 Self {
1770 session_id: session_id.into(),
1771 config_options: Vec::new(),
1772 available_commands: Vec::new(),
1773 meta: None,
1774 }
1775 }
1776
1777 #[must_use]
1783 pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
1784 self.config_options = config_options;
1785 self
1786 }
1787
1788 #[must_use]
1790 pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
1791 self.available_commands = available_commands;
1792 self
1793 }
1794
1795 #[must_use]
1801 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1802 self.meta = meta.into_option();
1803 self
1804 }
1805}
1806
1807#[serde_as]
1814#[skip_serializing_none]
1815#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1816#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1817#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_RESUME_METHOD_NAME)))]
1818#[serde(rename_all = "camelCase")]
1819#[non_exhaustive]
1820pub struct ResumeSessionRequest {
1821 pub session_id: SessionId,
1823 pub cwd: AbsolutePath,
1828 #[serde_as(deserialize_as = "DefaultOnNull")]
1835 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1836 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1837 pub additional_directories: Vec<AbsolutePath>,
1838 #[serde_as(deserialize_as = "DefaultOnNull")]
1843 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1844 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1845 pub mcp_servers: Vec<McpServer>,
1846 #[serde(default)]
1858 pub replay_from: Option<ReplayFrom>,
1859 #[serde(default)]
1867 pub system_prompt: Option<SystemPrompt>,
1868 #[cfg(feature = "unstable_session_options")]
1889 #[serde_as(deserialize_as = "DefaultOnNull")]
1890 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1891 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1892 pub config_options: Vec<InitialSessionConfigOption>,
1893 #[serde_as(deserialize_as = "DefaultOnError")]
1899 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1900 #[serde(default)]
1901 #[serde(rename = "_meta")]
1902 pub meta: Option<Meta>,
1903}
1904
1905impl ResumeSessionRequest {
1906 #[must_use]
1908 pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
1909 Self {
1910 session_id: session_id.into(),
1911 cwd: cwd.into(),
1912 additional_directories: vec![],
1913 mcp_servers: vec![],
1914 replay_from: None,
1915 system_prompt: None,
1916 #[cfg(feature = "unstable_session_options")]
1917 config_options: vec![],
1918 meta: None,
1919 }
1920 }
1921
1922 #[must_use]
1924 pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1925 where
1926 I: IntoIterator<Item = P>,
1927 P: Into<AbsolutePath>,
1928 {
1929 self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1930 self
1931 }
1932
1933 #[must_use]
1935 pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1936 self.mcp_servers = mcp_servers;
1937 self
1938 }
1939
1940 #[must_use]
1948 pub fn replay_from(mut self, replay_from: impl IntoOption<ReplayFrom>) -> Self {
1949 self.replay_from = replay_from.into_option();
1950 self
1951 }
1952
1953 #[must_use]
1955 pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1956 self.system_prompt = system_prompt.into_option();
1957 self
1958 }
1959
1960 #[cfg(feature = "unstable_session_options")]
1978 #[must_use]
1979 pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1980 self.config_options = config_options;
1981 self
1982 }
1983
1984 #[must_use]
1990 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1991 self.meta = meta.into_option();
1992 self
1993 }
1994}
1995
1996#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2000#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2001#[serde(tag = "type", rename_all = "snake_case")]
2002#[non_exhaustive]
2003pub enum ReplayFrom {
2004 Start(ReplayFromStart),
2006 #[serde(untagged)]
2017 Other(OtherReplayFrom),
2018}
2019
2020impl From<ReplayFromStart> for ReplayFrom {
2021 fn from(replay_from: ReplayFromStart) -> Self {
2022 Self::Start(replay_from)
2023 }
2024}
2025
2026#[serde_as]
2028#[skip_serializing_none]
2029#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2030#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2031#[serde(rename_all = "camelCase")]
2032#[non_exhaustive]
2033pub struct ReplayFromStart {
2034 #[serde_as(deserialize_as = "DefaultOnError")]
2040 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2041 #[serde(default)]
2042 #[serde(rename = "_meta")]
2043 pub meta: Option<Meta>,
2044}
2045
2046impl ReplayFromStart {
2047 #[must_use]
2049 pub fn new() -> Self {
2050 Self::default()
2051 }
2052
2053 #[must_use]
2059 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2060 self.meta = meta.into_option();
2061 self
2062 }
2063}
2064
2065#[serde_as]
2067#[skip_serializing_none]
2068#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2069#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
2070#[cfg_attr(feature = "schemars", schemars(inline))]
2071#[cfg_attr(feature = "schemars", schemars(transform = other_replay_from_schema))]
2072#[serde(rename_all = "camelCase")]
2073#[non_exhaustive]
2074pub struct OtherReplayFrom {
2075 #[serde(rename = "type")]
2081 pub type_: String,
2082 #[serde(flatten)]
2085 pub fields: IndexMap<String, serde_json::Value>,
2086}
2087
2088impl OtherReplayFrom {
2089 #[must_use]
2091 pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
2092 fields.shift_remove("type");
2093 Self {
2094 type_: type_.into(),
2095 fields,
2096 }
2097 }
2098}
2099
2100impl<'de> Deserialize<'de> for OtherReplayFrom {
2101 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2102 where
2103 D: serde::Deserializer<'de>,
2104 {
2105 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
2106 let type_ = fields
2107 .shift_remove("type")
2108 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
2109 let serde_json::Value::String(type_) = type_ else {
2110 return Err(serde::de::Error::custom("`type` must be a string"));
2111 };
2112
2113 if is_known_replay_from_type(&type_) {
2114 return Err(serde::de::Error::custom(format!(
2115 "known replay cursor `{type_}` did not match its schema"
2116 )));
2117 }
2118
2119 Ok(Self { type_, fields })
2120 }
2121}
2122
2123fn is_known_replay_from_type(type_: &str) -> bool {
2124 matches!(type_, "start")
2125}
2126
2127#[cfg(feature = "schemars")]
2128fn other_replay_from_schema(schema: &mut Schema) {
2129 super::schema_util::reject_known_string_discriminators(schema, "type", &["start"]);
2130}
2131
2132crate::serde_util::default_on_null! {
2133 #[serde_as]
2141 #[skip_serializing_none]
2142 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2143 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2144 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_RESUME_METHOD_NAME)))]
2145 #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}, {"action": "replace", "target": "availableCommands", "value": "availableCommands"}]})))]
2146 #[serde(rename_all = "camelCase")]
2147 #[non_exhaustive]
2148 pub struct ResumeSessionResponse {
2149 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2155 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2156 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2157 pub config_options: Vec<SessionConfigOption>,
2158 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2164 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2165 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2166 pub available_commands: Vec<AvailableCommand>,
2167 #[serde_as(deserialize_as = "DefaultOnError")]
2173 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2174 #[serde(default)]
2175 #[serde(rename = "_meta")]
2176 pub meta: Option<Meta>,
2177 }
2178}
2179
2180impl ResumeSessionResponse {
2181 #[must_use]
2183 pub fn new() -> Self {
2184 Self::default()
2185 }
2186
2187 #[must_use]
2193 pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
2194 self.config_options = config_options;
2195 self
2196 }
2197
2198 #[must_use]
2200 pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
2201 self.available_commands = available_commands;
2202 self
2203 }
2204
2205 #[must_use]
2211 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2212 self.meta = meta.into_option();
2213 self
2214 }
2215}
2216
2217#[serde_as]
2241#[skip_serializing_none]
2242#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2243#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2244#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CLOSE_METHOD_NAME)))]
2245#[serde(rename_all = "camelCase")]
2246#[non_exhaustive]
2247pub struct CloseSessionRequest {
2248 pub session_id: SessionId,
2250 #[serde_as(deserialize_as = "DefaultOnError")]
2256 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2257 #[serde(default)]
2258 #[serde(rename = "_meta")]
2259 pub meta: Option<Meta>,
2260}
2261
2262impl CloseSessionRequest {
2263 #[must_use]
2265 pub fn new(session_id: impl Into<SessionId>) -> Self {
2266 Self {
2267 session_id: session_id.into(),
2268 meta: None,
2269 }
2270 }
2271
2272 #[must_use]
2278 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2279 self.meta = meta.into_option();
2280 self
2281 }
2282}
2283
2284crate::serde_util::default_on_null! {
2285 #[serde_as]
2287 #[skip_serializing_none]
2288 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2289 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2290 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CLOSE_METHOD_NAME)))]
2291 #[serde(rename_all = "camelCase")]
2292 #[non_exhaustive]
2293 pub struct CloseSessionResponse {
2294 #[serde_as(deserialize_as = "DefaultOnError")]
2300 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2301 #[serde(default)]
2302 #[serde(rename = "_meta")]
2303 pub meta: Option<Meta>,
2304 }
2305}
2306
2307impl CloseSessionResponse {
2308 #[must_use]
2310 pub fn new() -> Self {
2311 Self::default()
2312 }
2313
2314 #[must_use]
2320 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2321 self.meta = meta.into_option();
2322 self
2323 }
2324}
2325
2326#[cfg(feature = "unstable_session_status")]
2340#[serde_as]
2341#[skip_serializing_none]
2342#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2343#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2344#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_STATUS_METHOD_NAME)))]
2345#[serde(rename_all = "camelCase")]
2346#[non_exhaustive]
2347pub struct SessionStatusRequest {
2348 pub session_id: SessionId,
2350 #[serde_as(deserialize_as = "DefaultOnError")]
2356 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2357 #[serde(default)]
2358 #[serde(rename = "_meta")]
2359 pub meta: Option<Meta>,
2360}
2361
2362#[cfg(feature = "unstable_session_status")]
2363impl SessionStatusRequest {
2364 #[must_use]
2366 pub fn new(session_id: impl Into<SessionId>) -> Self {
2367 Self {
2368 session_id: session_id.into(),
2369 meta: None,
2370 }
2371 }
2372
2373 #[must_use]
2379 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2380 self.meta = meta.into_option();
2381 self
2382 }
2383}
2384
2385#[cfg(feature = "unstable_session_status")]
2394#[serde_as]
2395#[skip_serializing_none]
2396#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2397#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2398#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_STATUS_METHOD_NAME)))]
2399#[serde(rename_all = "camelCase")]
2400#[non_exhaustive]
2401pub struct SessionStatusResponse {
2402 pub status: SessionStatus,
2406 #[serde_as(deserialize_as = "DefaultOnError")]
2414 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2415 #[serde(default)]
2416 pub state: Option<StateUpdate>,
2417 #[serde_as(deserialize_as = "DefaultOnError")]
2423 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2424 #[serde(default)]
2425 #[serde(rename = "_meta")]
2426 pub meta: Option<Meta>,
2427}
2428
2429#[cfg(feature = "unstable_session_status")]
2430impl SessionStatusResponse {
2431 #[must_use]
2433 pub fn new(status: SessionStatus) -> Self {
2434 Self {
2435 status,
2436 state: None,
2437 meta: None,
2438 }
2439 }
2440
2441 #[must_use]
2444 pub fn state(mut self, state: impl IntoOption<StateUpdate>) -> Self {
2445 self.state = state.into_option();
2446 self
2447 }
2448
2449 #[must_use]
2455 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2456 self.meta = meta.into_option();
2457 self
2458 }
2459}
2460
2461#[cfg(feature = "unstable_session_status")]
2467#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2468#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2469#[serde(rename_all = "snake_case")]
2470#[non_exhaustive]
2471pub enum SessionStatus {
2472 Open,
2479 Saved,
2483 #[serde(untagged)]
2490 Other(String),
2491}
2492
2493#[cfg(feature = "unstable_session_options")]
2507#[serde_as]
2508#[skip_serializing_none]
2509#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2510#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2511#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_OPTIONS_METHOD_NAME)))]
2512#[serde(rename_all = "camelCase")]
2513#[non_exhaustive]
2514pub struct SessionOptionsRequest {
2515 pub cwd: AbsolutePath,
2517 #[serde_as(deserialize_as = "DefaultOnNull")]
2521 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
2522 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2523 pub additional_directories: Vec<AbsolutePath>,
2524 #[serde(default)]
2531 pub session_id: Option<SessionId>,
2532 #[serde_as(deserialize_as = "DefaultOnError")]
2538 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2539 #[serde(default)]
2540 #[serde(rename = "_meta")]
2541 pub meta: Option<Meta>,
2542}
2543
2544#[cfg(feature = "unstable_session_options")]
2545impl SessionOptionsRequest {
2546 #[must_use]
2548 pub fn new(cwd: impl Into<AbsolutePath>) -> Self {
2549 Self {
2550 cwd: cwd.into(),
2551 additional_directories: vec![],
2552 session_id: None,
2553 meta: None,
2554 }
2555 }
2556
2557 #[must_use]
2559 pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
2560 where
2561 I: IntoIterator<Item = P>,
2562 P: Into<AbsolutePath>,
2563 {
2564 self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
2565 self
2566 }
2567
2568 #[must_use]
2570 pub fn session_id(mut self, session_id: impl IntoOption<SessionId>) -> Self {
2571 self.session_id = session_id.into_option();
2572 self
2573 }
2574
2575 #[must_use]
2581 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2582 self.meta = meta.into_option();
2583 self
2584 }
2585}
2586
2587#[cfg(feature = "unstable_session_options")]
2588crate::serde_util::default_on_null! {
2589 #[serde_as]
2598 #[skip_serializing_none]
2599 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2600 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2601 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_OPTIONS_METHOD_NAME)))]
2602 #[serde(rename_all = "camelCase")]
2603 #[non_exhaustive]
2604 pub struct SessionOptionsResponse {
2605 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2611 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2612 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2613 pub config_options: Vec<SessionConfigOption>,
2614 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2623 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2624 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2625 pub available_commands: Vec<AvailableCommand>,
2626 #[serde_as(deserialize_as = "DefaultOnError")]
2632 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2633 #[serde(default)]
2634 #[serde(rename = "_meta")]
2635 pub meta: Option<Meta>,
2636 }
2637}
2638
2639#[cfg(feature = "unstable_session_options")]
2640impl SessionOptionsResponse {
2641 #[must_use]
2643 pub fn new() -> Self {
2644 Self::default()
2645 }
2646
2647 #[must_use]
2649 pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
2650 self.config_options = config_options;
2651 self
2652 }
2653
2654 #[must_use]
2656 pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
2657 self.available_commands = available_commands;
2658 self
2659 }
2660
2661 #[must_use]
2667 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2668 self.meta = meta.into_option();
2669 self
2670 }
2671}
2672
2673#[cfg(feature = "unstable_session_options")]
2683#[serde_as]
2684#[skip_serializing_none]
2685#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2686#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2687#[serde(rename_all = "camelCase")]
2688#[non_exhaustive]
2689pub struct InitialSessionConfigOption {
2690 pub config_id: SessionConfigId,
2692 #[serde(flatten)]
2697 pub value: SessionConfigOptionValue,
2698 #[serde_as(deserialize_as = "DefaultOnError")]
2704 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2705 #[serde(default)]
2706 #[serde(rename = "_meta")]
2707 pub meta: Option<Meta>,
2708}
2709
2710#[cfg(feature = "unstable_session_options")]
2711impl InitialSessionConfigOption {
2712 #[must_use]
2714 pub fn new(
2715 config_id: impl Into<SessionConfigId>,
2716 value: impl Into<SessionConfigOptionValue>,
2717 ) -> Self {
2718 Self {
2719 config_id: config_id.into(),
2720 value: value.into(),
2721 meta: None,
2722 }
2723 }
2724
2725 #[must_use]
2731 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2732 self.meta = meta.into_option();
2733 self
2734 }
2735}
2736
2737#[serde_as]
2752#[skip_serializing_none]
2753#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2754#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2755#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TOOL_CALL_CANCEL_METHOD_NAME)))]
2756#[serde(rename_all = "camelCase")]
2757#[non_exhaustive]
2758pub struct CancelToolCallRequest {
2759 pub session_id: SessionId,
2761 pub tool_call_id: ToolCallId,
2763 #[serde_as(deserialize_as = "DefaultOnError")]
2769 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2770 #[serde(default)]
2771 #[serde(rename = "_meta")]
2772 pub meta: Option<Meta>,
2773}
2774
2775impl CancelToolCallRequest {
2776 #[must_use]
2778 pub fn new(session_id: impl Into<SessionId>, tool_call_id: impl Into<ToolCallId>) -> Self {
2779 Self {
2780 session_id: session_id.into(),
2781 tool_call_id: tool_call_id.into(),
2782 meta: None,
2783 }
2784 }
2785
2786 #[must_use]
2792 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2793 self.meta = meta.into_option();
2794 self
2795 }
2796}
2797
2798crate::serde_util::default_on_null! {
2799 #[serde_as]
2801 #[skip_serializing_none]
2802 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2803 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2804 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TOOL_CALL_CANCEL_METHOD_NAME)))]
2805 #[serde(rename_all = "camelCase")]
2806 #[non_exhaustive]
2807 pub struct CancelToolCallResponse {
2808 #[serde_as(deserialize_as = "DefaultOnError")]
2814 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2815 #[serde(default)]
2816 #[serde(rename = "_meta")]
2817 pub meta: Option<Meta>,
2818 }
2819}
2820
2821impl CancelToolCallResponse {
2822 #[must_use]
2824 pub fn new() -> Self {
2825 Self::default()
2826 }
2827
2828 #[must_use]
2834 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2835 self.meta = meta.into_option();
2836 self
2837 }
2838}
2839
2840#[serde_as]
2856#[skip_serializing_none]
2857#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2858#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2859#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TERMINAL_CANCEL_METHOD_NAME)))]
2860#[serde(rename_all = "camelCase")]
2861#[non_exhaustive]
2862pub struct CancelTerminalRequest {
2863 pub session_id: SessionId,
2865 pub terminal_id: TerminalId,
2867 #[serde_as(deserialize_as = "DefaultOnError")]
2873 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2874 #[serde(default)]
2875 #[serde(rename = "_meta")]
2876 pub meta: Option<Meta>,
2877}
2878
2879impl CancelTerminalRequest {
2880 #[must_use]
2882 pub fn new(session_id: impl Into<SessionId>, terminal_id: impl Into<TerminalId>) -> Self {
2883 Self {
2884 session_id: session_id.into(),
2885 terminal_id: terminal_id.into(),
2886 meta: None,
2887 }
2888 }
2889
2890 #[must_use]
2896 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2897 self.meta = meta.into_option();
2898 self
2899 }
2900}
2901
2902crate::serde_util::default_on_null! {
2903 #[serde_as]
2905 #[skip_serializing_none]
2906 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2907 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2908 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TERMINAL_CANCEL_METHOD_NAME)))]
2909 #[serde(rename_all = "camelCase")]
2910 #[non_exhaustive]
2911 pub struct CancelTerminalResponse {
2912 #[serde_as(deserialize_as = "DefaultOnError")]
2918 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2919 #[serde(default)]
2920 #[serde(rename = "_meta")]
2921 pub meta: Option<Meta>,
2922 }
2923}
2924
2925impl CancelTerminalResponse {
2926 #[must_use]
2928 pub fn new() -> Self {
2929 Self::default()
2930 }
2931
2932 #[must_use]
2938 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2939 self.meta = meta.into_option();
2940 self
2941 }
2942}
2943
2944#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2948#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
2949#[serde(transparent)]
2950#[from(Arc<str>, String, &str, &mut str, Box<str>, Cow<'_, str>)]
2951#[non_exhaustive]
2952pub struct SessionListCursor(pub Arc<str>);
2953
2954impl SessionListCursor {
2955 #[must_use]
2957 pub fn new(cursor: impl Into<Self>) -> Self {
2958 cursor.into()
2959 }
2960}
2961
2962impl AsRef<str> for SessionListCursor {
2963 fn as_ref(&self) -> &str {
2964 &self.0
2965 }
2966}
2967
2968impl From<&String> for SessionListCursor {
2969 fn from(cursor: &String) -> Self {
2970 Self(cursor.as_str().into())
2971 }
2972}
2973
2974macro_rules! impl_session_list_cursor_option_conversion {
2975 ($source:ty) => {
2976 impl IntoOption<SessionListCursor> for $source {
2977 fn into_option(self) -> Option<SessionListCursor> {
2978 Some(self.into())
2979 }
2980 }
2981 };
2982}
2983
2984impl_session_list_cursor_option_conversion!(Arc<str>);
2985impl_session_list_cursor_option_conversion!(String);
2986impl_session_list_cursor_option_conversion!(&str);
2987impl_session_list_cursor_option_conversion!(&mut str);
2988impl_session_list_cursor_option_conversion!(&String);
2989impl_session_list_cursor_option_conversion!(Box<str>);
2990impl_session_list_cursor_option_conversion!(Cow<'_, str>);
2991
2992crate::serde_util::default_on_null! {
2993 #[serde_as]
2995 #[skip_serializing_none]
2996 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2997 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2998 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LIST_METHOD_NAME)))]
2999 #[serde(rename_all = "camelCase")]
3000 #[non_exhaustive]
3001 pub struct ListSessionsRequest {
3002 #[serde(default)]
3010 pub cwd: Option<AbsolutePath>,
3011 #[serde(default)]
3015 pub cursor: Option<SessionListCursor>,
3016 #[cfg(feature = "unstable_session_archive")]
3026 #[serde(default)]
3027 pub archived: Option<SessionArchiveFilter>,
3028 #[serde_as(deserialize_as = "DefaultOnError")]
3034 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3035 #[serde(default)]
3036 #[serde(rename = "_meta")]
3037 pub meta: Option<Meta>,
3038 }
3039}
3040
3041impl ListSessionsRequest {
3042 #[must_use]
3044 pub fn new() -> Self {
3045 Self::default()
3046 }
3047
3048 #[must_use]
3050 pub fn cwd(mut self, cwd: impl IntoOption<AbsolutePath>) -> Self {
3051 self.cwd = cwd.into_option();
3052 self
3053 }
3054
3055 #[must_use]
3057 pub fn cursor(mut self, cursor: impl IntoOption<SessionListCursor>) -> Self {
3058 self.cursor = cursor.into_option();
3059 self
3060 }
3061
3062 #[cfg(feature = "unstable_session_archive")]
3068 #[must_use]
3069 pub fn archived(mut self, archived: impl IntoOption<SessionArchiveFilter>) -> Self {
3070 self.archived = archived.into_option();
3071 self
3072 }
3073
3074 #[must_use]
3080 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3081 self.meta = meta.into_option();
3082 self
3083 }
3084}
3085
3086#[serde_as]
3088#[skip_serializing_none]
3089#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3090#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3091#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LIST_METHOD_NAME)))]
3092#[serde(rename_all = "camelCase")]
3093#[non_exhaustive]
3094pub struct ListSessionsResponse {
3095 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
3099 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3100 pub sessions: Vec<SessionInfo>,
3101 #[serde(default)]
3105 pub next_cursor: Option<SessionListCursor>,
3106 #[serde_as(deserialize_as = "DefaultOnError")]
3112 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3113 #[serde(default)]
3114 #[serde(rename = "_meta")]
3115 pub meta: Option<Meta>,
3116}
3117
3118impl ListSessionsResponse {
3119 #[must_use]
3121 pub fn new(sessions: Vec<SessionInfo>) -> Self {
3122 Self {
3123 sessions,
3124 next_cursor: None,
3125 meta: None,
3126 }
3127 }
3128
3129 #[must_use]
3131 pub fn next_cursor(mut self, next_cursor: impl IntoOption<SessionListCursor>) -> Self {
3132 self.next_cursor = next_cursor.into_option();
3133 self
3134 }
3135
3136 #[must_use]
3142 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3143 self.meta = meta.into_option();
3144 self
3145 }
3146}
3147
3148#[serde_as]
3154#[skip_serializing_none]
3155#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3156#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3157#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_DELETE_METHOD_NAME)))]
3158#[serde(rename_all = "camelCase")]
3159#[non_exhaustive]
3160pub struct DeleteSessionRequest {
3161 pub session_id: SessionId,
3163 #[serde_as(deserialize_as = "DefaultOnError")]
3169 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3170 #[serde(default)]
3171 #[serde(rename = "_meta")]
3172 pub meta: Option<Meta>,
3173}
3174
3175impl DeleteSessionRequest {
3176 #[must_use]
3178 pub fn new(session_id: impl Into<SessionId>) -> Self {
3179 Self {
3180 session_id: session_id.into(),
3181 meta: None,
3182 }
3183 }
3184
3185 #[must_use]
3191 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3192 self.meta = meta.into_option();
3193 self
3194 }
3195}
3196
3197crate::serde_util::default_on_null! {
3198 #[serde_as]
3200 #[skip_serializing_none]
3201 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3202 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3203 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_DELETE_METHOD_NAME)))]
3204 #[serde(rename_all = "camelCase")]
3205 #[non_exhaustive]
3206 pub struct DeleteSessionResponse {
3207 #[serde_as(deserialize_as = "DefaultOnError")]
3213 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3214 #[serde(default)]
3215 #[serde(rename = "_meta")]
3216 pub meta: Option<Meta>,
3217 }
3218}
3219
3220impl DeleteSessionResponse {
3221 #[must_use]
3223 pub fn new() -> Self {
3224 Self::default()
3225 }
3226
3227 #[must_use]
3233 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3234 self.meta = meta.into_option();
3235 self
3236 }
3237}
3238
3239#[cfg(feature = "unstable_session_archive")]
3255#[serde_as]
3256#[skip_serializing_none]
3257#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3258#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3259#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_ARCHIVE_METHOD_NAME)))]
3260#[serde(rename_all = "camelCase")]
3261#[non_exhaustive]
3262pub struct ArchiveSessionRequest {
3263 pub session_id: SessionId,
3265 #[serde_as(deserialize_as = "DefaultOnError")]
3271 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3272 #[serde(default)]
3273 #[serde(rename = "_meta")]
3274 pub meta: Option<Meta>,
3275}
3276
3277#[cfg(feature = "unstable_session_archive")]
3278impl ArchiveSessionRequest {
3279 #[must_use]
3281 pub fn new(session_id: impl Into<SessionId>) -> Self {
3282 Self {
3283 session_id: session_id.into(),
3284 meta: None,
3285 }
3286 }
3287
3288 #[must_use]
3294 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3295 self.meta = meta.into_option();
3296 self
3297 }
3298}
3299
3300#[cfg(feature = "unstable_session_archive")]
3301crate::serde_util::default_on_null! {
3302 #[serde_as]
3308 #[skip_serializing_none]
3309 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3310 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3311 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_ARCHIVE_METHOD_NAME)))]
3312 #[serde(rename_all = "camelCase")]
3313 #[non_exhaustive]
3314 pub struct ArchiveSessionResponse {
3315 #[serde_as(deserialize_as = "DefaultOnError")]
3321 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3322 #[serde(default)]
3323 #[serde(rename = "_meta")]
3324 pub meta: Option<Meta>,
3325 }
3326}
3327
3328#[cfg(feature = "unstable_session_archive")]
3329impl ArchiveSessionResponse {
3330 #[must_use]
3332 pub fn new() -> Self {
3333 Self::default()
3334 }
3335
3336 #[must_use]
3342 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3343 self.meta = meta.into_option();
3344 self
3345 }
3346}
3347
3348#[cfg(feature = "unstable_session_archive")]
3363#[serde_as]
3364#[skip_serializing_none]
3365#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3366#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3367#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_UNARCHIVE_METHOD_NAME)))]
3368#[serde(rename_all = "camelCase")]
3369#[non_exhaustive]
3370pub struct UnarchiveSessionRequest {
3371 pub session_id: SessionId,
3373 #[serde_as(deserialize_as = "DefaultOnError")]
3379 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3380 #[serde(default)]
3381 #[serde(rename = "_meta")]
3382 pub meta: Option<Meta>,
3383}
3384
3385#[cfg(feature = "unstable_session_archive")]
3386impl UnarchiveSessionRequest {
3387 #[must_use]
3389 pub fn new(session_id: impl Into<SessionId>) -> Self {
3390 Self {
3391 session_id: session_id.into(),
3392 meta: None,
3393 }
3394 }
3395
3396 #[must_use]
3402 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3403 self.meta = meta.into_option();
3404 self
3405 }
3406}
3407
3408#[cfg(feature = "unstable_session_archive")]
3409crate::serde_util::default_on_null! {
3410 #[serde_as]
3416 #[skip_serializing_none]
3417 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3418 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3419 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_UNARCHIVE_METHOD_NAME)))]
3420 #[serde(rename_all = "camelCase")]
3421 #[non_exhaustive]
3422 pub struct UnarchiveSessionResponse {
3423 #[serde_as(deserialize_as = "DefaultOnError")]
3429 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3430 #[serde(default)]
3431 #[serde(rename = "_meta")]
3432 pub meta: Option<Meta>,
3433 }
3434}
3435
3436#[cfg(feature = "unstable_session_archive")]
3437impl UnarchiveSessionResponse {
3438 #[must_use]
3440 pub fn new() -> Self {
3441 Self::default()
3442 }
3443
3444 #[must_use]
3450 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3451 self.meta = meta.into_option();
3452 self
3453 }
3454}
3455
3456#[cfg(feature = "unstable_session_archive")]
3465#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3466#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
3467#[serde(rename_all = "snake_case")]
3468#[non_exhaustive]
3469pub enum SessionArchiveFilter {
3470 #[default]
3472 Exclude,
3473 Include,
3475 Only,
3477 #[serde(untagged)]
3483 Other(String),
3484}
3485
3486#[serde_as]
3488#[skip_serializing_none]
3489#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3490#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3491#[serde(rename_all = "camelCase")]
3492#[non_exhaustive]
3493pub struct SessionInfo {
3494 pub session_id: SessionId,
3496 pub cwd: AbsolutePath,
3498 #[serde_as(deserialize_as = "DefaultOnNull")]
3504 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
3505 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3506 pub additional_directories: Vec<AbsolutePath>,
3507
3508 #[serde_as(deserialize_as = "DefaultOnError")]
3512 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3513 #[serde(default)]
3514 pub title: Option<String>,
3515 #[serde_as(deserialize_as = "DefaultOnError")]
3519 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "format" = "date-time")))]
3520 #[serde(default)]
3521 pub updated_at: Option<String>,
3522 #[cfg(feature = "unstable_session_archive")]
3531 #[serde_as(deserialize_as = "DefaultOnError")]
3532 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3533 #[serde(default)]
3534 pub archived: Option<bool>,
3535 #[serde_as(deserialize_as = "DefaultOnError")]
3541 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3542 #[serde(default)]
3543 #[serde(rename = "_meta")]
3544 pub meta: Option<Meta>,
3545}
3546
3547impl SessionInfo {
3548 #[must_use]
3550 pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
3551 Self {
3552 session_id: session_id.into(),
3553 cwd: cwd.into(),
3554 additional_directories: vec![],
3555 title: None,
3556 updated_at: None,
3557 #[cfg(feature = "unstable_session_archive")]
3558 archived: None,
3559 meta: None,
3560 }
3561 }
3562
3563 #[must_use]
3565 pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
3566 where
3567 I: IntoIterator<Item = P>,
3568 P: Into<AbsolutePath>,
3569 {
3570 self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
3571 self
3572 }
3573
3574 #[must_use]
3576 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
3577 self.title = title.into_option();
3578 self
3579 }
3580
3581 #[must_use]
3583 pub fn updated_at(mut self, updated_at: impl IntoOption<String>) -> Self {
3584 self.updated_at = updated_at.into_option();
3585 self
3586 }
3587
3588 #[cfg(feature = "unstable_session_archive")]
3594 #[must_use]
3595 pub fn archived(mut self, archived: impl IntoOption<bool>) -> Self {
3596 self.archived = archived.into_option();
3597 self
3598 }
3599
3600 #[must_use]
3606 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3607 self.meta = meta.into_option();
3608 self
3609 }
3610}
3611
3612#[cfg(feature = "unstable_session_set_title")]
3628#[serde_as]
3629#[skip_serializing_none]
3630#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3631#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3632#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_TITLE_METHOD_NAME)))]
3633#[serde(rename_all = "camelCase")]
3634#[non_exhaustive]
3635pub struct SetSessionTitleRequest {
3636 pub session_id: SessionId,
3638 pub title: String,
3645 #[serde_as(deserialize_as = "DefaultOnError")]
3651 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3652 #[serde(default)]
3653 #[serde(rename = "_meta")]
3654 pub meta: Option<Meta>,
3655}
3656
3657#[cfg(feature = "unstable_session_set_title")]
3658impl SetSessionTitleRequest {
3659 #[must_use]
3661 pub fn new(session_id: impl Into<SessionId>, title: impl Into<String>) -> Self {
3662 Self {
3663 session_id: session_id.into(),
3664 title: title.into(),
3665 meta: None,
3666 }
3667 }
3668
3669 #[must_use]
3675 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3676 self.meta = meta.into_option();
3677 self
3678 }
3679}
3680
3681#[cfg(feature = "unstable_session_set_title")]
3687#[serde_as]
3688#[skip_serializing_none]
3689#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3690#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3691#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_TITLE_METHOD_NAME)))]
3692#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "sessionInfo", "field": "title", "value": "title"}]})))]
3693#[serde(rename_all = "camelCase")]
3694#[non_exhaustive]
3695pub struct SetSessionTitleResponse {
3696 pub title: String,
3701 #[serde_as(deserialize_as = "DefaultOnError")]
3707 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3708 #[serde(default)]
3709 #[serde(rename = "_meta")]
3710 pub meta: Option<Meta>,
3711}
3712
3713#[cfg(feature = "unstable_session_set_title")]
3714impl SetSessionTitleResponse {
3715 #[must_use]
3717 pub fn new(title: impl Into<String>) -> Self {
3718 Self {
3719 title: title.into(),
3720 meta: None,
3721 }
3722 }
3723
3724 #[must_use]
3730 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3731 self.meta = meta.into_option();
3732 self
3733 }
3734}
3735
3736#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3740#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3741#[serde(transparent)]
3742#[from(forward)]
3743#[non_exhaustive]
3744pub struct SessionConfigId(pub Arc<str>);
3745
3746impl SessionConfigId {
3747 #[must_use]
3749 pub fn new(id: impl Into<Self>) -> Self {
3750 id.into()
3751 }
3752}
3753
3754#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3756#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3757#[serde(transparent)]
3758#[from(forward)]
3759#[non_exhaustive]
3760pub struct SessionConfigValueId(pub Arc<str>);
3761
3762impl SessionConfigValueId {
3763 #[must_use]
3765 pub fn new(id: impl Into<Self>) -> Self {
3766 id.into()
3767 }
3768}
3769
3770#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3772#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3773#[serde(transparent)]
3774#[from(forward)]
3775#[non_exhaustive]
3776pub struct SessionConfigGroupId(pub Arc<str>);
3777
3778impl SessionConfigGroupId {
3779 #[must_use]
3781 pub fn new(id: impl Into<Self>) -> Self {
3782 id.into()
3783 }
3784}
3785
3786#[serde_as]
3788#[skip_serializing_none]
3789#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3790#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3791#[serde(rename_all = "camelCase")]
3792#[non_exhaustive]
3793pub struct SessionConfigSelectOption {
3794 pub value: SessionConfigValueId,
3796 pub name: String,
3798 #[serde_as(deserialize_as = "DefaultOnError")]
3803 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3804 #[serde(default)]
3805 pub description: Option<String>,
3806 #[serde_as(deserialize_as = "DefaultOnError")]
3812 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3813 #[serde(default)]
3814 #[serde(rename = "_meta")]
3815 pub meta: Option<Meta>,
3816}
3817
3818impl SessionConfigSelectOption {
3819 #[must_use]
3821 pub fn new(value: impl Into<SessionConfigValueId>, name: impl Into<String>) -> Self {
3822 Self {
3823 value: value.into(),
3824 name: name.into(),
3825 description: None,
3826 meta: None,
3827 }
3828 }
3829
3830 #[must_use]
3832 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
3833 self.description = description.into_option();
3834 self
3835 }
3836
3837 #[must_use]
3843 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3844 self.meta = meta.into_option();
3845 self
3846 }
3847}
3848
3849#[serde_as]
3851#[skip_serializing_none]
3852#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3853#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3854#[serde(rename_all = "camelCase")]
3855#[non_exhaustive]
3856pub struct SessionConfigSelectGroup {
3857 pub group_id: SessionConfigGroupId,
3859 pub name: String,
3861 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
3863 #[cfg_attr(feature = "schemars", schemars(length(min = 1), extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3864 pub options: Vec<SessionConfigSelectOption>,
3865 #[serde_as(deserialize_as = "DefaultOnError")]
3871 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3872 #[serde(default)]
3873 #[serde(rename = "_meta")]
3874 pub meta: Option<Meta>,
3875}
3876
3877impl SessionConfigSelectGroup {
3878 #[must_use]
3880 pub fn new(
3881 group_id: impl Into<SessionConfigGroupId>,
3882 name: impl Into<String>,
3883 options: Vec<SessionConfigSelectOption>,
3884 ) -> Self {
3885 Self {
3886 group_id: group_id.into(),
3887 name: name.into(),
3888 options,
3889 meta: None,
3890 }
3891 }
3892
3893 #[must_use]
3899 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3900 self.meta = meta.into_option();
3901 self
3902 }
3903}
3904
3905#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3907#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3908#[serde(untagged)]
3909#[non_exhaustive]
3910pub enum SessionConfigSelectOptions {
3911 Ungrouped(
3913 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))] Vec<SessionConfigSelectOption>,
3914 ),
3915 Grouped(
3917 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))] Vec<SessionConfigSelectGroup>,
3918 ),
3919}
3920
3921impl From<Vec<SessionConfigSelectOption>> for SessionConfigSelectOptions {
3922 fn from(options: Vec<SessionConfigSelectOption>) -> Self {
3923 SessionConfigSelectOptions::Ungrouped(options)
3924 }
3925}
3926
3927impl From<Vec<SessionConfigSelectGroup>> for SessionConfigSelectOptions {
3928 fn from(groups: Vec<SessionConfigSelectGroup>) -> Self {
3929 SessionConfigSelectOptions::Grouped(groups)
3930 }
3931}
3932
3933#[skip_serializing_none]
3935#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3936#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3937#[serde(rename_all = "camelCase")]
3938#[non_exhaustive]
3939pub struct SessionConfigSelect {
3940 pub current_value: SessionConfigValueId,
3942 pub options: SessionConfigSelectOptions,
3945}
3946
3947impl SessionConfigSelect {
3948 #[must_use]
3950 pub fn new(
3951 current_value: impl Into<SessionConfigValueId>,
3952 options: impl Into<SessionConfigSelectOptions>,
3953 ) -> Self {
3954 Self {
3955 current_value: current_value.into(),
3956 options: options.into(),
3957 }
3958 }
3959}
3960
3961#[skip_serializing_none]
3963#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3964#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3965#[serde(rename_all = "camelCase")]
3966#[non_exhaustive]
3967pub struct SessionConfigBoolean {
3968 pub current_value: bool,
3970}
3971
3972impl SessionConfigBoolean {
3973 #[must_use]
3975 pub fn new(current_value: bool) -> Self {
3976 Self { current_value }
3977 }
3978}
3979
3980#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3990#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3991#[serde(rename_all = "snake_case")]
3992#[non_exhaustive]
3993pub enum SessionConfigOptionCategory {
3994 Mode,
3996 Model,
3998 ModelConfig,
4000 #[cfg(feature = "unstable_speed_config_category")]
4006 Speed,
4007 ThoughtLevel,
4009 #[serde(untagged)]
4015 Other(String),
4016}
4017
4018#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4020#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4021#[serde(tag = "type", rename_all = "snake_case")]
4022#[non_exhaustive]
4023pub enum SessionConfigKind {
4024 Select(SessionConfigSelect),
4026 Boolean(SessionConfigBoolean),
4028 #[serde(untagged)]
4038 Other(OtherSessionConfigKind),
4039}
4040
4041#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4043#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4044#[cfg_attr(feature = "schemars", schemars(inline))]
4045#[cfg_attr(feature = "schemars", schemars(transform = other_session_config_kind_schema))]
4046#[serde(rename_all = "camelCase")]
4047#[non_exhaustive]
4048pub struct OtherSessionConfigKind {
4049 #[serde(rename = "type")]
4055 pub type_: String,
4056 #[serde(flatten)]
4058 pub fields: IndexMap<String, serde_json::Value>,
4059}
4060
4061impl OtherSessionConfigKind {
4062 #[must_use]
4064 pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
4065 fields.shift_remove("type");
4066 fields.shift_remove("_meta");
4067 Self {
4068 type_: type_.into(),
4069 fields,
4070 }
4071 }
4072}
4073
4074impl<'de> Deserialize<'de> for OtherSessionConfigKind {
4075 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4076 where
4077 D: serde::Deserializer<'de>,
4078 {
4079 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4080 let type_ = fields
4081 .shift_remove("type")
4082 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4083 let serde_json::Value::String(type_) = type_ else {
4084 return Err(serde::de::Error::custom("`type` must be a string"));
4085 };
4086
4087 if is_known_session_config_kind_type(&type_) {
4088 return Err(serde::de::Error::custom(format!(
4089 "known session configuration option `{type_}` did not match its schema"
4090 )));
4091 }
4092
4093 Ok(Self { type_, fields })
4094 }
4095}
4096
4097fn is_known_session_config_kind_type(type_: &str) -> bool {
4098 matches!(type_, "select" | "boolean")
4099}
4100
4101#[cfg(feature = "schemars")]
4102fn other_session_config_kind_schema(schema: &mut Schema) {
4103 super::schema_util::reject_known_string_discriminators(schema, "type", &["select", "boolean"]);
4104}
4105
4106#[serde_as]
4108#[skip_serializing_none]
4109#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4110#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4111#[serde(rename_all = "camelCase")]
4112#[non_exhaustive]
4113pub struct SessionConfigOption {
4114 pub config_id: SessionConfigId,
4116 pub name: String,
4118 #[serde_as(deserialize_as = "DefaultOnError")]
4123 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4124 #[serde(default)]
4125 pub description: Option<String>,
4126 #[serde_as(deserialize_as = "DefaultOnError")]
4130 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4131 #[serde(default)]
4132 pub category: Option<SessionConfigOptionCategory>,
4133 #[serde(flatten)]
4135 pub kind: SessionConfigKind,
4136 #[serde_as(deserialize_as = "DefaultOnError")]
4142 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4143 #[serde(default)]
4144 #[serde(rename = "_meta")]
4145 pub meta: Option<Meta>,
4146}
4147
4148impl SessionConfigOption {
4149 #[must_use]
4151 pub fn new(
4152 config_id: impl Into<SessionConfigId>,
4153 name: impl Into<String>,
4154 kind: SessionConfigKind,
4155 ) -> Self {
4156 Self {
4157 config_id: config_id.into(),
4158 name: name.into(),
4159 description: None,
4160 category: None,
4161 kind,
4162 meta: None,
4163 }
4164 }
4165
4166 #[must_use]
4168 pub fn select(
4169 config_id: impl Into<SessionConfigId>,
4170 name: impl Into<String>,
4171 current_value: impl Into<SessionConfigValueId>,
4172 options: impl Into<SessionConfigSelectOptions>,
4173 ) -> Self {
4174 Self::new(
4175 config_id,
4176 name,
4177 SessionConfigKind::Select(SessionConfigSelect::new(current_value, options)),
4178 )
4179 }
4180
4181 #[must_use]
4183 pub fn boolean(
4184 config_id: impl Into<SessionConfigId>,
4185 name: impl Into<String>,
4186 current_value: bool,
4187 ) -> Self {
4188 Self::new(
4189 config_id,
4190 name,
4191 SessionConfigKind::Boolean(SessionConfigBoolean::new(current_value)),
4192 )
4193 }
4194
4195 #[must_use]
4197 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
4198 self.description = description.into_option();
4199 self
4200 }
4201
4202 #[must_use]
4204 pub fn category(mut self, category: impl IntoOption<SessionConfigOptionCategory>) -> Self {
4205 self.category = category.into_option();
4206 self
4207 }
4208
4209 #[must_use]
4215 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4216 self.meta = meta.into_option();
4217 self
4218 }
4219}
4220
4221#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4230#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4231#[serde(tag = "type", rename_all = "snake_case")]
4232#[non_exhaustive]
4233pub enum SessionConfigOptionValue {
4234 Id {
4236 value: SessionConfigValueId,
4238 },
4239 Boolean {
4241 value: bool,
4243 },
4244 #[serde(untagged)]
4253 Other(Box<OtherSessionConfigOptionValue>),
4254}
4255
4256#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4258#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4259#[cfg_attr(feature = "schemars", schemars(inline))]
4260#[cfg_attr(feature = "schemars", schemars(transform = other_session_config_option_value_schema))]
4261#[serde(rename_all = "camelCase")]
4262#[non_exhaustive]
4263pub struct OtherSessionConfigOptionValue {
4264 #[serde(rename = "type")]
4270 pub type_: String,
4271 pub value: serde_json::Value,
4273 #[serde(flatten)]
4275 pub fields: IndexMap<String, serde_json::Value>,
4276}
4277
4278impl OtherSessionConfigOptionValue {
4279 #[must_use]
4281 pub fn new(
4282 type_: impl Into<String>,
4283 value: serde_json::Value,
4284 mut fields: IndexMap<String, serde_json::Value>,
4285 ) -> Self {
4286 fields.shift_remove("type");
4287 fields.shift_remove("value");
4288 fields.shift_remove("_meta");
4289 Self {
4290 type_: type_.into(),
4291 value,
4292 fields,
4293 }
4294 }
4295}
4296
4297impl<'de> Deserialize<'de> for OtherSessionConfigOptionValue {
4298 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4299 where
4300 D: serde::Deserializer<'de>,
4301 {
4302 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4303 let type_ = fields
4304 .shift_remove("type")
4305 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4306 let serde_json::Value::String(type_) = type_ else {
4307 return Err(serde::de::Error::custom("`type` must be a string"));
4308 };
4309
4310 if is_known_session_config_option_value_type(&type_) {
4311 return Err(serde::de::Error::custom(format!(
4312 "known session configuration option value `{type_}` did not match its schema"
4313 )));
4314 }
4315
4316 let value = fields
4317 .shift_remove("value")
4318 .ok_or_else(|| serde::de::Error::missing_field("value"))?;
4319
4320 Ok(Self {
4321 type_,
4322 value,
4323 fields,
4324 })
4325 }
4326}
4327
4328impl<'de> Deserialize<'de> for SessionConfigOptionValue {
4329 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4330 where
4331 D: serde::Deserializer<'de>,
4332 {
4333 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4334 let type_ = fields.shift_remove("type");
4335 let value = fields
4336 .shift_remove("value")
4337 .ok_or_else(|| serde::de::Error::missing_field("value"))?;
4338
4339 let type_ = type_.ok_or_else(|| serde::de::Error::missing_field("type"))?;
4340
4341 let serde_json::Value::String(type_) = type_ else {
4342 return Err(serde::de::Error::custom("`type` must be a string"));
4343 };
4344
4345 match type_.as_str() {
4346 "id" => {
4347 let value = serde_json::from_value(value).map_err(|error| {
4348 serde::de::Error::custom(format!(
4349 "`value` must be a string for `type: id`: {error}"
4350 ))
4351 })?;
4352 Ok(Self::Id { value })
4353 }
4354 "boolean" => {
4355 let value = serde_json::from_value(value).map_err(|error| {
4356 serde::de::Error::custom(format!(
4357 "`value` must be a boolean for `type: boolean`: {error}"
4358 ))
4359 })?;
4360 Ok(Self::Boolean { value })
4361 }
4362 _ => Ok(OtherSessionConfigOptionValue {
4363 type_,
4364 value,
4365 fields,
4366 }
4367 .into()),
4368 }
4369 }
4370}
4371
4372fn is_known_session_config_option_value_type(type_: &str) -> bool {
4373 matches!(type_, "id" | "boolean")
4374}
4375
4376#[cfg(feature = "schemars")]
4377fn other_session_config_option_value_schema(schema: &mut Schema) {
4378 super::schema_util::reject_known_string_discriminators(schema, "type", &["id", "boolean"]);
4379}
4380
4381impl SessionConfigOptionValue {
4382 #[must_use]
4384 pub fn id(id: impl Into<SessionConfigValueId>) -> Self {
4385 Self::Id { value: id.into() }
4386 }
4387
4388 #[must_use]
4390 pub fn boolean(val: bool) -> Self {
4391 Self::Boolean { value: val }
4392 }
4393
4394 #[must_use]
4397 pub fn as_id(&self) -> Option<&SessionConfigValueId> {
4398 match self {
4399 Self::Id { value } => Some(value),
4400 _ => None,
4401 }
4402 }
4403
4404 #[must_use]
4406 pub fn as_bool(&self) -> Option<bool> {
4407 match self {
4408 Self::Boolean { value } => Some(*value),
4409 _ => None,
4410 }
4411 }
4412}
4413
4414impl From<SessionConfigValueId> for SessionConfigOptionValue {
4415 fn from(value: SessionConfigValueId) -> Self {
4416 Self::Id { value }
4417 }
4418}
4419
4420impl From<bool> for SessionConfigOptionValue {
4421 fn from(value: bool) -> Self {
4422 Self::Boolean { value }
4423 }
4424}
4425
4426impl From<OtherSessionConfigOptionValue> for SessionConfigOptionValue {
4427 fn from(value: OtherSessionConfigOptionValue) -> Self {
4428 Self::Other(Box::new(value))
4429 }
4430}
4431
4432impl From<&str> for SessionConfigOptionValue {
4433 fn from(value: &str) -> Self {
4434 Self::Id {
4435 value: SessionConfigValueId::new(value),
4436 }
4437 }
4438}
4439
4440#[serde_as]
4451#[skip_serializing_none]
4452#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4453#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4454#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_CONFIG_OPTION_METHOD_NAME)))]
4455#[serde(rename_all = "camelCase")]
4456#[non_exhaustive]
4457pub struct SetSessionConfigOptionRequest {
4458 pub session_id: SessionId,
4460 pub config_id: SessionConfigId,
4462 #[serde(flatten)]
4466 pub value: SessionConfigOptionValue,
4467 #[serde_as(deserialize_as = "DefaultOnError")]
4473 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4474 #[serde(default)]
4475 #[serde(rename = "_meta")]
4476 pub meta: Option<Meta>,
4477}
4478
4479impl SetSessionConfigOptionRequest {
4480 #[must_use]
4482 pub fn new(
4483 session_id: impl Into<SessionId>,
4484 config_id: impl Into<SessionConfigId>,
4485 value: impl Into<SessionConfigOptionValue>,
4486 ) -> Self {
4487 Self {
4488 session_id: session_id.into(),
4489 config_id: config_id.into(),
4490 value: value.into(),
4491 meta: None,
4492 }
4493 }
4494
4495 #[must_use]
4501 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4502 self.meta = meta.into_option();
4503 self
4504 }
4505}
4506
4507#[serde_as]
4509#[skip_serializing_none]
4510#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4511#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4512#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_CONFIG_OPTION_METHOD_NAME)))]
4513#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}]})))]
4514#[serde(rename_all = "camelCase")]
4515#[non_exhaustive]
4516pub struct SetSessionConfigOptionResponse {
4517 #[serde_as(deserialize_as = "VecSkipError<_>")]
4519 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
4520 pub config_options: Vec<SessionConfigOption>,
4521 #[serde_as(deserialize_as = "DefaultOnError")]
4527 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4528 #[serde(default)]
4529 #[serde(rename = "_meta")]
4530 pub meta: Option<Meta>,
4531}
4532
4533impl SetSessionConfigOptionResponse {
4534 #[must_use]
4536 pub fn new(config_options: Vec<SessionConfigOption>) -> Self {
4537 Self {
4538 config_options,
4539 meta: None,
4540 }
4541 }
4542
4543 #[must_use]
4549 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4550 self.meta = meta.into_option();
4551 self
4552 }
4553}
4554
4555#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4564#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4565#[serde(tag = "type", rename_all = "snake_case")]
4566#[non_exhaustive]
4567pub enum McpServer {
4568 Http(McpServerHttp),
4572 #[cfg(feature = "unstable_mcp_over_acp")]
4581 Acp(McpServerAcp),
4582 Stdio(McpServerStdio),
4586 #[serde(untagged)]
4597 Other(OtherMcpServer),
4598}
4599
4600#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4602#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4603#[cfg_attr(feature = "schemars", schemars(inline))]
4604#[cfg_attr(feature = "schemars", schemars(transform = other_mcp_server_schema))]
4605#[serde(rename_all = "camelCase")]
4606#[non_exhaustive]
4607pub struct OtherMcpServer {
4608 #[serde(rename = "type")]
4614 pub type_: String,
4615 #[serde(flatten)]
4617 pub fields: IndexMap<String, serde_json::Value>,
4618}
4619
4620impl OtherMcpServer {
4621 #[must_use]
4623 pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
4624 fields.shift_remove("type");
4625 Self {
4626 type_: type_.into(),
4627 fields,
4628 }
4629 }
4630}
4631
4632impl<'de> Deserialize<'de> for OtherMcpServer {
4633 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4634 where
4635 D: serde::Deserializer<'de>,
4636 {
4637 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4638 let type_ = fields
4639 .shift_remove("type")
4640 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4641 let serde_json::Value::String(type_) = type_ else {
4642 return Err(serde::de::Error::custom("`type` must be a string"));
4643 };
4644
4645 if is_known_mcp_server_type(&type_) {
4646 return Err(serde::de::Error::custom(format!(
4647 "known MCP server transport `{type_}` did not match its schema"
4648 )));
4649 }
4650
4651 Ok(Self { type_, fields })
4652 }
4653}
4654
4655fn is_known_mcp_server_type(type_: &str) -> bool {
4656 match type_ {
4657 "http" | "stdio" => true,
4658 #[cfg(feature = "unstable_mcp_over_acp")]
4659 "acp" => true,
4660 _ => false,
4661 }
4662}
4663
4664#[cfg(feature = "schemars")]
4665fn other_mcp_server_schema(schema: &mut Schema) {
4666 super::schema_util::reject_known_string_discriminators(
4667 schema,
4668 "type",
4669 &[
4670 "http",
4671 "stdio",
4672 #[cfg(feature = "unstable_mcp_over_acp")]
4673 "acp",
4674 ],
4675 );
4676}
4677
4678#[serde_as]
4680#[skip_serializing_none]
4681#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4682#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4683#[serde(rename_all = "camelCase")]
4684#[non_exhaustive]
4685pub struct McpServerHttp {
4686 pub name: String,
4690 #[cfg_attr(feature = "schemars", schemars(url))]
4692 pub url: String,
4693 #[serde_as(deserialize_as = "DefaultOnNull")]
4696 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4697 #[serde(default, skip_serializing_if = "Vec::is_empty")]
4698 pub headers: Vec<HttpHeader>,
4699 #[serde_as(deserialize_as = "DefaultOnError")]
4705 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4706 #[serde(default)]
4707 #[serde(rename = "_meta")]
4708 pub meta: Option<Meta>,
4709}
4710
4711impl McpServerHttp {
4712 #[must_use]
4714 pub fn new(name: impl Into<String>, url: impl Into<String>) -> Self {
4715 Self {
4716 name: name.into(),
4717 url: url.into(),
4718 headers: Vec::new(),
4719 meta: None,
4720 }
4721 }
4722
4723 #[must_use]
4726 pub fn headers(mut self, headers: Vec<HttpHeader>) -> Self {
4727 self.headers = headers;
4728 self
4729 }
4730
4731 #[must_use]
4737 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4738 self.meta = meta.into_option();
4739 self
4740 }
4741}
4742
4743#[cfg(feature = "unstable_mcp_over_acp")]
4752#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4753#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
4754#[serde(transparent)]
4755#[from(forward)]
4756#[non_exhaustive]
4757pub struct McpServerAcpId(pub Arc<str>);
4758
4759#[cfg(feature = "unstable_mcp_over_acp")]
4760impl McpServerAcpId {
4761 #[must_use]
4763 pub fn new(id: impl Into<Self>) -> Self {
4764 id.into()
4765 }
4766}
4767
4768#[serde_as]
4777#[skip_serializing_none]
4778#[cfg(feature = "unstable_mcp_over_acp")]
4779#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4780#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4781#[serde(rename_all = "camelCase")]
4782#[non_exhaustive]
4783pub struct McpServerAcp {
4784 pub name: String,
4788 pub server_id: McpServerAcpId,
4793 #[serde_as(deserialize_as = "DefaultOnError")]
4799 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4800 #[serde(default)]
4801 #[serde(rename = "_meta")]
4802 pub meta: Option<Meta>,
4803}
4804
4805#[cfg(feature = "unstable_mcp_over_acp")]
4806impl McpServerAcp {
4807 #[must_use]
4809 pub fn new(name: impl Into<String>, server_id: impl Into<McpServerAcpId>) -> Self {
4810 Self {
4811 name: name.into(),
4812 server_id: server_id.into(),
4813 meta: None,
4814 }
4815 }
4816
4817 #[must_use]
4823 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4824 self.meta = meta.into_option();
4825 self
4826 }
4827}
4828
4829#[serde_as]
4831#[skip_serializing_none]
4832#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4833#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4834#[serde(rename_all = "camelCase")]
4835#[non_exhaustive]
4836pub struct McpServerStdio {
4837 pub name: String,
4841 pub command: AbsolutePath,
4845 #[serde_as(deserialize_as = "DefaultOnNull")]
4847 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4848 #[serde(default, skip_serializing_if = "Vec::is_empty")]
4849 pub args: Vec<String>,
4850 #[serde_as(deserialize_as = "DefaultOnNull")]
4853 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4854 #[serde(default, skip_serializing_if = "Vec::is_empty")]
4855 pub env: Vec<EnvVariable>,
4856 #[serde_as(deserialize_as = "DefaultOnError")]
4862 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4863 #[serde(default)]
4864 #[serde(rename = "_meta")]
4865 pub meta: Option<Meta>,
4866}
4867
4868impl McpServerStdio {
4869 #[must_use]
4871 pub fn new(name: impl Into<String>, command: impl Into<AbsolutePath>) -> Self {
4872 Self {
4873 name: name.into(),
4874 command: command.into(),
4875 args: Vec::new(),
4876 env: Vec::new(),
4877 meta: None,
4878 }
4879 }
4880
4881 #[must_use]
4883 pub fn args(mut self, args: Vec<String>) -> Self {
4884 self.args = args;
4885 self
4886 }
4887
4888 #[must_use]
4891 pub fn env(mut self, env: Vec<EnvVariable>) -> Self {
4892 self.env = env;
4893 self
4894 }
4895
4896 #[must_use]
4902 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4903 self.meta = meta.into_option();
4904 self
4905 }
4906}
4907
4908#[serde_as]
4910#[skip_serializing_none]
4911#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4912#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4913#[serde(rename_all = "camelCase")]
4914#[non_exhaustive]
4915pub struct EnvVariable {
4916 pub name: String,
4918 pub value: String,
4920 #[serde_as(deserialize_as = "DefaultOnError")]
4926 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4927 #[serde(default)]
4928 #[serde(rename = "_meta")]
4929 pub meta: Option<Meta>,
4930}
4931
4932impl EnvVariable {
4933 #[must_use]
4935 pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
4936 Self {
4937 name: name.into(),
4938 value: value.into(),
4939 meta: None,
4940 }
4941 }
4942
4943 #[must_use]
4949 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4950 self.meta = meta.into_option();
4951 self
4952 }
4953}
4954
4955#[serde_as]
4957#[skip_serializing_none]
4958#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4959#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4960#[serde(rename_all = "camelCase")]
4961#[non_exhaustive]
4962pub struct HttpHeader {
4963 pub name: String,
4965 pub value: String,
4967 #[serde_as(deserialize_as = "DefaultOnError")]
4973 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4974 #[serde(default)]
4975 #[serde(rename = "_meta")]
4976 pub meta: Option<Meta>,
4977}
4978
4979impl HttpHeader {
4980 #[must_use]
4982 pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
4983 Self {
4984 name: name.into(),
4985 value: value.into(),
4986 meta: None,
4987 }
4988 }
4989
4990 #[must_use]
4996 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4997 self.meta = meta.into_option();
4998 self
4999 }
5000}
5001
5002#[serde_as]
5011#[skip_serializing_none]
5012#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5013#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5014#[serde(rename_all = "camelCase")]
5015#[non_exhaustive]
5016pub struct SystemPrompt {
5017 pub mode: SystemPromptMode,
5022 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
5032 pub content: Vec<ContentBlock>,
5033 #[serde_as(deserialize_as = "DefaultOnError")]
5039 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5040 #[serde(default)]
5041 #[serde(rename = "_meta")]
5042 pub meta: Option<Meta>,
5043}
5044
5045impl SystemPrompt {
5046 #[must_use]
5051 pub fn new(content: Vec<ContentBlock>) -> Self {
5052 Self {
5053 mode: SystemPromptMode::default(),
5054 content,
5055 meta: None,
5056 }
5057 }
5058
5059 #[must_use]
5061 pub fn mode(mut self, mode: SystemPromptMode) -> Self {
5062 self.mode = mode;
5063 self
5064 }
5065
5066 #[must_use]
5072 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5073 self.meta = meta.into_option();
5074 self
5075 }
5076}
5077
5078#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5084#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
5085#[serde(rename_all = "snake_case")]
5086#[non_exhaustive]
5087pub enum SystemPromptMode {
5088 #[default]
5095 Append,
5096 Override,
5105 #[serde(untagged)]
5111 Other(String),
5112}
5113
5114#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5123#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash, Display)]
5124#[serde(transparent)]
5125pub struct IdempotencyKey(
5126 #[cfg_attr(feature = "schemars", schemars(length(min = 1, max = 255)))] Arc<str>,
5127);
5128
5129impl IdempotencyKey {
5130 pub const MAX_LENGTH: usize = 255;
5132
5133 pub fn new(key: impl Into<Arc<str>>) -> Result<Self, InvalidIdempotencyKey> {
5140 let key = key.into();
5141 if key.is_empty() {
5142 return Err(InvalidIdempotencyKey::Empty);
5143 }
5144 if key.chars().nth(Self::MAX_LENGTH).is_some() {
5146 return Err(InvalidIdempotencyKey::TooLong);
5147 }
5148 Ok(Self(key))
5149 }
5150
5151 #[cfg(feature = "uuid")]
5158 #[must_use]
5159 pub fn generate() -> Self {
5160 uuid::Uuid::new_v4().into()
5161 }
5162
5163 #[must_use]
5165 pub fn as_str(&self) -> &str {
5166 &self.0
5167 }
5168}
5169
5170impl AsRef<str> for IdempotencyKey {
5171 fn as_ref(&self) -> &str {
5172 &self.0
5173 }
5174}
5175
5176#[cfg(feature = "uuid")]
5177impl From<uuid::Uuid> for IdempotencyKey {
5178 fn from(uuid: uuid::Uuid) -> Self {
5181 Self(uuid.to_string().into())
5182 }
5183}
5184
5185impl TryFrom<String> for IdempotencyKey {
5186 type Error = InvalidIdempotencyKey;
5187
5188 fn try_from(key: String) -> Result<Self, Self::Error> {
5189 Self::new(key)
5190 }
5191}
5192
5193impl TryFrom<&str> for IdempotencyKey {
5194 type Error = InvalidIdempotencyKey;
5195
5196 fn try_from(key: &str) -> Result<Self, Self::Error> {
5197 Self::new(key)
5198 }
5199}
5200
5201impl std::str::FromStr for IdempotencyKey {
5202 type Err = InvalidIdempotencyKey;
5203
5204 fn from_str(key: &str) -> Result<Self, Self::Err> {
5205 Self::new(key)
5206 }
5207}
5208
5209impl<'de> Deserialize<'de> for IdempotencyKey {
5212 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
5213 where
5214 D: serde::Deserializer<'de>,
5215 {
5216 let key = Arc::<str>::deserialize(deserializer)?;
5217 Self::new(key).map_err(serde::de::Error::custom)
5218 }
5219}
5220
5221#[derive(Debug, Clone, Copy, PartialEq, Eq, Display)]
5223#[non_exhaustive]
5224pub enum InvalidIdempotencyKey {
5225 #[display("idempotency key must not be empty")]
5227 Empty,
5228 #[display(
5230 "idempotency key must be at most {} characters",
5231 IdempotencyKey::MAX_LENGTH
5232 )]
5233 TooLong,
5234}
5235
5236impl std::error::Error for InvalidIdempotencyKey {}
5237
5238#[serde_as]
5244#[skip_serializing_none]
5245#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5246#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5247#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_PROMPT_METHOD_NAME)))]
5248#[serde(rename_all = "camelCase")]
5249#[non_exhaustive]
5250pub struct PromptRequest {
5251 pub session_id: SessionId,
5253 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
5270 pub prompt: Vec<ContentBlock>,
5271 #[serde(default)]
5293 pub idempotency_key: Option<IdempotencyKey>,
5294 #[serde_as(deserialize_as = "DefaultOnError")]
5300 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5301 #[serde(default)]
5302 #[serde(rename = "_meta")]
5303 pub meta: Option<Meta>,
5304}
5305
5306impl PromptRequest {
5307 #[must_use]
5309 pub fn new(session_id: impl Into<SessionId>, prompt: Vec<ContentBlock>) -> Self {
5310 Self {
5311 session_id: session_id.into(),
5312 prompt,
5313 idempotency_key: None,
5314 meta: None,
5315 }
5316 }
5317
5318 #[must_use]
5322 pub fn idempotency_key(mut self, idempotency_key: impl IntoOption<IdempotencyKey>) -> Self {
5323 self.idempotency_key = idempotency_key.into_option();
5324 self
5325 }
5326
5327 #[must_use]
5333 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5334 self.meta = meta.into_option();
5335 self
5336 }
5337}
5338
5339#[serde_as]
5350#[skip_serializing_none]
5351#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5352#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5353#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_PROMPT_METHOD_NAME)))]
5354#[serde(rename_all = "camelCase")]
5355#[non_exhaustive]
5356pub struct PromptResponse {
5357 pub message_id: MessageId,
5365 #[serde_as(deserialize_as = "DefaultOnError")]
5371 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5372 #[serde(default)]
5373 #[serde(rename = "_meta")]
5374 pub meta: Option<Meta>,
5375}
5376
5377impl PromptResponse {
5378 #[must_use]
5380 pub fn new(message_id: impl Into<MessageId>) -> Self {
5381 Self {
5382 message_id: message_id.into(),
5383 meta: None,
5384 }
5385 }
5386
5387 #[must_use]
5393 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5394 self.meta = meta.into_option();
5395 self
5396 }
5397}
5398
5399#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5403#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
5404#[serde(tag = "stopReason", rename_all = "snake_case")]
5405#[non_exhaustive]
5406pub enum StopReason {
5407 EndTurn,
5410 MaxTokens,
5412 MaxTurnRequests,
5415 Refusal,
5417 Cancelled,
5429 Error(ErrorStopReason),
5435 #[serde(untagged)]
5441 Other(OtherStopReason),
5442}
5443
5444impl From<ErrorStopReason> for StopReason {
5445 fn from(value: ErrorStopReason) -> Self {
5446 Self::Error(value)
5447 }
5448}
5449
5450#[serde_as]
5452#[skip_serializing_none]
5453#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5454#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
5455#[serde(rename_all = "camelCase")]
5456#[non_exhaustive]
5457pub struct ErrorStopReason {
5458 #[serde_as(deserialize_as = "DefaultOnError")]
5463 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5464 #[serde(default)]
5465 pub error: Option<Box<Error>>,
5466}
5467
5468impl ErrorStopReason {
5469 #[must_use]
5471 pub fn new() -> Self {
5472 Self::default()
5473 }
5474
5475 #[must_use]
5477 pub fn error(mut self, error: impl IntoOption<Error>) -> Self {
5478 self.error = error.into_option().map(Box::new);
5479 self
5480 }
5481}
5482
5483#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5485#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
5486#[cfg_attr(feature = "schemars", schemars(inline))]
5487#[cfg_attr(feature = "schemars", schemars(transform = other_stop_reason_schema))]
5488#[serde(rename_all = "camelCase")]
5489#[non_exhaustive]
5490pub struct OtherStopReason {
5491 pub stop_reason: String,
5497 #[serde(flatten)]
5499 pub fields: IndexMap<String, serde_json::Value>,
5500}
5501
5502impl OtherStopReason {
5503 #[must_use]
5505 pub fn new(
5506 stop_reason: impl Into<String>,
5507 mut fields: IndexMap<String, serde_json::Value>,
5508 ) -> Self {
5509 remove_idle_state_update_fields(&mut fields);
5510 Self {
5511 stop_reason: stop_reason.into(),
5512 fields,
5513 }
5514 }
5515}
5516
5517impl<'de> Deserialize<'de> for OtherStopReason {
5518 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
5519 where
5520 D: serde::Deserializer<'de>,
5521 {
5522 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
5523 let stop_reason = fields
5524 .shift_remove("stopReason")
5525 .ok_or_else(|| serde::de::Error::missing_field("stopReason"))?;
5526 let serde_json::Value::String(stop_reason) = stop_reason else {
5527 return Err(serde::de::Error::custom("`stopReason` must be a string"));
5528 };
5529
5530 if KNOWN_STOP_REASONS.contains(&stop_reason.as_str()) {
5531 return Err(serde::de::Error::custom(format!(
5532 "known stop reason `{stop_reason}` did not match its schema"
5533 )));
5534 }
5535 remove_idle_state_update_fields(&mut fields);
5536
5537 Ok(Self {
5538 stop_reason,
5539 fields,
5540 })
5541 }
5542}
5543
5544const KNOWN_STOP_REASONS: &[&str] = &[
5545 "end_turn",
5546 "max_tokens",
5547 "max_turn_requests",
5548 "refusal",
5549 "cancelled",
5550 "error",
5551];
5552
5553fn remove_idle_state_update_fields(fields: &mut IndexMap<String, serde_json::Value>) {
5555 fields.shift_remove("stopReason");
5556 fields.shift_remove("usage");
5557 fields.shift_remove("_meta");
5558}
5559
5560#[cfg(feature = "schemars")]
5561fn other_stop_reason_schema(schema: &mut Schema) {
5562 super::schema_util::reject_known_string_discriminators(
5563 schema,
5564 "stopReason",
5565 KNOWN_STOP_REASONS,
5566 );
5567}
5568
5569#[cfg(feature = "unstable_end_turn_token_usage")]
5575#[serde_as]
5576#[skip_serializing_none]
5577#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5578#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5579#[serde(rename_all = "camelCase")]
5580#[non_exhaustive]
5581pub struct Usage {
5582 pub total_tokens: u64,
5584 pub input_tokens: u64,
5586 pub output_tokens: 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 thought_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_read_tokens: Option<u64>,
5602 #[serde_as(deserialize_as = "DefaultOnError")]
5606 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5607 #[serde(default)]
5608 pub cached_write_tokens: Option<u64>,
5609 #[serde_as(deserialize_as = "DefaultOnError")]
5615 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5616 #[serde(default)]
5617 #[serde(rename = "_meta")]
5618 pub meta: Option<Meta>,
5619}
5620
5621#[cfg(feature = "unstable_end_turn_token_usage")]
5622impl Usage {
5623 #[must_use]
5625 pub fn new(total_tokens: u64, input_tokens: u64, output_tokens: u64) -> Self {
5626 Self {
5627 total_tokens,
5628 input_tokens,
5629 output_tokens,
5630 thought_tokens: None,
5631 cached_read_tokens: None,
5632 cached_write_tokens: None,
5633 meta: None,
5634 }
5635 }
5636
5637 #[must_use]
5639 pub fn thought_tokens(mut self, thought_tokens: impl IntoOption<u64>) -> Self {
5640 self.thought_tokens = thought_tokens.into_option();
5641 self
5642 }
5643
5644 #[must_use]
5646 pub fn cached_read_tokens(mut self, cached_read_tokens: impl IntoOption<u64>) -> Self {
5647 self.cached_read_tokens = cached_read_tokens.into_option();
5648 self
5649 }
5650
5651 #[must_use]
5653 pub fn cached_write_tokens(mut self, cached_write_tokens: impl IntoOption<u64>) -> Self {
5654 self.cached_write_tokens = cached_write_tokens.into_option();
5655 self
5656 }
5657
5658 #[must_use]
5664 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5665 self.meta = meta.into_option();
5666 self
5667 }
5668}
5669
5670#[cfg(feature = "unstable_llm_providers")]
5683#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5684#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5685#[serde(rename_all = "snake_case")]
5686#[non_exhaustive]
5687pub enum LlmProtocol {
5688 Anthropic,
5690 #[serde(rename = "openai")]
5692 OpenAi,
5693 Azure,
5695 Vertex,
5697 Bedrock,
5699 #[serde(untagged)]
5705 Other(String),
5706}
5707
5708#[cfg(feature = "unstable_llm_providers")]
5714#[serde_as]
5715#[skip_serializing_none]
5716#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5717#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5718#[serde(rename_all = "camelCase")]
5719#[non_exhaustive]
5720pub struct ProviderCurrentConfig {
5721 pub api_type: LlmProtocol,
5723 #[cfg_attr(feature = "schemars", schemars(url))]
5725 pub base_url: String,
5726 #[serde_as(deserialize_as = "DefaultOnError")]
5732 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5733 #[serde(default)]
5734 #[serde(rename = "_meta")]
5735 pub meta: Option<Meta>,
5736}
5737
5738#[cfg(feature = "unstable_llm_providers")]
5739impl ProviderCurrentConfig {
5740 #[must_use]
5742 pub fn new(api_type: LlmProtocol, base_url: impl Into<String>) -> Self {
5743 Self {
5744 api_type,
5745 base_url: base_url.into(),
5746 meta: None,
5747 }
5748 }
5749
5750 #[must_use]
5756 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5757 self.meta = meta.into_option();
5758 self
5759 }
5760}
5761
5762#[cfg(feature = "unstable_llm_providers")]
5768#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5769#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
5770#[serde(transparent)]
5771#[from(forward)]
5772#[non_exhaustive]
5773pub struct ProviderId(pub Arc<str>);
5774
5775#[cfg(feature = "unstable_llm_providers")]
5776impl ProviderId {
5777 #[must_use]
5779 pub fn new(id: impl Into<Self>) -> Self {
5780 id.into()
5781 }
5782}
5783
5784#[cfg(feature = "unstable_llm_providers")]
5790#[serde_as]
5791#[skip_serializing_none]
5792#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5793#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5794#[serde(rename_all = "camelCase")]
5795#[non_exhaustive]
5796pub struct ProviderInfo {
5797 pub provider_id: ProviderId,
5799 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
5801 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
5802 pub supported: Vec<LlmProtocol>,
5803 pub required: bool,
5806 #[serde(default)]
5809 pub current: Option<ProviderCurrentConfig>,
5810 #[serde_as(deserialize_as = "DefaultOnError")]
5816 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5817 #[serde(default)]
5818 #[serde(rename = "_meta")]
5819 pub meta: Option<Meta>,
5820}
5821
5822#[cfg(feature = "unstable_llm_providers")]
5823impl ProviderInfo {
5824 #[must_use]
5826 pub fn new(
5827 provider_id: impl Into<ProviderId>,
5828 supported: Vec<LlmProtocol>,
5829 required: bool,
5830 current: impl IntoOption<ProviderCurrentConfig>,
5831 ) -> Self {
5832 Self {
5833 provider_id: provider_id.into(),
5834 supported,
5835 required,
5836 current: current.into_option(),
5837 meta: None,
5838 }
5839 }
5840
5841 #[must_use]
5847 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5848 self.meta = meta.into_option();
5849 self
5850 }
5851}
5852
5853#[cfg(feature = "unstable_llm_providers")]
5854crate::serde_util::default_on_null! {
5855 #[serde_as]
5861 #[skip_serializing_none]
5862 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5863 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
5864 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_LIST_METHOD_NAME)))]
5865 #[serde(rename_all = "camelCase")]
5866 #[non_exhaustive]
5867 pub struct ListProvidersRequest {
5868 #[serde_as(deserialize_as = "DefaultOnError")]
5874 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5875 #[serde(default)]
5876 #[serde(rename = "_meta")]
5877 pub meta: Option<Meta>,
5878 }
5879}
5880
5881#[cfg(feature = "unstable_llm_providers")]
5882impl ListProvidersRequest {
5883 #[must_use]
5885 pub fn new() -> Self {
5886 Self::default()
5887 }
5888
5889 #[must_use]
5895 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5896 self.meta = meta.into_option();
5897 self
5898 }
5899}
5900
5901#[cfg(feature = "unstable_llm_providers")]
5907#[serde_as]
5908#[skip_serializing_none]
5909#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5910#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5911#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_LIST_METHOD_NAME)))]
5912#[serde(rename_all = "camelCase")]
5913#[non_exhaustive]
5914pub struct ListProvidersResponse {
5915 pub providers: Vec<ProviderInfo>,
5917 #[serde_as(deserialize_as = "DefaultOnError")]
5923 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5924 #[serde(default)]
5925 #[serde(rename = "_meta")]
5926 pub meta: Option<Meta>,
5927}
5928
5929#[cfg(feature = "unstable_llm_providers")]
5930impl ListProvidersResponse {
5931 #[must_use]
5933 pub fn new(providers: Vec<ProviderInfo>) -> Self {
5934 Self {
5935 providers,
5936 meta: None,
5937 }
5938 }
5939
5940 #[must_use]
5946 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5947 self.meta = meta.into_option();
5948 self
5949 }
5950}
5951
5952#[cfg(feature = "unstable_llm_providers")]
5960#[serde_as]
5961#[skip_serializing_none]
5962#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5963#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
5964#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_SET_METHOD_NAME)))]
5965#[serde(rename_all = "camelCase")]
5966#[non_exhaustive]
5967pub struct SetProviderRequest {
5968 pub provider_id: ProviderId,
5970 pub api_type: LlmProtocol,
5972 #[cfg_attr(feature = "schemars", schemars(url))]
5974 pub base_url: String,
5975 #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
5978 pub headers: IndexMap<String, String>,
5979 #[serde_as(deserialize_as = "DefaultOnError")]
5985 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5986 #[serde(default)]
5987 #[serde(rename = "_meta")]
5988 pub meta: Option<Meta>,
5989}
5990
5991#[cfg(feature = "unstable_llm_providers")]
5992impl SetProviderRequest {
5993 #[must_use]
5995 pub fn new(
5996 provider_id: impl Into<ProviderId>,
5997 api_type: LlmProtocol,
5998 base_url: impl Into<String>,
5999 ) -> Self {
6000 Self {
6001 provider_id: provider_id.into(),
6002 api_type,
6003 base_url: base_url.into(),
6004 headers: IndexMap::new(),
6005 meta: None,
6006 }
6007 }
6008
6009 #[must_use]
6012 pub fn headers(mut self, headers: IndexMap<String, String>) -> Self {
6013 self.headers = headers;
6014 self
6015 }
6016
6017 #[must_use]
6023 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6024 self.meta = meta.into_option();
6025 self
6026 }
6027}
6028
6029#[cfg(feature = "unstable_llm_providers")]
6030crate::serde_util::default_on_null! {
6031 #[serde_as]
6037 #[skip_serializing_none]
6038 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6039 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
6040 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_SET_METHOD_NAME)))]
6041 #[serde(rename_all = "camelCase")]
6042 #[non_exhaustive]
6043 pub struct SetProviderResponse {
6044 #[serde_as(deserialize_as = "DefaultOnError")]
6050 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6051 #[serde(default)]
6052 #[serde(rename = "_meta")]
6053 pub meta: Option<Meta>,
6054 }
6055}
6056
6057#[cfg(feature = "unstable_llm_providers")]
6058impl SetProviderResponse {
6059 #[must_use]
6061 pub fn new() -> Self {
6062 Self::default()
6063 }
6064
6065 #[must_use]
6071 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6072 self.meta = meta.into_option();
6073 self
6074 }
6075}
6076
6077#[cfg(feature = "unstable_llm_providers")]
6083#[serde_as]
6084#[skip_serializing_none]
6085#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6086#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6087#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_DISABLE_METHOD_NAME)))]
6088#[serde(rename_all = "camelCase")]
6089#[non_exhaustive]
6090pub struct DisableProviderRequest {
6091 pub provider_id: ProviderId,
6093 #[serde_as(deserialize_as = "DefaultOnError")]
6099 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6100 #[serde(default)]
6101 #[serde(rename = "_meta")]
6102 pub meta: Option<Meta>,
6103}
6104
6105#[cfg(feature = "unstable_llm_providers")]
6106impl DisableProviderRequest {
6107 #[must_use]
6109 pub fn new(provider_id: impl Into<ProviderId>) -> Self {
6110 Self {
6111 provider_id: provider_id.into(),
6112 meta: None,
6113 }
6114 }
6115
6116 #[must_use]
6122 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6123 self.meta = meta.into_option();
6124 self
6125 }
6126}
6127
6128#[cfg(feature = "unstable_llm_providers")]
6129crate::serde_util::default_on_null! {
6130 #[serde_as]
6136 #[skip_serializing_none]
6137 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6138 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
6139 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_DISABLE_METHOD_NAME)))]
6140 #[serde(rename_all = "camelCase")]
6141 #[non_exhaustive]
6142 pub struct DisableProviderResponse {
6143 #[serde_as(deserialize_as = "DefaultOnError")]
6149 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6150 #[serde(default)]
6151 #[serde(rename = "_meta")]
6152 pub meta: Option<Meta>,
6153 }
6154}
6155
6156#[cfg(feature = "unstable_llm_providers")]
6157impl DisableProviderResponse {
6158 #[must_use]
6160 pub fn new() -> Self {
6161 Self::default()
6162 }
6163
6164 #[must_use]
6170 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6171 self.meta = meta.into_option();
6172 self
6173 }
6174}
6175
6176#[serde_as]
6185#[skip_serializing_none]
6186#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6187#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6188#[serde(rename_all = "camelCase")]
6189#[non_exhaustive]
6190pub struct AgentCapabilities {
6191 #[serde_as(deserialize_as = "DefaultOnError")]
6199 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6200 #[serde(default)]
6201 pub session: Option<SessionCapabilities>,
6202 #[serde_as(deserialize_as = "DefaultOnError")]
6209 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6210 #[serde(default)]
6211 pub auth: Option<AgentAuthCapabilities>,
6212 #[cfg(feature = "unstable_llm_providers")]
6221 #[serde_as(deserialize_as = "DefaultOnError")]
6222 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6223 #[serde(default)]
6224 pub providers: Option<ProvidersCapabilities>,
6225 #[serde_as(deserialize_as = "DefaultOnError")]
6231 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6232 #[serde(default)]
6233 #[serde(rename = "_meta")]
6234 pub meta: Option<Meta>,
6235}
6236
6237impl AgentCapabilities {
6238 #[must_use]
6240 pub fn new() -> Self {
6241 Self::default()
6242 }
6243
6244 #[must_use]
6252 pub fn session(mut self, session: impl IntoOption<SessionCapabilities>) -> Self {
6253 self.session = session.into_option();
6254 self
6255 }
6256
6257 #[must_use]
6261 pub fn auth(mut self, auth: impl IntoOption<AgentAuthCapabilities>) -> Self {
6262 self.auth = auth.into_option();
6263 self
6264 }
6265
6266 #[cfg(feature = "unstable_llm_providers")]
6272 #[must_use]
6273 pub fn providers(mut self, providers: impl IntoOption<ProvidersCapabilities>) -> Self {
6274 self.providers = providers.into_option();
6275 self
6276 }
6277
6278 #[must_use]
6284 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6285 self.meta = meta.into_option();
6286 self
6287 }
6288}
6289
6290#[cfg(feature = "unstable_llm_providers")]
6298#[serde_as]
6299#[skip_serializing_none]
6300#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6301#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6302#[non_exhaustive]
6303pub struct ProvidersCapabilities {
6304 #[serde_as(deserialize_as = "DefaultOnError")]
6310 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6311 #[serde(default)]
6312 #[serde(rename = "_meta")]
6313 pub meta: Option<Meta>,
6314}
6315
6316#[cfg(feature = "unstable_llm_providers")]
6317impl ProvidersCapabilities {
6318 #[must_use]
6320 pub fn new() -> Self {
6321 Self::default()
6322 }
6323
6324 #[must_use]
6330 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6331 self.meta = meta.into_option();
6332 self
6333 }
6334}
6335
6336#[serde_as]
6348#[skip_serializing_none]
6349#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6350#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6351#[serde(rename_all = "camelCase")]
6352#[non_exhaustive]
6353pub struct SessionCapabilities {
6354 #[serde_as(deserialize_as = "DefaultOnError")]
6360 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6361 #[serde(default)]
6362 pub prompt: Option<PromptCapabilities>,
6363 #[serde_as(deserialize_as = "DefaultOnError")]
6368 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6369 #[serde(default)]
6370 pub mcp: Option<McpCapabilities>,
6371 #[serde_as(deserialize_as = "DefaultOnError")]
6376 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6377 #[serde(default)]
6378 pub delete: Option<SessionDeleteCapabilities>,
6379 #[serde_as(deserialize_as = "DefaultOnError")]
6388 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6389 #[serde(default)]
6390 pub additional_directories: Option<SessionAdditionalDirectoriesCapabilities>,
6391 #[serde_as(deserialize_as = "DefaultOnError")]
6396 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6397 #[serde(default)]
6398 pub system_prompt: Option<SessionSystemPromptCapabilities>,
6399 #[cfg(feature = "unstable_session_fork")]
6408 #[serde_as(deserialize_as = "DefaultOnError")]
6409 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6410 #[serde(default)]
6411 pub fork: Option<SessionForkCapabilities>,
6412 #[cfg(feature = "unstable_session_archive")]
6422 #[serde_as(deserialize_as = "DefaultOnError")]
6423 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6424 #[serde(default)]
6425 pub archive: Option<SessionArchiveCapabilities>,
6426 #[cfg(feature = "unstable_session_status")]
6435 #[serde_as(deserialize_as = "DefaultOnError")]
6436 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6437 #[serde(default)]
6438 pub status: Option<SessionStatusCapabilities>,
6439 #[cfg(feature = "unstable_session_options")]
6449 #[serde_as(deserialize_as = "DefaultOnError")]
6450 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6451 #[serde(default)]
6452 pub options: Option<SessionOptionsCapabilities>,
6453 #[cfg(feature = "unstable_session_set_title")]
6465 #[serde_as(deserialize_as = "DefaultOnError")]
6466 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6467 #[serde(default)]
6468 pub title: Option<SessionTitleCapabilities>,
6469 #[serde_as(deserialize_as = "DefaultOnError")]
6475 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6476 #[serde(default)]
6477 #[serde(rename = "_meta")]
6478 pub meta: Option<Meta>,
6479}
6480
6481impl SessionCapabilities {
6482 #[must_use]
6484 pub fn new() -> Self {
6485 Self::default()
6486 }
6487
6488 #[must_use]
6494 pub fn prompt(mut self, prompt: impl IntoOption<PromptCapabilities>) -> Self {
6495 self.prompt = prompt.into_option();
6496 self
6497 }
6498
6499 #[must_use]
6504 pub fn mcp(mut self, mcp: impl IntoOption<McpCapabilities>) -> Self {
6505 self.mcp = mcp.into_option();
6506 self
6507 }
6508
6509 #[must_use]
6514 pub fn delete(mut self, delete: impl IntoOption<SessionDeleteCapabilities>) -> Self {
6515 self.delete = delete.into_option();
6516 self
6517 }
6518
6519 #[must_use]
6528 pub fn additional_directories(
6529 mut self,
6530 additional_directories: impl IntoOption<SessionAdditionalDirectoriesCapabilities>,
6531 ) -> Self {
6532 self.additional_directories = additional_directories.into_option();
6533 self
6534 }
6535
6536 #[must_use]
6541 pub fn system_prompt(
6542 mut self,
6543 system_prompt: impl IntoOption<SessionSystemPromptCapabilities>,
6544 ) -> Self {
6545 self.system_prompt = system_prompt.into_option();
6546 self
6547 }
6548
6549 #[cfg(feature = "unstable_session_fork")]
6550 #[must_use]
6555 pub fn fork(mut self, fork: impl IntoOption<SessionForkCapabilities>) -> Self {
6556 self.fork = fork.into_option();
6557 self
6558 }
6559
6560 #[cfg(feature = "unstable_session_archive")]
6570 #[must_use]
6571 pub fn archive(mut self, archive: impl IntoOption<SessionArchiveCapabilities>) -> Self {
6572 self.archive = archive.into_option();
6573 self
6574 }
6575
6576 #[cfg(feature = "unstable_session_status")]
6585 #[must_use]
6586 pub fn status(mut self, status: impl IntoOption<SessionStatusCapabilities>) -> Self {
6587 self.status = status.into_option();
6588 self
6589 }
6590
6591 #[cfg(feature = "unstable_session_options")]
6601 #[must_use]
6602 pub fn options(mut self, options: impl IntoOption<SessionOptionsCapabilities>) -> Self {
6603 self.options = options.into_option();
6604 self
6605 }
6606
6607 #[cfg(feature = "unstable_session_set_title")]
6619 #[must_use]
6620 pub fn title(mut self, title: impl IntoOption<SessionTitleCapabilities>) -> Self {
6621 self.title = title.into_option();
6622 self
6623 }
6624
6625 #[must_use]
6631 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6632 self.meta = meta.into_option();
6633 self
6634 }
6635}
6636
6637#[serde_as]
6641#[skip_serializing_none]
6642#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6643#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6644#[non_exhaustive]
6645pub struct SessionDeleteCapabilities {
6646 #[serde_as(deserialize_as = "DefaultOnError")]
6652 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6653 #[serde(default)]
6654 #[serde(rename = "_meta")]
6655 pub meta: Option<Meta>,
6656}
6657
6658impl SessionDeleteCapabilities {
6659 #[must_use]
6661 pub fn new() -> Self {
6662 Self::default()
6663 }
6664
6665 #[must_use]
6671 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6672 self.meta = meta.into_option();
6673 self
6674 }
6675}
6676
6677#[serde_as]
6684#[skip_serializing_none]
6685#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6686#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6687#[non_exhaustive]
6688pub struct SessionAdditionalDirectoriesCapabilities {
6689 #[serde_as(deserialize_as = "DefaultOnError")]
6695 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6696 #[serde(default)]
6697 #[serde(rename = "_meta")]
6698 pub meta: Option<Meta>,
6699}
6700
6701impl SessionAdditionalDirectoriesCapabilities {
6702 #[must_use]
6704 pub fn new() -> Self {
6705 Self::default()
6706 }
6707
6708 #[must_use]
6714 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6715 self.meta = meta.into_option();
6716 self
6717 }
6718}
6719
6720#[serde_as]
6725#[skip_serializing_none]
6726#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6727#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6728#[serde(rename_all = "camelCase")]
6729#[non_exhaustive]
6730pub struct SessionSystemPromptCapabilities {
6731 #[serde_as(deserialize_as = "DefaultOnError")]
6735 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6736 #[serde(default)]
6737 pub mode: Option<SessionSystemPromptModeCapabilities>,
6738 #[serde_as(deserialize_as = "DefaultOnError")]
6744 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6745 #[serde(default)]
6746 #[serde(rename = "_meta")]
6747 pub meta: Option<Meta>,
6748}
6749
6750impl SessionSystemPromptCapabilities {
6751 #[must_use]
6753 pub fn new() -> Self {
6754 Self::default()
6755 }
6756
6757 #[must_use]
6761 pub fn mode(mut self, mode: impl IntoOption<SessionSystemPromptModeCapabilities>) -> Self {
6762 self.mode = mode.into_option();
6763 self
6764 }
6765
6766 #[must_use]
6772 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6773 self.meta = meta.into_option();
6774 self
6775 }
6776}
6777
6778#[serde_as]
6783#[skip_serializing_none]
6784#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6785#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6786#[serde(rename_all = "camelCase")]
6787#[non_exhaustive]
6788pub struct SessionSystemPromptModeCapabilities {
6789 #[serde_as(deserialize_as = "DefaultOnError")]
6795 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6796 #[serde(default, rename = "override")]
6797 pub override_: Option<SessionSystemPromptOverrideCapabilities>,
6798 #[serde_as(deserialize_as = "DefaultOnError")]
6804 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6805 #[serde(default)]
6806 #[serde(rename = "_meta")]
6807 pub meta: Option<Meta>,
6808}
6809
6810impl SessionSystemPromptModeCapabilities {
6811 #[must_use]
6813 pub fn new() -> Self {
6814 Self::default()
6815 }
6816
6817 #[must_use]
6823 pub fn override_(
6824 mut self,
6825 override_: impl IntoOption<SessionSystemPromptOverrideCapabilities>,
6826 ) -> Self {
6827 self.override_ = override_.into_option();
6828 self
6829 }
6830
6831 #[must_use]
6837 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6838 self.meta = meta.into_option();
6839 self
6840 }
6841}
6842
6843#[serde_as]
6848#[skip_serializing_none]
6849#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6850#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6851#[non_exhaustive]
6852pub struct SessionSystemPromptOverrideCapabilities {
6853 #[serde_as(deserialize_as = "DefaultOnError")]
6859 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6860 #[serde(default)]
6861 #[serde(rename = "_meta")]
6862 pub meta: Option<Meta>,
6863}
6864
6865impl SessionSystemPromptOverrideCapabilities {
6866 #[must_use]
6868 pub fn new() -> Self {
6869 Self::default()
6870 }
6871
6872 #[must_use]
6878 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6879 self.meta = meta.into_option();
6880 self
6881 }
6882}
6883
6884#[cfg(feature = "unstable_session_fork")]
6892#[serde_as]
6893#[skip_serializing_none]
6894#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6895#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6896#[non_exhaustive]
6897pub struct SessionForkCapabilities {
6898 #[serde_as(deserialize_as = "DefaultOnError")]
6904 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6905 #[serde(default)]
6906 #[serde(rename = "_meta")]
6907 pub meta: Option<Meta>,
6908}
6909
6910#[cfg(feature = "unstable_session_fork")]
6911impl SessionForkCapabilities {
6912 #[must_use]
6914 pub fn new() -> Self {
6915 Self::default()
6916 }
6917
6918 #[must_use]
6924 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6925 self.meta = meta.into_option();
6926 self
6927 }
6928}
6929
6930#[cfg(feature = "unstable_session_archive")]
6939#[serde_as]
6940#[skip_serializing_none]
6941#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6942#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6943#[non_exhaustive]
6944pub struct SessionArchiveCapabilities {
6945 #[serde_as(deserialize_as = "DefaultOnError")]
6951 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6952 #[serde(default)]
6953 #[serde(rename = "_meta")]
6954 pub meta: Option<Meta>,
6955}
6956
6957#[cfg(feature = "unstable_session_archive")]
6958impl SessionArchiveCapabilities {
6959 #[must_use]
6961 pub fn new() -> Self {
6962 Self::default()
6963 }
6964
6965 #[must_use]
6971 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6972 self.meta = meta.into_option();
6973 self
6974 }
6975}
6976
6977#[cfg(feature = "unstable_session_status")]
6985#[serde_as]
6986#[skip_serializing_none]
6987#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6988#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6989#[non_exhaustive]
6990pub struct SessionStatusCapabilities {
6991 #[serde_as(deserialize_as = "DefaultOnError")]
6997 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6998 #[serde(default)]
6999 #[serde(rename = "_meta")]
7000 pub meta: Option<Meta>,
7001}
7002
7003#[cfg(feature = "unstable_session_status")]
7004impl SessionStatusCapabilities {
7005 #[must_use]
7007 pub fn new() -> Self {
7008 Self::default()
7009 }
7010
7011 #[must_use]
7017 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7018 self.meta = meta.into_option();
7019 self
7020 }
7021}
7022
7023#[cfg(feature = "unstable_session_options")]
7032#[serde_as]
7033#[skip_serializing_none]
7034#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7035#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7036#[non_exhaustive]
7037pub struct SessionOptionsCapabilities {
7038 #[serde_as(deserialize_as = "DefaultOnError")]
7044 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7045 #[serde(default)]
7046 #[serde(rename = "_meta")]
7047 pub meta: Option<Meta>,
7048}
7049
7050#[cfg(feature = "unstable_session_options")]
7051impl SessionOptionsCapabilities {
7052 #[must_use]
7054 pub fn new() -> Self {
7055 Self::default()
7056 }
7057
7058 #[must_use]
7064 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7065 self.meta = meta.into_option();
7066 self
7067 }
7068}
7069
7070#[cfg(feature = "unstable_session_set_title")]
7079#[serde_as]
7080#[skip_serializing_none]
7081#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7082#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7083#[non_exhaustive]
7084pub struct SessionTitleCapabilities {
7085 #[serde_as(deserialize_as = "DefaultOnError")]
7091 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7092 #[serde(default)]
7093 #[serde(rename = "_meta")]
7094 pub meta: Option<Meta>,
7095}
7096
7097#[cfg(feature = "unstable_session_set_title")]
7098impl SessionTitleCapabilities {
7099 #[must_use]
7101 pub fn new() -> Self {
7102 Self::default()
7103 }
7104
7105 #[must_use]
7111 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7112 self.meta = meta.into_option();
7113 self
7114 }
7115}
7116
7117#[serde_as]
7130#[skip_serializing_none]
7131#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7132#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7133#[serde(rename_all = "camelCase")]
7134#[non_exhaustive]
7135pub struct PromptCapabilities {
7136 #[serde_as(deserialize_as = "DefaultOnError")]
7141 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7142 #[serde(default)]
7143 pub image: Option<PromptImageCapabilities>,
7144 #[serde_as(deserialize_as = "DefaultOnError")]
7149 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7150 #[serde(default)]
7151 pub audio: Option<PromptAudioCapabilities>,
7152 #[serde_as(deserialize_as = "DefaultOnError")]
7160 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7161 #[serde(default)]
7162 pub embedded_context: Option<PromptEmbeddedContextCapabilities>,
7163 #[cfg(feature = "unstable_agent_skills")]
7173 #[serde_as(deserialize_as = "DefaultOnError")]
7174 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7175 #[serde(default)]
7176 pub skill: Option<PromptSkillCapabilities>,
7177 #[serde_as(deserialize_as = "DefaultOnError")]
7183 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7184 #[serde(default)]
7185 #[serde(rename = "_meta")]
7186 pub meta: Option<Meta>,
7187}
7188
7189impl PromptCapabilities {
7190 #[must_use]
7192 pub fn new() -> Self {
7193 Self::default()
7194 }
7195
7196 #[must_use]
7201 pub fn image(mut self, image: impl IntoOption<PromptImageCapabilities>) -> Self {
7202 self.image = image.into_option();
7203 self
7204 }
7205
7206 #[must_use]
7211 pub fn audio(mut self, audio: impl IntoOption<PromptAudioCapabilities>) -> Self {
7212 self.audio = audio.into_option();
7213 self
7214 }
7215
7216 #[must_use]
7224 pub fn embedded_context(
7225 mut self,
7226 embedded_context: impl IntoOption<PromptEmbeddedContextCapabilities>,
7227 ) -> Self {
7228 self.embedded_context = embedded_context.into_option();
7229 self
7230 }
7231
7232 #[cfg(feature = "unstable_agent_skills")]
7241 #[must_use]
7242 pub fn skill(mut self, skill: impl IntoOption<PromptSkillCapabilities>) -> Self {
7243 self.skill = skill.into_option();
7244 self
7245 }
7246
7247 #[must_use]
7253 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7254 self.meta = meta.into_option();
7255 self
7256 }
7257}
7258
7259#[serde_as]
7263#[skip_serializing_none]
7264#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7265#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7266#[non_exhaustive]
7267pub struct PromptImageCapabilities {
7268 #[serde_as(deserialize_as = "DefaultOnError")]
7274 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7275 #[serde(default)]
7276 #[serde(rename = "_meta")]
7277 pub meta: Option<Meta>,
7278}
7279
7280impl PromptImageCapabilities {
7281 #[must_use]
7283 pub fn new() -> Self {
7284 Self::default()
7285 }
7286
7287 #[must_use]
7293 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7294 self.meta = meta.into_option();
7295 self
7296 }
7297}
7298
7299#[serde_as]
7303#[skip_serializing_none]
7304#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7305#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7306#[non_exhaustive]
7307pub struct PromptAudioCapabilities {
7308 #[serde_as(deserialize_as = "DefaultOnError")]
7314 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7315 #[serde(default)]
7316 #[serde(rename = "_meta")]
7317 pub meta: Option<Meta>,
7318}
7319
7320impl PromptAudioCapabilities {
7321 #[must_use]
7323 pub fn new() -> Self {
7324 Self::default()
7325 }
7326
7327 #[must_use]
7333 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7334 self.meta = meta.into_option();
7335 self
7336 }
7337}
7338
7339#[serde_as]
7343#[skip_serializing_none]
7344#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7345#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7346#[non_exhaustive]
7347pub struct PromptEmbeddedContextCapabilities {
7348 #[serde_as(deserialize_as = "DefaultOnError")]
7354 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7355 #[serde(default)]
7356 #[serde(rename = "_meta")]
7357 pub meta: Option<Meta>,
7358}
7359
7360impl PromptEmbeddedContextCapabilities {
7361 #[must_use]
7363 pub fn new() -> Self {
7364 Self::default()
7365 }
7366
7367 #[must_use]
7373 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7374 self.meta = meta.into_option();
7375 self
7376 }
7377}
7378
7379#[cfg(feature = "unstable_agent_skills")]
7388#[serde_as]
7389#[skip_serializing_none]
7390#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7391#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7392#[serde(rename_all = "camelCase")]
7393#[non_exhaustive]
7394pub struct PromptSkillCapabilities {
7395 #[serde_as(deserialize_as = "DefaultOnError")]
7401 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7402 #[serde(default)]
7403 pub inline: Option<PromptSkillInlineCapabilities>,
7404 #[serde_as(deserialize_as = "DefaultOnError")]
7410 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7411 #[serde(default)]
7412 #[serde(rename = "_meta")]
7413 pub meta: Option<Meta>,
7414}
7415
7416#[cfg(feature = "unstable_agent_skills")]
7417impl PromptSkillCapabilities {
7418 #[must_use]
7420 pub fn new() -> Self {
7421 Self::default()
7422 }
7423
7424 #[must_use]
7430 pub fn inline(mut self, inline: impl IntoOption<PromptSkillInlineCapabilities>) -> Self {
7431 self.inline = inline.into_option();
7432 self
7433 }
7434
7435 #[must_use]
7441 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7442 self.meta = meta.into_option();
7443 self
7444 }
7445}
7446
7447#[cfg(feature = "unstable_agent_skills")]
7456#[serde_as]
7457#[skip_serializing_none]
7458#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7459#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7460#[non_exhaustive]
7461pub struct PromptSkillInlineCapabilities {
7462 #[serde_as(deserialize_as = "DefaultOnError")]
7468 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7469 #[serde(default)]
7470 #[serde(rename = "_meta")]
7471 pub meta: Option<Meta>,
7472}
7473
7474#[cfg(feature = "unstable_agent_skills")]
7475impl PromptSkillInlineCapabilities {
7476 #[must_use]
7478 pub fn new() -> Self {
7479 Self::default()
7480 }
7481
7482 #[must_use]
7488 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7489 self.meta = meta.into_option();
7490 self
7491 }
7492}
7493
7494#[serde_as]
7496#[skip_serializing_none]
7497#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7498#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7499#[serde(rename_all = "camelCase")]
7500#[non_exhaustive]
7501pub struct McpCapabilities {
7502 #[serde_as(deserialize_as = "DefaultOnError")]
7507 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7508 #[serde(default)]
7509 pub stdio: Option<McpStdioCapabilities>,
7510 #[serde_as(deserialize_as = "DefaultOnError")]
7515 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7516 #[serde(default)]
7517 pub http: Option<McpHttpCapabilities>,
7518 #[cfg(feature = "unstable_mcp_over_acp")]
7527 #[serde_as(deserialize_as = "DefaultOnError")]
7528 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7529 #[serde(default)]
7530 pub acp: Option<McpAcpCapabilities>,
7531 #[serde_as(deserialize_as = "DefaultOnError")]
7537 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7538 #[serde(default)]
7539 #[serde(rename = "_meta")]
7540 pub meta: Option<Meta>,
7541}
7542
7543impl McpCapabilities {
7544 #[must_use]
7546 pub fn new() -> Self {
7547 Self::default()
7548 }
7549
7550 #[must_use]
7555 pub fn stdio(mut self, stdio: impl IntoOption<McpStdioCapabilities>) -> Self {
7556 self.stdio = stdio.into_option();
7557 self
7558 }
7559
7560 #[must_use]
7565 pub fn http(mut self, http: impl IntoOption<McpHttpCapabilities>) -> Self {
7566 self.http = http.into_option();
7567 self
7568 }
7569
7570 #[cfg(feature = "unstable_mcp_over_acp")]
7576 #[must_use]
7580 pub fn acp(mut self, acp: impl IntoOption<McpAcpCapabilities>) -> Self {
7581 self.acp = acp.into_option();
7582 self
7583 }
7584
7585 #[must_use]
7591 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7592 self.meta = meta.into_option();
7593 self
7594 }
7595}
7596
7597#[serde_as]
7601#[skip_serializing_none]
7602#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7603#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7604#[non_exhaustive]
7605pub struct McpStdioCapabilities {
7606 #[serde_as(deserialize_as = "DefaultOnError")]
7612 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7613 #[serde(default)]
7614 #[serde(rename = "_meta")]
7615 pub meta: Option<Meta>,
7616}
7617
7618impl McpStdioCapabilities {
7619 #[must_use]
7621 pub fn new() -> Self {
7622 Self::default()
7623 }
7624
7625 #[must_use]
7631 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7632 self.meta = meta.into_option();
7633 self
7634 }
7635}
7636
7637#[serde_as]
7641#[skip_serializing_none]
7642#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7643#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7644#[non_exhaustive]
7645pub struct McpHttpCapabilities {
7646 #[serde_as(deserialize_as = "DefaultOnError")]
7652 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7653 #[serde(default)]
7654 #[serde(rename = "_meta")]
7655 pub meta: Option<Meta>,
7656}
7657
7658impl McpHttpCapabilities {
7659 #[must_use]
7661 pub fn new() -> Self {
7662 Self::default()
7663 }
7664
7665 #[must_use]
7671 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7672 self.meta = meta.into_option();
7673 self
7674 }
7675}
7676
7677#[cfg(feature = "unstable_mcp_over_acp")]
7685#[serde_as]
7686#[skip_serializing_none]
7687#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7688#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7689#[non_exhaustive]
7690pub struct McpAcpCapabilities {
7691 #[serde_as(deserialize_as = "DefaultOnError")]
7697 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7698 #[serde(default)]
7699 #[serde(rename = "_meta")]
7700 pub meta: Option<Meta>,
7701}
7702
7703#[cfg(feature = "unstable_mcp_over_acp")]
7704impl McpAcpCapabilities {
7705 #[must_use]
7707 pub fn new() -> Self {
7708 Self::default()
7709 }
7710
7711 #[must_use]
7717 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7718 self.meta = meta.into_option();
7719 self
7720 }
7721}
7722
7723#[serde_as]
7728#[skip_serializing_none]
7729#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7730#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7731#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CANCEL_METHOD_NAME)))]
7732#[serde(rename_all = "camelCase")]
7733#[non_exhaustive]
7734pub struct CancelSessionNotification {
7735 pub session_id: SessionId,
7737 #[serde_as(deserialize_as = "DefaultOnError")]
7743 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7744 #[serde(default)]
7745 #[serde(rename = "_meta")]
7746 pub meta: Option<Meta>,
7747}
7748
7749impl CancelSessionNotification {
7750 #[must_use]
7752 pub fn new(session_id: impl Into<SessionId>) -> Self {
7753 Self {
7754 session_id: session_id.into(),
7755 meta: None,
7756 }
7757 }
7758
7759 #[must_use]
7765 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7766 self.meta = meta.into_option();
7767 self
7768 }
7769}
7770
7771#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7777#[non_exhaustive]
7778pub struct AgentMethodNames {
7779 pub initialize: &'static str,
7781 pub auth_login: &'static str,
7783 #[cfg(feature = "unstable_llm_providers")]
7785 pub providers_list: &'static str,
7786 #[cfg(feature = "unstable_llm_providers")]
7788 pub providers_set: &'static str,
7789 #[cfg(feature = "unstable_llm_providers")]
7791 pub providers_disable: &'static str,
7792 pub session_new: &'static str,
7794 pub session_set_config_option: &'static str,
7796 pub session_prompt: &'static str,
7798 pub session_cancel: &'static str,
7800 #[cfg(feature = "unstable_mcp_over_acp")]
7802 pub mcp_message: &'static str,
7803 pub session_list: &'static str,
7805 pub session_delete: &'static str,
7807 #[cfg(feature = "unstable_session_fork")]
7809 pub session_fork: &'static str,
7810 #[cfg(feature = "unstable_session_archive")]
7812 pub session_archive: &'static str,
7813 #[cfg(feature = "unstable_session_archive")]
7815 pub session_unarchive: &'static str,
7816 #[cfg(feature = "unstable_session_status")]
7818 pub session_status: &'static str,
7819 #[cfg(feature = "unstable_session_options")]
7821 pub session_options: &'static str,
7822 #[cfg(feature = "unstable_session_set_title")]
7824 pub session_set_title: &'static str,
7825 pub session_resume: &'static str,
7827 pub session_close: &'static str,
7829 pub tool_call_cancel: &'static str,
7831 pub terminal_cancel: &'static str,
7833 pub auth_logout: &'static str,
7835 #[cfg(feature = "unstable_auth_status")]
7837 pub auth_status: &'static str,
7838}
7839
7840pub const AGENT_METHOD_NAMES: AgentMethodNames = AgentMethodNames {
7842 initialize: INITIALIZE_METHOD_NAME,
7843 auth_login: AUTH_LOGIN_METHOD_NAME,
7844 #[cfg(feature = "unstable_llm_providers")]
7845 providers_list: PROVIDERS_LIST_METHOD_NAME,
7846 #[cfg(feature = "unstable_llm_providers")]
7847 providers_set: PROVIDERS_SET_METHOD_NAME,
7848 #[cfg(feature = "unstable_llm_providers")]
7849 providers_disable: PROVIDERS_DISABLE_METHOD_NAME,
7850 session_new: SESSION_NEW_METHOD_NAME,
7851 session_set_config_option: SESSION_SET_CONFIG_OPTION_METHOD_NAME,
7852 session_prompt: SESSION_PROMPT_METHOD_NAME,
7853 session_cancel: SESSION_CANCEL_METHOD_NAME,
7854 #[cfg(feature = "unstable_mcp_over_acp")]
7855 mcp_message: MCP_MESSAGE_METHOD_NAME,
7856 session_list: SESSION_LIST_METHOD_NAME,
7857 session_delete: SESSION_DELETE_METHOD_NAME,
7858 #[cfg(feature = "unstable_session_fork")]
7859 session_fork: SESSION_FORK_METHOD_NAME,
7860 #[cfg(feature = "unstable_session_archive")]
7861 session_archive: SESSION_ARCHIVE_METHOD_NAME,
7862 #[cfg(feature = "unstable_session_archive")]
7863 session_unarchive: SESSION_UNARCHIVE_METHOD_NAME,
7864 #[cfg(feature = "unstable_session_status")]
7865 session_status: SESSION_STATUS_METHOD_NAME,
7866 #[cfg(feature = "unstable_session_options")]
7867 session_options: SESSION_OPTIONS_METHOD_NAME,
7868 #[cfg(feature = "unstable_session_set_title")]
7869 session_set_title: SESSION_SET_TITLE_METHOD_NAME,
7870 session_resume: SESSION_RESUME_METHOD_NAME,
7871 session_close: SESSION_CLOSE_METHOD_NAME,
7872 tool_call_cancel: TOOL_CALL_CANCEL_METHOD_NAME,
7873 terminal_cancel: TERMINAL_CANCEL_METHOD_NAME,
7874 auth_logout: AUTH_LOGOUT_METHOD_NAME,
7875 #[cfg(feature = "unstable_auth_status")]
7876 auth_status: AUTH_STATUS_METHOD_NAME,
7877};
7878
7879pub(crate) const INITIALIZE_METHOD_NAME: &str = "initialize";
7881pub(crate) const AUTH_LOGIN_METHOD_NAME: &str = "auth/login";
7883#[cfg(feature = "unstable_llm_providers")]
7885pub(crate) const PROVIDERS_LIST_METHOD_NAME: &str = "providers/list";
7886#[cfg(feature = "unstable_llm_providers")]
7888pub(crate) const PROVIDERS_SET_METHOD_NAME: &str = "providers/set";
7889#[cfg(feature = "unstable_llm_providers")]
7891pub(crate) const PROVIDERS_DISABLE_METHOD_NAME: &str = "providers/disable";
7892pub(crate) const SESSION_NEW_METHOD_NAME: &str = "session/new";
7894pub(crate) const SESSION_SET_CONFIG_OPTION_METHOD_NAME: &str = "session/set_config_option";
7896pub(crate) const SESSION_PROMPT_METHOD_NAME: &str = "session/prompt";
7898pub(crate) const SESSION_CANCEL_METHOD_NAME: &str = "session/cancel";
7900pub(crate) const SESSION_LIST_METHOD_NAME: &str = "session/list";
7902pub(crate) const SESSION_DELETE_METHOD_NAME: &str = "session/delete";
7904#[cfg(feature = "unstable_session_fork")]
7906pub(crate) const SESSION_FORK_METHOD_NAME: &str = "session/fork";
7907#[cfg(feature = "unstable_session_archive")]
7909pub(crate) const SESSION_ARCHIVE_METHOD_NAME: &str = "session/archive";
7910#[cfg(feature = "unstable_session_archive")]
7912pub(crate) const SESSION_UNARCHIVE_METHOD_NAME: &str = "session/unarchive";
7913#[cfg(feature = "unstable_session_status")]
7915pub(crate) const SESSION_STATUS_METHOD_NAME: &str = "session/status";
7916#[cfg(feature = "unstable_session_options")]
7918pub(crate) const SESSION_OPTIONS_METHOD_NAME: &str = "session/options";
7919#[cfg(feature = "unstable_session_set_title")]
7921pub(crate) const SESSION_SET_TITLE_METHOD_NAME: &str = "session/set_title";
7922pub(crate) const SESSION_RESUME_METHOD_NAME: &str = "session/resume";
7924pub(crate) const SESSION_CLOSE_METHOD_NAME: &str = "session/close";
7926pub(crate) const TOOL_CALL_CANCEL_METHOD_NAME: &str = "tool_call/cancel";
7928pub(crate) const TERMINAL_CANCEL_METHOD_NAME: &str = "terminal/cancel";
7930pub(crate) const AUTH_LOGOUT_METHOD_NAME: &str = "auth/logout";
7932#[cfg(feature = "unstable_auth_status")]
7934pub(crate) const AUTH_STATUS_METHOD_NAME: &str = "auth/status";
7935
7936#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7943#[derive(Clone, Debug, Serialize, Deserialize)]
7944#[serde(untagged)]
7945#[cfg_attr(feature = "schemars", schemars(inline))]
7946#[non_exhaustive]
7947pub enum ClientRequest {
7948 InitializeRequest(Box<InitializeRequest>),
7962 LoginAuthRequest(Box<LoginAuthRequest>),
7977 #[cfg(feature = "unstable_llm_providers")]
7983 ListProvidersRequest(Box<ListProvidersRequest>),
7984 #[cfg(feature = "unstable_llm_providers")]
7990 SetProviderRequest(Box<SetProviderRequest>),
7991 #[cfg(feature = "unstable_llm_providers")]
7997 DisableProviderRequest(Box<DisableProviderRequest>),
7998 LogoutAuthRequest(Box<LogoutAuthRequest>),
8008 #[cfg(feature = "unstable_auth_status")]
8017 AuthStatusRequest(Box<AuthStatusRequest>),
8018 NewSessionRequest(Box<NewSessionRequest>),
8031 ListSessionsRequest(Box<ListSessionsRequest>),
8035 DeleteSessionRequest(Box<DeleteSessionRequest>),
8039 #[cfg(feature = "unstable_session_fork")]
8040 ForkSessionRequest(Box<ForkSessionRequest>),
8056 #[cfg(feature = "unstable_session_archive")]
8057 ArchiveSessionRequest(Box<ArchiveSessionRequest>),
8065 #[cfg(feature = "unstable_session_archive")]
8066 UnarchiveSessionRequest(Box<UnarchiveSessionRequest>),
8074 #[cfg(feature = "unstable_session_status")]
8075 SessionStatusRequest(Box<SessionStatusRequest>),
8083 #[cfg(feature = "unstable_session_options")]
8084 SessionOptionsRequest(Box<SessionOptionsRequest>),
8092 #[cfg(feature = "unstable_session_set_title")]
8093 SetSessionTitleRequest(Box<SetSessionTitleRequest>),
8104 ResumeSessionRequest(Box<ResumeSessionRequest>),
8110 CloseSessionRequest(Box<CloseSessionRequest>),
8115 CancelToolCallRequest(Box<CancelToolCallRequest>),
8121 CancelTerminalRequest(Box<CancelTerminalRequest>),
8127 SetSessionConfigOptionRequest(Box<SetSessionConfigOptionRequest>),
8129 PromptRequest(Box<PromptRequest>),
8151 ExtMethodRequest(Box<ExtRequest>),
8157}
8158
8159impl_request_dispatch! {
8160 ClientRequest => AgentResponse {
8161 InitializeRequest => InitializeResponse: AGENT_METHOD_NAMES.initialize,
8162 LoginAuthRequest => LoginAuthResponse: AGENT_METHOD_NAMES.auth_login,
8163 #[cfg(feature = "unstable_llm_providers")]
8164 ListProvidersRequest => ListProvidersResponse: AGENT_METHOD_NAMES.providers_list,
8165 #[cfg(feature = "unstable_llm_providers")]
8166 SetProviderRequest => SetProviderResponse: AGENT_METHOD_NAMES.providers_set,
8167 #[cfg(feature = "unstable_llm_providers")]
8168 DisableProviderRequest => DisableProviderResponse: AGENT_METHOD_NAMES.providers_disable,
8169 LogoutAuthRequest => LogoutAuthResponse: AGENT_METHOD_NAMES.auth_logout,
8170 #[cfg(feature = "unstable_auth_status")]
8171 AuthStatusRequest => AuthStatusResponse: AGENT_METHOD_NAMES.auth_status,
8172 NewSessionRequest => NewSessionResponse: AGENT_METHOD_NAMES.session_new,
8173 ListSessionsRequest => ListSessionsResponse: AGENT_METHOD_NAMES.session_list,
8174 DeleteSessionRequest => DeleteSessionResponse: AGENT_METHOD_NAMES.session_delete,
8175 #[cfg(feature = "unstable_session_fork")]
8176 ForkSessionRequest => ForkSessionResponse: AGENT_METHOD_NAMES.session_fork,
8177 #[cfg(feature = "unstable_session_archive")]
8178 ArchiveSessionRequest => ArchiveSessionResponse: AGENT_METHOD_NAMES.session_archive,
8179 #[cfg(feature = "unstable_session_archive")]
8180 UnarchiveSessionRequest => UnarchiveSessionResponse: AGENT_METHOD_NAMES.session_unarchive,
8181 #[cfg(feature = "unstable_session_status")]
8182 SessionStatusRequest => SessionStatusResponse: AGENT_METHOD_NAMES.session_status,
8183 #[cfg(feature = "unstable_session_options")]
8184 SessionOptionsRequest => SessionOptionsResponse: AGENT_METHOD_NAMES.session_options,
8185 #[cfg(feature = "unstable_session_set_title")]
8186 SetSessionTitleRequest => SetSessionTitleResponse: AGENT_METHOD_NAMES.session_set_title,
8187 ResumeSessionRequest => ResumeSessionResponse: AGENT_METHOD_NAMES.session_resume,
8188 CloseSessionRequest => CloseSessionResponse: AGENT_METHOD_NAMES.session_close,
8189 CancelToolCallRequest => CancelToolCallResponse: AGENT_METHOD_NAMES.tool_call_cancel,
8190 CancelTerminalRequest => CancelTerminalResponse: AGENT_METHOD_NAMES.terminal_cancel,
8191 SetSessionConfigOptionRequest => SetSessionConfigOptionResponse: AGENT_METHOD_NAMES.session_set_config_option,
8192 PromptRequest => PromptResponse: AGENT_METHOD_NAMES.session_prompt,
8193 }
8194 extension ExtMethodRequest(Box<ExtRequest>) => ExtMethodResponse;
8195}
8196
8197#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
8204#[derive(Clone, Debug, Serialize, Deserialize)]
8205#[serde(untagged)]
8206#[cfg_attr(feature = "schemars", schemars(inline))]
8207#[non_exhaustive]
8208pub enum AgentResponse {
8209 InitializeResponse(Box<InitializeResponse>),
8211 LoginAuthResponse(#[serde(default)] Box<LoginAuthResponse>),
8213 #[cfg(feature = "unstable_llm_providers")]
8215 ListProvidersResponse(Box<ListProvidersResponse>),
8216 #[cfg(feature = "unstable_llm_providers")]
8218 SetProviderResponse(#[serde(default)] Box<SetProviderResponse>),
8219 #[cfg(feature = "unstable_llm_providers")]
8221 DisableProviderResponse(#[serde(default)] Box<DisableProviderResponse>),
8222 LogoutAuthResponse(#[serde(default)] Box<LogoutAuthResponse>),
8224 #[cfg(feature = "unstable_auth_status")]
8226 AuthStatusResponse(Box<AuthStatusResponse>),
8227 NewSessionResponse(Box<NewSessionResponse>),
8229 ListSessionsResponse(Box<ListSessionsResponse>),
8231 DeleteSessionResponse(#[serde(default)] Box<DeleteSessionResponse>),
8233 #[cfg(feature = "unstable_session_fork")]
8235 ForkSessionResponse(Box<ForkSessionResponse>),
8236 #[cfg(feature = "unstable_session_archive")]
8238 ArchiveSessionResponse(#[serde(default)] Box<ArchiveSessionResponse>),
8239 #[cfg(feature = "unstable_session_archive")]
8241 UnarchiveSessionResponse(#[serde(default)] Box<UnarchiveSessionResponse>),
8242 #[cfg(feature = "unstable_session_status")]
8244 SessionStatusResponse(Box<SessionStatusResponse>),
8245 #[cfg(feature = "unstable_session_options")]
8247 SessionOptionsResponse(#[serde(default)] Box<SessionOptionsResponse>),
8248 #[cfg(feature = "unstable_session_set_title")]
8250 SetSessionTitleResponse(Box<SetSessionTitleResponse>),
8251 ResumeSessionResponse(#[serde(default)] Box<ResumeSessionResponse>),
8253 CloseSessionResponse(#[serde(default)] Box<CloseSessionResponse>),
8255 CancelToolCallResponse(#[serde(default)] Box<CancelToolCallResponse>),
8257 CancelTerminalResponse(#[serde(default)] Box<CancelTerminalResponse>),
8259 SetSessionConfigOptionResponse(Box<SetSessionConfigOptionResponse>),
8261 PromptResponse(Box<PromptResponse>),
8263 ExtMethodResponse(Box<ExtResponse>),
8265}
8266
8267#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
8274#[derive(Clone, Debug, Serialize, Deserialize)]
8275#[serde(untagged)]
8276#[cfg_attr(feature = "schemars", schemars(inline))]
8277#[non_exhaustive]
8278pub enum ClientNotification {
8279 CancelSessionNotification(Box<CancelSessionNotification>),
8309 #[cfg(feature = "unstable_mcp_over_acp")]
8315 MessageMcpNotification(Box<MessageMcpNotification>),
8316 ExtNotification(Box<ExtNotification>),
8322}
8323
8324impl_message_dispatch! {
8325 ClientNotification {
8326 CancelSessionNotification => AGENT_METHOD_NAMES.session_cancel,
8327 #[cfg(feature = "unstable_mcp_over_acp")]
8328 MessageMcpNotification => AGENT_METHOD_NAMES.mcp_message,
8329 }
8330 extension ExtNotification(Box<ExtNotification>);
8331}
8332
8333#[cfg(test)]
8334mod test_serialization {
8335 use std::path::PathBuf;
8336
8337 use super::*;
8338 use serde_json::json;
8339
8340 fn test_meta() -> Meta {
8341 json!({ "source": "test" }).as_object().unwrap().clone()
8342 }
8343
8344 #[test]
8345 fn list_sessions_cursor_and_session_directories_are_strict() {
8346 for cursor in [json!(null), json!("next")] {
8347 let response = json!({ "sessions": [], "nextCursor": cursor });
8348 serde_json::from_value::<ListSessionsResponse>(response).unwrap();
8349 }
8350 let malformed = json!({ "sessions": [], "nextCursor": 42 });
8351 assert!(serde_json::from_value::<ListSessionsResponse>(malformed).is_err());
8352
8353 let session = |dirs: serde_json::Value| json!({ "sessionId": "s", "cwd": "/w", "additionalDirectories": dirs });
8354 let info: SessionInfo = serde_json::from_value(session(json!(null))).unwrap();
8355 assert_eq!(info.additional_directories, Vec::<AbsolutePath>::new());
8356 for bad in [json!(["/a", 42]), json!("/a")] {
8357 assert!(serde_json::from_value::<SessionInfo>(session(bad)).is_err());
8358 }
8359 let response = json!({ "sessions": [session(json!(["/a", 42]))] });
8361 let response: ListSessionsResponse = serde_json::from_value(response).unwrap();
8362 assert_eq!(response.sessions, Vec::<SessionInfo>::new());
8363 }
8364
8365 #[test]
8366 fn other_fallbacks_preserve_optional_fields_verbatim() {
8367 let valid = json!({ "type": "_custom", "methodId": "m", "name": "M",
8368 "description": "d", "_meta": { "k": 1 } });
8369 let method: AuthMethod = serde_json::from_value(valid.clone()).unwrap();
8370 assert_eq!(method.description(), Some("d"));
8371 assert_eq!(
8372 method.meta(),
8373 Some(&json!({ "k": 1 }).as_object().unwrap().clone())
8374 );
8375 assert_eq!(serde_json::to_value(&method).unwrap(), valid);
8376
8377 let malformed = json!({ "type": "_custom", "methodId": "m", "name": "M",
8379 "description": 42, "_meta": "bad", "extra": true });
8380 let method: AuthMethod = serde_json::from_value(malformed.clone()).unwrap();
8381 assert_eq!(method.description(), None);
8382 assert_eq!(method.meta(), None);
8383 assert_eq!(serde_json::to_value(&method).unwrap(), malformed);
8384
8385 let replay = json!({ "type": "_custom", "_meta": "bad", "cursor": 3 });
8386 let decoded: ReplayFrom = serde_json::from_value(replay.clone()).unwrap();
8387 assert_eq!(serde_json::to_value(&decoded).unwrap(), replay);
8388 }
8389
8390 fn serialized_meta_key_count(value: &impl serde::Serialize) -> usize {
8391 serde_json::to_string(value)
8392 .unwrap()
8393 .matches("\"_meta\"")
8394 .count()
8395 }
8396
8397 #[test]
8398 fn prompt_response_without_metadata_round_trips() {
8399 let response = PromptResponse::new(MessageId::new("message-1"));
8400 let serialized = serde_json::to_value(&response).unwrap();
8401 assert_eq!(serialized, json!({ "messageId": "message-1" }));
8402 assert_eq!(
8403 serde_json::from_value::<PromptResponse>(serialized).unwrap(),
8404 response
8405 );
8406 assert_eq!(
8407 serde_json::from_value::<PromptResponse>(json!({
8408 "messageId": "message-1",
8409 "_meta": null
8410 }))
8411 .unwrap(),
8412 response
8413 );
8414 }
8415
8416 #[test]
8417 fn prompt_response_requires_message_id_and_preserves_metadata_tolerance() {
8418 let response = PromptResponse::new("message-1").meta(test_meta());
8419 let serialized = serde_json::to_value(&response).unwrap();
8420 assert_eq!(
8421 serialized,
8422 json!({
8423 "messageId": "message-1",
8424 "_meta": { "source": "test" }
8425 })
8426 );
8427
8428 let deserialized: PromptResponse = serde_json::from_value(serialized).unwrap();
8429 assert_eq!(deserialized.message_id, MessageId::new("message-1"));
8430 assert_eq!(deserialized.meta, Some(test_meta()));
8431
8432 let malformed_meta: PromptResponse = serde_json::from_value(json!({
8433 "messageId": "message-2",
8434 "_meta": false
8435 }))
8436 .unwrap();
8437 assert_eq!(malformed_meta.message_id, MessageId::new("message-2"));
8438 assert_eq!(malformed_meta.meta, None);
8439
8440 for invalid in [
8441 json!({}),
8442 json!({ "messageId": null }),
8443 json!({ "messageId": 1 }),
8444 json!({ "messageId": false }),
8445 json!({ "messageId": {} }),
8446 json!({ "messageId": [] }),
8447 ] {
8448 assert!(
8449 serde_json::from_value::<PromptResponse>(invalid).is_err(),
8450 "missing, null, and non-string message IDs must be rejected"
8451 );
8452 }
8453 }
8454
8455 #[cfg(feature = "schemars")]
8456 #[test]
8457 fn prompt_response_schema_requires_non_null_string_message_id_reference() {
8458 let schema = serde_json::to_value(schemars::schema_for!(PromptResponse)).unwrap();
8459
8460 assert_eq!(schema["required"], json!(["messageId"]));
8461 assert_eq!(
8462 schema["properties"]["messageId"]["$ref"],
8463 "#/$defs/MessageId"
8464 );
8465 assert_eq!(schema["$defs"]["MessageId"]["type"], "string");
8466 }
8467
8468 #[test]
8469 fn test_initialize_capabilities_default_on_malformed_values() {
8470 let request: InitializeRequest = serde_json::from_value(json!({
8471 "protocolVersion": 2,
8472 "capabilities": false,
8473 "info": {
8474 "name": "client",
8475 "version": "1.0.0"
8476 }
8477 }))
8478 .unwrap();
8479 assert_eq!(request.capabilities, ClientCapabilities::default());
8480
8481 let response: InitializeResponse = serde_json::from_value(json!({
8482 "protocolVersion": 2,
8483 "capabilities": false,
8484 "info": {
8485 "name": "agent",
8486 "version": "1.0.0"
8487 }
8488 }))
8489 .unwrap();
8490 assert_eq!(response.capabilities, AgentCapabilities::default());
8491 }
8492
8493 #[test]
8494 fn test_agent_capabilities_default_on_malformed_values() {
8495 let capabilities: AgentCapabilities = serde_json::from_value(json!({
8496 "session": false,
8497 "auth": false
8498 }))
8499 .unwrap();
8500
8501 assert!(capabilities.session.is_none());
8502 assert_eq!(capabilities.auth, None);
8503 }
8504
8505 #[test]
8506 fn test_mcp_server_stdio_serialization() {
8507 let server = McpServer::Stdio(
8508 McpServerStdio::new("test-server", "/usr/bin/server")
8509 .args(vec!["--port".to_string(), "3000".to_string()])
8510 .env(vec![EnvVariable::new("API_KEY", "secret123")]),
8511 );
8512
8513 let json = serde_json::to_value(&server).unwrap();
8514 assert_eq!(
8515 json,
8516 json!({
8517 "type": "stdio",
8518 "name": "test-server",
8519 "command": "/usr/bin/server",
8520 "args": ["--port", "3000"],
8521 "env": [
8522 {
8523 "name": "API_KEY",
8524 "value": "secret123"
8525 }
8526 ]
8527 })
8528 );
8529
8530 let deserialized: McpServer = serde_json::from_value(json).unwrap();
8531 match deserialized {
8532 McpServer::Stdio(McpServerStdio {
8533 name,
8534 command,
8535 args,
8536 env,
8537 meta: _,
8538 }) => {
8539 assert_eq!(name, "test-server");
8540 assert_eq!(command, AbsolutePath::new("/usr/bin/server"));
8541 assert_eq!(args, vec!["--port", "3000"]);
8542 assert_eq!(env.len(), 1);
8543 assert_eq!(env[0].name, "API_KEY");
8544 assert_eq!(env[0].value, "secret123");
8545 }
8546 _ => panic!("Expected Stdio variant"),
8547 }
8548 }
8549
8550 #[test]
8551 fn test_mcp_server_empty_arrays_are_optional() {
8552 let stdio = McpServer::Stdio(McpServerStdio::new("test-server", "/usr/bin/server"));
8553 assert_eq!(
8554 serde_json::to_value(&stdio).unwrap(),
8555 json!({
8556 "type": "stdio",
8557 "name": "test-server",
8558 "command": "/usr/bin/server"
8559 })
8560 );
8561
8562 let McpServer::Stdio(McpServerStdio { args, env, .. }) =
8563 serde_json::from_value::<McpServer>(json!({
8564 "type": "stdio",
8565 "name": "test-server",
8566 "command": "/usr/bin/server"
8567 }))
8568 .unwrap()
8569 else {
8570 panic!("Expected Stdio variant");
8571 };
8572 assert_eq!(args, Vec::<String>::new());
8573 assert_eq!(env, []);
8574
8575 let http = McpServer::Http(McpServerHttp::new("http-server", "https://api.example.com"));
8576 assert_eq!(
8577 serde_json::to_value(&http).unwrap(),
8578 json!({
8579 "type": "http",
8580 "name": "http-server",
8581 "url": "https://api.example.com"
8582 })
8583 );
8584
8585 let McpServer::Http(McpServerHttp { headers, .. }) =
8586 serde_json::from_value::<McpServer>(json!({
8587 "type": "http",
8588 "name": "http-server",
8589 "url": "https://api.example.com"
8590 }))
8591 .unwrap()
8592 else {
8593 panic!("Expected Http variant");
8594 };
8595 assert_eq!(headers, []);
8596 }
8597
8598 #[test]
8599 fn test_mcp_server_unknown_transport_serialization() {
8600 let json = json!({
8601 "type": "websocket",
8602 "name": "future-server",
8603 "url": "wss://example.com/mcp",
8604 "protocolVersion": "2026-01-01"
8605 });
8606
8607 let deserialized: McpServer = serde_json::from_value(json.clone()).unwrap();
8608 let McpServer::Other(OtherMcpServer { type_, fields }) = &deserialized else {
8609 panic!("Expected Other variant");
8610 };
8611
8612 assert_eq!(type_, "websocket");
8613 assert_eq!(fields["name"], "future-server");
8614 assert_eq!(fields["url"], "wss://example.com/mcp");
8615 assert_eq!(fields["protocolVersion"], "2026-01-01");
8616 assert_eq!(serde_json::to_value(&deserialized).unwrap(), json);
8617 }
8618
8619 #[test]
8620 fn test_mcp_server_stdio_requires_type() {
8621 let result = serde_json::from_value::<McpServer>(json!({
8622 "name": "test-server",
8623 "command": "/usr/bin/server",
8624 "args": [],
8625 "env": []
8626 }));
8627
8628 assert!(result.is_err());
8629 }
8630
8631 #[test]
8632 fn test_mcp_server_unknown_does_not_hide_malformed_known_transport() {
8633 let result = serde_json::from_value::<McpServer>(json!({
8634 "type": "stdio",
8635 "name": "test-server",
8636 "args": [],
8637 "env": []
8638 }));
8639
8640 assert!(result.is_err());
8641 }
8642
8643 #[test]
8644 fn test_mcp_server_http_serialization() {
8645 let server = McpServer::Http(
8646 McpServerHttp::new("http-server", "https://api.example.com").headers(vec![
8647 HttpHeader::new("Authorization", "Bearer token123"),
8648 HttpHeader::new("Content-Type", "application/json"),
8649 ]),
8650 );
8651
8652 let json = serde_json::to_value(&server).unwrap();
8653 assert_eq!(
8654 json,
8655 json!({
8656 "type": "http",
8657 "name": "http-server",
8658 "url": "https://api.example.com",
8659 "headers": [
8660 {
8661 "name": "Authorization",
8662 "value": "Bearer token123"
8663 },
8664 {
8665 "name": "Content-Type",
8666 "value": "application/json"
8667 }
8668 ]
8669 })
8670 );
8671
8672 let deserialized: McpServer = serde_json::from_value(json).unwrap();
8673 match deserialized {
8674 McpServer::Http(McpServerHttp {
8675 name,
8676 url,
8677 headers,
8678 meta: _,
8679 }) => {
8680 assert_eq!(name, "http-server");
8681 assert_eq!(url, "https://api.example.com");
8682 assert_eq!(headers.len(), 2);
8683 assert_eq!(headers[0].name, "Authorization");
8684 assert_eq!(headers[0].value, "Bearer token123");
8685 assert_eq!(headers[1].name, "Content-Type");
8686 assert_eq!(headers[1].value, "application/json");
8687 }
8688 _ => panic!("Expected Http variant"),
8689 }
8690 }
8691
8692 #[cfg(feature = "schemars")]
8693 #[test]
8694 fn mcp_server_http_schema_marks_url_as_uri() {
8695 let schema = serde_json::to_value(schemars::schema_for!(McpServerHttp)).unwrap();
8696
8697 assert_eq!(schema["properties"]["url"]["format"], "uri");
8698 }
8699
8700 #[cfg(feature = "unstable_mcp_over_acp")]
8701 #[test]
8702 fn test_client_mcp_message_method_names() {
8703 use serde_json::json;
8704
8705 assert_eq!(AGENT_METHOD_NAMES.mcp_message, "mcp/message");
8706
8707 let notification =
8708 MessageMcpNotification::new("server-1", "req-1", "notifications/progress");
8709 assert_eq!(
8710 ClientNotification::MessageMcpNotification(Box::new(notification.clone())).method(),
8711 "mcp/message"
8712 );
8713 assert_eq!(
8714 serde_json::to_value(notification).unwrap(),
8715 json!({
8716 "serverId": "server-1",
8717 "requestId": "req-1",
8718 "method": "notifications/progress"
8719 })
8720 );
8721 let notification: MessageMcpNotification = serde_json::from_value(json!({
8722 "serverId": "server-1", "requestId": "req-1", "method": "notifications/progress",
8723 "params": null, "_meta": null
8724 }))
8725 .unwrap();
8726 assert_eq!(notification.params, None);
8727 assert_eq!(notification.meta, None);
8728 for key in ["serverId", "requestId", "method"] {
8729 let mut value = json!({"serverId":"server-1", "requestId":"req-1", "method":"notifications/progress"});
8730 value.as_object_mut().unwrap().remove(key);
8731 assert!(serde_json::from_value::<MessageMcpNotification>(value).is_err());
8732 }
8733 }
8734
8735 #[test]
8736 fn test_auth_method_names() {
8737 assert_eq!(AGENT_METHOD_NAMES.auth_login, "auth/login");
8738 assert_eq!(AGENT_METHOD_NAMES.auth_logout, "auth/logout");
8739
8740 assert_eq!(
8741 ClientRequest::LoginAuthRequest(Box::new(LoginAuthRequest::new("agent-login")))
8742 .method(),
8743 "auth/login"
8744 );
8745 assert_eq!(
8746 ClientRequest::LogoutAuthRequest(Box::new(LogoutAuthRequest::new())).method(),
8747 "auth/logout"
8748 );
8749 }
8750
8751 #[test]
8752 fn test_session_config_option_category_known_variants() {
8753 assert_eq!(
8755 serde_json::to_value(&SessionConfigOptionCategory::Mode).unwrap(),
8756 json!("mode")
8757 );
8758 assert_eq!(
8759 serde_json::to_value(&SessionConfigOptionCategory::Model).unwrap(),
8760 json!("model")
8761 );
8762 assert_eq!(
8763 serde_json::to_value(&SessionConfigOptionCategory::ModelConfig).unwrap(),
8764 json!("model_config")
8765 );
8766 #[cfg(feature = "unstable_speed_config_category")]
8767 assert_eq!(
8768 serde_json::to_value(&SessionConfigOptionCategory::Speed).unwrap(),
8769 json!("speed")
8770 );
8771 assert_eq!(
8772 serde_json::to_value(&SessionConfigOptionCategory::ThoughtLevel).unwrap(),
8773 json!("thought_level")
8774 );
8775
8776 assert_eq!(
8778 serde_json::from_str::<SessionConfigOptionCategory>("\"mode\"").unwrap(),
8779 SessionConfigOptionCategory::Mode
8780 );
8781 assert_eq!(
8782 serde_json::from_str::<SessionConfigOptionCategory>("\"model\"").unwrap(),
8783 SessionConfigOptionCategory::Model
8784 );
8785 assert_eq!(
8786 serde_json::from_str::<SessionConfigOptionCategory>("\"model_config\"").unwrap(),
8787 SessionConfigOptionCategory::ModelConfig
8788 );
8789 #[cfg(feature = "unstable_speed_config_category")]
8790 assert_eq!(
8791 serde_json::from_str::<SessionConfigOptionCategory>("\"speed\"").unwrap(),
8792 SessionConfigOptionCategory::Speed
8793 );
8794 assert_eq!(
8795 serde_json::from_str::<SessionConfigOptionCategory>("\"thought_level\"").unwrap(),
8796 SessionConfigOptionCategory::ThoughtLevel
8797 );
8798 }
8799
8800 #[test]
8801 fn test_session_config_option_category_unknown_variants() {
8802 let unknown: SessionConfigOptionCategory =
8804 serde_json::from_str("\"some_future_category\"").unwrap();
8805 assert_eq!(
8806 unknown,
8807 SessionConfigOptionCategory::Other("some_future_category".to_string())
8808 );
8809
8810 let json = serde_json::to_value(&unknown).unwrap();
8812 assert_eq!(json, json!("some_future_category"));
8813 }
8814
8815 #[cfg(not(feature = "unstable_speed_config_category"))]
8816 #[test]
8817 fn test_session_config_option_speed_is_unknown_without_feature() {
8818 let unknown: SessionConfigOptionCategory = serde_json::from_str("\"speed\"").unwrap();
8819 assert_eq!(
8820 unknown,
8821 SessionConfigOptionCategory::Other("speed".to_string())
8822 );
8823 }
8824
8825 #[test]
8826 fn test_session_config_option_category_custom_categories() {
8827 let custom: SessionConfigOptionCategory =
8829 serde_json::from_str("\"_my_custom_category\"").unwrap();
8830 assert_eq!(
8831 custom,
8832 SessionConfigOptionCategory::Other("_my_custom_category".to_string())
8833 );
8834
8835 let json = serde_json::to_value(&custom).unwrap();
8837 assert_eq!(json, json!("_my_custom_category"));
8838
8839 let deserialized: SessionConfigOptionCategory = serde_json::from_value(json).unwrap();
8841 assert_eq!(
8842 deserialized,
8843 SessionConfigOptionCategory::Other("_my_custom_category".to_string()),
8844 );
8845 }
8846
8847 fn test_config_option() -> SessionConfigOption {
8848 SessionConfigOption::select(
8849 "mode",
8850 "Mode",
8851 "ask",
8852 vec![SessionConfigSelectOption::new("ask", "Ask")],
8853 )
8854 }
8855
8856 #[test]
8857 fn test_session_response_initial_state_default_empty_and_skip_serializing() {
8858 assert_eq!(
8859 serde_json::to_value(NewSessionResponse::new("sess")).unwrap(),
8860 json!({ "sessionId": "sess" })
8861 );
8862 assert_eq!(
8863 serde_json::to_value(ResumeSessionResponse::new()).unwrap(),
8864 json!({})
8865 );
8866 #[cfg(feature = "unstable_session_fork")]
8867 assert_eq!(
8868 serde_json::to_value(ForkSessionResponse::new("fork")).unwrap(),
8869 json!({ "sessionId": "fork" })
8870 );
8871
8872 let json = serde_json::to_value(
8873 NewSessionResponse::new("sess").config_options(vec![test_config_option()]),
8874 )
8875 .unwrap();
8876 assert_eq!(json["configOptions"].as_array().unwrap().len(), 1);
8877 }
8878
8879 #[test]
8880 fn test_session_response_config_options_deserialize_missing_null_and_invalid() {
8881 let missing: NewSessionResponse =
8882 serde_json::from_value(json!({ "sessionId": "sess" })).unwrap();
8883 assert_eq!(missing.config_options, []);
8884
8885 let null: NewSessionResponse = serde_json::from_value(json!({
8886 "sessionId": "sess",
8887 "configOptions": null
8888 }))
8889 .unwrap();
8890 assert_eq!(null.config_options, []);
8891
8892 let wrong_shape: NewSessionResponse = serde_json::from_value(json!({
8893 "sessionId": "sess",
8894 "configOptions": "oops"
8895 }))
8896 .unwrap();
8897 assert_eq!(wrong_shape.config_options, []);
8898
8899 let valid_option = serde_json::to_value(test_config_option()).unwrap();
8900 let mixed: NewSessionResponse = serde_json::from_value(json!({
8901 "sessionId": "sess",
8902 "configOptions": ["oops", valid_option]
8903 }))
8904 .unwrap();
8905 assert_eq!(mixed.config_options.len(), 1);
8906
8907 let resume: ResumeSessionResponse = serde_json::from_value(json!({})).unwrap();
8908 assert_eq!(resume.config_options, []);
8909 #[cfg(feature = "unstable_session_fork")]
8910 {
8911 let fork: ForkSessionResponse =
8912 serde_json::from_value(json!({ "sessionId": "fork" })).unwrap();
8913 assert_eq!(fork.config_options, []);
8914 }
8915 }
8916
8917 #[test]
8918 fn test_session_response_available_commands_roundtrip_with_config_options() {
8919 use super::super::{AvailableCommandInput, Command, TextCommandInput};
8920
8921 let commands = vec![
8922 AvailableCommand::Command(
8923 Command::new("web", "Search the web")
8924 .input(AvailableCommandInput::Text(TextCommandInput::new("Query"))),
8925 ),
8926 AvailableCommand::Command(Command::new("test", "Run project tests")),
8927 ];
8928 let mut expected = json!({
8929 "sessionId": "sess",
8930 "configOptions": [test_config_option()],
8931 "availableCommands": [
8932 {
8933 "type": "command",
8934 "name": "web",
8935 "description": "Search the web",
8936 "input": { "type": "text", "hint": "Query" }
8937 },
8938 { "type": "command", "name": "test", "description": "Run project tests" }
8939 ]
8940 });
8941
8942 let new = NewSessionResponse::new("sess")
8943 .config_options(vec![test_config_option()])
8944 .available_commands(commands.clone());
8945 assert_eq!(serde_json::to_value(&new).unwrap(), expected);
8946 assert_eq!(
8947 serde_json::from_value::<NewSessionResponse>(expected.clone()).unwrap(),
8948 new
8949 );
8950
8951 expected.as_object_mut().unwrap().remove("sessionId");
8952 let resume = ResumeSessionResponse::new()
8953 .config_options(vec![test_config_option()])
8954 .available_commands(commands.clone());
8955 assert_eq!(serde_json::to_value(&resume).unwrap(), expected);
8956 assert_eq!(
8957 serde_json::from_value::<ResumeSessionResponse>(expected.clone()).unwrap(),
8958 resume
8959 );
8960
8961 #[cfg(feature = "unstable_session_fork")]
8962 {
8963 expected["sessionId"] = json!("fork");
8964 let fork = ForkSessionResponse::new("fork")
8965 .config_options(vec![test_config_option()])
8966 .available_commands(commands);
8967 assert_eq!(serde_json::to_value(&fork).unwrap(), expected);
8968 assert_eq!(
8969 serde_json::from_value::<ForkSessionResponse>(expected).unwrap(),
8970 fork
8971 );
8972 }
8973 }
8974
8975 #[test]
8976 fn test_session_response_available_commands_deserialize_missing_null_and_invalid() {
8977 let command =
8978 AvailableCommand::Command(super::super::Command::new("test", "Run project tests"));
8979 let config_options = vec![test_config_option()];
8980
8981 for (commands, expected) in [
8982 (None, vec![]),
8983 (Some(json!(null)), vec![]),
8984 (Some(json!([])), vec![]),
8985 (Some(json!("oops")), vec![]),
8986 (Some(json!({})), vec![]),
8987 (Some(json!([null, {}, { "name": "invalid" }])), vec![]),
8988 (
8989 Some(json!([{ "name": "test", "description": "Run project tests" }])),
8990 vec![],
8991 ),
8992 (
8993 Some(json!([null, command, { "name": "invalid" }])),
8994 vec![command.clone()],
8995 ),
8996 ] {
8997 let mut value = json!({
8998 "sessionId": "sess",
8999 "configOptions": config_options
9000 });
9001 if let Some(commands) = commands {
9002 value["availableCommands"] = commands;
9003 }
9004
9005 let new: NewSessionResponse = serde_json::from_value(value.clone()).unwrap();
9006 assert_eq!(new.available_commands, expected);
9007 assert_eq!(new.config_options, config_options);
9008
9009 #[cfg(feature = "unstable_session_fork")]
9010 {
9011 let fork: ForkSessionResponse = serde_json::from_value(value.clone()).unwrap();
9012 assert_eq!(fork.available_commands, expected);
9013 assert_eq!(fork.config_options, config_options);
9014 }
9015
9016 value.as_object_mut().unwrap().remove("sessionId");
9017 let resume: ResumeSessionResponse = serde_json::from_value(value).unwrap();
9018 assert_eq!(resume.available_commands, expected);
9019 assert_eq!(resume.config_options, config_options);
9020 }
9021
9022 let resume: ResumeSessionResponse = serde_json::from_value(json!(null)).unwrap();
9023 assert_eq!(resume.available_commands, []);
9024 }
9025
9026 #[test]
9027 fn test_resume_session_replay_from_serialization() {
9028 assert_eq!(
9029 serde_json::to_value(ResumeSessionRequest::new(
9030 "sess_abc123",
9031 "/home/user/project"
9032 ))
9033 .unwrap(),
9034 json!({
9035 "sessionId": "sess_abc123",
9036 "cwd": "/home/user/project"
9037 })
9038 );
9039 assert_eq!(
9040 serde_json::to_value(
9041 ResumeSessionRequest::new("sess_abc123", "/home/user/project")
9042 .replay_from(ReplayFrom::from(ReplayFromStart::new()))
9043 )
9044 .unwrap(),
9045 json!({
9046 "sessionId": "sess_abc123",
9047 "cwd": "/home/user/project",
9048 "replayFrom": {
9049 "type": "start"
9050 }
9051 })
9052 );
9053
9054 let replay: ResumeSessionRequest = serde_json::from_value(json!({
9055 "sessionId": "sess_abc123",
9056 "cwd": "/home/user/project",
9057 "replayFrom": {
9058 "type": "start"
9059 }
9060 }))
9061 .unwrap();
9062 assert!(matches!(replay.replay_from, Some(ReplayFrom::Start(_))));
9063
9064 let none: ResumeSessionRequest = serde_json::from_value(json!({
9065 "sessionId": "sess_abc123",
9066 "cwd": "/home/user/project",
9067 "replayFrom": null
9068 }))
9069 .unwrap();
9070 assert!(none.replay_from.is_none());
9071 }
9072
9073 #[test]
9074 fn test_auth_method_agent_serialization() {
9075 let method = AuthMethod::Agent(AuthMethodAgent::new("default-auth", "Default Auth"));
9076
9077 let json = serde_json::to_value(&method).unwrap();
9078 assert_eq!(
9079 json,
9080 json!({
9081 "methodId": "default-auth",
9082 "name": "Default Auth",
9083 "type": "agent"
9084 })
9085 );
9086 assert!(!json.as_object().unwrap().contains_key("description"));
9088
9089 let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9090 match deserialized {
9091 AuthMethod::Agent(AuthMethodAgent {
9092 method_id, name, ..
9093 }) => {
9094 assert_eq!(method_id.0.as_ref(), "default-auth");
9095 assert_eq!(name, "Default Auth");
9096 }
9097 _ => panic!("Expected Agent variant"),
9098 }
9099 }
9100
9101 #[test]
9102 fn test_auth_method_agent_deserialization() {
9103 let json = json!({
9104 "methodId": "agent-auth",
9105 "name": "Agent Auth",
9106 "type": "agent"
9107 });
9108
9109 let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9110 assert!(matches!(deserialized, AuthMethod::Agent(_)));
9111 }
9112
9113 #[test]
9114 fn test_auth_method_agent_requires_type() {
9115 assert!(
9116 serde_json::from_value::<AuthMethod>(json!({
9117 "methodId": "agent-auth",
9118 "name": "Agent Auth"
9119 }))
9120 .is_err()
9121 );
9122 }
9123
9124 #[test]
9125 fn test_auth_method_agent_rejects_null_type() {
9126 assert!(
9127 serde_json::from_value::<AuthMethod>(json!({
9128 "methodId": "agent-auth",
9129 "name": "Agent Auth",
9130 "type": null
9131 }))
9132 .is_err()
9133 );
9134 }
9135
9136 #[test]
9137 fn test_auth_method_unknown_does_not_hide_malformed_agent() {
9138 assert!(
9139 serde_json::from_value::<AuthMethod>(json!({
9140 "methodId": "agent-auth",
9141 "type": "agent"
9142 }))
9143 .is_err()
9144 );
9145 assert!(
9146 serde_json::from_value::<AuthMethod>(json!({
9147 "methodId": "api-key",
9148 "type": "env_var",
9149 "vars": [{"name": "API_KEY"}]
9150 }))
9151 .is_err()
9152 );
9153 }
9154
9155 #[test]
9156 fn test_auth_method_unknown_variant_roundtrip() {
9157 let method: AuthMethod = serde_json::from_value(json!({
9158 "methodId": "oauth",
9159 "name": "OAuth",
9160 "type": "_oauth",
9161 "authorizationUrl": "https://example.com/auth"
9162 }))
9163 .unwrap();
9164
9165 assert_eq!(method.method_id().0.as_ref(), "oauth");
9166 assert_eq!(method.name(), "OAuth");
9167 let AuthMethod::Other(unknown) = method else {
9168 panic!("expected unknown auth method");
9169 };
9170 assert_eq!(unknown.type_, "_oauth");
9171 assert_eq!(
9172 unknown.fields.get("authorizationUrl"),
9173 Some(&json!("https://example.com/auth"))
9174 );
9175
9176 assert_eq!(
9177 serde_json::to_value(AuthMethod::Other(unknown)).unwrap(),
9178 json!({
9179 "methodId": "oauth",
9180 "name": "OAuth",
9181 "type": "_oauth",
9182 "authorizationUrl": "https://example.com/auth"
9183 })
9184 );
9185 }
9186
9187 #[test]
9188 fn test_auth_method_unknown_does_not_hide_malformed_known_variant() {
9189 assert!(
9190 serde_json::from_value::<AuthMethod>(json!({
9191 "methodId": "terminal-auth",
9192 "type": "terminal"
9193 }))
9194 .is_err()
9195 );
9196 }
9197
9198 #[test]
9199 fn test_tool_call_and_terminal_cancel_serialization() {
9200 assert_eq!(AGENT_METHOD_NAMES.tool_call_cancel, "tool_call/cancel");
9201 assert_eq!(AGENT_METHOD_NAMES.terminal_cancel, "terminal/cancel");
9202 assert_eq!(
9203 ClientRequest::CancelToolCallRequest(Box::new(CancelToolCallRequest::new(
9204 "sess_abc123",
9205 "call_012"
9206 )))
9207 .method(),
9208 "tool_call/cancel"
9209 );
9210 assert_eq!(
9211 ClientRequest::CancelTerminalRequest(Box::new(CancelTerminalRequest::new(
9212 "sess_abc123",
9213 "term_003"
9214 )))
9215 .method(),
9216 "terminal/cancel"
9217 );
9218 assert_eq!(
9219 serde_json::to_value(CancelToolCallRequest::new("sess_abc123", "call_012")).unwrap(),
9220 json!({"sessionId": "sess_abc123", "toolCallId": "call_012"})
9221 );
9222 assert_eq!(
9223 serde_json::to_value(CancelTerminalRequest::new("sess_abc123", "term_003")).unwrap(),
9224 json!({"sessionId": "sess_abc123", "terminalId": "term_003"})
9225 );
9226 assert!(
9227 serde_json::from_value::<CancelToolCallRequest>(json!({"sessionId": "sess_abc123"}))
9228 .is_err()
9229 );
9230 assert_eq!(
9231 serde_json::to_value(CancelTerminalResponse::new()).unwrap(),
9232 json!({})
9233 );
9234 }
9235
9236 #[test]
9237 fn test_session_delete_serialization() {
9238 assert_eq!(AGENT_METHOD_NAMES.session_delete, "session/delete");
9239 assert_eq!(
9240 ClientRequest::DeleteSessionRequest(Box::new(DeleteSessionRequest::new("sess_abc123")))
9241 .method(),
9242 "session/delete"
9243 );
9244 assert_eq!(
9245 serde_json::to_value(DeleteSessionRequest::new("sess_abc123")).unwrap(),
9246 json!({
9247 "sessionId": "sess_abc123"
9248 })
9249 );
9250 assert_eq!(
9251 serde_json::to_value(DeleteSessionResponse::new()).unwrap(),
9252 json!({})
9253 );
9254 assert_eq!(
9255 serde_json::to_value(
9256 SessionCapabilities::new().delete(SessionDeleteCapabilities::new())
9257 )
9258 .unwrap(),
9259 json!({
9260 "delete": {}
9261 })
9262 );
9263 }
9264 #[cfg(feature = "unstable_session_set_title")]
9265 #[test]
9266 fn test_session_set_title_serialization() {
9267 assert_eq!(AGENT_METHOD_NAMES.session_set_title, "session/set_title");
9268 assert_eq!(
9269 ClientRequest::SetSessionTitleRequest(Box::new(SetSessionTitleRequest::new(
9270 "sess_abc123",
9271 "Investigate OAuth timeout"
9272 )))
9273 .method(),
9274 "session/set_title"
9275 );
9276 assert_eq!(
9277 serde_json::to_value(SetSessionTitleRequest::new(
9278 "sess_abc123",
9279 "Investigate OAuth timeout"
9280 ))
9281 .unwrap(),
9282 json!({
9283 "sessionId": "sess_abc123",
9284 "title": "Investigate OAuth timeout"
9285 })
9286 );
9287 assert_eq!(
9288 serde_json::to_value(SetSessionTitleResponse::new("Investigate OAuth timeout"))
9289 .unwrap(),
9290 json!({
9291 "title": "Investigate OAuth timeout"
9292 })
9293 );
9294 assert_eq!(
9295 serde_json::to_value(SessionCapabilities::new().title(SessionTitleCapabilities::new()))
9296 .unwrap(),
9297 json!({
9298 "title": {}
9299 })
9300 );
9301 }
9302
9303 #[cfg(feature = "unstable_session_set_title")]
9304 #[test]
9305 fn test_session_set_title_requires_title() {
9306 for params in [
9307 json!({"sessionId": "sess_abc123"}),
9308 json!({"sessionId": "sess_abc123", "title": null}),
9309 json!({"sessionId": "sess_abc123", "title": 42}),
9310 ] {
9311 assert!(serde_json::from_value::<SetSessionTitleRequest>(params).is_err());
9312 }
9313 for result in [json!({}), json!({"title": null})] {
9314 assert!(serde_json::from_value::<SetSessionTitleResponse>(result).is_err());
9315 }
9316 }
9317
9318 #[cfg(feature = "unstable_session_options")]
9319 #[test]
9320 fn test_session_options_serialization() {
9321 assert_eq!(AGENT_METHOD_NAMES.session_options, "session/options");
9322 assert_eq!(
9323 ClientRequest::SessionOptionsRequest(Box::new(SessionOptionsRequest::new(
9324 "/home/user/project"
9325 )))
9326 .method(),
9327 "session/options"
9328 );
9329 assert_eq!(
9330 serde_json::to_value(
9331 SessionOptionsRequest::new("/home/user/project")
9332 .session_id(SessionId::new("sess_abc123"))
9333 )
9334 .unwrap(),
9335 json!({"cwd": "/home/user/project", "sessionId": "sess_abc123"})
9336 );
9337 assert_eq!(
9338 serde_json::from_value::<SessionOptionsRequest>(
9339 json!({"cwd": "/home/user/project", "additionalDirectories": null, "sessionId": null})
9340 )
9341 .unwrap(),
9342 SessionOptionsRequest::new("/home/user/project")
9343 );
9344 let request = NewSessionRequest::new("/home/user/project").config_options(vec![
9345 InitialSessionConfigOption::new("model", SessionConfigOptionValue::id("model-2")),
9346 InitialSessionConfigOption::new("fast", SessionConfigOptionValue::boolean(true)),
9347 ]);
9348 let value = serde_json::to_value(&request).unwrap();
9349 assert_eq!(
9350 value["configOptions"],
9351 json!([
9352 {"configId": "model", "type": "id", "value": "model-2"},
9353 {"configId": "fast", "type": "boolean", "value": true}
9354 ])
9355 );
9356 assert_eq!(
9357 serde_json::from_value::<NewSessionRequest>(value).unwrap(),
9358 request
9359 );
9360 assert!(
9361 serde_json::from_value::<NewSessionRequest>(json!({
9362 "cwd": "/home/user/project",
9363 "mcpServers": [],
9364 "configOptions": [{"type": "boolean", "value": true}]
9365 }))
9366 .is_err()
9367 );
9368 assert_eq!(
9369 serde_json::to_value(SessionOptionsResponse::new()).unwrap(),
9370 json!({})
9371 );
9372 #[cfg(feature = "unstable_session_fork")]
9373 {
9374 let fork =
9375 ForkSessionRequest::new("sess_abc123", "/home/user/project").config_options(vec![
9376 InitialSessionConfigOption::new(
9377 "model",
9378 SessionConfigOptionValue::id("model-2"),
9379 ),
9380 ]);
9381 let value = serde_json::to_value(&fork).unwrap();
9382 assert_eq!(
9383 value["configOptions"],
9384 json!([{"configId": "model", "type": "id", "value": "model-2"}])
9385 );
9386 assert_eq!(
9387 serde_json::from_value::<ForkSessionRequest>(value).unwrap(),
9388 fork
9389 );
9390 assert_eq!(
9392 serde_json::from_value::<ForkSessionRequest>(json!({
9393 "sessionId": "sess_abc123",
9394 "cwd": "/home/user/project",
9395 "configOptions": null
9396 }))
9397 .unwrap(),
9398 ForkSessionRequest::new("sess_abc123", "/home/user/project")
9399 );
9400 assert!(
9401 serde_json::from_value::<ForkSessionRequest>(json!({
9402 "sessionId": "sess_abc123",
9403 "cwd": "/home/user/project",
9404 "configOptions": [{"type": "boolean", "value": true}]
9405 }))
9406 .is_err()
9407 );
9408 }
9409 assert_eq!(
9410 serde_json::to_value(
9411 SessionCapabilities::new().options(SessionOptionsCapabilities::new())
9412 )
9413 .unwrap(),
9414 json!({"options": {}})
9415 );
9416 }
9417
9418 #[cfg(feature = "unstable_session_status")]
9419 #[test]
9420 fn test_session_status_serialization() {
9421 assert_eq!(AGENT_METHOD_NAMES.session_status, "session/status");
9422 assert_eq!(
9423 ClientRequest::SessionStatusRequest(Box::new(SessionStatusRequest::new("sess_abc123")))
9424 .method(),
9425 "session/status"
9426 );
9427 assert_eq!(
9428 serde_json::to_value(SessionStatusRequest::new("sess_abc123")).unwrap(),
9429 json!({"sessionId": "sess_abc123"})
9430 );
9431 assert_eq!(
9432 serde_json::to_value(SessionStatusResponse::new(SessionStatus::Saved)).unwrap(),
9433 json!({"status": "saved"})
9434 );
9435 assert_eq!(
9436 serde_json::to_value(
9437 SessionCapabilities::new().status(SessionStatusCapabilities::new())
9438 )
9439 .unwrap(),
9440 json!({"status": {}})
9441 );
9442 assert_eq!(
9443 serde_json::to_value(SessionStatusResponse::new(SessionStatus::Open).state(
9444 StateUpdate::RequiresAction(crate::v2::RequiresActionStateUpdate::new())
9445 ))
9446 .unwrap(),
9447 json!({
9448 "status": "open",
9449 "state": {"state": "requires_action"}
9450 })
9451 );
9452 for state in [json!(null), json!("running"), json!({"state": 7})] {
9453 let response = serde_json::from_value::<SessionStatusResponse>(
9454 json!({"status": "open", "state": state}),
9455 )
9456 .unwrap();
9457 assert_eq!(response.state, None);
9458 }
9459 }
9460
9461 #[cfg(feature = "unstable_session_status")]
9462 #[test]
9463 fn test_session_status_is_strict_and_open() {
9464 let custom =
9465 serde_json::from_value::<SessionStatusResponse>(json!({"status": "_suspended"}))
9466 .unwrap();
9467 assert_eq!(
9468 custom.status,
9469 SessionStatus::Other("_suspended".to_string())
9470 );
9471 assert_eq!(
9472 serde_json::to_value(&custom).unwrap(),
9473 json!({"status": "_suspended"})
9474 );
9475 for result in [json!({}), json!({"status": null}), json!({"status": 1})] {
9476 assert!(serde_json::from_value::<SessionStatusResponse>(result).is_err());
9477 }
9478 for params in [json!({}), json!({"sessionId": null})] {
9479 assert!(serde_json::from_value::<SessionStatusRequest>(params).is_err());
9480 }
9481 }
9482
9483 #[cfg(feature = "unstable_session_archive")]
9484 #[test]
9485 fn test_session_archive_serialization() {
9486 assert_eq!(AGENT_METHOD_NAMES.session_archive, "session/archive");
9487 assert_eq!(AGENT_METHOD_NAMES.session_unarchive, "session/unarchive");
9488 assert_eq!(
9489 ClientRequest::ArchiveSessionRequest(Box::new(ArchiveSessionRequest::new(
9490 "sess_abc123"
9491 )))
9492 .method(),
9493 "session/archive"
9494 );
9495 assert_eq!(
9496 ClientRequest::UnarchiveSessionRequest(Box::new(UnarchiveSessionRequest::new(
9497 "sess_abc123"
9498 )))
9499 .method(),
9500 "session/unarchive"
9501 );
9502 assert_eq!(
9503 serde_json::to_value(ArchiveSessionRequest::new("sess_abc123")).unwrap(),
9504 json!({"sessionId": "sess_abc123"})
9505 );
9506 assert_eq!(
9507 serde_json::to_value(UnarchiveSessionResponse::new()).unwrap(),
9508 json!({})
9509 );
9510 assert_eq!(
9511 serde_json::to_value(
9512 SessionCapabilities::new().archive(SessionArchiveCapabilities::new())
9513 )
9514 .unwrap(),
9515 json!({"archive": {}})
9516 );
9517 assert_eq!(
9518 serde_json::to_value(
9519 ListSessionsRequest::new()
9520 .cwd("/home/user/project")
9521 .archived(SessionArchiveFilter::Only)
9522 )
9523 .unwrap(),
9524 json!({"cwd": "/home/user/project", "archived": "only"})
9525 );
9526 assert_eq!(
9527 serde_json::to_value(
9528 SessionInfo::new("sess_abc123", "/home/user/project").archived(true)
9529 )
9530 .unwrap(),
9531 json!({"sessionId": "sess_abc123", "cwd": "/home/user/project", "archived": true})
9532 );
9533 }
9534
9535 #[cfg(feature = "unstable_session_archive")]
9536 #[test]
9537 fn test_session_archive_filter_is_strict_and_open() {
9538 for (value, expected) in [
9539 (json!(null), None),
9540 (json!("include"), Some(SessionArchiveFilter::Include)),
9541 (
9542 json!("_recent"),
9543 Some(SessionArchiveFilter::Other("_recent".to_string())),
9544 ),
9545 ] {
9546 let request =
9547 serde_json::from_value::<ListSessionsRequest>(json!({"archived": value})).unwrap();
9548 assert_eq!(request.archived, expected);
9549 }
9550 for value in [json!(true), json!(1), json!({})] {
9551 assert!(
9552 serde_json::from_value::<ListSessionsRequest>(json!({"archived": value})).is_err()
9553 );
9554 }
9555 let info = serde_json::from_value::<SessionInfo>(
9556 json!({"sessionId": "sess_abc123", "cwd": "/home/user/project", "archived": "yes"}),
9557 )
9558 .unwrap();
9559 assert_eq!(info.archived, None);
9560 }
9561
9562 #[test]
9563 fn test_session_additional_directories_serialization() {
9564 assert_eq!(
9565 serde_json::to_value(NewSessionRequest::new("/home/user/project")).unwrap(),
9566 json!({
9567 "cwd": "/home/user/project",
9568 })
9569 );
9570 assert_eq!(
9571 serde_json::to_value(
9572 NewSessionRequest::new("/home/user/project").additional_directories(vec![
9573 PathBuf::from("/home/user/shared-lib"),
9574 PathBuf::from("/home/user/product-docs"),
9575 ])
9576 )
9577 .unwrap(),
9578 json!({
9579 "cwd": "/home/user/project",
9580 "additionalDirectories": [
9581 "/home/user/shared-lib",
9582 "/home/user/product-docs"
9583 ],
9584 })
9585 );
9586 assert_eq!(
9587 serde_json::to_value(ResumeSessionRequest::new(
9588 "sess_abc123",
9589 "/home/user/project"
9590 ))
9591 .unwrap(),
9592 json!({
9593 "sessionId": "sess_abc123",
9594 "cwd": "/home/user/project",
9595 })
9596 );
9597 assert_eq!(
9598 serde_json::from_value::<ResumeSessionRequest>(json!({
9599 "sessionId": "sess_abc123",
9600 "cwd": "/home/user/project"
9601 }))
9602 .unwrap()
9603 .mcp_servers,
9604 Vec::<McpServer>::new()
9605 );
9606 assert_eq!(
9607 serde_json::from_value::<ResumeSessionRequest>(json!({
9608 "sessionId": "sess_abc123",
9609 "cwd": "/home/user/project",
9610 "mcpServers": null
9611 }))
9612 .unwrap()
9613 .mcp_servers,
9614 Vec::<McpServer>::new()
9615 );
9616 assert_eq!(
9617 serde_json::to_value(SessionInfo::new("sess_abc123", "/home/user/project")).unwrap(),
9618 json!({
9619 "sessionId": "sess_abc123",
9620 "cwd": "/home/user/project"
9621 })
9622 );
9623 assert_eq!(
9624 serde_json::to_value(
9625 SessionInfo::new("sess_abc123", "/home/user/project").additional_directories(vec![
9626 PathBuf::from("/home/user/shared-lib"),
9627 PathBuf::from("/home/user/product-docs"),
9628 ])
9629 )
9630 .unwrap(),
9631 json!({
9632 "sessionId": "sess_abc123",
9633 "cwd": "/home/user/project",
9634 "additionalDirectories": [
9635 "/home/user/shared-lib",
9636 "/home/user/product-docs"
9637 ]
9638 })
9639 );
9640 assert_eq!(
9641 serde_json::from_value::<SessionInfo>(json!({
9642 "sessionId": "sess_abc123",
9643 "cwd": "/home/user/project"
9644 }))
9645 .unwrap()
9646 .additional_directories,
9647 Vec::<AbsolutePath>::new()
9648 );
9649 }
9650 #[test]
9651 fn test_session_additional_directories_capabilities_serialization() {
9652 assert_eq!(
9653 serde_json::to_value(
9654 SessionCapabilities::new()
9655 .additional_directories(SessionAdditionalDirectoriesCapabilities::new())
9656 )
9657 .unwrap(),
9658 json!({
9659 "additionalDirectories": {}
9660 })
9661 );
9662 }
9663
9664 #[test]
9665 fn test_session_system_prompt_capabilities_serialization() {
9666 assert_eq!(
9667 serde_json::to_value(
9668 SessionCapabilities::new().system_prompt(SessionSystemPromptCapabilities::new())
9669 )
9670 .unwrap(),
9671 json!({ "systemPrompt": {} })
9672 );
9673 assert_eq!(
9674 serde_json::to_value(
9675 SessionCapabilities::new().system_prompt(
9676 SessionSystemPromptCapabilities::new().mode(
9677 SessionSystemPromptModeCapabilities::new()
9678 .override_(SessionSystemPromptOverrideCapabilities::new())
9679 )
9680 )
9681 )
9682 .unwrap(),
9683 json!({ "systemPrompt": { "mode": { "override": {} } } })
9684 );
9685 assert_eq!(
9686 serde_json::from_value::<SessionCapabilities>(
9687 json!({ "systemPrompt": { "mode": { "override": {} } } })
9688 )
9689 .unwrap()
9690 .system_prompt
9691 .and_then(|capabilities| capabilities.mode)
9692 .and_then(|mode| mode.override_),
9693 Some(SessionSystemPromptOverrideCapabilities::new())
9694 );
9695
9696 assert_eq!(
9698 serde_json::from_value::<SessionCapabilities>(json!({ "systemPrompt": "yes" }))
9699 .unwrap()
9700 .system_prompt,
9701 None
9702 );
9703 assert_eq!(
9704 serde_json::from_value::<SessionCapabilities>(
9705 json!({ "systemPrompt": { "mode": { "override": true } } })
9706 )
9707 .unwrap()
9708 .system_prompt,
9709 Some(
9710 SessionSystemPromptCapabilities::new()
9711 .mode(SessionSystemPromptModeCapabilities::new())
9712 )
9713 );
9714 assert_eq!(
9715 serde_json::from_value::<SessionCapabilities>(
9716 json!({ "systemPrompt": { "mode": "override" } })
9717 )
9718 .unwrap()
9719 .system_prompt,
9720 Some(SessionSystemPromptCapabilities::new())
9721 );
9722 }
9723
9724 #[test]
9725 fn test_system_prompt_lifecycle_request_serialization() {
9726 let system_prompt = SystemPrompt::new(vec![ContentBlock::from(
9727 "You are a code review specialist.",
9728 )]);
9729 let system_prompt_json = json!({
9730 "mode": "append",
9731 "content": [{ "type": "text", "text": "You are a code review specialist." }]
9732 });
9733
9734 let request =
9735 NewSessionRequest::new("/home/user/project").system_prompt(system_prompt.clone());
9736 let request_json = json!({
9737 "cwd": "/home/user/project",
9738 "systemPrompt": system_prompt_json
9739 });
9740 assert_eq!(serde_json::to_value(&request).unwrap(), request_json);
9741 assert_eq!(
9742 serde_json::from_value::<NewSessionRequest>(request_json).unwrap(),
9743 request
9744 );
9745
9746 assert_eq!(
9747 serde_json::to_value(
9748 ResumeSessionRequest::new("sess_abc123", "/home/user/project")
9749 .system_prompt(system_prompt.clone())
9750 )
9751 .unwrap()["systemPrompt"],
9752 system_prompt_json
9753 );
9754 #[cfg(feature = "unstable_session_fork")]
9755 assert_eq!(
9756 serde_json::to_value(
9757 ForkSessionRequest::new("sess_abc123", "/home/user/project")
9758 .system_prompt(system_prompt.clone())
9759 )
9760 .unwrap()["systemPrompt"],
9761 system_prompt_json
9762 );
9763
9764 let override_prompt =
9765 SystemPrompt::new(vec![ContentBlock::from("...")]).mode(SystemPromptMode::Override);
9766 let override_json = json!({
9767 "mode": "override",
9768 "content": [{ "type": "text", "text": "..." }]
9769 });
9770 assert_eq!(
9771 serde_json::to_value(&override_prompt).unwrap(),
9772 override_json
9773 );
9774 assert_eq!(
9775 serde_json::from_value::<SystemPrompt>(override_json).unwrap(),
9776 override_prompt
9777 );
9778 }
9779
9780 #[test]
9783 fn test_system_prompt_new_defaults_to_append() {
9784 let system_prompt = SystemPrompt::new(vec![ContentBlock::from("...")]);
9785 assert_eq!(system_prompt.mode, SystemPromptMode::Append);
9786 assert_eq!(
9787 serde_json::to_value(&system_prompt).unwrap(),
9788 json!({ "mode": "append", "content": [{ "type": "text", "text": "..." }] })
9789 );
9790 }
9791
9792 #[test]
9796 fn test_system_prompt_preserves_unknown_modes() {
9797 for mode in ["_vendor_mode", "prepend"] {
9798 let system_prompt_json =
9799 json!({ "mode": mode, "content": [{ "type": "text", "text": "..." }] });
9800 let system_prompt: SystemPrompt =
9801 serde_json::from_value(system_prompt_json.clone()).unwrap();
9802 assert_eq!(
9803 system_prompt.mode,
9804 SystemPromptMode::Other(mode.to_string())
9805 );
9806 assert_eq!(
9807 serde_json::to_value(&system_prompt).unwrap(),
9808 system_prompt_json
9809 );
9810 }
9811 }
9812
9813 fn assert_system_prompt_is_strict<T>(base: &serde_json::Value)
9817 where
9818 T: serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
9819 {
9820 let name = std::any::type_name::<T>();
9821 let with = |system_prompt: serde_json::Value| {
9822 let mut request = base.clone();
9823 request["systemPrompt"] = system_prompt;
9824 serde_json::from_value::<T>(request)
9825 };
9826
9827 for system_prompt in [
9828 json!("You are a code review specialist."),
9829 json!({ "content": [{ "type": "text", "text": "..." }] }),
9830 json!({ "mode": null, "content": [{ "type": "text", "text": "..." }] }),
9831 json!({ "mode": 1, "content": [{ "type": "text", "text": "..." }] }),
9832 json!({ "mode": "append" }),
9833 json!({ "mode": "append", "content": "..." }),
9834 json!({ "mode": "append", "content": [{ "type": "text" }] }),
9835 ] {
9836 assert!(
9837 with(system_prompt.clone()).is_err(),
9838 "{name}.systemPrompt: {system_prompt}"
9839 );
9840 }
9841
9842 assert_eq!(
9843 with(serde_json::Value::Null).unwrap(),
9844 serde_json::from_value::<T>(base.clone()).unwrap(),
9845 "{name}.systemPrompt"
9846 );
9847 }
9848
9849 #[test]
9850 fn test_session_setup_requests_reject_malformed_system_prompts() {
9851 assert!(
9852 serde_json::to_value(NewSessionRequest::new("/repo"))
9853 .unwrap()
9854 .get("systemPrompt")
9855 .is_none()
9856 );
9857 assert_system_prompt_is_strict::<NewSessionRequest>(&json!({ "cwd": "/repo" }));
9858 assert_system_prompt_is_strict::<ResumeSessionRequest>(&json!({
9859 "sessionId": "sess-1",
9860 "cwd": "/repo"
9861 }));
9862 #[cfg(feature = "unstable_session_fork")]
9863 assert_system_prompt_is_strict::<ForkSessionRequest>(&json!({
9864 "sessionId": "sess-1",
9865 "cwd": "/repo"
9866 }));
9867 }
9868
9869 #[test]
9872 fn test_system_prompt_preserves_unknown_content_blocks() {
9873 let request: NewSessionRequest = serde_json::from_value(json!({
9874 "cwd": "/home/user/project",
9875 "systemPrompt": {
9876 "mode": "append",
9877 "content": [{ "type": "_vendor_video", "uri": "https://example.com/intro.mp4" }]
9878 }
9879 }))
9880 .unwrap();
9881 let content = request.system_prompt.unwrap().content;
9882 assert_eq!(content.len(), 1);
9883 assert!(matches!(content[0], ContentBlock::Other(_)));
9884 }
9885
9886 #[test]
9887 fn test_auth_method_terminal_serialization() {
9888 let method = AuthMethod::Terminal(AuthMethodTerminal::new("tui-auth", "Terminal Auth"));
9889
9890 let json = serde_json::to_value(&method).unwrap();
9891 assert_eq!(
9892 json,
9893 json!({
9894 "methodId": "tui-auth",
9895 "name": "Terminal Auth",
9896 "type": "terminal"
9897 })
9898 );
9899 assert!(!json.as_object().unwrap().contains_key("args"));
9901 assert!(!json.as_object().unwrap().contains_key("env"));
9902
9903 let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9904 match deserialized {
9905 AuthMethod::Terminal(AuthMethodTerminal { args, env, .. }) => {
9906 assert_eq!(args, Vec::<String>::new());
9907 assert_eq!(env, []);
9908 }
9909 _ => panic!("Expected Terminal variant"),
9910 }
9911 }
9912
9913 #[test]
9914 fn test_auth_method_terminal_with_args_and_env_serialization() {
9915 let method = AuthMethod::Terminal(
9916 AuthMethodTerminal::new("tui-auth", "Terminal Auth")
9917 .args(vec!["--interactive".to_string(), "--color".to_string()])
9918 .env(vec![EnvVariable::new("TERM", "xterm-256color")]),
9919 );
9920
9921 let json = serde_json::to_value(&method).unwrap();
9922 assert_eq!(
9923 json,
9924 json!({
9925 "methodId": "tui-auth",
9926 "name": "Terminal Auth",
9927 "type": "terminal",
9928 "args": ["--interactive", "--color"],
9929 "env": [
9930 {
9931 "name": "TERM",
9932 "value": "xterm-256color"
9933 }
9934 ]
9935 })
9936 );
9937
9938 let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9939 match deserialized {
9940 AuthMethod::Terminal(AuthMethodTerminal { args, env, .. }) => {
9941 assert_eq!(args, vec!["--interactive", "--color"]);
9942 assert_eq!(env.len(), 1);
9943 assert_eq!(env[0].name, "TERM");
9944 assert_eq!(env[0].value, "xterm-256color");
9945 }
9946 _ => panic!("Expected Terminal variant"),
9947 }
9948 }
9949
9950 #[test]
9951 fn test_session_config_option_id_serialize() {
9952 let val = SessionConfigOptionValue::id("model-1");
9953 let json = serde_json::to_value(&val).unwrap();
9954 assert_eq!(json, json!({ "type": "id", "value": "model-1" }));
9955 }
9956
9957 #[test]
9958 fn test_session_config_option_value_boolean_serialize() {
9959 let val = SessionConfigOptionValue::boolean(true);
9960 let json = serde_json::to_value(&val).unwrap();
9961 assert_eq!(json, json!({ "type": "boolean", "value": true }));
9962 }
9963
9964 #[test]
9965 fn test_session_config_option_value_deserialize_id() {
9966 let json = json!({ "type": "id", "value": "model-1" });
9967 let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9968 assert_eq!(val, SessionConfigOptionValue::id("model-1"));
9969 assert_eq!(val.as_id().unwrap().to_string(), "model-1");
9970 }
9971
9972 #[test]
9973 fn test_session_config_option_value_deserialize_requires_type() {
9974 let json = json!({ "value": "model-1" });
9975 let result = serde_json::from_value::<SessionConfigOptionValue>(json);
9976 assert!(result.is_err());
9977 }
9978
9979 #[test]
9980 fn test_session_config_option_value_deserialize_boolean() {
9981 let json = json!({ "type": "boolean", "value": true });
9982 let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9983 assert_eq!(val, SessionConfigOptionValue::boolean(true));
9984 assert_eq!(val.as_bool(), Some(true));
9985 }
9986
9987 #[test]
9988 fn test_session_config_option_value_deserialize_boolean_false() {
9989 let json = json!({ "type": "boolean", "value": false });
9990 let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9991 assert_eq!(val, SessionConfigOptionValue::boolean(false));
9992 assert_eq!(val.as_bool(), Some(false));
9993 }
9994
9995 #[test]
9996 fn test_session_config_option_value_deserialize_unknown_type_with_string_value() {
9997 let json = json!({
9998 "type": "text",
9999 "value": "freeform input",
10000 "maxLength": 200
10001 });
10002 let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10003 let SessionConfigOptionValue::Other(unknown) = val else {
10004 panic!("Expected Other variant");
10005 };
10006 assert_eq!(unknown.type_, "text");
10007 assert_eq!(unknown.value, json!("freeform input"));
10008 assert_eq!(unknown.fields["maxLength"], json!(200));
10009 }
10010
10011 #[test]
10012 fn test_session_config_option_value_deserialize_unknown_type_with_object_value() {
10013 let json = json!({
10014 "type": "range",
10015 "value": { "min": 1, "max": 5 }
10016 });
10017 let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10018 let SessionConfigOptionValue::Other(unknown) = val else {
10019 panic!("Expected Other variant");
10020 };
10021 assert_eq!(unknown.type_, "range");
10022 assert_eq!(unknown.value, json!({ "min": 1, "max": 5 }));
10023 }
10024
10025 #[test]
10026 fn test_session_config_option_value_roundtrip_id() {
10027 let original = SessionConfigOptionValue::id("option-a");
10028 let json = serde_json::to_value(&original).unwrap();
10029 let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10030 assert_eq!(original, roundtripped);
10031 }
10032
10033 #[test]
10034 fn test_session_config_option_value_roundtrip_boolean() {
10035 let original = SessionConfigOptionValue::boolean(false);
10036 let json = serde_json::to_value(&original).unwrap();
10037 let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10038 assert_eq!(original, roundtripped);
10039 }
10040
10041 #[test]
10042 fn test_session_config_option_value_roundtrip_other() {
10043 let mut fields = IndexMap::new();
10044 fields.insert("maxLength".to_string(), json!(200));
10045 let original = SessionConfigOptionValue::from(OtherSessionConfigOptionValue::new(
10046 "text",
10047 json!("freeform input"),
10048 fields,
10049 ));
10050 let json = serde_json::to_value(&original).unwrap();
10051 assert_eq!(
10052 json,
10053 json!({"type": "text", "value": "freeform input", "maxLength": 200})
10054 );
10055 let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10056 assert_eq!(original, roundtripped);
10057 }
10058
10059 #[test]
10060 fn test_session_config_option_value_type_mismatch_boolean_with_string() {
10061 let json = json!({ "type": "boolean", "value": "not a bool" });
10062 let result = serde_json::from_value::<SessionConfigOptionValue>(json);
10063 assert!(result.is_err());
10064 }
10065
10066 #[test]
10067 fn test_session_config_option_value_from_impls() {
10068 let from_str: SessionConfigOptionValue = "model-1".into();
10069 assert_eq!(from_str.as_id().unwrap().to_string(), "model-1");
10070
10071 let from_id: SessionConfigOptionValue = SessionConfigValueId::new("model-2").into();
10072 assert_eq!(from_id.as_id().unwrap().to_string(), "model-2");
10073
10074 let from_bool: SessionConfigOptionValue = true.into();
10075 assert_eq!(from_bool.as_bool(), Some(true));
10076 }
10077
10078 #[test]
10079 fn test_set_session_config_option_request_id() {
10080 let req = SetSessionConfigOptionRequest::new("sess_1", "model", "model-1");
10081 let json = serde_json::to_value(&req).unwrap();
10082 assert_eq!(
10083 json,
10084 json!({
10085 "sessionId": "sess_1",
10086 "configId": "model",
10087 "type": "id",
10088 "value": "model-1"
10089 })
10090 );
10091 }
10092
10093 #[test]
10094 fn test_set_session_config_option_request_boolean() {
10095 let req = SetSessionConfigOptionRequest::new("sess_1", "brave_mode", true);
10096 let json = serde_json::to_value(&req).unwrap();
10097 assert_eq!(
10098 json,
10099 json!({
10100 "sessionId": "sess_1",
10101 "configId": "brave_mode",
10102 "type": "boolean",
10103 "value": true
10104 })
10105 );
10106 }
10107
10108 #[test]
10109 fn test_set_session_config_option_request_deserialize_requires_type() {
10110 let json = json!({
10111 "sessionId": "sess_1",
10112 "configId": "model",
10113 "value": "model-1"
10114 });
10115 let result = serde_json::from_value::<SetSessionConfigOptionRequest>(json);
10116 assert!(result.is_err());
10117 }
10118
10119 #[test]
10120 fn test_set_session_config_option_request_deserialize_boolean() {
10121 let json = json!({
10122 "sessionId": "sess_1",
10123 "configId": "brave_mode",
10124 "type": "boolean",
10125 "value": true
10126 });
10127 let req: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
10128 assert_eq!(req.value.as_bool(), Some(true));
10129 }
10130
10131 #[test]
10132 fn test_set_session_config_option_request_roundtrip_id() {
10133 let original = SetSessionConfigOptionRequest::new("s", "c", "v");
10134 let json = serde_json::to_value(&original).unwrap();
10135 let roundtripped: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
10136 assert_eq!(original, roundtripped);
10137 }
10138
10139 #[test]
10140 fn test_set_session_config_option_request_roundtrip_boolean() {
10141 let original = SetSessionConfigOptionRequest::new("s", "c", false);
10142 let json = serde_json::to_value(&original).unwrap();
10143 let roundtripped: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
10144 assert_eq!(original, roundtripped);
10145 }
10146
10147 #[test]
10148 fn test_session_config_boolean_serialization() {
10149 let cfg = SessionConfigBoolean::new(true);
10150 let json = serde_json::to_value(&cfg).unwrap();
10151 assert_eq!(json, json!({ "currentValue": true }));
10152
10153 let deserialized: SessionConfigBoolean = serde_json::from_value(json).unwrap();
10154 assert!(deserialized.current_value);
10155 }
10156
10157 #[test]
10158 fn test_session_config_option_boolean_variant() {
10159 let opt = SessionConfigOption::boolean("brave_mode", "Brave Mode", false)
10160 .description("Skip confirmation prompts")
10161 .meta(test_meta());
10162 assert_eq!(serialized_meta_key_count(&opt), 1);
10163
10164 let json = serde_json::to_value(&opt).unwrap();
10165 assert_eq!(
10166 json,
10167 json!({
10168 "configId": "brave_mode",
10169 "name": "Brave Mode",
10170 "description": "Skip confirmation prompts",
10171 "type": "boolean",
10172 "currentValue": false,
10173 "_meta": {
10174 "source": "test"
10175 }
10176 })
10177 );
10178
10179 let deserialized: SessionConfigOption = serde_json::from_value(json).unwrap();
10180 assert_eq!(deserialized.config_id.to_string(), "brave_mode");
10181 assert_eq!(deserialized.name, "Brave Mode");
10182 match deserialized.kind {
10183 SessionConfigKind::Boolean(ref b) => assert!(!b.current_value),
10184 _ => panic!("Expected Boolean kind"),
10185 }
10186 }
10187
10188 #[test]
10189 fn test_session_config_option_select_still_works() {
10190 let opt = SessionConfigOption::select(
10192 "model",
10193 "Model",
10194 "model-1",
10195 vec![
10196 SessionConfigSelectOption::new("model-1", "Model 1"),
10197 SessionConfigSelectOption::new("model-2", "Model 2"),
10198 ],
10199 )
10200 .meta(test_meta());
10201 assert_eq!(serialized_meta_key_count(&opt), 1);
10202
10203 let json = serde_json::to_value(&opt).unwrap();
10204 assert_eq!(json["type"], "select");
10205 assert_eq!(json["currentValue"], "model-1");
10206 assert_eq!(json["options"].as_array().unwrap().len(), 2);
10207 assert_eq!(json["_meta"]["source"], "test");
10208
10209 let deserialized: SessionConfigOption = serde_json::from_value(json).unwrap();
10210 match deserialized.kind {
10211 SessionConfigKind::Select(ref s) => {
10212 assert_eq!(s.current_value.to_string(), "model-1");
10213 }
10214 _ => panic!("Expected Select kind"),
10215 }
10216 }
10217
10218 #[test]
10219 fn test_session_config_option_unknown_kind_roundtrip() {
10220 let option: SessionConfigOption = serde_json::from_value(json!({
10221 "configId": "verbosity",
10222 "name": "Verbosity",
10223 "type": "_slider",
10224 "currentValue": 3,
10225 "min": 0,
10226 "max": 5,
10227 "_meta": {
10228 "source": "test"
10229 }
10230 }))
10231 .unwrap();
10232
10233 assert_eq!(option.config_id.to_string(), "verbosity");
10234 assert_eq!(option.meta.as_ref().unwrap()["source"], "test");
10235 let SessionConfigKind::Other(unknown) = &option.kind else {
10236 panic!("expected unknown config kind");
10237 };
10238 assert_eq!(unknown.type_, "_slider");
10239 assert_eq!(unknown.fields.get("currentValue"), Some(&json!(3)));
10240 assert!(!unknown.fields.contains_key("_meta"));
10241 assert_eq!(serialized_meta_key_count(&option), 1);
10242
10243 let json = serde_json::to_value(&option).unwrap();
10244 assert_eq!(json["type"], "_slider");
10245 assert_eq!(json["currentValue"], 3);
10246 assert_eq!(json["min"], 0);
10247 assert_eq!(json["max"], 5);
10248 assert_eq!(json["_meta"]["source"], "test");
10249 }
10250
10251 #[test]
10252 fn test_session_config_option_unknown_kind_does_not_duplicate_flattened_meta() {
10253 let mut fields = IndexMap::new();
10254 fields.insert("currentValue".to_string(), json!(3));
10255 fields.insert("_meta".to_string(), json!({ "inner": "ignored" }));
10256
10257 let option = SessionConfigOption::new(
10258 "verbosity",
10259 "Verbosity",
10260 SessionConfigKind::Other(OtherSessionConfigKind::new("_slider", fields)),
10261 )
10262 .meta(test_meta());
10263
10264 let SessionConfigKind::Other(unknown) = &option.kind else {
10265 panic!("expected unknown config kind");
10266 };
10267 assert!(!unknown.fields.contains_key("_meta"));
10268 assert_eq!(serialized_meta_key_count(&option), 1);
10269
10270 let json = serde_json::to_value(&option).unwrap();
10271 assert_eq!(json["type"], "_slider");
10272 assert_eq!(json["currentValue"], 3);
10273 assert_eq!(json["_meta"]["source"], "test");
10274 }
10275
10276 #[test]
10277 fn test_session_config_option_unknown_does_not_hide_malformed_known_kind() {
10278 assert!(
10279 serde_json::from_value::<SessionConfigOption>(json!({
10280 "configId": "model",
10281 "name": "Model",
10282 "type": "select"
10283 }))
10284 .is_err()
10285 );
10286 }
10287
10288 #[cfg(feature = "unstable_llm_providers")]
10289 #[test]
10290 fn test_llm_protocol_known_variants() {
10291 assert_eq!(
10292 serde_json::to_value(&LlmProtocol::Anthropic).unwrap(),
10293 json!("anthropic")
10294 );
10295 assert_eq!(
10296 serde_json::to_value(&LlmProtocol::OpenAi).unwrap(),
10297 json!("openai")
10298 );
10299 assert_eq!(
10300 serde_json::to_value(&LlmProtocol::Azure).unwrap(),
10301 json!("azure")
10302 );
10303 assert_eq!(
10304 serde_json::to_value(&LlmProtocol::Vertex).unwrap(),
10305 json!("vertex")
10306 );
10307 assert_eq!(
10308 serde_json::to_value(&LlmProtocol::Bedrock).unwrap(),
10309 json!("bedrock")
10310 );
10311
10312 assert_eq!(
10313 serde_json::from_str::<LlmProtocol>("\"anthropic\"").unwrap(),
10314 LlmProtocol::Anthropic
10315 );
10316 assert_eq!(
10317 serde_json::from_str::<LlmProtocol>("\"openai\"").unwrap(),
10318 LlmProtocol::OpenAi
10319 );
10320 assert_eq!(
10321 serde_json::from_str::<LlmProtocol>("\"azure\"").unwrap(),
10322 LlmProtocol::Azure
10323 );
10324 assert_eq!(
10325 serde_json::from_str::<LlmProtocol>("\"vertex\"").unwrap(),
10326 LlmProtocol::Vertex
10327 );
10328 assert_eq!(
10329 serde_json::from_str::<LlmProtocol>("\"bedrock\"").unwrap(),
10330 LlmProtocol::Bedrock
10331 );
10332 }
10333
10334 #[cfg(feature = "unstable_llm_providers")]
10335 #[test]
10336 fn test_llm_protocol_unknown_variant() {
10337 let unknown: LlmProtocol = serde_json::from_str("\"cohere\"").unwrap();
10338 assert_eq!(unknown, LlmProtocol::Other("cohere".to_string()));
10339
10340 let json = serde_json::to_value(&unknown).unwrap();
10341 assert_eq!(json, json!("cohere"));
10342 }
10343
10344 #[cfg(feature = "unstable_llm_providers")]
10345 #[test]
10346 fn test_provider_current_config_serialization() {
10347 let config =
10348 ProviderCurrentConfig::new(LlmProtocol::Anthropic, "https://api.anthropic.com");
10349
10350 let json = serde_json::to_value(&config).unwrap();
10351 assert_eq!(
10352 json,
10353 json!({
10354 "apiType": "anthropic",
10355 "baseUrl": "https://api.anthropic.com"
10356 })
10357 );
10358
10359 let deserialized: ProviderCurrentConfig = serde_json::from_value(json).unwrap();
10360 assert_eq!(deserialized.api_type, LlmProtocol::Anthropic);
10361 assert_eq!(deserialized.base_url, "https://api.anthropic.com");
10362 }
10363
10364 #[cfg(feature = "unstable_llm_providers")]
10365 #[test]
10366 fn test_provider_info_with_current_config() {
10367 let info = ProviderInfo::new(
10368 "main",
10369 vec![LlmProtocol::Anthropic, LlmProtocol::OpenAi],
10370 true,
10371 Some(ProviderCurrentConfig::new(
10372 LlmProtocol::Anthropic,
10373 "https://api.anthropic.com",
10374 )),
10375 );
10376
10377 let json = serde_json::to_value(&info).unwrap();
10378 assert_eq!(
10379 json,
10380 json!({
10381 "providerId": "main",
10382 "supported": ["anthropic", "openai"],
10383 "required": true,
10384 "current": {
10385 "apiType": "anthropic",
10386 "baseUrl": "https://api.anthropic.com"
10387 }
10388 })
10389 );
10390
10391 let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10392 assert_eq!(deserialized.provider_id.to_string(), "main");
10393 assert_eq!(deserialized.supported.len(), 2);
10394 assert!(deserialized.required);
10395 assert!(deserialized.current.is_some());
10396 assert_eq!(
10397 deserialized.current.as_ref().unwrap().api_type,
10398 LlmProtocol::Anthropic
10399 );
10400 }
10401
10402 #[cfg(feature = "unstable_llm_providers")]
10403 #[test]
10404 fn test_provider_info_disabled() {
10405 let info = ProviderInfo::new(
10406 "secondary",
10407 vec![LlmProtocol::OpenAi],
10408 false,
10409 None::<ProviderCurrentConfig>,
10410 );
10411
10412 let json = serde_json::to_value(&info).unwrap();
10413 assert_eq!(
10414 json,
10415 json!({
10416 "providerId": "secondary",
10417 "supported": ["openai"],
10418 "required": false
10419 })
10420 );
10421
10422 let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10423 assert_eq!(deserialized.provider_id.to_string(), "secondary");
10424 assert!(!deserialized.required);
10425 assert!(deserialized.current.is_none());
10426 }
10427
10428 #[cfg(feature = "unstable_llm_providers")]
10429 #[test]
10430 fn test_provider_info_missing_current_defaults_to_none() {
10431 let json = json!({
10433 "providerId": "main",
10434 "supported": ["anthropic"],
10435 "required": true
10436 });
10437 let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10438 assert!(deserialized.current.is_none());
10439 }
10440
10441 #[cfg(feature = "unstable_llm_providers")]
10442 #[test]
10443 fn test_provider_info_explicit_null_current_decodes_to_none() {
10444 let json = json!({
10448 "providerId": "main",
10449 "supported": ["anthropic"],
10450 "required": true,
10451 "current": null
10452 });
10453 let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10454 assert!(deserialized.current.is_none());
10455 }
10456
10457 #[cfg(feature = "unstable_llm_providers")]
10458 #[test]
10459 fn test_list_providers_response_serialization() {
10460 let response = ListProvidersResponse::new(vec![ProviderInfo::new(
10461 "main",
10462 vec![LlmProtocol::Anthropic],
10463 true,
10464 Some(ProviderCurrentConfig::new(
10465 LlmProtocol::Anthropic,
10466 "https://api.anthropic.com",
10467 )),
10468 )]);
10469
10470 let json = serde_json::to_value(&response).unwrap();
10471 assert_eq!(json["providers"].as_array().unwrap().len(), 1);
10472 assert_eq!(json["providers"][0]["providerId"], "main");
10473
10474 let deserialized: ListProvidersResponse = serde_json::from_value(json).unwrap();
10475 assert_eq!(deserialized.providers.len(), 1);
10476 }
10477
10478 #[cfg(feature = "unstable_llm_providers")]
10479 #[test]
10480 fn test_set_provider_request_serialization() {
10481 let mut headers = IndexMap::new();
10482 headers.insert("Authorization".to_string(), "Bearer sk-test".to_string());
10483
10484 let request =
10485 SetProviderRequest::new("main", LlmProtocol::OpenAi, "https://api.openai.com/v1")
10486 .headers(headers);
10487
10488 let json = serde_json::to_value(&request).unwrap();
10489 assert_eq!(
10490 json,
10491 json!({
10492 "providerId": "main",
10493 "apiType": "openai",
10494 "baseUrl": "https://api.openai.com/v1",
10495 "headers": {
10496 "Authorization": "Bearer sk-test"
10497 }
10498 })
10499 );
10500
10501 let deserialized: SetProviderRequest = serde_json::from_value(json).unwrap();
10502 assert_eq!(deserialized.provider_id.to_string(), "main");
10503 assert_eq!(deserialized.api_type, LlmProtocol::OpenAi);
10504 assert_eq!(deserialized.base_url, "https://api.openai.com/v1");
10505 assert_eq!(deserialized.headers.len(), 1);
10506 assert_eq!(
10507 deserialized.headers.get("Authorization").unwrap(),
10508 "Bearer sk-test"
10509 );
10510 }
10511
10512 #[cfg(feature = "unstable_llm_providers")]
10513 #[test]
10514 fn test_set_provider_request_omits_empty_headers() {
10515 let request =
10516 SetProviderRequest::new("main", LlmProtocol::Anthropic, "https://api.anthropic.com");
10517
10518 let json = serde_json::to_value(&request).unwrap();
10519 assert!(!json.as_object().unwrap().contains_key("headers"));
10521 }
10522
10523 #[cfg(feature = "unstable_llm_providers")]
10524 #[test]
10525 fn test_disable_provider_request_serialization() {
10526 let request = DisableProviderRequest::new("secondary");
10527
10528 let json = serde_json::to_value(&request).unwrap();
10529 assert_eq!(json, json!({ "providerId": "secondary" }));
10530
10531 let deserialized: DisableProviderRequest = serde_json::from_value(json).unwrap();
10532 assert_eq!(deserialized.provider_id.to_string(), "secondary");
10533 }
10534
10535 #[cfg(feature = "unstable_llm_providers")]
10536 #[test]
10537 fn test_providers_capabilities_serialization() {
10538 let caps = ProvidersCapabilities::new();
10539
10540 let json = serde_json::to_value(&caps).unwrap();
10541 assert_eq!(json, json!({}));
10542
10543 let deserialized: ProvidersCapabilities = serde_json::from_value(json).unwrap();
10544 assert!(deserialized.meta.is_none());
10545 }
10546
10547 #[cfg(feature = "unstable_llm_providers")]
10548 #[test]
10549 fn test_agent_capabilities_with_providers() {
10550 let caps = AgentCapabilities::new().providers(ProvidersCapabilities::new());
10551
10552 let json = serde_json::to_value(&caps).unwrap();
10553 assert_eq!(json["providers"], json!({}));
10554
10555 let deserialized: AgentCapabilities = serde_json::from_value(json).unwrap();
10556 assert!(deserialized.providers.is_some());
10557 }
10558
10559 #[test]
10560 fn test_agent_capabilities_session_is_explicit() {
10561 let json = serde_json::to_value(AgentCapabilities::new()).unwrap();
10562 assert!(json.get("session").is_none());
10563
10564 let caps = AgentCapabilities::new().session(
10565 SessionCapabilities::new()
10566 .prompt(PromptCapabilities::new().image(PromptImageCapabilities::new()))
10567 .mcp(McpCapabilities::new().stdio(McpStdioCapabilities::new())),
10568 );
10569
10570 assert_eq!(
10571 serde_json::to_value(&caps).unwrap(),
10572 json!({
10573 "session": {
10574 "prompt": {
10575 "image": {}
10576 },
10577 "mcp": {
10578 "stdio": {}
10579 }
10580 }
10581 })
10582 );
10583
10584 let deserialized: AgentCapabilities = serde_json::from_value(json!({
10585 "session": false
10586 }))
10587 .unwrap();
10588 assert!(deserialized.session.is_none());
10589 }
10590
10591 #[test]
10592 fn test_prompt_capabilities_serialize_supported_content_as_objects() {
10593 let caps = PromptCapabilities::new()
10594 .image(PromptImageCapabilities::new())
10595 .audio(PromptAudioCapabilities::new())
10596 .embedded_context(PromptEmbeddedContextCapabilities::new());
10597
10598 assert_eq!(
10599 serde_json::to_value(&caps).unwrap(),
10600 json!({
10601 "image": {},
10602 "audio": {},
10603 "embeddedContext": {}
10604 })
10605 );
10606
10607 let deserialized: PromptCapabilities = serde_json::from_value(json!({
10608 "image": null,
10609 "audio": false,
10610 "embeddedContext": {}
10611 }))
10612 .unwrap();
10613 assert!(deserialized.image.is_none());
10614 assert!(deserialized.audio.is_none());
10615 assert!(deserialized.embedded_context.is_some());
10616 }
10617
10618 #[cfg(feature = "unstable_agent_skills")]
10619 #[test]
10620 fn prompt_skill_capability_has_two_levels() {
10621 let leading = PromptCapabilities::new().skill(PromptSkillCapabilities::new());
10623 assert_eq!(
10624 serde_json::to_value(&leading).unwrap(),
10625 json!({ "skill": {} })
10626 );
10627
10628 let inline = PromptCapabilities::new()
10629 .skill(PromptSkillCapabilities::new().inline(PromptSkillInlineCapabilities::new()));
10630 let wire = json!({ "skill": { "inline": {} } });
10631 assert_eq!(serde_json::to_value(&inline).unwrap(), wire);
10632 assert_eq!(
10633 serde_json::from_value::<PromptCapabilities>(wire).unwrap(),
10634 inline
10635 );
10636
10637 for unsupported in [
10638 json!({}),
10639 json!({ "skill": null }),
10640 json!({ "skill": false }),
10641 json!({ "skill": true }),
10642 ] {
10643 let caps: PromptCapabilities = serde_json::from_value(unsupported).unwrap();
10644 assert!(caps.skill.is_none());
10645 }
10646
10647 for leading_only in [
10649 json!({ "skill": { "inline": null } }),
10650 json!({ "skill": { "inline": true } }),
10651 ] {
10652 assert_eq!(
10653 serde_json::from_value::<PromptCapabilities>(leading_only).unwrap(),
10654 leading
10655 );
10656 }
10657 }
10658
10659 #[test]
10660 fn test_mcp_capabilities_serialize_supported_transports_as_objects() {
10661 let caps = McpCapabilities::new()
10662 .stdio(McpStdioCapabilities::new())
10663 .http(McpHttpCapabilities::new());
10664
10665 assert_eq!(
10666 serde_json::to_value(&caps).unwrap(),
10667 json!({
10668 "stdio": {},
10669 "http": {}
10670 })
10671 );
10672
10673 let deserialized: McpCapabilities = serde_json::from_value(json!({
10674 "stdio": null,
10675 "http": false
10676 }))
10677 .unwrap();
10678 assert!(deserialized.stdio.is_none());
10679 assert!(deserialized.http.is_none());
10680 }
10681
10682 #[cfg(feature = "unstable_mcp_over_acp")]
10683 #[test]
10684 fn test_mcp_capabilities_serialize_acp_support_as_object() {
10685 let caps = McpCapabilities::new().acp(McpAcpCapabilities::new());
10686
10687 assert_eq!(
10688 serde_json::to_value(&caps).unwrap(),
10689 json!({
10690 "acp": {}
10691 })
10692 );
10693 }
10694
10695 #[test]
10696 fn prompt_request_rejects_malformed_content_block() {
10697 use serde_json::json;
10698
10699 assert!(
10700 serde_json::from_value::<PromptRequest>(json!({
10701 "sessionId": "sess-1",
10702 "prompt": [{"type": "text"}]
10703 }))
10704 .is_err()
10705 );
10706 }
10707
10708 #[test]
10709 fn prompt_request_rejects_non_array_prompt() {
10710 use serde_json::json;
10711
10712 assert!(
10713 serde_json::from_value::<PromptRequest>(json!({
10714 "sessionId": "sess-1",
10715 "prompt": "hello"
10716 }))
10717 .is_err()
10718 );
10719 }
10720
10721 fn prompt_request_with_idempotency_key(key: &serde_json::Value) -> serde_json::Value {
10722 serde_json::json!({
10723 "sessionId": "sess-1",
10724 "idempotencyKey": key,
10725 "prompt": [{"type": "text", "text": "hello"}]
10726 })
10727 }
10728
10729 #[test]
10730 fn prompt_request_idempotency_key_round_trips() {
10731 use serde_json::json;
10732
10733 let key = "0b6f3c1e-8d2a-4c57-9a41-5e2f7d90c3ab";
10734 let value = prompt_request_with_idempotency_key(&json!(key));
10735
10736 let request: PromptRequest = serde_json::from_value(value.clone()).unwrap();
10737 assert_eq!(
10738 request.idempotency_key.as_ref().map(IdempotencyKey::as_str),
10739 Some(key)
10740 );
10741 assert_eq!(serde_json::to_value(&request).unwrap(), value);
10742
10743 let built = PromptRequest::new("sess-1", vec![ContentBlock::from("hello")])
10744 .idempotency_key(IdempotencyKey::new(key).unwrap());
10745 assert_eq!(built, request);
10746 }
10747
10748 #[test]
10749 fn prompt_request_omitted_and_null_idempotency_key_mean_no_key() {
10750 use serde_json::json;
10751
10752 let omitted = json!({
10753 "sessionId": "sess-1",
10754 "prompt": [{"type": "text", "text": "hello"}]
10755 });
10756 let request: PromptRequest = serde_json::from_value(omitted.clone()).unwrap();
10757 assert_eq!(request.idempotency_key, None);
10758 assert_eq!(serde_json::to_value(&request).unwrap(), omitted);
10760
10761 let null: PromptRequest =
10762 serde_json::from_value(prompt_request_with_idempotency_key(&json!(null))).unwrap();
10763 assert_eq!(null, request);
10764 }
10765
10766 #[test]
10767 fn prompt_request_rejects_malformed_idempotency_key() {
10768 use serde_json::json;
10769
10770 let too_long = "k".repeat(IdempotencyKey::MAX_LENGTH + 1);
10771 for (name, key) in [
10772 ("an empty string", json!("")),
10773 ("a string over 255 characters", json!(too_long)),
10774 ("a number", json!(7)),
10775 ("a boolean", json!(true)),
10776 ("an object", json!({"key": "k"})),
10777 ("an array", json!(["k"])),
10778 ] {
10779 assert!(
10780 serde_json::from_value::<PromptRequest>(prompt_request_with_idempotency_key(&key))
10781 .is_err(),
10782 "{name} must fail the request instead of being treated as no key"
10783 );
10784 }
10785 }
10786
10787 #[test]
10788 fn idempotency_key_length_is_counted_in_characters() {
10789 use serde_json::json;
10790
10791 assert_eq!(IdempotencyKey::new(""), Err(InvalidIdempotencyKey::Empty));
10792 assert_eq!(IdempotencyKey::new("k").unwrap().as_str(), "k");
10793
10794 let longest = "k".repeat(IdempotencyKey::MAX_LENGTH);
10795 assert_eq!(
10796 IdempotencyKey::new(longest.as_str()).unwrap().as_str(),
10797 longest
10798 );
10799 assert_eq!(
10800 IdempotencyKey::new(format!("{longest}k")),
10801 Err(InvalidIdempotencyKey::TooLong)
10802 );
10803
10804 let multibyte = "é".repeat(IdempotencyKey::MAX_LENGTH);
10806 assert!(IdempotencyKey::new(multibyte.as_str()).is_ok());
10807 assert!(
10808 serde_json::from_value::<PromptRequest>(prompt_request_with_idempotency_key(&json!(
10809 multibyte
10810 )))
10811 .is_ok()
10812 );
10813 assert_eq!(
10814 IdempotencyKey::new(format!("{multibyte}é")),
10815 Err(InvalidIdempotencyKey::TooLong)
10816 );
10817
10818 assert_eq!("k".parse::<IdempotencyKey>().unwrap().to_string(), "k");
10819 assert_eq!(
10820 IdempotencyKey::try_from(String::new()),
10821 Err(InvalidIdempotencyKey::Empty)
10822 );
10823 assert_eq!(
10824 InvalidIdempotencyKey::TooLong.to_string(),
10825 "idempotency key must be at most 255 characters"
10826 );
10827 }
10828
10829 #[cfg(feature = "uuid")]
10830 #[test]
10831 fn generated_idempotency_keys_are_distinct_valid_v4_uuids() {
10832 let first = IdempotencyKey::generate();
10833 let second = IdempotencyKey::generate();
10834 assert_ne!(first, second);
10835
10836 for key in [&first, &second] {
10837 let uuid = uuid::Uuid::parse_str(key.as_str()).unwrap();
10838 assert_eq!(uuid.get_version_num(), 4);
10839 assert_eq!(IdempotencyKey::new(key.as_str()).as_ref(), Ok(key));
10841 let request = PromptRequest::new("sess-1", vec![ContentBlock::from("hello")])
10842 .idempotency_key(key.clone());
10843 let value = serde_json::to_value(&request).unwrap();
10844 assert_eq!(value["idempotencyKey"], key.as_str());
10845 assert_eq!(
10846 serde_json::from_value::<PromptRequest>(value).unwrap(),
10847 request
10848 );
10849 }
10850
10851 assert_eq!(
10852 IdempotencyKey::from(uuid::Uuid::nil()).as_str(),
10853 "00000000-0000-0000-0000-000000000000"
10854 );
10855 }
10856
10857 #[cfg(feature = "schemars")]
10858 #[test]
10859 fn idempotency_key_schema_is_a_strict_bounded_string() {
10860 use serde_json::json;
10861
10862 let key = serde_json::to_value(schemars::schema_for!(IdempotencyKey)).unwrap();
10863 assert_eq!(key["type"], "string");
10864 assert_eq!(key["minLength"], 1);
10865 assert_eq!(key["maxLength"], json!(IdempotencyKey::MAX_LENGTH));
10866
10867 let request = serde_json::to_value(schemars::schema_for!(PromptRequest)).unwrap();
10868 assert_eq!(request["required"], json!(["sessionId", "prompt"]));
10869 let property = &request["properties"]["idempotencyKey"];
10870 assert_eq!(
10871 property["anyOf"],
10872 json!([{"$ref": "#/$defs/IdempotencyKey"}, {"type": "null"}])
10873 );
10874 assert!(property.get("x-deserialize-default-on-error").is_none());
10877 }
10878
10879 fn assert_session_setup_lists_are_strict<T>(base: &serde_json::Value)
10880 where
10881 T: serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
10882 {
10883 let name = std::any::type_name::<T>();
10884 let with = |field: &str, value: serde_json::Value| {
10885 let mut request = base.clone();
10886 request[field] = value;
10887 serde_json::from_value::<T>(request)
10888 };
10889
10890 for (field, value) in [
10891 (
10893 "mcpServers",
10894 json!([
10895 {"type": "stdio", "name": "github", "command": "/usr/bin/gh-mcp", "env": [{"name": "GITHUB_TOKEN", "value": null}]},
10896 {"type": "stdio", "name": "fs", "command": "/usr/bin/fs-mcp"}
10897 ]),
10898 ),
10899 ("mcpServers", json!({"type": "stdio", "name": "fs"})),
10900 ("additionalDirectories", json!(["/repo/lib", 42])),
10901 ("additionalDirectories", json!("/repo/lib")),
10902 ] {
10903 assert!(
10904 with(field, value.clone()).is_err(),
10905 "{name}.{field}: {value}"
10906 );
10907 }
10908
10909 let empty = serde_json::from_value::<T>(base.clone()).unwrap();
10910 for field in ["mcpServers", "additionalDirectories"] {
10911 assert_eq!(
10912 with(field, serde_json::Value::Null).unwrap(),
10913 empty,
10914 "{name}.{field}"
10915 );
10916 }
10917 }
10918
10919 #[test]
10920 fn session_setup_requests_reject_malformed_mcp_servers_and_directories() {
10921 assert_session_setup_lists_are_strict::<NewSessionRequest>(&json!({"cwd": "/repo"}));
10922 assert_session_setup_lists_are_strict::<ResumeSessionRequest>(&json!({
10923 "sessionId": "sess-1",
10924 "cwd": "/repo"
10925 }));
10926 #[cfg(feature = "unstable_session_fork")]
10927 assert_session_setup_lists_are_strict::<ForkSessionRequest>(&json!({
10928 "sessionId": "sess-1",
10929 "cwd": "/repo"
10930 }));
10931 }
10932
10933 #[test]
10934 fn resume_session_request_rejects_malformed_replay_from() {
10935 let request = |replay_from: serde_json::Value| {
10936 serde_json::from_value::<ResumeSessionRequest>(json!({
10937 "sessionId": "sess-1",
10938 "cwd": "/repo",
10939 "replayFrom": replay_from
10940 }))
10941 };
10942
10943 assert!(request(json!("start")).is_err());
10945 assert_eq!(request(serde_json::Value::Null).unwrap().replay_from, None);
10946 assert!(matches!(
10947 request(json!({"type": "start"})).unwrap().replay_from,
10948 Some(ReplayFrom::Start(_))
10949 ));
10950 }
10951
10952 #[test]
10953 fn mcp_server_lists_treat_null_as_empty() {
10954 let servers: Vec<McpServer> = serde_json::from_value(json!([
10955 {"type": "stdio", "name": "fs", "command": "/usr/bin/fs-mcp", "args": null, "env": null},
10956 {"type": "http", "name": "api", "url": "https://example.com/mcp", "headers": null}
10957 ]))
10958 .unwrap();
10959
10960 assert_eq!(
10961 servers,
10962 vec![
10963 McpServer::Stdio(McpServerStdio::new("fs", "/usr/bin/fs-mcp")),
10964 McpServer::Http(McpServerHttp::new("api", "https://example.com/mcp")),
10965 ]
10966 );
10967 }
10968
10969 #[test]
10970 fn terminal_auth_methods_reject_malformed_launch_config() {
10971 let response: InitializeResponse = serde_json::from_value(json!({
10975 "protocolVersion": 2,
10976 "info": {"name": "agent", "version": "1.0.0"},
10977 "authMethods": [
10978 {"type": "terminal", "methodId": "bad-args", "name": "Log in", "args": ["auth", "--port", 8123]},
10979 {"type": "terminal", "methodId": "bad-env", "name": "Log in", "env": [{"name": "DEBUG", "value": 1}]},
10980 {"type": "terminal", "methodId": "null-config", "name": "Log in", "args": null, "env": null},
10981 {"type": "agent", "methodId": "agent", "name": "Agent login"}
10982 ]
10983 }))
10984 .unwrap();
10985
10986 assert_eq!(
10987 response.auth_methods,
10988 vec![
10989 AuthMethod::Terminal(AuthMethodTerminal::new("null-config", "Log in")),
10990 AuthMethod::Agent(AuthMethodAgent::new("agent", "Agent login")),
10991 ]
10992 );
10993 }
10994
10995 #[cfg(feature = "unstable_auth_status")]
10996 #[test]
10997 fn auth_status_response_round_trips() {
10998 let response = AuthStatusResponse::new(AuthState::Authenticated).accounts(vec![
10999 AuthAccount::new("Anthropic API key")
11000 .description("API key helper".to_string())
11001 .active(true),
11002 AuthAccount::new("Claude Max").email("user@example.com".to_string()),
11003 ]);
11004 let json = serde_json::to_value(&response).unwrap();
11005 assert_eq!(
11006 json,
11007 json!({
11008 "state": "authenticated",
11009 "accounts": [
11010 {
11011 "label": "Anthropic API key",
11012 "description": "API key helper",
11013 "active": true
11014 },
11015 {
11016 "label": "Claude Max",
11017 "email": "user@example.com"
11018 }
11019 ]
11020 })
11021 );
11022 assert_eq!(
11023 serde_json::from_value::<AuthStatusResponse>(json).unwrap(),
11024 response
11025 );
11026 assert_eq!(
11027 serde_json::to_value(AuthStatusResponse::new(AuthState::NotRequired)).unwrap(),
11028 json!({"state": "not_required"})
11029 );
11030 }
11031
11032 #[cfg(feature = "unstable_auth_status")]
11033 #[test]
11034 fn auth_status_state_is_strict_and_accounts_are_lenient() {
11035 assert!(serde_json::from_value::<AuthStatusResponse>(json!({})).is_err());
11036 assert!(serde_json::from_value::<AuthStatusResponse>(json!({"state": null})).is_err());
11037 assert!(serde_json::from_value::<AuthStatusResponse>(json!({"state": 1})).is_err());
11038
11039 let response: AuthStatusResponse = serde_json::from_value(json!({
11040 "state": "_vendor_state",
11041 "accounts": [
11042 {"active": true},
11043 {
11044 "label": "Vertex AI",
11045 "description": 42,
11046 "active": "yes",
11047 "email": ["not", "a", "string"]
11048 }
11049 ]
11050 }))
11051 .unwrap();
11052 assert_eq!(
11053 response,
11054 AuthStatusResponse::new(AuthState::Other("_vendor_state".to_string()))
11055 .accounts(vec![AuthAccount::new("Vertex AI")])
11056 );
11057 assert_eq!(
11058 serde_json::from_value::<AuthStatusResponse>(
11059 json!({"state": "unknown", "accounts": null})
11060 )
11061 .unwrap(),
11062 AuthStatusResponse::new(AuthState::Unknown)
11063 );
11064 }
11065
11066 #[cfg(feature = "unstable_auth_status")]
11067 #[test]
11068 fn auth_status_update_notification_routes() {
11069 use crate::v2::{AgentNotification, CLIENT_METHOD_NAMES};
11070
11071 assert_eq!(AGENT_METHOD_NAMES.auth_status, "auth/status");
11072 assert_eq!(CLIENT_METHOD_NAMES.auth_status_update, "auth/status_update");
11073 let notification = AgentNotification::AuthStatusUpdateNotification(Box::new(
11074 AuthStatusUpdateNotification::new(AuthState::Unauthenticated),
11075 ));
11076 assert_eq!(notification.method(), "auth/status_update");
11077 assert_eq!(
11078 serde_json::to_value(¬ification).unwrap(),
11079 json!({"state": "unauthenticated"})
11080 );
11081 }
11082
11083 #[cfg(all(
11084 feature = "unstable_session_fork",
11085 feature = "unstable_session_cursors"
11086 ))]
11087 #[test]
11088 fn fork_session_request_cursor_id_is_optional_and_strict() {
11089 let request = ForkSessionRequest::new("sess_abc123", "/home/user/project")
11090 .cursor_id(CursorId::new("cur_1"));
11091 let wire = json!({
11092 "sessionId": "sess_abc123",
11093 "cursorId": "cur_1",
11094 "cwd": "/home/user/project"
11095 });
11096 assert_eq!(serde_json::to_value(&request).unwrap(), wire);
11097 assert_eq!(
11098 serde_json::from_value::<ForkSessionRequest>(wire).unwrap(),
11099 request
11100 );
11101
11102 for wire in [
11104 json!({ "sessionId": "sess_abc123", "cwd": "/home/user/project" }),
11105 json!({ "sessionId": "sess_abc123", "cwd": "/home/user/project", "cursorId": null }),
11106 ] {
11107 assert_eq!(
11108 serde_json::from_value::<ForkSessionRequest>(wire)
11109 .unwrap()
11110 .cursor_id,
11111 None
11112 );
11113 }
11114
11115 assert!(
11117 serde_json::from_value::<ForkSessionRequest>(json!({
11118 "sessionId": "sess_abc123",
11119 "cwd": "/home/user/project",
11120 "cursorId": 7
11121 }))
11122 .is_err()
11123 );
11124 }
11125}