1use std::{borrow::Cow, sync::Arc};
7
8use derive_more::{Display, From};
9use indexmap::IndexMap;
10#[cfg(feature = "schemars")]
11use schemars::Schema;
12use serde::{Deserialize, Serialize};
13use serde_with::{DefaultOnError, DefaultOnNull, VecSkipError, serde_as, skip_serializing_none};
14
15use super::{
16 AbsolutePath, AvailableCommand, ClientCapabilities, ContentBlock, Error, ExtNotification,
17 ExtRequest, ExtResponse, MessageId, Meta, SessionId, TerminalId, ToolCallId,
18};
19use crate::{IntoOption, ProtocolVersion};
20
21#[cfg(all(
22 feature = "unstable_session_fork",
23 feature = "unstable_session_cursors"
24))]
25use super::CursorId;
26#[cfg(feature = "unstable_session_status")]
27use super::StateUpdate;
28
29#[cfg(all(feature = "unstable_auth_status", feature = "schemars"))]
30use super::AUTH_STATUS_UPDATE_NOTIFICATION;
31#[cfg(feature = "unstable_mcp_over_acp")]
32use super::mcp::{MCP_MESSAGE_METHOD_NAME, MessageMcpNotification};
33
34#[serde_as]
42#[skip_serializing_none]
43#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
44#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
45#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = INITIALIZE_METHOD_NAME)))]
46#[serde(rename_all = "camelCase")]
47#[non_exhaustive]
48pub struct InitializeRequest {
49 pub protocol_version: ProtocolVersion,
51 pub info: Implementation,
53 #[serde_as(deserialize_as = "DefaultOnError")]
55 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
56 #[serde(default)]
57 pub capabilities: ClientCapabilities,
58 #[serde_as(deserialize_as = "DefaultOnError")]
64 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
65 #[serde(default)]
66 #[serde(rename = "_meta")]
67 pub meta: Option<Meta>,
68}
69
70impl InitializeRequest {
71 #[must_use]
73 pub fn new(protocol_version: ProtocolVersion, info: Implementation) -> Self {
74 Self {
75 protocol_version,
76 capabilities: ClientCapabilities::default(),
77 info,
78 meta: None,
79 }
80 }
81
82 #[must_use]
84 pub fn capabilities(mut self, capabilities: ClientCapabilities) -> Self {
85 self.capabilities = capabilities;
86 self
87 }
88
89 #[must_use]
95 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
96 self.meta = meta.into_option();
97 self
98 }
99}
100
101#[serde_as]
107#[skip_serializing_none]
108#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
109#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
110#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = INITIALIZE_METHOD_NAME)))]
111#[serde(rename_all = "camelCase")]
112#[non_exhaustive]
113pub struct InitializeResponse {
114 pub protocol_version: ProtocolVersion,
121 pub info: Implementation,
123 #[serde_as(deserialize_as = "DefaultOnError")]
125 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
126 #[serde(default)]
127 pub capabilities: AgentCapabilities,
128 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
134 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
135 #[serde(default, skip_serializing_if = "Vec::is_empty")]
136 pub auth_methods: Vec<AuthMethod>,
137 #[serde_as(deserialize_as = "DefaultOnError")]
143 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
144 #[serde(default)]
145 #[serde(rename = "_meta")]
146 pub meta: Option<Meta>,
147}
148
149impl InitializeResponse {
150 #[must_use]
152 pub fn new(protocol_version: ProtocolVersion, info: Implementation) -> Self {
153 Self {
154 protocol_version,
155 capabilities: AgentCapabilities::default(),
156 auth_methods: vec![],
157 info,
158 meta: None,
159 }
160 }
161
162 #[must_use]
164 pub fn capabilities(mut self, capabilities: AgentCapabilities) -> Self {
165 self.capabilities = capabilities;
166 self
167 }
168
169 #[must_use]
174 pub fn auth_methods(mut self, auth_methods: Vec<AuthMethod>) -> Self {
175 self.auth_methods = auth_methods;
176 self
177 }
178
179 #[must_use]
185 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
186 self.meta = meta.into_option();
187 self
188 }
189}
190
191#[serde_as]
195#[skip_serializing_none]
196#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
197#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
198#[serde(rename_all = "camelCase")]
199#[non_exhaustive]
200pub struct Implementation {
201 pub name: String,
204 #[serde_as(deserialize_as = "DefaultOnError")]
211 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
212 #[serde(default)]
213 pub title: Option<String>,
214 pub version: String,
217 #[serde_as(deserialize_as = "DefaultOnError")]
223 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
224 #[serde(default)]
225 #[serde(rename = "_meta")]
226 pub meta: Option<Meta>,
227}
228
229impl Implementation {
230 #[must_use]
232 pub fn new(name: impl Into<String>, version: impl Into<String>) -> Self {
233 Self {
234 name: name.into(),
235 title: None,
236 version: version.into(),
237 meta: None,
238 }
239 }
240
241 #[must_use]
246 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
247 self.title = title.into_option();
248 self
249 }
250
251 #[must_use]
257 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
258 self.meta = meta.into_option();
259 self
260 }
261}
262
263#[serde_as]
273#[skip_serializing_none]
274#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
275#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
276#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGIN_METHOD_NAME)))]
277#[serde(rename_all = "camelCase")]
278#[non_exhaustive]
279pub struct LoginAuthRequest {
280 pub method_id: AuthMethodId,
283 #[serde_as(deserialize_as = "DefaultOnError")]
289 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
290 #[serde(default)]
291 #[serde(rename = "_meta")]
292 pub meta: Option<Meta>,
293}
294
295impl LoginAuthRequest {
296 #[must_use]
298 pub fn new(method_id: impl Into<AuthMethodId>) -> Self {
299 Self {
300 method_id: method_id.into(),
301 meta: None,
302 }
303 }
304
305 #[must_use]
311 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
312 self.meta = meta.into_option();
313 self
314 }
315}
316
317crate::serde_util::default_on_null! {
318 #[serde_as]
320 #[skip_serializing_none]
321 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
322 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
323 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGIN_METHOD_NAME)))]
324 #[serde(rename_all = "camelCase")]
325 #[non_exhaustive]
326 pub struct LoginAuthResponse {
327 #[serde_as(deserialize_as = "DefaultOnError")]
333 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
334 #[serde(default)]
335 #[serde(rename = "_meta")]
336 pub meta: Option<Meta>,
337 }
338}
339
340impl LoginAuthResponse {
341 #[must_use]
343 pub fn new() -> Self {
344 Self::default()
345 }
346
347 #[must_use]
353 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
354 self.meta = meta.into_option();
355 self
356 }
357}
358
359crate::serde_util::default_on_null! {
362 #[serde_as]
370 #[skip_serializing_none]
371 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
372 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
373 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGOUT_METHOD_NAME)))]
374 #[serde(rename_all = "camelCase")]
375 #[non_exhaustive]
376 pub struct LogoutAuthRequest {
377 #[serde_as(deserialize_as = "DefaultOnError")]
383 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
384 #[serde(default)]
385 #[serde(rename = "_meta")]
386 pub meta: Option<Meta>,
387 }
388}
389
390impl LogoutAuthRequest {
391 #[must_use]
393 pub fn new() -> Self {
394 Self::default()
395 }
396
397 #[must_use]
403 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
404 self.meta = meta.into_option();
405 self
406 }
407}
408
409crate::serde_util::default_on_null! {
410 #[serde_as]
412 #[skip_serializing_none]
413 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
414 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
415 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGOUT_METHOD_NAME)))]
416 #[serde(rename_all = "camelCase")]
417 #[non_exhaustive]
418 pub struct LogoutAuthResponse {
419 #[serde_as(deserialize_as = "DefaultOnError")]
425 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
426 #[serde(default)]
427 #[serde(rename = "_meta")]
428 pub meta: Option<Meta>,
429 }
430}
431
432impl LogoutAuthResponse {
433 #[must_use]
435 pub fn new() -> Self {
436 Self::default()
437 }
438
439 #[must_use]
445 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
446 self.meta = meta.into_option();
447 self
448 }
449}
450
451#[cfg(feature = "unstable_auth_status")]
454crate::serde_util::default_on_null! {
455 #[serde_as]
466 #[skip_serializing_none]
467 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
468 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
469 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_STATUS_METHOD_NAME)))]
470 #[serde(rename_all = "camelCase")]
471 #[non_exhaustive]
472 pub struct AuthStatusRequest {
473 #[serde_as(deserialize_as = "DefaultOnError")]
479 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
480 #[serde(default)]
481 #[serde(rename = "_meta")]
482 pub meta: Option<Meta>,
483 }
484}
485
486#[cfg(feature = "unstable_auth_status")]
487impl AuthStatusRequest {
488 #[must_use]
490 pub fn new() -> Self {
491 Self::default()
492 }
493
494 #[must_use]
500 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
501 self.meta = meta.into_option();
502 self
503 }
504}
505
506#[cfg(feature = "unstable_auth_status")]
512#[serde_as]
513#[skip_serializing_none]
514#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
515#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
516#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_STATUS_METHOD_NAME)))]
517#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"agent": [{"action": "replace", "target": "authStatus"}]})))]
518#[serde(rename_all = "camelCase")]
519#[non_exhaustive]
520pub struct AuthStatusResponse {
521 pub state: AuthState,
526 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
532 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
533 #[serde(default, skip_serializing_if = "Vec::is_empty")]
534 pub accounts: Vec<AuthAccount>,
535 #[serde_as(deserialize_as = "DefaultOnError")]
541 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
542 #[serde(default)]
543 #[serde(rename = "_meta")]
544 pub meta: Option<Meta>,
545}
546
547#[cfg(feature = "unstable_auth_status")]
548impl AuthStatusResponse {
549 #[must_use]
551 pub fn new(state: AuthState) -> Self {
552 Self {
553 state,
554 accounts: vec![],
555 meta: None,
556 }
557 }
558
559 #[must_use]
561 pub fn accounts(mut self, accounts: Vec<AuthAccount>) -> Self {
562 self.accounts = accounts;
563 self
564 }
565
566 #[must_use]
572 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
573 self.meta = meta.into_option();
574 self
575 }
576}
577
578#[cfg(feature = "unstable_auth_status")]
588#[serde_as]
589#[skip_serializing_none]
590#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
591#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
592#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = AUTH_STATUS_UPDATE_NOTIFICATION)))]
593#[cfg_attr(feature = "schemars", schemars(extend("x-scope" = {})))]
594#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"agent": [{"action": "replace", "target": "authStatus"}]})))]
595#[serde(rename_all = "camelCase")]
596#[non_exhaustive]
597pub struct AuthStatusUpdateNotification {
598 pub state: AuthState,
603 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
609 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
610 #[serde(default, skip_serializing_if = "Vec::is_empty")]
611 pub accounts: Vec<AuthAccount>,
612 #[serde_as(deserialize_as = "DefaultOnError")]
618 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
619 #[serde(default)]
620 #[serde(rename = "_meta")]
621 pub meta: Option<Meta>,
622}
623
624#[cfg(feature = "unstable_auth_status")]
625impl AuthStatusUpdateNotification {
626 #[must_use]
628 pub fn new(state: AuthState) -> Self {
629 Self {
630 state,
631 accounts: vec![],
632 meta: None,
633 }
634 }
635
636 #[must_use]
638 pub fn accounts(mut self, accounts: Vec<AuthAccount>) -> Self {
639 self.accounts = accounts;
640 self
641 }
642
643 #[must_use]
649 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
650 self.meta = meta.into_option();
651 self
652 }
653}
654
655#[cfg(feature = "unstable_auth_status")]
661#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
662#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
663#[serde(rename_all = "snake_case")]
664#[non_exhaustive]
665pub enum AuthState {
666 Authenticated,
668 Unauthenticated,
671 NotRequired,
673 Unknown,
675 #[serde(untagged)]
681 Other(String),
682}
683
684#[cfg(feature = "unstable_auth_status")]
695#[serde_as]
696#[skip_serializing_none]
697#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
698#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
699#[serde(rename_all = "camelCase")]
700#[non_exhaustive]
701pub struct AuthAccount {
702 pub label: String,
705 #[serde_as(deserialize_as = "DefaultOnError")]
710 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
711 #[serde(default)]
712 pub description: Option<String>,
713 #[serde_as(deserialize_as = "DefaultOnError")]
719 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
720 #[serde(default)]
721 pub active: Option<bool>,
722 #[serde_as(deserialize_as = "DefaultOnError")]
726 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
727 #[serde(default)]
728 pub name: Option<String>,
729 #[serde_as(deserialize_as = "DefaultOnError")]
733 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
734 #[serde(default)]
735 pub email: Option<String>,
736 #[serde_as(deserialize_as = "DefaultOnError")]
740 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
741 #[serde(default)]
742 pub organization: Option<String>,
743 #[serde_as(deserialize_as = "DefaultOnError")]
749 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
750 #[serde(default)]
751 #[serde(rename = "_meta")]
752 pub meta: Option<Meta>,
753}
754
755#[cfg(feature = "unstable_auth_status")]
756impl AuthAccount {
757 #[must_use]
759 pub fn new(label: impl Into<String>) -> Self {
760 Self {
761 label: label.into(),
762 description: None,
763 active: None,
764 name: None,
765 email: None,
766 organization: None,
767 meta: None,
768 }
769 }
770
771 #[must_use]
773 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
774 self.description = description.into_option();
775 self
776 }
777
778 #[must_use]
780 pub fn active(mut self, active: impl IntoOption<bool>) -> Self {
781 self.active = active.into_option();
782 self
783 }
784
785 #[must_use]
787 pub fn name(mut self, name: impl IntoOption<String>) -> Self {
788 self.name = name.into_option();
789 self
790 }
791
792 #[must_use]
794 pub fn email(mut self, email: impl IntoOption<String>) -> Self {
795 self.email = email.into_option();
796 self
797 }
798
799 #[must_use]
801 pub fn organization(mut self, organization: impl IntoOption<String>) -> Self {
802 self.organization = organization.into_option();
803 self
804 }
805
806 #[must_use]
812 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
813 self.meta = meta.into_option();
814 self
815 }
816}
817
818#[cfg(feature = "unstable_auth_status")]
826#[serde_as]
827#[skip_serializing_none]
828#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
829#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
830#[non_exhaustive]
831pub struct AuthStatusCapabilities {
832 #[serde_as(deserialize_as = "DefaultOnError")]
838 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
839 #[serde(default)]
840 #[serde(rename = "_meta")]
841 pub meta: Option<Meta>,
842}
843
844#[cfg(feature = "unstable_auth_status")]
845impl AuthStatusCapabilities {
846 #[must_use]
848 pub fn new() -> Self {
849 Self::default()
850 }
851
852 #[must_use]
858 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
859 self.meta = meta.into_option();
860 self
861 }
862}
863
864#[serde_as]
870#[skip_serializing_none]
871#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
872#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
873#[serde(rename_all = "camelCase")]
874#[non_exhaustive]
875pub struct AgentAuthCapabilities {
876 #[cfg(feature = "unstable_auth_status")]
885 #[serde_as(deserialize_as = "DefaultOnError")]
886 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
887 #[serde(default)]
888 pub status: Option<AuthStatusCapabilities>,
889 #[serde_as(deserialize_as = "DefaultOnError")]
895 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
896 #[serde(default)]
897 #[serde(rename = "_meta")]
898 pub meta: Option<Meta>,
899}
900
901impl AgentAuthCapabilities {
902 #[must_use]
904 pub fn new() -> Self {
905 Self::default()
906 }
907
908 #[cfg(feature = "unstable_auth_status")]
914 #[must_use]
915 pub fn status(mut self, status: impl IntoOption<AuthStatusCapabilities>) -> Self {
916 self.status = status.into_option();
917 self
918 }
919
920 #[must_use]
926 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
927 self.meta = meta.into_option();
928 self
929 }
930}
931
932#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
934#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
935#[serde(transparent)]
936#[from(forward)]
937#[non_exhaustive]
938pub struct AuthMethodId(pub Arc<str>);
939
940impl AuthMethodId {
941 #[must_use]
943 pub fn new(id: impl Into<Self>) -> Self {
944 id.into()
945 }
946}
947
948#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
952#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
953#[serde(tag = "type", rename_all = "snake_case")]
954#[non_exhaustive]
955pub enum AuthMethod {
956 Terminal(AuthMethodTerminal),
959 Agent(AuthMethodAgent),
963 #[serde(untagged)]
973 Other(OtherAuthMethod),
974}
975
976impl AuthMethod {
977 #[must_use]
979 pub fn method_id(&self) -> &AuthMethodId {
980 match self {
981 Self::Agent(a) => &a.method_id,
982 Self::Other(a) => &a.method_id,
983 Self::Terminal(t) => &t.method_id,
984 }
985 }
986
987 #[must_use]
989 pub fn name(&self) -> &str {
990 match self {
991 Self::Agent(a) => &a.name,
992 Self::Other(a) => &a.name,
993 Self::Terminal(t) => &t.name,
994 }
995 }
996
997 #[must_use]
999 pub fn description(&self) -> Option<&str> {
1000 match self {
1001 Self::Agent(a) => a.description.as_deref(),
1002 Self::Other(a) => a
1003 .fields
1004 .get("description")
1005 .and_then(serde_json::Value::as_str),
1006 Self::Terminal(t) => t.description.as_deref(),
1007 }
1008 }
1009
1010 #[must_use]
1016 pub fn meta(&self) -> Option<&Meta> {
1017 match self {
1018 Self::Agent(a) => a.meta.as_ref(),
1019 Self::Other(a) => a.fields.get("_meta").and_then(serde_json::Value::as_object),
1020 Self::Terminal(t) => t.meta.as_ref(),
1021 }
1022 }
1023}
1024
1025#[serde_as]
1027#[skip_serializing_none]
1028#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1029#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1030#[cfg_attr(feature = "schemars", schemars(inline))]
1031#[cfg_attr(feature = "schemars", schemars(transform = other_auth_method_schema))]
1032#[serde(rename_all = "camelCase")]
1033#[non_exhaustive]
1034pub struct OtherAuthMethod {
1035 #[serde(rename = "type")]
1041 pub type_: String,
1042 pub method_id: AuthMethodId,
1044 pub name: String,
1046 #[serde(flatten)]
1049 pub fields: IndexMap<String, serde_json::Value>,
1050}
1051
1052impl OtherAuthMethod {
1053 #[must_use]
1055 pub fn new(
1056 type_: impl Into<String>,
1057 method_id: impl Into<AuthMethodId>,
1058 name: impl Into<String>,
1059 mut fields: IndexMap<String, serde_json::Value>,
1060 ) -> Self {
1061 fields.shift_remove("type");
1062 fields.shift_remove("methodId");
1063 fields.shift_remove("name");
1064 Self {
1065 type_: type_.into(),
1066 method_id: method_id.into(),
1067 name: name.into(),
1068 fields,
1069 }
1070 }
1071}
1072
1073impl<'de> Deserialize<'de> for OtherAuthMethod {
1074 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1075 where
1076 D: serde::Deserializer<'de>,
1077 {
1078 #[derive(Deserialize)]
1079 #[serde(rename_all = "camelCase")]
1080 struct RawOtherAuthMethod {
1081 #[serde(rename = "type")]
1082 type_: String,
1083 method_id: AuthMethodId,
1084 name: String,
1085 #[serde(flatten)]
1086 fields: IndexMap<String, serde_json::Value>,
1087 }
1088
1089 let raw = RawOtherAuthMethod::deserialize(deserializer)?;
1090 if is_known_auth_method_type(&raw.type_) {
1091 return Err(serde::de::Error::custom(format!(
1092 "known authentication method `{}` did not match its schema",
1093 raw.type_
1094 )));
1095 }
1096
1097 Ok(Self {
1098 type_: raw.type_,
1099 method_id: raw.method_id,
1100 name: raw.name,
1101 fields: raw.fields,
1102 })
1103 }
1104}
1105
1106fn is_known_auth_method_type(type_: &str) -> bool {
1107 matches!(type_, "agent" | "terminal")
1108}
1109
1110#[cfg(feature = "schemars")]
1111fn other_auth_method_schema(schema: &mut Schema) {
1112 super::schema_util::reject_known_string_discriminators(schema, "type", &["agent", "terminal"]);
1113}
1114
1115#[serde_as]
1119#[skip_serializing_none]
1120#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1121#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1122#[serde(rename_all = "camelCase")]
1123#[non_exhaustive]
1124pub struct AuthMethodAgent {
1125 pub method_id: AuthMethodId,
1127 pub name: String,
1129 #[serde_as(deserialize_as = "DefaultOnError")]
1133 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1134 #[serde(default)]
1135 pub description: Option<String>,
1136 #[serde_as(deserialize_as = "DefaultOnError")]
1142 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1143 #[serde(default)]
1144 #[serde(rename = "_meta")]
1145 pub meta: Option<Meta>,
1146}
1147
1148impl AuthMethodAgent {
1149 #[must_use]
1151 pub fn new(method_id: impl Into<AuthMethodId>, name: impl Into<String>) -> Self {
1152 Self {
1153 method_id: method_id.into(),
1154 name: name.into(),
1155 description: None,
1156 meta: None,
1157 }
1158 }
1159
1160 #[must_use]
1162 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
1163 self.description = description.into_option();
1164 self
1165 }
1166
1167 #[must_use]
1173 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1174 self.meta = meta.into_option();
1175 self
1176 }
1177}
1178
1179#[serde_as]
1187#[skip_serializing_none]
1188#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1189#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1190#[serde(rename_all = "camelCase")]
1191#[non_exhaustive]
1192pub struct AuthMethodTerminal {
1193 pub method_id: AuthMethodId,
1195 pub name: String,
1197 #[serde_as(deserialize_as = "DefaultOnError")]
1201 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1202 #[serde(default)]
1203 pub description: Option<String>,
1204 #[serde_as(deserialize_as = "DefaultOnNull")]
1206 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1207 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1208 pub args: Vec<String>,
1209 #[serde_as(deserialize_as = "DefaultOnNull")]
1213 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1214 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1215 pub env: Vec<EnvVariable>,
1216 #[serde_as(deserialize_as = "DefaultOnError")]
1222 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1223 #[serde(default)]
1224 #[serde(rename = "_meta")]
1225 pub meta: Option<Meta>,
1226}
1227
1228impl AuthMethodTerminal {
1229 #[must_use]
1231 pub fn new(method_id: impl Into<AuthMethodId>, name: impl Into<String>) -> Self {
1232 Self {
1233 method_id: method_id.into(),
1234 name: name.into(),
1235 description: None,
1236 args: Vec::new(),
1237 env: Vec::new(),
1238 meta: None,
1239 }
1240 }
1241
1242 #[must_use]
1244 pub fn args(mut self, args: Vec<String>) -> Self {
1245 self.args = args;
1246 self
1247 }
1248
1249 #[must_use]
1253 pub fn env(mut self, env: Vec<EnvVariable>) -> Self {
1254 self.env = env;
1255 self
1256 }
1257
1258 #[must_use]
1260 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
1261 self.description = description.into_option();
1262 self
1263 }
1264
1265 #[must_use]
1271 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1272 self.meta = meta.into_option();
1273 self
1274 }
1275}
1276
1277#[serde_as]
1283#[skip_serializing_none]
1284#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1285#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1286#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_NEW_METHOD_NAME)))]
1287#[serde(rename_all = "camelCase")]
1288#[non_exhaustive]
1289pub struct NewSessionRequest {
1290 pub cwd: AbsolutePath,
1292 #[serde_as(deserialize_as = "DefaultOnNull")]
1298 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1299 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1300 pub additional_directories: Vec<AbsolutePath>,
1301 #[serde_as(deserialize_as = "DefaultOnNull")]
1303 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1304 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1305 pub mcp_servers: Vec<McpServer>,
1306 #[serde(default)]
1312 pub system_prompt: Option<SystemPrompt>,
1313 #[cfg(feature = "unstable_session_options")]
1331 #[serde_as(deserialize_as = "DefaultOnNull")]
1332 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1333 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1334 pub config_options: Vec<InitialSessionConfigOption>,
1335 #[serde_as(deserialize_as = "DefaultOnError")]
1341 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1342 #[serde(default)]
1343 #[serde(rename = "_meta")]
1344 pub meta: Option<Meta>,
1345}
1346
1347impl NewSessionRequest {
1348 #[must_use]
1350 pub fn new(cwd: impl Into<AbsolutePath>) -> Self {
1351 Self {
1352 cwd: cwd.into(),
1353 additional_directories: vec![],
1354 mcp_servers: vec![],
1355 system_prompt: None,
1356 #[cfg(feature = "unstable_session_options")]
1357 config_options: vec![],
1358 meta: None,
1359 }
1360 }
1361
1362 #[must_use]
1364 pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1365 where
1366 I: IntoIterator<Item = P>,
1367 P: Into<AbsolutePath>,
1368 {
1369 self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1370 self
1371 }
1372
1373 #[must_use]
1375 pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1376 self.mcp_servers = mcp_servers;
1377 self
1378 }
1379
1380 #[must_use]
1382 pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1383 self.system_prompt = system_prompt.into_option();
1384 self
1385 }
1386
1387 #[cfg(feature = "unstable_session_options")]
1405 #[must_use]
1406 pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1407 self.config_options = config_options;
1408 self
1409 }
1410
1411 #[must_use]
1417 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1418 self.meta = meta.into_option();
1419 self
1420 }
1421}
1422
1423#[serde_as]
1434#[skip_serializing_none]
1435#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1436#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1437#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_NEW_METHOD_NAME)))]
1438#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}, {"action": "replace", "target": "availableCommands", "value": "availableCommands"}]})))]
1439#[serde(rename_all = "camelCase")]
1440#[non_exhaustive]
1441pub struct NewSessionResponse {
1442 pub session_id: SessionId,
1446 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1452 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1453 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1454 pub config_options: Vec<SessionConfigOption>,
1455 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1461 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1462 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1463 pub available_commands: Vec<AvailableCommand>,
1464 #[serde_as(deserialize_as = "DefaultOnError")]
1470 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1471 #[serde(default)]
1472 #[serde(rename = "_meta")]
1473 pub meta: Option<Meta>,
1474}
1475
1476impl NewSessionResponse {
1477 #[must_use]
1479 pub fn new(session_id: impl Into<SessionId>) -> Self {
1480 Self {
1481 session_id: session_id.into(),
1482 config_options: Vec::new(),
1483 available_commands: Vec::new(),
1484 meta: None,
1485 }
1486 }
1487
1488 #[must_use]
1494 pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
1495 self.config_options = config_options;
1496 self
1497 }
1498
1499 #[must_use]
1501 pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
1502 self.available_commands = available_commands;
1503 self
1504 }
1505
1506 #[must_use]
1512 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1513 self.meta = meta.into_option();
1514 self
1515 }
1516}
1517
1518#[cfg(feature = "unstable_session_fork")]
1531#[serde_as]
1532#[skip_serializing_none]
1533#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1534#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1535#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_FORK_METHOD_NAME)))]
1536#[serde(rename_all = "camelCase")]
1537#[non_exhaustive]
1538pub struct ForkSessionRequest {
1539 pub session_id: SessionId,
1541 #[cfg(feature = "unstable_session_cursors")]
1554 #[serde(default)]
1555 pub cursor_id: Option<CursorId>,
1556 pub cwd: AbsolutePath,
1558 #[serde_as(deserialize_as = "DefaultOnNull")]
1564 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1565 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1566 pub additional_directories: Vec<AbsolutePath>,
1567 #[serde_as(deserialize_as = "DefaultOnNull")]
1569 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1570 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1571 pub mcp_servers: Vec<McpServer>,
1572 #[serde(default)]
1580 pub system_prompt: Option<SystemPrompt>,
1581 #[cfg(feature = "unstable_session_options")]
1600 #[serde_as(deserialize_as = "DefaultOnNull")]
1601 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1602 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1603 pub config_options: Vec<InitialSessionConfigOption>,
1604 #[serde_as(deserialize_as = "DefaultOnError")]
1610 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1611 #[serde(default)]
1612 #[serde(rename = "_meta")]
1613 pub meta: Option<Meta>,
1614}
1615
1616#[cfg(feature = "unstable_session_fork")]
1617impl ForkSessionRequest {
1618 #[must_use]
1620 pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
1621 Self {
1622 session_id: session_id.into(),
1623 #[cfg(feature = "unstable_session_cursors")]
1624 cursor_id: None,
1625 cwd: cwd.into(),
1626 additional_directories: vec![],
1627 mcp_servers: vec![],
1628 system_prompt: None,
1629 #[cfg(feature = "unstable_session_options")]
1630 config_options: vec![],
1631 meta: None,
1632 }
1633 }
1634
1635 #[cfg(feature = "unstable_session_cursors")]
1644 #[must_use]
1645 pub fn cursor_id(mut self, cursor_id: impl IntoOption<CursorId>) -> Self {
1646 self.cursor_id = cursor_id.into_option();
1647 self
1648 }
1649
1650 #[must_use]
1652 pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1653 where
1654 I: IntoIterator<Item = P>,
1655 P: Into<AbsolutePath>,
1656 {
1657 self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1658 self
1659 }
1660
1661 #[must_use]
1663 pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1664 self.mcp_servers = mcp_servers;
1665 self
1666 }
1667
1668 #[must_use]
1670 pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1671 self.system_prompt = system_prompt.into_option();
1672 self
1673 }
1674
1675 #[cfg(feature = "unstable_session_options")]
1694 #[must_use]
1695 pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1696 self.config_options = config_options;
1697 self
1698 }
1699
1700 #[must_use]
1706 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1707 self.meta = meta.into_option();
1708 self
1709 }
1710}
1711
1712#[cfg(feature = "unstable_session_fork")]
1718#[serde_as]
1719#[skip_serializing_none]
1720#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1721#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1722#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_FORK_METHOD_NAME)))]
1723#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}, {"action": "replace", "target": "availableCommands", "value": "availableCommands"}]})))]
1724#[serde(rename_all = "camelCase")]
1725#[non_exhaustive]
1726pub struct ForkSessionResponse {
1727 pub session_id: SessionId,
1729 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1735 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1736 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1737 pub config_options: Vec<SessionConfigOption>,
1738 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1744 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1745 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1746 pub available_commands: Vec<AvailableCommand>,
1747 #[serde_as(deserialize_as = "DefaultOnError")]
1753 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1754 #[serde(default)]
1755 #[serde(rename = "_meta")]
1756 pub meta: Option<Meta>,
1757}
1758
1759#[cfg(feature = "unstable_session_fork")]
1760impl ForkSessionResponse {
1761 #[must_use]
1763 pub fn new(session_id: impl Into<SessionId>) -> Self {
1764 Self {
1765 session_id: session_id.into(),
1766 config_options: Vec::new(),
1767 available_commands: Vec::new(),
1768 meta: None,
1769 }
1770 }
1771
1772 #[must_use]
1778 pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
1779 self.config_options = config_options;
1780 self
1781 }
1782
1783 #[must_use]
1785 pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
1786 self.available_commands = available_commands;
1787 self
1788 }
1789
1790 #[must_use]
1796 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1797 self.meta = meta.into_option();
1798 self
1799 }
1800}
1801
1802#[serde_as]
1809#[skip_serializing_none]
1810#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1811#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1812#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_RESUME_METHOD_NAME)))]
1813#[serde(rename_all = "camelCase")]
1814#[non_exhaustive]
1815pub struct ResumeSessionRequest {
1816 pub session_id: SessionId,
1818 pub cwd: AbsolutePath,
1823 #[serde_as(deserialize_as = "DefaultOnNull")]
1830 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1831 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1832 pub additional_directories: Vec<AbsolutePath>,
1833 #[serde_as(deserialize_as = "DefaultOnNull")]
1838 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1839 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1840 pub mcp_servers: Vec<McpServer>,
1841 #[serde(default)]
1853 pub replay_from: Option<ReplayFrom>,
1854 #[serde(default)]
1862 pub system_prompt: Option<SystemPrompt>,
1863 #[cfg(feature = "unstable_session_options")]
1884 #[serde_as(deserialize_as = "DefaultOnNull")]
1885 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1886 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1887 pub config_options: Vec<InitialSessionConfigOption>,
1888 #[serde_as(deserialize_as = "DefaultOnError")]
1894 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1895 #[serde(default)]
1896 #[serde(rename = "_meta")]
1897 pub meta: Option<Meta>,
1898}
1899
1900impl ResumeSessionRequest {
1901 #[must_use]
1903 pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
1904 Self {
1905 session_id: session_id.into(),
1906 cwd: cwd.into(),
1907 additional_directories: vec![],
1908 mcp_servers: vec![],
1909 replay_from: None,
1910 system_prompt: None,
1911 #[cfg(feature = "unstable_session_options")]
1912 config_options: vec![],
1913 meta: None,
1914 }
1915 }
1916
1917 #[must_use]
1919 pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1920 where
1921 I: IntoIterator<Item = P>,
1922 P: Into<AbsolutePath>,
1923 {
1924 self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1925 self
1926 }
1927
1928 #[must_use]
1930 pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1931 self.mcp_servers = mcp_servers;
1932 self
1933 }
1934
1935 #[must_use]
1943 pub fn replay_from(mut self, replay_from: impl IntoOption<ReplayFrom>) -> Self {
1944 self.replay_from = replay_from.into_option();
1945 self
1946 }
1947
1948 #[must_use]
1950 pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1951 self.system_prompt = system_prompt.into_option();
1952 self
1953 }
1954
1955 #[cfg(feature = "unstable_session_options")]
1973 #[must_use]
1974 pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1975 self.config_options = config_options;
1976 self
1977 }
1978
1979 #[must_use]
1985 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1986 self.meta = meta.into_option();
1987 self
1988 }
1989}
1990
1991#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1995#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1996#[serde(tag = "type", rename_all = "snake_case")]
1997#[non_exhaustive]
1998pub enum ReplayFrom {
1999 Start(ReplayFromStart),
2001 #[serde(untagged)]
2012 Other(OtherReplayFrom),
2013}
2014
2015impl From<ReplayFromStart> for ReplayFrom {
2016 fn from(replay_from: ReplayFromStart) -> Self {
2017 Self::Start(replay_from)
2018 }
2019}
2020
2021#[serde_as]
2023#[skip_serializing_none]
2024#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2025#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2026#[serde(rename_all = "camelCase")]
2027#[non_exhaustive]
2028pub struct ReplayFromStart {
2029 #[serde_as(deserialize_as = "DefaultOnError")]
2035 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2036 #[serde(default)]
2037 #[serde(rename = "_meta")]
2038 pub meta: Option<Meta>,
2039}
2040
2041impl ReplayFromStart {
2042 #[must_use]
2044 pub fn new() -> Self {
2045 Self::default()
2046 }
2047
2048 #[must_use]
2054 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2055 self.meta = meta.into_option();
2056 self
2057 }
2058}
2059
2060#[serde_as]
2062#[skip_serializing_none]
2063#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2064#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
2065#[cfg_attr(feature = "schemars", schemars(inline))]
2066#[cfg_attr(feature = "schemars", schemars(transform = other_replay_from_schema))]
2067#[serde(rename_all = "camelCase")]
2068#[non_exhaustive]
2069pub struct OtherReplayFrom {
2070 #[serde(rename = "type")]
2076 pub type_: String,
2077 #[serde(flatten)]
2080 pub fields: IndexMap<String, serde_json::Value>,
2081}
2082
2083impl OtherReplayFrom {
2084 #[must_use]
2086 pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
2087 fields.shift_remove("type");
2088 Self {
2089 type_: type_.into(),
2090 fields,
2091 }
2092 }
2093}
2094
2095impl<'de> Deserialize<'de> for OtherReplayFrom {
2096 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2097 where
2098 D: serde::Deserializer<'de>,
2099 {
2100 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
2101 let type_ = fields
2102 .shift_remove("type")
2103 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
2104 let serde_json::Value::String(type_) = type_ else {
2105 return Err(serde::de::Error::custom("`type` must be a string"));
2106 };
2107
2108 if is_known_replay_from_type(&type_) {
2109 return Err(serde::de::Error::custom(format!(
2110 "known replay cursor `{type_}` did not match its schema"
2111 )));
2112 }
2113
2114 Ok(Self { type_, fields })
2115 }
2116}
2117
2118fn is_known_replay_from_type(type_: &str) -> bool {
2119 matches!(type_, "start")
2120}
2121
2122#[cfg(feature = "schemars")]
2123fn other_replay_from_schema(schema: &mut Schema) {
2124 super::schema_util::reject_known_string_discriminators(schema, "type", &["start"]);
2125}
2126
2127crate::serde_util::default_on_null! {
2128 #[serde_as]
2136 #[skip_serializing_none]
2137 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2138 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2139 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_RESUME_METHOD_NAME)))]
2140 #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}, {"action": "replace", "target": "availableCommands", "value": "availableCommands"}]})))]
2141 #[serde(rename_all = "camelCase")]
2142 #[non_exhaustive]
2143 pub struct ResumeSessionResponse {
2144 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2150 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2151 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2152 pub config_options: Vec<SessionConfigOption>,
2153 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2159 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2160 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2161 pub available_commands: Vec<AvailableCommand>,
2162 #[serde_as(deserialize_as = "DefaultOnError")]
2168 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2169 #[serde(default)]
2170 #[serde(rename = "_meta")]
2171 pub meta: Option<Meta>,
2172 }
2173}
2174
2175impl ResumeSessionResponse {
2176 #[must_use]
2178 pub fn new() -> Self {
2179 Self::default()
2180 }
2181
2182 #[must_use]
2188 pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
2189 self.config_options = config_options;
2190 self
2191 }
2192
2193 #[must_use]
2195 pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
2196 self.available_commands = available_commands;
2197 self
2198 }
2199
2200 #[must_use]
2206 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2207 self.meta = meta.into_option();
2208 self
2209 }
2210}
2211
2212#[serde_as]
2236#[skip_serializing_none]
2237#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2238#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2239#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CLOSE_METHOD_NAME)))]
2240#[serde(rename_all = "camelCase")]
2241#[non_exhaustive]
2242pub struct CloseSessionRequest {
2243 pub session_id: SessionId,
2245 #[serde_as(deserialize_as = "DefaultOnError")]
2251 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2252 #[serde(default)]
2253 #[serde(rename = "_meta")]
2254 pub meta: Option<Meta>,
2255}
2256
2257impl CloseSessionRequest {
2258 #[must_use]
2260 pub fn new(session_id: impl Into<SessionId>) -> Self {
2261 Self {
2262 session_id: session_id.into(),
2263 meta: None,
2264 }
2265 }
2266
2267 #[must_use]
2273 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2274 self.meta = meta.into_option();
2275 self
2276 }
2277}
2278
2279crate::serde_util::default_on_null! {
2280 #[serde_as]
2282 #[skip_serializing_none]
2283 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2284 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2285 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CLOSE_METHOD_NAME)))]
2286 #[serde(rename_all = "camelCase")]
2287 #[non_exhaustive]
2288 pub struct CloseSessionResponse {
2289 #[serde_as(deserialize_as = "DefaultOnError")]
2295 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2296 #[serde(default)]
2297 #[serde(rename = "_meta")]
2298 pub meta: Option<Meta>,
2299 }
2300}
2301
2302impl CloseSessionResponse {
2303 #[must_use]
2305 pub fn new() -> Self {
2306 Self::default()
2307 }
2308
2309 #[must_use]
2315 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2316 self.meta = meta.into_option();
2317 self
2318 }
2319}
2320
2321#[cfg(feature = "unstable_session_status")]
2335#[serde_as]
2336#[skip_serializing_none]
2337#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2338#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2339#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_STATUS_METHOD_NAME)))]
2340#[serde(rename_all = "camelCase")]
2341#[non_exhaustive]
2342pub struct SessionStatusRequest {
2343 pub session_id: SessionId,
2345 #[serde_as(deserialize_as = "DefaultOnError")]
2351 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2352 #[serde(default)]
2353 #[serde(rename = "_meta")]
2354 pub meta: Option<Meta>,
2355}
2356
2357#[cfg(feature = "unstable_session_status")]
2358impl SessionStatusRequest {
2359 #[must_use]
2361 pub fn new(session_id: impl Into<SessionId>) -> Self {
2362 Self {
2363 session_id: session_id.into(),
2364 meta: None,
2365 }
2366 }
2367
2368 #[must_use]
2374 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2375 self.meta = meta.into_option();
2376 self
2377 }
2378}
2379
2380#[cfg(feature = "unstable_session_status")]
2389#[serde_as]
2390#[skip_serializing_none]
2391#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2392#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2393#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_STATUS_METHOD_NAME)))]
2394#[serde(rename_all = "camelCase")]
2395#[non_exhaustive]
2396pub struct SessionStatusResponse {
2397 pub status: SessionStatus,
2401 #[serde_as(deserialize_as = "DefaultOnError")]
2409 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2410 #[serde(default)]
2411 pub state: Option<StateUpdate>,
2412 #[serde_as(deserialize_as = "DefaultOnError")]
2418 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2419 #[serde(default)]
2420 #[serde(rename = "_meta")]
2421 pub meta: Option<Meta>,
2422}
2423
2424#[cfg(feature = "unstable_session_status")]
2425impl SessionStatusResponse {
2426 #[must_use]
2428 pub fn new(status: SessionStatus) -> Self {
2429 Self {
2430 status,
2431 state: None,
2432 meta: None,
2433 }
2434 }
2435
2436 #[must_use]
2439 pub fn state(mut self, state: impl IntoOption<StateUpdate>) -> Self {
2440 self.state = state.into_option();
2441 self
2442 }
2443
2444 #[must_use]
2450 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2451 self.meta = meta.into_option();
2452 self
2453 }
2454}
2455
2456#[cfg(feature = "unstable_session_status")]
2462#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2463#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2464#[serde(rename_all = "snake_case")]
2465#[non_exhaustive]
2466pub enum SessionStatus {
2467 Open,
2474 Saved,
2478 #[serde(untagged)]
2485 Other(String),
2486}
2487
2488#[cfg(feature = "unstable_session_options")]
2502#[serde_as]
2503#[skip_serializing_none]
2504#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2505#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2506#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_OPTIONS_METHOD_NAME)))]
2507#[serde(rename_all = "camelCase")]
2508#[non_exhaustive]
2509pub struct SessionOptionsRequest {
2510 pub cwd: AbsolutePath,
2512 #[serde_as(deserialize_as = "DefaultOnNull")]
2516 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
2517 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2518 pub additional_directories: Vec<AbsolutePath>,
2519 #[serde(default)]
2526 pub session_id: Option<SessionId>,
2527 #[serde_as(deserialize_as = "DefaultOnError")]
2533 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2534 #[serde(default)]
2535 #[serde(rename = "_meta")]
2536 pub meta: Option<Meta>,
2537}
2538
2539#[cfg(feature = "unstable_session_options")]
2540impl SessionOptionsRequest {
2541 #[must_use]
2543 pub fn new(cwd: impl Into<AbsolutePath>) -> Self {
2544 Self {
2545 cwd: cwd.into(),
2546 additional_directories: vec![],
2547 session_id: None,
2548 meta: None,
2549 }
2550 }
2551
2552 #[must_use]
2554 pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
2555 where
2556 I: IntoIterator<Item = P>,
2557 P: Into<AbsolutePath>,
2558 {
2559 self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
2560 self
2561 }
2562
2563 #[must_use]
2565 pub fn session_id(mut self, session_id: impl IntoOption<SessionId>) -> Self {
2566 self.session_id = session_id.into_option();
2567 self
2568 }
2569
2570 #[must_use]
2576 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2577 self.meta = meta.into_option();
2578 self
2579 }
2580}
2581
2582#[cfg(feature = "unstable_session_options")]
2583crate::serde_util::default_on_null! {
2584 #[serde_as]
2593 #[skip_serializing_none]
2594 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2595 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2596 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_OPTIONS_METHOD_NAME)))]
2597 #[serde(rename_all = "camelCase")]
2598 #[non_exhaustive]
2599 pub struct SessionOptionsResponse {
2600 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2606 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2607 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2608 pub config_options: Vec<SessionConfigOption>,
2609 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2618 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2619 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2620 pub available_commands: Vec<AvailableCommand>,
2621 #[serde_as(deserialize_as = "DefaultOnError")]
2627 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2628 #[serde(default)]
2629 #[serde(rename = "_meta")]
2630 pub meta: Option<Meta>,
2631 }
2632}
2633
2634#[cfg(feature = "unstable_session_options")]
2635impl SessionOptionsResponse {
2636 #[must_use]
2638 pub fn new() -> Self {
2639 Self::default()
2640 }
2641
2642 #[must_use]
2644 pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
2645 self.config_options = config_options;
2646 self
2647 }
2648
2649 #[must_use]
2651 pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
2652 self.available_commands = available_commands;
2653 self
2654 }
2655
2656 #[must_use]
2662 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2663 self.meta = meta.into_option();
2664 self
2665 }
2666}
2667
2668#[cfg(feature = "unstable_session_options")]
2678#[serde_as]
2679#[skip_serializing_none]
2680#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2681#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2682#[serde(rename_all = "camelCase")]
2683#[non_exhaustive]
2684pub struct InitialSessionConfigOption {
2685 pub config_id: SessionConfigId,
2687 #[serde(flatten)]
2692 pub value: SessionConfigOptionValue,
2693 #[serde_as(deserialize_as = "DefaultOnError")]
2699 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2700 #[serde(default)]
2701 #[serde(rename = "_meta")]
2702 pub meta: Option<Meta>,
2703}
2704
2705#[cfg(feature = "unstable_session_options")]
2706impl InitialSessionConfigOption {
2707 #[must_use]
2709 pub fn new(
2710 config_id: impl Into<SessionConfigId>,
2711 value: impl Into<SessionConfigOptionValue>,
2712 ) -> Self {
2713 Self {
2714 config_id: config_id.into(),
2715 value: value.into(),
2716 meta: None,
2717 }
2718 }
2719
2720 #[must_use]
2726 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2727 self.meta = meta.into_option();
2728 self
2729 }
2730}
2731
2732#[serde_as]
2747#[skip_serializing_none]
2748#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2749#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2750#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TOOL_CALL_CANCEL_METHOD_NAME)))]
2751#[serde(rename_all = "camelCase")]
2752#[non_exhaustive]
2753pub struct CancelToolCallRequest {
2754 pub session_id: SessionId,
2756 pub tool_call_id: ToolCallId,
2758 #[serde_as(deserialize_as = "DefaultOnError")]
2764 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2765 #[serde(default)]
2766 #[serde(rename = "_meta")]
2767 pub meta: Option<Meta>,
2768}
2769
2770impl CancelToolCallRequest {
2771 #[must_use]
2773 pub fn new(session_id: impl Into<SessionId>, tool_call_id: impl Into<ToolCallId>) -> Self {
2774 Self {
2775 session_id: session_id.into(),
2776 tool_call_id: tool_call_id.into(),
2777 meta: None,
2778 }
2779 }
2780
2781 #[must_use]
2787 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2788 self.meta = meta.into_option();
2789 self
2790 }
2791}
2792
2793crate::serde_util::default_on_null! {
2794 #[serde_as]
2796 #[skip_serializing_none]
2797 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2798 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2799 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TOOL_CALL_CANCEL_METHOD_NAME)))]
2800 #[serde(rename_all = "camelCase")]
2801 #[non_exhaustive]
2802 pub struct CancelToolCallResponse {
2803 #[serde_as(deserialize_as = "DefaultOnError")]
2809 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2810 #[serde(default)]
2811 #[serde(rename = "_meta")]
2812 pub meta: Option<Meta>,
2813 }
2814}
2815
2816impl CancelToolCallResponse {
2817 #[must_use]
2819 pub fn new() -> Self {
2820 Self::default()
2821 }
2822
2823 #[must_use]
2829 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2830 self.meta = meta.into_option();
2831 self
2832 }
2833}
2834
2835#[serde_as]
2851#[skip_serializing_none]
2852#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2853#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2854#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TERMINAL_CANCEL_METHOD_NAME)))]
2855#[serde(rename_all = "camelCase")]
2856#[non_exhaustive]
2857pub struct CancelTerminalRequest {
2858 pub session_id: SessionId,
2860 pub terminal_id: TerminalId,
2862 #[serde_as(deserialize_as = "DefaultOnError")]
2868 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2869 #[serde(default)]
2870 #[serde(rename = "_meta")]
2871 pub meta: Option<Meta>,
2872}
2873
2874impl CancelTerminalRequest {
2875 #[must_use]
2877 pub fn new(session_id: impl Into<SessionId>, terminal_id: impl Into<TerminalId>) -> Self {
2878 Self {
2879 session_id: session_id.into(),
2880 terminal_id: terminal_id.into(),
2881 meta: None,
2882 }
2883 }
2884
2885 #[must_use]
2891 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2892 self.meta = meta.into_option();
2893 self
2894 }
2895}
2896
2897crate::serde_util::default_on_null! {
2898 #[serde_as]
2900 #[skip_serializing_none]
2901 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2902 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2903 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TERMINAL_CANCEL_METHOD_NAME)))]
2904 #[serde(rename_all = "camelCase")]
2905 #[non_exhaustive]
2906 pub struct CancelTerminalResponse {
2907 #[serde_as(deserialize_as = "DefaultOnError")]
2913 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2914 #[serde(default)]
2915 #[serde(rename = "_meta")]
2916 pub meta: Option<Meta>,
2917 }
2918}
2919
2920impl CancelTerminalResponse {
2921 #[must_use]
2923 pub fn new() -> Self {
2924 Self::default()
2925 }
2926
2927 #[must_use]
2933 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2934 self.meta = meta.into_option();
2935 self
2936 }
2937}
2938
2939#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2943#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
2944#[serde(transparent)]
2945#[from(Arc<str>, String, &str, &mut str, Box<str>, Cow<'_, str>)]
2946#[non_exhaustive]
2947pub struct SessionListCursor(pub Arc<str>);
2948
2949impl SessionListCursor {
2950 #[must_use]
2952 pub fn new(cursor: impl Into<Self>) -> Self {
2953 cursor.into()
2954 }
2955}
2956
2957impl AsRef<str> for SessionListCursor {
2958 fn as_ref(&self) -> &str {
2959 &self.0
2960 }
2961}
2962
2963impl From<&String> for SessionListCursor {
2964 fn from(cursor: &String) -> Self {
2965 Self(cursor.as_str().into())
2966 }
2967}
2968
2969macro_rules! impl_session_list_cursor_option_conversion {
2970 ($source:ty) => {
2971 impl IntoOption<SessionListCursor> for $source {
2972 fn into_option(self) -> Option<SessionListCursor> {
2973 Some(self.into())
2974 }
2975 }
2976 };
2977}
2978
2979impl_session_list_cursor_option_conversion!(Arc<str>);
2980impl_session_list_cursor_option_conversion!(String);
2981impl_session_list_cursor_option_conversion!(&str);
2982impl_session_list_cursor_option_conversion!(&mut str);
2983impl_session_list_cursor_option_conversion!(&String);
2984impl_session_list_cursor_option_conversion!(Box<str>);
2985impl_session_list_cursor_option_conversion!(Cow<'_, str>);
2986
2987crate::serde_util::default_on_null! {
2988 #[serde_as]
2990 #[skip_serializing_none]
2991 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2992 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2993 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LIST_METHOD_NAME)))]
2994 #[serde(rename_all = "camelCase")]
2995 #[non_exhaustive]
2996 pub struct ListSessionsRequest {
2997 #[serde(default)]
3005 pub cwd: Option<AbsolutePath>,
3006 #[serde(default)]
3010 pub cursor: Option<SessionListCursor>,
3011 #[cfg(feature = "unstable_session_archive")]
3021 #[serde(default)]
3022 pub archived: Option<SessionArchiveFilter>,
3023 #[serde_as(deserialize_as = "DefaultOnError")]
3029 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3030 #[serde(default)]
3031 #[serde(rename = "_meta")]
3032 pub meta: Option<Meta>,
3033 }
3034}
3035
3036impl ListSessionsRequest {
3037 #[must_use]
3039 pub fn new() -> Self {
3040 Self::default()
3041 }
3042
3043 #[must_use]
3045 pub fn cwd(mut self, cwd: impl IntoOption<AbsolutePath>) -> Self {
3046 self.cwd = cwd.into_option();
3047 self
3048 }
3049
3050 #[must_use]
3052 pub fn cursor(mut self, cursor: impl IntoOption<SessionListCursor>) -> Self {
3053 self.cursor = cursor.into_option();
3054 self
3055 }
3056
3057 #[cfg(feature = "unstable_session_archive")]
3063 #[must_use]
3064 pub fn archived(mut self, archived: impl IntoOption<SessionArchiveFilter>) -> Self {
3065 self.archived = archived.into_option();
3066 self
3067 }
3068
3069 #[must_use]
3075 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3076 self.meta = meta.into_option();
3077 self
3078 }
3079}
3080
3081#[serde_as]
3083#[skip_serializing_none]
3084#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3085#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3086#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LIST_METHOD_NAME)))]
3087#[serde(rename_all = "camelCase")]
3088#[non_exhaustive]
3089pub struct ListSessionsResponse {
3090 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
3094 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3095 pub sessions: Vec<SessionInfo>,
3096 #[serde(default)]
3100 pub next_cursor: Option<SessionListCursor>,
3101 #[serde_as(deserialize_as = "DefaultOnError")]
3107 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3108 #[serde(default)]
3109 #[serde(rename = "_meta")]
3110 pub meta: Option<Meta>,
3111}
3112
3113impl ListSessionsResponse {
3114 #[must_use]
3116 pub fn new(sessions: Vec<SessionInfo>) -> Self {
3117 Self {
3118 sessions,
3119 next_cursor: None,
3120 meta: None,
3121 }
3122 }
3123
3124 #[must_use]
3126 pub fn next_cursor(mut self, next_cursor: impl IntoOption<SessionListCursor>) -> Self {
3127 self.next_cursor = next_cursor.into_option();
3128 self
3129 }
3130
3131 #[must_use]
3137 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3138 self.meta = meta.into_option();
3139 self
3140 }
3141}
3142
3143#[serde_as]
3149#[skip_serializing_none]
3150#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3151#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3152#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_DELETE_METHOD_NAME)))]
3153#[serde(rename_all = "camelCase")]
3154#[non_exhaustive]
3155pub struct DeleteSessionRequest {
3156 pub session_id: SessionId,
3158 #[serde_as(deserialize_as = "DefaultOnError")]
3164 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3165 #[serde(default)]
3166 #[serde(rename = "_meta")]
3167 pub meta: Option<Meta>,
3168}
3169
3170impl DeleteSessionRequest {
3171 #[must_use]
3173 pub fn new(session_id: impl Into<SessionId>) -> Self {
3174 Self {
3175 session_id: session_id.into(),
3176 meta: None,
3177 }
3178 }
3179
3180 #[must_use]
3186 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3187 self.meta = meta.into_option();
3188 self
3189 }
3190}
3191
3192crate::serde_util::default_on_null! {
3193 #[serde_as]
3195 #[skip_serializing_none]
3196 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3197 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3198 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_DELETE_METHOD_NAME)))]
3199 #[serde(rename_all = "camelCase")]
3200 #[non_exhaustive]
3201 pub struct DeleteSessionResponse {
3202 #[serde_as(deserialize_as = "DefaultOnError")]
3208 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3209 #[serde(default)]
3210 #[serde(rename = "_meta")]
3211 pub meta: Option<Meta>,
3212 }
3213}
3214
3215impl DeleteSessionResponse {
3216 #[must_use]
3218 pub fn new() -> Self {
3219 Self::default()
3220 }
3221
3222 #[must_use]
3228 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3229 self.meta = meta.into_option();
3230 self
3231 }
3232}
3233
3234#[cfg(feature = "unstable_session_archive")]
3250#[serde_as]
3251#[skip_serializing_none]
3252#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3253#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3254#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_ARCHIVE_METHOD_NAME)))]
3255#[serde(rename_all = "camelCase")]
3256#[non_exhaustive]
3257pub struct ArchiveSessionRequest {
3258 pub session_id: SessionId,
3260 #[serde_as(deserialize_as = "DefaultOnError")]
3266 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3267 #[serde(default)]
3268 #[serde(rename = "_meta")]
3269 pub meta: Option<Meta>,
3270}
3271
3272#[cfg(feature = "unstable_session_archive")]
3273impl ArchiveSessionRequest {
3274 #[must_use]
3276 pub fn new(session_id: impl Into<SessionId>) -> Self {
3277 Self {
3278 session_id: session_id.into(),
3279 meta: None,
3280 }
3281 }
3282
3283 #[must_use]
3289 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3290 self.meta = meta.into_option();
3291 self
3292 }
3293}
3294
3295#[cfg(feature = "unstable_session_archive")]
3296crate::serde_util::default_on_null! {
3297 #[serde_as]
3303 #[skip_serializing_none]
3304 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3305 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3306 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_ARCHIVE_METHOD_NAME)))]
3307 #[serde(rename_all = "camelCase")]
3308 #[non_exhaustive]
3309 pub struct ArchiveSessionResponse {
3310 #[serde_as(deserialize_as = "DefaultOnError")]
3316 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3317 #[serde(default)]
3318 #[serde(rename = "_meta")]
3319 pub meta: Option<Meta>,
3320 }
3321}
3322
3323#[cfg(feature = "unstable_session_archive")]
3324impl ArchiveSessionResponse {
3325 #[must_use]
3327 pub fn new() -> Self {
3328 Self::default()
3329 }
3330
3331 #[must_use]
3337 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3338 self.meta = meta.into_option();
3339 self
3340 }
3341}
3342
3343#[cfg(feature = "unstable_session_archive")]
3358#[serde_as]
3359#[skip_serializing_none]
3360#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3361#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3362#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_UNARCHIVE_METHOD_NAME)))]
3363#[serde(rename_all = "camelCase")]
3364#[non_exhaustive]
3365pub struct UnarchiveSessionRequest {
3366 pub session_id: SessionId,
3368 #[serde_as(deserialize_as = "DefaultOnError")]
3374 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3375 #[serde(default)]
3376 #[serde(rename = "_meta")]
3377 pub meta: Option<Meta>,
3378}
3379
3380#[cfg(feature = "unstable_session_archive")]
3381impl UnarchiveSessionRequest {
3382 #[must_use]
3384 pub fn new(session_id: impl Into<SessionId>) -> Self {
3385 Self {
3386 session_id: session_id.into(),
3387 meta: None,
3388 }
3389 }
3390
3391 #[must_use]
3397 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3398 self.meta = meta.into_option();
3399 self
3400 }
3401}
3402
3403#[cfg(feature = "unstable_session_archive")]
3404crate::serde_util::default_on_null! {
3405 #[serde_as]
3411 #[skip_serializing_none]
3412 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3413 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3414 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_UNARCHIVE_METHOD_NAME)))]
3415 #[serde(rename_all = "camelCase")]
3416 #[non_exhaustive]
3417 pub struct UnarchiveSessionResponse {
3418 #[serde_as(deserialize_as = "DefaultOnError")]
3424 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3425 #[serde(default)]
3426 #[serde(rename = "_meta")]
3427 pub meta: Option<Meta>,
3428 }
3429}
3430
3431#[cfg(feature = "unstable_session_archive")]
3432impl UnarchiveSessionResponse {
3433 #[must_use]
3435 pub fn new() -> Self {
3436 Self::default()
3437 }
3438
3439 #[must_use]
3445 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3446 self.meta = meta.into_option();
3447 self
3448 }
3449}
3450
3451#[cfg(feature = "unstable_session_archive")]
3460#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3461#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
3462#[serde(rename_all = "snake_case")]
3463#[non_exhaustive]
3464pub enum SessionArchiveFilter {
3465 #[default]
3467 Exclude,
3468 Include,
3470 Only,
3472 #[serde(untagged)]
3478 Other(String),
3479}
3480
3481#[serde_as]
3483#[skip_serializing_none]
3484#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3485#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3486#[serde(rename_all = "camelCase")]
3487#[non_exhaustive]
3488pub struct SessionInfo {
3489 pub session_id: SessionId,
3491 pub cwd: AbsolutePath,
3493 #[serde_as(deserialize_as = "DefaultOnNull")]
3499 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
3500 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3501 pub additional_directories: Vec<AbsolutePath>,
3502
3503 #[serde_as(deserialize_as = "DefaultOnError")]
3507 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3508 #[serde(default)]
3509 pub title: Option<String>,
3510 #[serde_as(deserialize_as = "DefaultOnError")]
3514 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "format" = "date-time")))]
3515 #[serde(default)]
3516 pub updated_at: Option<String>,
3517 #[cfg(feature = "unstable_session_archive")]
3526 #[serde_as(deserialize_as = "DefaultOnError")]
3527 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3528 #[serde(default)]
3529 pub archived: Option<bool>,
3530 #[serde_as(deserialize_as = "DefaultOnError")]
3536 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3537 #[serde(default)]
3538 #[serde(rename = "_meta")]
3539 pub meta: Option<Meta>,
3540}
3541
3542impl SessionInfo {
3543 #[must_use]
3545 pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
3546 Self {
3547 session_id: session_id.into(),
3548 cwd: cwd.into(),
3549 additional_directories: vec![],
3550 title: None,
3551 updated_at: None,
3552 #[cfg(feature = "unstable_session_archive")]
3553 archived: None,
3554 meta: None,
3555 }
3556 }
3557
3558 #[must_use]
3560 pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
3561 where
3562 I: IntoIterator<Item = P>,
3563 P: Into<AbsolutePath>,
3564 {
3565 self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
3566 self
3567 }
3568
3569 #[must_use]
3571 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
3572 self.title = title.into_option();
3573 self
3574 }
3575
3576 #[must_use]
3578 pub fn updated_at(mut self, updated_at: impl IntoOption<String>) -> Self {
3579 self.updated_at = updated_at.into_option();
3580 self
3581 }
3582
3583 #[cfg(feature = "unstable_session_archive")]
3589 #[must_use]
3590 pub fn archived(mut self, archived: impl IntoOption<bool>) -> Self {
3591 self.archived = archived.into_option();
3592 self
3593 }
3594
3595 #[must_use]
3601 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3602 self.meta = meta.into_option();
3603 self
3604 }
3605}
3606
3607#[cfg(feature = "unstable_session_set_title")]
3623#[serde_as]
3624#[skip_serializing_none]
3625#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3626#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3627#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_TITLE_METHOD_NAME)))]
3628#[serde(rename_all = "camelCase")]
3629#[non_exhaustive]
3630pub struct SetSessionTitleRequest {
3631 pub session_id: SessionId,
3633 pub title: String,
3640 #[serde_as(deserialize_as = "DefaultOnError")]
3646 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3647 #[serde(default)]
3648 #[serde(rename = "_meta")]
3649 pub meta: Option<Meta>,
3650}
3651
3652#[cfg(feature = "unstable_session_set_title")]
3653impl SetSessionTitleRequest {
3654 #[must_use]
3656 pub fn new(session_id: impl Into<SessionId>, title: impl Into<String>) -> Self {
3657 Self {
3658 session_id: session_id.into(),
3659 title: title.into(),
3660 meta: None,
3661 }
3662 }
3663
3664 #[must_use]
3670 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3671 self.meta = meta.into_option();
3672 self
3673 }
3674}
3675
3676#[cfg(feature = "unstable_session_set_title")]
3682#[serde_as]
3683#[skip_serializing_none]
3684#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3685#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3686#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_TITLE_METHOD_NAME)))]
3687#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "sessionInfo", "field": "title", "value": "title"}]})))]
3688#[serde(rename_all = "camelCase")]
3689#[non_exhaustive]
3690pub struct SetSessionTitleResponse {
3691 pub title: String,
3696 #[serde_as(deserialize_as = "DefaultOnError")]
3702 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3703 #[serde(default)]
3704 #[serde(rename = "_meta")]
3705 pub meta: Option<Meta>,
3706}
3707
3708#[cfg(feature = "unstable_session_set_title")]
3709impl SetSessionTitleResponse {
3710 #[must_use]
3712 pub fn new(title: impl Into<String>) -> Self {
3713 Self {
3714 title: title.into(),
3715 meta: None,
3716 }
3717 }
3718
3719 #[must_use]
3725 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3726 self.meta = meta.into_option();
3727 self
3728 }
3729}
3730
3731#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3735#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3736#[serde(transparent)]
3737#[from(forward)]
3738#[non_exhaustive]
3739pub struct SessionConfigId(pub Arc<str>);
3740
3741impl SessionConfigId {
3742 #[must_use]
3744 pub fn new(id: impl Into<Self>) -> Self {
3745 id.into()
3746 }
3747}
3748
3749#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3751#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3752#[serde(transparent)]
3753#[from(forward)]
3754#[non_exhaustive]
3755pub struct SessionConfigValueId(pub Arc<str>);
3756
3757impl SessionConfigValueId {
3758 #[must_use]
3760 pub fn new(id: impl Into<Self>) -> Self {
3761 id.into()
3762 }
3763}
3764
3765#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3767#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3768#[serde(transparent)]
3769#[from(forward)]
3770#[non_exhaustive]
3771pub struct SessionConfigGroupId(pub Arc<str>);
3772
3773impl SessionConfigGroupId {
3774 #[must_use]
3776 pub fn new(id: impl Into<Self>) -> Self {
3777 id.into()
3778 }
3779}
3780
3781#[serde_as]
3783#[skip_serializing_none]
3784#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3785#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3786#[serde(rename_all = "camelCase")]
3787#[non_exhaustive]
3788pub struct SessionConfigSelectOption {
3789 pub value: SessionConfigValueId,
3791 pub name: String,
3793 #[serde_as(deserialize_as = "DefaultOnError")]
3797 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3798 #[serde(default)]
3799 pub description: Option<String>,
3800 #[serde_as(deserialize_as = "DefaultOnError")]
3806 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3807 #[serde(default)]
3808 #[serde(rename = "_meta")]
3809 pub meta: Option<Meta>,
3810}
3811
3812impl SessionConfigSelectOption {
3813 #[must_use]
3815 pub fn new(value: impl Into<SessionConfigValueId>, name: impl Into<String>) -> Self {
3816 Self {
3817 value: value.into(),
3818 name: name.into(),
3819 description: None,
3820 meta: None,
3821 }
3822 }
3823
3824 #[must_use]
3826 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
3827 self.description = description.into_option();
3828 self
3829 }
3830
3831 #[must_use]
3837 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3838 self.meta = meta.into_option();
3839 self
3840 }
3841}
3842
3843#[serde_as]
3845#[skip_serializing_none]
3846#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3847#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3848#[serde(rename_all = "camelCase")]
3849#[non_exhaustive]
3850pub struct SessionConfigSelectGroup {
3851 pub group_id: SessionConfigGroupId,
3853 pub name: String,
3855 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
3857 #[cfg_attr(feature = "schemars", schemars(length(min = 1), extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3858 pub options: Vec<SessionConfigSelectOption>,
3859 #[serde_as(deserialize_as = "DefaultOnError")]
3865 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3866 #[serde(default)]
3867 #[serde(rename = "_meta")]
3868 pub meta: Option<Meta>,
3869}
3870
3871impl SessionConfigSelectGroup {
3872 #[must_use]
3874 pub fn new(
3875 group_id: impl Into<SessionConfigGroupId>,
3876 name: impl Into<String>,
3877 options: Vec<SessionConfigSelectOption>,
3878 ) -> Self {
3879 Self {
3880 group_id: group_id.into(),
3881 name: name.into(),
3882 options,
3883 meta: None,
3884 }
3885 }
3886
3887 #[must_use]
3893 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3894 self.meta = meta.into_option();
3895 self
3896 }
3897}
3898
3899#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3901#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3902#[serde(untagged)]
3903#[non_exhaustive]
3904pub enum SessionConfigSelectOptions {
3905 Ungrouped(
3907 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))] Vec<SessionConfigSelectOption>,
3908 ),
3909 Grouped(
3911 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))] Vec<SessionConfigSelectGroup>,
3912 ),
3913}
3914
3915impl From<Vec<SessionConfigSelectOption>> for SessionConfigSelectOptions {
3916 fn from(options: Vec<SessionConfigSelectOption>) -> Self {
3917 SessionConfigSelectOptions::Ungrouped(options)
3918 }
3919}
3920
3921impl From<Vec<SessionConfigSelectGroup>> for SessionConfigSelectOptions {
3922 fn from(groups: Vec<SessionConfigSelectGroup>) -> Self {
3923 SessionConfigSelectOptions::Grouped(groups)
3924 }
3925}
3926
3927#[skip_serializing_none]
3929#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3930#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3931#[serde(rename_all = "camelCase")]
3932#[non_exhaustive]
3933pub struct SessionConfigSelect {
3934 pub current_value: SessionConfigValueId,
3936 pub options: SessionConfigSelectOptions,
3939}
3940
3941impl SessionConfigSelect {
3942 #[must_use]
3944 pub fn new(
3945 current_value: impl Into<SessionConfigValueId>,
3946 options: impl Into<SessionConfigSelectOptions>,
3947 ) -> Self {
3948 Self {
3949 current_value: current_value.into(),
3950 options: options.into(),
3951 }
3952 }
3953}
3954
3955#[skip_serializing_none]
3957#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3958#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3959#[serde(rename_all = "camelCase")]
3960#[non_exhaustive]
3961pub struct SessionConfigBoolean {
3962 pub current_value: bool,
3964}
3965
3966impl SessionConfigBoolean {
3967 #[must_use]
3969 pub fn new(current_value: bool) -> Self {
3970 Self { current_value }
3971 }
3972}
3973
3974#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3984#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3985#[serde(rename_all = "snake_case")]
3986#[non_exhaustive]
3987pub enum SessionConfigOptionCategory {
3988 Mode,
3990 Model,
3992 ModelConfig,
3994 #[cfg(feature = "unstable_speed_config_category")]
4000 Speed,
4001 ThoughtLevel,
4003 #[serde(untagged)]
4009 Other(String),
4010}
4011
4012#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4014#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4015#[serde(tag = "type", rename_all = "snake_case")]
4016#[non_exhaustive]
4017pub enum SessionConfigKind {
4018 Select(SessionConfigSelect),
4020 Boolean(SessionConfigBoolean),
4022 #[serde(untagged)]
4032 Other(OtherSessionConfigKind),
4033}
4034
4035#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4037#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4038#[cfg_attr(feature = "schemars", schemars(inline))]
4039#[cfg_attr(feature = "schemars", schemars(transform = other_session_config_kind_schema))]
4040#[serde(rename_all = "camelCase")]
4041#[non_exhaustive]
4042pub struct OtherSessionConfigKind {
4043 #[serde(rename = "type")]
4049 pub type_: String,
4050 #[serde(flatten)]
4052 pub fields: IndexMap<String, serde_json::Value>,
4053}
4054
4055impl OtherSessionConfigKind {
4056 #[must_use]
4058 pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
4059 fields.shift_remove("type");
4060 fields.shift_remove("_meta");
4061 Self {
4062 type_: type_.into(),
4063 fields,
4064 }
4065 }
4066}
4067
4068impl<'de> Deserialize<'de> for OtherSessionConfigKind {
4069 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4070 where
4071 D: serde::Deserializer<'de>,
4072 {
4073 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4074 let type_ = fields
4075 .shift_remove("type")
4076 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4077 let serde_json::Value::String(type_) = type_ else {
4078 return Err(serde::de::Error::custom("`type` must be a string"));
4079 };
4080
4081 if is_known_session_config_kind_type(&type_) {
4082 return Err(serde::de::Error::custom(format!(
4083 "known session configuration option `{type_}` did not match its schema"
4084 )));
4085 }
4086
4087 Ok(Self { type_, fields })
4088 }
4089}
4090
4091fn is_known_session_config_kind_type(type_: &str) -> bool {
4092 matches!(type_, "select" | "boolean")
4093}
4094
4095#[cfg(feature = "schemars")]
4096fn other_session_config_kind_schema(schema: &mut Schema) {
4097 super::schema_util::reject_known_string_discriminators(schema, "type", &["select", "boolean"]);
4098}
4099
4100#[serde_as]
4102#[skip_serializing_none]
4103#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4104#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4105#[serde(rename_all = "camelCase")]
4106#[non_exhaustive]
4107pub struct SessionConfigOption {
4108 pub config_id: SessionConfigId,
4110 pub name: String,
4112 #[serde_as(deserialize_as = "DefaultOnError")]
4116 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4117 #[serde(default)]
4118 pub description: Option<String>,
4119 #[serde_as(deserialize_as = "DefaultOnError")]
4123 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4124 #[serde(default)]
4125 pub category: Option<SessionConfigOptionCategory>,
4126 #[serde(flatten)]
4128 pub kind: SessionConfigKind,
4129 #[serde_as(deserialize_as = "DefaultOnError")]
4135 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4136 #[serde(default)]
4137 #[serde(rename = "_meta")]
4138 pub meta: Option<Meta>,
4139}
4140
4141impl SessionConfigOption {
4142 #[must_use]
4144 pub fn new(
4145 config_id: impl Into<SessionConfigId>,
4146 name: impl Into<String>,
4147 kind: SessionConfigKind,
4148 ) -> Self {
4149 Self {
4150 config_id: config_id.into(),
4151 name: name.into(),
4152 description: None,
4153 category: None,
4154 kind,
4155 meta: None,
4156 }
4157 }
4158
4159 #[must_use]
4161 pub fn select(
4162 config_id: impl Into<SessionConfigId>,
4163 name: impl Into<String>,
4164 current_value: impl Into<SessionConfigValueId>,
4165 options: impl Into<SessionConfigSelectOptions>,
4166 ) -> Self {
4167 Self::new(
4168 config_id,
4169 name,
4170 SessionConfigKind::Select(SessionConfigSelect::new(current_value, options)),
4171 )
4172 }
4173
4174 #[must_use]
4176 pub fn boolean(
4177 config_id: impl Into<SessionConfigId>,
4178 name: impl Into<String>,
4179 current_value: bool,
4180 ) -> Self {
4181 Self::new(
4182 config_id,
4183 name,
4184 SessionConfigKind::Boolean(SessionConfigBoolean::new(current_value)),
4185 )
4186 }
4187
4188 #[must_use]
4190 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
4191 self.description = description.into_option();
4192 self
4193 }
4194
4195 #[must_use]
4197 pub fn category(mut self, category: impl IntoOption<SessionConfigOptionCategory>) -> Self {
4198 self.category = category.into_option();
4199 self
4200 }
4201
4202 #[must_use]
4208 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4209 self.meta = meta.into_option();
4210 self
4211 }
4212}
4213
4214#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4223#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4224#[serde(tag = "type", rename_all = "snake_case")]
4225#[non_exhaustive]
4226pub enum SessionConfigOptionValue {
4227 Id {
4229 value: SessionConfigValueId,
4231 },
4232 Boolean {
4234 value: bool,
4236 },
4237 #[serde(untagged)]
4246 Other(OtherSessionConfigOptionValue),
4247}
4248
4249#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4251#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4252#[cfg_attr(feature = "schemars", schemars(inline))]
4253#[cfg_attr(feature = "schemars", schemars(transform = other_session_config_option_value_schema))]
4254#[serde(rename_all = "camelCase")]
4255#[non_exhaustive]
4256pub struct OtherSessionConfigOptionValue {
4257 #[serde(rename = "type")]
4263 pub type_: String,
4264 pub value: serde_json::Value,
4266 #[serde(flatten)]
4268 pub fields: IndexMap<String, serde_json::Value>,
4269}
4270
4271impl OtherSessionConfigOptionValue {
4272 #[must_use]
4274 pub fn new(
4275 type_: impl Into<String>,
4276 value: serde_json::Value,
4277 mut fields: IndexMap<String, serde_json::Value>,
4278 ) -> Self {
4279 fields.shift_remove("type");
4280 fields.shift_remove("value");
4281 fields.shift_remove("_meta");
4282 Self {
4283 type_: type_.into(),
4284 value,
4285 fields,
4286 }
4287 }
4288}
4289
4290impl<'de> Deserialize<'de> for OtherSessionConfigOptionValue {
4291 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4292 where
4293 D: serde::Deserializer<'de>,
4294 {
4295 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4296 let type_ = fields
4297 .shift_remove("type")
4298 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4299 let serde_json::Value::String(type_) = type_ else {
4300 return Err(serde::de::Error::custom("`type` must be a string"));
4301 };
4302
4303 if is_known_session_config_option_value_type(&type_) {
4304 return Err(serde::de::Error::custom(format!(
4305 "known session configuration option value `{type_}` did not match its schema"
4306 )));
4307 }
4308
4309 let value = fields
4310 .shift_remove("value")
4311 .ok_or_else(|| serde::de::Error::missing_field("value"))?;
4312
4313 Ok(Self {
4314 type_,
4315 value,
4316 fields,
4317 })
4318 }
4319}
4320
4321impl<'de> Deserialize<'de> for SessionConfigOptionValue {
4322 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4323 where
4324 D: serde::Deserializer<'de>,
4325 {
4326 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4327 let type_ = fields.shift_remove("type");
4328 let value = fields
4329 .shift_remove("value")
4330 .ok_or_else(|| serde::de::Error::missing_field("value"))?;
4331
4332 let type_ = type_.ok_or_else(|| serde::de::Error::missing_field("type"))?;
4333
4334 let serde_json::Value::String(type_) = type_ else {
4335 return Err(serde::de::Error::custom("`type` must be a string"));
4336 };
4337
4338 match type_.as_str() {
4339 "id" => {
4340 let value = serde_json::from_value(value).map_err(|error| {
4341 serde::de::Error::custom(format!(
4342 "`value` must be a string for `type: id`: {error}"
4343 ))
4344 })?;
4345 Ok(Self::Id { value })
4346 }
4347 "boolean" => {
4348 let value = serde_json::from_value(value).map_err(|error| {
4349 serde::de::Error::custom(format!(
4350 "`value` must be a boolean for `type: boolean`: {error}"
4351 ))
4352 })?;
4353 Ok(Self::Boolean { value })
4354 }
4355 _ => Ok(Self::Other(OtherSessionConfigOptionValue {
4356 type_,
4357 value,
4358 fields,
4359 })),
4360 }
4361 }
4362}
4363
4364fn is_known_session_config_option_value_type(type_: &str) -> bool {
4365 matches!(type_, "id" | "boolean")
4366}
4367
4368#[cfg(feature = "schemars")]
4369fn other_session_config_option_value_schema(schema: &mut Schema) {
4370 super::schema_util::reject_known_string_discriminators(schema, "type", &["id", "boolean"]);
4371}
4372
4373impl SessionConfigOptionValue {
4374 #[must_use]
4376 pub fn id(id: impl Into<SessionConfigValueId>) -> Self {
4377 Self::Id { value: id.into() }
4378 }
4379
4380 #[must_use]
4382 pub fn boolean(val: bool) -> Self {
4383 Self::Boolean { value: val }
4384 }
4385
4386 #[must_use]
4389 pub fn as_id(&self) -> Option<&SessionConfigValueId> {
4390 match self {
4391 Self::Id { value } => Some(value),
4392 _ => None,
4393 }
4394 }
4395
4396 #[must_use]
4398 pub fn as_bool(&self) -> Option<bool> {
4399 match self {
4400 Self::Boolean { value } => Some(*value),
4401 _ => None,
4402 }
4403 }
4404}
4405
4406impl From<SessionConfigValueId> for SessionConfigOptionValue {
4407 fn from(value: SessionConfigValueId) -> Self {
4408 Self::Id { value }
4409 }
4410}
4411
4412impl From<bool> for SessionConfigOptionValue {
4413 fn from(value: bool) -> Self {
4414 Self::Boolean { value }
4415 }
4416}
4417
4418impl From<&str> for SessionConfigOptionValue {
4419 fn from(value: &str) -> Self {
4420 Self::Id {
4421 value: SessionConfigValueId::new(value),
4422 }
4423 }
4424}
4425
4426#[serde_as]
4437#[skip_serializing_none]
4438#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4439#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4440#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_CONFIG_OPTION_METHOD_NAME)))]
4441#[serde(rename_all = "camelCase")]
4442#[non_exhaustive]
4443pub struct SetSessionConfigOptionRequest {
4444 pub session_id: SessionId,
4446 pub config_id: SessionConfigId,
4448 #[serde(flatten)]
4452 pub value: SessionConfigOptionValue,
4453 #[serde_as(deserialize_as = "DefaultOnError")]
4459 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4460 #[serde(default)]
4461 #[serde(rename = "_meta")]
4462 pub meta: Option<Meta>,
4463}
4464
4465impl SetSessionConfigOptionRequest {
4466 #[must_use]
4468 pub fn new(
4469 session_id: impl Into<SessionId>,
4470 config_id: impl Into<SessionConfigId>,
4471 value: impl Into<SessionConfigOptionValue>,
4472 ) -> Self {
4473 Self {
4474 session_id: session_id.into(),
4475 config_id: config_id.into(),
4476 value: value.into(),
4477 meta: None,
4478 }
4479 }
4480
4481 #[must_use]
4487 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4488 self.meta = meta.into_option();
4489 self
4490 }
4491}
4492
4493#[serde_as]
4495#[skip_serializing_none]
4496#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4497#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4498#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_CONFIG_OPTION_METHOD_NAME)))]
4499#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}]})))]
4500#[serde(rename_all = "camelCase")]
4501#[non_exhaustive]
4502pub struct SetSessionConfigOptionResponse {
4503 #[serde_as(deserialize_as = "VecSkipError<_>")]
4505 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
4506 pub config_options: Vec<SessionConfigOption>,
4507 #[serde_as(deserialize_as = "DefaultOnError")]
4513 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4514 #[serde(default)]
4515 #[serde(rename = "_meta")]
4516 pub meta: Option<Meta>,
4517}
4518
4519impl SetSessionConfigOptionResponse {
4520 #[must_use]
4522 pub fn new(config_options: Vec<SessionConfigOption>) -> Self {
4523 Self {
4524 config_options,
4525 meta: None,
4526 }
4527 }
4528
4529 #[must_use]
4535 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4536 self.meta = meta.into_option();
4537 self
4538 }
4539}
4540
4541#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4550#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4551#[serde(tag = "type", rename_all = "snake_case")]
4552#[non_exhaustive]
4553pub enum McpServer {
4554 Http(McpServerHttp),
4558 #[cfg(feature = "unstable_mcp_over_acp")]
4567 Acp(McpServerAcp),
4568 Stdio(McpServerStdio),
4572 #[serde(untagged)]
4583 Other(OtherMcpServer),
4584}
4585
4586#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4588#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4589#[cfg_attr(feature = "schemars", schemars(inline))]
4590#[cfg_attr(feature = "schemars", schemars(transform = other_mcp_server_schema))]
4591#[serde(rename_all = "camelCase")]
4592#[non_exhaustive]
4593pub struct OtherMcpServer {
4594 #[serde(rename = "type")]
4600 pub type_: String,
4601 #[serde(flatten)]
4603 pub fields: IndexMap<String, serde_json::Value>,
4604}
4605
4606impl OtherMcpServer {
4607 #[must_use]
4609 pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
4610 fields.shift_remove("type");
4611 Self {
4612 type_: type_.into(),
4613 fields,
4614 }
4615 }
4616}
4617
4618impl<'de> Deserialize<'de> for OtherMcpServer {
4619 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4620 where
4621 D: serde::Deserializer<'de>,
4622 {
4623 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4624 let type_ = fields
4625 .shift_remove("type")
4626 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4627 let serde_json::Value::String(type_) = type_ else {
4628 return Err(serde::de::Error::custom("`type` must be a string"));
4629 };
4630
4631 if is_known_mcp_server_type(&type_) {
4632 return Err(serde::de::Error::custom(format!(
4633 "known MCP server transport `{type_}` did not match its schema"
4634 )));
4635 }
4636
4637 Ok(Self { type_, fields })
4638 }
4639}
4640
4641fn is_known_mcp_server_type(type_: &str) -> bool {
4642 match type_ {
4643 "http" | "stdio" => true,
4644 #[cfg(feature = "unstable_mcp_over_acp")]
4645 "acp" => true,
4646 _ => false,
4647 }
4648}
4649
4650#[cfg(feature = "schemars")]
4651fn other_mcp_server_schema(schema: &mut Schema) {
4652 super::schema_util::reject_known_string_discriminators(
4653 schema,
4654 "type",
4655 &[
4656 "http",
4657 "stdio",
4658 #[cfg(feature = "unstable_mcp_over_acp")]
4659 "acp",
4660 ],
4661 );
4662}
4663
4664#[serde_as]
4666#[skip_serializing_none]
4667#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4668#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4669#[serde(rename_all = "camelCase")]
4670#[non_exhaustive]
4671pub struct McpServerHttp {
4672 pub name: String,
4676 #[cfg_attr(feature = "schemars", schemars(url))]
4678 pub url: String,
4679 #[serde_as(deserialize_as = "DefaultOnNull")]
4682 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4683 #[serde(default, skip_serializing_if = "Vec::is_empty")]
4684 pub headers: Vec<HttpHeader>,
4685 #[serde_as(deserialize_as = "DefaultOnError")]
4691 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4692 #[serde(default)]
4693 #[serde(rename = "_meta")]
4694 pub meta: Option<Meta>,
4695}
4696
4697impl McpServerHttp {
4698 #[must_use]
4700 pub fn new(name: impl Into<String>, url: impl Into<String>) -> Self {
4701 Self {
4702 name: name.into(),
4703 url: url.into(),
4704 headers: Vec::new(),
4705 meta: None,
4706 }
4707 }
4708
4709 #[must_use]
4712 pub fn headers(mut self, headers: Vec<HttpHeader>) -> Self {
4713 self.headers = headers;
4714 self
4715 }
4716
4717 #[must_use]
4723 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4724 self.meta = meta.into_option();
4725 self
4726 }
4727}
4728
4729#[cfg(feature = "unstable_mcp_over_acp")]
4738#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4739#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
4740#[serde(transparent)]
4741#[from(forward)]
4742#[non_exhaustive]
4743pub struct McpServerAcpId(pub Arc<str>);
4744
4745#[cfg(feature = "unstable_mcp_over_acp")]
4746impl McpServerAcpId {
4747 #[must_use]
4749 pub fn new(id: impl Into<Self>) -> Self {
4750 id.into()
4751 }
4752}
4753
4754#[serde_as]
4763#[skip_serializing_none]
4764#[cfg(feature = "unstable_mcp_over_acp")]
4765#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4766#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4767#[serde(rename_all = "camelCase")]
4768#[non_exhaustive]
4769pub struct McpServerAcp {
4770 pub name: String,
4774 pub server_id: McpServerAcpId,
4779 #[serde_as(deserialize_as = "DefaultOnError")]
4785 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4786 #[serde(default)]
4787 #[serde(rename = "_meta")]
4788 pub meta: Option<Meta>,
4789}
4790
4791#[cfg(feature = "unstable_mcp_over_acp")]
4792impl McpServerAcp {
4793 #[must_use]
4795 pub fn new(name: impl Into<String>, server_id: impl Into<McpServerAcpId>) -> Self {
4796 Self {
4797 name: name.into(),
4798 server_id: server_id.into(),
4799 meta: None,
4800 }
4801 }
4802
4803 #[must_use]
4809 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4810 self.meta = meta.into_option();
4811 self
4812 }
4813}
4814
4815#[serde_as]
4817#[skip_serializing_none]
4818#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4819#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4820#[serde(rename_all = "camelCase")]
4821#[non_exhaustive]
4822pub struct McpServerStdio {
4823 pub name: String,
4827 pub command: AbsolutePath,
4831 #[serde_as(deserialize_as = "DefaultOnNull")]
4833 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4834 #[serde(default, skip_serializing_if = "Vec::is_empty")]
4835 pub args: Vec<String>,
4836 #[serde_as(deserialize_as = "DefaultOnNull")]
4839 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4840 #[serde(default, skip_serializing_if = "Vec::is_empty")]
4841 pub env: Vec<EnvVariable>,
4842 #[serde_as(deserialize_as = "DefaultOnError")]
4848 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4849 #[serde(default)]
4850 #[serde(rename = "_meta")]
4851 pub meta: Option<Meta>,
4852}
4853
4854impl McpServerStdio {
4855 #[must_use]
4857 pub fn new(name: impl Into<String>, command: impl Into<AbsolutePath>) -> Self {
4858 Self {
4859 name: name.into(),
4860 command: command.into(),
4861 args: Vec::new(),
4862 env: Vec::new(),
4863 meta: None,
4864 }
4865 }
4866
4867 #[must_use]
4869 pub fn args(mut self, args: Vec<String>) -> Self {
4870 self.args = args;
4871 self
4872 }
4873
4874 #[must_use]
4877 pub fn env(mut self, env: Vec<EnvVariable>) -> Self {
4878 self.env = env;
4879 self
4880 }
4881
4882 #[must_use]
4888 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4889 self.meta = meta.into_option();
4890 self
4891 }
4892}
4893
4894#[serde_as]
4896#[skip_serializing_none]
4897#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4898#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4899#[serde(rename_all = "camelCase")]
4900#[non_exhaustive]
4901pub struct EnvVariable {
4902 pub name: String,
4904 pub value: String,
4906 #[serde_as(deserialize_as = "DefaultOnError")]
4912 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4913 #[serde(default)]
4914 #[serde(rename = "_meta")]
4915 pub meta: Option<Meta>,
4916}
4917
4918impl EnvVariable {
4919 #[must_use]
4921 pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
4922 Self {
4923 name: name.into(),
4924 value: value.into(),
4925 meta: None,
4926 }
4927 }
4928
4929 #[must_use]
4935 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4936 self.meta = meta.into_option();
4937 self
4938 }
4939}
4940
4941#[serde_as]
4943#[skip_serializing_none]
4944#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4945#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4946#[serde(rename_all = "camelCase")]
4947#[non_exhaustive]
4948pub struct HttpHeader {
4949 pub name: String,
4951 pub value: String,
4953 #[serde_as(deserialize_as = "DefaultOnError")]
4959 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4960 #[serde(default)]
4961 #[serde(rename = "_meta")]
4962 pub meta: Option<Meta>,
4963}
4964
4965impl HttpHeader {
4966 #[must_use]
4968 pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
4969 Self {
4970 name: name.into(),
4971 value: value.into(),
4972 meta: None,
4973 }
4974 }
4975
4976 #[must_use]
4982 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4983 self.meta = meta.into_option();
4984 self
4985 }
4986}
4987
4988#[serde_as]
4997#[skip_serializing_none]
4998#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4999#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5000#[serde(rename_all = "camelCase")]
5001#[non_exhaustive]
5002pub struct SystemPrompt {
5003 pub mode: SystemPromptMode,
5008 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
5018 pub content: Vec<ContentBlock>,
5019 #[serde_as(deserialize_as = "DefaultOnError")]
5025 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5026 #[serde(default)]
5027 #[serde(rename = "_meta")]
5028 pub meta: Option<Meta>,
5029}
5030
5031impl SystemPrompt {
5032 #[must_use]
5037 pub fn new(content: Vec<ContentBlock>) -> Self {
5038 Self {
5039 mode: SystemPromptMode::default(),
5040 content,
5041 meta: None,
5042 }
5043 }
5044
5045 #[must_use]
5047 pub fn mode(mut self, mode: SystemPromptMode) -> Self {
5048 self.mode = mode;
5049 self
5050 }
5051
5052 #[must_use]
5058 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5059 self.meta = meta.into_option();
5060 self
5061 }
5062}
5063
5064#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5070#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
5071#[serde(rename_all = "snake_case")]
5072#[non_exhaustive]
5073pub enum SystemPromptMode {
5074 #[default]
5081 Append,
5082 Override,
5091 #[serde(untagged)]
5097 Other(String),
5098}
5099
5100#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5109#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash, Display)]
5110#[serde(transparent)]
5111pub struct IdempotencyKey(
5112 #[cfg_attr(feature = "schemars", schemars(length(min = 1, max = 255)))] Arc<str>,
5113);
5114
5115impl IdempotencyKey {
5116 pub const MAX_LENGTH: usize = 255;
5118
5119 pub fn new(key: impl Into<Arc<str>>) -> Result<Self, InvalidIdempotencyKey> {
5126 let key = key.into();
5127 if key.is_empty() {
5128 return Err(InvalidIdempotencyKey::Empty);
5129 }
5130 if key.chars().nth(Self::MAX_LENGTH).is_some() {
5132 return Err(InvalidIdempotencyKey::TooLong);
5133 }
5134 Ok(Self(key))
5135 }
5136
5137 #[cfg(feature = "uuid")]
5144 #[must_use]
5145 pub fn generate() -> Self {
5146 uuid::Uuid::new_v4().into()
5147 }
5148
5149 #[must_use]
5151 pub fn as_str(&self) -> &str {
5152 &self.0
5153 }
5154}
5155
5156impl AsRef<str> for IdempotencyKey {
5157 fn as_ref(&self) -> &str {
5158 &self.0
5159 }
5160}
5161
5162#[cfg(feature = "uuid")]
5163impl From<uuid::Uuid> for IdempotencyKey {
5164 fn from(uuid: uuid::Uuid) -> Self {
5167 Self(uuid.to_string().into())
5168 }
5169}
5170
5171impl TryFrom<String> for IdempotencyKey {
5172 type Error = InvalidIdempotencyKey;
5173
5174 fn try_from(key: String) -> Result<Self, Self::Error> {
5175 Self::new(key)
5176 }
5177}
5178
5179impl TryFrom<&str> for IdempotencyKey {
5180 type Error = InvalidIdempotencyKey;
5181
5182 fn try_from(key: &str) -> Result<Self, Self::Error> {
5183 Self::new(key)
5184 }
5185}
5186
5187impl std::str::FromStr for IdempotencyKey {
5188 type Err = InvalidIdempotencyKey;
5189
5190 fn from_str(key: &str) -> Result<Self, Self::Err> {
5191 Self::new(key)
5192 }
5193}
5194
5195impl<'de> Deserialize<'de> for IdempotencyKey {
5198 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
5199 where
5200 D: serde::Deserializer<'de>,
5201 {
5202 let key = Arc::<str>::deserialize(deserializer)?;
5203 Self::new(key).map_err(serde::de::Error::custom)
5204 }
5205}
5206
5207#[derive(Debug, Clone, Copy, PartialEq, Eq, Display)]
5209#[non_exhaustive]
5210pub enum InvalidIdempotencyKey {
5211 #[display("idempotency key must not be empty")]
5213 Empty,
5214 #[display(
5216 "idempotency key must be at most {} characters",
5217 IdempotencyKey::MAX_LENGTH
5218 )]
5219 TooLong,
5220}
5221
5222impl std::error::Error for InvalidIdempotencyKey {}
5223
5224#[serde_as]
5230#[skip_serializing_none]
5231#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5232#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5233#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_PROMPT_METHOD_NAME)))]
5234#[serde(rename_all = "camelCase")]
5235#[non_exhaustive]
5236pub struct PromptRequest {
5237 pub session_id: SessionId,
5239 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
5256 pub prompt: Vec<ContentBlock>,
5257 #[serde(default)]
5279 pub idempotency_key: Option<IdempotencyKey>,
5280 #[serde_as(deserialize_as = "DefaultOnError")]
5286 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5287 #[serde(default)]
5288 #[serde(rename = "_meta")]
5289 pub meta: Option<Meta>,
5290}
5291
5292impl PromptRequest {
5293 #[must_use]
5295 pub fn new(session_id: impl Into<SessionId>, prompt: Vec<ContentBlock>) -> Self {
5296 Self {
5297 session_id: session_id.into(),
5298 prompt,
5299 idempotency_key: None,
5300 meta: None,
5301 }
5302 }
5303
5304 #[must_use]
5308 pub fn idempotency_key(mut self, idempotency_key: impl IntoOption<IdempotencyKey>) -> Self {
5309 self.idempotency_key = idempotency_key.into_option();
5310 self
5311 }
5312
5313 #[must_use]
5319 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5320 self.meta = meta.into_option();
5321 self
5322 }
5323}
5324
5325#[serde_as]
5336#[skip_serializing_none]
5337#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5338#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5339#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_PROMPT_METHOD_NAME)))]
5340#[serde(rename_all = "camelCase")]
5341#[non_exhaustive]
5342pub struct PromptResponse {
5343 pub message_id: MessageId,
5351 #[serde_as(deserialize_as = "DefaultOnError")]
5357 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5358 #[serde(default)]
5359 #[serde(rename = "_meta")]
5360 pub meta: Option<Meta>,
5361}
5362
5363impl PromptResponse {
5364 #[must_use]
5366 pub fn new(message_id: impl Into<MessageId>) -> Self {
5367 Self {
5368 message_id: message_id.into(),
5369 meta: None,
5370 }
5371 }
5372
5373 #[must_use]
5379 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5380 self.meta = meta.into_option();
5381 self
5382 }
5383}
5384
5385#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5389#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
5390#[serde(tag = "stopReason", rename_all = "snake_case")]
5391#[non_exhaustive]
5392pub enum StopReason {
5393 EndTurn,
5396 MaxTokens,
5398 MaxTurnRequests,
5401 Refusal,
5403 Cancelled,
5415 Error(ErrorStopReason),
5421 #[serde(untagged)]
5427 Other(OtherStopReason),
5428}
5429
5430impl From<ErrorStopReason> for StopReason {
5431 fn from(value: ErrorStopReason) -> Self {
5432 Self::Error(value)
5433 }
5434}
5435
5436#[serde_as]
5438#[skip_serializing_none]
5439#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5440#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
5441#[serde(rename_all = "camelCase")]
5442#[non_exhaustive]
5443pub struct ErrorStopReason {
5444 #[serde_as(deserialize_as = "DefaultOnError")]
5449 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5450 #[serde(default)]
5451 pub error: Option<Box<Error>>,
5452}
5453
5454impl ErrorStopReason {
5455 #[must_use]
5457 pub fn new() -> Self {
5458 Self::default()
5459 }
5460
5461 #[must_use]
5463 pub fn error(mut self, error: impl IntoOption<Error>) -> Self {
5464 self.error = error.into_option().map(Box::new);
5465 self
5466 }
5467}
5468
5469#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5471#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
5472#[cfg_attr(feature = "schemars", schemars(inline))]
5473#[cfg_attr(feature = "schemars", schemars(transform = other_stop_reason_schema))]
5474#[serde(rename_all = "camelCase")]
5475#[non_exhaustive]
5476pub struct OtherStopReason {
5477 pub stop_reason: String,
5483 #[serde(flatten)]
5485 pub fields: IndexMap<String, serde_json::Value>,
5486}
5487
5488impl OtherStopReason {
5489 #[must_use]
5491 pub fn new(
5492 stop_reason: impl Into<String>,
5493 mut fields: IndexMap<String, serde_json::Value>,
5494 ) -> Self {
5495 remove_idle_state_update_fields(&mut fields);
5496 Self {
5497 stop_reason: stop_reason.into(),
5498 fields,
5499 }
5500 }
5501}
5502
5503impl<'de> Deserialize<'de> for OtherStopReason {
5504 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
5505 where
5506 D: serde::Deserializer<'de>,
5507 {
5508 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
5509 let stop_reason = fields
5510 .shift_remove("stopReason")
5511 .ok_or_else(|| serde::de::Error::missing_field("stopReason"))?;
5512 let serde_json::Value::String(stop_reason) = stop_reason else {
5513 return Err(serde::de::Error::custom("`stopReason` must be a string"));
5514 };
5515
5516 if KNOWN_STOP_REASONS.contains(&stop_reason.as_str()) {
5517 return Err(serde::de::Error::custom(format!(
5518 "known stop reason `{stop_reason}` did not match its schema"
5519 )));
5520 }
5521 remove_idle_state_update_fields(&mut fields);
5522
5523 Ok(Self {
5524 stop_reason,
5525 fields,
5526 })
5527 }
5528}
5529
5530const KNOWN_STOP_REASONS: &[&str] = &[
5531 "end_turn",
5532 "max_tokens",
5533 "max_turn_requests",
5534 "refusal",
5535 "cancelled",
5536 "error",
5537];
5538
5539fn remove_idle_state_update_fields(fields: &mut IndexMap<String, serde_json::Value>) {
5541 fields.shift_remove("stopReason");
5542 fields.shift_remove("usage");
5543 fields.shift_remove("_meta");
5544}
5545
5546#[cfg(feature = "schemars")]
5547fn other_stop_reason_schema(schema: &mut Schema) {
5548 super::schema_util::reject_known_string_discriminators(
5549 schema,
5550 "stopReason",
5551 KNOWN_STOP_REASONS,
5552 );
5553}
5554
5555#[cfg(feature = "unstable_end_turn_token_usage")]
5561#[serde_as]
5562#[skip_serializing_none]
5563#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5564#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5565#[serde(rename_all = "camelCase")]
5566#[non_exhaustive]
5567pub struct Usage {
5568 pub total_tokens: u64,
5570 pub input_tokens: u64,
5572 pub output_tokens: u64,
5574 #[serde_as(deserialize_as = "DefaultOnError")]
5578 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5579 #[serde(default)]
5580 pub thought_tokens: Option<u64>,
5581 #[serde_as(deserialize_as = "DefaultOnError")]
5585 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5586 #[serde(default)]
5587 pub cached_read_tokens: Option<u64>,
5588 #[serde_as(deserialize_as = "DefaultOnError")]
5592 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5593 #[serde(default)]
5594 pub cached_write_tokens: Option<u64>,
5595 #[serde_as(deserialize_as = "DefaultOnError")]
5601 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5602 #[serde(default)]
5603 #[serde(rename = "_meta")]
5604 pub meta: Option<Meta>,
5605}
5606
5607#[cfg(feature = "unstable_end_turn_token_usage")]
5608impl Usage {
5609 #[must_use]
5611 pub fn new(total_tokens: u64, input_tokens: u64, output_tokens: u64) -> Self {
5612 Self {
5613 total_tokens,
5614 input_tokens,
5615 output_tokens,
5616 thought_tokens: None,
5617 cached_read_tokens: None,
5618 cached_write_tokens: None,
5619 meta: None,
5620 }
5621 }
5622
5623 #[must_use]
5625 pub fn thought_tokens(mut self, thought_tokens: impl IntoOption<u64>) -> Self {
5626 self.thought_tokens = thought_tokens.into_option();
5627 self
5628 }
5629
5630 #[must_use]
5632 pub fn cached_read_tokens(mut self, cached_read_tokens: impl IntoOption<u64>) -> Self {
5633 self.cached_read_tokens = cached_read_tokens.into_option();
5634 self
5635 }
5636
5637 #[must_use]
5639 pub fn cached_write_tokens(mut self, cached_write_tokens: impl IntoOption<u64>) -> Self {
5640 self.cached_write_tokens = cached_write_tokens.into_option();
5641 self
5642 }
5643
5644 #[must_use]
5650 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5651 self.meta = meta.into_option();
5652 self
5653 }
5654}
5655
5656#[cfg(feature = "unstable_llm_providers")]
5669#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5670#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5671#[serde(rename_all = "snake_case")]
5672#[non_exhaustive]
5673#[expect(clippy::doc_markdown)]
5674pub enum LlmProtocol {
5675 Anthropic,
5677 #[serde(rename = "openai")]
5679 OpenAi,
5680 Azure,
5682 Vertex,
5684 Bedrock,
5686 #[serde(untagged)]
5692 Other(String),
5693}
5694
5695#[cfg(feature = "unstable_llm_providers")]
5701#[serde_as]
5702#[skip_serializing_none]
5703#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5704#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5705#[serde(rename_all = "camelCase")]
5706#[non_exhaustive]
5707pub struct ProviderCurrentConfig {
5708 pub api_type: LlmProtocol,
5710 #[cfg_attr(feature = "schemars", schemars(url))]
5712 pub base_url: String,
5713 #[serde_as(deserialize_as = "DefaultOnError")]
5719 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5720 #[serde(default)]
5721 #[serde(rename = "_meta")]
5722 pub meta: Option<Meta>,
5723}
5724
5725#[cfg(feature = "unstable_llm_providers")]
5726impl ProviderCurrentConfig {
5727 #[must_use]
5729 pub fn new(api_type: LlmProtocol, base_url: impl Into<String>) -> Self {
5730 Self {
5731 api_type,
5732 base_url: base_url.into(),
5733 meta: None,
5734 }
5735 }
5736
5737 #[must_use]
5743 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5744 self.meta = meta.into_option();
5745 self
5746 }
5747}
5748
5749#[cfg(feature = "unstable_llm_providers")]
5755#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5756#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
5757#[serde(transparent)]
5758#[from(forward)]
5759#[non_exhaustive]
5760pub struct ProviderId(pub Arc<str>);
5761
5762#[cfg(feature = "unstable_llm_providers")]
5763impl ProviderId {
5764 #[must_use]
5766 pub fn new(id: impl Into<Self>) -> Self {
5767 id.into()
5768 }
5769}
5770
5771#[cfg(feature = "unstable_llm_providers")]
5777#[serde_as]
5778#[skip_serializing_none]
5779#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5780#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5781#[serde(rename_all = "camelCase")]
5782#[non_exhaustive]
5783pub struct ProviderInfo {
5784 pub provider_id: ProviderId,
5786 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
5788 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
5789 pub supported: Vec<LlmProtocol>,
5790 pub required: bool,
5793 #[serde(default)]
5796 pub current: Option<ProviderCurrentConfig>,
5797 #[serde_as(deserialize_as = "DefaultOnError")]
5803 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5804 #[serde(default)]
5805 #[serde(rename = "_meta")]
5806 pub meta: Option<Meta>,
5807}
5808
5809#[cfg(feature = "unstable_llm_providers")]
5810impl ProviderInfo {
5811 #[must_use]
5813 pub fn new(
5814 provider_id: impl Into<ProviderId>,
5815 supported: Vec<LlmProtocol>,
5816 required: bool,
5817 current: impl IntoOption<ProviderCurrentConfig>,
5818 ) -> Self {
5819 Self {
5820 provider_id: provider_id.into(),
5821 supported,
5822 required,
5823 current: current.into_option(),
5824 meta: None,
5825 }
5826 }
5827
5828 #[must_use]
5834 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5835 self.meta = meta.into_option();
5836 self
5837 }
5838}
5839
5840#[cfg(feature = "unstable_llm_providers")]
5841crate::serde_util::default_on_null! {
5842 #[serde_as]
5848 #[skip_serializing_none]
5849 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5850 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
5851 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_LIST_METHOD_NAME)))]
5852 #[serde(rename_all = "camelCase")]
5853 #[non_exhaustive]
5854 pub struct ListProvidersRequest {
5855 #[serde_as(deserialize_as = "DefaultOnError")]
5861 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5862 #[serde(default)]
5863 #[serde(rename = "_meta")]
5864 pub meta: Option<Meta>,
5865 }
5866}
5867
5868#[cfg(feature = "unstable_llm_providers")]
5869impl ListProvidersRequest {
5870 #[must_use]
5872 pub fn new() -> Self {
5873 Self::default()
5874 }
5875
5876 #[must_use]
5882 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5883 self.meta = meta.into_option();
5884 self
5885 }
5886}
5887
5888#[cfg(feature = "unstable_llm_providers")]
5894#[serde_as]
5895#[skip_serializing_none]
5896#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5897#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5898#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_LIST_METHOD_NAME)))]
5899#[serde(rename_all = "camelCase")]
5900#[non_exhaustive]
5901pub struct ListProvidersResponse {
5902 pub providers: Vec<ProviderInfo>,
5904 #[serde_as(deserialize_as = "DefaultOnError")]
5910 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5911 #[serde(default)]
5912 #[serde(rename = "_meta")]
5913 pub meta: Option<Meta>,
5914}
5915
5916#[cfg(feature = "unstable_llm_providers")]
5917impl ListProvidersResponse {
5918 #[must_use]
5920 pub fn new(providers: Vec<ProviderInfo>) -> Self {
5921 Self {
5922 providers,
5923 meta: None,
5924 }
5925 }
5926
5927 #[must_use]
5933 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5934 self.meta = meta.into_option();
5935 self
5936 }
5937}
5938
5939#[cfg(feature = "unstable_llm_providers")]
5947#[serde_as]
5948#[skip_serializing_none]
5949#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5950#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
5951#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_SET_METHOD_NAME)))]
5952#[serde(rename_all = "camelCase")]
5953#[non_exhaustive]
5954pub struct SetProviderRequest {
5955 pub provider_id: ProviderId,
5957 pub api_type: LlmProtocol,
5959 #[cfg_attr(feature = "schemars", schemars(url))]
5961 pub base_url: String,
5962 #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
5965 pub headers: IndexMap<String, String>,
5966 #[serde_as(deserialize_as = "DefaultOnError")]
5972 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5973 #[serde(default)]
5974 #[serde(rename = "_meta")]
5975 pub meta: Option<Meta>,
5976}
5977
5978#[cfg(feature = "unstable_llm_providers")]
5979impl SetProviderRequest {
5980 #[must_use]
5982 pub fn new(
5983 provider_id: impl Into<ProviderId>,
5984 api_type: LlmProtocol,
5985 base_url: impl Into<String>,
5986 ) -> Self {
5987 Self {
5988 provider_id: provider_id.into(),
5989 api_type,
5990 base_url: base_url.into(),
5991 headers: IndexMap::new(),
5992 meta: None,
5993 }
5994 }
5995
5996 #[must_use]
5999 pub fn headers(mut self, headers: IndexMap<String, String>) -> Self {
6000 self.headers = headers;
6001 self
6002 }
6003
6004 #[must_use]
6010 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6011 self.meta = meta.into_option();
6012 self
6013 }
6014}
6015
6016#[cfg(feature = "unstable_llm_providers")]
6017crate::serde_util::default_on_null! {
6018 #[serde_as]
6024 #[skip_serializing_none]
6025 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6026 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
6027 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_SET_METHOD_NAME)))]
6028 #[serde(rename_all = "camelCase")]
6029 #[non_exhaustive]
6030 pub struct SetProviderResponse {
6031 #[serde_as(deserialize_as = "DefaultOnError")]
6037 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6038 #[serde(default)]
6039 #[serde(rename = "_meta")]
6040 pub meta: Option<Meta>,
6041 }
6042}
6043
6044#[cfg(feature = "unstable_llm_providers")]
6045impl SetProviderResponse {
6046 #[must_use]
6048 pub fn new() -> Self {
6049 Self::default()
6050 }
6051
6052 #[must_use]
6058 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6059 self.meta = meta.into_option();
6060 self
6061 }
6062}
6063
6064#[cfg(feature = "unstable_llm_providers")]
6070#[serde_as]
6071#[skip_serializing_none]
6072#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6073#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6074#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_DISABLE_METHOD_NAME)))]
6075#[serde(rename_all = "camelCase")]
6076#[non_exhaustive]
6077pub struct DisableProviderRequest {
6078 pub provider_id: ProviderId,
6080 #[serde_as(deserialize_as = "DefaultOnError")]
6086 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6087 #[serde(default)]
6088 #[serde(rename = "_meta")]
6089 pub meta: Option<Meta>,
6090}
6091
6092#[cfg(feature = "unstable_llm_providers")]
6093impl DisableProviderRequest {
6094 #[must_use]
6096 pub fn new(provider_id: impl Into<ProviderId>) -> Self {
6097 Self {
6098 provider_id: provider_id.into(),
6099 meta: None,
6100 }
6101 }
6102
6103 #[must_use]
6109 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6110 self.meta = meta.into_option();
6111 self
6112 }
6113}
6114
6115#[cfg(feature = "unstable_llm_providers")]
6116crate::serde_util::default_on_null! {
6117 #[serde_as]
6123 #[skip_serializing_none]
6124 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6125 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
6126 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_DISABLE_METHOD_NAME)))]
6127 #[serde(rename_all = "camelCase")]
6128 #[non_exhaustive]
6129 pub struct DisableProviderResponse {
6130 #[serde_as(deserialize_as = "DefaultOnError")]
6136 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6137 #[serde(default)]
6138 #[serde(rename = "_meta")]
6139 pub meta: Option<Meta>,
6140 }
6141}
6142
6143#[cfg(feature = "unstable_llm_providers")]
6144impl DisableProviderResponse {
6145 #[must_use]
6147 pub fn new() -> Self {
6148 Self::default()
6149 }
6150
6151 #[must_use]
6157 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6158 self.meta = meta.into_option();
6159 self
6160 }
6161}
6162
6163#[serde_as]
6172#[skip_serializing_none]
6173#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6174#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6175#[serde(rename_all = "camelCase")]
6176#[non_exhaustive]
6177pub struct AgentCapabilities {
6178 #[serde_as(deserialize_as = "DefaultOnError")]
6186 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6187 #[serde(default)]
6188 pub session: Option<SessionCapabilities>,
6189 #[serde_as(deserialize_as = "DefaultOnError")]
6196 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6197 #[serde(default)]
6198 pub auth: Option<AgentAuthCapabilities>,
6199 #[cfg(feature = "unstable_llm_providers")]
6208 #[serde_as(deserialize_as = "DefaultOnError")]
6209 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6210 #[serde(default)]
6211 pub providers: Option<ProvidersCapabilities>,
6212 #[serde_as(deserialize_as = "DefaultOnError")]
6218 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6219 #[serde(default)]
6220 #[serde(rename = "_meta")]
6221 pub meta: Option<Meta>,
6222}
6223
6224impl AgentCapabilities {
6225 #[must_use]
6227 pub fn new() -> Self {
6228 Self::default()
6229 }
6230
6231 #[must_use]
6239 pub fn session(mut self, session: impl IntoOption<SessionCapabilities>) -> Self {
6240 self.session = session.into_option();
6241 self
6242 }
6243
6244 #[must_use]
6248 pub fn auth(mut self, auth: impl IntoOption<AgentAuthCapabilities>) -> Self {
6249 self.auth = auth.into_option();
6250 self
6251 }
6252
6253 #[cfg(feature = "unstable_llm_providers")]
6259 #[must_use]
6260 pub fn providers(mut self, providers: impl IntoOption<ProvidersCapabilities>) -> Self {
6261 self.providers = providers.into_option();
6262 self
6263 }
6264
6265 #[must_use]
6271 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6272 self.meta = meta.into_option();
6273 self
6274 }
6275}
6276
6277#[cfg(feature = "unstable_llm_providers")]
6285#[serde_as]
6286#[skip_serializing_none]
6287#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6288#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6289#[non_exhaustive]
6290pub struct ProvidersCapabilities {
6291 #[serde_as(deserialize_as = "DefaultOnError")]
6297 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6298 #[serde(default)]
6299 #[serde(rename = "_meta")]
6300 pub meta: Option<Meta>,
6301}
6302
6303#[cfg(feature = "unstable_llm_providers")]
6304impl ProvidersCapabilities {
6305 #[must_use]
6307 pub fn new() -> Self {
6308 Self::default()
6309 }
6310
6311 #[must_use]
6317 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6318 self.meta = meta.into_option();
6319 self
6320 }
6321}
6322
6323#[serde_as]
6335#[skip_serializing_none]
6336#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6337#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6338#[serde(rename_all = "camelCase")]
6339#[non_exhaustive]
6340pub struct SessionCapabilities {
6341 #[serde_as(deserialize_as = "DefaultOnError")]
6347 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6348 #[serde(default)]
6349 pub prompt: Option<PromptCapabilities>,
6350 #[serde_as(deserialize_as = "DefaultOnError")]
6355 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6356 #[serde(default)]
6357 pub mcp: Option<McpCapabilities>,
6358 #[serde_as(deserialize_as = "DefaultOnError")]
6363 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6364 #[serde(default)]
6365 pub delete: Option<SessionDeleteCapabilities>,
6366 #[serde_as(deserialize_as = "DefaultOnError")]
6375 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6376 #[serde(default)]
6377 pub additional_directories: Option<SessionAdditionalDirectoriesCapabilities>,
6378 #[serde_as(deserialize_as = "DefaultOnError")]
6383 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6384 #[serde(default)]
6385 pub system_prompt: Option<SessionSystemPromptCapabilities>,
6386 #[cfg(feature = "unstable_session_fork")]
6395 #[serde_as(deserialize_as = "DefaultOnError")]
6396 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6397 #[serde(default)]
6398 pub fork: Option<SessionForkCapabilities>,
6399 #[cfg(feature = "unstable_session_archive")]
6409 #[serde_as(deserialize_as = "DefaultOnError")]
6410 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6411 #[serde(default)]
6412 pub archive: Option<SessionArchiveCapabilities>,
6413 #[cfg(feature = "unstable_session_status")]
6422 #[serde_as(deserialize_as = "DefaultOnError")]
6423 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6424 #[serde(default)]
6425 pub status: Option<SessionStatusCapabilities>,
6426 #[cfg(feature = "unstable_session_options")]
6436 #[serde_as(deserialize_as = "DefaultOnError")]
6437 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6438 #[serde(default)]
6439 pub options: Option<SessionOptionsCapabilities>,
6440 #[cfg(feature = "unstable_session_set_title")]
6452 #[serde_as(deserialize_as = "DefaultOnError")]
6453 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6454 #[serde(default)]
6455 pub title: Option<SessionTitleCapabilities>,
6456 #[serde_as(deserialize_as = "DefaultOnError")]
6462 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6463 #[serde(default)]
6464 #[serde(rename = "_meta")]
6465 pub meta: Option<Meta>,
6466}
6467
6468impl SessionCapabilities {
6469 #[must_use]
6471 pub fn new() -> Self {
6472 Self::default()
6473 }
6474
6475 #[must_use]
6481 pub fn prompt(mut self, prompt: impl IntoOption<PromptCapabilities>) -> Self {
6482 self.prompt = prompt.into_option();
6483 self
6484 }
6485
6486 #[must_use]
6491 pub fn mcp(mut self, mcp: impl IntoOption<McpCapabilities>) -> Self {
6492 self.mcp = mcp.into_option();
6493 self
6494 }
6495
6496 #[must_use]
6501 pub fn delete(mut self, delete: impl IntoOption<SessionDeleteCapabilities>) -> Self {
6502 self.delete = delete.into_option();
6503 self
6504 }
6505
6506 #[must_use]
6515 pub fn additional_directories(
6516 mut self,
6517 additional_directories: impl IntoOption<SessionAdditionalDirectoriesCapabilities>,
6518 ) -> Self {
6519 self.additional_directories = additional_directories.into_option();
6520 self
6521 }
6522
6523 #[must_use]
6528 pub fn system_prompt(
6529 mut self,
6530 system_prompt: impl IntoOption<SessionSystemPromptCapabilities>,
6531 ) -> Self {
6532 self.system_prompt = system_prompt.into_option();
6533 self
6534 }
6535
6536 #[cfg(feature = "unstable_session_fork")]
6537 #[must_use]
6542 pub fn fork(mut self, fork: impl IntoOption<SessionForkCapabilities>) -> Self {
6543 self.fork = fork.into_option();
6544 self
6545 }
6546
6547 #[cfg(feature = "unstable_session_archive")]
6557 #[must_use]
6558 pub fn archive(mut self, archive: impl IntoOption<SessionArchiveCapabilities>) -> Self {
6559 self.archive = archive.into_option();
6560 self
6561 }
6562
6563 #[cfg(feature = "unstable_session_status")]
6572 #[must_use]
6573 pub fn status(mut self, status: impl IntoOption<SessionStatusCapabilities>) -> Self {
6574 self.status = status.into_option();
6575 self
6576 }
6577
6578 #[cfg(feature = "unstable_session_options")]
6588 #[must_use]
6589 pub fn options(mut self, options: impl IntoOption<SessionOptionsCapabilities>) -> Self {
6590 self.options = options.into_option();
6591 self
6592 }
6593
6594 #[cfg(feature = "unstable_session_set_title")]
6606 #[must_use]
6607 pub fn title(mut self, title: impl IntoOption<SessionTitleCapabilities>) -> Self {
6608 self.title = title.into_option();
6609 self
6610 }
6611
6612 #[must_use]
6618 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6619 self.meta = meta.into_option();
6620 self
6621 }
6622}
6623
6624#[serde_as]
6628#[skip_serializing_none]
6629#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6630#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6631#[non_exhaustive]
6632pub struct SessionDeleteCapabilities {
6633 #[serde_as(deserialize_as = "DefaultOnError")]
6639 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6640 #[serde(default)]
6641 #[serde(rename = "_meta")]
6642 pub meta: Option<Meta>,
6643}
6644
6645impl SessionDeleteCapabilities {
6646 #[must_use]
6648 pub fn new() -> Self {
6649 Self::default()
6650 }
6651
6652 #[must_use]
6658 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6659 self.meta = meta.into_option();
6660 self
6661 }
6662}
6663
6664#[serde_as]
6671#[skip_serializing_none]
6672#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6673#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6674#[non_exhaustive]
6675pub struct SessionAdditionalDirectoriesCapabilities {
6676 #[serde_as(deserialize_as = "DefaultOnError")]
6682 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6683 #[serde(default)]
6684 #[serde(rename = "_meta")]
6685 pub meta: Option<Meta>,
6686}
6687
6688impl SessionAdditionalDirectoriesCapabilities {
6689 #[must_use]
6691 pub fn new() -> Self {
6692 Self::default()
6693 }
6694
6695 #[must_use]
6701 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6702 self.meta = meta.into_option();
6703 self
6704 }
6705}
6706
6707#[serde_as]
6712#[skip_serializing_none]
6713#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6714#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6715#[serde(rename_all = "camelCase")]
6716#[non_exhaustive]
6717pub struct SessionSystemPromptCapabilities {
6718 #[serde_as(deserialize_as = "DefaultOnError")]
6722 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6723 #[serde(default)]
6724 pub mode: Option<SessionSystemPromptModeCapabilities>,
6725 #[serde_as(deserialize_as = "DefaultOnError")]
6731 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6732 #[serde(default)]
6733 #[serde(rename = "_meta")]
6734 pub meta: Option<Meta>,
6735}
6736
6737impl SessionSystemPromptCapabilities {
6738 #[must_use]
6740 pub fn new() -> Self {
6741 Self::default()
6742 }
6743
6744 #[must_use]
6748 pub fn mode(mut self, mode: impl IntoOption<SessionSystemPromptModeCapabilities>) -> Self {
6749 self.mode = mode.into_option();
6750 self
6751 }
6752
6753 #[must_use]
6759 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6760 self.meta = meta.into_option();
6761 self
6762 }
6763}
6764
6765#[serde_as]
6770#[skip_serializing_none]
6771#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6772#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6773#[serde(rename_all = "camelCase")]
6774#[non_exhaustive]
6775pub struct SessionSystemPromptModeCapabilities {
6776 #[serde_as(deserialize_as = "DefaultOnError")]
6782 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6783 #[serde(default, rename = "override")]
6784 pub override_: Option<SessionSystemPromptOverrideCapabilities>,
6785 #[serde_as(deserialize_as = "DefaultOnError")]
6791 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6792 #[serde(default)]
6793 #[serde(rename = "_meta")]
6794 pub meta: Option<Meta>,
6795}
6796
6797impl SessionSystemPromptModeCapabilities {
6798 #[must_use]
6800 pub fn new() -> Self {
6801 Self::default()
6802 }
6803
6804 #[must_use]
6810 pub fn override_(
6811 mut self,
6812 override_: impl IntoOption<SessionSystemPromptOverrideCapabilities>,
6813 ) -> Self {
6814 self.override_ = override_.into_option();
6815 self
6816 }
6817
6818 #[must_use]
6824 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6825 self.meta = meta.into_option();
6826 self
6827 }
6828}
6829
6830#[serde_as]
6835#[skip_serializing_none]
6836#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6837#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6838#[non_exhaustive]
6839pub struct SessionSystemPromptOverrideCapabilities {
6840 #[serde_as(deserialize_as = "DefaultOnError")]
6846 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6847 #[serde(default)]
6848 #[serde(rename = "_meta")]
6849 pub meta: Option<Meta>,
6850}
6851
6852impl SessionSystemPromptOverrideCapabilities {
6853 #[must_use]
6855 pub fn new() -> Self {
6856 Self::default()
6857 }
6858
6859 #[must_use]
6865 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6866 self.meta = meta.into_option();
6867 self
6868 }
6869}
6870
6871#[cfg(feature = "unstable_session_fork")]
6879#[serde_as]
6880#[skip_serializing_none]
6881#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6882#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6883#[non_exhaustive]
6884pub struct SessionForkCapabilities {
6885 #[serde_as(deserialize_as = "DefaultOnError")]
6891 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6892 #[serde(default)]
6893 #[serde(rename = "_meta")]
6894 pub meta: Option<Meta>,
6895}
6896
6897#[cfg(feature = "unstable_session_fork")]
6898impl SessionForkCapabilities {
6899 #[must_use]
6901 pub fn new() -> Self {
6902 Self::default()
6903 }
6904
6905 #[must_use]
6911 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6912 self.meta = meta.into_option();
6913 self
6914 }
6915}
6916
6917#[cfg(feature = "unstable_session_archive")]
6926#[serde_as]
6927#[skip_serializing_none]
6928#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6929#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6930#[non_exhaustive]
6931pub struct SessionArchiveCapabilities {
6932 #[serde_as(deserialize_as = "DefaultOnError")]
6938 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6939 #[serde(default)]
6940 #[serde(rename = "_meta")]
6941 pub meta: Option<Meta>,
6942}
6943
6944#[cfg(feature = "unstable_session_archive")]
6945impl SessionArchiveCapabilities {
6946 #[must_use]
6948 pub fn new() -> Self {
6949 Self::default()
6950 }
6951
6952 #[must_use]
6958 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6959 self.meta = meta.into_option();
6960 self
6961 }
6962}
6963
6964#[cfg(feature = "unstable_session_status")]
6972#[serde_as]
6973#[skip_serializing_none]
6974#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6975#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6976#[non_exhaustive]
6977pub struct SessionStatusCapabilities {
6978 #[serde_as(deserialize_as = "DefaultOnError")]
6984 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6985 #[serde(default)]
6986 #[serde(rename = "_meta")]
6987 pub meta: Option<Meta>,
6988}
6989
6990#[cfg(feature = "unstable_session_status")]
6991impl SessionStatusCapabilities {
6992 #[must_use]
6994 pub fn new() -> Self {
6995 Self::default()
6996 }
6997
6998 #[must_use]
7004 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7005 self.meta = meta.into_option();
7006 self
7007 }
7008}
7009
7010#[cfg(feature = "unstable_session_options")]
7019#[serde_as]
7020#[skip_serializing_none]
7021#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7022#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7023#[non_exhaustive]
7024pub struct SessionOptionsCapabilities {
7025 #[serde_as(deserialize_as = "DefaultOnError")]
7031 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7032 #[serde(default)]
7033 #[serde(rename = "_meta")]
7034 pub meta: Option<Meta>,
7035}
7036
7037#[cfg(feature = "unstable_session_options")]
7038impl SessionOptionsCapabilities {
7039 #[must_use]
7041 pub fn new() -> Self {
7042 Self::default()
7043 }
7044
7045 #[must_use]
7051 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7052 self.meta = meta.into_option();
7053 self
7054 }
7055}
7056
7057#[cfg(feature = "unstable_session_set_title")]
7066#[serde_as]
7067#[skip_serializing_none]
7068#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7069#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7070#[non_exhaustive]
7071pub struct SessionTitleCapabilities {
7072 #[serde_as(deserialize_as = "DefaultOnError")]
7078 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7079 #[serde(default)]
7080 #[serde(rename = "_meta")]
7081 pub meta: Option<Meta>,
7082}
7083
7084#[cfg(feature = "unstable_session_set_title")]
7085impl SessionTitleCapabilities {
7086 #[must_use]
7088 pub fn new() -> Self {
7089 Self::default()
7090 }
7091
7092 #[must_use]
7098 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7099 self.meta = meta.into_option();
7100 self
7101 }
7102}
7103
7104#[serde_as]
7117#[skip_serializing_none]
7118#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7119#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7120#[serde(rename_all = "camelCase")]
7121#[non_exhaustive]
7122pub struct PromptCapabilities {
7123 #[serde_as(deserialize_as = "DefaultOnError")]
7128 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7129 #[serde(default)]
7130 pub image: Option<PromptImageCapabilities>,
7131 #[serde_as(deserialize_as = "DefaultOnError")]
7136 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7137 #[serde(default)]
7138 pub audio: Option<PromptAudioCapabilities>,
7139 #[serde_as(deserialize_as = "DefaultOnError")]
7147 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7148 #[serde(default)]
7149 pub embedded_context: Option<PromptEmbeddedContextCapabilities>,
7150 #[cfg(feature = "unstable_agent_skills")]
7160 #[serde_as(deserialize_as = "DefaultOnError")]
7161 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7162 #[serde(default)]
7163 pub skill: Option<PromptSkillCapabilities>,
7164 #[serde_as(deserialize_as = "DefaultOnError")]
7170 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7171 #[serde(default)]
7172 #[serde(rename = "_meta")]
7173 pub meta: Option<Meta>,
7174}
7175
7176impl PromptCapabilities {
7177 #[must_use]
7179 pub fn new() -> Self {
7180 Self::default()
7181 }
7182
7183 #[must_use]
7188 pub fn image(mut self, image: impl IntoOption<PromptImageCapabilities>) -> Self {
7189 self.image = image.into_option();
7190 self
7191 }
7192
7193 #[must_use]
7198 pub fn audio(mut self, audio: impl IntoOption<PromptAudioCapabilities>) -> Self {
7199 self.audio = audio.into_option();
7200 self
7201 }
7202
7203 #[must_use]
7211 pub fn embedded_context(
7212 mut self,
7213 embedded_context: impl IntoOption<PromptEmbeddedContextCapabilities>,
7214 ) -> Self {
7215 self.embedded_context = embedded_context.into_option();
7216 self
7217 }
7218
7219 #[cfg(feature = "unstable_agent_skills")]
7228 #[must_use]
7229 pub fn skill(mut self, skill: impl IntoOption<PromptSkillCapabilities>) -> Self {
7230 self.skill = skill.into_option();
7231 self
7232 }
7233
7234 #[must_use]
7240 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7241 self.meta = meta.into_option();
7242 self
7243 }
7244}
7245
7246#[serde_as]
7250#[skip_serializing_none]
7251#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7252#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7253#[non_exhaustive]
7254pub struct PromptImageCapabilities {
7255 #[serde_as(deserialize_as = "DefaultOnError")]
7261 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7262 #[serde(default)]
7263 #[serde(rename = "_meta")]
7264 pub meta: Option<Meta>,
7265}
7266
7267impl PromptImageCapabilities {
7268 #[must_use]
7270 pub fn new() -> Self {
7271 Self::default()
7272 }
7273
7274 #[must_use]
7280 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7281 self.meta = meta.into_option();
7282 self
7283 }
7284}
7285
7286#[serde_as]
7290#[skip_serializing_none]
7291#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7292#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7293#[non_exhaustive]
7294pub struct PromptAudioCapabilities {
7295 #[serde_as(deserialize_as = "DefaultOnError")]
7301 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7302 #[serde(default)]
7303 #[serde(rename = "_meta")]
7304 pub meta: Option<Meta>,
7305}
7306
7307impl PromptAudioCapabilities {
7308 #[must_use]
7310 pub fn new() -> Self {
7311 Self::default()
7312 }
7313
7314 #[must_use]
7320 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7321 self.meta = meta.into_option();
7322 self
7323 }
7324}
7325
7326#[serde_as]
7330#[skip_serializing_none]
7331#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7332#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7333#[non_exhaustive]
7334pub struct PromptEmbeddedContextCapabilities {
7335 #[serde_as(deserialize_as = "DefaultOnError")]
7341 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7342 #[serde(default)]
7343 #[serde(rename = "_meta")]
7344 pub meta: Option<Meta>,
7345}
7346
7347impl PromptEmbeddedContextCapabilities {
7348 #[must_use]
7350 pub fn new() -> Self {
7351 Self::default()
7352 }
7353
7354 #[must_use]
7360 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7361 self.meta = meta.into_option();
7362 self
7363 }
7364}
7365
7366#[cfg(feature = "unstable_agent_skills")]
7375#[serde_as]
7376#[skip_serializing_none]
7377#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7378#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7379#[serde(rename_all = "camelCase")]
7380#[non_exhaustive]
7381pub struct PromptSkillCapabilities {
7382 #[serde_as(deserialize_as = "DefaultOnError")]
7388 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7389 #[serde(default)]
7390 pub inline: Option<PromptSkillInlineCapabilities>,
7391 #[serde_as(deserialize_as = "DefaultOnError")]
7397 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7398 #[serde(default)]
7399 #[serde(rename = "_meta")]
7400 pub meta: Option<Meta>,
7401}
7402
7403#[cfg(feature = "unstable_agent_skills")]
7404impl PromptSkillCapabilities {
7405 #[must_use]
7407 pub fn new() -> Self {
7408 Self::default()
7409 }
7410
7411 #[must_use]
7417 pub fn inline(mut self, inline: impl IntoOption<PromptSkillInlineCapabilities>) -> Self {
7418 self.inline = inline.into_option();
7419 self
7420 }
7421
7422 #[must_use]
7428 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7429 self.meta = meta.into_option();
7430 self
7431 }
7432}
7433
7434#[cfg(feature = "unstable_agent_skills")]
7443#[serde_as]
7444#[skip_serializing_none]
7445#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7446#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7447#[non_exhaustive]
7448pub struct PromptSkillInlineCapabilities {
7449 #[serde_as(deserialize_as = "DefaultOnError")]
7455 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7456 #[serde(default)]
7457 #[serde(rename = "_meta")]
7458 pub meta: Option<Meta>,
7459}
7460
7461#[cfg(feature = "unstable_agent_skills")]
7462impl PromptSkillInlineCapabilities {
7463 #[must_use]
7465 pub fn new() -> Self {
7466 Self::default()
7467 }
7468
7469 #[must_use]
7475 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7476 self.meta = meta.into_option();
7477 self
7478 }
7479}
7480
7481#[serde_as]
7483#[skip_serializing_none]
7484#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7485#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7486#[serde(rename_all = "camelCase")]
7487#[non_exhaustive]
7488pub struct McpCapabilities {
7489 #[serde_as(deserialize_as = "DefaultOnError")]
7494 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7495 #[serde(default)]
7496 pub stdio: Option<McpStdioCapabilities>,
7497 #[serde_as(deserialize_as = "DefaultOnError")]
7502 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7503 #[serde(default)]
7504 pub http: Option<McpHttpCapabilities>,
7505 #[cfg(feature = "unstable_mcp_over_acp")]
7514 #[serde_as(deserialize_as = "DefaultOnError")]
7515 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7516 #[serde(default)]
7517 pub acp: Option<McpAcpCapabilities>,
7518 #[serde_as(deserialize_as = "DefaultOnError")]
7524 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7525 #[serde(default)]
7526 #[serde(rename = "_meta")]
7527 pub meta: Option<Meta>,
7528}
7529
7530impl McpCapabilities {
7531 #[must_use]
7533 pub fn new() -> Self {
7534 Self::default()
7535 }
7536
7537 #[must_use]
7542 pub fn stdio(mut self, stdio: impl IntoOption<McpStdioCapabilities>) -> Self {
7543 self.stdio = stdio.into_option();
7544 self
7545 }
7546
7547 #[must_use]
7552 pub fn http(mut self, http: impl IntoOption<McpHttpCapabilities>) -> Self {
7553 self.http = http.into_option();
7554 self
7555 }
7556
7557 #[cfg(feature = "unstable_mcp_over_acp")]
7563 #[must_use]
7567 pub fn acp(mut self, acp: impl IntoOption<McpAcpCapabilities>) -> Self {
7568 self.acp = acp.into_option();
7569 self
7570 }
7571
7572 #[must_use]
7578 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7579 self.meta = meta.into_option();
7580 self
7581 }
7582}
7583
7584#[serde_as]
7588#[skip_serializing_none]
7589#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7590#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7591#[non_exhaustive]
7592pub struct McpStdioCapabilities {
7593 #[serde_as(deserialize_as = "DefaultOnError")]
7599 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7600 #[serde(default)]
7601 #[serde(rename = "_meta")]
7602 pub meta: Option<Meta>,
7603}
7604
7605impl McpStdioCapabilities {
7606 #[must_use]
7608 pub fn new() -> Self {
7609 Self::default()
7610 }
7611
7612 #[must_use]
7618 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7619 self.meta = meta.into_option();
7620 self
7621 }
7622}
7623
7624#[serde_as]
7628#[skip_serializing_none]
7629#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7630#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7631#[non_exhaustive]
7632pub struct McpHttpCapabilities {
7633 #[serde_as(deserialize_as = "DefaultOnError")]
7639 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7640 #[serde(default)]
7641 #[serde(rename = "_meta")]
7642 pub meta: Option<Meta>,
7643}
7644
7645impl McpHttpCapabilities {
7646 #[must_use]
7648 pub fn new() -> Self {
7649 Self::default()
7650 }
7651
7652 #[must_use]
7658 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7659 self.meta = meta.into_option();
7660 self
7661 }
7662}
7663
7664#[cfg(feature = "unstable_mcp_over_acp")]
7672#[serde_as]
7673#[skip_serializing_none]
7674#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7675#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7676#[non_exhaustive]
7677pub struct McpAcpCapabilities {
7678 #[serde_as(deserialize_as = "DefaultOnError")]
7684 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7685 #[serde(default)]
7686 #[serde(rename = "_meta")]
7687 pub meta: Option<Meta>,
7688}
7689
7690#[cfg(feature = "unstable_mcp_over_acp")]
7691impl McpAcpCapabilities {
7692 #[must_use]
7694 pub fn new() -> Self {
7695 Self::default()
7696 }
7697
7698 #[must_use]
7704 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7705 self.meta = meta.into_option();
7706 self
7707 }
7708}
7709
7710#[serde_as]
7715#[skip_serializing_none]
7716#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7717#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7718#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CANCEL_METHOD_NAME)))]
7719#[serde(rename_all = "camelCase")]
7720#[non_exhaustive]
7721pub struct CancelSessionNotification {
7722 pub session_id: SessionId,
7724 #[serde_as(deserialize_as = "DefaultOnError")]
7730 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7731 #[serde(default)]
7732 #[serde(rename = "_meta")]
7733 pub meta: Option<Meta>,
7734}
7735
7736impl CancelSessionNotification {
7737 #[must_use]
7739 pub fn new(session_id: impl Into<SessionId>) -> Self {
7740 Self {
7741 session_id: session_id.into(),
7742 meta: None,
7743 }
7744 }
7745
7746 #[must_use]
7752 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7753 self.meta = meta.into_option();
7754 self
7755 }
7756}
7757
7758#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7764#[non_exhaustive]
7765pub struct AgentMethodNames {
7766 pub initialize: &'static str,
7768 pub auth_login: &'static str,
7770 #[cfg(feature = "unstable_llm_providers")]
7772 pub providers_list: &'static str,
7773 #[cfg(feature = "unstable_llm_providers")]
7775 pub providers_set: &'static str,
7776 #[cfg(feature = "unstable_llm_providers")]
7778 pub providers_disable: &'static str,
7779 pub session_new: &'static str,
7781 pub session_set_config_option: &'static str,
7783 pub session_prompt: &'static str,
7785 pub session_cancel: &'static str,
7787 #[cfg(feature = "unstable_mcp_over_acp")]
7789 pub mcp_message: &'static str,
7790 pub session_list: &'static str,
7792 pub session_delete: &'static str,
7794 #[cfg(feature = "unstable_session_fork")]
7796 pub session_fork: &'static str,
7797 #[cfg(feature = "unstable_session_archive")]
7799 pub session_archive: &'static str,
7800 #[cfg(feature = "unstable_session_archive")]
7802 pub session_unarchive: &'static str,
7803 #[cfg(feature = "unstable_session_status")]
7805 pub session_status: &'static str,
7806 #[cfg(feature = "unstable_session_options")]
7808 pub session_options: &'static str,
7809 #[cfg(feature = "unstable_session_set_title")]
7811 pub session_set_title: &'static str,
7812 pub session_resume: &'static str,
7814 pub session_close: &'static str,
7816 pub tool_call_cancel: &'static str,
7818 pub terminal_cancel: &'static str,
7820 pub auth_logout: &'static str,
7822 #[cfg(feature = "unstable_auth_status")]
7824 pub auth_status: &'static str,
7825}
7826
7827pub const AGENT_METHOD_NAMES: AgentMethodNames = AgentMethodNames {
7829 initialize: INITIALIZE_METHOD_NAME,
7830 auth_login: AUTH_LOGIN_METHOD_NAME,
7831 #[cfg(feature = "unstable_llm_providers")]
7832 providers_list: PROVIDERS_LIST_METHOD_NAME,
7833 #[cfg(feature = "unstable_llm_providers")]
7834 providers_set: PROVIDERS_SET_METHOD_NAME,
7835 #[cfg(feature = "unstable_llm_providers")]
7836 providers_disable: PROVIDERS_DISABLE_METHOD_NAME,
7837 session_new: SESSION_NEW_METHOD_NAME,
7838 session_set_config_option: SESSION_SET_CONFIG_OPTION_METHOD_NAME,
7839 session_prompt: SESSION_PROMPT_METHOD_NAME,
7840 session_cancel: SESSION_CANCEL_METHOD_NAME,
7841 #[cfg(feature = "unstable_mcp_over_acp")]
7842 mcp_message: MCP_MESSAGE_METHOD_NAME,
7843 session_list: SESSION_LIST_METHOD_NAME,
7844 session_delete: SESSION_DELETE_METHOD_NAME,
7845 #[cfg(feature = "unstable_session_fork")]
7846 session_fork: SESSION_FORK_METHOD_NAME,
7847 #[cfg(feature = "unstable_session_archive")]
7848 session_archive: SESSION_ARCHIVE_METHOD_NAME,
7849 #[cfg(feature = "unstable_session_archive")]
7850 session_unarchive: SESSION_UNARCHIVE_METHOD_NAME,
7851 #[cfg(feature = "unstable_session_status")]
7852 session_status: SESSION_STATUS_METHOD_NAME,
7853 #[cfg(feature = "unstable_session_options")]
7854 session_options: SESSION_OPTIONS_METHOD_NAME,
7855 #[cfg(feature = "unstable_session_set_title")]
7856 session_set_title: SESSION_SET_TITLE_METHOD_NAME,
7857 session_resume: SESSION_RESUME_METHOD_NAME,
7858 session_close: SESSION_CLOSE_METHOD_NAME,
7859 tool_call_cancel: TOOL_CALL_CANCEL_METHOD_NAME,
7860 terminal_cancel: TERMINAL_CANCEL_METHOD_NAME,
7861 auth_logout: AUTH_LOGOUT_METHOD_NAME,
7862 #[cfg(feature = "unstable_auth_status")]
7863 auth_status: AUTH_STATUS_METHOD_NAME,
7864};
7865
7866pub(crate) const INITIALIZE_METHOD_NAME: &str = "initialize";
7868pub(crate) const AUTH_LOGIN_METHOD_NAME: &str = "auth/login";
7870#[cfg(feature = "unstable_llm_providers")]
7872pub(crate) const PROVIDERS_LIST_METHOD_NAME: &str = "providers/list";
7873#[cfg(feature = "unstable_llm_providers")]
7875pub(crate) const PROVIDERS_SET_METHOD_NAME: &str = "providers/set";
7876#[cfg(feature = "unstable_llm_providers")]
7878pub(crate) const PROVIDERS_DISABLE_METHOD_NAME: &str = "providers/disable";
7879pub(crate) const SESSION_NEW_METHOD_NAME: &str = "session/new";
7881pub(crate) const SESSION_SET_CONFIG_OPTION_METHOD_NAME: &str = "session/set_config_option";
7883pub(crate) const SESSION_PROMPT_METHOD_NAME: &str = "session/prompt";
7885pub(crate) const SESSION_CANCEL_METHOD_NAME: &str = "session/cancel";
7887pub(crate) const SESSION_LIST_METHOD_NAME: &str = "session/list";
7889pub(crate) const SESSION_DELETE_METHOD_NAME: &str = "session/delete";
7891#[cfg(feature = "unstable_session_fork")]
7893pub(crate) const SESSION_FORK_METHOD_NAME: &str = "session/fork";
7894#[cfg(feature = "unstable_session_archive")]
7896pub(crate) const SESSION_ARCHIVE_METHOD_NAME: &str = "session/archive";
7897#[cfg(feature = "unstable_session_archive")]
7899pub(crate) const SESSION_UNARCHIVE_METHOD_NAME: &str = "session/unarchive";
7900#[cfg(feature = "unstable_session_status")]
7902pub(crate) const SESSION_STATUS_METHOD_NAME: &str = "session/status";
7903#[cfg(feature = "unstable_session_options")]
7905pub(crate) const SESSION_OPTIONS_METHOD_NAME: &str = "session/options";
7906#[cfg(feature = "unstable_session_set_title")]
7908pub(crate) const SESSION_SET_TITLE_METHOD_NAME: &str = "session/set_title";
7909pub(crate) const SESSION_RESUME_METHOD_NAME: &str = "session/resume";
7911pub(crate) const SESSION_CLOSE_METHOD_NAME: &str = "session/close";
7913pub(crate) const TOOL_CALL_CANCEL_METHOD_NAME: &str = "tool_call/cancel";
7915pub(crate) const TERMINAL_CANCEL_METHOD_NAME: &str = "terminal/cancel";
7917pub(crate) const AUTH_LOGOUT_METHOD_NAME: &str = "auth/logout";
7919#[cfg(feature = "unstable_auth_status")]
7921pub(crate) const AUTH_STATUS_METHOD_NAME: &str = "auth/status";
7922
7923#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7930#[derive(Clone, Debug, Serialize, Deserialize)]
7931#[serde(untagged)]
7932#[cfg_attr(feature = "schemars", schemars(inline))]
7933#[non_exhaustive]
7934pub enum ClientRequest {
7935 InitializeRequest(Box<InitializeRequest>),
7949 LoginAuthRequest(Box<LoginAuthRequest>),
7964 #[cfg(feature = "unstable_llm_providers")]
7970 ListProvidersRequest(Box<ListProvidersRequest>),
7971 #[cfg(feature = "unstable_llm_providers")]
7977 SetProviderRequest(Box<SetProviderRequest>),
7978 #[cfg(feature = "unstable_llm_providers")]
7984 DisableProviderRequest(Box<DisableProviderRequest>),
7985 LogoutAuthRequest(Box<LogoutAuthRequest>),
7995 #[cfg(feature = "unstable_auth_status")]
8004 AuthStatusRequest(Box<AuthStatusRequest>),
8005 NewSessionRequest(Box<NewSessionRequest>),
8018 ListSessionsRequest(Box<ListSessionsRequest>),
8022 DeleteSessionRequest(Box<DeleteSessionRequest>),
8026 #[cfg(feature = "unstable_session_fork")]
8027 ForkSessionRequest(Box<ForkSessionRequest>),
8043 #[cfg(feature = "unstable_session_archive")]
8044 ArchiveSessionRequest(Box<ArchiveSessionRequest>),
8052 #[cfg(feature = "unstable_session_archive")]
8053 UnarchiveSessionRequest(Box<UnarchiveSessionRequest>),
8061 #[cfg(feature = "unstable_session_status")]
8062 SessionStatusRequest(Box<SessionStatusRequest>),
8070 #[cfg(feature = "unstable_session_options")]
8071 SessionOptionsRequest(Box<SessionOptionsRequest>),
8079 #[cfg(feature = "unstable_session_set_title")]
8080 SetSessionTitleRequest(Box<SetSessionTitleRequest>),
8091 ResumeSessionRequest(Box<ResumeSessionRequest>),
8097 CloseSessionRequest(Box<CloseSessionRequest>),
8102 CancelToolCallRequest(Box<CancelToolCallRequest>),
8108 CancelTerminalRequest(Box<CancelTerminalRequest>),
8114 SetSessionConfigOptionRequest(Box<SetSessionConfigOptionRequest>),
8116 PromptRequest(Box<PromptRequest>),
8138 ExtMethodRequest(Box<ExtRequest>),
8144}
8145
8146impl_request_dispatch! {
8147 ClientRequest => AgentResponse {
8148 InitializeRequest => InitializeResponse: AGENT_METHOD_NAMES.initialize,
8149 LoginAuthRequest => LoginAuthResponse: AGENT_METHOD_NAMES.auth_login,
8150 #[cfg(feature = "unstable_llm_providers")]
8151 ListProvidersRequest => ListProvidersResponse: AGENT_METHOD_NAMES.providers_list,
8152 #[cfg(feature = "unstable_llm_providers")]
8153 SetProviderRequest => SetProviderResponse: AGENT_METHOD_NAMES.providers_set,
8154 #[cfg(feature = "unstable_llm_providers")]
8155 DisableProviderRequest => DisableProviderResponse: AGENT_METHOD_NAMES.providers_disable,
8156 LogoutAuthRequest => LogoutAuthResponse: AGENT_METHOD_NAMES.auth_logout,
8157 #[cfg(feature = "unstable_auth_status")]
8158 AuthStatusRequest => AuthStatusResponse: AGENT_METHOD_NAMES.auth_status,
8159 NewSessionRequest => NewSessionResponse: AGENT_METHOD_NAMES.session_new,
8160 ListSessionsRequest => ListSessionsResponse: AGENT_METHOD_NAMES.session_list,
8161 DeleteSessionRequest => DeleteSessionResponse: AGENT_METHOD_NAMES.session_delete,
8162 #[cfg(feature = "unstable_session_fork")]
8163 ForkSessionRequest => ForkSessionResponse: AGENT_METHOD_NAMES.session_fork,
8164 #[cfg(feature = "unstable_session_archive")]
8165 ArchiveSessionRequest => ArchiveSessionResponse: AGENT_METHOD_NAMES.session_archive,
8166 #[cfg(feature = "unstable_session_archive")]
8167 UnarchiveSessionRequest => UnarchiveSessionResponse: AGENT_METHOD_NAMES.session_unarchive,
8168 #[cfg(feature = "unstable_session_status")]
8169 SessionStatusRequest => SessionStatusResponse: AGENT_METHOD_NAMES.session_status,
8170 #[cfg(feature = "unstable_session_options")]
8171 SessionOptionsRequest => SessionOptionsResponse: AGENT_METHOD_NAMES.session_options,
8172 #[cfg(feature = "unstable_session_set_title")]
8173 SetSessionTitleRequest => SetSessionTitleResponse: AGENT_METHOD_NAMES.session_set_title,
8174 ResumeSessionRequest => ResumeSessionResponse: AGENT_METHOD_NAMES.session_resume,
8175 CloseSessionRequest => CloseSessionResponse: AGENT_METHOD_NAMES.session_close,
8176 CancelToolCallRequest => CancelToolCallResponse: AGENT_METHOD_NAMES.tool_call_cancel,
8177 CancelTerminalRequest => CancelTerminalResponse: AGENT_METHOD_NAMES.terminal_cancel,
8178 SetSessionConfigOptionRequest => SetSessionConfigOptionResponse: AGENT_METHOD_NAMES.session_set_config_option,
8179 PromptRequest => PromptResponse: AGENT_METHOD_NAMES.session_prompt,
8180 }
8181 extension ExtMethodRequest(Box<ExtRequest>) => ExtMethodResponse;
8182}
8183
8184#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
8191#[derive(Clone, Debug, Serialize, Deserialize)]
8192#[serde(untagged)]
8193#[cfg_attr(feature = "schemars", schemars(inline))]
8194#[non_exhaustive]
8195pub enum AgentResponse {
8196 InitializeResponse(Box<InitializeResponse>),
8198 LoginAuthResponse(#[serde(default)] Box<LoginAuthResponse>),
8200 #[cfg(feature = "unstable_llm_providers")]
8202 ListProvidersResponse(Box<ListProvidersResponse>),
8203 #[cfg(feature = "unstable_llm_providers")]
8205 SetProviderResponse(#[serde(default)] Box<SetProviderResponse>),
8206 #[cfg(feature = "unstable_llm_providers")]
8208 DisableProviderResponse(#[serde(default)] Box<DisableProviderResponse>),
8209 LogoutAuthResponse(#[serde(default)] Box<LogoutAuthResponse>),
8211 #[cfg(feature = "unstable_auth_status")]
8213 AuthStatusResponse(Box<AuthStatusResponse>),
8214 NewSessionResponse(Box<NewSessionResponse>),
8216 ListSessionsResponse(Box<ListSessionsResponse>),
8218 DeleteSessionResponse(#[serde(default)] Box<DeleteSessionResponse>),
8220 #[cfg(feature = "unstable_session_fork")]
8222 ForkSessionResponse(Box<ForkSessionResponse>),
8223 #[cfg(feature = "unstable_session_archive")]
8225 ArchiveSessionResponse(#[serde(default)] Box<ArchiveSessionResponse>),
8226 #[cfg(feature = "unstable_session_archive")]
8228 UnarchiveSessionResponse(#[serde(default)] Box<UnarchiveSessionResponse>),
8229 #[cfg(feature = "unstable_session_status")]
8231 SessionStatusResponse(Box<SessionStatusResponse>),
8232 #[cfg(feature = "unstable_session_options")]
8234 SessionOptionsResponse(#[serde(default)] Box<SessionOptionsResponse>),
8235 #[cfg(feature = "unstable_session_set_title")]
8237 SetSessionTitleResponse(Box<SetSessionTitleResponse>),
8238 ResumeSessionResponse(#[serde(default)] Box<ResumeSessionResponse>),
8240 CloseSessionResponse(#[serde(default)] Box<CloseSessionResponse>),
8242 CancelToolCallResponse(#[serde(default)] Box<CancelToolCallResponse>),
8244 CancelTerminalResponse(#[serde(default)] Box<CancelTerminalResponse>),
8246 SetSessionConfigOptionResponse(Box<SetSessionConfigOptionResponse>),
8248 PromptResponse(Box<PromptResponse>),
8250 ExtMethodResponse(Box<ExtResponse>),
8252}
8253
8254#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
8261#[derive(Clone, Debug, Serialize, Deserialize)]
8262#[serde(untagged)]
8263#[cfg_attr(feature = "schemars", schemars(inline))]
8264#[non_exhaustive]
8265pub enum ClientNotification {
8266 CancelSessionNotification(Box<CancelSessionNotification>),
8296 #[cfg(feature = "unstable_mcp_over_acp")]
8302 MessageMcpNotification(Box<MessageMcpNotification>),
8303 ExtNotification(Box<ExtNotification>),
8309}
8310
8311impl_message_dispatch! {
8312 ClientNotification {
8313 CancelSessionNotification => AGENT_METHOD_NAMES.session_cancel,
8314 #[cfg(feature = "unstable_mcp_over_acp")]
8315 MessageMcpNotification => AGENT_METHOD_NAMES.mcp_message,
8316 }
8317 extension ExtNotification(Box<ExtNotification>);
8318}
8319
8320#[cfg(test)]
8321mod test_serialization {
8322 use std::path::PathBuf;
8323
8324 use super::*;
8325 use serde_json::json;
8326
8327 fn test_meta() -> Meta {
8328 json!({ "source": "test" }).as_object().unwrap().clone()
8329 }
8330
8331 #[test]
8332 fn list_sessions_cursor_and_session_directories_are_strict() {
8333 for cursor in [json!(null), json!("next")] {
8334 let response = json!({ "sessions": [], "nextCursor": cursor });
8335 serde_json::from_value::<ListSessionsResponse>(response).unwrap();
8336 }
8337 let malformed = json!({ "sessions": [], "nextCursor": 42 });
8338 assert!(serde_json::from_value::<ListSessionsResponse>(malformed).is_err());
8339
8340 let session = |dirs: serde_json::Value| json!({ "sessionId": "s", "cwd": "/w", "additionalDirectories": dirs });
8341 let info: SessionInfo = serde_json::from_value(session(json!(null))).unwrap();
8342 assert_eq!(info.additional_directories, Vec::<AbsolutePath>::new());
8343 for bad in [json!(["/a", 42]), json!("/a")] {
8344 assert!(serde_json::from_value::<SessionInfo>(session(bad)).is_err());
8345 }
8346 let response = json!({ "sessions": [session(json!(["/a", 42]))] });
8348 let response: ListSessionsResponse = serde_json::from_value(response).unwrap();
8349 assert_eq!(response.sessions, Vec::<SessionInfo>::new());
8350 }
8351
8352 #[test]
8353 fn other_fallbacks_preserve_optional_fields_verbatim() {
8354 let valid = json!({ "type": "_custom", "methodId": "m", "name": "M",
8355 "description": "d", "_meta": { "k": 1 } });
8356 let method: AuthMethod = serde_json::from_value(valid.clone()).unwrap();
8357 assert_eq!(method.description(), Some("d"));
8358 assert_eq!(
8359 method.meta(),
8360 Some(&json!({ "k": 1 }).as_object().unwrap().clone())
8361 );
8362 assert_eq!(serde_json::to_value(&method).unwrap(), valid);
8363
8364 let malformed = json!({ "type": "_custom", "methodId": "m", "name": "M",
8366 "description": 42, "_meta": "bad", "extra": true });
8367 let method: AuthMethod = serde_json::from_value(malformed.clone()).unwrap();
8368 assert_eq!(method.description(), None);
8369 assert_eq!(method.meta(), None);
8370 assert_eq!(serde_json::to_value(&method).unwrap(), malformed);
8371
8372 let replay = json!({ "type": "_custom", "_meta": "bad", "cursor": 3 });
8373 let decoded: ReplayFrom = serde_json::from_value(replay.clone()).unwrap();
8374 assert_eq!(serde_json::to_value(&decoded).unwrap(), replay);
8375 }
8376
8377 fn serialized_meta_key_count(value: &impl serde::Serialize) -> usize {
8378 serde_json::to_string(value)
8379 .unwrap()
8380 .matches("\"_meta\"")
8381 .count()
8382 }
8383
8384 #[test]
8385 fn prompt_response_without_metadata_round_trips() {
8386 let response = PromptResponse::new(MessageId::new("message-1"));
8387 let serialized = serde_json::to_value(&response).unwrap();
8388 assert_eq!(serialized, json!({ "messageId": "message-1" }));
8389 assert_eq!(
8390 serde_json::from_value::<PromptResponse>(serialized).unwrap(),
8391 response
8392 );
8393 assert_eq!(
8394 serde_json::from_value::<PromptResponse>(json!({
8395 "messageId": "message-1",
8396 "_meta": null
8397 }))
8398 .unwrap(),
8399 response
8400 );
8401 }
8402
8403 #[test]
8404 fn prompt_response_requires_message_id_and_preserves_metadata_tolerance() {
8405 let response = PromptResponse::new("message-1").meta(test_meta());
8406 let serialized = serde_json::to_value(&response).unwrap();
8407 assert_eq!(
8408 serialized,
8409 json!({
8410 "messageId": "message-1",
8411 "_meta": { "source": "test" }
8412 })
8413 );
8414
8415 let deserialized: PromptResponse = serde_json::from_value(serialized).unwrap();
8416 assert_eq!(deserialized.message_id, MessageId::new("message-1"));
8417 assert_eq!(deserialized.meta, Some(test_meta()));
8418
8419 let malformed_meta: PromptResponse = serde_json::from_value(json!({
8420 "messageId": "message-2",
8421 "_meta": false
8422 }))
8423 .unwrap();
8424 assert_eq!(malformed_meta.message_id, MessageId::new("message-2"));
8425 assert_eq!(malformed_meta.meta, None);
8426
8427 for invalid in [
8428 json!({}),
8429 json!({ "messageId": null }),
8430 json!({ "messageId": 1 }),
8431 json!({ "messageId": false }),
8432 json!({ "messageId": {} }),
8433 json!({ "messageId": [] }),
8434 ] {
8435 assert!(
8436 serde_json::from_value::<PromptResponse>(invalid).is_err(),
8437 "missing, null, and non-string message IDs must be rejected"
8438 );
8439 }
8440 }
8441
8442 #[cfg(feature = "schemars")]
8443 #[test]
8444 fn prompt_response_schema_requires_non_null_string_message_id_reference() {
8445 let schema = serde_json::to_value(schemars::schema_for!(PromptResponse)).unwrap();
8446
8447 assert_eq!(schema["required"], json!(["messageId"]));
8448 assert_eq!(
8449 schema["properties"]["messageId"]["$ref"],
8450 "#/$defs/MessageId"
8451 );
8452 assert_eq!(schema["$defs"]["MessageId"]["type"], "string");
8453 }
8454
8455 #[test]
8456 fn test_initialize_capabilities_default_on_malformed_values() {
8457 let request: InitializeRequest = serde_json::from_value(json!({
8458 "protocolVersion": 2,
8459 "capabilities": false,
8460 "info": {
8461 "name": "client",
8462 "version": "1.0.0"
8463 }
8464 }))
8465 .unwrap();
8466 assert_eq!(request.capabilities, ClientCapabilities::default());
8467
8468 let response: InitializeResponse = serde_json::from_value(json!({
8469 "protocolVersion": 2,
8470 "capabilities": false,
8471 "info": {
8472 "name": "agent",
8473 "version": "1.0.0"
8474 }
8475 }))
8476 .unwrap();
8477 assert_eq!(response.capabilities, AgentCapabilities::default());
8478 }
8479
8480 #[test]
8481 fn test_agent_capabilities_default_on_malformed_values() {
8482 let capabilities: AgentCapabilities = serde_json::from_value(json!({
8483 "session": false,
8484 "auth": false
8485 }))
8486 .unwrap();
8487
8488 assert!(capabilities.session.is_none());
8489 assert_eq!(capabilities.auth, None);
8490 }
8491
8492 #[test]
8493 fn test_mcp_server_stdio_serialization() {
8494 let server = McpServer::Stdio(
8495 McpServerStdio::new("test-server", "/usr/bin/server")
8496 .args(vec!["--port".to_string(), "3000".to_string()])
8497 .env(vec![EnvVariable::new("API_KEY", "secret123")]),
8498 );
8499
8500 let json = serde_json::to_value(&server).unwrap();
8501 assert_eq!(
8502 json,
8503 json!({
8504 "type": "stdio",
8505 "name": "test-server",
8506 "command": "/usr/bin/server",
8507 "args": ["--port", "3000"],
8508 "env": [
8509 {
8510 "name": "API_KEY",
8511 "value": "secret123"
8512 }
8513 ]
8514 })
8515 );
8516
8517 let deserialized: McpServer = serde_json::from_value(json).unwrap();
8518 match deserialized {
8519 McpServer::Stdio(McpServerStdio {
8520 name,
8521 command,
8522 args,
8523 env,
8524 meta: _,
8525 }) => {
8526 assert_eq!(name, "test-server");
8527 assert_eq!(command, AbsolutePath::new("/usr/bin/server"));
8528 assert_eq!(args, vec!["--port", "3000"]);
8529 assert_eq!(env.len(), 1);
8530 assert_eq!(env[0].name, "API_KEY");
8531 assert_eq!(env[0].value, "secret123");
8532 }
8533 _ => panic!("Expected Stdio variant"),
8534 }
8535 }
8536
8537 #[test]
8538 fn test_mcp_server_empty_arrays_are_optional() {
8539 let stdio = McpServer::Stdio(McpServerStdio::new("test-server", "/usr/bin/server"));
8540 assert_eq!(
8541 serde_json::to_value(&stdio).unwrap(),
8542 json!({
8543 "type": "stdio",
8544 "name": "test-server",
8545 "command": "/usr/bin/server"
8546 })
8547 );
8548
8549 let McpServer::Stdio(McpServerStdio { args, env, .. }) =
8550 serde_json::from_value::<McpServer>(json!({
8551 "type": "stdio",
8552 "name": "test-server",
8553 "command": "/usr/bin/server"
8554 }))
8555 .unwrap()
8556 else {
8557 panic!("Expected Stdio variant");
8558 };
8559 assert_eq!(args, Vec::<String>::new());
8560 assert_eq!(env, []);
8561
8562 let http = McpServer::Http(McpServerHttp::new("http-server", "https://api.example.com"));
8563 assert_eq!(
8564 serde_json::to_value(&http).unwrap(),
8565 json!({
8566 "type": "http",
8567 "name": "http-server",
8568 "url": "https://api.example.com"
8569 })
8570 );
8571
8572 let McpServer::Http(McpServerHttp { headers, .. }) =
8573 serde_json::from_value::<McpServer>(json!({
8574 "type": "http",
8575 "name": "http-server",
8576 "url": "https://api.example.com"
8577 }))
8578 .unwrap()
8579 else {
8580 panic!("Expected Http variant");
8581 };
8582 assert_eq!(headers, []);
8583 }
8584
8585 #[test]
8586 fn test_mcp_server_unknown_transport_serialization() {
8587 let json = json!({
8588 "type": "websocket",
8589 "name": "future-server",
8590 "url": "wss://example.com/mcp",
8591 "protocolVersion": "2026-01-01"
8592 });
8593
8594 let deserialized: McpServer = serde_json::from_value(json.clone()).unwrap();
8595 let McpServer::Other(OtherMcpServer { type_, fields }) = &deserialized else {
8596 panic!("Expected Other variant");
8597 };
8598
8599 assert_eq!(type_, "websocket");
8600 assert_eq!(fields["name"], "future-server");
8601 assert_eq!(fields["url"], "wss://example.com/mcp");
8602 assert_eq!(fields["protocolVersion"], "2026-01-01");
8603 assert_eq!(serde_json::to_value(&deserialized).unwrap(), json);
8604 }
8605
8606 #[test]
8607 fn test_mcp_server_stdio_requires_type() {
8608 let result = serde_json::from_value::<McpServer>(json!({
8609 "name": "test-server",
8610 "command": "/usr/bin/server",
8611 "args": [],
8612 "env": []
8613 }));
8614
8615 assert!(result.is_err());
8616 }
8617
8618 #[test]
8619 fn test_mcp_server_unknown_does_not_hide_malformed_known_transport() {
8620 let result = serde_json::from_value::<McpServer>(json!({
8621 "type": "stdio",
8622 "name": "test-server",
8623 "args": [],
8624 "env": []
8625 }));
8626
8627 assert!(result.is_err());
8628 }
8629
8630 #[test]
8631 fn test_mcp_server_http_serialization() {
8632 let server = McpServer::Http(
8633 McpServerHttp::new("http-server", "https://api.example.com").headers(vec![
8634 HttpHeader::new("Authorization", "Bearer token123"),
8635 HttpHeader::new("Content-Type", "application/json"),
8636 ]),
8637 );
8638
8639 let json = serde_json::to_value(&server).unwrap();
8640 assert_eq!(
8641 json,
8642 json!({
8643 "type": "http",
8644 "name": "http-server",
8645 "url": "https://api.example.com",
8646 "headers": [
8647 {
8648 "name": "Authorization",
8649 "value": "Bearer token123"
8650 },
8651 {
8652 "name": "Content-Type",
8653 "value": "application/json"
8654 }
8655 ]
8656 })
8657 );
8658
8659 let deserialized: McpServer = serde_json::from_value(json).unwrap();
8660 match deserialized {
8661 McpServer::Http(McpServerHttp {
8662 name,
8663 url,
8664 headers,
8665 meta: _,
8666 }) => {
8667 assert_eq!(name, "http-server");
8668 assert_eq!(url, "https://api.example.com");
8669 assert_eq!(headers.len(), 2);
8670 assert_eq!(headers[0].name, "Authorization");
8671 assert_eq!(headers[0].value, "Bearer token123");
8672 assert_eq!(headers[1].name, "Content-Type");
8673 assert_eq!(headers[1].value, "application/json");
8674 }
8675 _ => panic!("Expected Http variant"),
8676 }
8677 }
8678
8679 #[cfg(feature = "schemars")]
8680 #[test]
8681 fn mcp_server_http_schema_marks_url_as_uri() {
8682 let schema = serde_json::to_value(schemars::schema_for!(McpServerHttp)).unwrap();
8683
8684 assert_eq!(schema["properties"]["url"]["format"], "uri");
8685 }
8686
8687 #[cfg(feature = "unstable_mcp_over_acp")]
8688 #[test]
8689 fn test_client_mcp_message_method_names() {
8690 use serde_json::json;
8691
8692 assert_eq!(AGENT_METHOD_NAMES.mcp_message, "mcp/message");
8693
8694 let notification =
8695 MessageMcpNotification::new("server-1", "req-1", "notifications/progress");
8696 assert_eq!(
8697 ClientNotification::MessageMcpNotification(Box::new(notification.clone())).method(),
8698 "mcp/message"
8699 );
8700 assert_eq!(
8701 serde_json::to_value(notification).unwrap(),
8702 json!({
8703 "serverId": "server-1",
8704 "requestId": "req-1",
8705 "method": "notifications/progress"
8706 })
8707 );
8708 let notification: MessageMcpNotification = serde_json::from_value(json!({
8709 "serverId": "server-1", "requestId": "req-1", "method": "notifications/progress",
8710 "params": null, "_meta": null
8711 }))
8712 .unwrap();
8713 assert_eq!(notification.params, None);
8714 assert_eq!(notification.meta, None);
8715 for key in ["serverId", "requestId", "method"] {
8716 let mut value = json!({"serverId":"server-1", "requestId":"req-1", "method":"notifications/progress"});
8717 value.as_object_mut().unwrap().remove(key);
8718 assert!(serde_json::from_value::<MessageMcpNotification>(value).is_err());
8719 }
8720 }
8721
8722 #[test]
8723 fn test_auth_method_names() {
8724 assert_eq!(AGENT_METHOD_NAMES.auth_login, "auth/login");
8725 assert_eq!(AGENT_METHOD_NAMES.auth_logout, "auth/logout");
8726
8727 assert_eq!(
8728 ClientRequest::LoginAuthRequest(Box::new(LoginAuthRequest::new("agent-login")))
8729 .method(),
8730 "auth/login"
8731 );
8732 assert_eq!(
8733 ClientRequest::LogoutAuthRequest(Box::new(LogoutAuthRequest::new())).method(),
8734 "auth/logout"
8735 );
8736 }
8737
8738 #[test]
8739 fn test_session_config_option_category_known_variants() {
8740 assert_eq!(
8742 serde_json::to_value(&SessionConfigOptionCategory::Mode).unwrap(),
8743 json!("mode")
8744 );
8745 assert_eq!(
8746 serde_json::to_value(&SessionConfigOptionCategory::Model).unwrap(),
8747 json!("model")
8748 );
8749 assert_eq!(
8750 serde_json::to_value(&SessionConfigOptionCategory::ModelConfig).unwrap(),
8751 json!("model_config")
8752 );
8753 #[cfg(feature = "unstable_speed_config_category")]
8754 assert_eq!(
8755 serde_json::to_value(&SessionConfigOptionCategory::Speed).unwrap(),
8756 json!("speed")
8757 );
8758 assert_eq!(
8759 serde_json::to_value(&SessionConfigOptionCategory::ThoughtLevel).unwrap(),
8760 json!("thought_level")
8761 );
8762
8763 assert_eq!(
8765 serde_json::from_str::<SessionConfigOptionCategory>("\"mode\"").unwrap(),
8766 SessionConfigOptionCategory::Mode
8767 );
8768 assert_eq!(
8769 serde_json::from_str::<SessionConfigOptionCategory>("\"model\"").unwrap(),
8770 SessionConfigOptionCategory::Model
8771 );
8772 assert_eq!(
8773 serde_json::from_str::<SessionConfigOptionCategory>("\"model_config\"").unwrap(),
8774 SessionConfigOptionCategory::ModelConfig
8775 );
8776 #[cfg(feature = "unstable_speed_config_category")]
8777 assert_eq!(
8778 serde_json::from_str::<SessionConfigOptionCategory>("\"speed\"").unwrap(),
8779 SessionConfigOptionCategory::Speed
8780 );
8781 assert_eq!(
8782 serde_json::from_str::<SessionConfigOptionCategory>("\"thought_level\"").unwrap(),
8783 SessionConfigOptionCategory::ThoughtLevel
8784 );
8785 }
8786
8787 #[test]
8788 fn test_session_config_option_category_unknown_variants() {
8789 let unknown: SessionConfigOptionCategory =
8791 serde_json::from_str("\"some_future_category\"").unwrap();
8792 assert_eq!(
8793 unknown,
8794 SessionConfigOptionCategory::Other("some_future_category".to_string())
8795 );
8796
8797 let json = serde_json::to_value(&unknown).unwrap();
8799 assert_eq!(json, json!("some_future_category"));
8800 }
8801
8802 #[cfg(not(feature = "unstable_speed_config_category"))]
8803 #[test]
8804 fn test_session_config_option_speed_is_unknown_without_feature() {
8805 let unknown: SessionConfigOptionCategory = serde_json::from_str("\"speed\"").unwrap();
8806 assert_eq!(
8807 unknown,
8808 SessionConfigOptionCategory::Other("speed".to_string())
8809 );
8810 }
8811
8812 #[test]
8813 fn test_session_config_option_category_custom_categories() {
8814 let custom: SessionConfigOptionCategory =
8816 serde_json::from_str("\"_my_custom_category\"").unwrap();
8817 assert_eq!(
8818 custom,
8819 SessionConfigOptionCategory::Other("_my_custom_category".to_string())
8820 );
8821
8822 let json = serde_json::to_value(&custom).unwrap();
8824 assert_eq!(json, json!("_my_custom_category"));
8825
8826 let deserialized: SessionConfigOptionCategory = serde_json::from_value(json).unwrap();
8828 assert_eq!(
8829 deserialized,
8830 SessionConfigOptionCategory::Other("_my_custom_category".to_string()),
8831 );
8832 }
8833
8834 fn test_config_option() -> SessionConfigOption {
8835 SessionConfigOption::select(
8836 "mode",
8837 "Mode",
8838 "ask",
8839 vec![SessionConfigSelectOption::new("ask", "Ask")],
8840 )
8841 }
8842
8843 #[test]
8844 fn test_session_response_initial_state_default_empty_and_skip_serializing() {
8845 assert_eq!(
8846 serde_json::to_value(NewSessionResponse::new("sess")).unwrap(),
8847 json!({ "sessionId": "sess" })
8848 );
8849 assert_eq!(
8850 serde_json::to_value(ResumeSessionResponse::new()).unwrap(),
8851 json!({})
8852 );
8853 #[cfg(feature = "unstable_session_fork")]
8854 assert_eq!(
8855 serde_json::to_value(ForkSessionResponse::new("fork")).unwrap(),
8856 json!({ "sessionId": "fork" })
8857 );
8858
8859 let json = serde_json::to_value(
8860 NewSessionResponse::new("sess").config_options(vec![test_config_option()]),
8861 )
8862 .unwrap();
8863 assert_eq!(json["configOptions"].as_array().unwrap().len(), 1);
8864 }
8865
8866 #[test]
8867 fn test_session_response_config_options_deserialize_missing_null_and_invalid() {
8868 let missing: NewSessionResponse =
8869 serde_json::from_value(json!({ "sessionId": "sess" })).unwrap();
8870 assert_eq!(missing.config_options, []);
8871
8872 let null: NewSessionResponse = serde_json::from_value(json!({
8873 "sessionId": "sess",
8874 "configOptions": null
8875 }))
8876 .unwrap();
8877 assert_eq!(null.config_options, []);
8878
8879 let wrong_shape: NewSessionResponse = serde_json::from_value(json!({
8880 "sessionId": "sess",
8881 "configOptions": "oops"
8882 }))
8883 .unwrap();
8884 assert_eq!(wrong_shape.config_options, []);
8885
8886 let valid_option = serde_json::to_value(test_config_option()).unwrap();
8887 let mixed: NewSessionResponse = serde_json::from_value(json!({
8888 "sessionId": "sess",
8889 "configOptions": ["oops", valid_option]
8890 }))
8891 .unwrap();
8892 assert_eq!(mixed.config_options.len(), 1);
8893
8894 let resume: ResumeSessionResponse = serde_json::from_value(json!({})).unwrap();
8895 assert_eq!(resume.config_options, []);
8896 #[cfg(feature = "unstable_session_fork")]
8897 {
8898 let fork: ForkSessionResponse =
8899 serde_json::from_value(json!({ "sessionId": "fork" })).unwrap();
8900 assert_eq!(fork.config_options, []);
8901 }
8902 }
8903
8904 #[test]
8905 fn test_session_response_available_commands_roundtrip_with_config_options() {
8906 use super::super::{AvailableCommandInput, Command, TextCommandInput};
8907
8908 let commands = vec![
8909 AvailableCommand::Command(
8910 Command::new("web", "Search the web")
8911 .input(AvailableCommandInput::Text(TextCommandInput::new("Query"))),
8912 ),
8913 AvailableCommand::Command(Command::new("test", "Run project tests")),
8914 ];
8915 let mut expected = json!({
8916 "sessionId": "sess",
8917 "configOptions": [test_config_option()],
8918 "availableCommands": [
8919 {
8920 "type": "command",
8921 "name": "web",
8922 "description": "Search the web",
8923 "input": { "type": "text", "hint": "Query" }
8924 },
8925 { "type": "command", "name": "test", "description": "Run project tests" }
8926 ]
8927 });
8928
8929 let new = NewSessionResponse::new("sess")
8930 .config_options(vec![test_config_option()])
8931 .available_commands(commands.clone());
8932 assert_eq!(serde_json::to_value(&new).unwrap(), expected);
8933 assert_eq!(
8934 serde_json::from_value::<NewSessionResponse>(expected.clone()).unwrap(),
8935 new
8936 );
8937
8938 expected.as_object_mut().unwrap().remove("sessionId");
8939 let resume = ResumeSessionResponse::new()
8940 .config_options(vec![test_config_option()])
8941 .available_commands(commands.clone());
8942 assert_eq!(serde_json::to_value(&resume).unwrap(), expected);
8943 assert_eq!(
8944 serde_json::from_value::<ResumeSessionResponse>(expected.clone()).unwrap(),
8945 resume
8946 );
8947
8948 #[cfg(feature = "unstable_session_fork")]
8949 {
8950 expected["sessionId"] = json!("fork");
8951 let fork = ForkSessionResponse::new("fork")
8952 .config_options(vec![test_config_option()])
8953 .available_commands(commands);
8954 assert_eq!(serde_json::to_value(&fork).unwrap(), expected);
8955 assert_eq!(
8956 serde_json::from_value::<ForkSessionResponse>(expected).unwrap(),
8957 fork
8958 );
8959 }
8960 }
8961
8962 #[test]
8963 fn test_session_response_available_commands_deserialize_missing_null_and_invalid() {
8964 let command =
8965 AvailableCommand::Command(super::super::Command::new("test", "Run project tests"));
8966 let config_options = vec![test_config_option()];
8967
8968 for (commands, expected) in [
8969 (None, vec![]),
8970 (Some(json!(null)), vec![]),
8971 (Some(json!([])), vec![]),
8972 (Some(json!("oops")), vec![]),
8973 (Some(json!({})), vec![]),
8974 (Some(json!([null, {}, { "name": "invalid" }])), vec![]),
8975 (
8976 Some(json!([{ "name": "test", "description": "Run project tests" }])),
8977 vec![],
8978 ),
8979 (
8980 Some(json!([null, command, { "name": "invalid" }])),
8981 vec![command.clone()],
8982 ),
8983 ] {
8984 let mut value = json!({
8985 "sessionId": "sess",
8986 "configOptions": config_options
8987 });
8988 if let Some(commands) = commands {
8989 value["availableCommands"] = commands;
8990 }
8991
8992 let new: NewSessionResponse = serde_json::from_value(value.clone()).unwrap();
8993 assert_eq!(new.available_commands, expected);
8994 assert_eq!(new.config_options, config_options);
8995
8996 #[cfg(feature = "unstable_session_fork")]
8997 {
8998 let fork: ForkSessionResponse = serde_json::from_value(value.clone()).unwrap();
8999 assert_eq!(fork.available_commands, expected);
9000 assert_eq!(fork.config_options, config_options);
9001 }
9002
9003 value.as_object_mut().unwrap().remove("sessionId");
9004 let resume: ResumeSessionResponse = serde_json::from_value(value).unwrap();
9005 assert_eq!(resume.available_commands, expected);
9006 assert_eq!(resume.config_options, config_options);
9007 }
9008
9009 let resume: ResumeSessionResponse = serde_json::from_value(json!(null)).unwrap();
9010 assert_eq!(resume.available_commands, []);
9011 }
9012
9013 #[test]
9014 fn test_resume_session_replay_from_serialization() {
9015 assert_eq!(
9016 serde_json::to_value(ResumeSessionRequest::new(
9017 "sess_abc123",
9018 "/home/user/project"
9019 ))
9020 .unwrap(),
9021 json!({
9022 "sessionId": "sess_abc123",
9023 "cwd": "/home/user/project"
9024 })
9025 );
9026 assert_eq!(
9027 serde_json::to_value(
9028 ResumeSessionRequest::new("sess_abc123", "/home/user/project")
9029 .replay_from(ReplayFrom::from(ReplayFromStart::new()))
9030 )
9031 .unwrap(),
9032 json!({
9033 "sessionId": "sess_abc123",
9034 "cwd": "/home/user/project",
9035 "replayFrom": {
9036 "type": "start"
9037 }
9038 })
9039 );
9040
9041 let replay: ResumeSessionRequest = serde_json::from_value(json!({
9042 "sessionId": "sess_abc123",
9043 "cwd": "/home/user/project",
9044 "replayFrom": {
9045 "type": "start"
9046 }
9047 }))
9048 .unwrap();
9049 assert!(matches!(replay.replay_from, Some(ReplayFrom::Start(_))));
9050
9051 let none: ResumeSessionRequest = serde_json::from_value(json!({
9052 "sessionId": "sess_abc123",
9053 "cwd": "/home/user/project",
9054 "replayFrom": null
9055 }))
9056 .unwrap();
9057 assert!(none.replay_from.is_none());
9058 }
9059
9060 #[test]
9061 fn test_auth_method_agent_serialization() {
9062 let method = AuthMethod::Agent(AuthMethodAgent::new("default-auth", "Default Auth"));
9063
9064 let json = serde_json::to_value(&method).unwrap();
9065 assert_eq!(
9066 json,
9067 json!({
9068 "methodId": "default-auth",
9069 "name": "Default Auth",
9070 "type": "agent"
9071 })
9072 );
9073 assert!(!json.as_object().unwrap().contains_key("description"));
9075
9076 let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9077 match deserialized {
9078 AuthMethod::Agent(AuthMethodAgent {
9079 method_id, name, ..
9080 }) => {
9081 assert_eq!(method_id.0.as_ref(), "default-auth");
9082 assert_eq!(name, "Default Auth");
9083 }
9084 _ => panic!("Expected Agent variant"),
9085 }
9086 }
9087
9088 #[test]
9089 fn test_auth_method_agent_deserialization() {
9090 let json = json!({
9091 "methodId": "agent-auth",
9092 "name": "Agent Auth",
9093 "type": "agent"
9094 });
9095
9096 let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9097 assert!(matches!(deserialized, AuthMethod::Agent(_)));
9098 }
9099
9100 #[test]
9101 fn test_auth_method_agent_requires_type() {
9102 assert!(
9103 serde_json::from_value::<AuthMethod>(json!({
9104 "methodId": "agent-auth",
9105 "name": "Agent Auth"
9106 }))
9107 .is_err()
9108 );
9109 }
9110
9111 #[test]
9112 fn test_auth_method_agent_rejects_null_type() {
9113 assert!(
9114 serde_json::from_value::<AuthMethod>(json!({
9115 "methodId": "agent-auth",
9116 "name": "Agent Auth",
9117 "type": null
9118 }))
9119 .is_err()
9120 );
9121 }
9122
9123 #[test]
9124 fn test_auth_method_unknown_does_not_hide_malformed_agent() {
9125 assert!(
9126 serde_json::from_value::<AuthMethod>(json!({
9127 "methodId": "agent-auth",
9128 "type": "agent"
9129 }))
9130 .is_err()
9131 );
9132 assert!(
9133 serde_json::from_value::<AuthMethod>(json!({
9134 "methodId": "api-key",
9135 "type": "env_var",
9136 "vars": [{"name": "API_KEY"}]
9137 }))
9138 .is_err()
9139 );
9140 }
9141
9142 #[test]
9143 fn test_auth_method_unknown_variant_roundtrip() {
9144 let method: AuthMethod = serde_json::from_value(json!({
9145 "methodId": "oauth",
9146 "name": "OAuth",
9147 "type": "_oauth",
9148 "authorizationUrl": "https://example.com/auth"
9149 }))
9150 .unwrap();
9151
9152 assert_eq!(method.method_id().0.as_ref(), "oauth");
9153 assert_eq!(method.name(), "OAuth");
9154 let AuthMethod::Other(unknown) = method else {
9155 panic!("expected unknown auth method");
9156 };
9157 assert_eq!(unknown.type_, "_oauth");
9158 assert_eq!(
9159 unknown.fields.get("authorizationUrl"),
9160 Some(&json!("https://example.com/auth"))
9161 );
9162
9163 assert_eq!(
9164 serde_json::to_value(AuthMethod::Other(unknown)).unwrap(),
9165 json!({
9166 "methodId": "oauth",
9167 "name": "OAuth",
9168 "type": "_oauth",
9169 "authorizationUrl": "https://example.com/auth"
9170 })
9171 );
9172 }
9173
9174 #[test]
9175 fn test_auth_method_unknown_does_not_hide_malformed_known_variant() {
9176 assert!(
9177 serde_json::from_value::<AuthMethod>(json!({
9178 "methodId": "terminal-auth",
9179 "type": "terminal"
9180 }))
9181 .is_err()
9182 );
9183 }
9184
9185 #[test]
9186 fn test_tool_call_and_terminal_cancel_serialization() {
9187 assert_eq!(AGENT_METHOD_NAMES.tool_call_cancel, "tool_call/cancel");
9188 assert_eq!(AGENT_METHOD_NAMES.terminal_cancel, "terminal/cancel");
9189 assert_eq!(
9190 ClientRequest::CancelToolCallRequest(Box::new(CancelToolCallRequest::new(
9191 "sess_abc123",
9192 "call_012"
9193 )))
9194 .method(),
9195 "tool_call/cancel"
9196 );
9197 assert_eq!(
9198 ClientRequest::CancelTerminalRequest(Box::new(CancelTerminalRequest::new(
9199 "sess_abc123",
9200 "term_003"
9201 )))
9202 .method(),
9203 "terminal/cancel"
9204 );
9205 assert_eq!(
9206 serde_json::to_value(CancelToolCallRequest::new("sess_abc123", "call_012")).unwrap(),
9207 json!({"sessionId": "sess_abc123", "toolCallId": "call_012"})
9208 );
9209 assert_eq!(
9210 serde_json::to_value(CancelTerminalRequest::new("sess_abc123", "term_003")).unwrap(),
9211 json!({"sessionId": "sess_abc123", "terminalId": "term_003"})
9212 );
9213 assert!(
9214 serde_json::from_value::<CancelToolCallRequest>(json!({"sessionId": "sess_abc123"}))
9215 .is_err()
9216 );
9217 assert_eq!(
9218 serde_json::to_value(CancelTerminalResponse::new()).unwrap(),
9219 json!({})
9220 );
9221 }
9222
9223 #[test]
9224 fn test_session_delete_serialization() {
9225 assert_eq!(AGENT_METHOD_NAMES.session_delete, "session/delete");
9226 assert_eq!(
9227 ClientRequest::DeleteSessionRequest(Box::new(DeleteSessionRequest::new("sess_abc123")))
9228 .method(),
9229 "session/delete"
9230 );
9231 assert_eq!(
9232 serde_json::to_value(DeleteSessionRequest::new("sess_abc123")).unwrap(),
9233 json!({
9234 "sessionId": "sess_abc123"
9235 })
9236 );
9237 assert_eq!(
9238 serde_json::to_value(DeleteSessionResponse::new()).unwrap(),
9239 json!({})
9240 );
9241 assert_eq!(
9242 serde_json::to_value(
9243 SessionCapabilities::new().delete(SessionDeleteCapabilities::new())
9244 )
9245 .unwrap(),
9246 json!({
9247 "delete": {}
9248 })
9249 );
9250 }
9251 #[cfg(feature = "unstable_session_set_title")]
9252 #[test]
9253 fn test_session_set_title_serialization() {
9254 assert_eq!(AGENT_METHOD_NAMES.session_set_title, "session/set_title");
9255 assert_eq!(
9256 ClientRequest::SetSessionTitleRequest(Box::new(SetSessionTitleRequest::new(
9257 "sess_abc123",
9258 "Investigate OAuth timeout"
9259 )))
9260 .method(),
9261 "session/set_title"
9262 );
9263 assert_eq!(
9264 serde_json::to_value(SetSessionTitleRequest::new(
9265 "sess_abc123",
9266 "Investigate OAuth timeout"
9267 ))
9268 .unwrap(),
9269 json!({
9270 "sessionId": "sess_abc123",
9271 "title": "Investigate OAuth timeout"
9272 })
9273 );
9274 assert_eq!(
9275 serde_json::to_value(SetSessionTitleResponse::new("Investigate OAuth timeout"))
9276 .unwrap(),
9277 json!({
9278 "title": "Investigate OAuth timeout"
9279 })
9280 );
9281 assert_eq!(
9282 serde_json::to_value(SessionCapabilities::new().title(SessionTitleCapabilities::new()))
9283 .unwrap(),
9284 json!({
9285 "title": {}
9286 })
9287 );
9288 }
9289
9290 #[cfg(feature = "unstable_session_set_title")]
9291 #[test]
9292 fn test_session_set_title_requires_title() {
9293 for params in [
9294 json!({"sessionId": "sess_abc123"}),
9295 json!({"sessionId": "sess_abc123", "title": null}),
9296 json!({"sessionId": "sess_abc123", "title": 42}),
9297 ] {
9298 assert!(serde_json::from_value::<SetSessionTitleRequest>(params).is_err());
9299 }
9300 for result in [json!({}), json!({"title": null})] {
9301 assert!(serde_json::from_value::<SetSessionTitleResponse>(result).is_err());
9302 }
9303 }
9304
9305 #[cfg(feature = "unstable_session_options")]
9306 #[test]
9307 fn test_session_options_serialization() {
9308 assert_eq!(AGENT_METHOD_NAMES.session_options, "session/options");
9309 assert_eq!(
9310 ClientRequest::SessionOptionsRequest(Box::new(SessionOptionsRequest::new(
9311 "/home/user/project"
9312 )))
9313 .method(),
9314 "session/options"
9315 );
9316 assert_eq!(
9317 serde_json::to_value(
9318 SessionOptionsRequest::new("/home/user/project")
9319 .session_id(SessionId::new("sess_abc123"))
9320 )
9321 .unwrap(),
9322 json!({"cwd": "/home/user/project", "sessionId": "sess_abc123"})
9323 );
9324 assert_eq!(
9325 serde_json::from_value::<SessionOptionsRequest>(
9326 json!({"cwd": "/home/user/project", "additionalDirectories": null, "sessionId": null})
9327 )
9328 .unwrap(),
9329 SessionOptionsRequest::new("/home/user/project")
9330 );
9331 let request = NewSessionRequest::new("/home/user/project").config_options(vec![
9332 InitialSessionConfigOption::new("model", SessionConfigOptionValue::id("model-2")),
9333 InitialSessionConfigOption::new("fast", SessionConfigOptionValue::boolean(true)),
9334 ]);
9335 let value = serde_json::to_value(&request).unwrap();
9336 assert_eq!(
9337 value["configOptions"],
9338 json!([
9339 {"configId": "model", "type": "id", "value": "model-2"},
9340 {"configId": "fast", "type": "boolean", "value": true}
9341 ])
9342 );
9343 assert_eq!(
9344 serde_json::from_value::<NewSessionRequest>(value).unwrap(),
9345 request
9346 );
9347 assert!(
9348 serde_json::from_value::<NewSessionRequest>(json!({
9349 "cwd": "/home/user/project",
9350 "mcpServers": [],
9351 "configOptions": [{"type": "boolean", "value": true}]
9352 }))
9353 .is_err()
9354 );
9355 assert_eq!(
9356 serde_json::to_value(SessionOptionsResponse::new()).unwrap(),
9357 json!({})
9358 );
9359 #[cfg(feature = "unstable_session_fork")]
9360 {
9361 let fork =
9362 ForkSessionRequest::new("sess_abc123", "/home/user/project").config_options(vec![
9363 InitialSessionConfigOption::new(
9364 "model",
9365 SessionConfigOptionValue::id("model-2"),
9366 ),
9367 ]);
9368 let value = serde_json::to_value(&fork).unwrap();
9369 assert_eq!(
9370 value["configOptions"],
9371 json!([{"configId": "model", "type": "id", "value": "model-2"}])
9372 );
9373 assert_eq!(
9374 serde_json::from_value::<ForkSessionRequest>(value).unwrap(),
9375 fork
9376 );
9377 assert_eq!(
9379 serde_json::from_value::<ForkSessionRequest>(json!({
9380 "sessionId": "sess_abc123",
9381 "cwd": "/home/user/project",
9382 "configOptions": null
9383 }))
9384 .unwrap(),
9385 ForkSessionRequest::new("sess_abc123", "/home/user/project")
9386 );
9387 assert!(
9388 serde_json::from_value::<ForkSessionRequest>(json!({
9389 "sessionId": "sess_abc123",
9390 "cwd": "/home/user/project",
9391 "configOptions": [{"type": "boolean", "value": true}]
9392 }))
9393 .is_err()
9394 );
9395 }
9396 assert_eq!(
9397 serde_json::to_value(
9398 SessionCapabilities::new().options(SessionOptionsCapabilities::new())
9399 )
9400 .unwrap(),
9401 json!({"options": {}})
9402 );
9403 }
9404
9405 #[cfg(feature = "unstable_session_status")]
9406 #[test]
9407 fn test_session_status_serialization() {
9408 assert_eq!(AGENT_METHOD_NAMES.session_status, "session/status");
9409 assert_eq!(
9410 ClientRequest::SessionStatusRequest(Box::new(SessionStatusRequest::new("sess_abc123")))
9411 .method(),
9412 "session/status"
9413 );
9414 assert_eq!(
9415 serde_json::to_value(SessionStatusRequest::new("sess_abc123")).unwrap(),
9416 json!({"sessionId": "sess_abc123"})
9417 );
9418 assert_eq!(
9419 serde_json::to_value(SessionStatusResponse::new(SessionStatus::Saved)).unwrap(),
9420 json!({"status": "saved"})
9421 );
9422 assert_eq!(
9423 serde_json::to_value(
9424 SessionCapabilities::new().status(SessionStatusCapabilities::new())
9425 )
9426 .unwrap(),
9427 json!({"status": {}})
9428 );
9429 assert_eq!(
9430 serde_json::to_value(SessionStatusResponse::new(SessionStatus::Open).state(
9431 StateUpdate::RequiresAction(crate::v2::RequiresActionStateUpdate::new())
9432 ))
9433 .unwrap(),
9434 json!({
9435 "status": "open",
9436 "state": {"state": "requires_action"}
9437 })
9438 );
9439 for state in [json!(null), json!("running"), json!({"state": 7})] {
9440 let response = serde_json::from_value::<SessionStatusResponse>(
9441 json!({"status": "open", "state": state}),
9442 )
9443 .unwrap();
9444 assert_eq!(response.state, None);
9445 }
9446 }
9447
9448 #[cfg(feature = "unstable_session_status")]
9449 #[test]
9450 fn test_session_status_is_strict_and_open() {
9451 let custom =
9452 serde_json::from_value::<SessionStatusResponse>(json!({"status": "_suspended"}))
9453 .unwrap();
9454 assert_eq!(
9455 custom.status,
9456 SessionStatus::Other("_suspended".to_string())
9457 );
9458 assert_eq!(
9459 serde_json::to_value(&custom).unwrap(),
9460 json!({"status": "_suspended"})
9461 );
9462 for result in [json!({}), json!({"status": null}), json!({"status": 1})] {
9463 assert!(serde_json::from_value::<SessionStatusResponse>(result).is_err());
9464 }
9465 for params in [json!({}), json!({"sessionId": null})] {
9466 assert!(serde_json::from_value::<SessionStatusRequest>(params).is_err());
9467 }
9468 }
9469
9470 #[cfg(feature = "unstable_session_archive")]
9471 #[test]
9472 fn test_session_archive_serialization() {
9473 assert_eq!(AGENT_METHOD_NAMES.session_archive, "session/archive");
9474 assert_eq!(AGENT_METHOD_NAMES.session_unarchive, "session/unarchive");
9475 assert_eq!(
9476 ClientRequest::ArchiveSessionRequest(Box::new(ArchiveSessionRequest::new(
9477 "sess_abc123"
9478 )))
9479 .method(),
9480 "session/archive"
9481 );
9482 assert_eq!(
9483 ClientRequest::UnarchiveSessionRequest(Box::new(UnarchiveSessionRequest::new(
9484 "sess_abc123"
9485 )))
9486 .method(),
9487 "session/unarchive"
9488 );
9489 assert_eq!(
9490 serde_json::to_value(ArchiveSessionRequest::new("sess_abc123")).unwrap(),
9491 json!({"sessionId": "sess_abc123"})
9492 );
9493 assert_eq!(
9494 serde_json::to_value(UnarchiveSessionResponse::new()).unwrap(),
9495 json!({})
9496 );
9497 assert_eq!(
9498 serde_json::to_value(
9499 SessionCapabilities::new().archive(SessionArchiveCapabilities::new())
9500 )
9501 .unwrap(),
9502 json!({"archive": {}})
9503 );
9504 assert_eq!(
9505 serde_json::to_value(
9506 ListSessionsRequest::new()
9507 .cwd("/home/user/project")
9508 .archived(SessionArchiveFilter::Only)
9509 )
9510 .unwrap(),
9511 json!({"cwd": "/home/user/project", "archived": "only"})
9512 );
9513 assert_eq!(
9514 serde_json::to_value(
9515 SessionInfo::new("sess_abc123", "/home/user/project").archived(true)
9516 )
9517 .unwrap(),
9518 json!({"sessionId": "sess_abc123", "cwd": "/home/user/project", "archived": true})
9519 );
9520 }
9521
9522 #[cfg(feature = "unstable_session_archive")]
9523 #[test]
9524 fn test_session_archive_filter_is_strict_and_open() {
9525 for (value, expected) in [
9526 (json!(null), None),
9527 (json!("include"), Some(SessionArchiveFilter::Include)),
9528 (
9529 json!("_recent"),
9530 Some(SessionArchiveFilter::Other("_recent".to_string())),
9531 ),
9532 ] {
9533 let request =
9534 serde_json::from_value::<ListSessionsRequest>(json!({"archived": value})).unwrap();
9535 assert_eq!(request.archived, expected);
9536 }
9537 for value in [json!(true), json!(1), json!({})] {
9538 assert!(
9539 serde_json::from_value::<ListSessionsRequest>(json!({"archived": value})).is_err()
9540 );
9541 }
9542 let info = serde_json::from_value::<SessionInfo>(
9543 json!({"sessionId": "sess_abc123", "cwd": "/home/user/project", "archived": "yes"}),
9544 )
9545 .unwrap();
9546 assert_eq!(info.archived, None);
9547 }
9548
9549 #[test]
9550 fn test_session_additional_directories_serialization() {
9551 assert_eq!(
9552 serde_json::to_value(NewSessionRequest::new("/home/user/project")).unwrap(),
9553 json!({
9554 "cwd": "/home/user/project",
9555 })
9556 );
9557 assert_eq!(
9558 serde_json::to_value(
9559 NewSessionRequest::new("/home/user/project").additional_directories(vec![
9560 PathBuf::from("/home/user/shared-lib"),
9561 PathBuf::from("/home/user/product-docs"),
9562 ])
9563 )
9564 .unwrap(),
9565 json!({
9566 "cwd": "/home/user/project",
9567 "additionalDirectories": [
9568 "/home/user/shared-lib",
9569 "/home/user/product-docs"
9570 ],
9571 })
9572 );
9573 assert_eq!(
9574 serde_json::to_value(ResumeSessionRequest::new(
9575 "sess_abc123",
9576 "/home/user/project"
9577 ))
9578 .unwrap(),
9579 json!({
9580 "sessionId": "sess_abc123",
9581 "cwd": "/home/user/project",
9582 })
9583 );
9584 assert_eq!(
9585 serde_json::from_value::<ResumeSessionRequest>(json!({
9586 "sessionId": "sess_abc123",
9587 "cwd": "/home/user/project"
9588 }))
9589 .unwrap()
9590 .mcp_servers,
9591 Vec::<McpServer>::new()
9592 );
9593 assert_eq!(
9594 serde_json::from_value::<ResumeSessionRequest>(json!({
9595 "sessionId": "sess_abc123",
9596 "cwd": "/home/user/project",
9597 "mcpServers": null
9598 }))
9599 .unwrap()
9600 .mcp_servers,
9601 Vec::<McpServer>::new()
9602 );
9603 assert_eq!(
9604 serde_json::to_value(SessionInfo::new("sess_abc123", "/home/user/project")).unwrap(),
9605 json!({
9606 "sessionId": "sess_abc123",
9607 "cwd": "/home/user/project"
9608 })
9609 );
9610 assert_eq!(
9611 serde_json::to_value(
9612 SessionInfo::new("sess_abc123", "/home/user/project").additional_directories(vec![
9613 PathBuf::from("/home/user/shared-lib"),
9614 PathBuf::from("/home/user/product-docs"),
9615 ])
9616 )
9617 .unwrap(),
9618 json!({
9619 "sessionId": "sess_abc123",
9620 "cwd": "/home/user/project",
9621 "additionalDirectories": [
9622 "/home/user/shared-lib",
9623 "/home/user/product-docs"
9624 ]
9625 })
9626 );
9627 assert_eq!(
9628 serde_json::from_value::<SessionInfo>(json!({
9629 "sessionId": "sess_abc123",
9630 "cwd": "/home/user/project"
9631 }))
9632 .unwrap()
9633 .additional_directories,
9634 Vec::<AbsolutePath>::new()
9635 );
9636 }
9637 #[test]
9638 fn test_session_additional_directories_capabilities_serialization() {
9639 assert_eq!(
9640 serde_json::to_value(
9641 SessionCapabilities::new()
9642 .additional_directories(SessionAdditionalDirectoriesCapabilities::new())
9643 )
9644 .unwrap(),
9645 json!({
9646 "additionalDirectories": {}
9647 })
9648 );
9649 }
9650
9651 #[test]
9652 fn test_session_system_prompt_capabilities_serialization() {
9653 assert_eq!(
9654 serde_json::to_value(
9655 SessionCapabilities::new().system_prompt(SessionSystemPromptCapabilities::new())
9656 )
9657 .unwrap(),
9658 json!({ "systemPrompt": {} })
9659 );
9660 assert_eq!(
9661 serde_json::to_value(
9662 SessionCapabilities::new().system_prompt(
9663 SessionSystemPromptCapabilities::new().mode(
9664 SessionSystemPromptModeCapabilities::new()
9665 .override_(SessionSystemPromptOverrideCapabilities::new())
9666 )
9667 )
9668 )
9669 .unwrap(),
9670 json!({ "systemPrompt": { "mode": { "override": {} } } })
9671 );
9672 assert_eq!(
9673 serde_json::from_value::<SessionCapabilities>(
9674 json!({ "systemPrompt": { "mode": { "override": {} } } })
9675 )
9676 .unwrap()
9677 .system_prompt
9678 .and_then(|capabilities| capabilities.mode)
9679 .and_then(|mode| mode.override_),
9680 Some(SessionSystemPromptOverrideCapabilities::new())
9681 );
9682
9683 assert_eq!(
9685 serde_json::from_value::<SessionCapabilities>(json!({ "systemPrompt": "yes" }))
9686 .unwrap()
9687 .system_prompt,
9688 None
9689 );
9690 assert_eq!(
9691 serde_json::from_value::<SessionCapabilities>(
9692 json!({ "systemPrompt": { "mode": { "override": true } } })
9693 )
9694 .unwrap()
9695 .system_prompt,
9696 Some(
9697 SessionSystemPromptCapabilities::new()
9698 .mode(SessionSystemPromptModeCapabilities::new())
9699 )
9700 );
9701 assert_eq!(
9702 serde_json::from_value::<SessionCapabilities>(
9703 json!({ "systemPrompt": { "mode": "override" } })
9704 )
9705 .unwrap()
9706 .system_prompt,
9707 Some(SessionSystemPromptCapabilities::new())
9708 );
9709 }
9710
9711 #[test]
9712 fn test_system_prompt_lifecycle_request_serialization() {
9713 let system_prompt = SystemPrompt::new(vec![ContentBlock::from(
9714 "You are a code review specialist.",
9715 )]);
9716 let system_prompt_json = json!({
9717 "mode": "append",
9718 "content": [{ "type": "text", "text": "You are a code review specialist." }]
9719 });
9720
9721 let request =
9722 NewSessionRequest::new("/home/user/project").system_prompt(system_prompt.clone());
9723 let request_json = json!({
9724 "cwd": "/home/user/project",
9725 "systemPrompt": system_prompt_json
9726 });
9727 assert_eq!(serde_json::to_value(&request).unwrap(), request_json);
9728 assert_eq!(
9729 serde_json::from_value::<NewSessionRequest>(request_json).unwrap(),
9730 request
9731 );
9732
9733 assert_eq!(
9734 serde_json::to_value(
9735 ResumeSessionRequest::new("sess_abc123", "/home/user/project")
9736 .system_prompt(system_prompt.clone())
9737 )
9738 .unwrap()["systemPrompt"],
9739 system_prompt_json
9740 );
9741 #[cfg(feature = "unstable_session_fork")]
9742 assert_eq!(
9743 serde_json::to_value(
9744 ForkSessionRequest::new("sess_abc123", "/home/user/project")
9745 .system_prompt(system_prompt.clone())
9746 )
9747 .unwrap()["systemPrompt"],
9748 system_prompt_json
9749 );
9750
9751 let override_prompt =
9752 SystemPrompt::new(vec![ContentBlock::from("...")]).mode(SystemPromptMode::Override);
9753 let override_json = json!({
9754 "mode": "override",
9755 "content": [{ "type": "text", "text": "..." }]
9756 });
9757 assert_eq!(
9758 serde_json::to_value(&override_prompt).unwrap(),
9759 override_json
9760 );
9761 assert_eq!(
9762 serde_json::from_value::<SystemPrompt>(override_json).unwrap(),
9763 override_prompt
9764 );
9765 }
9766
9767 #[test]
9770 fn test_system_prompt_new_defaults_to_append() {
9771 let system_prompt = SystemPrompt::new(vec![ContentBlock::from("...")]);
9772 assert_eq!(system_prompt.mode, SystemPromptMode::Append);
9773 assert_eq!(
9774 serde_json::to_value(&system_prompt).unwrap(),
9775 json!({ "mode": "append", "content": [{ "type": "text", "text": "..." }] })
9776 );
9777 }
9778
9779 #[test]
9783 fn test_system_prompt_preserves_unknown_modes() {
9784 for mode in ["_vendor_mode", "prepend"] {
9785 let system_prompt_json =
9786 json!({ "mode": mode, "content": [{ "type": "text", "text": "..." }] });
9787 let system_prompt: SystemPrompt =
9788 serde_json::from_value(system_prompt_json.clone()).unwrap();
9789 assert_eq!(
9790 system_prompt.mode,
9791 SystemPromptMode::Other(mode.to_string())
9792 );
9793 assert_eq!(
9794 serde_json::to_value(&system_prompt).unwrap(),
9795 system_prompt_json
9796 );
9797 }
9798 }
9799
9800 fn assert_system_prompt_is_strict<T>(base: &serde_json::Value)
9804 where
9805 T: serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
9806 {
9807 let name = std::any::type_name::<T>();
9808 let with = |system_prompt: serde_json::Value| {
9809 let mut request = base.clone();
9810 request["systemPrompt"] = system_prompt;
9811 serde_json::from_value::<T>(request)
9812 };
9813
9814 for system_prompt in [
9815 json!("You are a code review specialist."),
9816 json!({ "content": [{ "type": "text", "text": "..." }] }),
9817 json!({ "mode": null, "content": [{ "type": "text", "text": "..." }] }),
9818 json!({ "mode": 1, "content": [{ "type": "text", "text": "..." }] }),
9819 json!({ "mode": "append" }),
9820 json!({ "mode": "append", "content": "..." }),
9821 json!({ "mode": "append", "content": [{ "type": "text" }] }),
9822 ] {
9823 assert!(
9824 with(system_prompt.clone()).is_err(),
9825 "{name}.systemPrompt: {system_prompt}"
9826 );
9827 }
9828
9829 assert_eq!(
9830 with(serde_json::Value::Null).unwrap(),
9831 serde_json::from_value::<T>(base.clone()).unwrap(),
9832 "{name}.systemPrompt"
9833 );
9834 }
9835
9836 #[test]
9837 fn test_session_setup_requests_reject_malformed_system_prompts() {
9838 assert!(
9839 serde_json::to_value(NewSessionRequest::new("/repo"))
9840 .unwrap()
9841 .get("systemPrompt")
9842 .is_none()
9843 );
9844 assert_system_prompt_is_strict::<NewSessionRequest>(&json!({ "cwd": "/repo" }));
9845 assert_system_prompt_is_strict::<ResumeSessionRequest>(&json!({
9846 "sessionId": "sess-1",
9847 "cwd": "/repo"
9848 }));
9849 #[cfg(feature = "unstable_session_fork")]
9850 assert_system_prompt_is_strict::<ForkSessionRequest>(&json!({
9851 "sessionId": "sess-1",
9852 "cwd": "/repo"
9853 }));
9854 }
9855
9856 #[test]
9859 fn test_system_prompt_preserves_unknown_content_blocks() {
9860 let request: NewSessionRequest = serde_json::from_value(json!({
9861 "cwd": "/home/user/project",
9862 "systemPrompt": {
9863 "mode": "append",
9864 "content": [{ "type": "_vendor_video", "uri": "https://example.com/intro.mp4" }]
9865 }
9866 }))
9867 .unwrap();
9868 let content = request.system_prompt.unwrap().content;
9869 assert_eq!(content.len(), 1);
9870 assert!(matches!(content[0], ContentBlock::Other(_)));
9871 }
9872
9873 #[test]
9874 fn test_auth_method_terminal_serialization() {
9875 let method = AuthMethod::Terminal(AuthMethodTerminal::new("tui-auth", "Terminal Auth"));
9876
9877 let json = serde_json::to_value(&method).unwrap();
9878 assert_eq!(
9879 json,
9880 json!({
9881 "methodId": "tui-auth",
9882 "name": "Terminal Auth",
9883 "type": "terminal"
9884 })
9885 );
9886 assert!(!json.as_object().unwrap().contains_key("args"));
9888 assert!(!json.as_object().unwrap().contains_key("env"));
9889
9890 let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9891 match deserialized {
9892 AuthMethod::Terminal(AuthMethodTerminal { args, env, .. }) => {
9893 assert_eq!(args, Vec::<String>::new());
9894 assert_eq!(env, []);
9895 }
9896 _ => panic!("Expected Terminal variant"),
9897 }
9898 }
9899
9900 #[test]
9901 fn test_auth_method_terminal_with_args_and_env_serialization() {
9902 let method = AuthMethod::Terminal(
9903 AuthMethodTerminal::new("tui-auth", "Terminal Auth")
9904 .args(vec!["--interactive".to_string(), "--color".to_string()])
9905 .env(vec![EnvVariable::new("TERM", "xterm-256color")]),
9906 );
9907
9908 let json = serde_json::to_value(&method).unwrap();
9909 assert_eq!(
9910 json,
9911 json!({
9912 "methodId": "tui-auth",
9913 "name": "Terminal Auth",
9914 "type": "terminal",
9915 "args": ["--interactive", "--color"],
9916 "env": [
9917 {
9918 "name": "TERM",
9919 "value": "xterm-256color"
9920 }
9921 ]
9922 })
9923 );
9924
9925 let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9926 match deserialized {
9927 AuthMethod::Terminal(AuthMethodTerminal { args, env, .. }) => {
9928 assert_eq!(args, vec!["--interactive", "--color"]);
9929 assert_eq!(env.len(), 1);
9930 assert_eq!(env[0].name, "TERM");
9931 assert_eq!(env[0].value, "xterm-256color");
9932 }
9933 _ => panic!("Expected Terminal variant"),
9934 }
9935 }
9936
9937 #[test]
9938 fn test_session_config_option_id_serialize() {
9939 let val = SessionConfigOptionValue::id("model-1");
9940 let json = serde_json::to_value(&val).unwrap();
9941 assert_eq!(json, json!({ "type": "id", "value": "model-1" }));
9942 }
9943
9944 #[test]
9945 fn test_session_config_option_value_boolean_serialize() {
9946 let val = SessionConfigOptionValue::boolean(true);
9947 let json = serde_json::to_value(&val).unwrap();
9948 assert_eq!(json, json!({ "type": "boolean", "value": true }));
9949 }
9950
9951 #[test]
9952 fn test_session_config_option_value_deserialize_id() {
9953 let json = json!({ "type": "id", "value": "model-1" });
9954 let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9955 assert_eq!(val, SessionConfigOptionValue::id("model-1"));
9956 assert_eq!(val.as_id().unwrap().to_string(), "model-1");
9957 }
9958
9959 #[test]
9960 fn test_session_config_option_value_deserialize_requires_type() {
9961 let json = json!({ "value": "model-1" });
9962 let result = serde_json::from_value::<SessionConfigOptionValue>(json);
9963 assert!(result.is_err());
9964 }
9965
9966 #[test]
9967 fn test_session_config_option_value_deserialize_boolean() {
9968 let json = json!({ "type": "boolean", "value": true });
9969 let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9970 assert_eq!(val, SessionConfigOptionValue::boolean(true));
9971 assert_eq!(val.as_bool(), Some(true));
9972 }
9973
9974 #[test]
9975 fn test_session_config_option_value_deserialize_boolean_false() {
9976 let json = json!({ "type": "boolean", "value": false });
9977 let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9978 assert_eq!(val, SessionConfigOptionValue::boolean(false));
9979 assert_eq!(val.as_bool(), Some(false));
9980 }
9981
9982 #[test]
9983 fn test_session_config_option_value_deserialize_unknown_type_with_string_value() {
9984 let json = json!({
9985 "type": "text",
9986 "value": "freeform input",
9987 "maxLength": 200
9988 });
9989 let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9990 let SessionConfigOptionValue::Other(unknown) = val else {
9991 panic!("Expected Other variant");
9992 };
9993 assert_eq!(unknown.type_, "text");
9994 assert_eq!(unknown.value, json!("freeform input"));
9995 assert_eq!(unknown.fields["maxLength"], json!(200));
9996 }
9997
9998 #[test]
9999 fn test_session_config_option_value_deserialize_unknown_type_with_object_value() {
10000 let json = json!({
10001 "type": "range",
10002 "value": { "min": 1, "max": 5 }
10003 });
10004 let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10005 let SessionConfigOptionValue::Other(unknown) = val else {
10006 panic!("Expected Other variant");
10007 };
10008 assert_eq!(unknown.type_, "range");
10009 assert_eq!(unknown.value, json!({ "min": 1, "max": 5 }));
10010 }
10011
10012 #[test]
10013 fn test_session_config_option_value_roundtrip_id() {
10014 let original = SessionConfigOptionValue::id("option-a");
10015 let json = serde_json::to_value(&original).unwrap();
10016 let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10017 assert_eq!(original, roundtripped);
10018 }
10019
10020 #[test]
10021 fn test_session_config_option_value_roundtrip_boolean() {
10022 let original = SessionConfigOptionValue::boolean(false);
10023 let json = serde_json::to_value(&original).unwrap();
10024 let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10025 assert_eq!(original, roundtripped);
10026 }
10027
10028 #[test]
10029 fn test_session_config_option_value_roundtrip_other() {
10030 let mut fields = IndexMap::new();
10031 fields.insert("maxLength".to_string(), json!(200));
10032 let original = SessionConfigOptionValue::Other(OtherSessionConfigOptionValue::new(
10033 "text",
10034 json!("freeform input"),
10035 fields,
10036 ));
10037 let json = serde_json::to_value(&original).unwrap();
10038 let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10039 assert_eq!(original, roundtripped);
10040 }
10041
10042 #[test]
10043 fn test_session_config_option_value_type_mismatch_boolean_with_string() {
10044 let json = json!({ "type": "boolean", "value": "not a bool" });
10045 let result = serde_json::from_value::<SessionConfigOptionValue>(json);
10046 assert!(result.is_err());
10047 }
10048
10049 #[test]
10050 fn test_session_config_option_value_from_impls() {
10051 let from_str: SessionConfigOptionValue = "model-1".into();
10052 assert_eq!(from_str.as_id().unwrap().to_string(), "model-1");
10053
10054 let from_id: SessionConfigOptionValue = SessionConfigValueId::new("model-2").into();
10055 assert_eq!(from_id.as_id().unwrap().to_string(), "model-2");
10056
10057 let from_bool: SessionConfigOptionValue = true.into();
10058 assert_eq!(from_bool.as_bool(), Some(true));
10059 }
10060
10061 #[test]
10062 fn test_set_session_config_option_request_id() {
10063 let req = SetSessionConfigOptionRequest::new("sess_1", "model", "model-1");
10064 let json = serde_json::to_value(&req).unwrap();
10065 assert_eq!(
10066 json,
10067 json!({
10068 "sessionId": "sess_1",
10069 "configId": "model",
10070 "type": "id",
10071 "value": "model-1"
10072 })
10073 );
10074 }
10075
10076 #[test]
10077 fn test_set_session_config_option_request_boolean() {
10078 let req = SetSessionConfigOptionRequest::new("sess_1", "brave_mode", true);
10079 let json = serde_json::to_value(&req).unwrap();
10080 assert_eq!(
10081 json,
10082 json!({
10083 "sessionId": "sess_1",
10084 "configId": "brave_mode",
10085 "type": "boolean",
10086 "value": true
10087 })
10088 );
10089 }
10090
10091 #[test]
10092 fn test_set_session_config_option_request_deserialize_requires_type() {
10093 let json = json!({
10094 "sessionId": "sess_1",
10095 "configId": "model",
10096 "value": "model-1"
10097 });
10098 let result = serde_json::from_value::<SetSessionConfigOptionRequest>(json);
10099 assert!(result.is_err());
10100 }
10101
10102 #[test]
10103 fn test_set_session_config_option_request_deserialize_boolean() {
10104 let json = json!({
10105 "sessionId": "sess_1",
10106 "configId": "brave_mode",
10107 "type": "boolean",
10108 "value": true
10109 });
10110 let req: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
10111 assert_eq!(req.value.as_bool(), Some(true));
10112 }
10113
10114 #[test]
10115 fn test_set_session_config_option_request_roundtrip_id() {
10116 let original = SetSessionConfigOptionRequest::new("s", "c", "v");
10117 let json = serde_json::to_value(&original).unwrap();
10118 let roundtripped: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
10119 assert_eq!(original, roundtripped);
10120 }
10121
10122 #[test]
10123 fn test_set_session_config_option_request_roundtrip_boolean() {
10124 let original = SetSessionConfigOptionRequest::new("s", "c", false);
10125 let json = serde_json::to_value(&original).unwrap();
10126 let roundtripped: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
10127 assert_eq!(original, roundtripped);
10128 }
10129
10130 #[test]
10131 fn test_session_config_boolean_serialization() {
10132 let cfg = SessionConfigBoolean::new(true);
10133 let json = serde_json::to_value(&cfg).unwrap();
10134 assert_eq!(json, json!({ "currentValue": true }));
10135
10136 let deserialized: SessionConfigBoolean = serde_json::from_value(json).unwrap();
10137 assert!(deserialized.current_value);
10138 }
10139
10140 #[test]
10141 fn test_session_config_option_boolean_variant() {
10142 let opt = SessionConfigOption::boolean("brave_mode", "Brave Mode", false)
10143 .description("Skip confirmation prompts")
10144 .meta(test_meta());
10145 assert_eq!(serialized_meta_key_count(&opt), 1);
10146
10147 let json = serde_json::to_value(&opt).unwrap();
10148 assert_eq!(
10149 json,
10150 json!({
10151 "configId": "brave_mode",
10152 "name": "Brave Mode",
10153 "description": "Skip confirmation prompts",
10154 "type": "boolean",
10155 "currentValue": false,
10156 "_meta": {
10157 "source": "test"
10158 }
10159 })
10160 );
10161
10162 let deserialized: SessionConfigOption = serde_json::from_value(json).unwrap();
10163 assert_eq!(deserialized.config_id.to_string(), "brave_mode");
10164 assert_eq!(deserialized.name, "Brave Mode");
10165 match deserialized.kind {
10166 SessionConfigKind::Boolean(ref b) => assert!(!b.current_value),
10167 _ => panic!("Expected Boolean kind"),
10168 }
10169 }
10170
10171 #[test]
10172 fn test_session_config_option_select_still_works() {
10173 let opt = SessionConfigOption::select(
10175 "model",
10176 "Model",
10177 "model-1",
10178 vec![
10179 SessionConfigSelectOption::new("model-1", "Model 1"),
10180 SessionConfigSelectOption::new("model-2", "Model 2"),
10181 ],
10182 )
10183 .meta(test_meta());
10184 assert_eq!(serialized_meta_key_count(&opt), 1);
10185
10186 let json = serde_json::to_value(&opt).unwrap();
10187 assert_eq!(json["type"], "select");
10188 assert_eq!(json["currentValue"], "model-1");
10189 assert_eq!(json["options"].as_array().unwrap().len(), 2);
10190 assert_eq!(json["_meta"]["source"], "test");
10191
10192 let deserialized: SessionConfigOption = serde_json::from_value(json).unwrap();
10193 match deserialized.kind {
10194 SessionConfigKind::Select(ref s) => {
10195 assert_eq!(s.current_value.to_string(), "model-1");
10196 }
10197 _ => panic!("Expected Select kind"),
10198 }
10199 }
10200
10201 #[test]
10202 fn test_session_config_option_unknown_kind_roundtrip() {
10203 let option: SessionConfigOption = serde_json::from_value(json!({
10204 "configId": "verbosity",
10205 "name": "Verbosity",
10206 "type": "_slider",
10207 "currentValue": 3,
10208 "min": 0,
10209 "max": 5,
10210 "_meta": {
10211 "source": "test"
10212 }
10213 }))
10214 .unwrap();
10215
10216 assert_eq!(option.config_id.to_string(), "verbosity");
10217 assert_eq!(option.meta.as_ref().unwrap()["source"], "test");
10218 let SessionConfigKind::Other(unknown) = &option.kind else {
10219 panic!("expected unknown config kind");
10220 };
10221 assert_eq!(unknown.type_, "_slider");
10222 assert_eq!(unknown.fields.get("currentValue"), Some(&json!(3)));
10223 assert!(!unknown.fields.contains_key("_meta"));
10224 assert_eq!(serialized_meta_key_count(&option), 1);
10225
10226 let json = serde_json::to_value(&option).unwrap();
10227 assert_eq!(json["type"], "_slider");
10228 assert_eq!(json["currentValue"], 3);
10229 assert_eq!(json["min"], 0);
10230 assert_eq!(json["max"], 5);
10231 assert_eq!(json["_meta"]["source"], "test");
10232 }
10233
10234 #[test]
10235 fn test_session_config_option_unknown_kind_does_not_duplicate_flattened_meta() {
10236 let mut fields = IndexMap::new();
10237 fields.insert("currentValue".to_string(), json!(3));
10238 fields.insert("_meta".to_string(), json!({ "inner": "ignored" }));
10239
10240 let option = SessionConfigOption::new(
10241 "verbosity",
10242 "Verbosity",
10243 SessionConfigKind::Other(OtherSessionConfigKind::new("_slider", fields)),
10244 )
10245 .meta(test_meta());
10246
10247 let SessionConfigKind::Other(unknown) = &option.kind else {
10248 panic!("expected unknown config kind");
10249 };
10250 assert!(!unknown.fields.contains_key("_meta"));
10251 assert_eq!(serialized_meta_key_count(&option), 1);
10252
10253 let json = serde_json::to_value(&option).unwrap();
10254 assert_eq!(json["type"], "_slider");
10255 assert_eq!(json["currentValue"], 3);
10256 assert_eq!(json["_meta"]["source"], "test");
10257 }
10258
10259 #[test]
10260 fn test_session_config_option_unknown_does_not_hide_malformed_known_kind() {
10261 assert!(
10262 serde_json::from_value::<SessionConfigOption>(json!({
10263 "configId": "model",
10264 "name": "Model",
10265 "type": "select"
10266 }))
10267 .is_err()
10268 );
10269 }
10270
10271 #[cfg(feature = "unstable_llm_providers")]
10272 #[test]
10273 fn test_llm_protocol_known_variants() {
10274 assert_eq!(
10275 serde_json::to_value(&LlmProtocol::Anthropic).unwrap(),
10276 json!("anthropic")
10277 );
10278 assert_eq!(
10279 serde_json::to_value(&LlmProtocol::OpenAi).unwrap(),
10280 json!("openai")
10281 );
10282 assert_eq!(
10283 serde_json::to_value(&LlmProtocol::Azure).unwrap(),
10284 json!("azure")
10285 );
10286 assert_eq!(
10287 serde_json::to_value(&LlmProtocol::Vertex).unwrap(),
10288 json!("vertex")
10289 );
10290 assert_eq!(
10291 serde_json::to_value(&LlmProtocol::Bedrock).unwrap(),
10292 json!("bedrock")
10293 );
10294
10295 assert_eq!(
10296 serde_json::from_str::<LlmProtocol>("\"anthropic\"").unwrap(),
10297 LlmProtocol::Anthropic
10298 );
10299 assert_eq!(
10300 serde_json::from_str::<LlmProtocol>("\"openai\"").unwrap(),
10301 LlmProtocol::OpenAi
10302 );
10303 assert_eq!(
10304 serde_json::from_str::<LlmProtocol>("\"azure\"").unwrap(),
10305 LlmProtocol::Azure
10306 );
10307 assert_eq!(
10308 serde_json::from_str::<LlmProtocol>("\"vertex\"").unwrap(),
10309 LlmProtocol::Vertex
10310 );
10311 assert_eq!(
10312 serde_json::from_str::<LlmProtocol>("\"bedrock\"").unwrap(),
10313 LlmProtocol::Bedrock
10314 );
10315 }
10316
10317 #[cfg(feature = "unstable_llm_providers")]
10318 #[test]
10319 fn test_llm_protocol_unknown_variant() {
10320 let unknown: LlmProtocol = serde_json::from_str("\"cohere\"").unwrap();
10321 assert_eq!(unknown, LlmProtocol::Other("cohere".to_string()));
10322
10323 let json = serde_json::to_value(&unknown).unwrap();
10324 assert_eq!(json, json!("cohere"));
10325 }
10326
10327 #[cfg(feature = "unstable_llm_providers")]
10328 #[test]
10329 fn test_provider_current_config_serialization() {
10330 let config =
10331 ProviderCurrentConfig::new(LlmProtocol::Anthropic, "https://api.anthropic.com");
10332
10333 let json = serde_json::to_value(&config).unwrap();
10334 assert_eq!(
10335 json,
10336 json!({
10337 "apiType": "anthropic",
10338 "baseUrl": "https://api.anthropic.com"
10339 })
10340 );
10341
10342 let deserialized: ProviderCurrentConfig = serde_json::from_value(json).unwrap();
10343 assert_eq!(deserialized.api_type, LlmProtocol::Anthropic);
10344 assert_eq!(deserialized.base_url, "https://api.anthropic.com");
10345 }
10346
10347 #[cfg(feature = "unstable_llm_providers")]
10348 #[test]
10349 fn test_provider_info_with_current_config() {
10350 let info = ProviderInfo::new(
10351 "main",
10352 vec![LlmProtocol::Anthropic, LlmProtocol::OpenAi],
10353 true,
10354 Some(ProviderCurrentConfig::new(
10355 LlmProtocol::Anthropic,
10356 "https://api.anthropic.com",
10357 )),
10358 );
10359
10360 let json = serde_json::to_value(&info).unwrap();
10361 assert_eq!(
10362 json,
10363 json!({
10364 "providerId": "main",
10365 "supported": ["anthropic", "openai"],
10366 "required": true,
10367 "current": {
10368 "apiType": "anthropic",
10369 "baseUrl": "https://api.anthropic.com"
10370 }
10371 })
10372 );
10373
10374 let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10375 assert_eq!(deserialized.provider_id.to_string(), "main");
10376 assert_eq!(deserialized.supported.len(), 2);
10377 assert!(deserialized.required);
10378 assert!(deserialized.current.is_some());
10379 assert_eq!(
10380 deserialized.current.as_ref().unwrap().api_type,
10381 LlmProtocol::Anthropic
10382 );
10383 }
10384
10385 #[cfg(feature = "unstable_llm_providers")]
10386 #[test]
10387 fn test_provider_info_disabled() {
10388 let info = ProviderInfo::new(
10389 "secondary",
10390 vec![LlmProtocol::OpenAi],
10391 false,
10392 None::<ProviderCurrentConfig>,
10393 );
10394
10395 let json = serde_json::to_value(&info).unwrap();
10396 assert_eq!(
10397 json,
10398 json!({
10399 "providerId": "secondary",
10400 "supported": ["openai"],
10401 "required": false
10402 })
10403 );
10404
10405 let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10406 assert_eq!(deserialized.provider_id.to_string(), "secondary");
10407 assert!(!deserialized.required);
10408 assert!(deserialized.current.is_none());
10409 }
10410
10411 #[cfg(feature = "unstable_llm_providers")]
10412 #[test]
10413 fn test_provider_info_missing_current_defaults_to_none() {
10414 let json = json!({
10416 "providerId": "main",
10417 "supported": ["anthropic"],
10418 "required": true
10419 });
10420 let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10421 assert!(deserialized.current.is_none());
10422 }
10423
10424 #[cfg(feature = "unstable_llm_providers")]
10425 #[test]
10426 fn test_provider_info_explicit_null_current_decodes_to_none() {
10427 let json = json!({
10431 "providerId": "main",
10432 "supported": ["anthropic"],
10433 "required": true,
10434 "current": null
10435 });
10436 let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10437 assert!(deserialized.current.is_none());
10438 }
10439
10440 #[cfg(feature = "unstable_llm_providers")]
10441 #[test]
10442 fn test_list_providers_response_serialization() {
10443 let response = ListProvidersResponse::new(vec![ProviderInfo::new(
10444 "main",
10445 vec![LlmProtocol::Anthropic],
10446 true,
10447 Some(ProviderCurrentConfig::new(
10448 LlmProtocol::Anthropic,
10449 "https://api.anthropic.com",
10450 )),
10451 )]);
10452
10453 let json = serde_json::to_value(&response).unwrap();
10454 assert_eq!(json["providers"].as_array().unwrap().len(), 1);
10455 assert_eq!(json["providers"][0]["providerId"], "main");
10456
10457 let deserialized: ListProvidersResponse = serde_json::from_value(json).unwrap();
10458 assert_eq!(deserialized.providers.len(), 1);
10459 }
10460
10461 #[cfg(feature = "unstable_llm_providers")]
10462 #[test]
10463 fn test_set_provider_request_serialization() {
10464 let mut headers = IndexMap::new();
10465 headers.insert("Authorization".to_string(), "Bearer sk-test".to_string());
10466
10467 let request =
10468 SetProviderRequest::new("main", LlmProtocol::OpenAi, "https://api.openai.com/v1")
10469 .headers(headers);
10470
10471 let json = serde_json::to_value(&request).unwrap();
10472 assert_eq!(
10473 json,
10474 json!({
10475 "providerId": "main",
10476 "apiType": "openai",
10477 "baseUrl": "https://api.openai.com/v1",
10478 "headers": {
10479 "Authorization": "Bearer sk-test"
10480 }
10481 })
10482 );
10483
10484 let deserialized: SetProviderRequest = serde_json::from_value(json).unwrap();
10485 assert_eq!(deserialized.provider_id.to_string(), "main");
10486 assert_eq!(deserialized.api_type, LlmProtocol::OpenAi);
10487 assert_eq!(deserialized.base_url, "https://api.openai.com/v1");
10488 assert_eq!(deserialized.headers.len(), 1);
10489 assert_eq!(
10490 deserialized.headers.get("Authorization").unwrap(),
10491 "Bearer sk-test"
10492 );
10493 }
10494
10495 #[cfg(feature = "unstable_llm_providers")]
10496 #[test]
10497 fn test_set_provider_request_omits_empty_headers() {
10498 let request =
10499 SetProviderRequest::new("main", LlmProtocol::Anthropic, "https://api.anthropic.com");
10500
10501 let json = serde_json::to_value(&request).unwrap();
10502 assert!(!json.as_object().unwrap().contains_key("headers"));
10504 }
10505
10506 #[cfg(feature = "unstable_llm_providers")]
10507 #[test]
10508 fn test_disable_provider_request_serialization() {
10509 let request = DisableProviderRequest::new("secondary");
10510
10511 let json = serde_json::to_value(&request).unwrap();
10512 assert_eq!(json, json!({ "providerId": "secondary" }));
10513
10514 let deserialized: DisableProviderRequest = serde_json::from_value(json).unwrap();
10515 assert_eq!(deserialized.provider_id.to_string(), "secondary");
10516 }
10517
10518 #[cfg(feature = "unstable_llm_providers")]
10519 #[test]
10520 fn test_providers_capabilities_serialization() {
10521 let caps = ProvidersCapabilities::new();
10522
10523 let json = serde_json::to_value(&caps).unwrap();
10524 assert_eq!(json, json!({}));
10525
10526 let deserialized: ProvidersCapabilities = serde_json::from_value(json).unwrap();
10527 assert!(deserialized.meta.is_none());
10528 }
10529
10530 #[cfg(feature = "unstable_llm_providers")]
10531 #[test]
10532 fn test_agent_capabilities_with_providers() {
10533 let caps = AgentCapabilities::new().providers(ProvidersCapabilities::new());
10534
10535 let json = serde_json::to_value(&caps).unwrap();
10536 assert_eq!(json["providers"], json!({}));
10537
10538 let deserialized: AgentCapabilities = serde_json::from_value(json).unwrap();
10539 assert!(deserialized.providers.is_some());
10540 }
10541
10542 #[test]
10543 fn test_agent_capabilities_session_is_explicit() {
10544 let json = serde_json::to_value(AgentCapabilities::new()).unwrap();
10545 assert!(json.get("session").is_none());
10546
10547 let caps = AgentCapabilities::new().session(
10548 SessionCapabilities::new()
10549 .prompt(PromptCapabilities::new().image(PromptImageCapabilities::new()))
10550 .mcp(McpCapabilities::new().stdio(McpStdioCapabilities::new())),
10551 );
10552
10553 assert_eq!(
10554 serde_json::to_value(&caps).unwrap(),
10555 json!({
10556 "session": {
10557 "prompt": {
10558 "image": {}
10559 },
10560 "mcp": {
10561 "stdio": {}
10562 }
10563 }
10564 })
10565 );
10566
10567 let deserialized: AgentCapabilities = serde_json::from_value(json!({
10568 "session": false
10569 }))
10570 .unwrap();
10571 assert!(deserialized.session.is_none());
10572 }
10573
10574 #[test]
10575 fn test_prompt_capabilities_serialize_supported_content_as_objects() {
10576 let caps = PromptCapabilities::new()
10577 .image(PromptImageCapabilities::new())
10578 .audio(PromptAudioCapabilities::new())
10579 .embedded_context(PromptEmbeddedContextCapabilities::new());
10580
10581 assert_eq!(
10582 serde_json::to_value(&caps).unwrap(),
10583 json!({
10584 "image": {},
10585 "audio": {},
10586 "embeddedContext": {}
10587 })
10588 );
10589
10590 let deserialized: PromptCapabilities = serde_json::from_value(json!({
10591 "image": null,
10592 "audio": false,
10593 "embeddedContext": {}
10594 }))
10595 .unwrap();
10596 assert!(deserialized.image.is_none());
10597 assert!(deserialized.audio.is_none());
10598 assert!(deserialized.embedded_context.is_some());
10599 }
10600
10601 #[cfg(feature = "unstable_agent_skills")]
10602 #[test]
10603 fn prompt_skill_capability_has_two_levels() {
10604 let leading = PromptCapabilities::new().skill(PromptSkillCapabilities::new());
10606 assert_eq!(
10607 serde_json::to_value(&leading).unwrap(),
10608 json!({ "skill": {} })
10609 );
10610
10611 let inline = PromptCapabilities::new()
10612 .skill(PromptSkillCapabilities::new().inline(PromptSkillInlineCapabilities::new()));
10613 let wire = json!({ "skill": { "inline": {} } });
10614 assert_eq!(serde_json::to_value(&inline).unwrap(), wire);
10615 assert_eq!(
10616 serde_json::from_value::<PromptCapabilities>(wire).unwrap(),
10617 inline
10618 );
10619
10620 for unsupported in [
10621 json!({}),
10622 json!({ "skill": null }),
10623 json!({ "skill": false }),
10624 json!({ "skill": true }),
10625 ] {
10626 let caps: PromptCapabilities = serde_json::from_value(unsupported).unwrap();
10627 assert!(caps.skill.is_none());
10628 }
10629
10630 for leading_only in [
10632 json!({ "skill": { "inline": null } }),
10633 json!({ "skill": { "inline": true } }),
10634 ] {
10635 assert_eq!(
10636 serde_json::from_value::<PromptCapabilities>(leading_only).unwrap(),
10637 leading
10638 );
10639 }
10640 }
10641
10642 #[test]
10643 fn test_mcp_capabilities_serialize_supported_transports_as_objects() {
10644 let caps = McpCapabilities::new()
10645 .stdio(McpStdioCapabilities::new())
10646 .http(McpHttpCapabilities::new());
10647
10648 assert_eq!(
10649 serde_json::to_value(&caps).unwrap(),
10650 json!({
10651 "stdio": {},
10652 "http": {}
10653 })
10654 );
10655
10656 let deserialized: McpCapabilities = serde_json::from_value(json!({
10657 "stdio": null,
10658 "http": false
10659 }))
10660 .unwrap();
10661 assert!(deserialized.stdio.is_none());
10662 assert!(deserialized.http.is_none());
10663 }
10664
10665 #[cfg(feature = "unstable_mcp_over_acp")]
10666 #[test]
10667 fn test_mcp_capabilities_serialize_acp_support_as_object() {
10668 let caps = McpCapabilities::new().acp(McpAcpCapabilities::new());
10669
10670 assert_eq!(
10671 serde_json::to_value(&caps).unwrap(),
10672 json!({
10673 "acp": {}
10674 })
10675 );
10676 }
10677
10678 #[test]
10679 fn prompt_request_rejects_malformed_content_block() {
10680 use serde_json::json;
10681
10682 assert!(
10683 serde_json::from_value::<PromptRequest>(json!({
10684 "sessionId": "sess-1",
10685 "prompt": [{"type": "text"}]
10686 }))
10687 .is_err()
10688 );
10689 }
10690
10691 #[test]
10692 fn prompt_request_rejects_non_array_prompt() {
10693 use serde_json::json;
10694
10695 assert!(
10696 serde_json::from_value::<PromptRequest>(json!({
10697 "sessionId": "sess-1",
10698 "prompt": "hello"
10699 }))
10700 .is_err()
10701 );
10702 }
10703
10704 fn prompt_request_with_idempotency_key(key: &serde_json::Value) -> serde_json::Value {
10705 serde_json::json!({
10706 "sessionId": "sess-1",
10707 "idempotencyKey": key,
10708 "prompt": [{"type": "text", "text": "hello"}]
10709 })
10710 }
10711
10712 #[test]
10713 fn prompt_request_idempotency_key_round_trips() {
10714 use serde_json::json;
10715
10716 let key = "0b6f3c1e-8d2a-4c57-9a41-5e2f7d90c3ab";
10717 let value = prompt_request_with_idempotency_key(&json!(key));
10718
10719 let request: PromptRequest = serde_json::from_value(value.clone()).unwrap();
10720 assert_eq!(
10721 request.idempotency_key.as_ref().map(IdempotencyKey::as_str),
10722 Some(key)
10723 );
10724 assert_eq!(serde_json::to_value(&request).unwrap(), value);
10725
10726 let built = PromptRequest::new("sess-1", vec![ContentBlock::from("hello")])
10727 .idempotency_key(IdempotencyKey::new(key).unwrap());
10728 assert_eq!(built, request);
10729 }
10730
10731 #[test]
10732 fn prompt_request_omitted_and_null_idempotency_key_mean_no_key() {
10733 use serde_json::json;
10734
10735 let omitted = json!({
10736 "sessionId": "sess-1",
10737 "prompt": [{"type": "text", "text": "hello"}]
10738 });
10739 let request: PromptRequest = serde_json::from_value(omitted.clone()).unwrap();
10740 assert_eq!(request.idempotency_key, None);
10741 assert_eq!(serde_json::to_value(&request).unwrap(), omitted);
10743
10744 let null: PromptRequest =
10745 serde_json::from_value(prompt_request_with_idempotency_key(&json!(null))).unwrap();
10746 assert_eq!(null, request);
10747 }
10748
10749 #[test]
10750 fn prompt_request_rejects_malformed_idempotency_key() {
10751 use serde_json::json;
10752
10753 let too_long = "k".repeat(IdempotencyKey::MAX_LENGTH + 1);
10754 for (name, key) in [
10755 ("an empty string", json!("")),
10756 ("a string over 255 characters", json!(too_long)),
10757 ("a number", json!(7)),
10758 ("a boolean", json!(true)),
10759 ("an object", json!({"key": "k"})),
10760 ("an array", json!(["k"])),
10761 ] {
10762 assert!(
10763 serde_json::from_value::<PromptRequest>(prompt_request_with_idempotency_key(&key))
10764 .is_err(),
10765 "{name} must fail the request instead of being treated as no key"
10766 );
10767 }
10768 }
10769
10770 #[test]
10771 fn idempotency_key_length_is_counted_in_characters() {
10772 use serde_json::json;
10773
10774 assert_eq!(IdempotencyKey::new(""), Err(InvalidIdempotencyKey::Empty));
10775 assert_eq!(IdempotencyKey::new("k").unwrap().as_str(), "k");
10776
10777 let longest = "k".repeat(IdempotencyKey::MAX_LENGTH);
10778 assert_eq!(
10779 IdempotencyKey::new(longest.as_str()).unwrap().as_str(),
10780 longest
10781 );
10782 assert_eq!(
10783 IdempotencyKey::new(format!("{longest}k")),
10784 Err(InvalidIdempotencyKey::TooLong)
10785 );
10786
10787 let multibyte = "é".repeat(IdempotencyKey::MAX_LENGTH);
10789 assert!(IdempotencyKey::new(multibyte.as_str()).is_ok());
10790 assert!(
10791 serde_json::from_value::<PromptRequest>(prompt_request_with_idempotency_key(&json!(
10792 multibyte
10793 )))
10794 .is_ok()
10795 );
10796 assert_eq!(
10797 IdempotencyKey::new(format!("{multibyte}é")),
10798 Err(InvalidIdempotencyKey::TooLong)
10799 );
10800
10801 assert_eq!("k".parse::<IdempotencyKey>().unwrap().to_string(), "k");
10802 assert_eq!(
10803 IdempotencyKey::try_from(String::new()),
10804 Err(InvalidIdempotencyKey::Empty)
10805 );
10806 assert_eq!(
10807 InvalidIdempotencyKey::TooLong.to_string(),
10808 "idempotency key must be at most 255 characters"
10809 );
10810 }
10811
10812 #[cfg(feature = "uuid")]
10813 #[test]
10814 fn generated_idempotency_keys_are_distinct_valid_v4_uuids() {
10815 let first = IdempotencyKey::generate();
10816 let second = IdempotencyKey::generate();
10817 assert_ne!(first, second);
10818
10819 for key in [&first, &second] {
10820 let uuid = uuid::Uuid::parse_str(key.as_str()).unwrap();
10821 assert_eq!(uuid.get_version_num(), 4);
10822 assert_eq!(IdempotencyKey::new(key.as_str()).as_ref(), Ok(key));
10824 let request = PromptRequest::new("sess-1", vec![ContentBlock::from("hello")])
10825 .idempotency_key(key.clone());
10826 let value = serde_json::to_value(&request).unwrap();
10827 assert_eq!(value["idempotencyKey"], key.as_str());
10828 assert_eq!(
10829 serde_json::from_value::<PromptRequest>(value).unwrap(),
10830 request
10831 );
10832 }
10833
10834 assert_eq!(
10835 IdempotencyKey::from(uuid::Uuid::nil()).as_str(),
10836 "00000000-0000-0000-0000-000000000000"
10837 );
10838 }
10839
10840 #[cfg(feature = "schemars")]
10841 #[test]
10842 fn idempotency_key_schema_is_a_strict_bounded_string() {
10843 use serde_json::json;
10844
10845 let key = serde_json::to_value(schemars::schema_for!(IdempotencyKey)).unwrap();
10846 assert_eq!(key["type"], "string");
10847 assert_eq!(key["minLength"], 1);
10848 assert_eq!(key["maxLength"], json!(IdempotencyKey::MAX_LENGTH));
10849
10850 let request = serde_json::to_value(schemars::schema_for!(PromptRequest)).unwrap();
10851 assert_eq!(request["required"], json!(["sessionId", "prompt"]));
10852 let property = &request["properties"]["idempotencyKey"];
10853 assert_eq!(
10854 property["anyOf"],
10855 json!([{"$ref": "#/$defs/IdempotencyKey"}, {"type": "null"}])
10856 );
10857 assert!(property.get("x-deserialize-default-on-error").is_none());
10860 }
10861
10862 fn assert_session_setup_lists_are_strict<T>(base: &serde_json::Value)
10863 where
10864 T: serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
10865 {
10866 let name = std::any::type_name::<T>();
10867 let with = |field: &str, value: serde_json::Value| {
10868 let mut request = base.clone();
10869 request[field] = value;
10870 serde_json::from_value::<T>(request)
10871 };
10872
10873 for (field, value) in [
10874 (
10876 "mcpServers",
10877 json!([
10878 {"type": "stdio", "name": "github", "command": "/usr/bin/gh-mcp", "env": [{"name": "GITHUB_TOKEN", "value": null}]},
10879 {"type": "stdio", "name": "fs", "command": "/usr/bin/fs-mcp"}
10880 ]),
10881 ),
10882 ("mcpServers", json!({"type": "stdio", "name": "fs"})),
10883 ("additionalDirectories", json!(["/repo/lib", 42])),
10884 ("additionalDirectories", json!("/repo/lib")),
10885 ] {
10886 assert!(
10887 with(field, value.clone()).is_err(),
10888 "{name}.{field}: {value}"
10889 );
10890 }
10891
10892 let empty = serde_json::from_value::<T>(base.clone()).unwrap();
10893 for field in ["mcpServers", "additionalDirectories"] {
10894 assert_eq!(
10895 with(field, serde_json::Value::Null).unwrap(),
10896 empty,
10897 "{name}.{field}"
10898 );
10899 }
10900 }
10901
10902 #[test]
10903 fn session_setup_requests_reject_malformed_mcp_servers_and_directories() {
10904 assert_session_setup_lists_are_strict::<NewSessionRequest>(&json!({"cwd": "/repo"}));
10905 assert_session_setup_lists_are_strict::<ResumeSessionRequest>(&json!({
10906 "sessionId": "sess-1",
10907 "cwd": "/repo"
10908 }));
10909 #[cfg(feature = "unstable_session_fork")]
10910 assert_session_setup_lists_are_strict::<ForkSessionRequest>(&json!({
10911 "sessionId": "sess-1",
10912 "cwd": "/repo"
10913 }));
10914 }
10915
10916 #[test]
10917 fn resume_session_request_rejects_malformed_replay_from() {
10918 let request = |replay_from: serde_json::Value| {
10919 serde_json::from_value::<ResumeSessionRequest>(json!({
10920 "sessionId": "sess-1",
10921 "cwd": "/repo",
10922 "replayFrom": replay_from
10923 }))
10924 };
10925
10926 assert!(request(json!("start")).is_err());
10928 assert_eq!(request(serde_json::Value::Null).unwrap().replay_from, None);
10929 assert!(matches!(
10930 request(json!({"type": "start"})).unwrap().replay_from,
10931 Some(ReplayFrom::Start(_))
10932 ));
10933 }
10934
10935 #[test]
10936 fn mcp_server_lists_treat_null_as_empty() {
10937 let servers: Vec<McpServer> = serde_json::from_value(json!([
10938 {"type": "stdio", "name": "fs", "command": "/usr/bin/fs-mcp", "args": null, "env": null},
10939 {"type": "http", "name": "api", "url": "https://example.com/mcp", "headers": null}
10940 ]))
10941 .unwrap();
10942
10943 assert_eq!(
10944 servers,
10945 vec![
10946 McpServer::Stdio(McpServerStdio::new("fs", "/usr/bin/fs-mcp")),
10947 McpServer::Http(McpServerHttp::new("api", "https://example.com/mcp")),
10948 ]
10949 );
10950 }
10951
10952 #[test]
10953 fn terminal_auth_methods_reject_malformed_launch_config() {
10954 let response: InitializeResponse = serde_json::from_value(json!({
10958 "protocolVersion": 2,
10959 "info": {"name": "agent", "version": "1.0.0"},
10960 "authMethods": [
10961 {"type": "terminal", "methodId": "bad-args", "name": "Log in", "args": ["auth", "--port", 8123]},
10962 {"type": "terminal", "methodId": "bad-env", "name": "Log in", "env": [{"name": "DEBUG", "value": 1}]},
10963 {"type": "terminal", "methodId": "null-config", "name": "Log in", "args": null, "env": null},
10964 {"type": "agent", "methodId": "agent", "name": "Agent login"}
10965 ]
10966 }))
10967 .unwrap();
10968
10969 assert_eq!(
10970 response.auth_methods,
10971 vec![
10972 AuthMethod::Terminal(AuthMethodTerminal::new("null-config", "Log in")),
10973 AuthMethod::Agent(AuthMethodAgent::new("agent", "Agent login")),
10974 ]
10975 );
10976 }
10977
10978 #[cfg(feature = "unstable_auth_status")]
10979 #[test]
10980 fn auth_status_response_round_trips() {
10981 let response = AuthStatusResponse::new(AuthState::Authenticated).accounts(vec![
10982 AuthAccount::new("Anthropic API key")
10983 .description("API key helper".to_string())
10984 .active(true),
10985 AuthAccount::new("Claude Max").email("user@example.com".to_string()),
10986 ]);
10987 let json = serde_json::to_value(&response).unwrap();
10988 assert_eq!(
10989 json,
10990 json!({
10991 "state": "authenticated",
10992 "accounts": [
10993 {
10994 "label": "Anthropic API key",
10995 "description": "API key helper",
10996 "active": true
10997 },
10998 {
10999 "label": "Claude Max",
11000 "email": "user@example.com"
11001 }
11002 ]
11003 })
11004 );
11005 assert_eq!(
11006 serde_json::from_value::<AuthStatusResponse>(json).unwrap(),
11007 response
11008 );
11009 assert_eq!(
11010 serde_json::to_value(AuthStatusResponse::new(AuthState::NotRequired)).unwrap(),
11011 json!({"state": "not_required"})
11012 );
11013 }
11014
11015 #[cfg(feature = "unstable_auth_status")]
11016 #[test]
11017 fn auth_status_state_is_strict_and_accounts_are_lenient() {
11018 assert!(serde_json::from_value::<AuthStatusResponse>(json!({})).is_err());
11019 assert!(serde_json::from_value::<AuthStatusResponse>(json!({"state": null})).is_err());
11020 assert!(serde_json::from_value::<AuthStatusResponse>(json!({"state": 1})).is_err());
11021
11022 let response: AuthStatusResponse = serde_json::from_value(json!({
11023 "state": "_vendor_state",
11024 "accounts": [
11025 {"active": true},
11026 {
11027 "label": "Vertex AI",
11028 "description": 42,
11029 "active": "yes",
11030 "email": ["not", "a", "string"]
11031 }
11032 ]
11033 }))
11034 .unwrap();
11035 assert_eq!(
11036 response,
11037 AuthStatusResponse::new(AuthState::Other("_vendor_state".to_string()))
11038 .accounts(vec![AuthAccount::new("Vertex AI")])
11039 );
11040 assert_eq!(
11041 serde_json::from_value::<AuthStatusResponse>(
11042 json!({"state": "unknown", "accounts": null})
11043 )
11044 .unwrap(),
11045 AuthStatusResponse::new(AuthState::Unknown)
11046 );
11047 }
11048
11049 #[cfg(feature = "unstable_auth_status")]
11050 #[test]
11051 fn auth_status_update_notification_routes() {
11052 use crate::v2::{AgentNotification, CLIENT_METHOD_NAMES};
11053
11054 assert_eq!(AGENT_METHOD_NAMES.auth_status, "auth/status");
11055 assert_eq!(CLIENT_METHOD_NAMES.auth_status_update, "auth/status_update");
11056 let notification = AgentNotification::AuthStatusUpdateNotification(Box::new(
11057 AuthStatusUpdateNotification::new(AuthState::Unauthenticated),
11058 ));
11059 assert_eq!(notification.method(), "auth/status_update");
11060 assert_eq!(
11061 serde_json::to_value(¬ification).unwrap(),
11062 json!({"state": "unauthenticated"})
11063 );
11064 }
11065
11066 #[cfg(all(
11067 feature = "unstable_session_fork",
11068 feature = "unstable_session_cursors"
11069 ))]
11070 #[test]
11071 fn fork_session_request_cursor_id_is_optional_and_strict() {
11072 let request = ForkSessionRequest::new("sess_abc123", "/home/user/project")
11073 .cursor_id(CursorId::new("cur_1"));
11074 let wire = json!({
11075 "sessionId": "sess_abc123",
11076 "cursorId": "cur_1",
11077 "cwd": "/home/user/project"
11078 });
11079 assert_eq!(serde_json::to_value(&request).unwrap(), wire);
11080 assert_eq!(
11081 serde_json::from_value::<ForkSessionRequest>(wire).unwrap(),
11082 request
11083 );
11084
11085 for wire in [
11087 json!({ "sessionId": "sess_abc123", "cwd": "/home/user/project" }),
11088 json!({ "sessionId": "sess_abc123", "cwd": "/home/user/project", "cursorId": null }),
11089 ] {
11090 assert_eq!(
11091 serde_json::from_value::<ForkSessionRequest>(wire)
11092 .unwrap()
11093 .cursor_id,
11094 None
11095 );
11096 }
11097
11098 assert!(
11100 serde_json::from_value::<ForkSessionRequest>(json!({
11101 "sessionId": "sess_abc123",
11102 "cwd": "/home/user/project",
11103 "cursorId": 7
11104 }))
11105 .is_err()
11106 );
11107 }
11108}