1use std::{borrow::Cow, collections::BTreeMap, sync::Arc};
7
8#[cfg(feature = "unstable_llm_providers")]
9use std::collections::HashMap;
10
11use derive_more::{Display, From};
12#[cfg(feature = "schemars")]
13use schemars::Schema;
14use serde::{Deserialize, Serialize};
15use serde_with::{DefaultOnError, DefaultOnNull, VecSkipError, serde_as, skip_serializing_none};
16
17use super::{
18 AbsolutePath, AvailableCommand, ClientCapabilities, ContentBlock, Error, ExtNotification,
19 ExtRequest, ExtResponse, MessageId, Meta, SessionId, TerminalId, ToolCallId,
20};
21use crate::{IntoOption, ProtocolVersion};
22
23#[cfg(feature = "unstable_session_status")]
24use super::StateUpdate;
25
26#[cfg(all(feature = "unstable_auth_status", feature = "schemars"))]
27use super::AUTH_STATUS_UPDATE_NOTIFICATION;
28#[cfg(feature = "unstable_mcp_over_acp")]
29use super::mcp::{MCP_MESSAGE_METHOD_NAME, MessageMcpNotification};
30
31#[serde_as]
39#[skip_serializing_none]
40#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
41#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
42#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = INITIALIZE_METHOD_NAME)))]
43#[serde(rename_all = "camelCase")]
44#[non_exhaustive]
45pub struct InitializeRequest {
46 pub protocol_version: ProtocolVersion,
48 pub info: Implementation,
50 #[serde_as(deserialize_as = "DefaultOnError")]
52 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
53 #[serde(default)]
54 pub capabilities: ClientCapabilities,
55 #[serde_as(deserialize_as = "DefaultOnError")]
61 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
62 #[serde(default)]
63 #[serde(rename = "_meta")]
64 pub meta: Option<Meta>,
65}
66
67impl InitializeRequest {
68 #[must_use]
70 pub fn new(protocol_version: ProtocolVersion, info: Implementation) -> Self {
71 Self {
72 protocol_version,
73 capabilities: ClientCapabilities::default(),
74 info,
75 meta: None,
76 }
77 }
78
79 #[must_use]
81 pub fn capabilities(mut self, capabilities: ClientCapabilities) -> Self {
82 self.capabilities = capabilities;
83 self
84 }
85
86 #[must_use]
92 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
93 self.meta = meta.into_option();
94 self
95 }
96}
97
98#[serde_as]
104#[skip_serializing_none]
105#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
106#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
107#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = INITIALIZE_METHOD_NAME)))]
108#[serde(rename_all = "camelCase")]
109#[non_exhaustive]
110pub struct InitializeResponse {
111 pub protocol_version: ProtocolVersion,
118 pub info: Implementation,
120 #[serde_as(deserialize_as = "DefaultOnError")]
122 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
123 #[serde(default)]
124 pub capabilities: AgentCapabilities,
125 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
131 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
132 #[serde(default, skip_serializing_if = "Vec::is_empty")]
133 pub auth_methods: Vec<AuthMethod>,
134 #[serde_as(deserialize_as = "DefaultOnError")]
140 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
141 #[serde(default)]
142 #[serde(rename = "_meta")]
143 pub meta: Option<Meta>,
144}
145
146impl InitializeResponse {
147 #[must_use]
149 pub fn new(protocol_version: ProtocolVersion, info: Implementation) -> Self {
150 Self {
151 protocol_version,
152 capabilities: AgentCapabilities::default(),
153 auth_methods: vec![],
154 info,
155 meta: None,
156 }
157 }
158
159 #[must_use]
161 pub fn capabilities(mut self, capabilities: AgentCapabilities) -> Self {
162 self.capabilities = capabilities;
163 self
164 }
165
166 #[must_use]
171 pub fn auth_methods(mut self, auth_methods: Vec<AuthMethod>) -> Self {
172 self.auth_methods = auth_methods;
173 self
174 }
175
176 #[must_use]
182 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
183 self.meta = meta.into_option();
184 self
185 }
186}
187
188#[serde_as]
192#[skip_serializing_none]
193#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
194#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
195#[serde(rename_all = "camelCase")]
196#[non_exhaustive]
197pub struct Implementation {
198 pub name: String,
201 #[serde_as(deserialize_as = "DefaultOnError")]
208 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
209 #[serde(default)]
210 pub title: Option<String>,
211 pub version: String,
214 #[serde_as(deserialize_as = "DefaultOnError")]
220 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
221 #[serde(default)]
222 #[serde(rename = "_meta")]
223 pub meta: Option<Meta>,
224}
225
226impl Implementation {
227 #[must_use]
229 pub fn new(name: impl Into<String>, version: impl Into<String>) -> Self {
230 Self {
231 name: name.into(),
232 title: None,
233 version: version.into(),
234 meta: None,
235 }
236 }
237
238 #[must_use]
243 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
244 self.title = title.into_option();
245 self
246 }
247
248 #[must_use]
254 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
255 self.meta = meta.into_option();
256 self
257 }
258}
259
260#[serde_as]
270#[skip_serializing_none]
271#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
272#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
273#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGIN_METHOD_NAME)))]
274#[serde(rename_all = "camelCase")]
275#[non_exhaustive]
276pub struct LoginAuthRequest {
277 pub method_id: AuthMethodId,
280 #[serde_as(deserialize_as = "DefaultOnError")]
286 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
287 #[serde(default)]
288 #[serde(rename = "_meta")]
289 pub meta: Option<Meta>,
290}
291
292impl LoginAuthRequest {
293 #[must_use]
295 pub fn new(method_id: impl Into<AuthMethodId>) -> Self {
296 Self {
297 method_id: method_id.into(),
298 meta: None,
299 }
300 }
301
302 #[must_use]
308 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
309 self.meta = meta.into_option();
310 self
311 }
312}
313
314crate::serde_util::default_on_null! {
315 #[serde_as]
317 #[skip_serializing_none]
318 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
319 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
320 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGIN_METHOD_NAME)))]
321 #[serde(rename_all = "camelCase")]
322 #[non_exhaustive]
323 pub struct LoginAuthResponse {
324 #[serde_as(deserialize_as = "DefaultOnError")]
330 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
331 #[serde(default)]
332 #[serde(rename = "_meta")]
333 pub meta: Option<Meta>,
334 }
335}
336
337impl LoginAuthResponse {
338 #[must_use]
340 pub fn new() -> Self {
341 Self::default()
342 }
343
344 #[must_use]
350 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
351 self.meta = meta.into_option();
352 self
353 }
354}
355
356crate::serde_util::default_on_null! {
359 #[serde_as]
367 #[skip_serializing_none]
368 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
369 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
370 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGOUT_METHOD_NAME)))]
371 #[serde(rename_all = "camelCase")]
372 #[non_exhaustive]
373 pub struct LogoutAuthRequest {
374 #[serde_as(deserialize_as = "DefaultOnError")]
380 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
381 #[serde(default)]
382 #[serde(rename = "_meta")]
383 pub meta: Option<Meta>,
384 }
385}
386
387impl LogoutAuthRequest {
388 #[must_use]
390 pub fn new() -> Self {
391 Self::default()
392 }
393
394 #[must_use]
400 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
401 self.meta = meta.into_option();
402 self
403 }
404}
405
406crate::serde_util::default_on_null! {
407 #[serde_as]
409 #[skip_serializing_none]
410 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
411 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
412 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGOUT_METHOD_NAME)))]
413 #[serde(rename_all = "camelCase")]
414 #[non_exhaustive]
415 pub struct LogoutAuthResponse {
416 #[serde_as(deserialize_as = "DefaultOnError")]
422 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
423 #[serde(default)]
424 #[serde(rename = "_meta")]
425 pub meta: Option<Meta>,
426 }
427}
428
429impl LogoutAuthResponse {
430 #[must_use]
432 pub fn new() -> Self {
433 Self::default()
434 }
435
436 #[must_use]
442 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
443 self.meta = meta.into_option();
444 self
445 }
446}
447
448#[cfg(feature = "unstable_auth_status")]
451crate::serde_util::default_on_null! {
452 #[serde_as]
463 #[skip_serializing_none]
464 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
465 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
466 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_STATUS_METHOD_NAME)))]
467 #[serde(rename_all = "camelCase")]
468 #[non_exhaustive]
469 pub struct AuthStatusRequest {
470 #[serde_as(deserialize_as = "DefaultOnError")]
476 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
477 #[serde(default)]
478 #[serde(rename = "_meta")]
479 pub meta: Option<Meta>,
480 }
481}
482
483#[cfg(feature = "unstable_auth_status")]
484impl AuthStatusRequest {
485 #[must_use]
487 pub fn new() -> Self {
488 Self::default()
489 }
490
491 #[must_use]
497 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
498 self.meta = meta.into_option();
499 self
500 }
501}
502
503#[cfg(feature = "unstable_auth_status")]
509#[serde_as]
510#[skip_serializing_none]
511#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
512#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
513#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_STATUS_METHOD_NAME)))]
514#[serde(rename_all = "camelCase")]
515#[non_exhaustive]
516pub struct AuthStatusResponse {
517 pub state: AuthState,
522 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
528 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
529 #[serde(default, skip_serializing_if = "Vec::is_empty")]
530 pub accounts: Vec<AuthAccount>,
531 #[serde_as(deserialize_as = "DefaultOnError")]
537 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
538 #[serde(default)]
539 #[serde(rename = "_meta")]
540 pub meta: Option<Meta>,
541}
542
543#[cfg(feature = "unstable_auth_status")]
544impl AuthStatusResponse {
545 #[must_use]
547 pub fn new(state: AuthState) -> Self {
548 Self {
549 state,
550 accounts: vec![],
551 meta: None,
552 }
553 }
554
555 #[must_use]
557 pub fn accounts(mut self, accounts: Vec<AuthAccount>) -> Self {
558 self.accounts = accounts;
559 self
560 }
561
562 #[must_use]
568 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
569 self.meta = meta.into_option();
570 self
571 }
572}
573
574#[cfg(feature = "unstable_auth_status")]
584#[serde_as]
585#[skip_serializing_none]
586#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
587#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
588#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = AUTH_STATUS_UPDATE_NOTIFICATION)))]
589#[serde(rename_all = "camelCase")]
590#[non_exhaustive]
591pub struct AuthStatusUpdateNotification {
592 pub state: AuthState,
597 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
603 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
604 #[serde(default, skip_serializing_if = "Vec::is_empty")]
605 pub accounts: Vec<AuthAccount>,
606 #[serde_as(deserialize_as = "DefaultOnError")]
612 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
613 #[serde(default)]
614 #[serde(rename = "_meta")]
615 pub meta: Option<Meta>,
616}
617
618#[cfg(feature = "unstable_auth_status")]
619impl AuthStatusUpdateNotification {
620 #[must_use]
622 pub fn new(state: AuthState) -> Self {
623 Self {
624 state,
625 accounts: vec![],
626 meta: None,
627 }
628 }
629
630 #[must_use]
632 pub fn accounts(mut self, accounts: Vec<AuthAccount>) -> Self {
633 self.accounts = accounts;
634 self
635 }
636
637 #[must_use]
643 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
644 self.meta = meta.into_option();
645 self
646 }
647}
648
649#[cfg(feature = "unstable_auth_status")]
655#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
656#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
657#[serde(rename_all = "snake_case")]
658#[non_exhaustive]
659pub enum AuthState {
660 Authenticated,
662 Unauthenticated,
665 NotRequired,
667 Unknown,
669 #[serde(untagged)]
675 Other(String),
676}
677
678#[cfg(feature = "unstable_auth_status")]
689#[serde_as]
690#[skip_serializing_none]
691#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
692#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
693#[serde(rename_all = "camelCase")]
694#[non_exhaustive]
695pub struct AuthAccount {
696 pub label: String,
699 #[serde_as(deserialize_as = "DefaultOnError")]
704 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
705 #[serde(default)]
706 pub description: Option<String>,
707 #[serde_as(deserialize_as = "DefaultOnError")]
713 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
714 #[serde(default)]
715 pub active: Option<bool>,
716 #[serde_as(deserialize_as = "DefaultOnError")]
720 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
721 #[serde(default)]
722 pub name: Option<String>,
723 #[serde_as(deserialize_as = "DefaultOnError")]
727 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
728 #[serde(default)]
729 pub email: Option<String>,
730 #[serde_as(deserialize_as = "DefaultOnError")]
734 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
735 #[serde(default)]
736 pub organization: Option<String>,
737 #[serde_as(deserialize_as = "DefaultOnError")]
743 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
744 #[serde(default)]
745 #[serde(rename = "_meta")]
746 pub meta: Option<Meta>,
747}
748
749#[cfg(feature = "unstable_auth_status")]
750impl AuthAccount {
751 #[must_use]
753 pub fn new(label: impl Into<String>) -> Self {
754 Self {
755 label: label.into(),
756 description: None,
757 active: None,
758 name: None,
759 email: None,
760 organization: None,
761 meta: None,
762 }
763 }
764
765 #[must_use]
767 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
768 self.description = description.into_option();
769 self
770 }
771
772 #[must_use]
774 pub fn active(mut self, active: impl IntoOption<bool>) -> Self {
775 self.active = active.into_option();
776 self
777 }
778
779 #[must_use]
781 pub fn name(mut self, name: impl IntoOption<String>) -> Self {
782 self.name = name.into_option();
783 self
784 }
785
786 #[must_use]
788 pub fn email(mut self, email: impl IntoOption<String>) -> Self {
789 self.email = email.into_option();
790 self
791 }
792
793 #[must_use]
795 pub fn organization(mut self, organization: impl IntoOption<String>) -> Self {
796 self.organization = organization.into_option();
797 self
798 }
799
800 #[must_use]
806 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
807 self.meta = meta.into_option();
808 self
809 }
810}
811
812#[cfg(feature = "unstable_auth_status")]
820#[serde_as]
821#[skip_serializing_none]
822#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
823#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
824#[non_exhaustive]
825pub struct AuthStatusCapabilities {
826 #[serde_as(deserialize_as = "DefaultOnError")]
832 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
833 #[serde(default)]
834 #[serde(rename = "_meta")]
835 pub meta: Option<Meta>,
836}
837
838#[cfg(feature = "unstable_auth_status")]
839impl AuthStatusCapabilities {
840 #[must_use]
842 pub fn new() -> Self {
843 Self::default()
844 }
845
846 #[must_use]
852 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
853 self.meta = meta.into_option();
854 self
855 }
856}
857
858#[serde_as]
864#[skip_serializing_none]
865#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
866#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
867#[serde(rename_all = "camelCase")]
868#[non_exhaustive]
869pub struct AgentAuthCapabilities {
870 #[cfg(feature = "unstable_auth_status")]
879 #[serde_as(deserialize_as = "DefaultOnError")]
880 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
881 #[serde(default)]
882 pub status: Option<AuthStatusCapabilities>,
883 #[serde_as(deserialize_as = "DefaultOnError")]
889 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
890 #[serde(default)]
891 #[serde(rename = "_meta")]
892 pub meta: Option<Meta>,
893}
894
895impl AgentAuthCapabilities {
896 #[must_use]
898 pub fn new() -> Self {
899 Self::default()
900 }
901
902 #[cfg(feature = "unstable_auth_status")]
908 #[must_use]
909 pub fn status(mut self, status: impl IntoOption<AuthStatusCapabilities>) -> Self {
910 self.status = status.into_option();
911 self
912 }
913
914 #[must_use]
920 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
921 self.meta = meta.into_option();
922 self
923 }
924}
925
926#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
928#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
929#[serde(transparent)]
930#[from(forward)]
931#[non_exhaustive]
932pub struct AuthMethodId(pub Arc<str>);
933
934impl AuthMethodId {
935 #[must_use]
937 pub fn new(id: impl Into<Self>) -> Self {
938 id.into()
939 }
940}
941
942#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
946#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
947#[serde(tag = "type", rename_all = "snake_case")]
948#[non_exhaustive]
949pub enum AuthMethod {
950 Terminal(AuthMethodTerminal),
953 Agent(AuthMethodAgent),
957 #[serde(untagged)]
967 Other(OtherAuthMethod),
968}
969
970impl AuthMethod {
971 #[must_use]
973 pub fn method_id(&self) -> &AuthMethodId {
974 match self {
975 Self::Agent(a) => &a.method_id,
976 Self::Other(a) => &a.method_id,
977 Self::Terminal(t) => &t.method_id,
978 }
979 }
980
981 #[must_use]
983 pub fn name(&self) -> &str {
984 match self {
985 Self::Agent(a) => &a.name,
986 Self::Other(a) => &a.name,
987 Self::Terminal(t) => &t.name,
988 }
989 }
990
991 #[must_use]
993 pub fn description(&self) -> Option<&str> {
994 match self {
995 Self::Agent(a) => a.description.as_deref(),
996 Self::Other(a) => a
997 .fields
998 .get("description")
999 .and_then(serde_json::Value::as_str),
1000 Self::Terminal(t) => t.description.as_deref(),
1001 }
1002 }
1003
1004 #[must_use]
1010 pub fn meta(&self) -> Option<&Meta> {
1011 match self {
1012 Self::Agent(a) => a.meta.as_ref(),
1013 Self::Other(a) => a.fields.get("_meta").and_then(serde_json::Value::as_object),
1014 Self::Terminal(t) => t.meta.as_ref(),
1015 }
1016 }
1017}
1018
1019#[serde_as]
1021#[skip_serializing_none]
1022#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1023#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1024#[cfg_attr(feature = "schemars", schemars(inline))]
1025#[cfg_attr(feature = "schemars", schemars(transform = other_auth_method_schema))]
1026#[serde(rename_all = "camelCase")]
1027#[non_exhaustive]
1028pub struct OtherAuthMethod {
1029 #[serde(rename = "type")]
1035 pub type_: String,
1036 pub method_id: AuthMethodId,
1038 pub name: String,
1040 #[serde(flatten)]
1043 pub fields: BTreeMap<String, serde_json::Value>,
1044}
1045
1046impl OtherAuthMethod {
1047 #[must_use]
1049 pub fn new(
1050 type_: impl Into<String>,
1051 method_id: impl Into<AuthMethodId>,
1052 name: impl Into<String>,
1053 mut fields: BTreeMap<String, serde_json::Value>,
1054 ) -> Self {
1055 fields.remove("type");
1056 fields.remove("methodId");
1057 fields.remove("name");
1058 Self {
1059 type_: type_.into(),
1060 method_id: method_id.into(),
1061 name: name.into(),
1062 fields,
1063 }
1064 }
1065}
1066
1067impl<'de> Deserialize<'de> for OtherAuthMethod {
1068 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1069 where
1070 D: serde::Deserializer<'de>,
1071 {
1072 #[derive(Deserialize)]
1073 #[serde(rename_all = "camelCase")]
1074 struct RawOtherAuthMethod {
1075 #[serde(rename = "type")]
1076 type_: String,
1077 method_id: AuthMethodId,
1078 name: String,
1079 #[serde(flatten)]
1080 fields: BTreeMap<String, serde_json::Value>,
1081 }
1082
1083 let raw = RawOtherAuthMethod::deserialize(deserializer)?;
1084 if is_known_auth_method_type(&raw.type_) {
1085 return Err(serde::de::Error::custom(format!(
1086 "known authentication method `{}` did not match its schema",
1087 raw.type_
1088 )));
1089 }
1090
1091 Ok(Self {
1092 type_: raw.type_,
1093 method_id: raw.method_id,
1094 name: raw.name,
1095 fields: raw.fields,
1096 })
1097 }
1098}
1099
1100fn is_known_auth_method_type(type_: &str) -> bool {
1101 matches!(type_, "agent" | "terminal")
1102}
1103
1104#[cfg(feature = "schemars")]
1105fn other_auth_method_schema(schema: &mut Schema) {
1106 super::schema_util::reject_known_string_discriminators(schema, "type", &["agent", "terminal"]);
1107}
1108
1109#[serde_as]
1113#[skip_serializing_none]
1114#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1115#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1116#[serde(rename_all = "camelCase")]
1117#[non_exhaustive]
1118pub struct AuthMethodAgent {
1119 pub method_id: AuthMethodId,
1121 pub name: String,
1123 #[serde_as(deserialize_as = "DefaultOnError")]
1127 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1128 #[serde(default)]
1129 pub description: Option<String>,
1130 #[serde_as(deserialize_as = "DefaultOnError")]
1136 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1137 #[serde(default)]
1138 #[serde(rename = "_meta")]
1139 pub meta: Option<Meta>,
1140}
1141
1142impl AuthMethodAgent {
1143 #[must_use]
1145 pub fn new(method_id: impl Into<AuthMethodId>, name: impl Into<String>) -> Self {
1146 Self {
1147 method_id: method_id.into(),
1148 name: name.into(),
1149 description: None,
1150 meta: None,
1151 }
1152 }
1153
1154 #[must_use]
1156 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
1157 self.description = description.into_option();
1158 self
1159 }
1160
1161 #[must_use]
1167 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1168 self.meta = meta.into_option();
1169 self
1170 }
1171}
1172
1173#[serde_as]
1181#[skip_serializing_none]
1182#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1183#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1184#[serde(rename_all = "camelCase")]
1185#[non_exhaustive]
1186pub struct AuthMethodTerminal {
1187 pub method_id: AuthMethodId,
1189 pub name: String,
1191 #[serde_as(deserialize_as = "DefaultOnError")]
1195 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1196 #[serde(default)]
1197 pub description: Option<String>,
1198 #[serde_as(deserialize_as = "DefaultOnNull")]
1200 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1201 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1202 pub args: Vec<String>,
1203 #[serde_as(deserialize_as = "DefaultOnNull")]
1207 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1208 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1209 pub env: Vec<EnvVariable>,
1210 #[serde_as(deserialize_as = "DefaultOnError")]
1216 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1217 #[serde(default)]
1218 #[serde(rename = "_meta")]
1219 pub meta: Option<Meta>,
1220}
1221
1222impl AuthMethodTerminal {
1223 #[must_use]
1225 pub fn new(method_id: impl Into<AuthMethodId>, name: impl Into<String>) -> Self {
1226 Self {
1227 method_id: method_id.into(),
1228 name: name.into(),
1229 description: None,
1230 args: Vec::new(),
1231 env: Vec::new(),
1232 meta: None,
1233 }
1234 }
1235
1236 #[must_use]
1238 pub fn args(mut self, args: Vec<String>) -> Self {
1239 self.args = args;
1240 self
1241 }
1242
1243 #[must_use]
1247 pub fn env(mut self, env: Vec<EnvVariable>) -> Self {
1248 self.env = env;
1249 self
1250 }
1251
1252 #[must_use]
1254 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
1255 self.description = description.into_option();
1256 self
1257 }
1258
1259 #[must_use]
1265 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1266 self.meta = meta.into_option();
1267 self
1268 }
1269}
1270
1271#[serde_as]
1277#[skip_serializing_none]
1278#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1279#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1280#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_NEW_METHOD_NAME)))]
1281#[serde(rename_all = "camelCase")]
1282#[non_exhaustive]
1283pub struct NewSessionRequest {
1284 pub cwd: AbsolutePath,
1286 #[serde_as(deserialize_as = "DefaultOnNull")]
1292 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1293 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1294 pub additional_directories: Vec<AbsolutePath>,
1295 #[serde_as(deserialize_as = "DefaultOnNull")]
1297 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1298 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1299 pub mcp_servers: Vec<McpServer>,
1300 #[serde(default)]
1306 pub system_prompt: Option<SystemPrompt>,
1307 #[cfg(feature = "unstable_session_options")]
1323 #[serde_as(deserialize_as = "DefaultOnNull")]
1324 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1325 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1326 pub config_options: Vec<InitialSessionConfigOption>,
1327 #[serde_as(deserialize_as = "DefaultOnError")]
1333 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1334 #[serde(default)]
1335 #[serde(rename = "_meta")]
1336 pub meta: Option<Meta>,
1337}
1338
1339impl NewSessionRequest {
1340 #[must_use]
1342 pub fn new(cwd: impl Into<AbsolutePath>) -> Self {
1343 Self {
1344 cwd: cwd.into(),
1345 additional_directories: vec![],
1346 mcp_servers: vec![],
1347 system_prompt: None,
1348 #[cfg(feature = "unstable_session_options")]
1349 config_options: vec![],
1350 meta: None,
1351 }
1352 }
1353
1354 #[must_use]
1356 pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1357 where
1358 I: IntoIterator<Item = P>,
1359 P: Into<AbsolutePath>,
1360 {
1361 self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1362 self
1363 }
1364
1365 #[must_use]
1367 pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1368 self.mcp_servers = mcp_servers;
1369 self
1370 }
1371
1372 #[must_use]
1374 pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1375 self.system_prompt = system_prompt.into_option();
1376 self
1377 }
1378
1379 #[cfg(feature = "unstable_session_options")]
1395 #[must_use]
1396 pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1397 self.config_options = config_options;
1398 self
1399 }
1400
1401 #[must_use]
1407 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1408 self.meta = meta.into_option();
1409 self
1410 }
1411}
1412
1413#[serde_as]
1421#[skip_serializing_none]
1422#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1423#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1424#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_NEW_METHOD_NAME)))]
1425#[serde(rename_all = "camelCase")]
1426#[non_exhaustive]
1427pub struct NewSessionResponse {
1428 pub session_id: SessionId,
1432 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1438 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1439 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1440 pub config_options: Vec<SessionConfigOption>,
1441 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1447 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1448 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1449 pub available_commands: Vec<AvailableCommand>,
1450 #[serde_as(deserialize_as = "DefaultOnError")]
1456 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1457 #[serde(default)]
1458 #[serde(rename = "_meta")]
1459 pub meta: Option<Meta>,
1460}
1461
1462impl NewSessionResponse {
1463 #[must_use]
1465 pub fn new(session_id: impl Into<SessionId>) -> Self {
1466 Self {
1467 session_id: session_id.into(),
1468 config_options: Vec::new(),
1469 available_commands: Vec::new(),
1470 meta: None,
1471 }
1472 }
1473
1474 #[must_use]
1480 pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
1481 self.config_options = config_options;
1482 self
1483 }
1484
1485 #[must_use]
1487 pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
1488 self.available_commands = available_commands;
1489 self
1490 }
1491
1492 #[must_use]
1498 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1499 self.meta = meta.into_option();
1500 self
1501 }
1502}
1503
1504#[cfg(feature = "unstable_session_fork")]
1517#[serde_as]
1518#[skip_serializing_none]
1519#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1520#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1521#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_FORK_METHOD_NAME)))]
1522#[serde(rename_all = "camelCase")]
1523#[non_exhaustive]
1524pub struct ForkSessionRequest {
1525 pub session_id: SessionId,
1527 pub cwd: AbsolutePath,
1529 #[serde_as(deserialize_as = "DefaultOnNull")]
1535 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1536 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1537 pub additional_directories: Vec<AbsolutePath>,
1538 #[serde_as(deserialize_as = "DefaultOnNull")]
1540 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1541 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1542 pub mcp_servers: Vec<McpServer>,
1543 #[serde(default)]
1551 pub system_prompt: Option<SystemPrompt>,
1552 #[serde_as(deserialize_as = "DefaultOnError")]
1558 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1559 #[serde(default)]
1560 #[serde(rename = "_meta")]
1561 pub meta: Option<Meta>,
1562}
1563
1564#[cfg(feature = "unstable_session_fork")]
1565impl ForkSessionRequest {
1566 #[must_use]
1568 pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
1569 Self {
1570 session_id: session_id.into(),
1571 cwd: cwd.into(),
1572 additional_directories: vec![],
1573 mcp_servers: vec![],
1574 system_prompt: None,
1575 meta: None,
1576 }
1577 }
1578
1579 #[must_use]
1581 pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1582 where
1583 I: IntoIterator<Item = P>,
1584 P: Into<AbsolutePath>,
1585 {
1586 self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1587 self
1588 }
1589
1590 #[must_use]
1592 pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1593 self.mcp_servers = mcp_servers;
1594 self
1595 }
1596
1597 #[must_use]
1599 pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1600 self.system_prompt = system_prompt.into_option();
1601 self
1602 }
1603
1604 #[must_use]
1610 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1611 self.meta = meta.into_option();
1612 self
1613 }
1614}
1615
1616#[cfg(feature = "unstable_session_fork")]
1622#[serde_as]
1623#[skip_serializing_none]
1624#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1625#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1626#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_FORK_METHOD_NAME)))]
1627#[serde(rename_all = "camelCase")]
1628#[non_exhaustive]
1629pub struct ForkSessionResponse {
1630 pub session_id: SessionId,
1632 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1638 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1639 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1640 pub config_options: Vec<SessionConfigOption>,
1641 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1647 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1648 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1649 pub available_commands: Vec<AvailableCommand>,
1650 #[serde_as(deserialize_as = "DefaultOnError")]
1656 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1657 #[serde(default)]
1658 #[serde(rename = "_meta")]
1659 pub meta: Option<Meta>,
1660}
1661
1662#[cfg(feature = "unstable_session_fork")]
1663impl ForkSessionResponse {
1664 #[must_use]
1666 pub fn new(session_id: impl Into<SessionId>) -> Self {
1667 Self {
1668 session_id: session_id.into(),
1669 config_options: Vec::new(),
1670 available_commands: Vec::new(),
1671 meta: None,
1672 }
1673 }
1674
1675 #[must_use]
1681 pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
1682 self.config_options = config_options;
1683 self
1684 }
1685
1686 #[must_use]
1688 pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
1689 self.available_commands = available_commands;
1690 self
1691 }
1692
1693 #[must_use]
1699 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1700 self.meta = meta.into_option();
1701 self
1702 }
1703}
1704
1705#[serde_as]
1712#[skip_serializing_none]
1713#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1714#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1715#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_RESUME_METHOD_NAME)))]
1716#[serde(rename_all = "camelCase")]
1717#[non_exhaustive]
1718pub struct ResumeSessionRequest {
1719 pub session_id: SessionId,
1721 pub cwd: AbsolutePath,
1726 #[serde_as(deserialize_as = "DefaultOnNull")]
1733 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1734 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1735 pub additional_directories: Vec<AbsolutePath>,
1736 #[serde_as(deserialize_as = "DefaultOnNull")]
1741 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1742 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1743 pub mcp_servers: Vec<McpServer>,
1744 #[serde(default)]
1756 pub replay_from: Option<ReplayFrom>,
1757 #[serde(default)]
1765 pub system_prompt: Option<SystemPrompt>,
1766 #[cfg(feature = "unstable_session_options")]
1785 #[serde_as(deserialize_as = "DefaultOnNull")]
1786 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1787 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1788 pub config_options: Vec<InitialSessionConfigOption>,
1789 #[serde_as(deserialize_as = "DefaultOnError")]
1795 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1796 #[serde(default)]
1797 #[serde(rename = "_meta")]
1798 pub meta: Option<Meta>,
1799}
1800
1801impl ResumeSessionRequest {
1802 #[must_use]
1804 pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
1805 Self {
1806 session_id: session_id.into(),
1807 cwd: cwd.into(),
1808 additional_directories: vec![],
1809 mcp_servers: vec![],
1810 replay_from: None,
1811 system_prompt: None,
1812 #[cfg(feature = "unstable_session_options")]
1813 config_options: vec![],
1814 meta: None,
1815 }
1816 }
1817
1818 #[must_use]
1820 pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1821 where
1822 I: IntoIterator<Item = P>,
1823 P: Into<AbsolutePath>,
1824 {
1825 self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1826 self
1827 }
1828
1829 #[must_use]
1831 pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1832 self.mcp_servers = mcp_servers;
1833 self
1834 }
1835
1836 #[must_use]
1844 pub fn replay_from(mut self, replay_from: impl IntoOption<ReplayFrom>) -> Self {
1845 self.replay_from = replay_from.into_option();
1846 self
1847 }
1848
1849 #[must_use]
1851 pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1852 self.system_prompt = system_prompt.into_option();
1853 self
1854 }
1855
1856 #[cfg(feature = "unstable_session_options")]
1872 #[must_use]
1873 pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1874 self.config_options = config_options;
1875 self
1876 }
1877
1878 #[must_use]
1884 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1885 self.meta = meta.into_option();
1886 self
1887 }
1888}
1889
1890#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1894#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1895#[serde(tag = "type", rename_all = "snake_case")]
1896#[non_exhaustive]
1897pub enum ReplayFrom {
1898 Start(ReplayFromStart),
1900 #[serde(untagged)]
1911 Other(OtherReplayFrom),
1912}
1913
1914impl From<ReplayFromStart> for ReplayFrom {
1915 fn from(replay_from: ReplayFromStart) -> Self {
1916 Self::Start(replay_from)
1917 }
1918}
1919
1920#[serde_as]
1922#[skip_serializing_none]
1923#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1924#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1925#[serde(rename_all = "camelCase")]
1926#[non_exhaustive]
1927pub struct ReplayFromStart {
1928 #[serde_as(deserialize_as = "DefaultOnError")]
1934 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1935 #[serde(default)]
1936 #[serde(rename = "_meta")]
1937 pub meta: Option<Meta>,
1938}
1939
1940impl ReplayFromStart {
1941 #[must_use]
1943 pub fn new() -> Self {
1944 Self::default()
1945 }
1946
1947 #[must_use]
1953 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1954 self.meta = meta.into_option();
1955 self
1956 }
1957}
1958
1959#[serde_as]
1961#[skip_serializing_none]
1962#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1963#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1964#[cfg_attr(feature = "schemars", schemars(inline))]
1965#[cfg_attr(feature = "schemars", schemars(transform = other_replay_from_schema))]
1966#[serde(rename_all = "camelCase")]
1967#[non_exhaustive]
1968pub struct OtherReplayFrom {
1969 #[serde(rename = "type")]
1975 pub type_: String,
1976 #[serde(flatten)]
1979 pub fields: BTreeMap<String, serde_json::Value>,
1980}
1981
1982impl OtherReplayFrom {
1983 #[must_use]
1985 pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
1986 fields.remove("type");
1987 Self {
1988 type_: type_.into(),
1989 fields,
1990 }
1991 }
1992}
1993
1994impl<'de> Deserialize<'de> for OtherReplayFrom {
1995 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1996 where
1997 D: serde::Deserializer<'de>,
1998 {
1999 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
2000 let type_ = fields
2001 .remove("type")
2002 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
2003 let serde_json::Value::String(type_) = type_ else {
2004 return Err(serde::de::Error::custom("`type` must be a string"));
2005 };
2006
2007 if is_known_replay_from_type(&type_) {
2008 return Err(serde::de::Error::custom(format!(
2009 "known replay cursor `{type_}` did not match its schema"
2010 )));
2011 }
2012
2013 Ok(Self { type_, fields })
2014 }
2015}
2016
2017fn is_known_replay_from_type(type_: &str) -> bool {
2018 matches!(type_, "start")
2019}
2020
2021#[cfg(feature = "schemars")]
2022fn other_replay_from_schema(schema: &mut Schema) {
2023 super::schema_util::reject_known_string_discriminators(schema, "type", &["start"]);
2024}
2025
2026crate::serde_util::default_on_null! {
2027 #[serde_as]
2035 #[skip_serializing_none]
2036 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2037 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2038 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_RESUME_METHOD_NAME)))]
2039 #[serde(rename_all = "camelCase")]
2040 #[non_exhaustive]
2041 pub struct ResumeSessionResponse {
2042 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2048 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2049 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2050 pub config_options: Vec<SessionConfigOption>,
2051 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2057 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2058 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2059 pub available_commands: Vec<AvailableCommand>,
2060 #[serde_as(deserialize_as = "DefaultOnError")]
2066 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2067 #[serde(default)]
2068 #[serde(rename = "_meta")]
2069 pub meta: Option<Meta>,
2070 }
2071}
2072
2073impl ResumeSessionResponse {
2074 #[must_use]
2076 pub fn new() -> Self {
2077 Self::default()
2078 }
2079
2080 #[must_use]
2086 pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
2087 self.config_options = config_options;
2088 self
2089 }
2090
2091 #[must_use]
2093 pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
2094 self.available_commands = available_commands;
2095 self
2096 }
2097
2098 #[must_use]
2104 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2105 self.meta = meta.into_option();
2106 self
2107 }
2108}
2109
2110#[serde_as]
2133#[skip_serializing_none]
2134#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2135#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2136#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CLOSE_METHOD_NAME)))]
2137#[serde(rename_all = "camelCase")]
2138#[non_exhaustive]
2139pub struct CloseSessionRequest {
2140 pub session_id: SessionId,
2142 #[serde_as(deserialize_as = "DefaultOnError")]
2148 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2149 #[serde(default)]
2150 #[serde(rename = "_meta")]
2151 pub meta: Option<Meta>,
2152}
2153
2154impl CloseSessionRequest {
2155 #[must_use]
2157 pub fn new(session_id: impl Into<SessionId>) -> Self {
2158 Self {
2159 session_id: session_id.into(),
2160 meta: None,
2161 }
2162 }
2163
2164 #[must_use]
2170 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2171 self.meta = meta.into_option();
2172 self
2173 }
2174}
2175
2176crate::serde_util::default_on_null! {
2177 #[serde_as]
2179 #[skip_serializing_none]
2180 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2181 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2182 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CLOSE_METHOD_NAME)))]
2183 #[serde(rename_all = "camelCase")]
2184 #[non_exhaustive]
2185 pub struct CloseSessionResponse {
2186 #[serde_as(deserialize_as = "DefaultOnError")]
2192 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2193 #[serde(default)]
2194 #[serde(rename = "_meta")]
2195 pub meta: Option<Meta>,
2196 }
2197}
2198
2199impl CloseSessionResponse {
2200 #[must_use]
2202 pub fn new() -> Self {
2203 Self::default()
2204 }
2205
2206 #[must_use]
2212 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2213 self.meta = meta.into_option();
2214 self
2215 }
2216}
2217
2218#[cfg(feature = "unstable_session_status")]
2232#[serde_as]
2233#[skip_serializing_none]
2234#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2235#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2236#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_STATUS_METHOD_NAME)))]
2237#[serde(rename_all = "camelCase")]
2238#[non_exhaustive]
2239pub struct SessionStatusRequest {
2240 pub session_id: SessionId,
2242 #[serde_as(deserialize_as = "DefaultOnError")]
2248 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2249 #[serde(default)]
2250 #[serde(rename = "_meta")]
2251 pub meta: Option<Meta>,
2252}
2253
2254#[cfg(feature = "unstable_session_status")]
2255impl SessionStatusRequest {
2256 #[must_use]
2258 pub fn new(session_id: impl Into<SessionId>) -> Self {
2259 Self {
2260 session_id: session_id.into(),
2261 meta: None,
2262 }
2263 }
2264
2265 #[must_use]
2271 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2272 self.meta = meta.into_option();
2273 self
2274 }
2275}
2276
2277#[cfg(feature = "unstable_session_status")]
2286#[serde_as]
2287#[skip_serializing_none]
2288#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2289#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2290#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_STATUS_METHOD_NAME)))]
2291#[serde(rename_all = "camelCase")]
2292#[non_exhaustive]
2293pub struct SessionStatusResponse {
2294 pub status: SessionStatus,
2298 #[serde_as(deserialize_as = "DefaultOnError")]
2306 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2307 #[serde(default)]
2308 pub state: Option<StateUpdate>,
2309 #[serde_as(deserialize_as = "DefaultOnError")]
2315 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2316 #[serde(default)]
2317 #[serde(rename = "_meta")]
2318 pub meta: Option<Meta>,
2319}
2320
2321#[cfg(feature = "unstable_session_status")]
2322impl SessionStatusResponse {
2323 #[must_use]
2325 pub fn new(status: SessionStatus) -> Self {
2326 Self {
2327 status,
2328 state: None,
2329 meta: None,
2330 }
2331 }
2332
2333 #[must_use]
2336 pub fn state(mut self, state: impl IntoOption<StateUpdate>) -> Self {
2337 self.state = state.into_option();
2338 self
2339 }
2340
2341 #[must_use]
2347 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2348 self.meta = meta.into_option();
2349 self
2350 }
2351}
2352
2353#[cfg(feature = "unstable_session_status")]
2359#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2360#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2361#[serde(rename_all = "snake_case")]
2362#[non_exhaustive]
2363pub enum SessionStatus {
2364 Open,
2371 Saved,
2375 #[serde(untagged)]
2382 Other(String),
2383}
2384
2385#[cfg(feature = "unstable_session_options")]
2398#[serde_as]
2399#[skip_serializing_none]
2400#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2401#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2402#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_OPTIONS_METHOD_NAME)))]
2403#[serde(rename_all = "camelCase")]
2404#[non_exhaustive]
2405pub struct SessionOptionsRequest {
2406 pub cwd: AbsolutePath,
2408 #[serde_as(deserialize_as = "DefaultOnNull")]
2412 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
2413 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2414 pub additional_directories: Vec<AbsolutePath>,
2415 #[serde(default)]
2422 pub session_id: Option<SessionId>,
2423 #[serde_as(deserialize_as = "DefaultOnError")]
2429 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2430 #[serde(default)]
2431 #[serde(rename = "_meta")]
2432 pub meta: Option<Meta>,
2433}
2434
2435#[cfg(feature = "unstable_session_options")]
2436impl SessionOptionsRequest {
2437 #[must_use]
2439 pub fn new(cwd: impl Into<AbsolutePath>) -> Self {
2440 Self {
2441 cwd: cwd.into(),
2442 additional_directories: vec![],
2443 session_id: None,
2444 meta: None,
2445 }
2446 }
2447
2448 #[must_use]
2450 pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
2451 where
2452 I: IntoIterator<Item = P>,
2453 P: Into<AbsolutePath>,
2454 {
2455 self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
2456 self
2457 }
2458
2459 #[must_use]
2461 pub fn session_id(mut self, session_id: impl IntoOption<SessionId>) -> Self {
2462 self.session_id = session_id.into_option();
2463 self
2464 }
2465
2466 #[must_use]
2472 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2473 self.meta = meta.into_option();
2474 self
2475 }
2476}
2477
2478#[cfg(feature = "unstable_session_options")]
2479crate::serde_util::default_on_null! {
2480 #[serde_as]
2489 #[skip_serializing_none]
2490 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2491 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2492 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_OPTIONS_METHOD_NAME)))]
2493 #[serde(rename_all = "camelCase")]
2494 #[non_exhaustive]
2495 pub struct SessionOptionsResponse {
2496 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2502 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2503 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2504 pub config_options: Vec<SessionConfigOption>,
2505 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2514 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2515 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2516 pub available_commands: Vec<AvailableCommand>,
2517 #[serde_as(deserialize_as = "DefaultOnError")]
2523 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2524 #[serde(default)]
2525 #[serde(rename = "_meta")]
2526 pub meta: Option<Meta>,
2527 }
2528}
2529
2530#[cfg(feature = "unstable_session_options")]
2531impl SessionOptionsResponse {
2532 #[must_use]
2534 pub fn new() -> Self {
2535 Self::default()
2536 }
2537
2538 #[must_use]
2540 pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
2541 self.config_options = config_options;
2542 self
2543 }
2544
2545 #[must_use]
2547 pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
2548 self.available_commands = available_commands;
2549 self
2550 }
2551
2552 #[must_use]
2558 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2559 self.meta = meta.into_option();
2560 self
2561 }
2562}
2563
2564#[cfg(feature = "unstable_session_options")]
2574#[serde_as]
2575#[skip_serializing_none]
2576#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2577#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2578#[serde(rename_all = "camelCase")]
2579#[non_exhaustive]
2580pub struct InitialSessionConfigOption {
2581 pub config_id: SessionConfigId,
2583 #[serde(flatten)]
2588 pub value: SessionConfigOptionValue,
2589 #[serde_as(deserialize_as = "DefaultOnError")]
2595 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2596 #[serde(default)]
2597 #[serde(rename = "_meta")]
2598 pub meta: Option<Meta>,
2599}
2600
2601#[cfg(feature = "unstable_session_options")]
2602impl InitialSessionConfigOption {
2603 #[must_use]
2605 pub fn new(
2606 config_id: impl Into<SessionConfigId>,
2607 value: impl Into<SessionConfigOptionValue>,
2608 ) -> Self {
2609 Self {
2610 config_id: config_id.into(),
2611 value: value.into(),
2612 meta: None,
2613 }
2614 }
2615
2616 #[must_use]
2622 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2623 self.meta = meta.into_option();
2624 self
2625 }
2626}
2627
2628#[serde_as]
2643#[skip_serializing_none]
2644#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2645#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2646#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TOOL_CALL_CANCEL_METHOD_NAME)))]
2647#[serde(rename_all = "camelCase")]
2648#[non_exhaustive]
2649pub struct CancelToolCallRequest {
2650 pub session_id: SessionId,
2652 pub tool_call_id: ToolCallId,
2654 #[serde_as(deserialize_as = "DefaultOnError")]
2660 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2661 #[serde(default)]
2662 #[serde(rename = "_meta")]
2663 pub meta: Option<Meta>,
2664}
2665
2666impl CancelToolCallRequest {
2667 #[must_use]
2669 pub fn new(session_id: impl Into<SessionId>, tool_call_id: impl Into<ToolCallId>) -> Self {
2670 Self {
2671 session_id: session_id.into(),
2672 tool_call_id: tool_call_id.into(),
2673 meta: None,
2674 }
2675 }
2676
2677 #[must_use]
2683 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2684 self.meta = meta.into_option();
2685 self
2686 }
2687}
2688
2689crate::serde_util::default_on_null! {
2690 #[serde_as]
2692 #[skip_serializing_none]
2693 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2694 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2695 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TOOL_CALL_CANCEL_METHOD_NAME)))]
2696 #[serde(rename_all = "camelCase")]
2697 #[non_exhaustive]
2698 pub struct CancelToolCallResponse {
2699 #[serde_as(deserialize_as = "DefaultOnError")]
2705 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2706 #[serde(default)]
2707 #[serde(rename = "_meta")]
2708 pub meta: Option<Meta>,
2709 }
2710}
2711
2712impl CancelToolCallResponse {
2713 #[must_use]
2715 pub fn new() -> Self {
2716 Self::default()
2717 }
2718
2719 #[must_use]
2725 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2726 self.meta = meta.into_option();
2727 self
2728 }
2729}
2730
2731#[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" = TERMINAL_CANCEL_METHOD_NAME)))]
2751#[serde(rename_all = "camelCase")]
2752#[non_exhaustive]
2753pub struct CancelTerminalRequest {
2754 pub session_id: SessionId,
2756 pub terminal_id: TerminalId,
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 CancelTerminalRequest {
2771 #[must_use]
2773 pub fn new(session_id: impl Into<SessionId>, terminal_id: impl Into<TerminalId>) -> Self {
2774 Self {
2775 session_id: session_id.into(),
2776 terminal_id: terminal_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" = TERMINAL_CANCEL_METHOD_NAME)))]
2800 #[serde(rename_all = "camelCase")]
2801 #[non_exhaustive]
2802 pub struct CancelTerminalResponse {
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 CancelTerminalResponse {
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#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2839#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
2840#[serde(transparent)]
2841#[from(Arc<str>, String, &str, &mut str, Box<str>, Cow<'_, str>)]
2842#[non_exhaustive]
2843pub struct SessionListCursor(pub Arc<str>);
2844
2845impl SessionListCursor {
2846 #[must_use]
2848 pub fn new(cursor: impl Into<Self>) -> Self {
2849 cursor.into()
2850 }
2851}
2852
2853impl AsRef<str> for SessionListCursor {
2854 fn as_ref(&self) -> &str {
2855 &self.0
2856 }
2857}
2858
2859impl From<&String> for SessionListCursor {
2860 fn from(cursor: &String) -> Self {
2861 Self(cursor.as_str().into())
2862 }
2863}
2864
2865macro_rules! impl_session_list_cursor_option_conversion {
2866 ($source:ty) => {
2867 impl IntoOption<SessionListCursor> for $source {
2868 fn into_option(self) -> Option<SessionListCursor> {
2869 Some(self.into())
2870 }
2871 }
2872 };
2873}
2874
2875impl_session_list_cursor_option_conversion!(Arc<str>);
2876impl_session_list_cursor_option_conversion!(String);
2877impl_session_list_cursor_option_conversion!(&str);
2878impl_session_list_cursor_option_conversion!(&mut str);
2879impl_session_list_cursor_option_conversion!(&String);
2880impl_session_list_cursor_option_conversion!(Box<str>);
2881impl_session_list_cursor_option_conversion!(Cow<'_, str>);
2882
2883crate::serde_util::default_on_null! {
2884 #[serde_as]
2886 #[skip_serializing_none]
2887 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2888 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2889 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LIST_METHOD_NAME)))]
2890 #[serde(rename_all = "camelCase")]
2891 #[non_exhaustive]
2892 pub struct ListSessionsRequest {
2893 #[serde(default)]
2900 pub cwd: Option<AbsolutePath>,
2901 #[serde(default)]
2905 pub cursor: Option<SessionListCursor>,
2906 #[cfg(feature = "unstable_session_archive")]
2916 #[serde(default)]
2917 pub archived: Option<SessionArchiveFilter>,
2918 #[serde_as(deserialize_as = "DefaultOnError")]
2924 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2925 #[serde(default)]
2926 #[serde(rename = "_meta")]
2927 pub meta: Option<Meta>,
2928 }
2929}
2930
2931impl ListSessionsRequest {
2932 #[must_use]
2934 pub fn new() -> Self {
2935 Self::default()
2936 }
2937
2938 #[must_use]
2940 pub fn cwd(mut self, cwd: impl IntoOption<AbsolutePath>) -> Self {
2941 self.cwd = cwd.into_option();
2942 self
2943 }
2944
2945 #[must_use]
2947 pub fn cursor(mut self, cursor: impl IntoOption<SessionListCursor>) -> Self {
2948 self.cursor = cursor.into_option();
2949 self
2950 }
2951
2952 #[cfg(feature = "unstable_session_archive")]
2958 #[must_use]
2959 pub fn archived(mut self, archived: impl IntoOption<SessionArchiveFilter>) -> Self {
2960 self.archived = archived.into_option();
2961 self
2962 }
2963
2964 #[must_use]
2970 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2971 self.meta = meta.into_option();
2972 self
2973 }
2974}
2975
2976#[serde_as]
2978#[skip_serializing_none]
2979#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2980#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2981#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LIST_METHOD_NAME)))]
2982#[serde(rename_all = "camelCase")]
2983#[non_exhaustive]
2984pub struct ListSessionsResponse {
2985 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2987 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2988 pub sessions: Vec<SessionInfo>,
2989 #[serde(default)]
2993 pub next_cursor: Option<SessionListCursor>,
2994 #[serde_as(deserialize_as = "DefaultOnError")]
3000 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3001 #[serde(default)]
3002 #[serde(rename = "_meta")]
3003 pub meta: Option<Meta>,
3004}
3005
3006impl ListSessionsResponse {
3007 #[must_use]
3009 pub fn new(sessions: Vec<SessionInfo>) -> Self {
3010 Self {
3011 sessions,
3012 next_cursor: None,
3013 meta: None,
3014 }
3015 }
3016
3017 #[must_use]
3019 pub fn next_cursor(mut self, next_cursor: impl IntoOption<SessionListCursor>) -> Self {
3020 self.next_cursor = next_cursor.into_option();
3021 self
3022 }
3023
3024 #[must_use]
3030 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3031 self.meta = meta.into_option();
3032 self
3033 }
3034}
3035
3036#[serde_as]
3042#[skip_serializing_none]
3043#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3044#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3045#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_DELETE_METHOD_NAME)))]
3046#[serde(rename_all = "camelCase")]
3047#[non_exhaustive]
3048pub struct DeleteSessionRequest {
3049 pub session_id: SessionId,
3051 #[serde_as(deserialize_as = "DefaultOnError")]
3057 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3058 #[serde(default)]
3059 #[serde(rename = "_meta")]
3060 pub meta: Option<Meta>,
3061}
3062
3063impl DeleteSessionRequest {
3064 #[must_use]
3066 pub fn new(session_id: impl Into<SessionId>) -> Self {
3067 Self {
3068 session_id: session_id.into(),
3069 meta: None,
3070 }
3071 }
3072
3073 #[must_use]
3079 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3080 self.meta = meta.into_option();
3081 self
3082 }
3083}
3084
3085crate::serde_util::default_on_null! {
3086 #[serde_as]
3088 #[skip_serializing_none]
3089 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3090 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3091 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_DELETE_METHOD_NAME)))]
3092 #[serde(rename_all = "camelCase")]
3093 #[non_exhaustive]
3094 pub struct DeleteSessionResponse {
3095 #[serde_as(deserialize_as = "DefaultOnError")]
3101 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3102 #[serde(default)]
3103 #[serde(rename = "_meta")]
3104 pub meta: Option<Meta>,
3105 }
3106}
3107
3108impl DeleteSessionResponse {
3109 #[must_use]
3111 pub fn new() -> Self {
3112 Self::default()
3113 }
3114
3115 #[must_use]
3121 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3122 self.meta = meta.into_option();
3123 self
3124 }
3125}
3126
3127#[cfg(feature = "unstable_session_archive")]
3143#[serde_as]
3144#[skip_serializing_none]
3145#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3146#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3147#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_ARCHIVE_METHOD_NAME)))]
3148#[serde(rename_all = "camelCase")]
3149#[non_exhaustive]
3150pub struct ArchiveSessionRequest {
3151 pub session_id: SessionId,
3153 #[serde_as(deserialize_as = "DefaultOnError")]
3159 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3160 #[serde(default)]
3161 #[serde(rename = "_meta")]
3162 pub meta: Option<Meta>,
3163}
3164
3165#[cfg(feature = "unstable_session_archive")]
3166impl ArchiveSessionRequest {
3167 #[must_use]
3169 pub fn new(session_id: impl Into<SessionId>) -> Self {
3170 Self {
3171 session_id: session_id.into(),
3172 meta: None,
3173 }
3174 }
3175
3176 #[must_use]
3182 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3183 self.meta = meta.into_option();
3184 self
3185 }
3186}
3187
3188#[cfg(feature = "unstable_session_archive")]
3189crate::serde_util::default_on_null! {
3190 #[serde_as]
3196 #[skip_serializing_none]
3197 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3198 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3199 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_ARCHIVE_METHOD_NAME)))]
3200 #[serde(rename_all = "camelCase")]
3201 #[non_exhaustive]
3202 pub struct ArchiveSessionResponse {
3203 #[serde_as(deserialize_as = "DefaultOnError")]
3209 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3210 #[serde(default)]
3211 #[serde(rename = "_meta")]
3212 pub meta: Option<Meta>,
3213 }
3214}
3215
3216#[cfg(feature = "unstable_session_archive")]
3217impl ArchiveSessionResponse {
3218 #[must_use]
3220 pub fn new() -> Self {
3221 Self::default()
3222 }
3223
3224 #[must_use]
3230 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3231 self.meta = meta.into_option();
3232 self
3233 }
3234}
3235
3236#[cfg(feature = "unstable_session_archive")]
3251#[serde_as]
3252#[skip_serializing_none]
3253#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3254#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3255#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_UNARCHIVE_METHOD_NAME)))]
3256#[serde(rename_all = "camelCase")]
3257#[non_exhaustive]
3258pub struct UnarchiveSessionRequest {
3259 pub session_id: SessionId,
3261 #[serde_as(deserialize_as = "DefaultOnError")]
3267 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3268 #[serde(default)]
3269 #[serde(rename = "_meta")]
3270 pub meta: Option<Meta>,
3271}
3272
3273#[cfg(feature = "unstable_session_archive")]
3274impl UnarchiveSessionRequest {
3275 #[must_use]
3277 pub fn new(session_id: impl Into<SessionId>) -> Self {
3278 Self {
3279 session_id: session_id.into(),
3280 meta: None,
3281 }
3282 }
3283
3284 #[must_use]
3290 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3291 self.meta = meta.into_option();
3292 self
3293 }
3294}
3295
3296#[cfg(feature = "unstable_session_archive")]
3297crate::serde_util::default_on_null! {
3298 #[serde_as]
3304 #[skip_serializing_none]
3305 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3306 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3307 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_UNARCHIVE_METHOD_NAME)))]
3308 #[serde(rename_all = "camelCase")]
3309 #[non_exhaustive]
3310 pub struct UnarchiveSessionResponse {
3311 #[serde_as(deserialize_as = "DefaultOnError")]
3317 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3318 #[serde(default)]
3319 #[serde(rename = "_meta")]
3320 pub meta: Option<Meta>,
3321 }
3322}
3323
3324#[cfg(feature = "unstable_session_archive")]
3325impl UnarchiveSessionResponse {
3326 #[must_use]
3328 pub fn new() -> Self {
3329 Self::default()
3330 }
3331
3332 #[must_use]
3338 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3339 self.meta = meta.into_option();
3340 self
3341 }
3342}
3343
3344#[cfg(feature = "unstable_session_archive")]
3353#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3354#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
3355#[serde(rename_all = "snake_case")]
3356#[non_exhaustive]
3357pub enum SessionArchiveFilter {
3358 #[default]
3360 Exclude,
3361 Include,
3363 Only,
3365 #[serde(untagged)]
3371 Other(String),
3372}
3373
3374#[serde_as]
3376#[skip_serializing_none]
3377#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3378#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3379#[serde(rename_all = "camelCase")]
3380#[non_exhaustive]
3381pub struct SessionInfo {
3382 pub session_id: SessionId,
3384 pub cwd: AbsolutePath,
3386 #[serde_as(deserialize_as = "DefaultOnNull")]
3392 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
3393 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3394 pub additional_directories: Vec<AbsolutePath>,
3395
3396 #[serde_as(deserialize_as = "DefaultOnError")]
3400 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3401 #[serde(default)]
3402 pub title: Option<String>,
3403 #[serde_as(deserialize_as = "DefaultOnError")]
3407 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "format" = "date-time")))]
3408 #[serde(default)]
3409 pub updated_at: Option<String>,
3410 #[cfg(feature = "unstable_session_archive")]
3419 #[serde_as(deserialize_as = "DefaultOnError")]
3420 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3421 #[serde(default)]
3422 pub archived: Option<bool>,
3423 #[serde_as(deserialize_as = "DefaultOnError")]
3429 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3430 #[serde(default)]
3431 #[serde(rename = "_meta")]
3432 pub meta: Option<Meta>,
3433}
3434
3435impl SessionInfo {
3436 #[must_use]
3438 pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
3439 Self {
3440 session_id: session_id.into(),
3441 cwd: cwd.into(),
3442 additional_directories: vec![],
3443 title: None,
3444 updated_at: None,
3445 #[cfg(feature = "unstable_session_archive")]
3446 archived: None,
3447 meta: None,
3448 }
3449 }
3450
3451 #[must_use]
3453 pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
3454 where
3455 I: IntoIterator<Item = P>,
3456 P: Into<AbsolutePath>,
3457 {
3458 self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
3459 self
3460 }
3461
3462 #[must_use]
3464 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
3465 self.title = title.into_option();
3466 self
3467 }
3468
3469 #[must_use]
3471 pub fn updated_at(mut self, updated_at: impl IntoOption<String>) -> Self {
3472 self.updated_at = updated_at.into_option();
3473 self
3474 }
3475
3476 #[cfg(feature = "unstable_session_archive")]
3482 #[must_use]
3483 pub fn archived(mut self, archived: impl IntoOption<bool>) -> Self {
3484 self.archived = archived.into_option();
3485 self
3486 }
3487
3488 #[must_use]
3494 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3495 self.meta = meta.into_option();
3496 self
3497 }
3498}
3499
3500#[cfg(feature = "unstable_session_set_title")]
3516#[serde_as]
3517#[skip_serializing_none]
3518#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3519#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3520#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_TITLE_METHOD_NAME)))]
3521#[serde(rename_all = "camelCase")]
3522#[non_exhaustive]
3523pub struct SetSessionTitleRequest {
3524 pub session_id: SessionId,
3526 pub title: String,
3533 #[serde_as(deserialize_as = "DefaultOnError")]
3539 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3540 #[serde(default)]
3541 #[serde(rename = "_meta")]
3542 pub meta: Option<Meta>,
3543}
3544
3545#[cfg(feature = "unstable_session_set_title")]
3546impl SetSessionTitleRequest {
3547 #[must_use]
3549 pub fn new(session_id: impl Into<SessionId>, title: impl Into<String>) -> Self {
3550 Self {
3551 session_id: session_id.into(),
3552 title: title.into(),
3553 meta: None,
3554 }
3555 }
3556
3557 #[must_use]
3563 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3564 self.meta = meta.into_option();
3565 self
3566 }
3567}
3568
3569#[cfg(feature = "unstable_session_set_title")]
3575#[serde_as]
3576#[skip_serializing_none]
3577#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3578#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3579#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_TITLE_METHOD_NAME)))]
3580#[serde(rename_all = "camelCase")]
3581#[non_exhaustive]
3582pub struct SetSessionTitleResponse {
3583 pub title: String,
3588 #[serde_as(deserialize_as = "DefaultOnError")]
3594 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3595 #[serde(default)]
3596 #[serde(rename = "_meta")]
3597 pub meta: Option<Meta>,
3598}
3599
3600#[cfg(feature = "unstable_session_set_title")]
3601impl SetSessionTitleResponse {
3602 #[must_use]
3604 pub fn new(title: impl Into<String>) -> Self {
3605 Self {
3606 title: title.into(),
3607 meta: None,
3608 }
3609 }
3610
3611 #[must_use]
3617 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3618 self.meta = meta.into_option();
3619 self
3620 }
3621}
3622
3623#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3627#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3628#[serde(transparent)]
3629#[from(forward)]
3630#[non_exhaustive]
3631pub struct SessionConfigId(pub Arc<str>);
3632
3633impl SessionConfigId {
3634 #[must_use]
3636 pub fn new(id: impl Into<Self>) -> Self {
3637 id.into()
3638 }
3639}
3640
3641#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3643#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3644#[serde(transparent)]
3645#[from(forward)]
3646#[non_exhaustive]
3647pub struct SessionConfigValueId(pub Arc<str>);
3648
3649impl SessionConfigValueId {
3650 #[must_use]
3652 pub fn new(id: impl Into<Self>) -> Self {
3653 id.into()
3654 }
3655}
3656
3657#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3659#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3660#[serde(transparent)]
3661#[from(forward)]
3662#[non_exhaustive]
3663pub struct SessionConfigGroupId(pub Arc<str>);
3664
3665impl SessionConfigGroupId {
3666 #[must_use]
3668 pub fn new(id: impl Into<Self>) -> Self {
3669 id.into()
3670 }
3671}
3672
3673#[serde_as]
3675#[skip_serializing_none]
3676#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3677#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3678#[serde(rename_all = "camelCase")]
3679#[non_exhaustive]
3680pub struct SessionConfigSelectOption {
3681 pub value: SessionConfigValueId,
3683 pub name: String,
3685 #[serde_as(deserialize_as = "DefaultOnError")]
3689 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3690 #[serde(default)]
3691 pub description: Option<String>,
3692 #[serde_as(deserialize_as = "DefaultOnError")]
3698 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3699 #[serde(default)]
3700 #[serde(rename = "_meta")]
3701 pub meta: Option<Meta>,
3702}
3703
3704impl SessionConfigSelectOption {
3705 #[must_use]
3707 pub fn new(value: impl Into<SessionConfigValueId>, name: impl Into<String>) -> Self {
3708 Self {
3709 value: value.into(),
3710 name: name.into(),
3711 description: None,
3712 meta: None,
3713 }
3714 }
3715
3716 #[must_use]
3718 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
3719 self.description = description.into_option();
3720 self
3721 }
3722
3723 #[must_use]
3729 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3730 self.meta = meta.into_option();
3731 self
3732 }
3733}
3734
3735#[serde_as]
3737#[skip_serializing_none]
3738#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3739#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3740#[serde(rename_all = "camelCase")]
3741#[non_exhaustive]
3742pub struct SessionConfigSelectGroup {
3743 pub group_id: SessionConfigGroupId,
3745 pub name: String,
3747 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
3749 #[cfg_attr(feature = "schemars", schemars(length(min = 1), extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3750 pub options: Vec<SessionConfigSelectOption>,
3751 #[serde_as(deserialize_as = "DefaultOnError")]
3757 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3758 #[serde(default)]
3759 #[serde(rename = "_meta")]
3760 pub meta: Option<Meta>,
3761}
3762
3763impl SessionConfigSelectGroup {
3764 #[must_use]
3766 pub fn new(
3767 group_id: impl Into<SessionConfigGroupId>,
3768 name: impl Into<String>,
3769 options: Vec<SessionConfigSelectOption>,
3770 ) -> Self {
3771 Self {
3772 group_id: group_id.into(),
3773 name: name.into(),
3774 options,
3775 meta: None,
3776 }
3777 }
3778
3779 #[must_use]
3785 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3786 self.meta = meta.into_option();
3787 self
3788 }
3789}
3790
3791#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3793#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3794#[serde(untagged)]
3795#[non_exhaustive]
3796pub enum SessionConfigSelectOptions {
3797 Ungrouped(
3799 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))] Vec<SessionConfigSelectOption>,
3800 ),
3801 Grouped(
3803 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))] Vec<SessionConfigSelectGroup>,
3804 ),
3805}
3806
3807impl From<Vec<SessionConfigSelectOption>> for SessionConfigSelectOptions {
3808 fn from(options: Vec<SessionConfigSelectOption>) -> Self {
3809 SessionConfigSelectOptions::Ungrouped(options)
3810 }
3811}
3812
3813impl From<Vec<SessionConfigSelectGroup>> for SessionConfigSelectOptions {
3814 fn from(groups: Vec<SessionConfigSelectGroup>) -> Self {
3815 SessionConfigSelectOptions::Grouped(groups)
3816 }
3817}
3818
3819#[skip_serializing_none]
3821#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3822#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3823#[serde(rename_all = "camelCase")]
3824#[non_exhaustive]
3825pub struct SessionConfigSelect {
3826 pub current_value: SessionConfigValueId,
3828 pub options: SessionConfigSelectOptions,
3831}
3832
3833impl SessionConfigSelect {
3834 #[must_use]
3836 pub fn new(
3837 current_value: impl Into<SessionConfigValueId>,
3838 options: impl Into<SessionConfigSelectOptions>,
3839 ) -> Self {
3840 Self {
3841 current_value: current_value.into(),
3842 options: options.into(),
3843 }
3844 }
3845}
3846
3847#[skip_serializing_none]
3849#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3850#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3851#[serde(rename_all = "camelCase")]
3852#[non_exhaustive]
3853pub struct SessionConfigBoolean {
3854 pub current_value: bool,
3856}
3857
3858impl SessionConfigBoolean {
3859 #[must_use]
3861 pub fn new(current_value: bool) -> Self {
3862 Self { current_value }
3863 }
3864}
3865
3866#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3876#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3877#[serde(rename_all = "snake_case")]
3878#[non_exhaustive]
3879pub enum SessionConfigOptionCategory {
3880 Mode,
3882 Model,
3884 ModelConfig,
3886 ThoughtLevel,
3888 #[serde(untagged)]
3894 Other(String),
3895}
3896
3897#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3899#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3900#[serde(tag = "type", rename_all = "snake_case")]
3901#[non_exhaustive]
3902pub enum SessionConfigKind {
3903 Select(SessionConfigSelect),
3905 Boolean(SessionConfigBoolean),
3907 #[serde(untagged)]
3917 Other(OtherSessionConfigKind),
3918}
3919
3920#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3922#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
3923#[cfg_attr(feature = "schemars", schemars(inline))]
3924#[cfg_attr(feature = "schemars", schemars(transform = other_session_config_kind_schema))]
3925#[serde(rename_all = "camelCase")]
3926#[non_exhaustive]
3927pub struct OtherSessionConfigKind {
3928 #[serde(rename = "type")]
3934 pub type_: String,
3935 #[serde(flatten)]
3937 pub fields: BTreeMap<String, serde_json::Value>,
3938}
3939
3940impl OtherSessionConfigKind {
3941 #[must_use]
3943 pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
3944 fields.remove("type");
3945 fields.remove("_meta");
3946 Self {
3947 type_: type_.into(),
3948 fields,
3949 }
3950 }
3951}
3952
3953impl<'de> Deserialize<'de> for OtherSessionConfigKind {
3954 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3955 where
3956 D: serde::Deserializer<'de>,
3957 {
3958 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
3959 let type_ = fields
3960 .remove("type")
3961 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
3962 let serde_json::Value::String(type_) = type_ else {
3963 return Err(serde::de::Error::custom("`type` must be a string"));
3964 };
3965
3966 if is_known_session_config_kind_type(&type_) {
3967 return Err(serde::de::Error::custom(format!(
3968 "known session configuration option `{type_}` did not match its schema"
3969 )));
3970 }
3971
3972 Ok(Self { type_, fields })
3973 }
3974}
3975
3976fn is_known_session_config_kind_type(type_: &str) -> bool {
3977 matches!(type_, "select" | "boolean")
3978}
3979
3980#[cfg(feature = "schemars")]
3981fn other_session_config_kind_schema(schema: &mut Schema) {
3982 super::schema_util::reject_known_string_discriminators(schema, "type", &["select", "boolean"]);
3983}
3984
3985#[serde_as]
3987#[skip_serializing_none]
3988#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3989#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3990#[serde(rename_all = "camelCase")]
3991#[non_exhaustive]
3992pub struct SessionConfigOption {
3993 pub config_id: SessionConfigId,
3995 pub name: String,
3997 #[serde_as(deserialize_as = "DefaultOnError")]
4001 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4002 #[serde(default)]
4003 pub description: Option<String>,
4004 #[serde_as(deserialize_as = "DefaultOnError")]
4008 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4009 #[serde(default)]
4010 pub category: Option<SessionConfigOptionCategory>,
4011 #[serde(flatten)]
4013 pub kind: SessionConfigKind,
4014 #[serde_as(deserialize_as = "DefaultOnError")]
4020 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4021 #[serde(default)]
4022 #[serde(rename = "_meta")]
4023 pub meta: Option<Meta>,
4024}
4025
4026impl SessionConfigOption {
4027 #[must_use]
4029 pub fn new(
4030 config_id: impl Into<SessionConfigId>,
4031 name: impl Into<String>,
4032 kind: SessionConfigKind,
4033 ) -> Self {
4034 Self {
4035 config_id: config_id.into(),
4036 name: name.into(),
4037 description: None,
4038 category: None,
4039 kind,
4040 meta: None,
4041 }
4042 }
4043
4044 #[must_use]
4046 pub fn select(
4047 config_id: impl Into<SessionConfigId>,
4048 name: impl Into<String>,
4049 current_value: impl Into<SessionConfigValueId>,
4050 options: impl Into<SessionConfigSelectOptions>,
4051 ) -> Self {
4052 Self::new(
4053 config_id,
4054 name,
4055 SessionConfigKind::Select(SessionConfigSelect::new(current_value, options)),
4056 )
4057 }
4058
4059 #[must_use]
4061 pub fn boolean(
4062 config_id: impl Into<SessionConfigId>,
4063 name: impl Into<String>,
4064 current_value: bool,
4065 ) -> Self {
4066 Self::new(
4067 config_id,
4068 name,
4069 SessionConfigKind::Boolean(SessionConfigBoolean::new(current_value)),
4070 )
4071 }
4072
4073 #[must_use]
4075 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
4076 self.description = description.into_option();
4077 self
4078 }
4079
4080 #[must_use]
4082 pub fn category(mut self, category: impl IntoOption<SessionConfigOptionCategory>) -> Self {
4083 self.category = category.into_option();
4084 self
4085 }
4086
4087 #[must_use]
4093 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4094 self.meta = meta.into_option();
4095 self
4096 }
4097}
4098
4099#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4108#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4109#[serde(tag = "type", rename_all = "snake_case")]
4110#[non_exhaustive]
4111pub enum SessionConfigOptionValue {
4112 Id {
4114 value: SessionConfigValueId,
4116 },
4117 Boolean {
4119 value: bool,
4121 },
4122 #[serde(untagged)]
4131 Other(OtherSessionConfigOptionValue),
4132}
4133
4134#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4136#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4137#[cfg_attr(feature = "schemars", schemars(inline))]
4138#[cfg_attr(feature = "schemars", schemars(transform = other_session_config_option_value_schema))]
4139#[serde(rename_all = "camelCase")]
4140#[non_exhaustive]
4141pub struct OtherSessionConfigOptionValue {
4142 #[serde(rename = "type")]
4148 pub type_: String,
4149 pub value: serde_json::Value,
4151 #[serde(flatten)]
4153 pub fields: BTreeMap<String, serde_json::Value>,
4154}
4155
4156impl OtherSessionConfigOptionValue {
4157 #[must_use]
4159 pub fn new(
4160 type_: impl Into<String>,
4161 value: serde_json::Value,
4162 mut fields: BTreeMap<String, serde_json::Value>,
4163 ) -> Self {
4164 fields.remove("type");
4165 fields.remove("value");
4166 fields.remove("_meta");
4167 Self {
4168 type_: type_.into(),
4169 value,
4170 fields,
4171 }
4172 }
4173}
4174
4175impl<'de> Deserialize<'de> for OtherSessionConfigOptionValue {
4176 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4177 where
4178 D: serde::Deserializer<'de>,
4179 {
4180 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
4181 let type_ = fields
4182 .remove("type")
4183 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4184 let serde_json::Value::String(type_) = type_ else {
4185 return Err(serde::de::Error::custom("`type` must be a string"));
4186 };
4187
4188 if is_known_session_config_option_value_type(&type_) {
4189 return Err(serde::de::Error::custom(format!(
4190 "known session configuration option value `{type_}` did not match its schema"
4191 )));
4192 }
4193
4194 let value = fields
4195 .remove("value")
4196 .ok_or_else(|| serde::de::Error::missing_field("value"))?;
4197
4198 Ok(Self {
4199 type_,
4200 value,
4201 fields,
4202 })
4203 }
4204}
4205
4206impl<'de> Deserialize<'de> for SessionConfigOptionValue {
4207 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4208 where
4209 D: serde::Deserializer<'de>,
4210 {
4211 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
4212 let type_ = fields.remove("type");
4213 let value = fields
4214 .remove("value")
4215 .ok_or_else(|| serde::de::Error::missing_field("value"))?;
4216
4217 let type_ = type_.ok_or_else(|| serde::de::Error::missing_field("type"))?;
4218
4219 let serde_json::Value::String(type_) = type_ else {
4220 return Err(serde::de::Error::custom("`type` must be a string"));
4221 };
4222
4223 match type_.as_str() {
4224 "id" => {
4225 let value = serde_json::from_value(value).map_err(|error| {
4226 serde::de::Error::custom(format!(
4227 "`value` must be a string for `type: id`: {error}"
4228 ))
4229 })?;
4230 Ok(Self::Id { value })
4231 }
4232 "boolean" => {
4233 let value = serde_json::from_value(value).map_err(|error| {
4234 serde::de::Error::custom(format!(
4235 "`value` must be a boolean for `type: boolean`: {error}"
4236 ))
4237 })?;
4238 Ok(Self::Boolean { value })
4239 }
4240 _ => Ok(Self::Other(OtherSessionConfigOptionValue {
4241 type_,
4242 value,
4243 fields,
4244 })),
4245 }
4246 }
4247}
4248
4249fn is_known_session_config_option_value_type(type_: &str) -> bool {
4250 matches!(type_, "id" | "boolean")
4251}
4252
4253#[cfg(feature = "schemars")]
4254fn other_session_config_option_value_schema(schema: &mut Schema) {
4255 super::schema_util::reject_known_string_discriminators(schema, "type", &["id", "boolean"]);
4256}
4257
4258impl SessionConfigOptionValue {
4259 #[must_use]
4261 pub fn id(id: impl Into<SessionConfigValueId>) -> Self {
4262 Self::Id { value: id.into() }
4263 }
4264
4265 #[must_use]
4267 pub fn boolean(val: bool) -> Self {
4268 Self::Boolean { value: val }
4269 }
4270
4271 #[must_use]
4274 pub fn as_id(&self) -> Option<&SessionConfigValueId> {
4275 match self {
4276 Self::Id { value } => Some(value),
4277 _ => None,
4278 }
4279 }
4280
4281 #[must_use]
4283 pub fn as_bool(&self) -> Option<bool> {
4284 match self {
4285 Self::Boolean { value } => Some(*value),
4286 _ => None,
4287 }
4288 }
4289}
4290
4291impl From<SessionConfigValueId> for SessionConfigOptionValue {
4292 fn from(value: SessionConfigValueId) -> Self {
4293 Self::Id { value }
4294 }
4295}
4296
4297impl From<bool> for SessionConfigOptionValue {
4298 fn from(value: bool) -> Self {
4299 Self::Boolean { value }
4300 }
4301}
4302
4303impl From<&str> for SessionConfigOptionValue {
4304 fn from(value: &str) -> Self {
4305 Self::Id {
4306 value: SessionConfigValueId::new(value),
4307 }
4308 }
4309}
4310
4311#[serde_as]
4319#[skip_serializing_none]
4320#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4321#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4322#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_CONFIG_OPTION_METHOD_NAME)))]
4323#[serde(rename_all = "camelCase")]
4324#[non_exhaustive]
4325pub struct SetSessionConfigOptionRequest {
4326 pub session_id: SessionId,
4328 pub config_id: SessionConfigId,
4330 #[serde(flatten)]
4334 pub value: SessionConfigOptionValue,
4335 #[serde_as(deserialize_as = "DefaultOnError")]
4341 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4342 #[serde(default)]
4343 #[serde(rename = "_meta")]
4344 pub meta: Option<Meta>,
4345}
4346
4347impl SetSessionConfigOptionRequest {
4348 #[must_use]
4350 pub fn new(
4351 session_id: impl Into<SessionId>,
4352 config_id: impl Into<SessionConfigId>,
4353 value: impl Into<SessionConfigOptionValue>,
4354 ) -> Self {
4355 Self {
4356 session_id: session_id.into(),
4357 config_id: config_id.into(),
4358 value: value.into(),
4359 meta: None,
4360 }
4361 }
4362
4363 #[must_use]
4369 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4370 self.meta = meta.into_option();
4371 self
4372 }
4373}
4374
4375#[serde_as]
4377#[skip_serializing_none]
4378#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4379#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4380#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_CONFIG_OPTION_METHOD_NAME)))]
4381#[serde(rename_all = "camelCase")]
4382#[non_exhaustive]
4383pub struct SetSessionConfigOptionResponse {
4384 #[serde_as(deserialize_as = "VecSkipError<_>")]
4386 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
4387 pub config_options: Vec<SessionConfigOption>,
4388 #[serde_as(deserialize_as = "DefaultOnError")]
4394 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4395 #[serde(default)]
4396 #[serde(rename = "_meta")]
4397 pub meta: Option<Meta>,
4398}
4399
4400impl SetSessionConfigOptionResponse {
4401 #[must_use]
4403 pub fn new(config_options: Vec<SessionConfigOption>) -> Self {
4404 Self {
4405 config_options,
4406 meta: None,
4407 }
4408 }
4409
4410 #[must_use]
4416 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4417 self.meta = meta.into_option();
4418 self
4419 }
4420}
4421
4422#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4431#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4432#[serde(tag = "type", rename_all = "snake_case")]
4433#[non_exhaustive]
4434pub enum McpServer {
4435 Http(McpServerHttp),
4439 #[cfg(feature = "unstable_mcp_over_acp")]
4448 Acp(McpServerAcp),
4449 Stdio(McpServerStdio),
4453 #[serde(untagged)]
4464 Other(OtherMcpServer),
4465}
4466
4467#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4469#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4470#[cfg_attr(feature = "schemars", schemars(inline))]
4471#[cfg_attr(feature = "schemars", schemars(transform = other_mcp_server_schema))]
4472#[serde(rename_all = "camelCase")]
4473#[non_exhaustive]
4474pub struct OtherMcpServer {
4475 #[serde(rename = "type")]
4481 pub type_: String,
4482 #[serde(flatten)]
4484 pub fields: BTreeMap<String, serde_json::Value>,
4485}
4486
4487impl OtherMcpServer {
4488 #[must_use]
4490 pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
4491 fields.remove("type");
4492 Self {
4493 type_: type_.into(),
4494 fields,
4495 }
4496 }
4497}
4498
4499impl<'de> Deserialize<'de> for OtherMcpServer {
4500 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4501 where
4502 D: serde::Deserializer<'de>,
4503 {
4504 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
4505 let type_ = fields
4506 .remove("type")
4507 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4508 let serde_json::Value::String(type_) = type_ else {
4509 return Err(serde::de::Error::custom("`type` must be a string"));
4510 };
4511
4512 if is_known_mcp_server_type(&type_) {
4513 return Err(serde::de::Error::custom(format!(
4514 "known MCP server transport `{type_}` did not match its schema"
4515 )));
4516 }
4517
4518 Ok(Self { type_, fields })
4519 }
4520}
4521
4522fn is_known_mcp_server_type(type_: &str) -> bool {
4523 match type_ {
4524 "http" | "stdio" => true,
4525 #[cfg(feature = "unstable_mcp_over_acp")]
4526 "acp" => true,
4527 _ => false,
4528 }
4529}
4530
4531#[cfg(feature = "schemars")]
4532fn other_mcp_server_schema(schema: &mut Schema) {
4533 super::schema_util::reject_known_string_discriminators(
4534 schema,
4535 "type",
4536 &[
4537 "http",
4538 "stdio",
4539 #[cfg(feature = "unstable_mcp_over_acp")]
4540 "acp",
4541 ],
4542 );
4543}
4544
4545#[serde_as]
4547#[skip_serializing_none]
4548#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4549#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4550#[serde(rename_all = "camelCase")]
4551#[non_exhaustive]
4552pub struct McpServerHttp {
4553 pub name: String,
4555 #[cfg_attr(feature = "schemars", schemars(url))]
4557 pub url: String,
4558 #[serde_as(deserialize_as = "DefaultOnNull")]
4561 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4562 #[serde(default, skip_serializing_if = "Vec::is_empty")]
4563 pub headers: Vec<HttpHeader>,
4564 #[serde_as(deserialize_as = "DefaultOnError")]
4570 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4571 #[serde(default)]
4572 #[serde(rename = "_meta")]
4573 pub meta: Option<Meta>,
4574}
4575
4576impl McpServerHttp {
4577 #[must_use]
4579 pub fn new(name: impl Into<String>, url: impl Into<String>) -> Self {
4580 Self {
4581 name: name.into(),
4582 url: url.into(),
4583 headers: Vec::new(),
4584 meta: None,
4585 }
4586 }
4587
4588 #[must_use]
4591 pub fn headers(mut self, headers: Vec<HttpHeader>) -> Self {
4592 self.headers = headers;
4593 self
4594 }
4595
4596 #[must_use]
4602 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4603 self.meta = meta.into_option();
4604 self
4605 }
4606}
4607
4608#[cfg(feature = "unstable_mcp_over_acp")]
4617#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4618#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
4619#[serde(transparent)]
4620#[from(forward)]
4621#[non_exhaustive]
4622pub struct McpServerAcpId(pub Arc<str>);
4623
4624#[cfg(feature = "unstable_mcp_over_acp")]
4625impl McpServerAcpId {
4626 #[must_use]
4628 pub fn new(id: impl Into<Self>) -> Self {
4629 id.into()
4630 }
4631}
4632
4633#[serde_as]
4642#[skip_serializing_none]
4643#[cfg(feature = "unstable_mcp_over_acp")]
4644#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4645#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4646#[serde(rename_all = "camelCase")]
4647#[non_exhaustive]
4648pub struct McpServerAcp {
4649 pub name: String,
4651 pub server_id: McpServerAcpId,
4656 #[serde_as(deserialize_as = "DefaultOnError")]
4662 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4663 #[serde(default)]
4664 #[serde(rename = "_meta")]
4665 pub meta: Option<Meta>,
4666}
4667
4668#[cfg(feature = "unstable_mcp_over_acp")]
4669impl McpServerAcp {
4670 #[must_use]
4672 pub fn new(name: impl Into<String>, server_id: impl Into<McpServerAcpId>) -> Self {
4673 Self {
4674 name: name.into(),
4675 server_id: server_id.into(),
4676 meta: None,
4677 }
4678 }
4679
4680 #[must_use]
4686 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4687 self.meta = meta.into_option();
4688 self
4689 }
4690}
4691
4692#[serde_as]
4694#[skip_serializing_none]
4695#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4696#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4697#[serde(rename_all = "camelCase")]
4698#[non_exhaustive]
4699pub struct McpServerStdio {
4700 pub name: String,
4702 pub command: AbsolutePath,
4704 #[serde_as(deserialize_as = "DefaultOnNull")]
4706 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4707 #[serde(default, skip_serializing_if = "Vec::is_empty")]
4708 pub args: Vec<String>,
4709 #[serde_as(deserialize_as = "DefaultOnNull")]
4712 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4713 #[serde(default, skip_serializing_if = "Vec::is_empty")]
4714 pub env: Vec<EnvVariable>,
4715 #[serde_as(deserialize_as = "DefaultOnError")]
4721 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4722 #[serde(default)]
4723 #[serde(rename = "_meta")]
4724 pub meta: Option<Meta>,
4725}
4726
4727impl McpServerStdio {
4728 #[must_use]
4730 pub fn new(name: impl Into<String>, command: impl Into<AbsolutePath>) -> Self {
4731 Self {
4732 name: name.into(),
4733 command: command.into(),
4734 args: Vec::new(),
4735 env: Vec::new(),
4736 meta: None,
4737 }
4738 }
4739
4740 #[must_use]
4742 pub fn args(mut self, args: Vec<String>) -> Self {
4743 self.args = args;
4744 self
4745 }
4746
4747 #[must_use]
4750 pub fn env(mut self, env: Vec<EnvVariable>) -> Self {
4751 self.env = env;
4752 self
4753 }
4754
4755 #[must_use]
4761 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4762 self.meta = meta.into_option();
4763 self
4764 }
4765}
4766
4767#[serde_as]
4769#[skip_serializing_none]
4770#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4771#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4772#[serde(rename_all = "camelCase")]
4773#[non_exhaustive]
4774pub struct EnvVariable {
4775 pub name: String,
4777 pub value: String,
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
4791impl EnvVariable {
4792 #[must_use]
4794 pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
4795 Self {
4796 name: name.into(),
4797 value: value.into(),
4798 meta: None,
4799 }
4800 }
4801
4802 #[must_use]
4808 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4809 self.meta = meta.into_option();
4810 self
4811 }
4812}
4813
4814#[serde_as]
4816#[skip_serializing_none]
4817#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4818#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4819#[serde(rename_all = "camelCase")]
4820#[non_exhaustive]
4821pub struct HttpHeader {
4822 pub name: String,
4824 pub value: String,
4826 #[serde_as(deserialize_as = "DefaultOnError")]
4832 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4833 #[serde(default)]
4834 #[serde(rename = "_meta")]
4835 pub meta: Option<Meta>,
4836}
4837
4838impl HttpHeader {
4839 #[must_use]
4841 pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
4842 Self {
4843 name: name.into(),
4844 value: value.into(),
4845 meta: None,
4846 }
4847 }
4848
4849 #[must_use]
4855 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4856 self.meta = meta.into_option();
4857 self
4858 }
4859}
4860
4861#[serde_as]
4870#[skip_serializing_none]
4871#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4872#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4873#[serde(rename_all = "camelCase")]
4874#[non_exhaustive]
4875pub struct SystemPrompt {
4876 pub mode: SystemPromptMode,
4881 pub content: Vec<ContentBlock>,
4891 #[serde_as(deserialize_as = "DefaultOnError")]
4897 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4898 #[serde(default)]
4899 #[serde(rename = "_meta")]
4900 pub meta: Option<Meta>,
4901}
4902
4903impl SystemPrompt {
4904 #[must_use]
4909 pub fn new(content: Vec<ContentBlock>) -> Self {
4910 Self {
4911 mode: SystemPromptMode::default(),
4912 content,
4913 meta: None,
4914 }
4915 }
4916
4917 #[must_use]
4919 pub fn mode(mut self, mode: SystemPromptMode) -> Self {
4920 self.mode = mode;
4921 self
4922 }
4923
4924 #[must_use]
4930 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4931 self.meta = meta.into_option();
4932 self
4933 }
4934}
4935
4936#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4942#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
4943#[serde(rename_all = "snake_case")]
4944#[non_exhaustive]
4945pub enum SystemPromptMode {
4946 #[default]
4953 Append,
4954 Override,
4963 #[serde(untagged)]
4969 Other(String),
4970}
4971
4972#[serde_as]
4980#[skip_serializing_none]
4981#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4982#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4983#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_PROMPT_METHOD_NAME)))]
4984#[serde(rename_all = "camelCase")]
4985#[non_exhaustive]
4986pub struct PromptRequest {
4987 pub session_id: SessionId,
4989 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
5006 pub prompt: Vec<ContentBlock>,
5007 #[serde_as(deserialize_as = "DefaultOnError")]
5013 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5014 #[serde(default)]
5015 #[serde(rename = "_meta")]
5016 pub meta: Option<Meta>,
5017}
5018
5019impl PromptRequest {
5020 #[must_use]
5022 pub fn new(session_id: impl Into<SessionId>, prompt: Vec<ContentBlock>) -> Self {
5023 Self {
5024 session_id: session_id.into(),
5025 prompt,
5026 meta: None,
5027 }
5028 }
5029
5030 #[must_use]
5036 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5037 self.meta = meta.into_option();
5038 self
5039 }
5040}
5041
5042#[serde_as]
5053#[skip_serializing_none]
5054#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5055#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5056#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_PROMPT_METHOD_NAME)))]
5057#[serde(rename_all = "camelCase")]
5058#[non_exhaustive]
5059pub struct PromptResponse {
5060 pub message_id: MessageId,
5068 #[serde_as(deserialize_as = "DefaultOnError")]
5074 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5075 #[serde(default)]
5076 #[serde(rename = "_meta")]
5077 pub meta: Option<Meta>,
5078}
5079
5080impl PromptResponse {
5081 #[must_use]
5083 pub fn new(message_id: impl Into<MessageId>) -> Self {
5084 Self {
5085 message_id: message_id.into(),
5086 meta: None,
5087 }
5088 }
5089
5090 #[must_use]
5096 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5097 self.meta = meta.into_option();
5098 self
5099 }
5100}
5101
5102#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5106#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
5107#[serde(tag = "stopReason", rename_all = "snake_case")]
5108#[non_exhaustive]
5109pub enum StopReason {
5110 EndTurn,
5113 MaxTokens,
5115 MaxTurnRequests,
5118 Refusal,
5120 Cancelled,
5131 Error(ErrorStopReason),
5137 #[serde(untagged)]
5143 Other(OtherStopReason),
5144}
5145
5146impl From<ErrorStopReason> for StopReason {
5147 fn from(value: ErrorStopReason) -> Self {
5148 Self::Error(value)
5149 }
5150}
5151
5152#[serde_as]
5154#[skip_serializing_none]
5155#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5156#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
5157#[serde(rename_all = "camelCase")]
5158#[non_exhaustive]
5159pub struct ErrorStopReason {
5160 #[serde_as(deserialize_as = "DefaultOnError")]
5165 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5166 #[serde(default)]
5167 pub error: Option<Box<Error>>,
5168}
5169
5170impl ErrorStopReason {
5171 #[must_use]
5173 pub fn new() -> Self {
5174 Self::default()
5175 }
5176
5177 #[must_use]
5179 pub fn error(mut self, error: impl IntoOption<Error>) -> Self {
5180 self.error = error.into_option().map(Box::new);
5181 self
5182 }
5183}
5184
5185#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5187#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
5188#[cfg_attr(feature = "schemars", schemars(inline))]
5189#[cfg_attr(feature = "schemars", schemars(transform = other_stop_reason_schema))]
5190#[serde(rename_all = "camelCase")]
5191#[non_exhaustive]
5192pub struct OtherStopReason {
5193 pub stop_reason: String,
5199 #[serde(flatten)]
5201 pub fields: BTreeMap<String, serde_json::Value>,
5202}
5203
5204impl OtherStopReason {
5205 #[must_use]
5207 pub fn new(
5208 stop_reason: impl Into<String>,
5209 mut fields: BTreeMap<String, serde_json::Value>,
5210 ) -> Self {
5211 remove_idle_state_update_fields(&mut fields);
5212 Self {
5213 stop_reason: stop_reason.into(),
5214 fields,
5215 }
5216 }
5217}
5218
5219impl<'de> Deserialize<'de> for OtherStopReason {
5220 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
5221 where
5222 D: serde::Deserializer<'de>,
5223 {
5224 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
5225 let stop_reason = fields
5226 .remove("stopReason")
5227 .ok_or_else(|| serde::de::Error::missing_field("stopReason"))?;
5228 let serde_json::Value::String(stop_reason) = stop_reason else {
5229 return Err(serde::de::Error::custom("`stopReason` must be a string"));
5230 };
5231
5232 if KNOWN_STOP_REASONS.contains(&stop_reason.as_str()) {
5233 return Err(serde::de::Error::custom(format!(
5234 "known stop reason `{stop_reason}` did not match its schema"
5235 )));
5236 }
5237 remove_idle_state_update_fields(&mut fields);
5238
5239 Ok(Self {
5240 stop_reason,
5241 fields,
5242 })
5243 }
5244}
5245
5246const KNOWN_STOP_REASONS: &[&str] = &[
5247 "end_turn",
5248 "max_tokens",
5249 "max_turn_requests",
5250 "refusal",
5251 "cancelled",
5252 "error",
5253];
5254
5255fn remove_idle_state_update_fields(fields: &mut BTreeMap<String, serde_json::Value>) {
5257 fields.remove("stopReason");
5258 fields.remove("usage");
5259 fields.remove("_meta");
5260}
5261
5262#[cfg(feature = "schemars")]
5263fn other_stop_reason_schema(schema: &mut Schema) {
5264 super::schema_util::reject_known_string_discriminators(
5265 schema,
5266 "stopReason",
5267 KNOWN_STOP_REASONS,
5268 );
5269}
5270
5271#[cfg(feature = "unstable_end_turn_token_usage")]
5277#[serde_as]
5278#[skip_serializing_none]
5279#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5280#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5281#[serde(rename_all = "camelCase")]
5282#[non_exhaustive]
5283pub struct Usage {
5284 pub total_tokens: u64,
5286 pub input_tokens: u64,
5288 pub output_tokens: u64,
5290 #[serde_as(deserialize_as = "DefaultOnError")]
5294 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5295 #[serde(default)]
5296 pub thought_tokens: Option<u64>,
5297 #[serde_as(deserialize_as = "DefaultOnError")]
5301 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5302 #[serde(default)]
5303 pub cached_read_tokens: Option<u64>,
5304 #[serde_as(deserialize_as = "DefaultOnError")]
5308 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5309 #[serde(default)]
5310 pub cached_write_tokens: Option<u64>,
5311 #[serde_as(deserialize_as = "DefaultOnError")]
5317 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5318 #[serde(default)]
5319 #[serde(rename = "_meta")]
5320 pub meta: Option<Meta>,
5321}
5322
5323#[cfg(feature = "unstable_end_turn_token_usage")]
5324impl Usage {
5325 #[must_use]
5327 pub fn new(total_tokens: u64, input_tokens: u64, output_tokens: u64) -> Self {
5328 Self {
5329 total_tokens,
5330 input_tokens,
5331 output_tokens,
5332 thought_tokens: None,
5333 cached_read_tokens: None,
5334 cached_write_tokens: None,
5335 meta: None,
5336 }
5337 }
5338
5339 #[must_use]
5341 pub fn thought_tokens(mut self, thought_tokens: impl IntoOption<u64>) -> Self {
5342 self.thought_tokens = thought_tokens.into_option();
5343 self
5344 }
5345
5346 #[must_use]
5348 pub fn cached_read_tokens(mut self, cached_read_tokens: impl IntoOption<u64>) -> Self {
5349 self.cached_read_tokens = cached_read_tokens.into_option();
5350 self
5351 }
5352
5353 #[must_use]
5355 pub fn cached_write_tokens(mut self, cached_write_tokens: impl IntoOption<u64>) -> Self {
5356 self.cached_write_tokens = cached_write_tokens.into_option();
5357 self
5358 }
5359
5360 #[must_use]
5366 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5367 self.meta = meta.into_option();
5368 self
5369 }
5370}
5371
5372#[cfg(feature = "unstable_llm_providers")]
5385#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5386#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5387#[serde(rename_all = "snake_case")]
5388#[non_exhaustive]
5389#[expect(clippy::doc_markdown)]
5390pub enum LlmProtocol {
5391 Anthropic,
5393 #[serde(rename = "openai")]
5395 OpenAi,
5396 Azure,
5398 Vertex,
5400 Bedrock,
5402 #[serde(untagged)]
5408 Other(String),
5409}
5410
5411#[cfg(feature = "unstable_llm_providers")]
5417#[serde_as]
5418#[skip_serializing_none]
5419#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5420#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5421#[serde(rename_all = "camelCase")]
5422#[non_exhaustive]
5423pub struct ProviderCurrentConfig {
5424 pub api_type: LlmProtocol,
5426 #[cfg_attr(feature = "schemars", schemars(url))]
5428 pub base_url: String,
5429 #[serde_as(deserialize_as = "DefaultOnError")]
5435 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5436 #[serde(default)]
5437 #[serde(rename = "_meta")]
5438 pub meta: Option<Meta>,
5439}
5440
5441#[cfg(feature = "unstable_llm_providers")]
5442impl ProviderCurrentConfig {
5443 #[must_use]
5445 pub fn new(api_type: LlmProtocol, base_url: impl Into<String>) -> Self {
5446 Self {
5447 api_type,
5448 base_url: base_url.into(),
5449 meta: None,
5450 }
5451 }
5452
5453 #[must_use]
5459 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5460 self.meta = meta.into_option();
5461 self
5462 }
5463}
5464
5465#[cfg(feature = "unstable_llm_providers")]
5471#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5472#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
5473#[serde(transparent)]
5474#[from(forward)]
5475#[non_exhaustive]
5476pub struct ProviderId(pub Arc<str>);
5477
5478#[cfg(feature = "unstable_llm_providers")]
5479impl ProviderId {
5480 #[must_use]
5482 pub fn new(id: impl Into<Self>) -> Self {
5483 id.into()
5484 }
5485}
5486
5487#[cfg(feature = "unstable_llm_providers")]
5493#[serde_as]
5494#[skip_serializing_none]
5495#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5496#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5497#[serde(rename_all = "camelCase")]
5498#[non_exhaustive]
5499pub struct ProviderInfo {
5500 pub provider_id: ProviderId,
5502 #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
5504 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
5505 pub supported: Vec<LlmProtocol>,
5506 pub required: bool,
5509 #[serde(default)]
5512 pub current: Option<ProviderCurrentConfig>,
5513 #[serde_as(deserialize_as = "DefaultOnError")]
5519 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5520 #[serde(default)]
5521 #[serde(rename = "_meta")]
5522 pub meta: Option<Meta>,
5523}
5524
5525#[cfg(feature = "unstable_llm_providers")]
5526impl ProviderInfo {
5527 #[must_use]
5529 pub fn new(
5530 provider_id: impl Into<ProviderId>,
5531 supported: Vec<LlmProtocol>,
5532 required: bool,
5533 current: impl IntoOption<ProviderCurrentConfig>,
5534 ) -> Self {
5535 Self {
5536 provider_id: provider_id.into(),
5537 supported,
5538 required,
5539 current: current.into_option(),
5540 meta: None,
5541 }
5542 }
5543
5544 #[must_use]
5550 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5551 self.meta = meta.into_option();
5552 self
5553 }
5554}
5555
5556#[cfg(feature = "unstable_llm_providers")]
5557crate::serde_util::default_on_null! {
5558 #[serde_as]
5564 #[skip_serializing_none]
5565 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5566 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
5567 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_LIST_METHOD_NAME)))]
5568 #[serde(rename_all = "camelCase")]
5569 #[non_exhaustive]
5570 pub struct ListProvidersRequest {
5571 #[serde_as(deserialize_as = "DefaultOnError")]
5577 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5578 #[serde(default)]
5579 #[serde(rename = "_meta")]
5580 pub meta: Option<Meta>,
5581 }
5582}
5583
5584#[cfg(feature = "unstable_llm_providers")]
5585impl ListProvidersRequest {
5586 #[must_use]
5588 pub fn new() -> Self {
5589 Self::default()
5590 }
5591
5592 #[must_use]
5598 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5599 self.meta = meta.into_option();
5600 self
5601 }
5602}
5603
5604#[cfg(feature = "unstable_llm_providers")]
5610#[serde_as]
5611#[skip_serializing_none]
5612#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5613#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5614#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_LIST_METHOD_NAME)))]
5615#[serde(rename_all = "camelCase")]
5616#[non_exhaustive]
5617pub struct ListProvidersResponse {
5618 pub providers: Vec<ProviderInfo>,
5620 #[serde_as(deserialize_as = "DefaultOnError")]
5626 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5627 #[serde(default)]
5628 #[serde(rename = "_meta")]
5629 pub meta: Option<Meta>,
5630}
5631
5632#[cfg(feature = "unstable_llm_providers")]
5633impl ListProvidersResponse {
5634 #[must_use]
5636 pub fn new(providers: Vec<ProviderInfo>) -> Self {
5637 Self {
5638 providers,
5639 meta: None,
5640 }
5641 }
5642
5643 #[must_use]
5649 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5650 self.meta = meta.into_option();
5651 self
5652 }
5653}
5654
5655#[cfg(feature = "unstable_llm_providers")]
5663#[serde_as]
5664#[skip_serializing_none]
5665#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5666#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
5667#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_SET_METHOD_NAME)))]
5668#[serde(rename_all = "camelCase")]
5669#[non_exhaustive]
5670pub struct SetProviderRequest {
5671 pub provider_id: ProviderId,
5673 pub api_type: LlmProtocol,
5675 #[cfg_attr(feature = "schemars", schemars(url))]
5677 pub base_url: String,
5678 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
5681 pub headers: HashMap<String, String>,
5682 #[serde_as(deserialize_as = "DefaultOnError")]
5688 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5689 #[serde(default)]
5690 #[serde(rename = "_meta")]
5691 pub meta: Option<Meta>,
5692}
5693
5694#[cfg(feature = "unstable_llm_providers")]
5695impl SetProviderRequest {
5696 #[must_use]
5698 pub fn new(
5699 provider_id: impl Into<ProviderId>,
5700 api_type: LlmProtocol,
5701 base_url: impl Into<String>,
5702 ) -> Self {
5703 Self {
5704 provider_id: provider_id.into(),
5705 api_type,
5706 base_url: base_url.into(),
5707 headers: HashMap::new(),
5708 meta: None,
5709 }
5710 }
5711
5712 #[must_use]
5715 pub fn headers(mut self, headers: HashMap<String, String>) -> Self {
5716 self.headers = headers;
5717 self
5718 }
5719
5720 #[must_use]
5726 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5727 self.meta = meta.into_option();
5728 self
5729 }
5730}
5731
5732#[cfg(feature = "unstable_llm_providers")]
5733crate::serde_util::default_on_null! {
5734 #[serde_as]
5740 #[skip_serializing_none]
5741 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5742 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
5743 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_SET_METHOD_NAME)))]
5744 #[serde(rename_all = "camelCase")]
5745 #[non_exhaustive]
5746 pub struct SetProviderResponse {
5747 #[serde_as(deserialize_as = "DefaultOnError")]
5753 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5754 #[serde(default)]
5755 #[serde(rename = "_meta")]
5756 pub meta: Option<Meta>,
5757 }
5758}
5759
5760#[cfg(feature = "unstable_llm_providers")]
5761impl SetProviderResponse {
5762 #[must_use]
5764 pub fn new() -> Self {
5765 Self::default()
5766 }
5767
5768 #[must_use]
5774 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5775 self.meta = meta.into_option();
5776 self
5777 }
5778}
5779
5780#[cfg(feature = "unstable_llm_providers")]
5786#[serde_as]
5787#[skip_serializing_none]
5788#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5789#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5790#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_DISABLE_METHOD_NAME)))]
5791#[serde(rename_all = "camelCase")]
5792#[non_exhaustive]
5793pub struct DisableProviderRequest {
5794 pub provider_id: ProviderId,
5796 #[serde_as(deserialize_as = "DefaultOnError")]
5802 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5803 #[serde(default)]
5804 #[serde(rename = "_meta")]
5805 pub meta: Option<Meta>,
5806}
5807
5808#[cfg(feature = "unstable_llm_providers")]
5809impl DisableProviderRequest {
5810 #[must_use]
5812 pub fn new(provider_id: impl Into<ProviderId>) -> Self {
5813 Self {
5814 provider_id: provider_id.into(),
5815 meta: None,
5816 }
5817 }
5818
5819 #[must_use]
5825 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5826 self.meta = meta.into_option();
5827 self
5828 }
5829}
5830
5831#[cfg(feature = "unstable_llm_providers")]
5832crate::serde_util::default_on_null! {
5833 #[serde_as]
5839 #[skip_serializing_none]
5840 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5841 #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
5842 #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_DISABLE_METHOD_NAME)))]
5843 #[serde(rename_all = "camelCase")]
5844 #[non_exhaustive]
5845 pub struct DisableProviderResponse {
5846 #[serde_as(deserialize_as = "DefaultOnError")]
5852 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5853 #[serde(default)]
5854 #[serde(rename = "_meta")]
5855 pub meta: Option<Meta>,
5856 }
5857}
5858
5859#[cfg(feature = "unstable_llm_providers")]
5860impl DisableProviderResponse {
5861 #[must_use]
5863 pub fn new() -> Self {
5864 Self::default()
5865 }
5866
5867 #[must_use]
5873 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5874 self.meta = meta.into_option();
5875 self
5876 }
5877}
5878
5879#[serde_as]
5888#[skip_serializing_none]
5889#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5890#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5891#[serde(rename_all = "camelCase")]
5892#[non_exhaustive]
5893pub struct AgentCapabilities {
5894 #[serde_as(deserialize_as = "DefaultOnError")]
5902 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5903 #[serde(default)]
5904 pub session: Option<SessionCapabilities>,
5905 #[serde_as(deserialize_as = "DefaultOnError")]
5912 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5913 #[serde(default)]
5914 pub auth: Option<AgentAuthCapabilities>,
5915 #[cfg(feature = "unstable_llm_providers")]
5924 #[serde_as(deserialize_as = "DefaultOnError")]
5925 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5926 #[serde(default)]
5927 pub providers: Option<ProvidersCapabilities>,
5928 #[serde_as(deserialize_as = "DefaultOnError")]
5934 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5935 #[serde(default)]
5936 #[serde(rename = "_meta")]
5937 pub meta: Option<Meta>,
5938}
5939
5940impl AgentCapabilities {
5941 #[must_use]
5943 pub fn new() -> Self {
5944 Self::default()
5945 }
5946
5947 #[must_use]
5955 pub fn session(mut self, session: impl IntoOption<SessionCapabilities>) -> Self {
5956 self.session = session.into_option();
5957 self
5958 }
5959
5960 #[must_use]
5964 pub fn auth(mut self, auth: impl IntoOption<AgentAuthCapabilities>) -> Self {
5965 self.auth = auth.into_option();
5966 self
5967 }
5968
5969 #[cfg(feature = "unstable_llm_providers")]
5975 #[must_use]
5976 pub fn providers(mut self, providers: impl IntoOption<ProvidersCapabilities>) -> Self {
5977 self.providers = providers.into_option();
5978 self
5979 }
5980
5981 #[must_use]
5987 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5988 self.meta = meta.into_option();
5989 self
5990 }
5991}
5992
5993#[cfg(feature = "unstable_llm_providers")]
6001#[serde_as]
6002#[skip_serializing_none]
6003#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6004#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6005#[non_exhaustive]
6006pub struct ProvidersCapabilities {
6007 #[serde_as(deserialize_as = "DefaultOnError")]
6013 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6014 #[serde(default)]
6015 #[serde(rename = "_meta")]
6016 pub meta: Option<Meta>,
6017}
6018
6019#[cfg(feature = "unstable_llm_providers")]
6020impl ProvidersCapabilities {
6021 #[must_use]
6023 pub fn new() -> Self {
6024 Self::default()
6025 }
6026
6027 #[must_use]
6033 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6034 self.meta = meta.into_option();
6035 self
6036 }
6037}
6038
6039#[serde_as]
6051#[skip_serializing_none]
6052#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6053#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6054#[serde(rename_all = "camelCase")]
6055#[non_exhaustive]
6056pub struct SessionCapabilities {
6057 #[serde_as(deserialize_as = "DefaultOnError")]
6063 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6064 #[serde(default)]
6065 pub prompt: Option<PromptCapabilities>,
6066 #[serde_as(deserialize_as = "DefaultOnError")]
6071 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6072 #[serde(default)]
6073 pub mcp: Option<McpCapabilities>,
6074 #[serde_as(deserialize_as = "DefaultOnError")]
6079 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6080 #[serde(default)]
6081 pub delete: Option<SessionDeleteCapabilities>,
6082 #[serde_as(deserialize_as = "DefaultOnError")]
6091 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6092 #[serde(default)]
6093 pub additional_directories: Option<SessionAdditionalDirectoriesCapabilities>,
6094 #[serde_as(deserialize_as = "DefaultOnError")]
6099 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6100 #[serde(default)]
6101 pub system_prompt: Option<SessionSystemPromptCapabilities>,
6102 #[cfg(feature = "unstable_session_fork")]
6111 #[serde_as(deserialize_as = "DefaultOnError")]
6112 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6113 #[serde(default)]
6114 pub fork: Option<SessionForkCapabilities>,
6115 #[cfg(feature = "unstable_session_archive")]
6125 #[serde_as(deserialize_as = "DefaultOnError")]
6126 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6127 #[serde(default)]
6128 pub archive: Option<SessionArchiveCapabilities>,
6129 #[cfg(feature = "unstable_session_status")]
6138 #[serde_as(deserialize_as = "DefaultOnError")]
6139 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6140 #[serde(default)]
6141 pub status: Option<SessionStatusCapabilities>,
6142 #[cfg(feature = "unstable_session_options")]
6152 #[serde_as(deserialize_as = "DefaultOnError")]
6153 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6154 #[serde(default)]
6155 pub options: Option<SessionOptionsCapabilities>,
6156 #[cfg(feature = "unstable_session_set_title")]
6168 #[serde_as(deserialize_as = "DefaultOnError")]
6169 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6170 #[serde(default)]
6171 pub title: Option<SessionTitleCapabilities>,
6172 #[serde_as(deserialize_as = "DefaultOnError")]
6178 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6179 #[serde(default)]
6180 #[serde(rename = "_meta")]
6181 pub meta: Option<Meta>,
6182}
6183
6184impl SessionCapabilities {
6185 #[must_use]
6187 pub fn new() -> Self {
6188 Self::default()
6189 }
6190
6191 #[must_use]
6197 pub fn prompt(mut self, prompt: impl IntoOption<PromptCapabilities>) -> Self {
6198 self.prompt = prompt.into_option();
6199 self
6200 }
6201
6202 #[must_use]
6207 pub fn mcp(mut self, mcp: impl IntoOption<McpCapabilities>) -> Self {
6208 self.mcp = mcp.into_option();
6209 self
6210 }
6211
6212 #[must_use]
6217 pub fn delete(mut self, delete: impl IntoOption<SessionDeleteCapabilities>) -> Self {
6218 self.delete = delete.into_option();
6219 self
6220 }
6221
6222 #[must_use]
6231 pub fn additional_directories(
6232 mut self,
6233 additional_directories: impl IntoOption<SessionAdditionalDirectoriesCapabilities>,
6234 ) -> Self {
6235 self.additional_directories = additional_directories.into_option();
6236 self
6237 }
6238
6239 #[must_use]
6244 pub fn system_prompt(
6245 mut self,
6246 system_prompt: impl IntoOption<SessionSystemPromptCapabilities>,
6247 ) -> Self {
6248 self.system_prompt = system_prompt.into_option();
6249 self
6250 }
6251
6252 #[cfg(feature = "unstable_session_fork")]
6253 #[must_use]
6258 pub fn fork(mut self, fork: impl IntoOption<SessionForkCapabilities>) -> Self {
6259 self.fork = fork.into_option();
6260 self
6261 }
6262
6263 #[cfg(feature = "unstable_session_archive")]
6273 #[must_use]
6274 pub fn archive(mut self, archive: impl IntoOption<SessionArchiveCapabilities>) -> Self {
6275 self.archive = archive.into_option();
6276 self
6277 }
6278
6279 #[cfg(feature = "unstable_session_status")]
6288 #[must_use]
6289 pub fn status(mut self, status: impl IntoOption<SessionStatusCapabilities>) -> Self {
6290 self.status = status.into_option();
6291 self
6292 }
6293
6294 #[cfg(feature = "unstable_session_options")]
6304 #[must_use]
6305 pub fn options(mut self, options: impl IntoOption<SessionOptionsCapabilities>) -> Self {
6306 self.options = options.into_option();
6307 self
6308 }
6309
6310 #[cfg(feature = "unstable_session_set_title")]
6322 #[must_use]
6323 pub fn title(mut self, title: impl IntoOption<SessionTitleCapabilities>) -> Self {
6324 self.title = title.into_option();
6325 self
6326 }
6327
6328 #[must_use]
6334 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6335 self.meta = meta.into_option();
6336 self
6337 }
6338}
6339
6340#[serde_as]
6344#[skip_serializing_none]
6345#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6346#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6347#[non_exhaustive]
6348pub struct SessionDeleteCapabilities {
6349 #[serde_as(deserialize_as = "DefaultOnError")]
6355 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6356 #[serde(default)]
6357 #[serde(rename = "_meta")]
6358 pub meta: Option<Meta>,
6359}
6360
6361impl SessionDeleteCapabilities {
6362 #[must_use]
6364 pub fn new() -> Self {
6365 Self::default()
6366 }
6367
6368 #[must_use]
6374 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6375 self.meta = meta.into_option();
6376 self
6377 }
6378}
6379
6380#[serde_as]
6387#[skip_serializing_none]
6388#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6389#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6390#[non_exhaustive]
6391pub struct SessionAdditionalDirectoriesCapabilities {
6392 #[serde_as(deserialize_as = "DefaultOnError")]
6398 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6399 #[serde(default)]
6400 #[serde(rename = "_meta")]
6401 pub meta: Option<Meta>,
6402}
6403
6404impl SessionAdditionalDirectoriesCapabilities {
6405 #[must_use]
6407 pub fn new() -> Self {
6408 Self::default()
6409 }
6410
6411 #[must_use]
6417 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6418 self.meta = meta.into_option();
6419 self
6420 }
6421}
6422
6423#[serde_as]
6428#[skip_serializing_none]
6429#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6430#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6431#[serde(rename_all = "camelCase")]
6432#[non_exhaustive]
6433pub struct SessionSystemPromptCapabilities {
6434 #[serde_as(deserialize_as = "DefaultOnError")]
6438 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6439 #[serde(default)]
6440 pub mode: Option<SessionSystemPromptModeCapabilities>,
6441 #[serde_as(deserialize_as = "DefaultOnError")]
6447 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6448 #[serde(default)]
6449 #[serde(rename = "_meta")]
6450 pub meta: Option<Meta>,
6451}
6452
6453impl SessionSystemPromptCapabilities {
6454 #[must_use]
6456 pub fn new() -> Self {
6457 Self::default()
6458 }
6459
6460 #[must_use]
6464 pub fn mode(mut self, mode: impl IntoOption<SessionSystemPromptModeCapabilities>) -> Self {
6465 self.mode = mode.into_option();
6466 self
6467 }
6468
6469 #[must_use]
6475 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6476 self.meta = meta.into_option();
6477 self
6478 }
6479}
6480
6481#[serde_as]
6486#[skip_serializing_none]
6487#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6488#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6489#[serde(rename_all = "camelCase")]
6490#[non_exhaustive]
6491pub struct SessionSystemPromptModeCapabilities {
6492 #[serde_as(deserialize_as = "DefaultOnError")]
6498 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6499 #[serde(default, rename = "override")]
6500 pub override_: Option<SessionSystemPromptOverrideCapabilities>,
6501 #[serde_as(deserialize_as = "DefaultOnError")]
6507 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6508 #[serde(default)]
6509 #[serde(rename = "_meta")]
6510 pub meta: Option<Meta>,
6511}
6512
6513impl SessionSystemPromptModeCapabilities {
6514 #[must_use]
6516 pub fn new() -> Self {
6517 Self::default()
6518 }
6519
6520 #[must_use]
6526 pub fn override_(
6527 mut self,
6528 override_: impl IntoOption<SessionSystemPromptOverrideCapabilities>,
6529 ) -> Self {
6530 self.override_ = override_.into_option();
6531 self
6532 }
6533
6534 #[must_use]
6540 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6541 self.meta = meta.into_option();
6542 self
6543 }
6544}
6545
6546#[serde_as]
6551#[skip_serializing_none]
6552#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6553#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6554#[non_exhaustive]
6555pub struct SessionSystemPromptOverrideCapabilities {
6556 #[serde_as(deserialize_as = "DefaultOnError")]
6562 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6563 #[serde(default)]
6564 #[serde(rename = "_meta")]
6565 pub meta: Option<Meta>,
6566}
6567
6568impl SessionSystemPromptOverrideCapabilities {
6569 #[must_use]
6571 pub fn new() -> Self {
6572 Self::default()
6573 }
6574
6575 #[must_use]
6581 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6582 self.meta = meta.into_option();
6583 self
6584 }
6585}
6586
6587#[cfg(feature = "unstable_session_fork")]
6595#[serde_as]
6596#[skip_serializing_none]
6597#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6598#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6599#[non_exhaustive]
6600pub struct SessionForkCapabilities {
6601 #[serde_as(deserialize_as = "DefaultOnError")]
6607 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6608 #[serde(default)]
6609 #[serde(rename = "_meta")]
6610 pub meta: Option<Meta>,
6611}
6612
6613#[cfg(feature = "unstable_session_fork")]
6614impl SessionForkCapabilities {
6615 #[must_use]
6617 pub fn new() -> Self {
6618 Self::default()
6619 }
6620
6621 #[must_use]
6627 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6628 self.meta = meta.into_option();
6629 self
6630 }
6631}
6632
6633#[cfg(feature = "unstable_session_archive")]
6642#[serde_as]
6643#[skip_serializing_none]
6644#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6645#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6646#[non_exhaustive]
6647pub struct SessionArchiveCapabilities {
6648 #[serde_as(deserialize_as = "DefaultOnError")]
6654 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6655 #[serde(default)]
6656 #[serde(rename = "_meta")]
6657 pub meta: Option<Meta>,
6658}
6659
6660#[cfg(feature = "unstable_session_archive")]
6661impl SessionArchiveCapabilities {
6662 #[must_use]
6664 pub fn new() -> Self {
6665 Self::default()
6666 }
6667
6668 #[must_use]
6674 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6675 self.meta = meta.into_option();
6676 self
6677 }
6678}
6679
6680#[cfg(feature = "unstable_session_status")]
6688#[serde_as]
6689#[skip_serializing_none]
6690#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6691#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6692#[non_exhaustive]
6693pub struct SessionStatusCapabilities {
6694 #[serde_as(deserialize_as = "DefaultOnError")]
6700 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6701 #[serde(default)]
6702 #[serde(rename = "_meta")]
6703 pub meta: Option<Meta>,
6704}
6705
6706#[cfg(feature = "unstable_session_status")]
6707impl SessionStatusCapabilities {
6708 #[must_use]
6710 pub fn new() -> Self {
6711 Self::default()
6712 }
6713
6714 #[must_use]
6720 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6721 self.meta = meta.into_option();
6722 self
6723 }
6724}
6725
6726#[cfg(feature = "unstable_session_options")]
6735#[serde_as]
6736#[skip_serializing_none]
6737#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6738#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6739#[non_exhaustive]
6740pub struct SessionOptionsCapabilities {
6741 #[serde_as(deserialize_as = "DefaultOnError")]
6747 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6748 #[serde(default)]
6749 #[serde(rename = "_meta")]
6750 pub meta: Option<Meta>,
6751}
6752
6753#[cfg(feature = "unstable_session_options")]
6754impl SessionOptionsCapabilities {
6755 #[must_use]
6757 pub fn new() -> Self {
6758 Self::default()
6759 }
6760
6761 #[must_use]
6767 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6768 self.meta = meta.into_option();
6769 self
6770 }
6771}
6772
6773#[cfg(feature = "unstable_session_set_title")]
6782#[serde_as]
6783#[skip_serializing_none]
6784#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6785#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6786#[non_exhaustive]
6787pub struct SessionTitleCapabilities {
6788 #[serde_as(deserialize_as = "DefaultOnError")]
6794 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6795 #[serde(default)]
6796 #[serde(rename = "_meta")]
6797 pub meta: Option<Meta>,
6798}
6799
6800#[cfg(feature = "unstable_session_set_title")]
6801impl SessionTitleCapabilities {
6802 #[must_use]
6804 pub fn new() -> Self {
6805 Self::default()
6806 }
6807
6808 #[must_use]
6814 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6815 self.meta = meta.into_option();
6816 self
6817 }
6818}
6819
6820#[serde_as]
6833#[skip_serializing_none]
6834#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6835#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6836#[serde(rename_all = "camelCase")]
6837#[non_exhaustive]
6838pub struct PromptCapabilities {
6839 #[serde_as(deserialize_as = "DefaultOnError")]
6844 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6845 #[serde(default)]
6846 pub image: Option<PromptImageCapabilities>,
6847 #[serde_as(deserialize_as = "DefaultOnError")]
6852 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6853 #[serde(default)]
6854 pub audio: Option<PromptAudioCapabilities>,
6855 #[serde_as(deserialize_as = "DefaultOnError")]
6863 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6864 #[serde(default)]
6865 pub embedded_context: Option<PromptEmbeddedContextCapabilities>,
6866 #[serde_as(deserialize_as = "DefaultOnError")]
6872 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6873 #[serde(default)]
6874 #[serde(rename = "_meta")]
6875 pub meta: Option<Meta>,
6876}
6877
6878impl PromptCapabilities {
6879 #[must_use]
6881 pub fn new() -> Self {
6882 Self::default()
6883 }
6884
6885 #[must_use]
6890 pub fn image(mut self, image: impl IntoOption<PromptImageCapabilities>) -> Self {
6891 self.image = image.into_option();
6892 self
6893 }
6894
6895 #[must_use]
6900 pub fn audio(mut self, audio: impl IntoOption<PromptAudioCapabilities>) -> Self {
6901 self.audio = audio.into_option();
6902 self
6903 }
6904
6905 #[must_use]
6913 pub fn embedded_context(
6914 mut self,
6915 embedded_context: impl IntoOption<PromptEmbeddedContextCapabilities>,
6916 ) -> Self {
6917 self.embedded_context = embedded_context.into_option();
6918 self
6919 }
6920
6921 #[must_use]
6927 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6928 self.meta = meta.into_option();
6929 self
6930 }
6931}
6932
6933#[serde_as]
6937#[skip_serializing_none]
6938#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6939#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6940#[non_exhaustive]
6941pub struct PromptImageCapabilities {
6942 #[serde_as(deserialize_as = "DefaultOnError")]
6948 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6949 #[serde(default)]
6950 #[serde(rename = "_meta")]
6951 pub meta: Option<Meta>,
6952}
6953
6954impl PromptImageCapabilities {
6955 #[must_use]
6957 pub fn new() -> Self {
6958 Self::default()
6959 }
6960
6961 #[must_use]
6967 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6968 self.meta = meta.into_option();
6969 self
6970 }
6971}
6972
6973#[serde_as]
6977#[skip_serializing_none]
6978#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6979#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6980#[non_exhaustive]
6981pub struct PromptAudioCapabilities {
6982 #[serde_as(deserialize_as = "DefaultOnError")]
6988 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6989 #[serde(default)]
6990 #[serde(rename = "_meta")]
6991 pub meta: Option<Meta>,
6992}
6993
6994impl PromptAudioCapabilities {
6995 #[must_use]
6997 pub fn new() -> Self {
6998 Self::default()
6999 }
7000
7001 #[must_use]
7007 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7008 self.meta = meta.into_option();
7009 self
7010 }
7011}
7012
7013#[serde_as]
7017#[skip_serializing_none]
7018#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7019#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7020#[non_exhaustive]
7021pub struct PromptEmbeddedContextCapabilities {
7022 #[serde_as(deserialize_as = "DefaultOnError")]
7028 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7029 #[serde(default)]
7030 #[serde(rename = "_meta")]
7031 pub meta: Option<Meta>,
7032}
7033
7034impl PromptEmbeddedContextCapabilities {
7035 #[must_use]
7037 pub fn new() -> Self {
7038 Self::default()
7039 }
7040
7041 #[must_use]
7047 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7048 self.meta = meta.into_option();
7049 self
7050 }
7051}
7052
7053#[serde_as]
7055#[skip_serializing_none]
7056#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7057#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7058#[serde(rename_all = "camelCase")]
7059#[non_exhaustive]
7060pub struct McpCapabilities {
7061 #[serde_as(deserialize_as = "DefaultOnError")]
7066 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7067 #[serde(default)]
7068 pub stdio: Option<McpStdioCapabilities>,
7069 #[serde_as(deserialize_as = "DefaultOnError")]
7074 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7075 #[serde(default)]
7076 pub http: Option<McpHttpCapabilities>,
7077 #[cfg(feature = "unstable_mcp_over_acp")]
7086 #[serde_as(deserialize_as = "DefaultOnError")]
7087 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7088 #[serde(default)]
7089 pub acp: Option<McpAcpCapabilities>,
7090 #[serde_as(deserialize_as = "DefaultOnError")]
7096 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7097 #[serde(default)]
7098 #[serde(rename = "_meta")]
7099 pub meta: Option<Meta>,
7100}
7101
7102impl McpCapabilities {
7103 #[must_use]
7105 pub fn new() -> Self {
7106 Self::default()
7107 }
7108
7109 #[must_use]
7114 pub fn stdio(mut self, stdio: impl IntoOption<McpStdioCapabilities>) -> Self {
7115 self.stdio = stdio.into_option();
7116 self
7117 }
7118
7119 #[must_use]
7124 pub fn http(mut self, http: impl IntoOption<McpHttpCapabilities>) -> Self {
7125 self.http = http.into_option();
7126 self
7127 }
7128
7129 #[cfg(feature = "unstable_mcp_over_acp")]
7135 #[must_use]
7139 pub fn acp(mut self, acp: impl IntoOption<McpAcpCapabilities>) -> Self {
7140 self.acp = acp.into_option();
7141 self
7142 }
7143
7144 #[must_use]
7150 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7151 self.meta = meta.into_option();
7152 self
7153 }
7154}
7155
7156#[serde_as]
7160#[skip_serializing_none]
7161#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7162#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7163#[non_exhaustive]
7164pub struct McpStdioCapabilities {
7165 #[serde_as(deserialize_as = "DefaultOnError")]
7171 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7172 #[serde(default)]
7173 #[serde(rename = "_meta")]
7174 pub meta: Option<Meta>,
7175}
7176
7177impl McpStdioCapabilities {
7178 #[must_use]
7180 pub fn new() -> Self {
7181 Self::default()
7182 }
7183
7184 #[must_use]
7190 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7191 self.meta = meta.into_option();
7192 self
7193 }
7194}
7195
7196#[serde_as]
7200#[skip_serializing_none]
7201#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7202#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7203#[non_exhaustive]
7204pub struct McpHttpCapabilities {
7205 #[serde_as(deserialize_as = "DefaultOnError")]
7211 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7212 #[serde(default)]
7213 #[serde(rename = "_meta")]
7214 pub meta: Option<Meta>,
7215}
7216
7217impl McpHttpCapabilities {
7218 #[must_use]
7220 pub fn new() -> Self {
7221 Self::default()
7222 }
7223
7224 #[must_use]
7230 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7231 self.meta = meta.into_option();
7232 self
7233 }
7234}
7235
7236#[cfg(feature = "unstable_mcp_over_acp")]
7244#[serde_as]
7245#[skip_serializing_none]
7246#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7247#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7248#[non_exhaustive]
7249pub struct McpAcpCapabilities {
7250 #[serde_as(deserialize_as = "DefaultOnError")]
7256 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7257 #[serde(default)]
7258 #[serde(rename = "_meta")]
7259 pub meta: Option<Meta>,
7260}
7261
7262#[cfg(feature = "unstable_mcp_over_acp")]
7263impl McpAcpCapabilities {
7264 #[must_use]
7266 pub fn new() -> Self {
7267 Self::default()
7268 }
7269
7270 #[must_use]
7276 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7277 self.meta = meta.into_option();
7278 self
7279 }
7280}
7281
7282#[serde_as]
7286#[skip_serializing_none]
7287#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7288#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7289#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CANCEL_METHOD_NAME)))]
7290#[serde(rename_all = "camelCase")]
7291#[non_exhaustive]
7292pub struct CancelSessionNotification {
7293 pub session_id: SessionId,
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 CancelSessionNotification {
7308 #[must_use]
7310 pub fn new(session_id: impl Into<SessionId>) -> Self {
7311 Self {
7312 session_id: session_id.into(),
7313 meta: None,
7314 }
7315 }
7316
7317 #[must_use]
7323 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7324 self.meta = meta.into_option();
7325 self
7326 }
7327}
7328
7329#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7335#[non_exhaustive]
7336pub struct AgentMethodNames {
7337 pub initialize: &'static str,
7339 pub auth_login: &'static str,
7341 #[cfg(feature = "unstable_llm_providers")]
7343 pub providers_list: &'static str,
7344 #[cfg(feature = "unstable_llm_providers")]
7346 pub providers_set: &'static str,
7347 #[cfg(feature = "unstable_llm_providers")]
7349 pub providers_disable: &'static str,
7350 pub session_new: &'static str,
7352 pub session_set_config_option: &'static str,
7354 pub session_prompt: &'static str,
7356 pub session_cancel: &'static str,
7358 #[cfg(feature = "unstable_mcp_over_acp")]
7360 pub mcp_message: &'static str,
7361 pub session_list: &'static str,
7363 pub session_delete: &'static str,
7365 #[cfg(feature = "unstable_session_fork")]
7367 pub session_fork: &'static str,
7368 #[cfg(feature = "unstable_session_archive")]
7370 pub session_archive: &'static str,
7371 #[cfg(feature = "unstable_session_archive")]
7373 pub session_unarchive: &'static str,
7374 #[cfg(feature = "unstable_session_status")]
7376 pub session_status: &'static str,
7377 #[cfg(feature = "unstable_session_options")]
7379 pub session_options: &'static str,
7380 #[cfg(feature = "unstable_session_set_title")]
7382 pub session_set_title: &'static str,
7383 pub session_resume: &'static str,
7385 pub session_close: &'static str,
7387 pub tool_call_cancel: &'static str,
7389 pub terminal_cancel: &'static str,
7391 pub auth_logout: &'static str,
7393 #[cfg(feature = "unstable_auth_status")]
7395 pub auth_status: &'static str,
7396}
7397
7398pub const AGENT_METHOD_NAMES: AgentMethodNames = AgentMethodNames {
7400 initialize: INITIALIZE_METHOD_NAME,
7401 auth_login: AUTH_LOGIN_METHOD_NAME,
7402 #[cfg(feature = "unstable_llm_providers")]
7403 providers_list: PROVIDERS_LIST_METHOD_NAME,
7404 #[cfg(feature = "unstable_llm_providers")]
7405 providers_set: PROVIDERS_SET_METHOD_NAME,
7406 #[cfg(feature = "unstable_llm_providers")]
7407 providers_disable: PROVIDERS_DISABLE_METHOD_NAME,
7408 session_new: SESSION_NEW_METHOD_NAME,
7409 session_set_config_option: SESSION_SET_CONFIG_OPTION_METHOD_NAME,
7410 session_prompt: SESSION_PROMPT_METHOD_NAME,
7411 session_cancel: SESSION_CANCEL_METHOD_NAME,
7412 #[cfg(feature = "unstable_mcp_over_acp")]
7413 mcp_message: MCP_MESSAGE_METHOD_NAME,
7414 session_list: SESSION_LIST_METHOD_NAME,
7415 session_delete: SESSION_DELETE_METHOD_NAME,
7416 #[cfg(feature = "unstable_session_fork")]
7417 session_fork: SESSION_FORK_METHOD_NAME,
7418 #[cfg(feature = "unstable_session_archive")]
7419 session_archive: SESSION_ARCHIVE_METHOD_NAME,
7420 #[cfg(feature = "unstable_session_archive")]
7421 session_unarchive: SESSION_UNARCHIVE_METHOD_NAME,
7422 #[cfg(feature = "unstable_session_status")]
7423 session_status: SESSION_STATUS_METHOD_NAME,
7424 #[cfg(feature = "unstable_session_options")]
7425 session_options: SESSION_OPTIONS_METHOD_NAME,
7426 #[cfg(feature = "unstable_session_set_title")]
7427 session_set_title: SESSION_SET_TITLE_METHOD_NAME,
7428 session_resume: SESSION_RESUME_METHOD_NAME,
7429 session_close: SESSION_CLOSE_METHOD_NAME,
7430 tool_call_cancel: TOOL_CALL_CANCEL_METHOD_NAME,
7431 terminal_cancel: TERMINAL_CANCEL_METHOD_NAME,
7432 auth_logout: AUTH_LOGOUT_METHOD_NAME,
7433 #[cfg(feature = "unstable_auth_status")]
7434 auth_status: AUTH_STATUS_METHOD_NAME,
7435};
7436
7437pub(crate) const INITIALIZE_METHOD_NAME: &str = "initialize";
7439pub(crate) const AUTH_LOGIN_METHOD_NAME: &str = "auth/login";
7441#[cfg(feature = "unstable_llm_providers")]
7443pub(crate) const PROVIDERS_LIST_METHOD_NAME: &str = "providers/list";
7444#[cfg(feature = "unstable_llm_providers")]
7446pub(crate) const PROVIDERS_SET_METHOD_NAME: &str = "providers/set";
7447#[cfg(feature = "unstable_llm_providers")]
7449pub(crate) const PROVIDERS_DISABLE_METHOD_NAME: &str = "providers/disable";
7450pub(crate) const SESSION_NEW_METHOD_NAME: &str = "session/new";
7452pub(crate) const SESSION_SET_CONFIG_OPTION_METHOD_NAME: &str = "session/set_config_option";
7454pub(crate) const SESSION_PROMPT_METHOD_NAME: &str = "session/prompt";
7456pub(crate) const SESSION_CANCEL_METHOD_NAME: &str = "session/cancel";
7458pub(crate) const SESSION_LIST_METHOD_NAME: &str = "session/list";
7460pub(crate) const SESSION_DELETE_METHOD_NAME: &str = "session/delete";
7462#[cfg(feature = "unstable_session_fork")]
7464pub(crate) const SESSION_FORK_METHOD_NAME: &str = "session/fork";
7465#[cfg(feature = "unstable_session_archive")]
7467pub(crate) const SESSION_ARCHIVE_METHOD_NAME: &str = "session/archive";
7468#[cfg(feature = "unstable_session_archive")]
7470pub(crate) const SESSION_UNARCHIVE_METHOD_NAME: &str = "session/unarchive";
7471#[cfg(feature = "unstable_session_status")]
7473pub(crate) const SESSION_STATUS_METHOD_NAME: &str = "session/status";
7474#[cfg(feature = "unstable_session_options")]
7476pub(crate) const SESSION_OPTIONS_METHOD_NAME: &str = "session/options";
7477#[cfg(feature = "unstable_session_set_title")]
7479pub(crate) const SESSION_SET_TITLE_METHOD_NAME: &str = "session/set_title";
7480pub(crate) const SESSION_RESUME_METHOD_NAME: &str = "session/resume";
7482pub(crate) const SESSION_CLOSE_METHOD_NAME: &str = "session/close";
7484pub(crate) const TOOL_CALL_CANCEL_METHOD_NAME: &str = "tool_call/cancel";
7486pub(crate) const TERMINAL_CANCEL_METHOD_NAME: &str = "terminal/cancel";
7488pub(crate) const AUTH_LOGOUT_METHOD_NAME: &str = "auth/logout";
7490#[cfg(feature = "unstable_auth_status")]
7492pub(crate) const AUTH_STATUS_METHOD_NAME: &str = "auth/status";
7493
7494#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7501#[derive(Clone, Debug, Serialize, Deserialize)]
7502#[serde(untagged)]
7503#[cfg_attr(feature = "schemars", schemars(inline))]
7504#[non_exhaustive]
7505pub enum ClientRequest {
7506 InitializeRequest(Box<InitializeRequest>),
7520 LoginAuthRequest(Box<LoginAuthRequest>),
7535 #[cfg(feature = "unstable_llm_providers")]
7541 ListProvidersRequest(Box<ListProvidersRequest>),
7542 #[cfg(feature = "unstable_llm_providers")]
7548 SetProviderRequest(Box<SetProviderRequest>),
7549 #[cfg(feature = "unstable_llm_providers")]
7555 DisableProviderRequest(Box<DisableProviderRequest>),
7556 LogoutAuthRequest(Box<LogoutAuthRequest>),
7566 #[cfg(feature = "unstable_auth_status")]
7575 AuthStatusRequest(Box<AuthStatusRequest>),
7576 NewSessionRequest(Box<NewSessionRequest>),
7589 ListSessionsRequest(Box<ListSessionsRequest>),
7593 DeleteSessionRequest(Box<DeleteSessionRequest>),
7597 #[cfg(feature = "unstable_session_fork")]
7598 ForkSessionRequest(Box<ForkSessionRequest>),
7614 #[cfg(feature = "unstable_session_archive")]
7615 ArchiveSessionRequest(Box<ArchiveSessionRequest>),
7623 #[cfg(feature = "unstable_session_archive")]
7624 UnarchiveSessionRequest(Box<UnarchiveSessionRequest>),
7632 #[cfg(feature = "unstable_session_status")]
7633 SessionStatusRequest(Box<SessionStatusRequest>),
7641 #[cfg(feature = "unstable_session_options")]
7642 SessionOptionsRequest(Box<SessionOptionsRequest>),
7650 #[cfg(feature = "unstable_session_set_title")]
7651 SetSessionTitleRequest(Box<SetSessionTitleRequest>),
7662 ResumeSessionRequest(Box<ResumeSessionRequest>),
7668 CloseSessionRequest(Box<CloseSessionRequest>),
7673 CancelToolCallRequest(Box<CancelToolCallRequest>),
7679 CancelTerminalRequest(Box<CancelTerminalRequest>),
7685 SetSessionConfigOptionRequest(Box<SetSessionConfigOptionRequest>),
7687 PromptRequest(Box<PromptRequest>),
7709 ExtMethodRequest(Box<ExtRequest>),
7716}
7717
7718impl ClientRequest {
7719 #[must_use]
7721 pub fn method(&self) -> &str {
7722 match self {
7723 Self::InitializeRequest(_) => AGENT_METHOD_NAMES.initialize,
7724 Self::LoginAuthRequest(_) => AGENT_METHOD_NAMES.auth_login,
7725 #[cfg(feature = "unstable_llm_providers")]
7726 Self::ListProvidersRequest(_) => AGENT_METHOD_NAMES.providers_list,
7727 #[cfg(feature = "unstable_llm_providers")]
7728 Self::SetProviderRequest(_) => AGENT_METHOD_NAMES.providers_set,
7729 #[cfg(feature = "unstable_llm_providers")]
7730 Self::DisableProviderRequest(_) => AGENT_METHOD_NAMES.providers_disable,
7731 Self::LogoutAuthRequest(_) => AGENT_METHOD_NAMES.auth_logout,
7732 #[cfg(feature = "unstable_auth_status")]
7733 Self::AuthStatusRequest(_) => AGENT_METHOD_NAMES.auth_status,
7734 Self::NewSessionRequest(_) => AGENT_METHOD_NAMES.session_new,
7735 Self::ListSessionsRequest(_) => AGENT_METHOD_NAMES.session_list,
7736 Self::DeleteSessionRequest(_) => AGENT_METHOD_NAMES.session_delete,
7737 #[cfg(feature = "unstable_session_fork")]
7738 Self::ForkSessionRequest(_) => AGENT_METHOD_NAMES.session_fork,
7739 #[cfg(feature = "unstable_session_archive")]
7740 Self::ArchiveSessionRequest(_) => AGENT_METHOD_NAMES.session_archive,
7741 #[cfg(feature = "unstable_session_archive")]
7742 Self::UnarchiveSessionRequest(_) => AGENT_METHOD_NAMES.session_unarchive,
7743 #[cfg(feature = "unstable_session_status")]
7744 Self::SessionStatusRequest(_) => AGENT_METHOD_NAMES.session_status,
7745 #[cfg(feature = "unstable_session_options")]
7746 Self::SessionOptionsRequest(_) => AGENT_METHOD_NAMES.session_options,
7747 #[cfg(feature = "unstable_session_set_title")]
7748 Self::SetSessionTitleRequest(_) => AGENT_METHOD_NAMES.session_set_title,
7749 Self::ResumeSessionRequest(_) => AGENT_METHOD_NAMES.session_resume,
7750 Self::CloseSessionRequest(_) => AGENT_METHOD_NAMES.session_close,
7751 Self::CancelToolCallRequest(_) => AGENT_METHOD_NAMES.tool_call_cancel,
7752 Self::CancelTerminalRequest(_) => AGENT_METHOD_NAMES.terminal_cancel,
7753 Self::SetSessionConfigOptionRequest(_) => AGENT_METHOD_NAMES.session_set_config_option,
7754 Self::PromptRequest(_) => AGENT_METHOD_NAMES.session_prompt,
7755 Self::ExtMethodRequest(ext_request) => &ext_request.method,
7756 }
7757 }
7758}
7759
7760#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7767#[derive(Clone, Debug, Serialize, Deserialize)]
7768#[serde(untagged)]
7769#[cfg_attr(feature = "schemars", schemars(inline))]
7770#[non_exhaustive]
7771pub enum AgentResponse {
7772 InitializeResponse(Box<InitializeResponse>),
7774 LoginAuthResponse(#[serde(default)] Box<LoginAuthResponse>),
7776 #[cfg(feature = "unstable_llm_providers")]
7778 ListProvidersResponse(Box<ListProvidersResponse>),
7779 #[cfg(feature = "unstable_llm_providers")]
7781 SetProviderResponse(#[serde(default)] Box<SetProviderResponse>),
7782 #[cfg(feature = "unstable_llm_providers")]
7784 DisableProviderResponse(#[serde(default)] Box<DisableProviderResponse>),
7785 LogoutAuthResponse(#[serde(default)] Box<LogoutAuthResponse>),
7787 #[cfg(feature = "unstable_auth_status")]
7789 AuthStatusResponse(Box<AuthStatusResponse>),
7790 NewSessionResponse(Box<NewSessionResponse>),
7792 ListSessionsResponse(Box<ListSessionsResponse>),
7794 DeleteSessionResponse(#[serde(default)] Box<DeleteSessionResponse>),
7796 #[cfg(feature = "unstable_session_fork")]
7798 ForkSessionResponse(Box<ForkSessionResponse>),
7799 #[cfg(feature = "unstable_session_archive")]
7801 ArchiveSessionResponse(#[serde(default)] Box<ArchiveSessionResponse>),
7802 #[cfg(feature = "unstable_session_archive")]
7804 UnarchiveSessionResponse(#[serde(default)] Box<UnarchiveSessionResponse>),
7805 #[cfg(feature = "unstable_session_status")]
7807 SessionStatusResponse(Box<SessionStatusResponse>),
7808 #[cfg(feature = "unstable_session_options")]
7810 SessionOptionsResponse(#[serde(default)] Box<SessionOptionsResponse>),
7811 #[cfg(feature = "unstable_session_set_title")]
7813 SetSessionTitleResponse(Box<SetSessionTitleResponse>),
7814 ResumeSessionResponse(#[serde(default)] Box<ResumeSessionResponse>),
7816 CloseSessionResponse(#[serde(default)] Box<CloseSessionResponse>),
7818 CancelToolCallResponse(#[serde(default)] Box<CancelToolCallResponse>),
7820 CancelTerminalResponse(#[serde(default)] Box<CancelTerminalResponse>),
7822 SetSessionConfigOptionResponse(Box<SetSessionConfigOptionResponse>),
7824 PromptResponse(Box<PromptResponse>),
7826 ExtMethodResponse(Box<ExtResponse>),
7828}
7829
7830#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7837#[derive(Clone, Debug, Serialize, Deserialize)]
7838#[serde(untagged)]
7839#[cfg_attr(feature = "schemars", schemars(inline))]
7840#[non_exhaustive]
7841pub enum ClientNotification {
7842 CancelSessionNotification(Box<CancelSessionNotification>),
7873 #[cfg(feature = "unstable_mcp_over_acp")]
7879 MessageMcpNotification(Box<MessageMcpNotification>),
7880 ExtNotification(Box<ExtNotification>),
7887}
7888
7889impl ClientNotification {
7890 #[must_use]
7892 pub fn method(&self) -> &str {
7893 match self {
7894 Self::CancelSessionNotification(_) => AGENT_METHOD_NAMES.session_cancel,
7895 #[cfg(feature = "unstable_mcp_over_acp")]
7896 Self::MessageMcpNotification(_) => AGENT_METHOD_NAMES.mcp_message,
7897 Self::ExtNotification(ext_notification) => &ext_notification.method,
7898 }
7899 }
7900}
7901
7902#[cfg(test)]
7903mod test_serialization {
7904 use std::path::PathBuf;
7905
7906 use super::*;
7907 use serde_json::json;
7908
7909 fn test_meta() -> Meta {
7910 json!({ "source": "test" }).as_object().unwrap().clone()
7911 }
7912
7913 #[test]
7914 fn list_sessions_cursor_and_session_directories_are_strict() {
7915 for cursor in [json!(null), json!("next")] {
7916 let response = json!({ "sessions": [], "nextCursor": cursor });
7917 serde_json::from_value::<ListSessionsResponse>(response).unwrap();
7918 }
7919 let malformed = json!({ "sessions": [], "nextCursor": 42 });
7920 assert!(serde_json::from_value::<ListSessionsResponse>(malformed).is_err());
7921
7922 let session = |dirs: serde_json::Value| json!({ "sessionId": "s", "cwd": "/w", "additionalDirectories": dirs });
7923 let info: SessionInfo = serde_json::from_value(session(json!(null))).unwrap();
7924 assert_eq!(info.additional_directories, Vec::<AbsolutePath>::new());
7925 for bad in [json!(["/a", 42]), json!("/a")] {
7926 assert!(serde_json::from_value::<SessionInfo>(session(bad)).is_err());
7927 }
7928 let response = json!({ "sessions": [session(json!(["/a", 42]))] });
7930 let response: ListSessionsResponse = serde_json::from_value(response).unwrap();
7931 assert_eq!(response.sessions, Vec::<SessionInfo>::new());
7932 }
7933
7934 #[test]
7935 fn other_fallbacks_preserve_optional_fields_verbatim() {
7936 let valid = json!({ "type": "_custom", "methodId": "m", "name": "M",
7937 "description": "d", "_meta": { "k": 1 } });
7938 let method: AuthMethod = serde_json::from_value(valid.clone()).unwrap();
7939 assert_eq!(method.description(), Some("d"));
7940 assert_eq!(
7941 method.meta(),
7942 Some(&json!({ "k": 1 }).as_object().unwrap().clone())
7943 );
7944 assert_eq!(serde_json::to_value(&method).unwrap(), valid);
7945
7946 let malformed = json!({ "type": "_custom", "methodId": "m", "name": "M",
7948 "description": 42, "_meta": "bad", "extra": true });
7949 let method: AuthMethod = serde_json::from_value(malformed.clone()).unwrap();
7950 assert_eq!(method.description(), None);
7951 assert_eq!(method.meta(), None);
7952 assert_eq!(serde_json::to_value(&method).unwrap(), malformed);
7953
7954 let replay = json!({ "type": "_custom", "_meta": "bad", "cursor": 3 });
7955 let decoded: ReplayFrom = serde_json::from_value(replay.clone()).unwrap();
7956 assert_eq!(serde_json::to_value(&decoded).unwrap(), replay);
7957 }
7958
7959 fn serialized_meta_key_count(value: &impl serde::Serialize) -> usize {
7960 serde_json::to_string(value)
7961 .unwrap()
7962 .matches("\"_meta\"")
7963 .count()
7964 }
7965
7966 #[test]
7967 fn prompt_response_without_metadata_round_trips() {
7968 let response = PromptResponse::new(MessageId::new("message-1"));
7969 let serialized = serde_json::to_value(&response).unwrap();
7970 assert_eq!(serialized, json!({ "messageId": "message-1" }));
7971 assert_eq!(
7972 serde_json::from_value::<PromptResponse>(serialized).unwrap(),
7973 response
7974 );
7975 assert_eq!(
7976 serde_json::from_value::<PromptResponse>(json!({
7977 "messageId": "message-1",
7978 "_meta": null
7979 }))
7980 .unwrap(),
7981 response
7982 );
7983 }
7984
7985 #[test]
7986 fn prompt_response_requires_message_id_and_preserves_metadata_tolerance() {
7987 let response = PromptResponse::new("message-1").meta(test_meta());
7988 let serialized = serde_json::to_value(&response).unwrap();
7989 assert_eq!(
7990 serialized,
7991 json!({
7992 "messageId": "message-1",
7993 "_meta": { "source": "test" }
7994 })
7995 );
7996
7997 let deserialized: PromptResponse = serde_json::from_value(serialized).unwrap();
7998 assert_eq!(deserialized.message_id, MessageId::new("message-1"));
7999 assert_eq!(deserialized.meta, Some(test_meta()));
8000
8001 let malformed_meta: PromptResponse = serde_json::from_value(json!({
8002 "messageId": "message-2",
8003 "_meta": false
8004 }))
8005 .unwrap();
8006 assert_eq!(malformed_meta.message_id, MessageId::new("message-2"));
8007 assert_eq!(malformed_meta.meta, None);
8008
8009 for invalid in [
8010 json!({}),
8011 json!({ "messageId": null }),
8012 json!({ "messageId": 1 }),
8013 json!({ "messageId": false }),
8014 json!({ "messageId": {} }),
8015 json!({ "messageId": [] }),
8016 ] {
8017 assert!(
8018 serde_json::from_value::<PromptResponse>(invalid).is_err(),
8019 "missing, null, and non-string message IDs must be rejected"
8020 );
8021 }
8022 }
8023
8024 #[cfg(feature = "schemars")]
8025 #[test]
8026 fn prompt_response_schema_requires_non_null_string_message_id_reference() {
8027 let schema = serde_json::to_value(schemars::schema_for!(PromptResponse)).unwrap();
8028
8029 assert_eq!(schema["required"], json!(["messageId"]));
8030 assert_eq!(
8031 schema["properties"]["messageId"]["$ref"],
8032 "#/$defs/MessageId"
8033 );
8034 assert_eq!(schema["$defs"]["MessageId"]["type"], "string");
8035 }
8036
8037 #[test]
8038 fn test_initialize_capabilities_default_on_malformed_values() {
8039 let request: InitializeRequest = serde_json::from_value(json!({
8040 "protocolVersion": 2,
8041 "capabilities": false,
8042 "info": {
8043 "name": "client",
8044 "version": "1.0.0"
8045 }
8046 }))
8047 .unwrap();
8048 assert_eq!(request.capabilities, ClientCapabilities::default());
8049
8050 let response: InitializeResponse = serde_json::from_value(json!({
8051 "protocolVersion": 2,
8052 "capabilities": false,
8053 "info": {
8054 "name": "agent",
8055 "version": "1.0.0"
8056 }
8057 }))
8058 .unwrap();
8059 assert_eq!(response.capabilities, AgentCapabilities::default());
8060 }
8061
8062 #[test]
8063 fn test_agent_capabilities_default_on_malformed_values() {
8064 let capabilities: AgentCapabilities = serde_json::from_value(json!({
8065 "session": false,
8066 "auth": false
8067 }))
8068 .unwrap();
8069
8070 assert!(capabilities.session.is_none());
8071 assert_eq!(capabilities.auth, None);
8072 }
8073
8074 #[test]
8075 fn test_mcp_server_stdio_serialization() {
8076 let server = McpServer::Stdio(
8077 McpServerStdio::new("test-server", "/usr/bin/server")
8078 .args(vec!["--port".to_string(), "3000".to_string()])
8079 .env(vec![EnvVariable::new("API_KEY", "secret123")]),
8080 );
8081
8082 let json = serde_json::to_value(&server).unwrap();
8083 assert_eq!(
8084 json,
8085 json!({
8086 "type": "stdio",
8087 "name": "test-server",
8088 "command": "/usr/bin/server",
8089 "args": ["--port", "3000"],
8090 "env": [
8091 {
8092 "name": "API_KEY",
8093 "value": "secret123"
8094 }
8095 ]
8096 })
8097 );
8098
8099 let deserialized: McpServer = serde_json::from_value(json).unwrap();
8100 match deserialized {
8101 McpServer::Stdio(McpServerStdio {
8102 name,
8103 command,
8104 args,
8105 env,
8106 meta: _,
8107 }) => {
8108 assert_eq!(name, "test-server");
8109 assert_eq!(command, AbsolutePath::new("/usr/bin/server"));
8110 assert_eq!(args, vec!["--port", "3000"]);
8111 assert_eq!(env.len(), 1);
8112 assert_eq!(env[0].name, "API_KEY");
8113 assert_eq!(env[0].value, "secret123");
8114 }
8115 _ => panic!("Expected Stdio variant"),
8116 }
8117 }
8118
8119 #[test]
8120 fn test_mcp_server_empty_arrays_are_optional() {
8121 let stdio = McpServer::Stdio(McpServerStdio::new("test-server", "/usr/bin/server"));
8122 assert_eq!(
8123 serde_json::to_value(&stdio).unwrap(),
8124 json!({
8125 "type": "stdio",
8126 "name": "test-server",
8127 "command": "/usr/bin/server"
8128 })
8129 );
8130
8131 let McpServer::Stdio(McpServerStdio { args, env, .. }) =
8132 serde_json::from_value::<McpServer>(json!({
8133 "type": "stdio",
8134 "name": "test-server",
8135 "command": "/usr/bin/server"
8136 }))
8137 .unwrap()
8138 else {
8139 panic!("Expected Stdio variant");
8140 };
8141 assert_eq!(args, Vec::<String>::new());
8142 assert_eq!(env, []);
8143
8144 let http = McpServer::Http(McpServerHttp::new("http-server", "https://api.example.com"));
8145 assert_eq!(
8146 serde_json::to_value(&http).unwrap(),
8147 json!({
8148 "type": "http",
8149 "name": "http-server",
8150 "url": "https://api.example.com"
8151 })
8152 );
8153
8154 let McpServer::Http(McpServerHttp { headers, .. }) =
8155 serde_json::from_value::<McpServer>(json!({
8156 "type": "http",
8157 "name": "http-server",
8158 "url": "https://api.example.com"
8159 }))
8160 .unwrap()
8161 else {
8162 panic!("Expected Http variant");
8163 };
8164 assert_eq!(headers, []);
8165 }
8166
8167 #[test]
8168 fn test_mcp_server_unknown_transport_serialization() {
8169 let json = json!({
8170 "type": "websocket",
8171 "name": "future-server",
8172 "url": "wss://example.com/mcp",
8173 "protocolVersion": "2026-01-01"
8174 });
8175
8176 let deserialized: McpServer = serde_json::from_value(json.clone()).unwrap();
8177 let McpServer::Other(OtherMcpServer { type_, fields }) = &deserialized else {
8178 panic!("Expected Other variant");
8179 };
8180
8181 assert_eq!(type_, "websocket");
8182 assert_eq!(fields["name"], "future-server");
8183 assert_eq!(fields["url"], "wss://example.com/mcp");
8184 assert_eq!(fields["protocolVersion"], "2026-01-01");
8185 assert_eq!(serde_json::to_value(&deserialized).unwrap(), json);
8186 }
8187
8188 #[test]
8189 fn test_mcp_server_stdio_requires_type() {
8190 let result = serde_json::from_value::<McpServer>(json!({
8191 "name": "test-server",
8192 "command": "/usr/bin/server",
8193 "args": [],
8194 "env": []
8195 }));
8196
8197 assert!(result.is_err());
8198 }
8199
8200 #[test]
8201 fn test_mcp_server_unknown_does_not_hide_malformed_known_transport() {
8202 let result = serde_json::from_value::<McpServer>(json!({
8203 "type": "stdio",
8204 "name": "test-server",
8205 "args": [],
8206 "env": []
8207 }));
8208
8209 assert!(result.is_err());
8210 }
8211
8212 #[test]
8213 fn test_mcp_server_http_serialization() {
8214 let server = McpServer::Http(
8215 McpServerHttp::new("http-server", "https://api.example.com").headers(vec![
8216 HttpHeader::new("Authorization", "Bearer token123"),
8217 HttpHeader::new("Content-Type", "application/json"),
8218 ]),
8219 );
8220
8221 let json = serde_json::to_value(&server).unwrap();
8222 assert_eq!(
8223 json,
8224 json!({
8225 "type": "http",
8226 "name": "http-server",
8227 "url": "https://api.example.com",
8228 "headers": [
8229 {
8230 "name": "Authorization",
8231 "value": "Bearer token123"
8232 },
8233 {
8234 "name": "Content-Type",
8235 "value": "application/json"
8236 }
8237 ]
8238 })
8239 );
8240
8241 let deserialized: McpServer = serde_json::from_value(json).unwrap();
8242 match deserialized {
8243 McpServer::Http(McpServerHttp {
8244 name,
8245 url,
8246 headers,
8247 meta: _,
8248 }) => {
8249 assert_eq!(name, "http-server");
8250 assert_eq!(url, "https://api.example.com");
8251 assert_eq!(headers.len(), 2);
8252 assert_eq!(headers[0].name, "Authorization");
8253 assert_eq!(headers[0].value, "Bearer token123");
8254 assert_eq!(headers[1].name, "Content-Type");
8255 assert_eq!(headers[1].value, "application/json");
8256 }
8257 _ => panic!("Expected Http variant"),
8258 }
8259 }
8260
8261 #[cfg(feature = "schemars")]
8262 #[test]
8263 fn mcp_server_http_schema_marks_url_as_uri() {
8264 let schema = serde_json::to_value(schemars::schema_for!(McpServerHttp)).unwrap();
8265
8266 assert_eq!(schema["properties"]["url"]["format"], "uri");
8267 }
8268
8269 #[cfg(feature = "unstable_mcp_over_acp")]
8270 #[test]
8271 fn test_client_mcp_message_method_names() {
8272 use serde_json::json;
8273
8274 assert_eq!(AGENT_METHOD_NAMES.mcp_message, "mcp/message");
8275
8276 let notification =
8277 MessageMcpNotification::new("server-1", "req-1", "notifications/progress");
8278 assert_eq!(
8279 ClientNotification::MessageMcpNotification(Box::new(notification.clone())).method(),
8280 "mcp/message"
8281 );
8282 assert_eq!(
8283 serde_json::to_value(notification).unwrap(),
8284 json!({
8285 "serverId": "server-1",
8286 "requestId": "req-1",
8287 "method": "notifications/progress"
8288 })
8289 );
8290 let notification: MessageMcpNotification = serde_json::from_value(json!({
8291 "serverId": "server-1", "requestId": "req-1", "method": "notifications/progress",
8292 "params": null, "_meta": null
8293 }))
8294 .unwrap();
8295 assert_eq!(notification.params, None);
8296 assert_eq!(notification.meta, None);
8297 for key in ["serverId", "requestId", "method"] {
8298 let mut value = json!({"serverId":"server-1", "requestId":"req-1", "method":"notifications/progress"});
8299 value.as_object_mut().unwrap().remove(key);
8300 assert!(serde_json::from_value::<MessageMcpNotification>(value).is_err());
8301 }
8302 }
8303
8304 #[test]
8305 fn test_auth_method_names() {
8306 assert_eq!(AGENT_METHOD_NAMES.auth_login, "auth/login");
8307 assert_eq!(AGENT_METHOD_NAMES.auth_logout, "auth/logout");
8308
8309 assert_eq!(
8310 ClientRequest::LoginAuthRequest(Box::new(LoginAuthRequest::new("agent-login")))
8311 .method(),
8312 "auth/login"
8313 );
8314 assert_eq!(
8315 ClientRequest::LogoutAuthRequest(Box::new(LogoutAuthRequest::new())).method(),
8316 "auth/logout"
8317 );
8318 }
8319
8320 #[test]
8321 fn test_session_config_option_category_known_variants() {
8322 assert_eq!(
8324 serde_json::to_value(&SessionConfigOptionCategory::Mode).unwrap(),
8325 json!("mode")
8326 );
8327 assert_eq!(
8328 serde_json::to_value(&SessionConfigOptionCategory::Model).unwrap(),
8329 json!("model")
8330 );
8331 assert_eq!(
8332 serde_json::to_value(&SessionConfigOptionCategory::ModelConfig).unwrap(),
8333 json!("model_config")
8334 );
8335 assert_eq!(
8336 serde_json::to_value(&SessionConfigOptionCategory::ThoughtLevel).unwrap(),
8337 json!("thought_level")
8338 );
8339
8340 assert_eq!(
8342 serde_json::from_str::<SessionConfigOptionCategory>("\"mode\"").unwrap(),
8343 SessionConfigOptionCategory::Mode
8344 );
8345 assert_eq!(
8346 serde_json::from_str::<SessionConfigOptionCategory>("\"model\"").unwrap(),
8347 SessionConfigOptionCategory::Model
8348 );
8349 assert_eq!(
8350 serde_json::from_str::<SessionConfigOptionCategory>("\"model_config\"").unwrap(),
8351 SessionConfigOptionCategory::ModelConfig
8352 );
8353 assert_eq!(
8354 serde_json::from_str::<SessionConfigOptionCategory>("\"thought_level\"").unwrap(),
8355 SessionConfigOptionCategory::ThoughtLevel
8356 );
8357 }
8358
8359 #[test]
8360 fn test_session_config_option_category_unknown_variants() {
8361 let unknown: SessionConfigOptionCategory =
8363 serde_json::from_str("\"some_future_category\"").unwrap();
8364 assert_eq!(
8365 unknown,
8366 SessionConfigOptionCategory::Other("some_future_category".to_string())
8367 );
8368
8369 let json = serde_json::to_value(&unknown).unwrap();
8371 assert_eq!(json, json!("some_future_category"));
8372 }
8373
8374 #[test]
8375 fn test_session_config_option_category_custom_categories() {
8376 let custom: SessionConfigOptionCategory =
8378 serde_json::from_str("\"_my_custom_category\"").unwrap();
8379 assert_eq!(
8380 custom,
8381 SessionConfigOptionCategory::Other("_my_custom_category".to_string())
8382 );
8383
8384 let json = serde_json::to_value(&custom).unwrap();
8386 assert_eq!(json, json!("_my_custom_category"));
8387
8388 let deserialized: SessionConfigOptionCategory = serde_json::from_value(json).unwrap();
8390 assert_eq!(
8391 deserialized,
8392 SessionConfigOptionCategory::Other("_my_custom_category".to_string()),
8393 );
8394 }
8395
8396 fn test_config_option() -> SessionConfigOption {
8397 SessionConfigOption::select(
8398 "mode",
8399 "Mode",
8400 "ask",
8401 vec![SessionConfigSelectOption::new("ask", "Ask")],
8402 )
8403 }
8404
8405 #[test]
8406 fn test_session_response_initial_state_default_empty_and_skip_serializing() {
8407 assert_eq!(
8408 serde_json::to_value(NewSessionResponse::new("sess")).unwrap(),
8409 json!({ "sessionId": "sess" })
8410 );
8411 assert_eq!(
8412 serde_json::to_value(ResumeSessionResponse::new()).unwrap(),
8413 json!({})
8414 );
8415 #[cfg(feature = "unstable_session_fork")]
8416 assert_eq!(
8417 serde_json::to_value(ForkSessionResponse::new("fork")).unwrap(),
8418 json!({ "sessionId": "fork" })
8419 );
8420
8421 let json = serde_json::to_value(
8422 NewSessionResponse::new("sess").config_options(vec![test_config_option()]),
8423 )
8424 .unwrap();
8425 assert_eq!(json["configOptions"].as_array().unwrap().len(), 1);
8426 }
8427
8428 #[test]
8429 fn test_session_response_config_options_deserialize_missing_null_and_invalid() {
8430 let missing: NewSessionResponse =
8431 serde_json::from_value(json!({ "sessionId": "sess" })).unwrap();
8432 assert_eq!(missing.config_options, []);
8433
8434 let null: NewSessionResponse = serde_json::from_value(json!({
8435 "sessionId": "sess",
8436 "configOptions": null
8437 }))
8438 .unwrap();
8439 assert_eq!(null.config_options, []);
8440
8441 let wrong_shape: NewSessionResponse = serde_json::from_value(json!({
8442 "sessionId": "sess",
8443 "configOptions": "oops"
8444 }))
8445 .unwrap();
8446 assert_eq!(wrong_shape.config_options, []);
8447
8448 let valid_option = serde_json::to_value(test_config_option()).unwrap();
8449 let mixed: NewSessionResponse = serde_json::from_value(json!({
8450 "sessionId": "sess",
8451 "configOptions": ["oops", valid_option]
8452 }))
8453 .unwrap();
8454 assert_eq!(mixed.config_options.len(), 1);
8455
8456 let resume: ResumeSessionResponse = serde_json::from_value(json!({})).unwrap();
8457 assert_eq!(resume.config_options, []);
8458 #[cfg(feature = "unstable_session_fork")]
8459 {
8460 let fork: ForkSessionResponse =
8461 serde_json::from_value(json!({ "sessionId": "fork" })).unwrap();
8462 assert_eq!(fork.config_options, []);
8463 }
8464 }
8465
8466 #[test]
8467 fn test_session_response_available_commands_roundtrip_with_config_options() {
8468 use super::super::{AvailableCommandInput, Command, TextCommandInput};
8469
8470 let commands = vec![
8471 AvailableCommand::Command(
8472 Command::new("web", "Search the web")
8473 .input(AvailableCommandInput::Text(TextCommandInput::new("Query"))),
8474 ),
8475 AvailableCommand::Command(Command::new("test", "Run project tests")),
8476 ];
8477 let mut expected = json!({
8478 "sessionId": "sess",
8479 "configOptions": [test_config_option()],
8480 "availableCommands": [
8481 {
8482 "type": "command",
8483 "name": "web",
8484 "description": "Search the web",
8485 "input": { "type": "text", "hint": "Query" }
8486 },
8487 { "type": "command", "name": "test", "description": "Run project tests" }
8488 ]
8489 });
8490
8491 let new = NewSessionResponse::new("sess")
8492 .config_options(vec![test_config_option()])
8493 .available_commands(commands.clone());
8494 assert_eq!(serde_json::to_value(&new).unwrap(), expected);
8495 assert_eq!(
8496 serde_json::from_value::<NewSessionResponse>(expected.clone()).unwrap(),
8497 new
8498 );
8499
8500 expected.as_object_mut().unwrap().remove("sessionId");
8501 let resume = ResumeSessionResponse::new()
8502 .config_options(vec![test_config_option()])
8503 .available_commands(commands.clone());
8504 assert_eq!(serde_json::to_value(&resume).unwrap(), expected);
8505 assert_eq!(
8506 serde_json::from_value::<ResumeSessionResponse>(expected.clone()).unwrap(),
8507 resume
8508 );
8509
8510 #[cfg(feature = "unstable_session_fork")]
8511 {
8512 expected["sessionId"] = json!("fork");
8513 let fork = ForkSessionResponse::new("fork")
8514 .config_options(vec![test_config_option()])
8515 .available_commands(commands);
8516 assert_eq!(serde_json::to_value(&fork).unwrap(), expected);
8517 assert_eq!(
8518 serde_json::from_value::<ForkSessionResponse>(expected).unwrap(),
8519 fork
8520 );
8521 }
8522 }
8523
8524 #[test]
8525 fn test_session_response_available_commands_deserialize_missing_null_and_invalid() {
8526 let command =
8527 AvailableCommand::Command(super::super::Command::new("test", "Run project tests"));
8528 let config_options = vec![test_config_option()];
8529
8530 for (commands, expected) in [
8531 (None, vec![]),
8532 (Some(json!(null)), vec![]),
8533 (Some(json!([])), vec![]),
8534 (Some(json!("oops")), vec![]),
8535 (Some(json!({})), vec![]),
8536 (Some(json!([null, {}, { "name": "invalid" }])), vec![]),
8537 (
8538 Some(json!([{ "name": "test", "description": "Run project tests" }])),
8539 vec![],
8540 ),
8541 (
8542 Some(json!([null, command, { "name": "invalid" }])),
8543 vec![command.clone()],
8544 ),
8545 ] {
8546 let mut value = json!({
8547 "sessionId": "sess",
8548 "configOptions": config_options
8549 });
8550 if let Some(commands) = commands {
8551 value["availableCommands"] = commands;
8552 }
8553
8554 let new: NewSessionResponse = serde_json::from_value(value.clone()).unwrap();
8555 assert_eq!(new.available_commands, expected);
8556 assert_eq!(new.config_options, config_options);
8557
8558 #[cfg(feature = "unstable_session_fork")]
8559 {
8560 let fork: ForkSessionResponse = serde_json::from_value(value.clone()).unwrap();
8561 assert_eq!(fork.available_commands, expected);
8562 assert_eq!(fork.config_options, config_options);
8563 }
8564
8565 value.as_object_mut().unwrap().remove("sessionId");
8566 let resume: ResumeSessionResponse = serde_json::from_value(value).unwrap();
8567 assert_eq!(resume.available_commands, expected);
8568 assert_eq!(resume.config_options, config_options);
8569 }
8570
8571 let resume: ResumeSessionResponse = serde_json::from_value(json!(null)).unwrap();
8572 assert_eq!(resume.available_commands, []);
8573 }
8574
8575 #[test]
8576 fn test_resume_session_replay_from_serialization() {
8577 assert_eq!(
8578 serde_json::to_value(ResumeSessionRequest::new(
8579 "sess_abc123",
8580 "/home/user/project"
8581 ))
8582 .unwrap(),
8583 json!({
8584 "sessionId": "sess_abc123",
8585 "cwd": "/home/user/project"
8586 })
8587 );
8588 assert_eq!(
8589 serde_json::to_value(
8590 ResumeSessionRequest::new("sess_abc123", "/home/user/project")
8591 .replay_from(ReplayFrom::from(ReplayFromStart::new()))
8592 )
8593 .unwrap(),
8594 json!({
8595 "sessionId": "sess_abc123",
8596 "cwd": "/home/user/project",
8597 "replayFrom": {
8598 "type": "start"
8599 }
8600 })
8601 );
8602
8603 let replay: ResumeSessionRequest = serde_json::from_value(json!({
8604 "sessionId": "sess_abc123",
8605 "cwd": "/home/user/project",
8606 "replayFrom": {
8607 "type": "start"
8608 }
8609 }))
8610 .unwrap();
8611 assert!(matches!(replay.replay_from, Some(ReplayFrom::Start(_))));
8612
8613 let none: ResumeSessionRequest = serde_json::from_value(json!({
8614 "sessionId": "sess_abc123",
8615 "cwd": "/home/user/project",
8616 "replayFrom": null
8617 }))
8618 .unwrap();
8619 assert!(none.replay_from.is_none());
8620 }
8621
8622 #[test]
8623 fn test_auth_method_agent_serialization() {
8624 let method = AuthMethod::Agent(AuthMethodAgent::new("default-auth", "Default Auth"));
8625
8626 let json = serde_json::to_value(&method).unwrap();
8627 assert_eq!(
8628 json,
8629 json!({
8630 "methodId": "default-auth",
8631 "name": "Default Auth",
8632 "type": "agent"
8633 })
8634 );
8635 assert!(!json.as_object().unwrap().contains_key("description"));
8637
8638 let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
8639 match deserialized {
8640 AuthMethod::Agent(AuthMethodAgent {
8641 method_id, name, ..
8642 }) => {
8643 assert_eq!(method_id.0.as_ref(), "default-auth");
8644 assert_eq!(name, "Default Auth");
8645 }
8646 _ => panic!("Expected Agent variant"),
8647 }
8648 }
8649
8650 #[test]
8651 fn test_auth_method_agent_deserialization() {
8652 let json = json!({
8653 "methodId": "agent-auth",
8654 "name": "Agent Auth",
8655 "type": "agent"
8656 });
8657
8658 let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
8659 assert!(matches!(deserialized, AuthMethod::Agent(_)));
8660 }
8661
8662 #[test]
8663 fn test_auth_method_agent_requires_type() {
8664 assert!(
8665 serde_json::from_value::<AuthMethod>(json!({
8666 "methodId": "agent-auth",
8667 "name": "Agent Auth"
8668 }))
8669 .is_err()
8670 );
8671 }
8672
8673 #[test]
8674 fn test_auth_method_agent_rejects_null_type() {
8675 assert!(
8676 serde_json::from_value::<AuthMethod>(json!({
8677 "methodId": "agent-auth",
8678 "name": "Agent Auth",
8679 "type": null
8680 }))
8681 .is_err()
8682 );
8683 }
8684
8685 #[test]
8686 fn test_auth_method_unknown_does_not_hide_malformed_agent() {
8687 assert!(
8688 serde_json::from_value::<AuthMethod>(json!({
8689 "methodId": "agent-auth",
8690 "type": "agent"
8691 }))
8692 .is_err()
8693 );
8694 assert!(
8695 serde_json::from_value::<AuthMethod>(json!({
8696 "methodId": "api-key",
8697 "type": "env_var",
8698 "vars": [{"name": "API_KEY"}]
8699 }))
8700 .is_err()
8701 );
8702 }
8703
8704 #[test]
8705 fn test_auth_method_unknown_variant_roundtrip() {
8706 let method: AuthMethod = serde_json::from_value(json!({
8707 "methodId": "oauth",
8708 "name": "OAuth",
8709 "type": "_oauth",
8710 "authorizationUrl": "https://example.com/auth"
8711 }))
8712 .unwrap();
8713
8714 assert_eq!(method.method_id().0.as_ref(), "oauth");
8715 assert_eq!(method.name(), "OAuth");
8716 let AuthMethod::Other(unknown) = method else {
8717 panic!("expected unknown auth method");
8718 };
8719 assert_eq!(unknown.type_, "_oauth");
8720 assert_eq!(
8721 unknown.fields.get("authorizationUrl"),
8722 Some(&json!("https://example.com/auth"))
8723 );
8724
8725 assert_eq!(
8726 serde_json::to_value(AuthMethod::Other(unknown)).unwrap(),
8727 json!({
8728 "methodId": "oauth",
8729 "name": "OAuth",
8730 "type": "_oauth",
8731 "authorizationUrl": "https://example.com/auth"
8732 })
8733 );
8734 }
8735
8736 #[test]
8737 fn test_auth_method_unknown_does_not_hide_malformed_known_variant() {
8738 assert!(
8739 serde_json::from_value::<AuthMethod>(json!({
8740 "methodId": "terminal-auth",
8741 "type": "terminal"
8742 }))
8743 .is_err()
8744 );
8745 }
8746
8747 #[test]
8748 fn test_tool_call_and_terminal_cancel_serialization() {
8749 assert_eq!(AGENT_METHOD_NAMES.tool_call_cancel, "tool_call/cancel");
8750 assert_eq!(AGENT_METHOD_NAMES.terminal_cancel, "terminal/cancel");
8751 assert_eq!(
8752 ClientRequest::CancelToolCallRequest(Box::new(CancelToolCallRequest::new(
8753 "sess_abc123",
8754 "call_012"
8755 )))
8756 .method(),
8757 "tool_call/cancel"
8758 );
8759 assert_eq!(
8760 ClientRequest::CancelTerminalRequest(Box::new(CancelTerminalRequest::new(
8761 "sess_abc123",
8762 "term_003"
8763 )))
8764 .method(),
8765 "terminal/cancel"
8766 );
8767 assert_eq!(
8768 serde_json::to_value(CancelToolCallRequest::new("sess_abc123", "call_012")).unwrap(),
8769 json!({"sessionId": "sess_abc123", "toolCallId": "call_012"})
8770 );
8771 assert_eq!(
8772 serde_json::to_value(CancelTerminalRequest::new("sess_abc123", "term_003")).unwrap(),
8773 json!({"sessionId": "sess_abc123", "terminalId": "term_003"})
8774 );
8775 assert!(
8776 serde_json::from_value::<CancelToolCallRequest>(json!({"sessionId": "sess_abc123"}))
8777 .is_err()
8778 );
8779 assert_eq!(
8780 serde_json::to_value(CancelTerminalResponse::new()).unwrap(),
8781 json!({})
8782 );
8783 }
8784
8785 #[test]
8786 fn test_session_delete_serialization() {
8787 assert_eq!(AGENT_METHOD_NAMES.session_delete, "session/delete");
8788 assert_eq!(
8789 ClientRequest::DeleteSessionRequest(Box::new(DeleteSessionRequest::new("sess_abc123")))
8790 .method(),
8791 "session/delete"
8792 );
8793 assert_eq!(
8794 serde_json::to_value(DeleteSessionRequest::new("sess_abc123")).unwrap(),
8795 json!({
8796 "sessionId": "sess_abc123"
8797 })
8798 );
8799 assert_eq!(
8800 serde_json::to_value(DeleteSessionResponse::new()).unwrap(),
8801 json!({})
8802 );
8803 assert_eq!(
8804 serde_json::to_value(
8805 SessionCapabilities::new().delete(SessionDeleteCapabilities::new())
8806 )
8807 .unwrap(),
8808 json!({
8809 "delete": {}
8810 })
8811 );
8812 }
8813 #[cfg(feature = "unstable_session_set_title")]
8814 #[test]
8815 fn test_session_set_title_serialization() {
8816 assert_eq!(AGENT_METHOD_NAMES.session_set_title, "session/set_title");
8817 assert_eq!(
8818 ClientRequest::SetSessionTitleRequest(Box::new(SetSessionTitleRequest::new(
8819 "sess_abc123",
8820 "Investigate OAuth timeout"
8821 )))
8822 .method(),
8823 "session/set_title"
8824 );
8825 assert_eq!(
8826 serde_json::to_value(SetSessionTitleRequest::new(
8827 "sess_abc123",
8828 "Investigate OAuth timeout"
8829 ))
8830 .unwrap(),
8831 json!({
8832 "sessionId": "sess_abc123",
8833 "title": "Investigate OAuth timeout"
8834 })
8835 );
8836 assert_eq!(
8837 serde_json::to_value(SetSessionTitleResponse::new("Investigate OAuth timeout"))
8838 .unwrap(),
8839 json!({
8840 "title": "Investigate OAuth timeout"
8841 })
8842 );
8843 assert_eq!(
8844 serde_json::to_value(SessionCapabilities::new().title(SessionTitleCapabilities::new()))
8845 .unwrap(),
8846 json!({
8847 "title": {}
8848 })
8849 );
8850 }
8851
8852 #[cfg(feature = "unstable_session_set_title")]
8853 #[test]
8854 fn test_session_set_title_requires_title() {
8855 for params in [
8856 json!({"sessionId": "sess_abc123"}),
8857 json!({"sessionId": "sess_abc123", "title": null}),
8858 json!({"sessionId": "sess_abc123", "title": 42}),
8859 ] {
8860 assert!(serde_json::from_value::<SetSessionTitleRequest>(params).is_err());
8861 }
8862 for result in [json!({}), json!({"title": null})] {
8863 assert!(serde_json::from_value::<SetSessionTitleResponse>(result).is_err());
8864 }
8865 }
8866
8867 #[cfg(feature = "unstable_session_options")]
8868 #[test]
8869 fn test_session_options_serialization() {
8870 assert_eq!(AGENT_METHOD_NAMES.session_options, "session/options");
8871 assert_eq!(
8872 ClientRequest::SessionOptionsRequest(Box::new(SessionOptionsRequest::new(
8873 "/home/user/project"
8874 )))
8875 .method(),
8876 "session/options"
8877 );
8878 assert_eq!(
8879 serde_json::to_value(
8880 SessionOptionsRequest::new("/home/user/project")
8881 .session_id(SessionId::new("sess_abc123"))
8882 )
8883 .unwrap(),
8884 json!({"cwd": "/home/user/project", "sessionId": "sess_abc123"})
8885 );
8886 assert_eq!(
8887 serde_json::from_value::<SessionOptionsRequest>(
8888 json!({"cwd": "/home/user/project", "additionalDirectories": null, "sessionId": null})
8889 )
8890 .unwrap(),
8891 SessionOptionsRequest::new("/home/user/project")
8892 );
8893 let request = NewSessionRequest::new("/home/user/project").config_options(vec![
8894 InitialSessionConfigOption::new("model", SessionConfigOptionValue::id("model-2")),
8895 InitialSessionConfigOption::new("fast", SessionConfigOptionValue::boolean(true)),
8896 ]);
8897 let value = serde_json::to_value(&request).unwrap();
8898 assert_eq!(
8899 value["configOptions"],
8900 json!([
8901 {"configId": "model", "type": "id", "value": "model-2"},
8902 {"configId": "fast", "type": "boolean", "value": true}
8903 ])
8904 );
8905 assert_eq!(
8906 serde_json::from_value::<NewSessionRequest>(value).unwrap(),
8907 request
8908 );
8909 assert!(
8910 serde_json::from_value::<NewSessionRequest>(json!({
8911 "cwd": "/home/user/project",
8912 "mcpServers": [],
8913 "configOptions": [{"type": "boolean", "value": true}]
8914 }))
8915 .is_err()
8916 );
8917 assert_eq!(
8918 serde_json::to_value(SessionOptionsResponse::new()).unwrap(),
8919 json!({})
8920 );
8921 assert_eq!(
8922 serde_json::to_value(
8923 SessionCapabilities::new().options(SessionOptionsCapabilities::new())
8924 )
8925 .unwrap(),
8926 json!({"options": {}})
8927 );
8928 }
8929
8930 #[cfg(feature = "unstable_session_status")]
8931 #[test]
8932 fn test_session_status_serialization() {
8933 assert_eq!(AGENT_METHOD_NAMES.session_status, "session/status");
8934 assert_eq!(
8935 ClientRequest::SessionStatusRequest(Box::new(SessionStatusRequest::new("sess_abc123")))
8936 .method(),
8937 "session/status"
8938 );
8939 assert_eq!(
8940 serde_json::to_value(SessionStatusRequest::new("sess_abc123")).unwrap(),
8941 json!({"sessionId": "sess_abc123"})
8942 );
8943 assert_eq!(
8944 serde_json::to_value(SessionStatusResponse::new(SessionStatus::Saved)).unwrap(),
8945 json!({"status": "saved"})
8946 );
8947 assert_eq!(
8948 serde_json::to_value(
8949 SessionCapabilities::new().status(SessionStatusCapabilities::new())
8950 )
8951 .unwrap(),
8952 json!({"status": {}})
8953 );
8954 assert_eq!(
8955 serde_json::to_value(SessionStatusResponse::new(SessionStatus::Open).state(
8956 StateUpdate::RequiresAction(crate::v2::RequiresActionStateUpdate::new())
8957 ))
8958 .unwrap(),
8959 json!({
8960 "status": "open",
8961 "state": {"state": "requires_action"}
8962 })
8963 );
8964 for state in [json!(null), json!("running"), json!({"state": 7})] {
8965 let response = serde_json::from_value::<SessionStatusResponse>(
8966 json!({"status": "open", "state": state}),
8967 )
8968 .unwrap();
8969 assert_eq!(response.state, None);
8970 }
8971 }
8972
8973 #[cfg(feature = "unstable_session_status")]
8974 #[test]
8975 fn test_session_status_is_strict_and_open() {
8976 let custom =
8977 serde_json::from_value::<SessionStatusResponse>(json!({"status": "_suspended"}))
8978 .unwrap();
8979 assert_eq!(
8980 custom.status,
8981 SessionStatus::Other("_suspended".to_string())
8982 );
8983 assert_eq!(
8984 serde_json::to_value(&custom).unwrap(),
8985 json!({"status": "_suspended"})
8986 );
8987 for result in [json!({}), json!({"status": null}), json!({"status": 1})] {
8988 assert!(serde_json::from_value::<SessionStatusResponse>(result).is_err());
8989 }
8990 for params in [json!({}), json!({"sessionId": null})] {
8991 assert!(serde_json::from_value::<SessionStatusRequest>(params).is_err());
8992 }
8993 }
8994
8995 #[cfg(feature = "unstable_session_archive")]
8996 #[test]
8997 fn test_session_archive_serialization() {
8998 assert_eq!(AGENT_METHOD_NAMES.session_archive, "session/archive");
8999 assert_eq!(AGENT_METHOD_NAMES.session_unarchive, "session/unarchive");
9000 assert_eq!(
9001 ClientRequest::ArchiveSessionRequest(Box::new(ArchiveSessionRequest::new(
9002 "sess_abc123"
9003 )))
9004 .method(),
9005 "session/archive"
9006 );
9007 assert_eq!(
9008 ClientRequest::UnarchiveSessionRequest(Box::new(UnarchiveSessionRequest::new(
9009 "sess_abc123"
9010 )))
9011 .method(),
9012 "session/unarchive"
9013 );
9014 assert_eq!(
9015 serde_json::to_value(ArchiveSessionRequest::new("sess_abc123")).unwrap(),
9016 json!({"sessionId": "sess_abc123"})
9017 );
9018 assert_eq!(
9019 serde_json::to_value(UnarchiveSessionResponse::new()).unwrap(),
9020 json!({})
9021 );
9022 assert_eq!(
9023 serde_json::to_value(
9024 SessionCapabilities::new().archive(SessionArchiveCapabilities::new())
9025 )
9026 .unwrap(),
9027 json!({"archive": {}})
9028 );
9029 assert_eq!(
9030 serde_json::to_value(
9031 ListSessionsRequest::new()
9032 .cwd("/home/user/project")
9033 .archived(SessionArchiveFilter::Only)
9034 )
9035 .unwrap(),
9036 json!({"cwd": "/home/user/project", "archived": "only"})
9037 );
9038 assert_eq!(
9039 serde_json::to_value(
9040 SessionInfo::new("sess_abc123", "/home/user/project").archived(true)
9041 )
9042 .unwrap(),
9043 json!({"sessionId": "sess_abc123", "cwd": "/home/user/project", "archived": true})
9044 );
9045 }
9046
9047 #[cfg(feature = "unstable_session_archive")]
9048 #[test]
9049 fn test_session_archive_filter_is_strict_and_open() {
9050 for (value, expected) in [
9051 (json!(null), None),
9052 (json!("include"), Some(SessionArchiveFilter::Include)),
9053 (
9054 json!("_recent"),
9055 Some(SessionArchiveFilter::Other("_recent".to_string())),
9056 ),
9057 ] {
9058 let request =
9059 serde_json::from_value::<ListSessionsRequest>(json!({"archived": value})).unwrap();
9060 assert_eq!(request.archived, expected);
9061 }
9062 for value in [json!(true), json!(1), json!({})] {
9063 assert!(
9064 serde_json::from_value::<ListSessionsRequest>(json!({"archived": value})).is_err()
9065 );
9066 }
9067 let info = serde_json::from_value::<SessionInfo>(
9068 json!({"sessionId": "sess_abc123", "cwd": "/home/user/project", "archived": "yes"}),
9069 )
9070 .unwrap();
9071 assert_eq!(info.archived, None);
9072 }
9073
9074 #[test]
9075 fn test_session_additional_directories_serialization() {
9076 assert_eq!(
9077 serde_json::to_value(NewSessionRequest::new("/home/user/project")).unwrap(),
9078 json!({
9079 "cwd": "/home/user/project",
9080 })
9081 );
9082 assert_eq!(
9083 serde_json::to_value(
9084 NewSessionRequest::new("/home/user/project").additional_directories(vec![
9085 PathBuf::from("/home/user/shared-lib"),
9086 PathBuf::from("/home/user/product-docs"),
9087 ])
9088 )
9089 .unwrap(),
9090 json!({
9091 "cwd": "/home/user/project",
9092 "additionalDirectories": [
9093 "/home/user/shared-lib",
9094 "/home/user/product-docs"
9095 ],
9096 })
9097 );
9098 assert_eq!(
9099 serde_json::to_value(ResumeSessionRequest::new(
9100 "sess_abc123",
9101 "/home/user/project"
9102 ))
9103 .unwrap(),
9104 json!({
9105 "sessionId": "sess_abc123",
9106 "cwd": "/home/user/project",
9107 })
9108 );
9109 assert_eq!(
9110 serde_json::from_value::<ResumeSessionRequest>(json!({
9111 "sessionId": "sess_abc123",
9112 "cwd": "/home/user/project"
9113 }))
9114 .unwrap()
9115 .mcp_servers,
9116 Vec::<McpServer>::new()
9117 );
9118 assert_eq!(
9119 serde_json::from_value::<ResumeSessionRequest>(json!({
9120 "sessionId": "sess_abc123",
9121 "cwd": "/home/user/project",
9122 "mcpServers": null
9123 }))
9124 .unwrap()
9125 .mcp_servers,
9126 Vec::<McpServer>::new()
9127 );
9128 assert_eq!(
9129 serde_json::to_value(SessionInfo::new("sess_abc123", "/home/user/project")).unwrap(),
9130 json!({
9131 "sessionId": "sess_abc123",
9132 "cwd": "/home/user/project"
9133 })
9134 );
9135 assert_eq!(
9136 serde_json::to_value(
9137 SessionInfo::new("sess_abc123", "/home/user/project").additional_directories(vec![
9138 PathBuf::from("/home/user/shared-lib"),
9139 PathBuf::from("/home/user/product-docs"),
9140 ])
9141 )
9142 .unwrap(),
9143 json!({
9144 "sessionId": "sess_abc123",
9145 "cwd": "/home/user/project",
9146 "additionalDirectories": [
9147 "/home/user/shared-lib",
9148 "/home/user/product-docs"
9149 ]
9150 })
9151 );
9152 assert_eq!(
9153 serde_json::from_value::<SessionInfo>(json!({
9154 "sessionId": "sess_abc123",
9155 "cwd": "/home/user/project"
9156 }))
9157 .unwrap()
9158 .additional_directories,
9159 Vec::<AbsolutePath>::new()
9160 );
9161 }
9162 #[test]
9163 fn test_session_additional_directories_capabilities_serialization() {
9164 assert_eq!(
9165 serde_json::to_value(
9166 SessionCapabilities::new()
9167 .additional_directories(SessionAdditionalDirectoriesCapabilities::new())
9168 )
9169 .unwrap(),
9170 json!({
9171 "additionalDirectories": {}
9172 })
9173 );
9174 }
9175
9176 #[test]
9177 fn test_session_system_prompt_capabilities_serialization() {
9178 assert_eq!(
9179 serde_json::to_value(
9180 SessionCapabilities::new().system_prompt(SessionSystemPromptCapabilities::new())
9181 )
9182 .unwrap(),
9183 json!({ "systemPrompt": {} })
9184 );
9185 assert_eq!(
9186 serde_json::to_value(
9187 SessionCapabilities::new().system_prompt(
9188 SessionSystemPromptCapabilities::new().mode(
9189 SessionSystemPromptModeCapabilities::new()
9190 .override_(SessionSystemPromptOverrideCapabilities::new())
9191 )
9192 )
9193 )
9194 .unwrap(),
9195 json!({ "systemPrompt": { "mode": { "override": {} } } })
9196 );
9197 assert_eq!(
9198 serde_json::from_value::<SessionCapabilities>(
9199 json!({ "systemPrompt": { "mode": { "override": {} } } })
9200 )
9201 .unwrap()
9202 .system_prompt
9203 .and_then(|capabilities| capabilities.mode)
9204 .and_then(|mode| mode.override_),
9205 Some(SessionSystemPromptOverrideCapabilities::new())
9206 );
9207
9208 assert_eq!(
9210 serde_json::from_value::<SessionCapabilities>(json!({ "systemPrompt": "yes" }))
9211 .unwrap()
9212 .system_prompt,
9213 None
9214 );
9215 assert_eq!(
9216 serde_json::from_value::<SessionCapabilities>(
9217 json!({ "systemPrompt": { "mode": { "override": true } } })
9218 )
9219 .unwrap()
9220 .system_prompt,
9221 Some(
9222 SessionSystemPromptCapabilities::new()
9223 .mode(SessionSystemPromptModeCapabilities::new())
9224 )
9225 );
9226 assert_eq!(
9227 serde_json::from_value::<SessionCapabilities>(
9228 json!({ "systemPrompt": { "mode": "override" } })
9229 )
9230 .unwrap()
9231 .system_prompt,
9232 Some(SessionSystemPromptCapabilities::new())
9233 );
9234 }
9235
9236 #[test]
9237 fn test_system_prompt_lifecycle_request_serialization() {
9238 let system_prompt = SystemPrompt::new(vec![ContentBlock::from(
9239 "You are a code review specialist.",
9240 )]);
9241 let system_prompt_json = json!({
9242 "mode": "append",
9243 "content": [{ "type": "text", "text": "You are a code review specialist." }]
9244 });
9245
9246 let request =
9247 NewSessionRequest::new("/home/user/project").system_prompt(system_prompt.clone());
9248 let request_json = json!({
9249 "cwd": "/home/user/project",
9250 "systemPrompt": system_prompt_json
9251 });
9252 assert_eq!(serde_json::to_value(&request).unwrap(), request_json);
9253 assert_eq!(
9254 serde_json::from_value::<NewSessionRequest>(request_json).unwrap(),
9255 request
9256 );
9257
9258 assert_eq!(
9259 serde_json::to_value(
9260 ResumeSessionRequest::new("sess_abc123", "/home/user/project")
9261 .system_prompt(system_prompt.clone())
9262 )
9263 .unwrap()["systemPrompt"],
9264 system_prompt_json
9265 );
9266 #[cfg(feature = "unstable_session_fork")]
9267 assert_eq!(
9268 serde_json::to_value(
9269 ForkSessionRequest::new("sess_abc123", "/home/user/project")
9270 .system_prompt(system_prompt.clone())
9271 )
9272 .unwrap()["systemPrompt"],
9273 system_prompt_json
9274 );
9275
9276 let override_prompt =
9277 SystemPrompt::new(vec![ContentBlock::from("...")]).mode(SystemPromptMode::Override);
9278 let override_json = json!({
9279 "mode": "override",
9280 "content": [{ "type": "text", "text": "..." }]
9281 });
9282 assert_eq!(
9283 serde_json::to_value(&override_prompt).unwrap(),
9284 override_json
9285 );
9286 assert_eq!(
9287 serde_json::from_value::<SystemPrompt>(override_json).unwrap(),
9288 override_prompt
9289 );
9290 }
9291
9292 #[test]
9295 fn test_system_prompt_new_defaults_to_append() {
9296 let system_prompt = SystemPrompt::new(vec![ContentBlock::from("...")]);
9297 assert_eq!(system_prompt.mode, SystemPromptMode::Append);
9298 assert_eq!(
9299 serde_json::to_value(&system_prompt).unwrap(),
9300 json!({ "mode": "append", "content": [{ "type": "text", "text": "..." }] })
9301 );
9302 }
9303
9304 #[test]
9308 fn test_system_prompt_preserves_unknown_modes() {
9309 for mode in ["_vendor_mode", "prepend"] {
9310 let system_prompt_json =
9311 json!({ "mode": mode, "content": [{ "type": "text", "text": "..." }] });
9312 let system_prompt: SystemPrompt =
9313 serde_json::from_value(system_prompt_json.clone()).unwrap();
9314 assert_eq!(
9315 system_prompt.mode,
9316 SystemPromptMode::Other(mode.to_string())
9317 );
9318 assert_eq!(
9319 serde_json::to_value(&system_prompt).unwrap(),
9320 system_prompt_json
9321 );
9322 }
9323 }
9324
9325 fn assert_system_prompt_is_strict<T>(base: &serde_json::Value)
9329 where
9330 T: serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
9331 {
9332 let name = std::any::type_name::<T>();
9333 let with = |system_prompt: serde_json::Value| {
9334 let mut request = base.clone();
9335 request["systemPrompt"] = system_prompt;
9336 serde_json::from_value::<T>(request)
9337 };
9338
9339 for system_prompt in [
9340 json!("You are a code review specialist."),
9341 json!({ "content": [{ "type": "text", "text": "..." }] }),
9342 json!({ "mode": null, "content": [{ "type": "text", "text": "..." }] }),
9343 json!({ "mode": 1, "content": [{ "type": "text", "text": "..." }] }),
9344 json!({ "mode": "append" }),
9345 json!({ "mode": "append", "content": "..." }),
9346 json!({ "mode": "append", "content": [{ "type": "text" }] }),
9347 ] {
9348 assert!(
9349 with(system_prompt.clone()).is_err(),
9350 "{name}.systemPrompt: {system_prompt}"
9351 );
9352 }
9353
9354 assert_eq!(
9355 with(serde_json::Value::Null).unwrap(),
9356 serde_json::from_value::<T>(base.clone()).unwrap(),
9357 "{name}.systemPrompt"
9358 );
9359 }
9360
9361 #[test]
9362 fn test_session_setup_requests_reject_malformed_system_prompts() {
9363 assert!(
9364 serde_json::to_value(NewSessionRequest::new("/repo"))
9365 .unwrap()
9366 .get("systemPrompt")
9367 .is_none()
9368 );
9369 assert_system_prompt_is_strict::<NewSessionRequest>(&json!({ "cwd": "/repo" }));
9370 assert_system_prompt_is_strict::<ResumeSessionRequest>(&json!({
9371 "sessionId": "sess-1",
9372 "cwd": "/repo"
9373 }));
9374 #[cfg(feature = "unstable_session_fork")]
9375 assert_system_prompt_is_strict::<ForkSessionRequest>(&json!({
9376 "sessionId": "sess-1",
9377 "cwd": "/repo"
9378 }));
9379 }
9380
9381 #[test]
9384 fn test_system_prompt_preserves_unknown_content_blocks() {
9385 let request: NewSessionRequest = serde_json::from_value(json!({
9386 "cwd": "/home/user/project",
9387 "systemPrompt": {
9388 "mode": "append",
9389 "content": [{ "type": "_vendor_video", "uri": "https://example.com/intro.mp4" }]
9390 }
9391 }))
9392 .unwrap();
9393 let content = request.system_prompt.unwrap().content;
9394 assert_eq!(content.len(), 1);
9395 assert!(matches!(content[0], ContentBlock::Other(_)));
9396 }
9397
9398 #[test]
9399 fn test_auth_method_terminal_serialization() {
9400 let method = AuthMethod::Terminal(AuthMethodTerminal::new("tui-auth", "Terminal Auth"));
9401
9402 let json = serde_json::to_value(&method).unwrap();
9403 assert_eq!(
9404 json,
9405 json!({
9406 "methodId": "tui-auth",
9407 "name": "Terminal Auth",
9408 "type": "terminal"
9409 })
9410 );
9411 assert!(!json.as_object().unwrap().contains_key("args"));
9413 assert!(!json.as_object().unwrap().contains_key("env"));
9414
9415 let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9416 match deserialized {
9417 AuthMethod::Terminal(AuthMethodTerminal { args, env, .. }) => {
9418 assert_eq!(args, Vec::<String>::new());
9419 assert_eq!(env, []);
9420 }
9421 _ => panic!("Expected Terminal variant"),
9422 }
9423 }
9424
9425 #[test]
9426 fn test_auth_method_terminal_with_args_and_env_serialization() {
9427 let method = AuthMethod::Terminal(
9428 AuthMethodTerminal::new("tui-auth", "Terminal Auth")
9429 .args(vec!["--interactive".to_string(), "--color".to_string()])
9430 .env(vec![EnvVariable::new("TERM", "xterm-256color")]),
9431 );
9432
9433 let json = serde_json::to_value(&method).unwrap();
9434 assert_eq!(
9435 json,
9436 json!({
9437 "methodId": "tui-auth",
9438 "name": "Terminal Auth",
9439 "type": "terminal",
9440 "args": ["--interactive", "--color"],
9441 "env": [
9442 {
9443 "name": "TERM",
9444 "value": "xterm-256color"
9445 }
9446 ]
9447 })
9448 );
9449
9450 let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9451 match deserialized {
9452 AuthMethod::Terminal(AuthMethodTerminal { args, env, .. }) => {
9453 assert_eq!(args, vec!["--interactive", "--color"]);
9454 assert_eq!(env.len(), 1);
9455 assert_eq!(env[0].name, "TERM");
9456 assert_eq!(env[0].value, "xterm-256color");
9457 }
9458 _ => panic!("Expected Terminal variant"),
9459 }
9460 }
9461
9462 #[test]
9463 fn test_session_config_option_id_serialize() {
9464 let val = SessionConfigOptionValue::id("model-1");
9465 let json = serde_json::to_value(&val).unwrap();
9466 assert_eq!(json, json!({ "type": "id", "value": "model-1" }));
9467 }
9468
9469 #[test]
9470 fn test_session_config_option_value_boolean_serialize() {
9471 let val = SessionConfigOptionValue::boolean(true);
9472 let json = serde_json::to_value(&val).unwrap();
9473 assert_eq!(json, json!({ "type": "boolean", "value": true }));
9474 }
9475
9476 #[test]
9477 fn test_session_config_option_value_deserialize_id() {
9478 let json = json!({ "type": "id", "value": "model-1" });
9479 let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9480 assert_eq!(val, SessionConfigOptionValue::id("model-1"));
9481 assert_eq!(val.as_id().unwrap().to_string(), "model-1");
9482 }
9483
9484 #[test]
9485 fn test_session_config_option_value_deserialize_requires_type() {
9486 let json = json!({ "value": "model-1" });
9487 let result = serde_json::from_value::<SessionConfigOptionValue>(json);
9488 assert!(result.is_err());
9489 }
9490
9491 #[test]
9492 fn test_session_config_option_value_deserialize_boolean() {
9493 let json = json!({ "type": "boolean", "value": true });
9494 let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9495 assert_eq!(val, SessionConfigOptionValue::boolean(true));
9496 assert_eq!(val.as_bool(), Some(true));
9497 }
9498
9499 #[test]
9500 fn test_session_config_option_value_deserialize_boolean_false() {
9501 let json = json!({ "type": "boolean", "value": false });
9502 let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9503 assert_eq!(val, SessionConfigOptionValue::boolean(false));
9504 assert_eq!(val.as_bool(), Some(false));
9505 }
9506
9507 #[test]
9508 fn test_session_config_option_value_deserialize_unknown_type_with_string_value() {
9509 let json = json!({
9510 "type": "text",
9511 "value": "freeform input",
9512 "maxLength": 200
9513 });
9514 let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9515 let SessionConfigOptionValue::Other(unknown) = val else {
9516 panic!("Expected Other variant");
9517 };
9518 assert_eq!(unknown.type_, "text");
9519 assert_eq!(unknown.value, json!("freeform input"));
9520 assert_eq!(unknown.fields["maxLength"], json!(200));
9521 }
9522
9523 #[test]
9524 fn test_session_config_option_value_deserialize_unknown_type_with_object_value() {
9525 let json = json!({
9526 "type": "range",
9527 "value": { "min": 1, "max": 5 }
9528 });
9529 let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9530 let SessionConfigOptionValue::Other(unknown) = val else {
9531 panic!("Expected Other variant");
9532 };
9533 assert_eq!(unknown.type_, "range");
9534 assert_eq!(unknown.value, json!({ "min": 1, "max": 5 }));
9535 }
9536
9537 #[test]
9538 fn test_session_config_option_value_roundtrip_id() {
9539 let original = SessionConfigOptionValue::id("option-a");
9540 let json = serde_json::to_value(&original).unwrap();
9541 let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9542 assert_eq!(original, roundtripped);
9543 }
9544
9545 #[test]
9546 fn test_session_config_option_value_roundtrip_boolean() {
9547 let original = SessionConfigOptionValue::boolean(false);
9548 let json = serde_json::to_value(&original).unwrap();
9549 let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9550 assert_eq!(original, roundtripped);
9551 }
9552
9553 #[test]
9554 fn test_session_config_option_value_roundtrip_other() {
9555 let mut fields = BTreeMap::new();
9556 fields.insert("maxLength".to_string(), json!(200));
9557 let original = SessionConfigOptionValue::Other(OtherSessionConfigOptionValue::new(
9558 "text",
9559 json!("freeform input"),
9560 fields,
9561 ));
9562 let json = serde_json::to_value(&original).unwrap();
9563 let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9564 assert_eq!(original, roundtripped);
9565 }
9566
9567 #[test]
9568 fn test_session_config_option_value_type_mismatch_boolean_with_string() {
9569 let json = json!({ "type": "boolean", "value": "not a bool" });
9570 let result = serde_json::from_value::<SessionConfigOptionValue>(json);
9571 assert!(result.is_err());
9572 }
9573
9574 #[test]
9575 fn test_session_config_option_value_from_impls() {
9576 let from_str: SessionConfigOptionValue = "model-1".into();
9577 assert_eq!(from_str.as_id().unwrap().to_string(), "model-1");
9578
9579 let from_id: SessionConfigOptionValue = SessionConfigValueId::new("model-2").into();
9580 assert_eq!(from_id.as_id().unwrap().to_string(), "model-2");
9581
9582 let from_bool: SessionConfigOptionValue = true.into();
9583 assert_eq!(from_bool.as_bool(), Some(true));
9584 }
9585
9586 #[test]
9587 fn test_set_session_config_option_request_id() {
9588 let req = SetSessionConfigOptionRequest::new("sess_1", "model", "model-1");
9589 let json = serde_json::to_value(&req).unwrap();
9590 assert_eq!(
9591 json,
9592 json!({
9593 "sessionId": "sess_1",
9594 "configId": "model",
9595 "type": "id",
9596 "value": "model-1"
9597 })
9598 );
9599 }
9600
9601 #[test]
9602 fn test_set_session_config_option_request_boolean() {
9603 let req = SetSessionConfigOptionRequest::new("sess_1", "brave_mode", true);
9604 let json = serde_json::to_value(&req).unwrap();
9605 assert_eq!(
9606 json,
9607 json!({
9608 "sessionId": "sess_1",
9609 "configId": "brave_mode",
9610 "type": "boolean",
9611 "value": true
9612 })
9613 );
9614 }
9615
9616 #[test]
9617 fn test_set_session_config_option_request_deserialize_requires_type() {
9618 let json = json!({
9619 "sessionId": "sess_1",
9620 "configId": "model",
9621 "value": "model-1"
9622 });
9623 let result = serde_json::from_value::<SetSessionConfigOptionRequest>(json);
9624 assert!(result.is_err());
9625 }
9626
9627 #[test]
9628 fn test_set_session_config_option_request_deserialize_boolean() {
9629 let json = json!({
9630 "sessionId": "sess_1",
9631 "configId": "brave_mode",
9632 "type": "boolean",
9633 "value": true
9634 });
9635 let req: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
9636 assert_eq!(req.value.as_bool(), Some(true));
9637 }
9638
9639 #[test]
9640 fn test_set_session_config_option_request_roundtrip_id() {
9641 let original = SetSessionConfigOptionRequest::new("s", "c", "v");
9642 let json = serde_json::to_value(&original).unwrap();
9643 let roundtripped: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
9644 assert_eq!(original, roundtripped);
9645 }
9646
9647 #[test]
9648 fn test_set_session_config_option_request_roundtrip_boolean() {
9649 let original = SetSessionConfigOptionRequest::new("s", "c", false);
9650 let json = serde_json::to_value(&original).unwrap();
9651 let roundtripped: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
9652 assert_eq!(original, roundtripped);
9653 }
9654
9655 #[test]
9656 fn test_session_config_boolean_serialization() {
9657 let cfg = SessionConfigBoolean::new(true);
9658 let json = serde_json::to_value(&cfg).unwrap();
9659 assert_eq!(json, json!({ "currentValue": true }));
9660
9661 let deserialized: SessionConfigBoolean = serde_json::from_value(json).unwrap();
9662 assert!(deserialized.current_value);
9663 }
9664
9665 #[test]
9666 fn test_session_config_option_boolean_variant() {
9667 let opt = SessionConfigOption::boolean("brave_mode", "Brave Mode", false)
9668 .description("Skip confirmation prompts")
9669 .meta(test_meta());
9670 assert_eq!(serialized_meta_key_count(&opt), 1);
9671
9672 let json = serde_json::to_value(&opt).unwrap();
9673 assert_eq!(
9674 json,
9675 json!({
9676 "configId": "brave_mode",
9677 "name": "Brave Mode",
9678 "description": "Skip confirmation prompts",
9679 "type": "boolean",
9680 "currentValue": false,
9681 "_meta": {
9682 "source": "test"
9683 }
9684 })
9685 );
9686
9687 let deserialized: SessionConfigOption = serde_json::from_value(json).unwrap();
9688 assert_eq!(deserialized.config_id.to_string(), "brave_mode");
9689 assert_eq!(deserialized.name, "Brave Mode");
9690 match deserialized.kind {
9691 SessionConfigKind::Boolean(ref b) => assert!(!b.current_value),
9692 _ => panic!("Expected Boolean kind"),
9693 }
9694 }
9695
9696 #[test]
9697 fn test_session_config_option_select_still_works() {
9698 let opt = SessionConfigOption::select(
9700 "model",
9701 "Model",
9702 "model-1",
9703 vec![
9704 SessionConfigSelectOption::new("model-1", "Model 1"),
9705 SessionConfigSelectOption::new("model-2", "Model 2"),
9706 ],
9707 )
9708 .meta(test_meta());
9709 assert_eq!(serialized_meta_key_count(&opt), 1);
9710
9711 let json = serde_json::to_value(&opt).unwrap();
9712 assert_eq!(json["type"], "select");
9713 assert_eq!(json["currentValue"], "model-1");
9714 assert_eq!(json["options"].as_array().unwrap().len(), 2);
9715 assert_eq!(json["_meta"]["source"], "test");
9716
9717 let deserialized: SessionConfigOption = serde_json::from_value(json).unwrap();
9718 match deserialized.kind {
9719 SessionConfigKind::Select(ref s) => {
9720 assert_eq!(s.current_value.to_string(), "model-1");
9721 }
9722 _ => panic!("Expected Select kind"),
9723 }
9724 }
9725
9726 #[test]
9727 fn test_session_config_option_unknown_kind_roundtrip() {
9728 let option: SessionConfigOption = serde_json::from_value(json!({
9729 "configId": "verbosity",
9730 "name": "Verbosity",
9731 "type": "_slider",
9732 "currentValue": 3,
9733 "min": 0,
9734 "max": 5,
9735 "_meta": {
9736 "source": "test"
9737 }
9738 }))
9739 .unwrap();
9740
9741 assert_eq!(option.config_id.to_string(), "verbosity");
9742 assert_eq!(option.meta.as_ref().unwrap()["source"], "test");
9743 let SessionConfigKind::Other(unknown) = &option.kind else {
9744 panic!("expected unknown config kind");
9745 };
9746 assert_eq!(unknown.type_, "_slider");
9747 assert_eq!(unknown.fields.get("currentValue"), Some(&json!(3)));
9748 assert!(!unknown.fields.contains_key("_meta"));
9749 assert_eq!(serialized_meta_key_count(&option), 1);
9750
9751 let json = serde_json::to_value(&option).unwrap();
9752 assert_eq!(json["type"], "_slider");
9753 assert_eq!(json["currentValue"], 3);
9754 assert_eq!(json["min"], 0);
9755 assert_eq!(json["max"], 5);
9756 assert_eq!(json["_meta"]["source"], "test");
9757 }
9758
9759 #[test]
9760 fn test_session_config_option_unknown_kind_does_not_duplicate_flattened_meta() {
9761 let mut fields = std::collections::BTreeMap::new();
9762 fields.insert("currentValue".to_string(), json!(3));
9763 fields.insert("_meta".to_string(), json!({ "inner": "ignored" }));
9764
9765 let option = SessionConfigOption::new(
9766 "verbosity",
9767 "Verbosity",
9768 SessionConfigKind::Other(OtherSessionConfigKind::new("_slider", fields)),
9769 )
9770 .meta(test_meta());
9771
9772 let SessionConfigKind::Other(unknown) = &option.kind else {
9773 panic!("expected unknown config kind");
9774 };
9775 assert!(!unknown.fields.contains_key("_meta"));
9776 assert_eq!(serialized_meta_key_count(&option), 1);
9777
9778 let json = serde_json::to_value(&option).unwrap();
9779 assert_eq!(json["type"], "_slider");
9780 assert_eq!(json["currentValue"], 3);
9781 assert_eq!(json["_meta"]["source"], "test");
9782 }
9783
9784 #[test]
9785 fn test_session_config_option_unknown_does_not_hide_malformed_known_kind() {
9786 assert!(
9787 serde_json::from_value::<SessionConfigOption>(json!({
9788 "configId": "model",
9789 "name": "Model",
9790 "type": "select"
9791 }))
9792 .is_err()
9793 );
9794 }
9795
9796 #[cfg(feature = "unstable_llm_providers")]
9797 #[test]
9798 fn test_llm_protocol_known_variants() {
9799 assert_eq!(
9800 serde_json::to_value(&LlmProtocol::Anthropic).unwrap(),
9801 json!("anthropic")
9802 );
9803 assert_eq!(
9804 serde_json::to_value(&LlmProtocol::OpenAi).unwrap(),
9805 json!("openai")
9806 );
9807 assert_eq!(
9808 serde_json::to_value(&LlmProtocol::Azure).unwrap(),
9809 json!("azure")
9810 );
9811 assert_eq!(
9812 serde_json::to_value(&LlmProtocol::Vertex).unwrap(),
9813 json!("vertex")
9814 );
9815 assert_eq!(
9816 serde_json::to_value(&LlmProtocol::Bedrock).unwrap(),
9817 json!("bedrock")
9818 );
9819
9820 assert_eq!(
9821 serde_json::from_str::<LlmProtocol>("\"anthropic\"").unwrap(),
9822 LlmProtocol::Anthropic
9823 );
9824 assert_eq!(
9825 serde_json::from_str::<LlmProtocol>("\"openai\"").unwrap(),
9826 LlmProtocol::OpenAi
9827 );
9828 assert_eq!(
9829 serde_json::from_str::<LlmProtocol>("\"azure\"").unwrap(),
9830 LlmProtocol::Azure
9831 );
9832 assert_eq!(
9833 serde_json::from_str::<LlmProtocol>("\"vertex\"").unwrap(),
9834 LlmProtocol::Vertex
9835 );
9836 assert_eq!(
9837 serde_json::from_str::<LlmProtocol>("\"bedrock\"").unwrap(),
9838 LlmProtocol::Bedrock
9839 );
9840 }
9841
9842 #[cfg(feature = "unstable_llm_providers")]
9843 #[test]
9844 fn test_llm_protocol_unknown_variant() {
9845 let unknown: LlmProtocol = serde_json::from_str("\"cohere\"").unwrap();
9846 assert_eq!(unknown, LlmProtocol::Other("cohere".to_string()));
9847
9848 let json = serde_json::to_value(&unknown).unwrap();
9849 assert_eq!(json, json!("cohere"));
9850 }
9851
9852 #[cfg(feature = "unstable_llm_providers")]
9853 #[test]
9854 fn test_provider_current_config_serialization() {
9855 let config =
9856 ProviderCurrentConfig::new(LlmProtocol::Anthropic, "https://api.anthropic.com");
9857
9858 let json = serde_json::to_value(&config).unwrap();
9859 assert_eq!(
9860 json,
9861 json!({
9862 "apiType": "anthropic",
9863 "baseUrl": "https://api.anthropic.com"
9864 })
9865 );
9866
9867 let deserialized: ProviderCurrentConfig = serde_json::from_value(json).unwrap();
9868 assert_eq!(deserialized.api_type, LlmProtocol::Anthropic);
9869 assert_eq!(deserialized.base_url, "https://api.anthropic.com");
9870 }
9871
9872 #[cfg(feature = "unstable_llm_providers")]
9873 #[test]
9874 fn test_provider_info_with_current_config() {
9875 let info = ProviderInfo::new(
9876 "main",
9877 vec![LlmProtocol::Anthropic, LlmProtocol::OpenAi],
9878 true,
9879 Some(ProviderCurrentConfig::new(
9880 LlmProtocol::Anthropic,
9881 "https://api.anthropic.com",
9882 )),
9883 );
9884
9885 let json = serde_json::to_value(&info).unwrap();
9886 assert_eq!(
9887 json,
9888 json!({
9889 "providerId": "main",
9890 "supported": ["anthropic", "openai"],
9891 "required": true,
9892 "current": {
9893 "apiType": "anthropic",
9894 "baseUrl": "https://api.anthropic.com"
9895 }
9896 })
9897 );
9898
9899 let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
9900 assert_eq!(deserialized.provider_id.to_string(), "main");
9901 assert_eq!(deserialized.supported.len(), 2);
9902 assert!(deserialized.required);
9903 assert!(deserialized.current.is_some());
9904 assert_eq!(
9905 deserialized.current.as_ref().unwrap().api_type,
9906 LlmProtocol::Anthropic
9907 );
9908 }
9909
9910 #[cfg(feature = "unstable_llm_providers")]
9911 #[test]
9912 fn test_provider_info_disabled() {
9913 let info = ProviderInfo::new(
9914 "secondary",
9915 vec![LlmProtocol::OpenAi],
9916 false,
9917 None::<ProviderCurrentConfig>,
9918 );
9919
9920 let json = serde_json::to_value(&info).unwrap();
9921 assert_eq!(
9922 json,
9923 json!({
9924 "providerId": "secondary",
9925 "supported": ["openai"],
9926 "required": false
9927 })
9928 );
9929
9930 let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
9931 assert_eq!(deserialized.provider_id.to_string(), "secondary");
9932 assert!(!deserialized.required);
9933 assert!(deserialized.current.is_none());
9934 }
9935
9936 #[cfg(feature = "unstable_llm_providers")]
9937 #[test]
9938 fn test_provider_info_missing_current_defaults_to_none() {
9939 let json = json!({
9941 "providerId": "main",
9942 "supported": ["anthropic"],
9943 "required": true
9944 });
9945 let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
9946 assert!(deserialized.current.is_none());
9947 }
9948
9949 #[cfg(feature = "unstable_llm_providers")]
9950 #[test]
9951 fn test_provider_info_explicit_null_current_decodes_to_none() {
9952 let json = json!({
9956 "providerId": "main",
9957 "supported": ["anthropic"],
9958 "required": true,
9959 "current": null
9960 });
9961 let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
9962 assert!(deserialized.current.is_none());
9963 }
9964
9965 #[cfg(feature = "unstable_llm_providers")]
9966 #[test]
9967 fn test_list_providers_response_serialization() {
9968 let response = ListProvidersResponse::new(vec![ProviderInfo::new(
9969 "main",
9970 vec![LlmProtocol::Anthropic],
9971 true,
9972 Some(ProviderCurrentConfig::new(
9973 LlmProtocol::Anthropic,
9974 "https://api.anthropic.com",
9975 )),
9976 )]);
9977
9978 let json = serde_json::to_value(&response).unwrap();
9979 assert_eq!(json["providers"].as_array().unwrap().len(), 1);
9980 assert_eq!(json["providers"][0]["providerId"], "main");
9981
9982 let deserialized: ListProvidersResponse = serde_json::from_value(json).unwrap();
9983 assert_eq!(deserialized.providers.len(), 1);
9984 }
9985
9986 #[cfg(feature = "unstable_llm_providers")]
9987 #[test]
9988 fn test_set_provider_request_serialization() {
9989 use std::collections::HashMap;
9990
9991 let mut headers = HashMap::new();
9992 headers.insert("Authorization".to_string(), "Bearer sk-test".to_string());
9993
9994 let request =
9995 SetProviderRequest::new("main", LlmProtocol::OpenAi, "https://api.openai.com/v1")
9996 .headers(headers);
9997
9998 let json = serde_json::to_value(&request).unwrap();
9999 assert_eq!(
10000 json,
10001 json!({
10002 "providerId": "main",
10003 "apiType": "openai",
10004 "baseUrl": "https://api.openai.com/v1",
10005 "headers": {
10006 "Authorization": "Bearer sk-test"
10007 }
10008 })
10009 );
10010
10011 let deserialized: SetProviderRequest = serde_json::from_value(json).unwrap();
10012 assert_eq!(deserialized.provider_id.to_string(), "main");
10013 assert_eq!(deserialized.api_type, LlmProtocol::OpenAi);
10014 assert_eq!(deserialized.base_url, "https://api.openai.com/v1");
10015 assert_eq!(deserialized.headers.len(), 1);
10016 assert_eq!(
10017 deserialized.headers.get("Authorization").unwrap(),
10018 "Bearer sk-test"
10019 );
10020 }
10021
10022 #[cfg(feature = "unstable_llm_providers")]
10023 #[test]
10024 fn test_set_provider_request_omits_empty_headers() {
10025 let request =
10026 SetProviderRequest::new("main", LlmProtocol::Anthropic, "https://api.anthropic.com");
10027
10028 let json = serde_json::to_value(&request).unwrap();
10029 assert!(!json.as_object().unwrap().contains_key("headers"));
10031 }
10032
10033 #[cfg(feature = "unstable_llm_providers")]
10034 #[test]
10035 fn test_disable_provider_request_serialization() {
10036 let request = DisableProviderRequest::new("secondary");
10037
10038 let json = serde_json::to_value(&request).unwrap();
10039 assert_eq!(json, json!({ "providerId": "secondary" }));
10040
10041 let deserialized: DisableProviderRequest = serde_json::from_value(json).unwrap();
10042 assert_eq!(deserialized.provider_id.to_string(), "secondary");
10043 }
10044
10045 #[cfg(feature = "unstable_llm_providers")]
10046 #[test]
10047 fn test_providers_capabilities_serialization() {
10048 let caps = ProvidersCapabilities::new();
10049
10050 let json = serde_json::to_value(&caps).unwrap();
10051 assert_eq!(json, json!({}));
10052
10053 let deserialized: ProvidersCapabilities = serde_json::from_value(json).unwrap();
10054 assert!(deserialized.meta.is_none());
10055 }
10056
10057 #[cfg(feature = "unstable_llm_providers")]
10058 #[test]
10059 fn test_agent_capabilities_with_providers() {
10060 let caps = AgentCapabilities::new().providers(ProvidersCapabilities::new());
10061
10062 let json = serde_json::to_value(&caps).unwrap();
10063 assert_eq!(json["providers"], json!({}));
10064
10065 let deserialized: AgentCapabilities = serde_json::from_value(json).unwrap();
10066 assert!(deserialized.providers.is_some());
10067 }
10068
10069 #[test]
10070 fn test_agent_capabilities_session_is_explicit() {
10071 let json = serde_json::to_value(AgentCapabilities::new()).unwrap();
10072 assert!(json.get("session").is_none());
10073
10074 let caps = AgentCapabilities::new().session(
10075 SessionCapabilities::new()
10076 .prompt(PromptCapabilities::new().image(PromptImageCapabilities::new()))
10077 .mcp(McpCapabilities::new().stdio(McpStdioCapabilities::new())),
10078 );
10079
10080 assert_eq!(
10081 serde_json::to_value(&caps).unwrap(),
10082 json!({
10083 "session": {
10084 "prompt": {
10085 "image": {}
10086 },
10087 "mcp": {
10088 "stdio": {}
10089 }
10090 }
10091 })
10092 );
10093
10094 let deserialized: AgentCapabilities = serde_json::from_value(json!({
10095 "session": false
10096 }))
10097 .unwrap();
10098 assert!(deserialized.session.is_none());
10099 }
10100
10101 #[test]
10102 fn test_prompt_capabilities_serialize_supported_content_as_objects() {
10103 let caps = PromptCapabilities::new()
10104 .image(PromptImageCapabilities::new())
10105 .audio(PromptAudioCapabilities::new())
10106 .embedded_context(PromptEmbeddedContextCapabilities::new());
10107
10108 assert_eq!(
10109 serde_json::to_value(&caps).unwrap(),
10110 json!({
10111 "image": {},
10112 "audio": {},
10113 "embeddedContext": {}
10114 })
10115 );
10116
10117 let deserialized: PromptCapabilities = serde_json::from_value(json!({
10118 "image": null,
10119 "audio": false,
10120 "embeddedContext": {}
10121 }))
10122 .unwrap();
10123 assert!(deserialized.image.is_none());
10124 assert!(deserialized.audio.is_none());
10125 assert!(deserialized.embedded_context.is_some());
10126 }
10127
10128 #[test]
10129 fn test_mcp_capabilities_serialize_supported_transports_as_objects() {
10130 let caps = McpCapabilities::new()
10131 .stdio(McpStdioCapabilities::new())
10132 .http(McpHttpCapabilities::new());
10133
10134 assert_eq!(
10135 serde_json::to_value(&caps).unwrap(),
10136 json!({
10137 "stdio": {},
10138 "http": {}
10139 })
10140 );
10141
10142 let deserialized: McpCapabilities = serde_json::from_value(json!({
10143 "stdio": null,
10144 "http": false
10145 }))
10146 .unwrap();
10147 assert!(deserialized.stdio.is_none());
10148 assert!(deserialized.http.is_none());
10149 }
10150
10151 #[cfg(feature = "unstable_mcp_over_acp")]
10152 #[test]
10153 fn test_mcp_capabilities_serialize_acp_support_as_object() {
10154 let caps = McpCapabilities::new().acp(McpAcpCapabilities::new());
10155
10156 assert_eq!(
10157 serde_json::to_value(&caps).unwrap(),
10158 json!({
10159 "acp": {}
10160 })
10161 );
10162 }
10163
10164 #[test]
10165 fn prompt_request_rejects_malformed_content_block() {
10166 use serde_json::json;
10167
10168 assert!(
10169 serde_json::from_value::<PromptRequest>(json!({
10170 "sessionId": "sess-1",
10171 "prompt": [{"type": "text"}]
10172 }))
10173 .is_err()
10174 );
10175 }
10176
10177 #[test]
10178 fn prompt_request_rejects_non_array_prompt() {
10179 use serde_json::json;
10180
10181 assert!(
10182 serde_json::from_value::<PromptRequest>(json!({
10183 "sessionId": "sess-1",
10184 "prompt": "hello"
10185 }))
10186 .is_err()
10187 );
10188 }
10189
10190 fn assert_session_setup_lists_are_strict<T>(base: &serde_json::Value)
10191 where
10192 T: serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
10193 {
10194 let name = std::any::type_name::<T>();
10195 let with = |field: &str, value: serde_json::Value| {
10196 let mut request = base.clone();
10197 request[field] = value;
10198 serde_json::from_value::<T>(request)
10199 };
10200
10201 for (field, value) in [
10202 (
10204 "mcpServers",
10205 json!([
10206 {"type": "stdio", "name": "github", "command": "/usr/bin/gh-mcp", "env": [{"name": "GITHUB_TOKEN", "value": null}]},
10207 {"type": "stdio", "name": "fs", "command": "/usr/bin/fs-mcp"}
10208 ]),
10209 ),
10210 ("mcpServers", json!({"type": "stdio", "name": "fs"})),
10211 ("additionalDirectories", json!(["/repo/lib", 42])),
10212 ("additionalDirectories", json!("/repo/lib")),
10213 ] {
10214 assert!(
10215 with(field, value.clone()).is_err(),
10216 "{name}.{field}: {value}"
10217 );
10218 }
10219
10220 let empty = serde_json::from_value::<T>(base.clone()).unwrap();
10221 for field in ["mcpServers", "additionalDirectories"] {
10222 assert_eq!(
10223 with(field, serde_json::Value::Null).unwrap(),
10224 empty,
10225 "{name}.{field}"
10226 );
10227 }
10228 }
10229
10230 #[test]
10231 fn session_setup_requests_reject_malformed_mcp_servers_and_directories() {
10232 assert_session_setup_lists_are_strict::<NewSessionRequest>(&json!({"cwd": "/repo"}));
10233 assert_session_setup_lists_are_strict::<ResumeSessionRequest>(&json!({
10234 "sessionId": "sess-1",
10235 "cwd": "/repo"
10236 }));
10237 #[cfg(feature = "unstable_session_fork")]
10238 assert_session_setup_lists_are_strict::<ForkSessionRequest>(&json!({
10239 "sessionId": "sess-1",
10240 "cwd": "/repo"
10241 }));
10242 }
10243
10244 #[test]
10245 fn resume_session_request_rejects_malformed_replay_from() {
10246 let request = |replay_from: serde_json::Value| {
10247 serde_json::from_value::<ResumeSessionRequest>(json!({
10248 "sessionId": "sess-1",
10249 "cwd": "/repo",
10250 "replayFrom": replay_from
10251 }))
10252 };
10253
10254 assert!(request(json!("start")).is_err());
10256 assert_eq!(request(serde_json::Value::Null).unwrap().replay_from, None);
10257 assert!(matches!(
10258 request(json!({"type": "start"})).unwrap().replay_from,
10259 Some(ReplayFrom::Start(_))
10260 ));
10261 }
10262
10263 #[test]
10264 fn mcp_server_lists_treat_null_as_empty() {
10265 let servers: Vec<McpServer> = serde_json::from_value(json!([
10266 {"type": "stdio", "name": "fs", "command": "/usr/bin/fs-mcp", "args": null, "env": null},
10267 {"type": "http", "name": "api", "url": "https://example.com/mcp", "headers": null}
10268 ]))
10269 .unwrap();
10270
10271 assert_eq!(
10272 servers,
10273 vec![
10274 McpServer::Stdio(McpServerStdio::new("fs", "/usr/bin/fs-mcp")),
10275 McpServer::Http(McpServerHttp::new("api", "https://example.com/mcp")),
10276 ]
10277 );
10278 }
10279
10280 #[test]
10281 fn terminal_auth_methods_reject_malformed_launch_config() {
10282 let response: InitializeResponse = serde_json::from_value(json!({
10286 "protocolVersion": 2,
10287 "info": {"name": "agent", "version": "1.0.0"},
10288 "authMethods": [
10289 {"type": "terminal", "methodId": "bad-args", "name": "Log in", "args": ["auth", "--port", 8123]},
10290 {"type": "terminal", "methodId": "bad-env", "name": "Log in", "env": [{"name": "DEBUG", "value": 1}]},
10291 {"type": "terminal", "methodId": "null-config", "name": "Log in", "args": null, "env": null},
10292 {"type": "agent", "methodId": "agent", "name": "Agent login"}
10293 ]
10294 }))
10295 .unwrap();
10296
10297 assert_eq!(
10298 response.auth_methods,
10299 vec![
10300 AuthMethod::Terminal(AuthMethodTerminal::new("null-config", "Log in")),
10301 AuthMethod::Agent(AuthMethodAgent::new("agent", "Agent login")),
10302 ]
10303 );
10304 }
10305
10306 #[cfg(feature = "unstable_auth_status")]
10307 #[test]
10308 fn auth_status_response_round_trips() {
10309 let response = AuthStatusResponse::new(AuthState::Authenticated).accounts(vec![
10310 AuthAccount::new("Anthropic API key")
10311 .description("API key helper".to_string())
10312 .active(true),
10313 AuthAccount::new("Claude Max").email("user@example.com".to_string()),
10314 ]);
10315 let json = serde_json::to_value(&response).unwrap();
10316 assert_eq!(
10317 json,
10318 json!({
10319 "state": "authenticated",
10320 "accounts": [
10321 {
10322 "label": "Anthropic API key",
10323 "description": "API key helper",
10324 "active": true
10325 },
10326 {
10327 "label": "Claude Max",
10328 "email": "user@example.com"
10329 }
10330 ]
10331 })
10332 );
10333 assert_eq!(
10334 serde_json::from_value::<AuthStatusResponse>(json).unwrap(),
10335 response
10336 );
10337 assert_eq!(
10338 serde_json::to_value(AuthStatusResponse::new(AuthState::NotRequired)).unwrap(),
10339 json!({"state": "not_required"})
10340 );
10341 }
10342
10343 #[cfg(feature = "unstable_auth_status")]
10344 #[test]
10345 fn auth_status_state_is_strict_and_accounts_are_lenient() {
10346 assert!(serde_json::from_value::<AuthStatusResponse>(json!({})).is_err());
10347 assert!(serde_json::from_value::<AuthStatusResponse>(json!({"state": null})).is_err());
10348 assert!(serde_json::from_value::<AuthStatusResponse>(json!({"state": 1})).is_err());
10349
10350 let response: AuthStatusResponse = serde_json::from_value(json!({
10351 "state": "_vendor_state",
10352 "accounts": [
10353 {"active": true},
10354 {
10355 "label": "Vertex AI",
10356 "description": 42,
10357 "active": "yes",
10358 "email": ["not", "a", "string"]
10359 }
10360 ]
10361 }))
10362 .unwrap();
10363 assert_eq!(
10364 response,
10365 AuthStatusResponse::new(AuthState::Other("_vendor_state".to_string()))
10366 .accounts(vec![AuthAccount::new("Vertex AI")])
10367 );
10368 assert_eq!(
10369 serde_json::from_value::<AuthStatusResponse>(
10370 json!({"state": "unknown", "accounts": null})
10371 )
10372 .unwrap(),
10373 AuthStatusResponse::new(AuthState::Unknown)
10374 );
10375 }
10376
10377 #[cfg(feature = "unstable_auth_status")]
10378 #[test]
10379 fn auth_status_update_notification_routes() {
10380 use crate::v2::{AgentNotification, CLIENT_METHOD_NAMES};
10381
10382 assert_eq!(AGENT_METHOD_NAMES.auth_status, "auth/status");
10383 assert_eq!(CLIENT_METHOD_NAMES.auth_status_update, "auth/status_update");
10384 let notification = AgentNotification::AuthStatusUpdateNotification(Box::new(
10385 AuthStatusUpdateNotification::new(AuthState::Unauthenticated),
10386 ));
10387 assert_eq!(notification.method(), "auth/status_update");
10388 assert_eq!(
10389 serde_json::to_value(¬ification).unwrap(),
10390 json!({"state": "unauthenticated"})
10391 );
10392 }
10393}