Skip to main content

agent_client_protocol_schema/v1/
agent.rs

1//! Methods and notifications the agent handles/receives.
2//!
3//! This module defines the Agent trait and all associated types for implementing
4//! an AI coding agent that follows the Agent Client Protocol (ACP).
5
6use std::{path::PathBuf, sync::Arc};
7
8use std::collections::HashMap;
9
10use derive_more::{Display, From};
11use serde::{Deserialize, Serialize};
12use serde_with::{DefaultOnError, DefaultOnNull, VecSkipError, serde_as, skip_serializing_none};
13
14use crate::{IntoOption, ProtocolVersion};
15
16use super::{
17    ClientCapabilities, ContentBlock, ExtNotification, ExtRequest, ExtResponse, Meta, SessionId,
18};
19
20#[cfg(all(feature = "unstable_auth_status", feature = "schemars"))]
21use super::AUTH_STATUS_UPDATE_NOTIFICATION;
22#[cfg(feature = "unstable_mcp_over_acp")]
23use super::mcp::{MCP_MESSAGE_METHOD_NAME, MessageMcpNotification};
24
25// Initialize
26
27/// Request parameters for the initialize method.
28///
29/// Sent by the client to establish connection and negotiate capabilities.
30///
31/// See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/v1/initialization)
32#[serde_as]
33#[skip_serializing_none]
34#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
35#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
36#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = INITIALIZE_METHOD_NAME)))]
37#[serde(rename_all = "camelCase")]
38#[non_exhaustive]
39pub struct InitializeRequest {
40    /// The latest protocol version supported by the client.
41    pub protocol_version: ProtocolVersion,
42    /// Capabilities supported by the client.
43    #[serde_as(deserialize_as = "DefaultOnError")]
44    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
45    #[serde(default)]
46    pub client_capabilities: ClientCapabilities,
47    /// Information about the Client name and version sent to the Agent.
48    ///
49    /// Note: in future versions of the protocol, this will be required.
50    #[serde_as(deserialize_as = "DefaultOnError")]
51    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
52    #[serde(default)]
53    pub client_info: Option<Implementation>,
54    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
55    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
56    /// these keys.
57    ///
58    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
59    #[serde_as(deserialize_as = "DefaultOnError")]
60    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
61    #[serde(default)]
62    #[serde(rename = "_meta")]
63    pub meta: Option<Meta>,
64}
65
66impl InitializeRequest {
67    /// Builds [`InitializeRequest`] with the required request fields set. Optional fields start unset or empty.
68    #[must_use]
69    pub fn new(protocol_version: ProtocolVersion) -> Self {
70        Self {
71            protocol_version,
72            client_capabilities: ClientCapabilities::default(),
73            client_info: None,
74            meta: None,
75        }
76    }
77
78    /// Capabilities supported by the client.
79    #[must_use]
80    pub fn client_capabilities(mut self, client_capabilities: ClientCapabilities) -> Self {
81        self.client_capabilities = client_capabilities;
82        self
83    }
84
85    /// Information about the Client name and version sent to the Agent.
86    #[must_use]
87    pub fn client_info(mut self, client_info: impl IntoOption<Implementation>) -> Self {
88        self.client_info = client_info.into_option();
89        self
90    }
91
92    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
93    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
94    /// these keys.
95    ///
96    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
97    #[must_use]
98    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
99        self.meta = meta.into_option();
100        self
101    }
102}
103
104/// Response to the `initialize` method.
105///
106/// Contains the negotiated protocol version and agent capabilities.
107///
108/// See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/v1/initialization)
109#[serde_as]
110#[skip_serializing_none]
111#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
112#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
113#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = INITIALIZE_METHOD_NAME)))]
114#[serde(rename_all = "camelCase")]
115#[non_exhaustive]
116pub struct InitializeResponse {
117    /// The protocol version the client specified if supported by the agent,
118    /// or the latest protocol version supported by the agent.
119    ///
120    /// The client should disconnect, if it doesn't support this version.
121    pub protocol_version: ProtocolVersion,
122    /// Capabilities supported by the agent.
123    #[serde_as(deserialize_as = "DefaultOnError")]
124    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
125    #[serde(default)]
126    pub agent_capabilities: AgentCapabilities,
127    /// Authentication methods supported by the agent.
128    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
129    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
130    #[serde(default)]
131    pub auth_methods: Vec<AuthMethod>,
132    /// Information about the Agent name and version sent to the Client.
133    ///
134    /// Note: in future versions of the protocol, this will be required.
135    #[serde_as(deserialize_as = "DefaultOnError")]
136    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
137    #[serde(default)]
138    pub agent_info: Option<Implementation>,
139    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
140    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
141    /// these keys.
142    ///
143    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
144    #[serde_as(deserialize_as = "DefaultOnError")]
145    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
146    #[serde(default)]
147    #[serde(rename = "_meta")]
148    pub meta: Option<Meta>,
149}
150
151impl InitializeResponse {
152    /// Builds [`InitializeResponse`] with the required response fields set. Optional fields start unset or empty.
153    #[must_use]
154    pub fn new(protocol_version: ProtocolVersion) -> Self {
155        Self {
156            protocol_version,
157            agent_capabilities: AgentCapabilities::default(),
158            auth_methods: vec![],
159            agent_info: None,
160            meta: None,
161        }
162    }
163
164    /// Capabilities supported by the agent.
165    #[must_use]
166    pub fn agent_capabilities(mut self, agent_capabilities: AgentCapabilities) -> Self {
167        self.agent_capabilities = agent_capabilities;
168        self
169    }
170
171    /// Authentication methods supported by the agent.
172    #[must_use]
173    pub fn auth_methods(mut self, auth_methods: Vec<AuthMethod>) -> Self {
174        self.auth_methods = auth_methods;
175        self
176    }
177
178    /// Information about the Agent name and version sent to the Client.
179    #[must_use]
180    pub fn agent_info(mut self, agent_info: impl IntoOption<Implementation>) -> Self {
181        self.agent_info = agent_info.into_option();
182        self
183    }
184
185    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
186    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
187    /// these keys.
188    ///
189    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
190    #[must_use]
191    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
192        self.meta = meta.into_option();
193        self
194    }
195}
196
197/// Metadata about the implementation of the client or agent.
198/// Describes the name and version of an ACP implementation, with an optional
199/// title for UI representation.
200#[serde_as]
201#[skip_serializing_none]
202#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
203#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
204#[serde(rename_all = "camelCase")]
205#[non_exhaustive]
206pub struct Implementation {
207    /// Intended for programmatic or logical use, but can be used as a display
208    /// name fallback if title isn't present.
209    pub name: String,
210    /// Intended for UI and end-user contexts and optimized to be human-readable
211    /// and easily understood.
212    ///
213    /// If not provided, the name should be used for display.
214    #[serde_as(deserialize_as = "DefaultOnError")]
215    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
216    #[serde(default)]
217    pub title: Option<String>,
218    /// Version of the implementation. Can be displayed to the user or used
219    /// for debugging or metrics purposes. (e.g. "1.0.0").
220    pub version: String,
221    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
222    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
223    /// these keys.
224    ///
225    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
226    #[serde_as(deserialize_as = "DefaultOnError")]
227    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
228    #[serde(default)]
229    #[serde(rename = "_meta")]
230    pub meta: Option<Meta>,
231}
232
233impl Implementation {
234    /// Builds [`Implementation`] with the required fields set. Optional fields start unset or empty.
235    #[must_use]
236    pub fn new(name: impl Into<String>, version: impl Into<String>) -> Self {
237        Self {
238            name: name.into(),
239            title: None,
240            version: version.into(),
241            meta: None,
242        }
243    }
244
245    /// Intended for UI and end-user contexts and optimized to be human-readable
246    /// and easily understood.
247    ///
248    /// If not provided, the name should be used for display.
249    #[must_use]
250    pub fn title(mut self, title: impl IntoOption<String>) -> Self {
251        self.title = title.into_option();
252        self
253    }
254
255    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
256    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
257    /// these keys.
258    ///
259    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
260    #[must_use]
261    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
262        self.meta = meta.into_option();
263        self
264    }
265}
266
267// Authentication
268
269/// Request parameters for the authenticate method.
270///
271/// Specifies which authentication method to use.
272#[serde_as]
273#[skip_serializing_none]
274#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
275#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
276#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTHENTICATE_METHOD_NAME)))]
277#[serde(rename_all = "camelCase")]
278#[non_exhaustive]
279pub struct AuthenticateRequest {
280    /// The ID of the authentication method to use.
281    /// Must be one of the methods advertised in the initialize response.
282    pub method_id: AuthMethodId,
283    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
284    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
285    /// these keys.
286    ///
287    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
288    #[serde_as(deserialize_as = "DefaultOnError")]
289    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
290    #[serde(default)]
291    #[serde(rename = "_meta")]
292    pub meta: Option<Meta>,
293}
294
295impl AuthenticateRequest {
296    /// Builds [`AuthenticateRequest`] with the required request fields set. Optional fields start unset or empty.
297    #[must_use]
298    pub fn new(method_id: impl Into<AuthMethodId>) -> Self {
299        Self {
300            method_id: method_id.into(),
301            meta: None,
302        }
303    }
304
305    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
306    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
307    /// these keys.
308    ///
309    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
310    #[must_use]
311    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
312        self.meta = meta.into_option();
313        self
314    }
315}
316
317crate::serde_util::default_on_null! {
318    /// Response to the `authenticate` method.
319    #[serde_as]
320    #[skip_serializing_none]
321    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
322    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
323    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTHENTICATE_METHOD_NAME)))]
324    #[serde(rename_all = "camelCase")]
325    #[non_exhaustive]
326    pub struct AuthenticateResponse {
327        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
328        /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
329        /// these keys.
330        ///
331        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
332        #[serde_as(deserialize_as = "DefaultOnError")]
333        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
334        #[serde(default)]
335        #[serde(rename = "_meta")]
336        pub meta: Option<Meta>,
337    }
338}
339
340impl AuthenticateResponse {
341    /// Builds [`AuthenticateResponse`] with the required response fields set. Optional fields start unset or empty.
342    #[must_use]
343    pub fn new() -> Self {
344        Self::default()
345    }
346
347    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
348    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
349    /// these keys.
350    ///
351    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
352    #[must_use]
353    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
354        self.meta = meta.into_option();
355        self
356    }
357}
358
359// Logout
360
361crate::serde_util::default_on_null! {
362    /// Request parameters for the logout method.
363    ///
364    /// Terminates the current authenticated session.
365    #[serde_as]
366    #[skip_serializing_none]
367    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
368    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
369    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = LOGOUT_METHOD_NAME)))]
370    #[serde(rename_all = "camelCase")]
371    #[non_exhaustive]
372    pub struct LogoutRequest {
373        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
374        /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
375        /// these keys.
376        ///
377        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
378        #[serde_as(deserialize_as = "DefaultOnError")]
379        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
380        #[serde(default)]
381        #[serde(rename = "_meta")]
382        pub meta: Option<Meta>,
383    }
384}
385
386impl LogoutRequest {
387    /// Builds [`LogoutRequest`] with the required request fields set. Optional fields start unset or empty.
388    #[must_use]
389    pub fn new() -> Self {
390        Self::default()
391    }
392
393    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
394    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
395    /// these keys.
396    ///
397    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
398    #[must_use]
399    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
400        self.meta = meta.into_option();
401        self
402    }
403}
404
405crate::serde_util::default_on_null! {
406    /// Response to the `logout` method.
407    #[serde_as]
408    #[skip_serializing_none]
409    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
410    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
411    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = LOGOUT_METHOD_NAME)))]
412    #[serde(rename_all = "camelCase")]
413    #[non_exhaustive]
414    pub struct LogoutResponse {
415        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
416        /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
417        /// these keys.
418        ///
419        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
420        #[serde_as(deserialize_as = "DefaultOnError")]
421        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
422        #[serde(default)]
423        #[serde(rename = "_meta")]
424        pub meta: Option<Meta>,
425    }
426}
427
428impl LogoutResponse {
429    /// Builds [`LogoutResponse`] with the required response fields set. Optional fields start unset or empty.
430    #[must_use]
431    pub fn new() -> Self {
432        Self::default()
433    }
434
435    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
436    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
437    /// these keys.
438    ///
439    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
440    #[must_use]
441    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
442        self.meta = meta.into_option();
443        self
444    }
445}
446
447// Auth status
448
449#[cfg(feature = "unstable_auth_status")]
450crate::serde_util::default_on_null! {
451    /// **UNSTABLE**
452    ///
453    /// This capability is not part of the spec yet, and may be removed or changed at any point.
454    ///
455    /// Request parameters for the `auth/status` method.
456    ///
457    /// Queries the agent's current authentication state without changing it.
458    ///
459    /// Agents MUST NOT reject it with `auth_required` (`-32000`), since Clients call it to learn
460    /// whether authentication is required.
461    #[serde_as]
462    #[skip_serializing_none]
463    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
464    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
465    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_STATUS_METHOD_NAME)))]
466    #[serde(rename_all = "camelCase")]
467    #[non_exhaustive]
468    pub struct AuthStatusRequest {
469        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
470        /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
471        /// these keys.
472        ///
473        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
474        #[serde_as(deserialize_as = "DefaultOnError")]
475        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
476        #[serde(default)]
477        #[serde(rename = "_meta")]
478        pub meta: Option<Meta>,
479    }
480}
481
482#[cfg(feature = "unstable_auth_status")]
483impl AuthStatusRequest {
484    /// Builds [`AuthStatusRequest`] with the required request fields set. Optional fields start unset or empty.
485    #[must_use]
486    pub fn new() -> Self {
487        Self::default()
488    }
489
490    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
491    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
492    /// these keys.
493    ///
494    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
495    #[must_use]
496    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
497        self.meta = meta.into_option();
498        self
499    }
500}
501
502/// **UNSTABLE**
503///
504/// This capability is not part of the spec yet, and may be removed or changed at any point.
505///
506/// Response to the `auth/status` method.
507#[cfg(feature = "unstable_auth_status")]
508#[serde_as]
509#[skip_serializing_none]
510#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
511#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
512#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_STATUS_METHOD_NAME)))]
513#[serde(rename_all = "camelCase")]
514#[non_exhaustive]
515pub struct AuthStatusResponse {
516    /// Whether the agent can start sessions without the user signing in first.
517    ///
518    /// Clients use this field to decide whether sign-in is needed. Clients MUST treat
519    /// values they do not recognize as `unknown`.
520    pub state: AuthState,
521    /// The accounts the agent has configured, for display.
522    ///
523    /// Optional. Omitted and empty are equivalent and mean no accounts are reported.
524    /// Agents that hold credentials for several providers or accounts SHOULD list each
525    /// of them and mark the ones in effect with `active`.
526    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
527    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
528    #[serde(default, skip_serializing_if = "Vec::is_empty")]
529    pub accounts: Vec<AuthAccount>,
530    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
531    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
532    /// these keys.
533    ///
534    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
535    #[serde_as(deserialize_as = "DefaultOnError")]
536    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
537    #[serde(default)]
538    #[serde(rename = "_meta")]
539    pub meta: Option<Meta>,
540}
541
542#[cfg(feature = "unstable_auth_status")]
543impl AuthStatusResponse {
544    /// Builds [`AuthStatusResponse`] with the required fields set. Optional fields start unset or empty.
545    #[must_use]
546    pub fn new(state: AuthState) -> Self {
547        Self {
548            state,
549            accounts: vec![],
550            meta: None,
551        }
552    }
553
554    /// The accounts the agent has configured, for display.
555    #[must_use]
556    pub fn accounts(mut self, accounts: Vec<AuthAccount>) -> Self {
557        self.accounts = accounts;
558        self
559    }
560
561    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
562    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
563    /// these keys.
564    ///
565    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
566    #[must_use]
567    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
568        self.meta = meta.into_option();
569        self
570    }
571}
572
573/// **UNSTABLE**
574///
575/// This capability is not part of the spec yet, and may be removed or changed at any point.
576///
577/// Notification sent by the agent when its authentication status changes.
578///
579/// Carries the same fields as the `auth/status` response. Agents that advertise the
580/// `auth.status` capability MAY send it at any time after `initialize`, and SHOULD only
581/// send it when the reported status differs from the last one sent on the connection.
582#[cfg(feature = "unstable_auth_status")]
583#[serde_as]
584#[skip_serializing_none]
585#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
586#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
587#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = AUTH_STATUS_UPDATE_NOTIFICATION)))]
588#[serde(rename_all = "camelCase")]
589#[non_exhaustive]
590pub struct AuthStatusUpdateNotification {
591    /// Whether the agent can start sessions without the user signing in first.
592    ///
593    /// Clients use this field to decide whether sign-in is needed. Clients MUST treat
594    /// values they do not recognize as `unknown`.
595    pub state: AuthState,
596    /// The accounts the agent has configured, for display.
597    ///
598    /// Optional. Omitted and empty are equivalent and mean no accounts are reported.
599    /// Agents that hold credentials for several providers or accounts SHOULD list each
600    /// of them and mark the ones in effect with `active`.
601    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
602    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
603    #[serde(default, skip_serializing_if = "Vec::is_empty")]
604    pub accounts: Vec<AuthAccount>,
605    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
606    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
607    /// these keys.
608    ///
609    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
610    #[serde_as(deserialize_as = "DefaultOnError")]
611    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
612    #[serde(default)]
613    #[serde(rename = "_meta")]
614    pub meta: Option<Meta>,
615}
616
617#[cfg(feature = "unstable_auth_status")]
618impl AuthStatusUpdateNotification {
619    /// Builds [`AuthStatusUpdateNotification`] with the required fields set. Optional fields start unset or empty.
620    #[must_use]
621    pub fn new(state: AuthState) -> Self {
622        Self {
623            state,
624            accounts: vec![],
625            meta: None,
626        }
627    }
628
629    /// The accounts the agent has configured, for display.
630    #[must_use]
631    pub fn accounts(mut self, accounts: Vec<AuthAccount>) -> Self {
632        self.accounts = accounts;
633        self
634    }
635
636    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
637    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
638    /// these keys.
639    ///
640    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
641    #[must_use]
642    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
643        self.meta = meta.into_option();
644        self
645    }
646}
647
648/// **UNSTABLE**
649///
650/// This capability is not part of the spec yet, and may be removed or changed at any point.
651///
652/// The agent's overall authentication state.
653#[cfg(feature = "unstable_auth_status")]
654#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
655#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
656#[serde(rename_all = "snake_case")]
657#[non_exhaustive]
658pub enum AuthState {
659    /// Credentials are configured. This does not guarantee that they are valid.
660    Authenticated,
661    /// The user needs to sign in. This includes credentials that are missing,
662    /// expired, or known to be invalid.
663    Unauthenticated,
664    /// No authentication is needed, for example because the agent uses a local model.
665    NotRequired,
666    /// The agent cannot currently determine the state.
667    Unknown,
668    /// Custom or future authentication state.
669    ///
670    /// Values beginning with `_` are reserved for implementation-specific
671    /// extensions. Unknown values that do not begin with `_` are reserved for
672    /// future ACP variants.
673    #[serde(untagged)]
674    Other(String),
675}
676
677/// **UNSTABLE**
678///
679/// This capability is not part of the spec yet, and may be removed or changed at any point.
680///
681/// An account or credential the agent has configured, such as a signed-in user
682/// account or an API key.
683///
684/// All fields are display information only. Clients MUST NOT use them as stable
685/// account identifiers, and SHOULD NOT log them or send them elsewhere, such as to
686/// telemetry.
687#[cfg(feature = "unstable_auth_status")]
688#[serde_as]
689#[skip_serializing_none]
690#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
691#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
692#[serde(rename_all = "camelCase")]
693#[non_exhaustive]
694pub struct AuthAccount {
695    /// Human-readable name for the account, suitable for display on its own,
696    /// for example `Claude Max`, `OpenAI API key`, or `Vertex AI`.
697    pub label: String,
698    /// Short text shown with the label, such as the credential source, for example
699    /// `API key helper`. MUST NOT contain credentials.
700    ///
701    /// Optional. Omitted and `null` are equivalent and mean no description is reported.
702    #[serde_as(deserialize_as = "DefaultOnError")]
703    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
704    #[serde(default)]
705    pub description: Option<String>,
706    /// Whether the agent currently uses this account by default.
707    ///
708    /// Several accounts MAY be active, for example one per provider.
709    ///
710    /// Optional. Omitted and `null` are equivalent and mean the agent does not indicate whether this account is in effect.
711    #[serde_as(deserialize_as = "DefaultOnError")]
712    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
713    #[serde(default)]
714    pub active: Option<bool>,
715    /// Display name of the user, such as a username or full name.
716    ///
717    /// Optional. Omitted and `null` are equivalent and mean no name is reported.
718    #[serde_as(deserialize_as = "DefaultOnError")]
719    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
720    #[serde(default)]
721    pub name: Option<String>,
722    /// Email address of the user.
723    ///
724    /// Optional. Omitted and `null` are equivalent and mean no email is reported.
725    #[serde_as(deserialize_as = "DefaultOnError")]
726    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
727    #[serde(default)]
728    pub email: Option<String>,
729    /// Display name of the organization, team, or workspace the account is using.
730    ///
731    /// Optional. Omitted and `null` are equivalent and mean no organization is reported.
732    #[serde_as(deserialize_as = "DefaultOnError")]
733    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
734    #[serde(default)]
735    pub organization: Option<String>,
736    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
737    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
738    /// these keys.
739    ///
740    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
741    #[serde_as(deserialize_as = "DefaultOnError")]
742    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
743    #[serde(default)]
744    #[serde(rename = "_meta")]
745    pub meta: Option<Meta>,
746}
747
748#[cfg(feature = "unstable_auth_status")]
749impl AuthAccount {
750    /// Builds [`AuthAccount`] with the required fields set. Optional fields start unset or empty.
751    #[must_use]
752    pub fn new(label: impl Into<String>) -> Self {
753        Self {
754            label: label.into(),
755            description: None,
756            active: None,
757            name: None,
758            email: None,
759            organization: None,
760            meta: None,
761        }
762    }
763
764    /// Short text shown with the label, such as the credential source.
765    #[must_use]
766    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
767        self.description = description.into_option();
768        self
769    }
770
771    /// Whether the agent currently uses this account by default.
772    #[must_use]
773    pub fn active(mut self, active: impl IntoOption<bool>) -> Self {
774        self.active = active.into_option();
775        self
776    }
777
778    /// Display name of the user, such as a username or full name.
779    #[must_use]
780    pub fn name(mut self, name: impl IntoOption<String>) -> Self {
781        self.name = name.into_option();
782        self
783    }
784
785    /// Email address of the user.
786    #[must_use]
787    pub fn email(mut self, email: impl IntoOption<String>) -> Self {
788        self.email = email.into_option();
789        self
790    }
791
792    /// Display name of the organization, team, or workspace the account is using.
793    #[must_use]
794    pub fn organization(mut self, organization: impl IntoOption<String>) -> Self {
795        self.organization = organization.into_option();
796        self
797    }
798
799    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
800    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
801    /// these keys.
802    ///
803    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
804    #[must_use]
805    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
806        self.meta = meta.into_option();
807        self
808    }
809}
810
811/// **UNSTABLE**
812///
813/// This capability is not part of the spec yet, and may be removed or changed at any point.
814///
815/// Auth status capabilities supported by the agent.
816///
817/// Supplying `{}` means the agent supports the `auth/status` method.
818#[cfg(feature = "unstable_auth_status")]
819#[serde_as]
820#[skip_serializing_none]
821#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
822#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
823#[non_exhaustive]
824pub struct AuthStatusCapabilities {
825    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
826    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
827    /// these keys.
828    ///
829    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
830    #[serde_as(deserialize_as = "DefaultOnError")]
831    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
832    #[serde(default)]
833    #[serde(rename = "_meta")]
834    pub meta: Option<Meta>,
835}
836
837#[cfg(feature = "unstable_auth_status")]
838impl AuthStatusCapabilities {
839    /// Builds an empty [`AuthStatusCapabilities`]. Use builder methods to advertise supported sub-capabilities.
840    #[must_use]
841    pub fn new() -> Self {
842        Self::default()
843    }
844
845    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
846    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
847    /// these keys.
848    ///
849    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
850    #[must_use]
851    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
852        self.meta = meta.into_option();
853        self
854    }
855}
856
857/// Authentication-related capabilities supported by the agent.
858#[serde_as]
859#[skip_serializing_none]
860#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
861#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
862#[serde(rename_all = "camelCase")]
863#[non_exhaustive]
864pub struct AgentAuthCapabilities {
865    /// **UNSTABLE**
866    ///
867    /// This capability is not part of the spec yet, and may be removed or changed at any point.
868    ///
869    /// Whether the agent supports the `auth/status` method.
870    ///
871    /// Optional. Omitted or `null` both mean the agent does not advertise support.
872    /// Supplying `{}` means the agent supports the `auth/status` method.
873    #[cfg(feature = "unstable_auth_status")]
874    #[serde_as(deserialize_as = "DefaultOnError")]
875    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
876    #[serde(default)]
877    pub status: Option<AuthStatusCapabilities>,
878    /// Whether the agent supports the logout method.
879    ///
880    /// Optional. Omitted or `null` both mean the agent does not advertise support.
881    /// Supplying `{}` means the agent supports the logout method.
882    #[serde_as(deserialize_as = "DefaultOnError")]
883    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
884    #[serde(default)]
885    pub logout: Option<LogoutCapabilities>,
886    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
887    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
888    /// these keys.
889    ///
890    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
891    #[serde_as(deserialize_as = "DefaultOnError")]
892    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
893    #[serde(default)]
894    #[serde(rename = "_meta")]
895    pub meta: Option<Meta>,
896}
897
898impl AgentAuthCapabilities {
899    /// Builds an empty [`AgentAuthCapabilities`]. Use builder methods to advertise supported sub-capabilities.
900    #[must_use]
901    pub fn new() -> Self {
902        Self::default()
903    }
904
905    /// **UNSTABLE**
906    ///
907    /// This capability is not part of the spec yet, and may be removed or changed at any point.
908    ///
909    /// Whether the agent supports the `auth/status` method.
910    #[cfg(feature = "unstable_auth_status")]
911    #[must_use]
912    pub fn status(mut self, status: impl IntoOption<AuthStatusCapabilities>) -> Self {
913        self.status = status.into_option();
914        self
915    }
916
917    /// Whether the agent supports the logout method.
918    #[must_use]
919    pub fn logout(mut self, logout: impl IntoOption<LogoutCapabilities>) -> Self {
920        self.logout = logout.into_option();
921        self
922    }
923
924    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
925    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
926    /// these keys.
927    ///
928    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
929    #[must_use]
930    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
931        self.meta = meta.into_option();
932        self
933    }
934}
935
936/// Logout capabilities supported by the agent.
937///
938/// Supplying `{}` means the agent supports the logout method.
939#[serde_as]
940#[skip_serializing_none]
941#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
942#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
943#[non_exhaustive]
944pub struct LogoutCapabilities {
945    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
946    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
947    /// these keys.
948    ///
949    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
950    #[serde_as(deserialize_as = "DefaultOnError")]
951    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
952    #[serde(default)]
953    #[serde(rename = "_meta")]
954    pub meta: Option<Meta>,
955}
956
957impl LogoutCapabilities {
958    /// Builds an empty [`LogoutCapabilities`]. Use builder methods to advertise supported sub-capabilities.
959    #[must_use]
960    pub fn new() -> Self {
961        Self::default()
962    }
963
964    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
965    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
966    /// these keys.
967    ///
968    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
969    #[must_use]
970    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
971        self.meta = meta.into_option();
972        self
973    }
974}
975
976/// Typed identifier used for auth method values on the wire.
977#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
978#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
979#[serde(transparent)]
980#[from(Arc<str>, String, &'static str)]
981#[non_exhaustive]
982pub struct AuthMethodId(pub Arc<str>);
983
984impl AuthMethodId {
985    /// Wraps a protocol string as a typed [`AuthMethodId`].
986    #[must_use]
987    pub fn new(id: impl Into<Arc<str>>) -> Self {
988        Self(id.into())
989    }
990}
991
992/// Describes an available authentication method.
993///
994/// The `type` field acts as the discriminator in the serialized JSON form.
995/// When no `type` is present, the method is treated as `agent`.
996#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
997#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
998#[serde(tag = "type", rename_all = "snake_case")]
999#[non_exhaustive]
1000pub enum AuthMethod {
1001    /// Client runs the configured agent program as a separate interactive
1002    /// process, without passing this method to `authenticate`.
1003    Terminal(AuthMethodTerminal),
1004    /// Agent handles authentication itself through `authenticate`.
1005    ///
1006    /// This is the default when no `type` is specified.
1007    #[serde(untagged, deserialize_with = "deserialize_agent_auth_method_fallback")]
1008    Agent(AuthMethodAgent),
1009}
1010
1011/// Deserializes the untagged `agent` fallback of [`AuthMethod`].
1012///
1013/// A `terminal` method that fails its own schema must not fall through to
1014/// `agent`, or the client would pass it to `authenticate`.
1015fn deserialize_agent_auth_method_fallback<'de, D>(
1016    deserializer: D,
1017) -> Result<AuthMethodAgent, D::Error>
1018where
1019    D: serde::Deserializer<'de>,
1020{
1021    let value = serde_json::Value::deserialize(deserializer)?;
1022    if value.get("type").and_then(serde_json::Value::as_str) == Some("terminal") {
1023        return Err(serde::de::Error::custom(
1024            "known authentication method `terminal` did not match its schema",
1025        ));
1026    }
1027    AuthMethodAgent::deserialize(value).map_err(serde::de::Error::custom)
1028}
1029
1030impl AuthMethod {
1031    /// The unique identifier for this authentication method.
1032    #[must_use]
1033    pub fn id(&self) -> &AuthMethodId {
1034        match self {
1035            Self::Agent(a) => &a.id,
1036            Self::Terminal(t) => &t.id,
1037        }
1038    }
1039
1040    /// The human-readable name of this authentication method.
1041    #[must_use]
1042    pub fn name(&self) -> &str {
1043        match self {
1044            Self::Agent(a) => &a.name,
1045            Self::Terminal(t) => &t.name,
1046        }
1047    }
1048
1049    /// Optional human-readable description of this authentication method.
1050    #[must_use]
1051    pub fn description(&self) -> Option<&str> {
1052        match self {
1053            Self::Agent(a) => a.description.as_deref(),
1054            Self::Terminal(t) => t.description.as_deref(),
1055        }
1056    }
1057
1058    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1059    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1060    /// these keys.
1061    ///
1062    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1063    #[must_use]
1064    pub fn meta(&self) -> Option<&Meta> {
1065        match self {
1066            Self::Agent(a) => a.meta.as_ref(),
1067            Self::Terminal(t) => t.meta.as_ref(),
1068        }
1069    }
1070}
1071
1072/// Agent handles authentication itself through `authenticate`.
1073///
1074/// This is the default authentication method type.
1075#[serde_as]
1076#[skip_serializing_none]
1077#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1078#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1079#[serde(rename_all = "camelCase")]
1080#[non_exhaustive]
1081pub struct AuthMethodAgent {
1082    /// Unique identifier for this authentication method.
1083    pub id: AuthMethodId,
1084    /// Human-readable name of the authentication method.
1085    pub name: String,
1086    /// Optional human-readable description of this authentication method.
1087    #[serde_as(deserialize_as = "DefaultOnError")]
1088    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1089    #[serde(default)]
1090    pub description: Option<String>,
1091    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1092    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1093    /// these keys.
1094    ///
1095    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1096    #[serde_as(deserialize_as = "DefaultOnError")]
1097    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1098    #[serde(default)]
1099    #[serde(rename = "_meta")]
1100    pub meta: Option<Meta>,
1101}
1102
1103impl AuthMethodAgent {
1104    /// Builds [`AuthMethodAgent`] with the required fields set. Optional fields start unset or empty.
1105    #[must_use]
1106    pub fn new(id: impl Into<AuthMethodId>, name: impl Into<String>) -> Self {
1107        Self {
1108            id: id.into(),
1109            name: name.into(),
1110            description: None,
1111            meta: None,
1112        }
1113    }
1114
1115    /// Optional human-readable description of this authentication method.
1116    #[must_use]
1117    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
1118        self.description = description.into_option();
1119        self
1120    }
1121
1122    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1123    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1124    /// these keys.
1125    ///
1126    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1127    #[must_use]
1128    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1129        self.meta = meta.into_option();
1130        self
1131    }
1132}
1133
1134/// Terminal-based authentication method.
1135///
1136/// The client runs the configured agent program as a separate interactive
1137/// process for the user to authenticate via a TUI. Agents MUST advertise this
1138/// method only when the client enabled its terminal authentication capability.
1139/// A zero exit status signals success. Any other termination signals failure.
1140/// The client MUST NOT pass this method to `authenticate`.
1141#[serde_as]
1142#[skip_serializing_none]
1143#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1144#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1145#[serde(rename_all = "camelCase")]
1146#[non_exhaustive]
1147pub struct AuthMethodTerminal {
1148    /// Unique identifier for this authentication method.
1149    pub id: AuthMethodId,
1150    /// Human-readable name of the authentication method.
1151    pub name: String,
1152    /// Optional human-readable description of this authentication method.
1153    #[serde_as(deserialize_as = "DefaultOnError")]
1154    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1155    #[serde(default)]
1156    pub description: Option<String>,
1157    /// Additional arguments to append to the configured agent invocation for terminal auth.
1158    #[serde_as(deserialize_as = "DefaultOnNull")]
1159    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1160    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1161    pub args: Vec<String>,
1162    /// Additional environment variables to set on the configured agent invocation for terminal auth.
1163    /// These values override same-named variables in the base launch configuration.
1164    #[serde_as(deserialize_as = "DefaultOnNull")]
1165    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1166    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
1167    pub env: HashMap<String, String>,
1168    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1169    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1170    /// these keys.
1171    ///
1172    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1173    #[serde_as(deserialize_as = "DefaultOnError")]
1174    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1175    #[serde(default)]
1176    #[serde(rename = "_meta")]
1177    pub meta: Option<Meta>,
1178}
1179
1180impl AuthMethodTerminal {
1181    /// Builds [`AuthMethodTerminal`] with the required fields set. Optional fields start unset or empty.
1182    #[must_use]
1183    pub fn new(id: impl Into<AuthMethodId>, name: impl Into<String>) -> Self {
1184        Self {
1185            id: id.into(),
1186            name: name.into(),
1187            description: None,
1188            args: Vec::new(),
1189            env: HashMap::new(),
1190            meta: None,
1191        }
1192    }
1193
1194    /// Additional arguments to append to the configured agent invocation for terminal auth.
1195    #[must_use]
1196    pub fn args(mut self, args: Vec<String>) -> Self {
1197        self.args = args;
1198        self
1199    }
1200
1201    /// Additional environment variables to set on the configured agent invocation for terminal auth.
1202    /// These values override same-named variables in the base launch configuration.
1203    #[must_use]
1204    pub fn env(mut self, env: HashMap<String, String>) -> Self {
1205        self.env = env;
1206        self
1207    }
1208
1209    /// Optional human-readable description of this authentication method.
1210    #[must_use]
1211    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
1212        self.description = description.into_option();
1213        self
1214    }
1215
1216    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1217    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1218    /// these keys.
1219    ///
1220    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1221    #[must_use]
1222    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1223        self.meta = meta.into_option();
1224        self
1225    }
1226}
1227
1228// New session
1229
1230/// Request parameters for creating a new session.
1231///
1232/// See protocol docs: [Creating a Session](https://agentclientprotocol.com/protocol/v1/session-setup#creating-a-session)
1233#[serde_as]
1234#[skip_serializing_none]
1235#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1236#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1237#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_NEW_METHOD_NAME)))]
1238#[serde(rename_all = "camelCase")]
1239#[non_exhaustive]
1240pub struct NewSessionRequest {
1241    /// The working directory for this session. Must be an absolute path.
1242    pub cwd: PathBuf,
1243    /// Additional workspace roots for this session. Each path must be absolute.
1244    ///
1245    /// These expand the session's filesystem scope without changing `cwd`, which
1246    /// remains the base for relative paths. When omitted or empty, no
1247    /// additional roots are activated for the new session.
1248    #[serde_as(deserialize_as = "DefaultOnNull")]
1249    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1250    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1251    pub additional_directories: Vec<PathBuf>,
1252    /// List of MCP (Model Context Protocol) servers the agent should connect to.
1253    #[serde_as(deserialize_as = "DefaultOnNull")]
1254    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1255    pub mcp_servers: Vec<McpServer>,
1256    /// System-level instructions for the new session.
1257    ///
1258    /// Optional. Omitted and `null` are equivalent and mean the Agent uses its
1259    /// own default instructions. Clients MUST only send this when the Agent
1260    /// advertises `sessionCapabilities.systemPrompt`.
1261    #[serde(default)]
1262    pub system_prompt: Option<SystemPrompt>,
1263    /// **UNSTABLE**
1264    ///
1265    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1266    ///
1267    /// Initial values for the session's config options.
1268    ///
1269    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1270    /// this when the Agent advertises `sessionCapabilities.options`.
1271    ///
1272    /// The Agent applies the entries in list order, as if the Client had called
1273    /// `session/set_config_option` for each entry after the session was set up. Malformed
1274    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1275    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1276    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1277    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries.
1278    #[cfg(feature = "unstable_session_options")]
1279    #[serde_as(deserialize_as = "DefaultOnNull")]
1280    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1281    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1282    pub config_options: Vec<InitialSessionConfigOption>,
1283    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1284    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1285    /// these keys.
1286    ///
1287    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1288    #[serde_as(deserialize_as = "DefaultOnError")]
1289    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1290    #[serde(default)]
1291    #[serde(rename = "_meta")]
1292    pub meta: Option<Meta>,
1293}
1294
1295impl NewSessionRequest {
1296    /// Builds [`NewSessionRequest`] with the required request fields set. Optional fields start unset or empty.
1297    #[must_use]
1298    pub fn new(cwd: impl Into<PathBuf>) -> Self {
1299        Self {
1300            cwd: cwd.into(),
1301            additional_directories: vec![],
1302            mcp_servers: vec![],
1303            system_prompt: None,
1304            #[cfg(feature = "unstable_session_options")]
1305            config_options: vec![],
1306            meta: None,
1307        }
1308    }
1309
1310    /// Additional workspace roots for this session. Each path must be absolute.
1311    #[must_use]
1312    pub fn additional_directories(mut self, additional_directories: Vec<PathBuf>) -> Self {
1313        self.additional_directories = additional_directories;
1314        self
1315    }
1316
1317    /// List of MCP (Model Context Protocol) servers the agent should connect to.
1318    #[must_use]
1319    pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1320        self.mcp_servers = mcp_servers;
1321        self
1322    }
1323
1324    /// System-level instructions for the new session.
1325    #[must_use]
1326    pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1327        self.system_prompt = system_prompt.into_option();
1328        self
1329    }
1330
1331    /// **UNSTABLE**
1332    ///
1333    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1334    ///
1335    /// Initial values for the session's config options.
1336    ///
1337    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1338    /// this when the Agent advertises `sessionCapabilities.options`.
1339    ///
1340    /// The Agent applies the entries in list order, as if the Client had called
1341    /// `session/set_config_option` for each entry after the session was set up. Malformed
1342    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1343    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1344    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1345    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries.
1346    #[cfg(feature = "unstable_session_options")]
1347    #[must_use]
1348    pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1349        self.config_options = config_options;
1350        self
1351    }
1352
1353    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1354    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1355    /// these keys.
1356    ///
1357    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1358    #[must_use]
1359    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1360        self.meta = meta.into_option();
1361        self
1362    }
1363}
1364
1365/// Response from creating a new session.
1366///
1367/// See protocol docs: [Creating a Session](https://agentclientprotocol.com/protocol/v1/session-setup#creating-a-session)
1368#[serde_as]
1369#[skip_serializing_none]
1370#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1371#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1372#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_NEW_METHOD_NAME)))]
1373#[serde(rename_all = "camelCase")]
1374#[non_exhaustive]
1375pub struct NewSessionResponse {
1376    /// Unique identifier for the created session.
1377    ///
1378    /// Used in all subsequent requests for this conversation.
1379    pub session_id: SessionId,
1380    /// Initial mode state if supported by the Agent
1381    ///
1382    /// See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/v1/session-modes)
1383    #[serde_as(deserialize_as = "DefaultOnError")]
1384    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1385    #[serde(default)]
1386    pub modes: Option<SessionModeState>,
1387    /// Initial session configuration options if supported by the Agent.
1388    #[serde_as(deserialize_as = "DefaultOnError<Option<VecSkipError<_>>>")]
1389    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1390    #[serde(default)]
1391    pub config_options: Option<Vec<SessionConfigOption>>,
1392    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1393    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1394    /// these keys.
1395    ///
1396    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1397    #[serde_as(deserialize_as = "DefaultOnError")]
1398    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1399    #[serde(default)]
1400    #[serde(rename = "_meta")]
1401    pub meta: Option<Meta>,
1402}
1403
1404impl NewSessionResponse {
1405    /// Builds [`NewSessionResponse`] with the required response fields set. Optional fields start unset or empty.
1406    #[must_use]
1407    pub fn new(session_id: impl Into<SessionId>) -> Self {
1408        Self {
1409            session_id: session_id.into(),
1410            modes: None,
1411            config_options: None,
1412            meta: None,
1413        }
1414    }
1415
1416    /// Initial mode state if supported by the Agent
1417    ///
1418    /// See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/v1/session-modes)
1419    #[must_use]
1420    pub fn modes(mut self, modes: impl IntoOption<SessionModeState>) -> Self {
1421        self.modes = modes.into_option();
1422        self
1423    }
1424
1425    /// Initial session configuration options if supported by the Agent.
1426    #[must_use]
1427    pub fn config_options(
1428        mut self,
1429        config_options: impl IntoOption<Vec<SessionConfigOption>>,
1430    ) -> Self {
1431        self.config_options = config_options.into_option();
1432        self
1433    }
1434
1435    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1436    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1437    /// these keys.
1438    ///
1439    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1440    #[must_use]
1441    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1442        self.meta = meta.into_option();
1443        self
1444    }
1445}
1446
1447// Load session
1448
1449/// Request parameters for loading an existing session.
1450///
1451/// Only available if the Agent supports the `loadSession` capability.
1452///
1453/// See protocol docs: [Loading Sessions](https://agentclientprotocol.com/protocol/v1/session-setup#loading-sessions)
1454#[serde_as]
1455#[skip_serializing_none]
1456#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1457#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1458#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LOAD_METHOD_NAME)))]
1459#[serde(rename_all = "camelCase")]
1460#[non_exhaustive]
1461pub struct LoadSessionRequest {
1462    /// List of MCP servers to connect to for this session.
1463    #[serde_as(deserialize_as = "DefaultOnNull")]
1464    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1465    pub mcp_servers: Vec<McpServer>,
1466    /// The working directory for this session. Must be an absolute path.
1467    pub cwd: PathBuf,
1468    /// Additional workspace roots to activate for this session. Each path must be absolute.
1469    ///
1470    /// When omitted or empty, no additional roots are activated. When non-empty,
1471    /// this is the complete resulting additional-root list for the loaded
1472    /// session. It may differ from any previously used or reported list as long as
1473    /// the request `cwd` matches the session's `cwd`.
1474    #[serde_as(deserialize_as = "DefaultOnNull")]
1475    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1476    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1477    pub additional_directories: Vec<PathBuf>,
1478    /// The ID of the session to load.
1479    pub session_id: SessionId,
1480    /// System-level instructions for the loaded session.
1481    ///
1482    /// Optional. Omitted and `null` are equivalent. The Agent may then keep a
1483    /// system prompt it stored with the session or use its default instructions.
1484    /// Clients MUST only send this when the Agent advertises
1485    /// `sessionCapabilities.systemPrompt`, and SHOULD send the same value they used
1486    /// when the session was created.
1487    #[serde(default)]
1488    pub system_prompt: Option<SystemPrompt>,
1489    /// **UNSTABLE**
1490    ///
1491    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1492    ///
1493    /// Initial values for the session's config options.
1494    ///
1495    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1496    /// this when the Agent advertises `sessionCapabilities.options`.
1497    ///
1498    /// The Agent applies the entries in list order, as if the Client had called
1499    /// `session/set_config_option` for each entry after the session was set up. Malformed
1500    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1501    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1502    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1503    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries.
1504    #[cfg(feature = "unstable_session_options")]
1505    #[serde_as(deserialize_as = "DefaultOnNull")]
1506    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1507    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1508    pub config_options: Vec<InitialSessionConfigOption>,
1509    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1510    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1511    /// these keys.
1512    ///
1513    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1514    #[serde_as(deserialize_as = "DefaultOnError")]
1515    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1516    #[serde(default)]
1517    #[serde(rename = "_meta")]
1518    pub meta: Option<Meta>,
1519}
1520
1521impl LoadSessionRequest {
1522    /// Builds [`LoadSessionRequest`] with the required request fields set. Optional fields start unset or empty.
1523    #[must_use]
1524    pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<PathBuf>) -> Self {
1525        Self {
1526            mcp_servers: vec![],
1527            cwd: cwd.into(),
1528            additional_directories: vec![],
1529            session_id: session_id.into(),
1530            system_prompt: None,
1531            #[cfg(feature = "unstable_session_options")]
1532            config_options: vec![],
1533            meta: None,
1534        }
1535    }
1536
1537    /// Additional workspace roots to activate for this session. Each path must be absolute.
1538    #[must_use]
1539    pub fn additional_directories(mut self, additional_directories: Vec<PathBuf>) -> Self {
1540        self.additional_directories = additional_directories;
1541        self
1542    }
1543
1544    /// List of MCP servers to connect to for this session.
1545    #[must_use]
1546    pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1547        self.mcp_servers = mcp_servers;
1548        self
1549    }
1550
1551    /// System-level instructions for the loaded session.
1552    #[must_use]
1553    pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1554        self.system_prompt = system_prompt.into_option();
1555        self
1556    }
1557
1558    /// **UNSTABLE**
1559    ///
1560    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1561    ///
1562    /// Initial values for the session's config options.
1563    ///
1564    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1565    /// this when the Agent advertises `sessionCapabilities.options`.
1566    ///
1567    /// The Agent applies the entries in list order, as if the Client had called
1568    /// `session/set_config_option` for each entry after the session was set up. Malformed
1569    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1570    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1571    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1572    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries.
1573    #[cfg(feature = "unstable_session_options")]
1574    #[must_use]
1575    pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1576        self.config_options = config_options;
1577        self
1578    }
1579
1580    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1581    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1582    /// these keys.
1583    ///
1584    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1585    #[must_use]
1586    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1587        self.meta = meta.into_option();
1588        self
1589    }
1590}
1591
1592crate::serde_util::default_on_null! {
1593    /// Response from loading an existing session.
1594    #[serde_as]
1595    #[skip_serializing_none]
1596    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1597    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
1598    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LOAD_METHOD_NAME)))]
1599    #[serde(rename_all = "camelCase")]
1600    #[non_exhaustive]
1601    pub struct LoadSessionResponse {
1602        /// Initial mode state if supported by the Agent
1603        ///
1604        /// See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/v1/session-modes)
1605        #[serde_as(deserialize_as = "DefaultOnError")]
1606        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1607        #[serde(default)]
1608        pub modes: Option<SessionModeState>,
1609        /// Initial session configuration options if supported by the Agent.
1610        #[serde_as(deserialize_as = "DefaultOnError<Option<VecSkipError<_>>>")]
1611        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1612        #[serde(default)]
1613        pub config_options: Option<Vec<SessionConfigOption>>,
1614        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1615        /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1616        /// these keys.
1617        ///
1618        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1619        #[serde_as(deserialize_as = "DefaultOnError")]
1620        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1621        #[serde(default)]
1622        #[serde(rename = "_meta")]
1623        pub meta: Option<Meta>,
1624    }
1625}
1626
1627impl LoadSessionResponse {
1628    /// Builds [`LoadSessionResponse`] with the required response fields set. Optional fields start unset or empty.
1629    #[must_use]
1630    pub fn new() -> Self {
1631        Self::default()
1632    }
1633
1634    /// Initial mode state if supported by the Agent
1635    ///
1636    /// See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/v1/session-modes)
1637    #[must_use]
1638    pub fn modes(mut self, modes: impl IntoOption<SessionModeState>) -> Self {
1639        self.modes = modes.into_option();
1640        self
1641    }
1642
1643    /// Initial session configuration options if supported by the Agent.
1644    #[must_use]
1645    pub fn config_options(
1646        mut self,
1647        config_options: impl IntoOption<Vec<SessionConfigOption>>,
1648    ) -> Self {
1649        self.config_options = config_options.into_option();
1650        self
1651    }
1652
1653    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1654    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1655    /// these keys.
1656    ///
1657    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1658    #[must_use]
1659    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1660        self.meta = meta.into_option();
1661        self
1662    }
1663}
1664
1665// Fork session
1666
1667/// **UNSTABLE**
1668///
1669/// This capability is not part of the spec yet, and may be removed or changed at any point.
1670///
1671/// Request parameters for forking an existing session.
1672///
1673/// Creates a new session based on the context of an existing one, allowing
1674/// operations like generating summaries without affecting the original session's history.
1675///
1676/// Only available if the Agent supports the `session.fork` capability.
1677#[cfg(feature = "unstable_session_fork")]
1678#[serde_as]
1679#[skip_serializing_none]
1680#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1681#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1682#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_FORK_METHOD_NAME)))]
1683#[serde(rename_all = "camelCase")]
1684#[non_exhaustive]
1685pub struct ForkSessionRequest {
1686    /// The ID of the session to fork.
1687    pub session_id: SessionId,
1688    /// The working directory for this session. Must be an absolute path.
1689    pub cwd: PathBuf,
1690    /// Additional workspace roots to activate for this session. Each path must be absolute.
1691    ///
1692    /// When omitted or empty, no additional roots are activated. When non-empty,
1693    /// this is the complete resulting additional-root list for the forked
1694    /// session.
1695    #[serde_as(deserialize_as = "DefaultOnNull")]
1696    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1697    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1698    pub additional_directories: Vec<PathBuf>,
1699    /// List of MCP servers to connect to for this session.
1700    #[serde_as(deserialize_as = "DefaultOnNull")]
1701    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1702    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1703    pub mcp_servers: Vec<McpServer>,
1704    /// System-level instructions for the forked session.
1705    ///
1706    /// Optional. Omitted and `null` are equivalent. The Agent may then keep a
1707    /// system prompt it stored with the source session or use its default
1708    /// instructions. Clients MUST only send this when the Agent advertises
1709    /// `sessionCapabilities.systemPrompt`, and SHOULD send the same value they used
1710    /// for the source session.
1711    #[serde(default)]
1712    pub system_prompt: Option<SystemPrompt>,
1713    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1714    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1715    /// these keys.
1716    ///
1717    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1718    #[serde_as(deserialize_as = "DefaultOnError")]
1719    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1720    #[serde(default)]
1721    #[serde(rename = "_meta")]
1722    pub meta: Option<Meta>,
1723}
1724
1725#[cfg(feature = "unstable_session_fork")]
1726impl ForkSessionRequest {
1727    /// Builds [`ForkSessionRequest`] with the required request fields set. Optional fields start unset or empty.
1728    #[must_use]
1729    pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<PathBuf>) -> Self {
1730        Self {
1731            session_id: session_id.into(),
1732            cwd: cwd.into(),
1733            additional_directories: vec![],
1734            mcp_servers: vec![],
1735            system_prompt: None,
1736            meta: None,
1737        }
1738    }
1739
1740    /// Additional workspace roots to activate for this session. Each path must be absolute.
1741    #[must_use]
1742    pub fn additional_directories(mut self, additional_directories: Vec<PathBuf>) -> Self {
1743        self.additional_directories = additional_directories;
1744        self
1745    }
1746
1747    /// List of MCP servers to connect to for this session.
1748    #[must_use]
1749    pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1750        self.mcp_servers = mcp_servers;
1751        self
1752    }
1753
1754    /// System-level instructions for the forked session.
1755    #[must_use]
1756    pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1757        self.system_prompt = system_prompt.into_option();
1758        self
1759    }
1760
1761    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1762    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1763    /// these keys.
1764    ///
1765    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1766    #[must_use]
1767    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1768        self.meta = meta.into_option();
1769        self
1770    }
1771}
1772
1773/// **UNSTABLE**
1774///
1775/// This capability is not part of the spec yet, and may be removed or changed at any point.
1776///
1777/// Response from forking an existing session.
1778#[cfg(feature = "unstable_session_fork")]
1779#[serde_as]
1780#[skip_serializing_none]
1781#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1782#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1783#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_FORK_METHOD_NAME)))]
1784#[serde(rename_all = "camelCase")]
1785#[non_exhaustive]
1786pub struct ForkSessionResponse {
1787    /// Unique identifier for the newly created forked session.
1788    pub session_id: SessionId,
1789    /// Initial mode state if supported by the Agent
1790    ///
1791    /// See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/v1/session-modes)
1792    #[serde_as(deserialize_as = "DefaultOnError")]
1793    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1794    #[serde(default)]
1795    pub modes: Option<SessionModeState>,
1796    /// Initial session configuration options if supported by the Agent.
1797    #[serde_as(deserialize_as = "DefaultOnError<Option<VecSkipError<_>>>")]
1798    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1799    #[serde(default)]
1800    pub config_options: Option<Vec<SessionConfigOption>>,
1801    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1802    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1803    /// these keys.
1804    ///
1805    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1806    #[serde_as(deserialize_as = "DefaultOnError")]
1807    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1808    #[serde(default)]
1809    #[serde(rename = "_meta")]
1810    pub meta: Option<Meta>,
1811}
1812
1813#[cfg(feature = "unstable_session_fork")]
1814impl ForkSessionResponse {
1815    /// Builds [`ForkSessionResponse`] with the required response fields set. Optional fields start unset or empty.
1816    #[must_use]
1817    pub fn new(session_id: impl Into<SessionId>) -> Self {
1818        Self {
1819            session_id: session_id.into(),
1820            modes: None,
1821            config_options: None,
1822            meta: None,
1823        }
1824    }
1825
1826    /// Initial mode state if supported by the Agent
1827    ///
1828    /// See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/v1/session-modes)
1829    #[must_use]
1830    pub fn modes(mut self, modes: impl IntoOption<SessionModeState>) -> Self {
1831        self.modes = modes.into_option();
1832        self
1833    }
1834
1835    /// Initial session configuration options if supported by the Agent.
1836    #[must_use]
1837    pub fn config_options(
1838        mut self,
1839        config_options: impl IntoOption<Vec<SessionConfigOption>>,
1840    ) -> Self {
1841        self.config_options = config_options.into_option();
1842        self
1843    }
1844
1845    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1846    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1847    /// these keys.
1848    ///
1849    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1850    #[must_use]
1851    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1852        self.meta = meta.into_option();
1853        self
1854    }
1855}
1856
1857// Resume session
1858
1859/// Request parameters for resuming an existing session.
1860///
1861/// Resumes an existing session without returning previous messages (unlike `session/load`).
1862/// This is useful for agents that can resume sessions but don't implement full session loading.
1863///
1864/// Only available if the Agent supports the `sessionCapabilities.resume` capability.
1865#[serde_as]
1866#[skip_serializing_none]
1867#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1868#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1869#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_RESUME_METHOD_NAME)))]
1870#[serde(rename_all = "camelCase")]
1871#[non_exhaustive]
1872pub struct ResumeSessionRequest {
1873    /// The ID of the session to resume.
1874    pub session_id: SessionId,
1875    /// The working directory for this session. Must be an absolute path.
1876    pub cwd: PathBuf,
1877    /// Additional workspace roots to activate for this session. Each path must be absolute.
1878    ///
1879    /// When omitted or empty, no additional roots are activated. When non-empty,
1880    /// this is the complete resulting additional-root list for the resumed
1881    /// session. It may differ from any previously used or reported list as long as
1882    /// the request `cwd` matches the session's `cwd`.
1883    #[serde_as(deserialize_as = "DefaultOnNull")]
1884    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1885    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1886    pub additional_directories: Vec<PathBuf>,
1887    /// List of MCP servers to connect to for this session.
1888    #[serde_as(deserialize_as = "DefaultOnNull")]
1889    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1890    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1891    pub mcp_servers: Vec<McpServer>,
1892    /// System-level instructions for the resumed session.
1893    ///
1894    /// Optional. Omitted and `null` are equivalent. The Agent may then keep a
1895    /// system prompt it stored with the session or use its default instructions.
1896    /// Clients MUST only send this when the Agent advertises
1897    /// `sessionCapabilities.systemPrompt`, and SHOULD send the same value they used
1898    /// when the session was created.
1899    #[serde(default)]
1900    pub system_prompt: Option<SystemPrompt>,
1901    /// **UNSTABLE**
1902    ///
1903    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1904    ///
1905    /// Initial values for the session's config options.
1906    ///
1907    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1908    /// this when the Agent advertises `sessionCapabilities.options`.
1909    ///
1910    /// The Agent applies the entries in list order, as if the Client had called
1911    /// `session/set_config_option` for each entry after the session was set up. Malformed
1912    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1913    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1914    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1915    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries.
1916    #[cfg(feature = "unstable_session_options")]
1917    #[serde_as(deserialize_as = "DefaultOnNull")]
1918    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1919    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1920    pub config_options: Vec<InitialSessionConfigOption>,
1921    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1922    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1923    /// these keys.
1924    ///
1925    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1926    #[serde_as(deserialize_as = "DefaultOnError")]
1927    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1928    #[serde(default)]
1929    #[serde(rename = "_meta")]
1930    pub meta: Option<Meta>,
1931}
1932
1933impl ResumeSessionRequest {
1934    /// Builds [`ResumeSessionRequest`] with the required request fields set. Optional fields start unset or empty.
1935    #[must_use]
1936    pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<PathBuf>) -> Self {
1937        Self {
1938            session_id: session_id.into(),
1939            cwd: cwd.into(),
1940            additional_directories: vec![],
1941            mcp_servers: vec![],
1942            system_prompt: None,
1943            #[cfg(feature = "unstable_session_options")]
1944            config_options: vec![],
1945            meta: None,
1946        }
1947    }
1948
1949    /// Additional workspace roots to activate for this session. Each path must be absolute.
1950    #[must_use]
1951    pub fn additional_directories(mut self, additional_directories: Vec<PathBuf>) -> Self {
1952        self.additional_directories = additional_directories;
1953        self
1954    }
1955
1956    /// List of MCP servers to connect to for this session.
1957    #[must_use]
1958    pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1959        self.mcp_servers = mcp_servers;
1960        self
1961    }
1962
1963    /// System-level instructions for the resumed session.
1964    #[must_use]
1965    pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1966        self.system_prompt = system_prompt.into_option();
1967        self
1968    }
1969
1970    /// **UNSTABLE**
1971    ///
1972    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1973    ///
1974    /// Initial values for the session's config options.
1975    ///
1976    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1977    /// this when the Agent advertises `sessionCapabilities.options`.
1978    ///
1979    /// The Agent applies the entries in list order, as if the Client had called
1980    /// `session/set_config_option` for each entry after the session was set up. Malformed
1981    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1982    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1983    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1984    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries.
1985    #[cfg(feature = "unstable_session_options")]
1986    #[must_use]
1987    pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1988        self.config_options = config_options;
1989        self
1990    }
1991
1992    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1993    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1994    /// these keys.
1995    ///
1996    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1997    #[must_use]
1998    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1999        self.meta = meta.into_option();
2000        self
2001    }
2002}
2003
2004crate::serde_util::default_on_null! {
2005    /// Response from resuming an existing session.
2006    #[serde_as]
2007    #[skip_serializing_none]
2008    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2009    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2010    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_RESUME_METHOD_NAME)))]
2011    #[serde(rename_all = "camelCase")]
2012    #[non_exhaustive]
2013    pub struct ResumeSessionResponse {
2014        /// Initial mode state if supported by the Agent
2015        ///
2016        /// See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/v1/session-modes)
2017        #[serde_as(deserialize_as = "DefaultOnError")]
2018        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2019        #[serde(default)]
2020        pub modes: Option<SessionModeState>,
2021        /// Initial session configuration options if supported by the Agent.
2022        #[serde_as(deserialize_as = "DefaultOnError<Option<VecSkipError<_>>>")]
2023        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2024        #[serde(default)]
2025        pub config_options: Option<Vec<SessionConfigOption>>,
2026        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2027        /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2028        /// these keys.
2029        ///
2030        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2031        #[serde_as(deserialize_as = "DefaultOnError")]
2032        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2033        #[serde(default)]
2034        #[serde(rename = "_meta")]
2035        pub meta: Option<Meta>,
2036    }
2037}
2038
2039impl ResumeSessionResponse {
2040    /// Builds [`ResumeSessionResponse`] with the required response fields set. Optional fields start unset or empty.
2041    #[must_use]
2042    pub fn new() -> Self {
2043        Self::default()
2044    }
2045
2046    /// Initial mode state if supported by the Agent
2047    ///
2048    /// See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/v1/session-modes)
2049    #[must_use]
2050    pub fn modes(mut self, modes: impl IntoOption<SessionModeState>) -> Self {
2051        self.modes = modes.into_option();
2052        self
2053    }
2054
2055    /// Initial session configuration options if supported by the Agent.
2056    #[must_use]
2057    pub fn config_options(
2058        mut self,
2059        config_options: impl IntoOption<Vec<SessionConfigOption>>,
2060    ) -> Self {
2061        self.config_options = config_options.into_option();
2062        self
2063    }
2064
2065    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2066    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2067    /// these keys.
2068    ///
2069    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2070    #[must_use]
2071    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2072        self.meta = meta.into_option();
2073        self
2074    }
2075}
2076
2077// Close session
2078
2079/// Request parameters for closing an active session.
2080///
2081/// If supported, the agent **must** cancel any ongoing work related to the session
2082/// (treat it as if `session/cancel` was called) and then free up any resources
2083/// associated with the session.
2084///
2085/// Only available if the Agent supports the `sessionCapabilities.close` capability.
2086#[serde_as]
2087#[skip_serializing_none]
2088#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2089#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2090#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CLOSE_METHOD_NAME)))]
2091#[serde(rename_all = "camelCase")]
2092#[non_exhaustive]
2093pub struct CloseSessionRequest {
2094    /// The ID of the session to close.
2095    pub session_id: SessionId,
2096    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2097    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2098    /// these keys.
2099    ///
2100    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2101    #[serde_as(deserialize_as = "DefaultOnError")]
2102    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2103    #[serde(default)]
2104    #[serde(rename = "_meta")]
2105    pub meta: Option<Meta>,
2106}
2107
2108impl CloseSessionRequest {
2109    /// Builds [`CloseSessionRequest`] with the required request fields set. Optional fields start unset or empty.
2110    #[must_use]
2111    pub fn new(session_id: impl Into<SessionId>) -> Self {
2112        Self {
2113            session_id: session_id.into(),
2114            meta: None,
2115        }
2116    }
2117
2118    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2119    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2120    /// these keys.
2121    ///
2122    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2123    #[must_use]
2124    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2125        self.meta = meta.into_option();
2126        self
2127    }
2128}
2129
2130crate::serde_util::default_on_null! {
2131    /// Response from closing a session.
2132    #[serde_as]
2133    #[skip_serializing_none]
2134    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2135    #[derive(Default, Debug, Clone, Serialize, 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]
2139    pub struct CloseSessionResponse {
2140        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2141        /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2142        /// these keys.
2143        ///
2144        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2145        #[serde_as(deserialize_as = "DefaultOnError")]
2146        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2147        #[serde(default)]
2148        #[serde(rename = "_meta")]
2149        pub meta: Option<Meta>,
2150    }
2151}
2152
2153impl CloseSessionResponse {
2154    /// Builds [`CloseSessionResponse`] with the required response fields set. Optional fields start unset or empty.
2155    #[must_use]
2156    pub fn new() -> Self {
2157        Self::default()
2158    }
2159
2160    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2161    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2162    /// these keys.
2163    ///
2164    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2165    #[must_use]
2166    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2167        self.meta = meta.into_option();
2168        self
2169    }
2170}
2171
2172// Session status
2173
2174/// **UNSTABLE**
2175///
2176/// This capability is not part of the spec yet, and may be removed or changed at any point.
2177///
2178/// Request parameters for checking the status of a session.
2179///
2180/// Only available if the Agent supports the `sessionCapabilities.status` capability.
2181///
2182/// `session/status` MUST NOT have side effects. The Agent does not load, resume, create,
2183/// close, or change the session, and does not attach the requesting connection to it.
2184/// A session the Agent does not know gets `-32002` with the requested `sessionId` in `data`.
2185#[cfg(feature = "unstable_session_status")]
2186#[serde_as]
2187#[skip_serializing_none]
2188#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2189#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2190#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_STATUS_METHOD_NAME)))]
2191#[serde(rename_all = "camelCase")]
2192#[non_exhaustive]
2193pub struct SessionStatusRequest {
2194    /// The ID of the session to check.
2195    pub session_id: SessionId,
2196    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2197    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2198    /// these keys.
2199    ///
2200    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2201    #[serde_as(deserialize_as = "DefaultOnError")]
2202    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2203    #[serde(default)]
2204    #[serde(rename = "_meta")]
2205    pub meta: Option<Meta>,
2206}
2207
2208#[cfg(feature = "unstable_session_status")]
2209impl SessionStatusRequest {
2210    /// Builds [`SessionStatusRequest`] with the required request fields set. Optional fields start unset or empty.
2211    #[must_use]
2212    pub fn new(session_id: impl Into<SessionId>) -> Self {
2213        Self {
2214            session_id: session_id.into(),
2215            meta: None,
2216        }
2217    }
2218
2219    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2220    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2221    /// these keys.
2222    ///
2223    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2224    #[must_use]
2225    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2226        self.meta = meta.into_option();
2227        self
2228    }
2229}
2230
2231/// **UNSTABLE**
2232///
2233/// This capability is not part of the spec yet, and may be removed or changed at any point.
2234///
2235/// Response from checking the status of a session.
2236///
2237/// The result is a snapshot. A session reported `open` may be closed or evicted before
2238/// the Client's next request.
2239#[cfg(feature = "unstable_session_status")]
2240#[serde_as]
2241#[skip_serializing_none]
2242#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2243#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2244#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_STATUS_METHOD_NAME)))]
2245#[serde(rename_all = "camelCase")]
2246#[non_exhaustive]
2247pub struct SessionStatusResponse {
2248    /// Whether the Agent has the session in memory.
2249    ///
2250    /// Required. Clients MUST treat a value they do not recognize as `saved`.
2251    pub status: SessionStatus,
2252    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2253    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2254    /// these keys.
2255    ///
2256    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2257    #[serde_as(deserialize_as = "DefaultOnError")]
2258    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2259    #[serde(default)]
2260    #[serde(rename = "_meta")]
2261    pub meta: Option<Meta>,
2262}
2263
2264#[cfg(feature = "unstable_session_status")]
2265impl SessionStatusResponse {
2266    /// Builds [`SessionStatusResponse`] with the required response fields set. Optional fields start unset or empty.
2267    #[must_use]
2268    pub fn new(status: SessionStatus) -> Self {
2269        Self { status, meta: None }
2270    }
2271
2272    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2273    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2274    /// these keys.
2275    ///
2276    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2277    #[must_use]
2278    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2279        self.meta = meta.into_option();
2280        self
2281    }
2282}
2283
2284/// **UNSTABLE**
2285///
2286/// This capability is not part of the spec yet, and may be removed or changed at any point.
2287///
2288/// Whether the Agent has a session in memory, as reported by `session/status`.
2289#[cfg(feature = "unstable_session_status")]
2290#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2291#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2292#[serde(rename_all = "snake_case")]
2293#[non_exhaustive]
2294pub enum SessionStatus {
2295    /// The Agent has the session in memory, for any connection.
2296    ///
2297    /// This does not mean the requesting connection is attached to it. A Client that did
2298    /// not create or resume the session on its own connection MUST still call
2299    /// `session/load` or `session/resume` before sending `session/prompt` or expecting
2300    /// `session/update` notifications.
2301    Open,
2302    /// The Agent knows the session and can resume it, but does not have it in memory.
2303    ///
2304    /// The Client can call `session/load` or `session/resume` to start it.
2305    Saved,
2306    /// Custom or future session status.
2307    ///
2308    /// Values beginning with `_` are reserved for implementation-specific
2309    /// extensions. Unknown values that do not begin with `_` are reserved for
2310    /// future ACP variants. Clients MUST treat a value they do not recognize as
2311    /// `saved`.
2312    #[serde(untagged)]
2313    Other(String),
2314}
2315
2316/// **UNSTABLE**
2317///
2318/// This capability is not part of the spec yet, and may be removed or changed at any point.
2319///
2320/// Request parameters for `session/options`, which returns the config options a session
2321/// would start with, without creating or resuming a session.
2322///
2323/// Only available if the Agent supports the `sessionCapabilities.options` capability.
2324///
2325/// `session/options` MUST NOT create or resume a session, send `session/update`
2326/// notifications, add an entry to `session/list`, or change an existing session. Agents
2327/// SHOULD NOT connect to MCP servers to answer it.
2328#[cfg(feature = "unstable_session_options")]
2329#[serde_as]
2330#[skip_serializing_none]
2331#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2332#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2333#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_OPTIONS_METHOD_NAME)))]
2334#[serde(rename_all = "camelCase")]
2335#[non_exhaustive]
2336pub struct SessionOptionsRequest {
2337    /// The working directory to resolve options for. Must be an absolute path.
2338    pub cwd: PathBuf,
2339    /// Additional workspace roots to resolve options for. Each path must be absolute.
2340    ///
2341    /// Optional. Omitted and `null` are equivalent to an empty list.
2342    #[serde_as(deserialize_as = "DefaultOnNull")]
2343    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
2344    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2345    pub additional_directories: Vec<PathBuf>,
2346    /// The session to resolve options for.
2347    ///
2348    /// Optional. Omitted and `null` are equivalent and mean a new session. When present,
2349    /// the Agent returns what `session/load` or `session/resume` with the same `cwd` and
2350    /// `additionalDirectories` would return, with the same `cwd` rules. A session the
2351    /// Agent does not know gets `-32002`.
2352    /// Clients MUST only send this when the Agent supports `session/load` (`loadSession`)
2353    /// or `session/resume` (`sessionCapabilities.resume`).
2354    #[serde(default)]
2355    pub session_id: Option<SessionId>,
2356    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2357    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2358    /// these keys.
2359    ///
2360    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2361    #[serde_as(deserialize_as = "DefaultOnError")]
2362    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2363    #[serde(default)]
2364    #[serde(rename = "_meta")]
2365    pub meta: Option<Meta>,
2366}
2367
2368#[cfg(feature = "unstable_session_options")]
2369impl SessionOptionsRequest {
2370    /// Builds [`SessionOptionsRequest`] with the required request fields set. Optional fields start unset or empty.
2371    #[must_use]
2372    pub fn new(cwd: impl Into<PathBuf>) -> Self {
2373        Self {
2374            cwd: cwd.into(),
2375            additional_directories: vec![],
2376            session_id: None,
2377            meta: None,
2378        }
2379    }
2380
2381    /// Additional workspace roots to resolve options for. Each path must be absolute.
2382    #[must_use]
2383    pub fn additional_directories(mut self, additional_directories: Vec<PathBuf>) -> Self {
2384        self.additional_directories = additional_directories;
2385        self
2386    }
2387
2388    /// The session to resolve options for. Unset means a new session.
2389    #[must_use]
2390    pub fn session_id(mut self, session_id: impl IntoOption<SessionId>) -> Self {
2391        self.session_id = session_id.into_option();
2392        self
2393    }
2394
2395    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2396    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2397    /// these keys.
2398    ///
2399    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2400    #[must_use]
2401    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2402        self.meta = meta.into_option();
2403        self
2404    }
2405}
2406
2407#[cfg(feature = "unstable_session_options")]
2408crate::serde_util::default_on_null! {
2409    /// **UNSTABLE**
2410    ///
2411    /// This capability is not part of the spec yet, and may be removed or changed at any point.
2412    ///
2413    /// Response from `session/options`.
2414    ///
2415    /// The result is a snapshot. The options a session actually starts with are the ones in
2416    /// the session setup response.
2417    ///
2418    /// Agents only return `type: "boolean"` options when the Client advertises
2419    /// `sessionCapabilities.configOptions.boolean`.
2420    #[serde_as]
2421    #[skip_serializing_none]
2422    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2423    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2424    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_OPTIONS_METHOD_NAME)))]
2425    #[serde(rename_all = "camelCase")]
2426    #[non_exhaustive]
2427    pub struct SessionOptionsResponse {
2428        /// The mode state the session would start with, if the Agent supports modes.
2429        ///
2430        /// See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/v1/session-modes)
2431        #[serde_as(deserialize_as = "DefaultOnError")]
2432        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2433        #[serde(default)]
2434        pub modes: Option<SessionModeState>,
2435        /// The config options the session would start with, with the same rules as on
2436        /// `NewSessionResponse`.
2437        ///
2438        /// Optional. Omitted, `null`, or empty means no config options are advertised.
2439        #[serde_as(deserialize_as = "DefaultOnError<Option<VecSkipError<_>>>")]
2440        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2441        #[serde(default)]
2442        pub config_options: Option<Vec<SessionConfigOption>>,
2443        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2444        /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2445        /// these keys.
2446        ///
2447        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2448        #[serde_as(deserialize_as = "DefaultOnError")]
2449        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2450        #[serde(default)]
2451        #[serde(rename = "_meta")]
2452        pub meta: Option<Meta>,
2453    }
2454}
2455
2456#[cfg(feature = "unstable_session_options")]
2457impl SessionOptionsResponse {
2458    /// Builds [`SessionOptionsResponse`] with the required response fields set. Optional fields start unset or empty.
2459    #[must_use]
2460    pub fn new() -> Self {
2461        Self::default()
2462    }
2463
2464    /// The mode state the session would start with, if the Agent supports modes.
2465    ///
2466    /// See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/v1/session-modes)
2467    #[must_use]
2468    pub fn modes(mut self, modes: impl IntoOption<SessionModeState>) -> Self {
2469        self.modes = modes.into_option();
2470        self
2471    }
2472
2473    /// The config options the session would start with.
2474    #[must_use]
2475    pub fn config_options(
2476        mut self,
2477        config_options: impl IntoOption<Vec<SessionConfigOption>>,
2478    ) -> Self {
2479        self.config_options = config_options.into_option();
2480        self
2481    }
2482
2483    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2484    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2485    /// these keys.
2486    ///
2487    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2488    #[must_use]
2489    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2490        self.meta = meta.into_option();
2491        self
2492    }
2493}
2494
2495/// **UNSTABLE**
2496///
2497/// This capability is not part of the spec yet, and may be removed or changed at any point.
2498///
2499/// An initial value for a config option, sent on session setup requests.
2500///
2501/// Same shape as `session/set_config_option` without `sessionId`. Unlike
2502/// `session/set_config_option`, an unknown `configId`, a `type` that does not match the
2503/// option, or a value that is not allowed is ignored instead of rejected.
2504///
2505/// Clients only send `type: "boolean"` entries when they advertise
2506/// `sessionCapabilities.configOptions.boolean`.
2507#[cfg(feature = "unstable_session_options")]
2508#[serde_as]
2509#[skip_serializing_none]
2510#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2511#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2512#[serde(rename_all = "camelCase")]
2513#[non_exhaustive]
2514pub struct InitialSessionConfigOption {
2515    /// The ID of the configuration option to set.
2516    pub config_id: SessionConfigId,
2517    /// The value to set, including a `type` discriminator and the raw `value`.
2518    ///
2519    /// When `type` is absent on the wire, defaults to treating the value as a
2520    /// [`SessionConfigValueId`] for `select` options.
2521    #[serde(flatten)]
2522    pub value: SessionConfigOptionValue,
2523    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2524    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2525    /// these keys.
2526    ///
2527    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2528    #[serde_as(deserialize_as = "DefaultOnError")]
2529    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2530    #[serde(default)]
2531    #[serde(rename = "_meta")]
2532    pub meta: Option<Meta>,
2533}
2534
2535#[cfg(feature = "unstable_session_options")]
2536impl InitialSessionConfigOption {
2537    /// Builds [`InitialSessionConfigOption`] with the required fields set. Optional fields start unset or empty.
2538    #[must_use]
2539    pub fn new(
2540        config_id: impl Into<SessionConfigId>,
2541        value: impl Into<SessionConfigOptionValue>,
2542    ) -> Self {
2543        Self {
2544            config_id: config_id.into(),
2545            value: value.into(),
2546            meta: None,
2547        }
2548    }
2549
2550    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2551    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2552    /// these keys.
2553    ///
2554    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2555    #[must_use]
2556    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2557        self.meta = meta.into_option();
2558        self
2559    }
2560}
2561
2562// List sessions
2563
2564crate::serde_util::default_on_null! {
2565    /// Request parameters for listing existing sessions.
2566    ///
2567    /// Only available if the Agent supports the `sessionCapabilities.list` capability.
2568    #[serde_as]
2569    #[skip_serializing_none]
2570    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2571    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2572    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LIST_METHOD_NAME)))]
2573    #[serde(rename_all = "camelCase")]
2574    #[non_exhaustive]
2575    pub struct ListSessionsRequest {
2576        /// Filter sessions by working directory. Must be an absolute path.
2577        #[serde(default)]
2578        pub cwd: Option<PathBuf>,
2579        /// Opaque cursor token from a previous response's nextCursor field for cursor-based pagination
2580        #[serde(default)]
2581        pub cursor: Option<String>,
2582        /// **UNSTABLE**
2583        ///
2584        /// This capability is not part of the spec yet, and may be removed or changed at any point.
2585        ///
2586        /// Filter sessions by archive state.
2587        ///
2588        /// Optional. Omitted and `null` are equivalent and mean `exclude`. Only send this when
2589        /// the Agent advertises the `sessionCapabilities.archive` capability. The filter combines with `cwd` and
2590        /// applies before pagination. Clients keep the same value when following `nextCursor`.
2591        #[cfg(feature = "unstable_session_archive")]
2592        #[serde(default)]
2593        pub archived: Option<SessionArchiveFilter>,
2594        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2595        /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2596        /// these keys.
2597        ///
2598        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2599        #[serde_as(deserialize_as = "DefaultOnError")]
2600        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2601        #[serde(default)]
2602        #[serde(rename = "_meta")]
2603        pub meta: Option<Meta>,
2604    }
2605}
2606
2607impl ListSessionsRequest {
2608    /// Builds [`ListSessionsRequest`] with the required request fields set. Optional fields start unset or empty.
2609    #[must_use]
2610    pub fn new() -> Self {
2611        Self::default()
2612    }
2613
2614    /// Filter sessions by working directory. Must be an absolute path.
2615    #[must_use]
2616    pub fn cwd(mut self, cwd: impl IntoOption<PathBuf>) -> Self {
2617        self.cwd = cwd.into_option();
2618        self
2619    }
2620
2621    /// Opaque cursor token from a previous response's nextCursor field for cursor-based pagination
2622    #[must_use]
2623    pub fn cursor(mut self, cursor: impl IntoOption<String>) -> Self {
2624        self.cursor = cursor.into_option();
2625        self
2626    }
2627
2628    /// **UNSTABLE**
2629    ///
2630    /// This capability is not part of the spec yet, and may be removed or changed at any point.
2631    ///
2632    /// Filter sessions by archive state.
2633    #[cfg(feature = "unstable_session_archive")]
2634    #[must_use]
2635    pub fn archived(mut self, archived: impl IntoOption<SessionArchiveFilter>) -> Self {
2636        self.archived = archived.into_option();
2637        self
2638    }
2639
2640    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2641    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2642    /// these keys.
2643    ///
2644    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2645    #[must_use]
2646    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2647        self.meta = meta.into_option();
2648        self
2649    }
2650}
2651
2652/// Response from listing sessions.
2653#[serde_as]
2654#[skip_serializing_none]
2655#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2656#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2657#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LIST_METHOD_NAME)))]
2658#[serde(rename_all = "camelCase")]
2659#[non_exhaustive]
2660pub struct ListSessionsResponse {
2661    /// Array of session information objects
2662    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2663    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2664    pub sessions: Vec<SessionInfo>,
2665    /// Opaque cursor token. If present, pass this in the next request's cursor parameter
2666    /// to fetch the next page. If absent, there are no more results.
2667    #[serde_as(deserialize_as = "DefaultOnError")]
2668    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2669    #[serde(default)]
2670    pub next_cursor: Option<String>,
2671    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2672    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2673    /// these keys.
2674    ///
2675    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2676    #[serde_as(deserialize_as = "DefaultOnError")]
2677    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2678    #[serde(default)]
2679    #[serde(rename = "_meta")]
2680    pub meta: Option<Meta>,
2681}
2682
2683impl ListSessionsResponse {
2684    /// Builds [`ListSessionsResponse`] with the required response fields set. Optional fields start unset or empty.
2685    #[must_use]
2686    pub fn new(sessions: Vec<SessionInfo>) -> Self {
2687        Self {
2688            sessions,
2689            next_cursor: None,
2690            meta: None,
2691        }
2692    }
2693
2694    /// Sets or clears the optional `nextCursor` field.
2695    #[must_use]
2696    pub fn next_cursor(mut self, next_cursor: impl IntoOption<String>) -> Self {
2697        self.next_cursor = next_cursor.into_option();
2698        self
2699    }
2700
2701    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2702    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2703    /// these keys.
2704    ///
2705    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2706    #[must_use]
2707    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2708        self.meta = meta.into_option();
2709        self
2710    }
2711}
2712
2713// Delete session
2714
2715/// Request parameters for deleting an existing session from `session/list`.
2716///
2717/// Only available if the Agent supports the `sessionCapabilities.delete` capability.
2718#[serde_as]
2719#[skip_serializing_none]
2720#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2721#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2722#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_DELETE_METHOD_NAME)))]
2723#[serde(rename_all = "camelCase")]
2724#[non_exhaustive]
2725pub struct DeleteSessionRequest {
2726    /// The ID of the session to delete.
2727    pub session_id: SessionId,
2728    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2729    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2730    /// these keys.
2731    ///
2732    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2733    #[serde_as(deserialize_as = "DefaultOnError")]
2734    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2735    #[serde(default)]
2736    #[serde(rename = "_meta")]
2737    pub meta: Option<Meta>,
2738}
2739
2740impl DeleteSessionRequest {
2741    /// Builds [`DeleteSessionRequest`] with the required request fields set. Optional fields start unset or empty.
2742    #[must_use]
2743    pub fn new(session_id: impl Into<SessionId>) -> Self {
2744        Self {
2745            session_id: session_id.into(),
2746            meta: None,
2747        }
2748    }
2749
2750    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2751    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2752    /// these keys.
2753    ///
2754    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2755    #[must_use]
2756    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2757        self.meta = meta.into_option();
2758        self
2759    }
2760}
2761
2762crate::serde_util::default_on_null! {
2763    /// Response from deleting a session.
2764    #[serde_as]
2765    #[skip_serializing_none]
2766    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2767    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2768    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_DELETE_METHOD_NAME)))]
2769    #[serde(rename_all = "camelCase")]
2770    #[non_exhaustive]
2771    pub struct DeleteSessionResponse {
2772        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2773        /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2774        /// these keys.
2775        ///
2776        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2777        #[serde_as(deserialize_as = "DefaultOnError")]
2778        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2779        #[serde(default)]
2780        #[serde(rename = "_meta")]
2781        pub meta: Option<Meta>,
2782    }
2783}
2784
2785impl DeleteSessionResponse {
2786    /// Builds [`DeleteSessionResponse`] with the required response fields set. Optional fields start unset or empty.
2787    #[must_use]
2788    pub fn new() -> Self {
2789        Self::default()
2790    }
2791
2792    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2793    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2794    /// these keys.
2795    ///
2796    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2797    #[must_use]
2798    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2799        self.meta = meta.into_option();
2800        self
2801    }
2802}
2803
2804// Archive session
2805
2806/// **UNSTABLE**
2807///
2808/// This capability is not part of the spec yet, and may be removed or changed at any point.
2809///
2810/// Request parameters for archiving a session.
2811///
2812/// Only available if the Agent supports the `sessionCapabilities.archive` capability.
2813///
2814/// Archiving hides the session from default `session/list` results. It keeps the session ID
2815/// and saved history. If the session is active, the Agent MUST cancel any ongoing work and
2816/// free the session's resources as if `session/close` had been called, then archive it.
2817/// Archiving an archived session succeeds. A session that does not exist gets `-32002`.
2818///
2819#[cfg(feature = "unstable_session_archive")]
2820#[serde_as]
2821#[skip_serializing_none]
2822#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2823#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2824#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_ARCHIVE_METHOD_NAME)))]
2825#[serde(rename_all = "camelCase")]
2826#[non_exhaustive]
2827pub struct ArchiveSessionRequest {
2828    /// The ID of the session to archive.
2829    pub session_id: SessionId,
2830    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2831    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2832    /// these keys.
2833    ///
2834    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2835    #[serde_as(deserialize_as = "DefaultOnError")]
2836    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2837    #[serde(default)]
2838    #[serde(rename = "_meta")]
2839    pub meta: Option<Meta>,
2840}
2841
2842#[cfg(feature = "unstable_session_archive")]
2843impl ArchiveSessionRequest {
2844    /// Builds [`ArchiveSessionRequest`] with the required request fields set. Optional fields start unset or empty.
2845    #[must_use]
2846    pub fn new(session_id: impl Into<SessionId>) -> Self {
2847        Self {
2848            session_id: session_id.into(),
2849            meta: None,
2850        }
2851    }
2852
2853    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2854    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2855    /// these keys.
2856    ///
2857    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2858    #[must_use]
2859    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2860        self.meta = meta.into_option();
2861        self
2862    }
2863}
2864
2865#[cfg(feature = "unstable_session_archive")]
2866crate::serde_util::default_on_null! {
2867    /// **UNSTABLE**
2868    ///
2869    /// This capability is not part of the spec yet, and may be removed or changed at any point.
2870    ///
2871    /// Response from archiving a session.
2872    #[serde_as]
2873    #[skip_serializing_none]
2874    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2875    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2876    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_ARCHIVE_METHOD_NAME)))]
2877    #[serde(rename_all = "camelCase")]
2878    #[non_exhaustive]
2879    pub struct ArchiveSessionResponse {
2880        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2881        /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2882        /// these keys.
2883        ///
2884        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2885        #[serde_as(deserialize_as = "DefaultOnError")]
2886        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2887        #[serde(default)]
2888        #[serde(rename = "_meta")]
2889        pub meta: Option<Meta>,
2890    }
2891}
2892
2893#[cfg(feature = "unstable_session_archive")]
2894impl ArchiveSessionResponse {
2895    /// Builds [`ArchiveSessionResponse`] with the required response fields set. Optional fields start unset or empty.
2896    #[must_use]
2897    pub fn new() -> Self {
2898        Self::default()
2899    }
2900
2901    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2902    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2903    /// these keys.
2904    ///
2905    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2906    #[must_use]
2907    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2908        self.meta = meta.into_option();
2909        self
2910    }
2911}
2912
2913/// **UNSTABLE**
2914///
2915/// This capability is not part of the spec yet, and may be removed or changed at any point.
2916///
2917/// Request parameters for unarchiving a session.
2918///
2919/// Only available if the Agent supports the `sessionCapabilities.archive` capability.
2920///
2921/// Unarchiving returns the session to default `session/list` results with the same ID and
2922/// saved history. It never loads or resumes the session. Clients that want to continue an
2923/// archived session SHOULD unarchive it before calling `session/load` or `session/resume`.
2924/// Unarchiving a session that is not archived succeeds. A session that does not exist
2925/// gets `-32002`.
2926///
2927#[cfg(feature = "unstable_session_archive")]
2928#[serde_as]
2929#[skip_serializing_none]
2930#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2931#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2932#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_UNARCHIVE_METHOD_NAME)))]
2933#[serde(rename_all = "camelCase")]
2934#[non_exhaustive]
2935pub struct UnarchiveSessionRequest {
2936    /// The ID of the session to unarchive.
2937    pub session_id: SessionId,
2938    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2939    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2940    /// these keys.
2941    ///
2942    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2943    #[serde_as(deserialize_as = "DefaultOnError")]
2944    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2945    #[serde(default)]
2946    #[serde(rename = "_meta")]
2947    pub meta: Option<Meta>,
2948}
2949
2950#[cfg(feature = "unstable_session_archive")]
2951impl UnarchiveSessionRequest {
2952    /// Builds [`UnarchiveSessionRequest`] with the required request fields set. Optional fields start unset or empty.
2953    #[must_use]
2954    pub fn new(session_id: impl Into<SessionId>) -> Self {
2955        Self {
2956            session_id: session_id.into(),
2957            meta: None,
2958        }
2959    }
2960
2961    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2962    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2963    /// these keys.
2964    ///
2965    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2966    #[must_use]
2967    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2968        self.meta = meta.into_option();
2969        self
2970    }
2971}
2972
2973#[cfg(feature = "unstable_session_archive")]
2974crate::serde_util::default_on_null! {
2975    /// **UNSTABLE**
2976    ///
2977    /// This capability is not part of the spec yet, and may be removed or changed at any point.
2978    ///
2979    /// Response from unarchiving a session.
2980    #[serde_as]
2981    #[skip_serializing_none]
2982    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2983    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2984    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_UNARCHIVE_METHOD_NAME)))]
2985    #[serde(rename_all = "camelCase")]
2986    #[non_exhaustive]
2987    pub struct UnarchiveSessionResponse {
2988        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2989        /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2990        /// these keys.
2991        ///
2992        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2993        #[serde_as(deserialize_as = "DefaultOnError")]
2994        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2995        #[serde(default)]
2996        #[serde(rename = "_meta")]
2997        pub meta: Option<Meta>,
2998    }
2999}
3000
3001#[cfg(feature = "unstable_session_archive")]
3002impl UnarchiveSessionResponse {
3003    /// Builds [`UnarchiveSessionResponse`] with the required response fields set. Optional fields start unset or empty.
3004    #[must_use]
3005    pub fn new() -> Self {
3006        Self::default()
3007    }
3008
3009    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3010    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3011    /// these keys.
3012    ///
3013    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3014    #[must_use]
3015    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3016        self.meta = meta.into_option();
3017        self
3018    }
3019}
3020
3021/// **UNSTABLE**
3022///
3023/// This capability is not part of the spec yet, and may be removed or changed at any point.
3024///
3025/// Which sessions `session/list` returns based on their archive state.
3026///
3027/// Unknown values are preserved so they can be stored, proxied, or forwarded. An Agent MUST
3028/// return `-32602` for a value it does not support rather than treating it as `exclude`.
3029#[cfg(feature = "unstable_session_archive")]
3030#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3031#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
3032#[serde(rename_all = "snake_case")]
3033#[non_exhaustive]
3034pub enum SessionArchiveFilter {
3035    /// Only sessions that are not archived. This is the default.
3036    #[default]
3037    Exclude,
3038    /// Both archived sessions and sessions that are not archived.
3039    Include,
3040    /// Only archived sessions.
3041    Only,
3042    /// Custom or future archive filter.
3043    ///
3044    /// Values beginning with `_` are reserved for implementation-specific
3045    /// extensions. Unknown values that do not begin with `_` are reserved for
3046    /// future ACP variants.
3047    #[serde(untagged)]
3048    Other(String),
3049}
3050
3051/// Information about a session returned by session/list
3052#[serde_as]
3053#[skip_serializing_none]
3054#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3055#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3056#[serde(rename_all = "camelCase")]
3057#[non_exhaustive]
3058pub struct SessionInfo {
3059    /// Unique identifier for the session
3060    pub session_id: SessionId,
3061    /// The working directory for this session. Must be an absolute path.
3062    pub cwd: PathBuf,
3063    /// Additional workspace roots reported for this session. Each path must be absolute.
3064    ///
3065    /// When present, this is the complete ordered additional-root list reported
3066    /// by the Agent. Omitted and empty values are equivalent: the response
3067    /// reports no additional roots.
3068    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
3069    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3070    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3071    pub additional_directories: Vec<PathBuf>,
3072
3073    /// Human-readable title for the session
3074    #[serde_as(deserialize_as = "DefaultOnError")]
3075    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3076    #[serde(default)]
3077    pub title: Option<String>,
3078    /// ISO 8601 timestamp of last activity
3079    #[serde_as(deserialize_as = "DefaultOnError")]
3080    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3081    #[serde(default)]
3082    pub updated_at: Option<String>,
3083    /// **UNSTABLE**
3084    ///
3085    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3086    ///
3087    /// Whether the session is archived.
3088    ///
3089    /// Optional. Omitted and `null` are equivalent and mean the archive state is not reported.
3090    /// Agents that advertise the `sessionCapabilities.archive` capability MUST include it on every listed session.
3091    #[cfg(feature = "unstable_session_archive")]
3092    #[serde_as(deserialize_as = "DefaultOnError")]
3093    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3094    #[serde(default)]
3095    pub archived: Option<bool>,
3096    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3097    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3098    /// these keys.
3099    ///
3100    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3101    #[serde_as(deserialize_as = "DefaultOnError")]
3102    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3103    #[serde(default)]
3104    #[serde(rename = "_meta")]
3105    pub meta: Option<Meta>,
3106}
3107
3108impl SessionInfo {
3109    /// Builds [`SessionInfo`] with the required fields set. Optional fields start unset or empty.
3110    #[must_use]
3111    pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<PathBuf>) -> Self {
3112        Self {
3113            session_id: session_id.into(),
3114            cwd: cwd.into(),
3115            additional_directories: vec![],
3116            title: None,
3117            updated_at: None,
3118            #[cfg(feature = "unstable_session_archive")]
3119            archived: None,
3120            meta: None,
3121        }
3122    }
3123
3124    /// Additional workspace roots reported for this session. Each path must be absolute.
3125    #[must_use]
3126    pub fn additional_directories(mut self, additional_directories: Vec<PathBuf>) -> Self {
3127        self.additional_directories = additional_directories;
3128        self
3129    }
3130
3131    /// Human-readable title for the session
3132    #[must_use]
3133    pub fn title(mut self, title: impl IntoOption<String>) -> Self {
3134        self.title = title.into_option();
3135        self
3136    }
3137
3138    /// ISO 8601 timestamp of last activity
3139    #[must_use]
3140    pub fn updated_at(mut self, updated_at: impl IntoOption<String>) -> Self {
3141        self.updated_at = updated_at.into_option();
3142        self
3143    }
3144
3145    /// **UNSTABLE**
3146    ///
3147    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3148    ///
3149    /// Whether the session is archived.
3150    #[cfg(feature = "unstable_session_archive")]
3151    #[must_use]
3152    pub fn archived(mut self, archived: impl IntoOption<bool>) -> Self {
3153        self.archived = archived.into_option();
3154        self
3155    }
3156
3157    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3158    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3159    /// these keys.
3160    ///
3161    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3162    #[must_use]
3163    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3164        self.meta = meta.into_option();
3165        self
3166    }
3167}
3168
3169// Set session title
3170
3171/// **UNSTABLE**
3172///
3173/// This capability is not part of the spec yet, and may be removed or changed at any point.
3174///
3175/// Request parameters for setting the title of a session.
3176///
3177/// Only available if the Agent supports the `sessionCapabilities.title` capability.
3178///
3179/// The session does not need to be active on the connection. Any session the Agent would
3180/// return from `session/list` can be retitled. A session that does not exist gets `-32002`.
3181///
3182/// The Agent responds only after it has stored the title. After a successful response, the
3183/// Agent SHOULD NOT replace the title with one it generates automatically.
3184#[cfg(feature = "unstable_session_set_title")]
3185#[serde_as]
3186#[skip_serializing_none]
3187#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3188#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3189#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_TITLE_METHOD_NAME)))]
3190#[serde(rename_all = "camelCase")]
3191#[non_exhaustive]
3192pub struct SetSessionTitleRequest {
3193    /// The ID of the session to retitle.
3194    pub session_id: SessionId,
3195    /// The new title for the session.
3196    ///
3197    /// Required and non-null. Omission and explicit `null` are both invalid. The Agent MAY
3198    /// normalize the title before storing it, for example by trimming whitespace or
3199    /// truncating it. The Agent rejects a title that fails its validation, including one
3200    /// that is empty after normalization, with `-32602`.
3201    pub title: String,
3202    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3203    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3204    /// these keys.
3205    ///
3206    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3207    #[serde_as(deserialize_as = "DefaultOnError")]
3208    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3209    #[serde(default)]
3210    #[serde(rename = "_meta")]
3211    pub meta: Option<Meta>,
3212}
3213
3214#[cfg(feature = "unstable_session_set_title")]
3215impl SetSessionTitleRequest {
3216    /// Builds [`SetSessionTitleRequest`] with the required request fields set. Optional fields start unset or empty.
3217    #[must_use]
3218    pub fn new(session_id: impl Into<SessionId>, title: impl Into<String>) -> Self {
3219        Self {
3220            session_id: session_id.into(),
3221            title: title.into(),
3222            meta: None,
3223        }
3224    }
3225
3226    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3227    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3228    /// these keys.
3229    ///
3230    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3231    #[must_use]
3232    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3233        self.meta = meta.into_option();
3234        self
3235    }
3236}
3237
3238/// **UNSTABLE**
3239///
3240/// This capability is not part of the spec yet, and may be removed or changed at any point.
3241///
3242/// Response from setting the title of a session.
3243#[cfg(feature = "unstable_session_set_title")]
3244#[serde_as]
3245#[skip_serializing_none]
3246#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3247#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3248#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_TITLE_METHOD_NAME)))]
3249#[serde(rename_all = "camelCase")]
3250#[non_exhaustive]
3251pub struct SetSessionTitleResponse {
3252    /// The title the Agent stored.
3253    ///
3254    /// This differs from the requested title if the Agent normalized it. Clients SHOULD
3255    /// display this value rather than the one they sent.
3256    pub title: String,
3257    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3258    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3259    /// these keys.
3260    ///
3261    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3262    #[serde_as(deserialize_as = "DefaultOnError")]
3263    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3264    #[serde(default)]
3265    #[serde(rename = "_meta")]
3266    pub meta: Option<Meta>,
3267}
3268
3269#[cfg(feature = "unstable_session_set_title")]
3270impl SetSessionTitleResponse {
3271    /// Builds [`SetSessionTitleResponse`] with the required response fields set. Optional fields start unset or empty.
3272    #[must_use]
3273    pub fn new(title: impl Into<String>) -> Self {
3274        Self {
3275            title: title.into(),
3276            meta: None,
3277        }
3278    }
3279
3280    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3281    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3282    /// these keys.
3283    ///
3284    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3285    #[must_use]
3286    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3287        self.meta = meta.into_option();
3288        self
3289    }
3290}
3291
3292// Session modes
3293
3294/// The set of modes and the one currently active.
3295#[serde_as]
3296#[skip_serializing_none]
3297#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3298#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3299#[serde(rename_all = "camelCase")]
3300#[non_exhaustive]
3301pub struct SessionModeState {
3302    /// The current mode the Agent is in.
3303    pub current_mode_id: SessionModeId,
3304    /// The set of modes that the Agent can operate in
3305    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
3306    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3307    pub available_modes: Vec<SessionMode>,
3308    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3309    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3310    /// these keys.
3311    ///
3312    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3313    #[serde_as(deserialize_as = "DefaultOnError")]
3314    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3315    #[serde(default)]
3316    #[serde(rename = "_meta")]
3317    pub meta: Option<Meta>,
3318}
3319
3320impl SessionModeState {
3321    /// Builds [`SessionModeState`] with the required fields set. Optional fields start unset or empty.
3322    #[must_use]
3323    pub fn new(
3324        current_mode_id: impl Into<SessionModeId>,
3325        available_modes: Vec<SessionMode>,
3326    ) -> Self {
3327        Self {
3328            current_mode_id: current_mode_id.into(),
3329            available_modes,
3330            meta: None,
3331        }
3332    }
3333
3334    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3335    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3336    /// these keys.
3337    ///
3338    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3339    #[must_use]
3340    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3341        self.meta = meta.into_option();
3342        self
3343    }
3344}
3345
3346/// A mode the agent can operate in.
3347///
3348/// See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/v1/session-modes)
3349#[serde_as]
3350#[skip_serializing_none]
3351#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3352#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3353#[serde(rename_all = "camelCase")]
3354#[non_exhaustive]
3355pub struct SessionMode {
3356    /// Stable identifier used to refer to this protocol object in later messages.
3357    pub id: SessionModeId,
3358    /// Human-readable name shown for this protocol object.
3359    pub name: String,
3360    /// Optional human-readable details shown with this protocol object.
3361    #[serde_as(deserialize_as = "DefaultOnError")]
3362    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3363    #[serde(default)]
3364    pub description: Option<String>,
3365    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3366    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3367    /// these keys.
3368    ///
3369    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3370    #[serde_as(deserialize_as = "DefaultOnError")]
3371    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3372    #[serde(default)]
3373    #[serde(rename = "_meta")]
3374    pub meta: Option<Meta>,
3375}
3376
3377impl SessionMode {
3378    /// Builds [`SessionMode`] with the required fields set. Optional fields start unset or empty.
3379    #[must_use]
3380    pub fn new(id: impl Into<SessionModeId>, name: impl Into<String>) -> Self {
3381        Self {
3382            id: id.into(),
3383            name: name.into(),
3384            description: None,
3385            meta: None,
3386        }
3387    }
3388
3389    /// Sets or clears the optional `description` field.
3390    #[must_use]
3391    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
3392        self.description = description.into_option();
3393        self
3394    }
3395
3396    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3397    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3398    /// these keys.
3399    ///
3400    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3401    #[must_use]
3402    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3403        self.meta = meta.into_option();
3404        self
3405    }
3406}
3407
3408/// Unique identifier for a Session Mode.
3409#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3410#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3411#[serde(transparent)]
3412#[from(Arc<str>, String, &'static str)]
3413#[non_exhaustive]
3414pub struct SessionModeId(pub Arc<str>);
3415
3416impl SessionModeId {
3417    /// Wraps a protocol string as a typed [`SessionModeId`].
3418    #[must_use]
3419    pub fn new(id: impl Into<Arc<str>>) -> Self {
3420        Self(id.into())
3421    }
3422}
3423
3424/// Request parameters for setting a session mode.
3425#[serde_as]
3426#[skip_serializing_none]
3427#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3428#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3429#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_MODE_METHOD_NAME)))]
3430#[serde(rename_all = "camelCase")]
3431#[non_exhaustive]
3432pub struct SetSessionModeRequest {
3433    /// The ID of the session to set the mode for.
3434    pub session_id: SessionId,
3435    /// The ID of the mode to set.
3436    pub mode_id: SessionModeId,
3437    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3438    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3439    /// these keys.
3440    ///
3441    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3442    #[serde_as(deserialize_as = "DefaultOnError")]
3443    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3444    #[serde(default)]
3445    #[serde(rename = "_meta")]
3446    pub meta: Option<Meta>,
3447}
3448
3449impl SetSessionModeRequest {
3450    /// Builds [`SetSessionModeRequest`] with the required request fields set. Optional fields start unset or empty.
3451    #[must_use]
3452    pub fn new(session_id: impl Into<SessionId>, mode_id: impl Into<SessionModeId>) -> Self {
3453        Self {
3454            session_id: session_id.into(),
3455            mode_id: mode_id.into(),
3456            meta: None,
3457        }
3458    }
3459
3460    /// Sets or clears ACP `_meta` extension metadata.
3461    #[must_use]
3462    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3463        self.meta = meta.into_option();
3464        self
3465    }
3466}
3467
3468crate::serde_util::default_on_null! {
3469    /// Response to `session/set_mode` method.
3470    #[serde_as]
3471    #[skip_serializing_none]
3472    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3473    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3474    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_MODE_METHOD_NAME)))]
3475    #[serde(rename_all = "camelCase")]
3476    #[non_exhaustive]
3477    pub struct SetSessionModeResponse {
3478        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3479        /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3480        /// these keys.
3481        ///
3482        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3483        #[serde_as(deserialize_as = "DefaultOnError")]
3484        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3485        #[serde(default)]
3486        #[serde(rename = "_meta")]
3487        pub meta: Option<Meta>,
3488    }
3489}
3490
3491impl SetSessionModeResponse {
3492    /// Builds [`SetSessionModeResponse`] with the required response fields set. Optional fields start unset or empty.
3493    #[must_use]
3494    pub fn new() -> Self {
3495        Self::default()
3496    }
3497
3498    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3499    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3500    /// these keys.
3501    ///
3502    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3503    #[must_use]
3504    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3505        self.meta = meta.into_option();
3506        self
3507    }
3508}
3509
3510// Session config options
3511
3512/// Unique identifier for a session configuration option.
3513#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3514#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3515#[serde(transparent)]
3516#[from(Arc<str>, String, &'static str)]
3517#[non_exhaustive]
3518pub struct SessionConfigId(pub Arc<str>);
3519
3520impl SessionConfigId {
3521    /// Wraps a protocol string as a typed [`SessionConfigId`].
3522    #[must_use]
3523    pub fn new(id: impl Into<Arc<str>>) -> Self {
3524        Self(id.into())
3525    }
3526}
3527
3528/// Unique identifier for a session configuration option value.
3529#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3530#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3531#[serde(transparent)]
3532#[from(Arc<str>, String, &'static str)]
3533#[non_exhaustive]
3534pub struct SessionConfigValueId(pub Arc<str>);
3535
3536impl SessionConfigValueId {
3537    /// Wraps a protocol string as a typed [`SessionConfigValueId`].
3538    #[must_use]
3539    pub fn new(id: impl Into<Arc<str>>) -> Self {
3540        Self(id.into())
3541    }
3542}
3543
3544/// Unique identifier for a session configuration option value group.
3545#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3546#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3547#[serde(transparent)]
3548#[from(Arc<str>, String, &'static str)]
3549#[non_exhaustive]
3550pub struct SessionConfigGroupId(pub Arc<str>);
3551
3552impl SessionConfigGroupId {
3553    /// Wraps a protocol string as a typed [`SessionConfigGroupId`].
3554    #[must_use]
3555    pub fn new(id: impl Into<Arc<str>>) -> Self {
3556        Self(id.into())
3557    }
3558}
3559
3560/// A possible value for a session configuration option.
3561#[serde_as]
3562#[skip_serializing_none]
3563#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3564#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3565#[serde(rename_all = "camelCase")]
3566#[non_exhaustive]
3567pub struct SessionConfigSelectOption {
3568    /// Unique identifier for this option value.
3569    pub value: SessionConfigValueId,
3570    /// Human-readable label for this option value.
3571    pub name: String,
3572    /// Optional description for this option value.
3573    #[serde_as(deserialize_as = "DefaultOnError")]
3574    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3575    #[serde(default)]
3576    pub description: Option<String>,
3577    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3578    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3579    /// these keys.
3580    ///
3581    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3582    #[serde_as(deserialize_as = "DefaultOnError")]
3583    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3584    #[serde(default)]
3585    #[serde(rename = "_meta")]
3586    pub meta: Option<Meta>,
3587}
3588
3589impl SessionConfigSelectOption {
3590    /// Builds [`SessionConfigSelectOption`] with the required fields set. Optional fields start unset or empty.
3591    #[must_use]
3592    pub fn new(value: impl Into<SessionConfigValueId>, name: impl Into<String>) -> Self {
3593        Self {
3594            value: value.into(),
3595            name: name.into(),
3596            description: None,
3597            meta: None,
3598        }
3599    }
3600
3601    /// Sets or clears the optional `description` field.
3602    #[must_use]
3603    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
3604        self.description = description.into_option();
3605        self
3606    }
3607
3608    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3609    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3610    /// these keys.
3611    ///
3612    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3613    #[must_use]
3614    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3615        self.meta = meta.into_option();
3616        self
3617    }
3618}
3619
3620/// A group of possible values for a session configuration option.
3621#[serde_as]
3622#[skip_serializing_none]
3623#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3624#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3625#[serde(rename_all = "camelCase")]
3626#[non_exhaustive]
3627pub struct SessionConfigSelectGroup {
3628    /// Unique identifier for this group.
3629    pub group: SessionConfigGroupId,
3630    /// Human-readable label for this group.
3631    pub name: String,
3632    /// The set of option values in this group.
3633    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
3634    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3635    pub options: Vec<SessionConfigSelectOption>,
3636    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3637    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3638    /// these keys.
3639    ///
3640    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3641    #[serde_as(deserialize_as = "DefaultOnError")]
3642    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3643    #[serde(default)]
3644    #[serde(rename = "_meta")]
3645    pub meta: Option<Meta>,
3646}
3647
3648impl SessionConfigSelectGroup {
3649    /// Builds [`SessionConfigSelectGroup`] with the required fields set. Optional fields start unset or empty.
3650    #[must_use]
3651    pub fn new(
3652        group: impl Into<SessionConfigGroupId>,
3653        name: impl Into<String>,
3654        options: Vec<SessionConfigSelectOption>,
3655    ) -> Self {
3656        Self {
3657            group: group.into(),
3658            name: name.into(),
3659            options,
3660            meta: None,
3661        }
3662    }
3663
3664    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3665    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3666    /// these keys.
3667    ///
3668    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3669    #[must_use]
3670    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3671        self.meta = meta.into_option();
3672        self
3673    }
3674}
3675
3676/// Possible values for a session configuration option.
3677#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3678#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3679#[serde(untagged)]
3680#[non_exhaustive]
3681pub enum SessionConfigSelectOptions {
3682    /// A flat list of options with no grouping.
3683    Ungrouped(Vec<SessionConfigSelectOption>),
3684    /// A list of options grouped under headers.
3685    Grouped(Vec<SessionConfigSelectGroup>),
3686}
3687
3688impl From<Vec<SessionConfigSelectOption>> for SessionConfigSelectOptions {
3689    fn from(options: Vec<SessionConfigSelectOption>) -> Self {
3690        SessionConfigSelectOptions::Ungrouped(options)
3691    }
3692}
3693
3694impl From<Vec<SessionConfigSelectGroup>> for SessionConfigSelectOptions {
3695    fn from(groups: Vec<SessionConfigSelectGroup>) -> Self {
3696        SessionConfigSelectOptions::Grouped(groups)
3697    }
3698}
3699
3700/// A single-value selector (dropdown) session configuration option payload.
3701#[skip_serializing_none]
3702#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3703#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3704#[serde(rename_all = "camelCase")]
3705#[non_exhaustive]
3706pub struct SessionConfigSelect {
3707    /// The currently selected value.
3708    pub current_value: SessionConfigValueId,
3709    /// The set of selectable options.
3710    pub options: SessionConfigSelectOptions,
3711}
3712
3713impl SessionConfigSelect {
3714    /// Builds [`SessionConfigSelect`] with the required fields set. Optional fields start unset or empty.
3715    #[must_use]
3716    pub fn new(
3717        current_value: impl Into<SessionConfigValueId>,
3718        options: impl Into<SessionConfigSelectOptions>,
3719    ) -> Self {
3720        Self {
3721            current_value: current_value.into(),
3722            options: options.into(),
3723        }
3724    }
3725}
3726
3727/// A boolean on/off toggle session configuration option payload.
3728#[skip_serializing_none]
3729#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3730#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3731#[serde(rename_all = "camelCase")]
3732#[non_exhaustive]
3733pub struct SessionConfigBoolean {
3734    /// The current value of the boolean option.
3735    pub current_value: bool,
3736}
3737
3738impl SessionConfigBoolean {
3739    /// Builds [`SessionConfigBoolean`] with the required fields set. Optional fields start unset or empty.
3740    #[must_use]
3741    pub fn new(current_value: bool) -> Self {
3742        Self { current_value }
3743    }
3744}
3745
3746/// Semantic category for a session configuration option.
3747///
3748/// This is intended to help Clients distinguish broadly common selectors (e.g. model selector vs
3749/// session mode selector vs thought/reasoning level) for UX purposes (keyboard shortcuts, icons,
3750/// placement). It MUST NOT be required for correctness. Clients MUST handle missing or unknown
3751/// categories gracefully.
3752///
3753/// Category names beginning with `_` are free for custom use, like other ACP extension methods.
3754/// Category names that do not begin with `_` are reserved for the ACP spec.
3755#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3756#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3757#[serde(rename_all = "snake_case")]
3758#[non_exhaustive]
3759pub enum SessionConfigOptionCategory {
3760    /// Session mode selector.
3761    Mode,
3762    /// Model selector.
3763    Model,
3764    /// Model-related configuration parameter.
3765    ModelConfig,
3766    /// Thought/reasoning level selector.
3767    ThoughtLevel,
3768    /// Unknown / uncategorized selector.
3769    #[serde(untagged)]
3770    Other(String),
3771}
3772
3773/// Type-specific session configuration option payload.
3774#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3775#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3776#[serde(tag = "type", rename_all = "snake_case")]
3777#[cfg_attr(feature = "schemars", schemars(extend("discriminator" = {"propertyName": "type"})))]
3778#[non_exhaustive]
3779pub enum SessionConfigKind {
3780    /// Single-value selector (dropdown).
3781    Select(SessionConfigSelect),
3782    /// Boolean on/off toggle.
3783    Boolean(SessionConfigBoolean),
3784}
3785
3786/// A session configuration option selector and its current state.
3787#[serde_as]
3788#[skip_serializing_none]
3789#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3790#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3791#[serde(rename_all = "camelCase")]
3792#[non_exhaustive]
3793pub struct SessionConfigOption {
3794    /// Unique identifier for the configuration option.
3795    pub id: SessionConfigId,
3796    /// Human-readable label for the option.
3797    pub name: String,
3798    /// Optional description for the Client to display to the user.
3799    #[serde_as(deserialize_as = "DefaultOnError")]
3800    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3801    #[serde(default)]
3802    pub description: Option<String>,
3803    /// Optional semantic category for this option (UX only).
3804    #[serde_as(deserialize_as = "DefaultOnError")]
3805    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3806    #[serde(default)]
3807    pub category: Option<SessionConfigOptionCategory>,
3808    /// Type-specific fields for this configuration option.
3809    #[serde(flatten)]
3810    pub kind: SessionConfigKind,
3811    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3812    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3813    /// these keys.
3814    ///
3815    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3816    #[serde_as(deserialize_as = "DefaultOnError")]
3817    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3818    #[serde(default)]
3819    #[serde(rename = "_meta")]
3820    pub meta: Option<Meta>,
3821}
3822
3823impl SessionConfigOption {
3824    /// Builds [`SessionConfigOption`] with the required fields set. Optional fields start unset or empty.
3825    #[must_use]
3826    pub fn new(
3827        id: impl Into<SessionConfigId>,
3828        name: impl Into<String>,
3829        kind: SessionConfigKind,
3830    ) -> Self {
3831        Self {
3832            id: id.into(),
3833            name: name.into(),
3834            description: None,
3835            category: None,
3836            kind,
3837            meta: None,
3838        }
3839    }
3840
3841    /// Builds a select-style session configuration option with its current value and choices.
3842    #[must_use]
3843    pub fn select(
3844        id: impl Into<SessionConfigId>,
3845        name: impl Into<String>,
3846        current_value: impl Into<SessionConfigValueId>,
3847        options: impl Into<SessionConfigSelectOptions>,
3848    ) -> Self {
3849        Self::new(
3850            id,
3851            name,
3852            SessionConfigKind::Select(SessionConfigSelect::new(current_value, options)),
3853        )
3854    }
3855
3856    /// Builds a boolean-style session configuration option with its current value.
3857    #[must_use]
3858    pub fn boolean(
3859        id: impl Into<SessionConfigId>,
3860        name: impl Into<String>,
3861        current_value: bool,
3862    ) -> Self {
3863        Self::new(
3864            id,
3865            name,
3866            SessionConfigKind::Boolean(SessionConfigBoolean::new(current_value)),
3867        )
3868    }
3869
3870    /// Sets or clears the optional `description` field.
3871    #[must_use]
3872    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
3873        self.description = description.into_option();
3874        self
3875    }
3876
3877    /// Sets or clears the optional `category` field.
3878    #[must_use]
3879    pub fn category(mut self, category: impl IntoOption<SessionConfigOptionCategory>) -> Self {
3880        self.category = category.into_option();
3881        self
3882    }
3883
3884    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3885    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3886    /// these keys.
3887    ///
3888    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3889    #[must_use]
3890    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3891        self.meta = meta.into_option();
3892        self
3893    }
3894}
3895
3896/// The value to set for a session configuration option.
3897///
3898/// The `type` field acts as the discriminator in the serialized JSON form.
3899/// When no `type` is present, the value is treated as a [`SessionConfigValueId`]
3900/// via the [`ValueId`](Self::ValueId) fallback variant.
3901///
3902/// The `type` discriminator describes the *shape* of the value, not the option
3903/// kind. For example every option kind that picks from a list of ids
3904/// (`select`, `radio`, …) would use [`ValueId`](Self::ValueId), while a
3905/// future freeform text option would get its own variant.
3906#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3907#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3908#[serde(tag = "type", rename_all = "snake_case")]
3909#[non_exhaustive]
3910pub enum SessionConfigOptionValue {
3911    /// A boolean value (`type: "boolean"`).
3912    Boolean {
3913        /// The boolean value.
3914        value: bool,
3915    },
3916    /// A `SessionConfigValueId` string value.
3917    ///
3918    /// This is the default when `type` is absent on the wire. Unknown `type`
3919    /// values with string payloads also gracefully deserialize into this
3920    /// variant.
3921    #[serde(untagged)]
3922    ValueId {
3923        /// The value ID.
3924        value: SessionConfigValueId,
3925    },
3926}
3927
3928impl SessionConfigOptionValue {
3929    /// Create a value-id option value (used by `select` and other id-based option types).
3930    #[must_use]
3931    pub fn value_id(id: impl Into<SessionConfigValueId>) -> Self {
3932        Self::ValueId { value: id.into() }
3933    }
3934
3935    /// Create a boolean option value.
3936    #[must_use]
3937    pub fn boolean(val: bool) -> Self {
3938        Self::Boolean { value: val }
3939    }
3940
3941    /// Return the inner [`SessionConfigValueId`] if this is a
3942    /// [`ValueId`](Self::ValueId) value.
3943    #[must_use]
3944    pub fn as_value_id(&self) -> Option<&SessionConfigValueId> {
3945        match self {
3946            Self::ValueId { value } => Some(value),
3947            _ => None,
3948        }
3949    }
3950
3951    /// Return the inner [`bool`] if this is a [`Boolean`](Self::Boolean) value.
3952    #[must_use]
3953    pub fn as_bool(&self) -> Option<bool> {
3954        match self {
3955            Self::Boolean { value } => Some(*value),
3956            _ => None,
3957        }
3958    }
3959}
3960
3961impl From<SessionConfigValueId> for SessionConfigOptionValue {
3962    fn from(value: SessionConfigValueId) -> Self {
3963        Self::ValueId { value }
3964    }
3965}
3966
3967impl From<bool> for SessionConfigOptionValue {
3968    fn from(value: bool) -> Self {
3969        Self::Boolean { value }
3970    }
3971}
3972
3973impl From<&str> for SessionConfigOptionValue {
3974    fn from(value: &str) -> Self {
3975        Self::ValueId {
3976            value: SessionConfigValueId::new(value),
3977        }
3978    }
3979}
3980
3981/// Request parameters for setting a session configuration option.
3982#[serde_as]
3983#[skip_serializing_none]
3984#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3985#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3986#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_CONFIG_OPTION_METHOD_NAME)))]
3987#[serde(rename_all = "camelCase")]
3988#[non_exhaustive]
3989pub struct SetSessionConfigOptionRequest {
3990    /// The ID of the session to set the configuration option for.
3991    pub session_id: SessionId,
3992    /// The ID of the configuration option to set.
3993    pub config_id: SessionConfigId,
3994    /// The value to set, including a `type` discriminator and the raw `value`.
3995    ///
3996    /// When `type` is absent on the wire, defaults to treating the value as a
3997    /// [`SessionConfigValueId`] for `select` options.
3998    #[serde(flatten)]
3999    pub value: SessionConfigOptionValue,
4000    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4001    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4002    /// these keys.
4003    ///
4004    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4005    #[serde_as(deserialize_as = "DefaultOnError")]
4006    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4007    #[serde(default)]
4008    #[serde(rename = "_meta")]
4009    pub meta: Option<Meta>,
4010}
4011
4012impl SetSessionConfigOptionRequest {
4013    /// Builds [`SetSessionConfigOptionRequest`] with the required request fields set. Optional fields start unset or empty.
4014    #[must_use]
4015    pub fn new(
4016        session_id: impl Into<SessionId>,
4017        config_id: impl Into<SessionConfigId>,
4018        value: impl Into<SessionConfigOptionValue>,
4019    ) -> Self {
4020        Self {
4021            session_id: session_id.into(),
4022            config_id: config_id.into(),
4023            value: value.into(),
4024            meta: None,
4025        }
4026    }
4027
4028    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4029    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4030    /// these keys.
4031    ///
4032    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4033    #[must_use]
4034    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4035        self.meta = meta.into_option();
4036        self
4037    }
4038}
4039
4040/// Response to `session/set_config_option` method.
4041#[serde_as]
4042#[skip_serializing_none]
4043#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4044#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4045#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_CONFIG_OPTION_METHOD_NAME)))]
4046#[serde(rename_all = "camelCase")]
4047#[non_exhaustive]
4048pub struct SetSessionConfigOptionResponse {
4049    /// The full set of configuration options and their current values.
4050    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
4051    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
4052    pub config_options: Vec<SessionConfigOption>,
4053    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4054    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4055    /// these keys.
4056    ///
4057    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4058    #[serde_as(deserialize_as = "DefaultOnError")]
4059    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4060    #[serde(default)]
4061    #[serde(rename = "_meta")]
4062    pub meta: Option<Meta>,
4063}
4064
4065impl SetSessionConfigOptionResponse {
4066    /// Builds [`SetSessionConfigOptionResponse`] with the required response fields set. Optional fields start unset or empty.
4067    #[must_use]
4068    pub fn new(config_options: Vec<SessionConfigOption>) -> Self {
4069        Self {
4070            config_options,
4071            meta: None,
4072        }
4073    }
4074
4075    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4076    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4077    /// these keys.
4078    ///
4079    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4080    #[must_use]
4081    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4082        self.meta = meta.into_option();
4083        self
4084    }
4085}
4086
4087// MCP
4088
4089/// Configuration for connecting to an MCP (Model Context Protocol) server.
4090///
4091/// MCP servers provide tools and context that the agent can use when
4092/// processing prompts.
4093///
4094/// See protocol docs: [MCP Servers](https://agentclientprotocol.com/protocol/v1/session-setup#mcp-servers)
4095#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4096#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4097#[serde(tag = "type", rename_all = "snake_case")]
4098#[non_exhaustive]
4099pub enum McpServer {
4100    /// HTTP transport configuration
4101    ///
4102    /// Only available when the Agent capabilities indicate `mcp_capabilities.http` is `true`.
4103    Http(McpServerHttp),
4104    /// SSE transport configuration
4105    ///
4106    /// Only available when the Agent capabilities indicate `mcp_capabilities.sse` is `true`.
4107    Sse(McpServerSse),
4108    /// **UNSTABLE**
4109    ///
4110    /// This capability is not part of the spec yet, and may be removed or changed at any point.
4111    ///
4112    /// ACP transport configuration
4113    ///
4114    /// Only available when the Agent capabilities indicate `mcp_capabilities.acp` is `true`.
4115    /// The MCP server is provided by an ACP component and communicates over the ACP channel.
4116    #[cfg(feature = "unstable_mcp_over_acp")]
4117    Acp(McpServerAcp),
4118    /// Stdio transport configuration
4119    ///
4120    /// All Agents MUST support this transport.
4121    #[serde(untagged)]
4122    Stdio(McpServerStdio),
4123}
4124
4125/// HTTP transport configuration for MCP.
4126#[serde_as]
4127#[skip_serializing_none]
4128#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4129#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4130#[serde(rename_all = "camelCase")]
4131#[non_exhaustive]
4132pub struct McpServerHttp {
4133    /// Human-readable name identifying this MCP server.
4134    pub name: String,
4135    /// URL to the MCP server.
4136    pub url: String,
4137    /// HTTP headers to set when making requests to the MCP server.
4138    #[serde_as(deserialize_as = "DefaultOnNull")]
4139    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4140    pub headers: Vec<HttpHeader>,
4141    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4142    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4143    /// these keys.
4144    ///
4145    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4146    #[serde_as(deserialize_as = "DefaultOnError")]
4147    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4148    #[serde(default)]
4149    #[serde(rename = "_meta")]
4150    pub meta: Option<Meta>,
4151}
4152
4153impl McpServerHttp {
4154    /// Builds [`McpServerHttp`] with the required fields set. Optional fields start unset or empty.
4155    #[must_use]
4156    pub fn new(name: impl Into<String>, url: impl Into<String>) -> Self {
4157        Self {
4158            name: name.into(),
4159            url: url.into(),
4160            headers: Vec::new(),
4161            meta: None,
4162        }
4163    }
4164
4165    /// HTTP headers to set when making requests to the MCP server.
4166    #[must_use]
4167    pub fn headers(mut self, headers: Vec<HttpHeader>) -> Self {
4168        self.headers = headers;
4169        self
4170    }
4171
4172    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4173    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4174    /// these keys.
4175    ///
4176    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4177    #[must_use]
4178    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4179        self.meta = meta.into_option();
4180        self
4181    }
4182}
4183
4184/// SSE transport configuration for MCP.
4185#[serde_as]
4186#[skip_serializing_none]
4187#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4188#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4189#[serde(rename_all = "camelCase")]
4190#[non_exhaustive]
4191pub struct McpServerSse {
4192    /// Human-readable name identifying this MCP server.
4193    pub name: String,
4194    /// URL to the MCP server.
4195    pub url: String,
4196    /// HTTP headers to set when making requests to the MCP server.
4197    #[serde_as(deserialize_as = "DefaultOnNull")]
4198    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4199    pub headers: Vec<HttpHeader>,
4200    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4201    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4202    /// these keys.
4203    ///
4204    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4205    #[serde_as(deserialize_as = "DefaultOnError")]
4206    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4207    #[serde(default)]
4208    #[serde(rename = "_meta")]
4209    pub meta: Option<Meta>,
4210}
4211
4212impl McpServerSse {
4213    /// Builds [`McpServerSse`] with the required fields set. Optional fields start unset or empty.
4214    #[must_use]
4215    pub fn new(name: impl Into<String>, url: impl Into<String>) -> Self {
4216        Self {
4217            name: name.into(),
4218            url: url.into(),
4219            headers: Vec::new(),
4220            meta: None,
4221        }
4222    }
4223
4224    /// HTTP headers to set when making requests to the MCP server.
4225    #[must_use]
4226    pub fn headers(mut self, headers: Vec<HttpHeader>) -> Self {
4227        self.headers = headers;
4228        self
4229    }
4230
4231    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4232    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4233    /// these keys.
4234    ///
4235    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4236    #[must_use]
4237    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4238        self.meta = meta.into_option();
4239        self
4240    }
4241}
4242
4243/// **UNSTABLE**
4244///
4245/// This capability is not part of the spec yet, and may be removed or changed at any point.
4246///
4247/// Unique identifier for an MCP server using the ACP transport.
4248///
4249/// The value is opaque and generated by the ACP component providing the MCP server. It is
4250/// used by `mcp/message` to route requests to the component that declared the server.
4251#[cfg(feature = "unstable_mcp_over_acp")]
4252#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4253#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
4254#[serde(transparent)]
4255#[from(Arc<str>, String, &'static str)]
4256#[non_exhaustive]
4257pub struct McpServerAcpId(pub Arc<str>);
4258
4259#[cfg(feature = "unstable_mcp_over_acp")]
4260impl McpServerAcpId {
4261    /// Wraps a protocol string as a typed [`McpServerAcpId`].
4262    #[must_use]
4263    pub fn new(id: impl Into<Arc<str>>) -> Self {
4264        Self(id.into())
4265    }
4266}
4267
4268/// **UNSTABLE**
4269///
4270/// This capability is not part of the spec yet, and may be removed or changed at any point.
4271///
4272/// ACP transport configuration for MCP.
4273///
4274/// The MCP server is provided by an ACP component and communicates over the ACP channel
4275/// using `mcp/message`.
4276#[serde_as]
4277#[skip_serializing_none]
4278#[cfg(feature = "unstable_mcp_over_acp")]
4279#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4280#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4281#[serde(rename_all = "camelCase")]
4282#[non_exhaustive]
4283pub struct McpServerAcp {
4284    /// Human-readable name identifying this MCP server.
4285    pub name: String,
4286    /// Unique identifier for this MCP server, generated by the component providing it.
4287    ///
4288    /// Providers MUST NOT reuse an ID for multiple ACP-transport MCP servers that are visible
4289    /// on the same ACP connection.
4290    pub server_id: McpServerAcpId,
4291    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4292    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4293    /// these keys.
4294    ///
4295    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4296    #[serde_as(deserialize_as = "DefaultOnError")]
4297    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4298    #[serde(default)]
4299    #[serde(rename = "_meta")]
4300    pub meta: Option<Meta>,
4301}
4302
4303#[cfg(feature = "unstable_mcp_over_acp")]
4304impl McpServerAcp {
4305    /// Builds [`McpServerAcp`] with the required fields set. Optional fields start unset or empty.
4306    #[must_use]
4307    pub fn new(name: impl Into<String>, id: impl Into<McpServerAcpId>) -> Self {
4308        Self {
4309            name: name.into(),
4310            server_id: id.into(),
4311            meta: None,
4312        }
4313    }
4314
4315    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4316    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4317    /// these keys.
4318    ///
4319    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4320    #[must_use]
4321    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4322        self.meta = meta.into_option();
4323        self
4324    }
4325}
4326
4327/// Stdio transport configuration for MCP.
4328#[serde_as]
4329#[skip_serializing_none]
4330#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4331#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4332#[serde(rename_all = "camelCase")]
4333#[non_exhaustive]
4334pub struct McpServerStdio {
4335    /// Human-readable name identifying this MCP server.
4336    pub name: String,
4337    /// Absolute path to the MCP server executable.
4338    pub command: PathBuf,
4339    /// Command-line arguments to pass to the MCP server.
4340    #[serde_as(deserialize_as = "DefaultOnNull")]
4341    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4342    pub args: Vec<String>,
4343    /// Environment variables to set when launching the MCP server.
4344    #[serde_as(deserialize_as = "DefaultOnNull")]
4345    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4346    pub env: Vec<EnvVariable>,
4347    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4348    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4349    /// these keys.
4350    ///
4351    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4352    #[serde_as(deserialize_as = "DefaultOnError")]
4353    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4354    #[serde(default)]
4355    #[serde(rename = "_meta")]
4356    pub meta: Option<Meta>,
4357}
4358
4359impl McpServerStdio {
4360    /// Builds [`McpServerStdio`] with the required fields set. Optional fields start unset or empty.
4361    #[must_use]
4362    pub fn new(name: impl Into<String>, command: impl Into<PathBuf>) -> Self {
4363        Self {
4364            name: name.into(),
4365            command: command.into(),
4366            args: Vec::new(),
4367            env: Vec::new(),
4368            meta: None,
4369        }
4370    }
4371
4372    /// Command-line arguments to pass to the MCP server.
4373    #[must_use]
4374    pub fn args(mut self, args: Vec<String>) -> Self {
4375        self.args = args;
4376        self
4377    }
4378
4379    /// Environment variables to set when launching the MCP server.
4380    #[must_use]
4381    pub fn env(mut self, env: Vec<EnvVariable>) -> Self {
4382        self.env = env;
4383        self
4384    }
4385
4386    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4387    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4388    /// these keys.
4389    ///
4390    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4391    #[must_use]
4392    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4393        self.meta = meta.into_option();
4394        self
4395    }
4396}
4397
4398/// An environment variable to set when launching an MCP server.
4399#[serde_as]
4400#[skip_serializing_none]
4401#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4402#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4403#[serde(rename_all = "camelCase")]
4404#[non_exhaustive]
4405pub struct EnvVariable {
4406    /// The name of the environment variable.
4407    pub name: String,
4408    /// The value to set for the environment variable.
4409    pub value: String,
4410    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4411    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4412    /// these keys.
4413    ///
4414    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4415    #[serde_as(deserialize_as = "DefaultOnError")]
4416    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4417    #[serde(default)]
4418    #[serde(rename = "_meta")]
4419    pub meta: Option<Meta>,
4420}
4421
4422impl EnvVariable {
4423    /// Builds [`EnvVariable`] with the required fields set. Optional fields start unset or empty.
4424    #[must_use]
4425    pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
4426        Self {
4427            name: name.into(),
4428            value: value.into(),
4429            meta: None,
4430        }
4431    }
4432
4433    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4434    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4435    /// these keys.
4436    ///
4437    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4438    #[must_use]
4439    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4440        self.meta = meta.into_option();
4441        self
4442    }
4443}
4444
4445/// An HTTP header to set when making requests to the MCP server.
4446#[serde_as]
4447#[skip_serializing_none]
4448#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4449#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4450#[serde(rename_all = "camelCase")]
4451#[non_exhaustive]
4452pub struct HttpHeader {
4453    /// The name of the HTTP header.
4454    pub name: String,
4455    /// The value to set for the HTTP header.
4456    pub value: String,
4457    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4458    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4459    /// these keys.
4460    ///
4461    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4462    #[serde_as(deserialize_as = "DefaultOnError")]
4463    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4464    #[serde(default)]
4465    #[serde(rename = "_meta")]
4466    pub meta: Option<Meta>,
4467}
4468
4469impl HttpHeader {
4470    /// Builds [`HttpHeader`] with the required fields set. Optional fields start unset or empty.
4471    #[must_use]
4472    pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
4473        Self {
4474            name: name.into(),
4475            value: value.into(),
4476            meta: None,
4477        }
4478    }
4479
4480    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4481    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4482    /// these keys.
4483    ///
4484    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4485    #[must_use]
4486    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4487        self.meta = meta.into_option();
4488        self
4489    }
4490}
4491
4492// System prompt
4493
4494/// Client-provided system-level instructions for a session.
4495///
4496/// Clients MUST only send this when the Agent advertises
4497/// `sessionCapabilities.systemPrompt`. Agents that cannot apply it, for example
4498/// because of an unadvertised mode or an unsupported content block type, MUST
4499/// return an error instead of creating, loading, or resuming the session.
4500#[serde_as]
4501#[skip_serializing_none]
4502#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4503#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4504#[serde(rename_all = "camelCase")]
4505#[non_exhaustive]
4506pub struct SystemPrompt {
4507    /// How the Agent combines `content` with its own instructions.
4508    ///
4509    /// Required. Agents MUST return an error for a mode they do not support rather than
4510    /// treating it as `append` or `override`.
4511    pub mode: SystemPromptMode,
4512    /// The system prompt content.
4513    ///
4514    /// Agents advertising the capability MUST accept `text` content blocks.
4515    /// Clients MUST NOT send other content block types until a future
4516    /// capability allows them, and Agents MUST return an error for content
4517    /// blocks they do not support.
4518    ///
4519    /// Clients MUST NOT send an empty array. Agents MAY reject one with
4520    /// `-32602` without creating, loading, or resuming the session.
4521    pub content: Vec<ContentBlock>,
4522    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4523    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4524    /// these keys.
4525    ///
4526    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4527    #[serde_as(deserialize_as = "DefaultOnError")]
4528    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4529    #[serde(default)]
4530    #[serde(rename = "_meta")]
4531    pub meta: Option<Meta>,
4532}
4533
4534impl SystemPrompt {
4535    /// Builds [`SystemPrompt`] with the required fields set. Optional fields start unset or empty.
4536    ///
4537    /// `mode` starts as [`SystemPromptMode::Append`]. Use [`SystemPrompt::mode`]
4538    /// to request another mode.
4539    #[must_use]
4540    pub fn new(content: Vec<ContentBlock>) -> Self {
4541        Self {
4542            mode: SystemPromptMode::default(),
4543            content,
4544            meta: None,
4545        }
4546    }
4547
4548    /// How the Agent combines `content` with its own instructions.
4549    #[must_use]
4550    pub fn mode(mut self, mode: SystemPromptMode) -> Self {
4551        self.mode = mode;
4552        self
4553    }
4554
4555    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4556    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4557    /// these keys.
4558    ///
4559    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4560    #[must_use]
4561    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4562        self.meta = meta.into_option();
4563        self
4564    }
4565}
4566
4567/// How the Agent combines a client-provided system prompt with its own instructions.
4568///
4569/// Unknown modes are preserved so they can be stored,
4570/// proxied, or forwarded. An Agent MUST return an error for a mode it does not
4571/// support rather than treating it as `append` or `override`.
4572#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4573#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
4574#[serde(rename_all = "snake_case")]
4575#[non_exhaustive]
4576pub enum SystemPromptMode {
4577    /// Add the content to the Agent's own instructions rather than replacing them.
4578    ///
4579    /// Every Agent that advertises `sessionCapabilities.systemPrompt` supports this mode.
4580    /// Agents SHOULD give the content system-level precedence, for example in the
4581    /// model's system prompt or developer instructions rather than in user-turn
4582    /// content. Where it is placed and how it is formatted is implementation-defined.
4583    #[default]
4584    Append,
4585    /// Replace the Agent's built-in default instructions with the content.
4586    ///
4587    /// This does not change tool availability, MCP servers, permissions, or session
4588    /// configuration. Context the Agent supplies from the workspace or environment
4589    /// MAY still be included. Clients that use this mode take responsibility for any
4590    /// tool guidance or safety instructions the Agent's default instructions
4591    /// provided, and MUST only use it when the Agent advertises
4592    /// `sessionCapabilities.systemPrompt.mode.override`.
4593    Override,
4594    /// Custom or future system prompt mode.
4595    ///
4596    /// Values beginning with `_` are reserved for implementation-specific
4597    /// extensions. Unknown values that do not begin with `_` are reserved for
4598    /// future ACP variants.
4599    #[serde(untagged)]
4600    Other(String),
4601}
4602
4603// Prompt
4604
4605/// Request parameters for sending a user prompt to the agent.
4606///
4607/// Contains the user's message and any additional context.
4608///
4609/// See protocol docs: [User Message](https://agentclientprotocol.com/protocol/v1/prompt-turn#1-user-message)
4610#[serde_as]
4611#[skip_serializing_none]
4612#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4613#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4614#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_PROMPT_METHOD_NAME)))]
4615#[serde(rename_all = "camelCase")]
4616#[non_exhaustive]
4617pub struct PromptRequest {
4618    /// The ID of the session to send this user message to
4619    pub session_id: SessionId,
4620    /// The blocks of content that compose the user's message.
4621    ///
4622    /// As a baseline, the Agent MUST support `text` and `resource_link` content blocks,
4623    /// while other variants are optionally enabled via `PromptCapabilities`.
4624    ///
4625    /// The Client MUST adapt its interface according to `PromptCapabilities`.
4626    ///
4627    /// The client MAY include referenced pieces of context as either
4628    /// `resource` or `resource_link` content blocks.
4629    ///
4630    /// When available, `resource` is preferred
4631    /// as it avoids extra round-trips and allows the message to include
4632    /// pieces of context from sources the agent may not have access to.
4633    pub prompt: Vec<ContentBlock>,
4634    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4635    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4636    /// these keys.
4637    ///
4638    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4639    #[serde_as(deserialize_as = "DefaultOnError")]
4640    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4641    #[serde(default)]
4642    #[serde(rename = "_meta")]
4643    pub meta: Option<Meta>,
4644}
4645
4646impl PromptRequest {
4647    /// Builds [`PromptRequest`] with the required request fields set. Optional fields start unset or empty.
4648    #[must_use]
4649    pub fn new(session_id: impl Into<SessionId>, prompt: Vec<ContentBlock>) -> Self {
4650        Self {
4651            session_id: session_id.into(),
4652            prompt,
4653            meta: None,
4654        }
4655    }
4656
4657    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4658    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4659    /// these keys.
4660    ///
4661    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4662    #[must_use]
4663    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4664        self.meta = meta.into_option();
4665        self
4666    }
4667}
4668
4669/// Response from processing a user prompt.
4670///
4671/// See protocol docs: [Check for Completion](https://agentclientprotocol.com/protocol/v1/prompt-turn#4-check-for-completion)
4672#[serde_as]
4673#[skip_serializing_none]
4674#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4675#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4676#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_PROMPT_METHOD_NAME)))]
4677#[serde(rename_all = "camelCase")]
4678#[non_exhaustive]
4679pub struct PromptResponse {
4680    /// Indicates why the agent stopped processing the turn.
4681    pub stop_reason: StopReason,
4682    /// **UNSTABLE**
4683    ///
4684    /// This capability is not part of the spec yet, and may be removed or changed at any point.
4685    ///
4686    /// Token usage for this turn (optional).
4687    #[cfg(feature = "unstable_end_turn_token_usage")]
4688    #[serde_as(deserialize_as = "DefaultOnError")]
4689    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4690    #[serde(default)]
4691    pub usage: Option<Usage>,
4692    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4693    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4694    /// these keys.
4695    ///
4696    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4697    #[serde_as(deserialize_as = "DefaultOnError")]
4698    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4699    #[serde(default)]
4700    #[serde(rename = "_meta")]
4701    pub meta: Option<Meta>,
4702}
4703
4704impl PromptResponse {
4705    /// Builds [`PromptResponse`] with the required response fields set. Optional fields start unset or empty.
4706    #[must_use]
4707    pub fn new(stop_reason: StopReason) -> Self {
4708        Self {
4709            stop_reason,
4710            #[cfg(feature = "unstable_end_turn_token_usage")]
4711            usage: None,
4712            meta: None,
4713        }
4714    }
4715
4716    /// **UNSTABLE**
4717    ///
4718    /// This capability is not part of the spec yet, and may be removed or changed at any point.
4719    ///
4720    /// Token usage for this turn.
4721    #[cfg(feature = "unstable_end_turn_token_usage")]
4722    #[must_use]
4723    pub fn usage(mut self, usage: impl IntoOption<Usage>) -> Self {
4724        self.usage = usage.into_option();
4725        self
4726    }
4727
4728    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4729    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4730    /// these keys.
4731    ///
4732    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4733    #[must_use]
4734    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4735        self.meta = meta.into_option();
4736        self
4737    }
4738}
4739
4740/// Reasons why an agent stops processing a prompt turn.
4741///
4742/// See protocol docs: [Stop Reasons](https://agentclientprotocol.com/protocol/v1/prompt-turn#stop-reasons)
4743#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4744#[derive(Debug, Copy, Clone, Eq, PartialEq, Serialize, Deserialize)]
4745#[serde(rename_all = "snake_case")]
4746#[non_exhaustive]
4747pub enum StopReason {
4748    /// The turn ended successfully.
4749    EndTurn,
4750    /// The turn ended because the agent reached the maximum number of tokens.
4751    MaxTokens,
4752    /// The turn ended because the agent reached the maximum number of allowed
4753    /// agent requests between user turns.
4754    MaxTurnRequests,
4755    /// The turn ended because the agent refused to continue. The user prompt
4756    /// and everything that comes after it won't be included in the next
4757    /// prompt, so this should be reflected in the UI.
4758    Refusal,
4759    /// The turn was cancelled by the client via `session/cancel`.
4760    ///
4761    /// This stop reason MUST be returned when the client sends a `session/cancel`
4762    /// notification, even if the cancellation causes exceptions in underlying operations.
4763    /// Agents should catch these exceptions and return this semantically meaningful
4764    /// response to confirm successful cancellation.
4765    Cancelled,
4766}
4767
4768/// **UNSTABLE**
4769///
4770/// This capability is not part of the spec yet, and may be removed or changed at any point.
4771///
4772/// Token usage information for a prompt turn.
4773#[cfg(feature = "unstable_end_turn_token_usage")]
4774#[serde_as]
4775#[skip_serializing_none]
4776#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4777#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4778#[serde(rename_all = "camelCase")]
4779#[non_exhaustive]
4780pub struct Usage {
4781    /// Sum of all token types across session.
4782    pub total_tokens: u64,
4783    /// Total input tokens across all turns.
4784    pub input_tokens: u64,
4785    /// Total output tokens across all turns.
4786    pub output_tokens: u64,
4787    /// Total thought/reasoning tokens
4788    #[serde_as(deserialize_as = "DefaultOnError")]
4789    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4790    #[serde(default)]
4791    pub thought_tokens: Option<u64>,
4792    /// Total cache read tokens.
4793    #[serde_as(deserialize_as = "DefaultOnError")]
4794    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4795    #[serde(default)]
4796    pub cached_read_tokens: Option<u64>,
4797    /// Total cache write tokens.
4798    #[serde_as(deserialize_as = "DefaultOnError")]
4799    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4800    #[serde(default)]
4801    pub cached_write_tokens: Option<u64>,
4802    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4803    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4804    /// these keys.
4805    ///
4806    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4807    #[serde_as(deserialize_as = "DefaultOnError")]
4808    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4809    #[serde(default)]
4810    #[serde(rename = "_meta")]
4811    pub meta: Option<Meta>,
4812}
4813
4814#[cfg(feature = "unstable_end_turn_token_usage")]
4815impl Usage {
4816    /// Builds [`Usage`] with the required fields set. Optional fields start unset or empty.
4817    #[must_use]
4818    pub fn new(total_tokens: u64, input_tokens: u64, output_tokens: u64) -> Self {
4819        Self {
4820            total_tokens,
4821            input_tokens,
4822            output_tokens,
4823            thought_tokens: None,
4824            cached_read_tokens: None,
4825            cached_write_tokens: None,
4826            meta: None,
4827        }
4828    }
4829
4830    /// Total thought/reasoning tokens
4831    #[must_use]
4832    pub fn thought_tokens(mut self, thought_tokens: impl IntoOption<u64>) -> Self {
4833        self.thought_tokens = thought_tokens.into_option();
4834        self
4835    }
4836
4837    /// Total cache read tokens.
4838    #[must_use]
4839    pub fn cached_read_tokens(mut self, cached_read_tokens: impl IntoOption<u64>) -> Self {
4840        self.cached_read_tokens = cached_read_tokens.into_option();
4841        self
4842    }
4843
4844    /// Total cache write tokens.
4845    #[must_use]
4846    pub fn cached_write_tokens(mut self, cached_write_tokens: impl IntoOption<u64>) -> Self {
4847        self.cached_write_tokens = cached_write_tokens.into_option();
4848        self
4849    }
4850
4851    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4852    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4853    /// these keys.
4854    ///
4855    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4856    #[must_use]
4857    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4858        self.meta = meta.into_option();
4859        self
4860    }
4861}
4862
4863// Providers
4864
4865/// **UNSTABLE**
4866///
4867/// This capability is not part of the spec yet, and may be removed or changed at any point.
4868///
4869/// Well-known API protocol identifiers for LLM providers.
4870///
4871/// Agents and clients MUST handle unknown protocol identifiers gracefully.
4872///
4873/// Protocol names beginning with `_` are free for custom use, like other ACP extension methods.
4874/// Protocol names that do not begin with `_` are reserved for the ACP spec.
4875#[cfg(feature = "unstable_llm_providers")]
4876#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4877#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4878#[serde(rename_all = "snake_case")]
4879#[non_exhaustive]
4880#[expect(clippy::doc_markdown)]
4881pub enum LlmProtocol {
4882    /// Anthropic API protocol.
4883    Anthropic,
4884    /// OpenAI API protocol.
4885    #[serde(rename = "openai")]
4886    OpenAi,
4887    /// Azure OpenAI API protocol.
4888    Azure,
4889    /// Google Vertex AI API protocol.
4890    Vertex,
4891    /// AWS Bedrock API protocol.
4892    Bedrock,
4893    /// Unknown or custom protocol.
4894    #[serde(untagged)]
4895    Other(String),
4896}
4897
4898/// **UNSTABLE**
4899///
4900/// This capability is not part of the spec yet, and may be removed or changed at any point.
4901///
4902/// Current effective non-secret routing configuration for a provider.
4903#[cfg(feature = "unstable_llm_providers")]
4904#[serde_as]
4905#[skip_serializing_none]
4906#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4907#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4908#[serde(rename_all = "camelCase")]
4909#[non_exhaustive]
4910pub struct ProviderCurrentConfig {
4911    /// Protocol currently used by this provider.
4912    pub api_type: LlmProtocol,
4913    /// Base URL currently used by this provider.
4914    pub base_url: String,
4915    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4916    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4917    /// these keys.
4918    ///
4919    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4920    #[serde_as(deserialize_as = "DefaultOnError")]
4921    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4922    #[serde(default)]
4923    #[serde(rename = "_meta")]
4924    pub meta: Option<Meta>,
4925}
4926
4927#[cfg(feature = "unstable_llm_providers")]
4928impl ProviderCurrentConfig {
4929    /// Builds [`ProviderCurrentConfig`] with the required fields set. Optional fields start unset or empty.
4930    #[must_use]
4931    pub fn new(api_type: LlmProtocol, base_url: impl Into<String>) -> Self {
4932        Self {
4933            api_type,
4934            base_url: base_url.into(),
4935            meta: None,
4936        }
4937    }
4938
4939    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4940    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4941    /// these keys.
4942    ///
4943    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4944    #[must_use]
4945    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4946        self.meta = meta.into_option();
4947        self
4948    }
4949}
4950
4951/// **UNSTABLE**
4952///
4953/// This capability is not part of the spec yet, and may be removed or changed at any point.
4954///
4955/// Unique identifier for a configurable LLM provider.
4956#[cfg(feature = "unstable_llm_providers")]
4957#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4958#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
4959#[serde(transparent)]
4960#[from(Arc<str>, String, &'static str)]
4961#[non_exhaustive]
4962pub struct ProviderId(pub Arc<str>);
4963
4964#[cfg(feature = "unstable_llm_providers")]
4965impl ProviderId {
4966    /// Wraps a protocol string as a typed [`ProviderId`].
4967    #[must_use]
4968    pub fn new(id: impl Into<Arc<str>>) -> Self {
4969        Self(id.into())
4970    }
4971}
4972
4973/// **UNSTABLE**
4974///
4975/// This capability is not part of the spec yet, and may be removed or changed at any point.
4976///
4977/// Information about a configurable LLM provider.
4978#[cfg(feature = "unstable_llm_providers")]
4979#[serde_as]
4980#[skip_serializing_none]
4981#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4982#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4983#[serde(rename_all = "camelCase")]
4984#[non_exhaustive]
4985pub struct ProviderInfo {
4986    /// Provider identifier, for example "main" or "openai".
4987    pub provider_id: ProviderId,
4988    /// Supported protocol types for this provider.
4989    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
4990    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
4991    pub supported: Vec<LlmProtocol>,
4992    /// Whether this provider is mandatory and cannot be disabled via `providers/disable`.
4993    /// If true, clients must not call `providers/disable` for this provider ID.
4994    pub required: bool,
4995    /// Current effective non-secret routing config.
4996    /// Null or omitted means provider is disabled.
4997    #[serde(default)]
4998    pub current: Option<ProviderCurrentConfig>,
4999    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5000    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5001    /// these keys.
5002    ///
5003    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5004    #[serde_as(deserialize_as = "DefaultOnError")]
5005    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5006    #[serde(default)]
5007    #[serde(rename = "_meta")]
5008    pub meta: Option<Meta>,
5009}
5010
5011#[cfg(feature = "unstable_llm_providers")]
5012impl ProviderInfo {
5013    /// Builds [`ProviderInfo`] with the required fields set. Optional fields start unset or empty.
5014    #[must_use]
5015    pub fn new(
5016        provider_id: impl Into<ProviderId>,
5017        supported: Vec<LlmProtocol>,
5018        required: bool,
5019        current: impl IntoOption<ProviderCurrentConfig>,
5020    ) -> Self {
5021        Self {
5022            provider_id: provider_id.into(),
5023            supported,
5024            required,
5025            current: current.into_option(),
5026            meta: None,
5027        }
5028    }
5029
5030    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5031    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5032    /// these keys.
5033    ///
5034    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5035    #[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#[cfg(feature = "unstable_llm_providers")]
5043crate::serde_util::default_on_null! {
5044    /// **UNSTABLE**
5045    ///
5046    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5047    ///
5048    /// Request parameters for `providers/list`.
5049    #[serde_as]
5050    #[skip_serializing_none]
5051    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5052    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
5053    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_LIST_METHOD_NAME)))]
5054    #[serde(rename_all = "camelCase")]
5055    #[non_exhaustive]
5056    pub struct ListProvidersRequest {
5057        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5058        /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5059        /// these keys.
5060        ///
5061        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5062        #[serde_as(deserialize_as = "DefaultOnError")]
5063        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5064        #[serde(default)]
5065        #[serde(rename = "_meta")]
5066        pub meta: Option<Meta>,
5067    }
5068}
5069
5070#[cfg(feature = "unstable_llm_providers")]
5071impl ListProvidersRequest {
5072    /// Builds [`ListProvidersRequest`] with the required request fields set. Optional fields start unset or empty.
5073    #[must_use]
5074    pub fn new() -> Self {
5075        Self::default()
5076    }
5077
5078    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5079    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5080    /// these keys.
5081    ///
5082    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5083    #[must_use]
5084    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5085        self.meta = meta.into_option();
5086        self
5087    }
5088}
5089
5090/// **UNSTABLE**
5091///
5092/// This capability is not part of the spec yet, and may be removed or changed at any point.
5093///
5094/// Response to `providers/list`.
5095#[cfg(feature = "unstable_llm_providers")]
5096#[serde_as]
5097#[skip_serializing_none]
5098#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5099#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5100#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_LIST_METHOD_NAME)))]
5101#[serde(rename_all = "camelCase")]
5102#[non_exhaustive]
5103pub struct ListProvidersResponse {
5104    /// Configurable providers with current routing info suitable for UI display.
5105    pub providers: Vec<ProviderInfo>,
5106    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5107    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5108    /// these keys.
5109    ///
5110    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5111    #[serde_as(deserialize_as = "DefaultOnError")]
5112    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5113    #[serde(default)]
5114    #[serde(rename = "_meta")]
5115    pub meta: Option<Meta>,
5116}
5117
5118#[cfg(feature = "unstable_llm_providers")]
5119impl ListProvidersResponse {
5120    /// Builds [`ListProvidersResponse`] with the required response fields set. Optional fields start unset or empty.
5121    #[must_use]
5122    pub fn new(providers: Vec<ProviderInfo>) -> Self {
5123        Self {
5124            providers,
5125            meta: None,
5126        }
5127    }
5128
5129    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5130    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5131    /// these keys.
5132    ///
5133    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5134    #[must_use]
5135    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5136        self.meta = meta.into_option();
5137        self
5138    }
5139}
5140
5141/// **UNSTABLE**
5142///
5143/// This capability is not part of the spec yet, and may be removed or changed at any point.
5144///
5145/// Request parameters for `providers/set`.
5146///
5147/// Replaces the full configuration for one provider ID.
5148#[cfg(feature = "unstable_llm_providers")]
5149#[serde_as]
5150#[skip_serializing_none]
5151#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5152#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
5153#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_SET_METHOD_NAME)))]
5154#[serde(rename_all = "camelCase")]
5155#[non_exhaustive]
5156pub struct SetProviderRequest {
5157    /// Provider ID to configure.
5158    pub provider_id: ProviderId,
5159    /// Protocol type for this provider.
5160    pub api_type: LlmProtocol,
5161    /// Base URL for requests sent through this provider.
5162    pub base_url: String,
5163    /// Full headers map for this provider.
5164    /// May include authorization, routing, or other integration-specific headers.
5165    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
5166    pub headers: HashMap<String, String>,
5167    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5168    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5169    /// these keys.
5170    ///
5171    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5172    #[serde_as(deserialize_as = "DefaultOnError")]
5173    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5174    #[serde(default)]
5175    #[serde(rename = "_meta")]
5176    pub meta: Option<Meta>,
5177}
5178
5179#[cfg(feature = "unstable_llm_providers")]
5180impl SetProviderRequest {
5181    /// Builds [`SetProviderRequest`] with the required request fields set. Optional fields start unset or empty.
5182    #[must_use]
5183    pub fn new(
5184        provider_id: impl Into<ProviderId>,
5185        api_type: LlmProtocol,
5186        base_url: impl Into<String>,
5187    ) -> Self {
5188        Self {
5189            provider_id: provider_id.into(),
5190            api_type,
5191            base_url: base_url.into(),
5192            headers: HashMap::new(),
5193            meta: None,
5194        }
5195    }
5196
5197    /// Full headers map for this provider.
5198    /// May include authorization, routing, or other integration-specific headers.
5199    #[must_use]
5200    pub fn headers(mut self, headers: HashMap<String, String>) -> Self {
5201        self.headers = headers;
5202        self
5203    }
5204
5205    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5206    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5207    /// these keys.
5208    ///
5209    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5210    #[must_use]
5211    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5212        self.meta = meta.into_option();
5213        self
5214    }
5215}
5216
5217#[cfg(feature = "unstable_llm_providers")]
5218crate::serde_util::default_on_null! {
5219    /// **UNSTABLE**
5220    ///
5221    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5222    ///
5223    /// Response to `providers/set`.
5224    #[serde_as]
5225    #[skip_serializing_none]
5226    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5227    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
5228    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_SET_METHOD_NAME)))]
5229    #[serde(rename_all = "camelCase")]
5230    #[non_exhaustive]
5231    pub struct SetProviderResponse {
5232        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5233        /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5234        /// these keys.
5235        ///
5236        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5237        #[serde_as(deserialize_as = "DefaultOnError")]
5238        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5239        #[serde(default)]
5240        #[serde(rename = "_meta")]
5241        pub meta: Option<Meta>,
5242    }
5243}
5244
5245#[cfg(feature = "unstable_llm_providers")]
5246impl SetProviderResponse {
5247    /// Builds [`SetProviderResponse`] with the required response fields set. Optional fields start unset or empty.
5248    #[must_use]
5249    pub fn new() -> Self {
5250        Self::default()
5251    }
5252
5253    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5254    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5255    /// these keys.
5256    ///
5257    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5258    #[must_use]
5259    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5260        self.meta = meta.into_option();
5261        self
5262    }
5263}
5264
5265/// **UNSTABLE**
5266///
5267/// This capability is not part of the spec yet, and may be removed or changed at any point.
5268///
5269/// Request parameters for `providers/disable`.
5270#[cfg(feature = "unstable_llm_providers")]
5271#[serde_as]
5272#[skip_serializing_none]
5273#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5274#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5275#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_DISABLE_METHOD_NAME)))]
5276#[serde(rename_all = "camelCase")]
5277#[non_exhaustive]
5278pub struct DisableProviderRequest {
5279    /// Provider ID to disable.
5280    pub provider_id: ProviderId,
5281    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5282    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5283    /// these keys.
5284    ///
5285    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5286    #[serde_as(deserialize_as = "DefaultOnError")]
5287    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5288    #[serde(default)]
5289    #[serde(rename = "_meta")]
5290    pub meta: Option<Meta>,
5291}
5292
5293#[cfg(feature = "unstable_llm_providers")]
5294impl DisableProviderRequest {
5295    /// Builds [`DisableProviderRequest`] with the required request fields set. Optional fields start unset or empty.
5296    #[must_use]
5297    pub fn new(provider_id: impl Into<ProviderId>) -> Self {
5298        Self {
5299            provider_id: provider_id.into(),
5300            meta: None,
5301        }
5302    }
5303
5304    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5305    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5306    /// these keys.
5307    ///
5308    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5309    #[must_use]
5310    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5311        self.meta = meta.into_option();
5312        self
5313    }
5314}
5315
5316#[cfg(feature = "unstable_llm_providers")]
5317crate::serde_util::default_on_null! {
5318    /// **UNSTABLE**
5319    ///
5320    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5321    ///
5322    /// Response to `providers/disable`.
5323    #[serde_as]
5324    #[skip_serializing_none]
5325    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5326    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
5327    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_DISABLE_METHOD_NAME)))]
5328    #[serde(rename_all = "camelCase")]
5329    #[non_exhaustive]
5330    pub struct DisableProviderResponse {
5331        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5332        /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5333        /// these keys.
5334        ///
5335        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5336        #[serde_as(deserialize_as = "DefaultOnError")]
5337        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5338        #[serde(default)]
5339        #[serde(rename = "_meta")]
5340        pub meta: Option<Meta>,
5341    }
5342}
5343
5344#[cfg(feature = "unstable_llm_providers")]
5345impl DisableProviderResponse {
5346    /// Builds [`DisableProviderResponse`] with the required response fields set. Optional fields start unset or empty.
5347    #[must_use]
5348    pub fn new() -> Self {
5349        Self::default()
5350    }
5351
5352    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5353    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5354    /// these keys.
5355    ///
5356    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5357    #[must_use]
5358    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5359        self.meta = meta.into_option();
5360        self
5361    }
5362}
5363
5364// Capabilities
5365
5366/// Capabilities supported by the agent.
5367///
5368/// Advertised during initialization to inform the client about
5369/// available features and content types.
5370///
5371/// See protocol docs: [Agent Capabilities](https://agentclientprotocol.com/protocol/v1/initialization#agent-capabilities)
5372#[serde_as]
5373#[skip_serializing_none]
5374#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5375#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5376#[serde(rename_all = "camelCase")]
5377#[non_exhaustive]
5378pub struct AgentCapabilities {
5379    /// Whether the agent supports `session/load`.
5380    #[serde_as(deserialize_as = "DefaultOnError")]
5381    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5382    #[serde(default)]
5383    pub load_session: bool,
5384    /// Prompt capabilities supported by the agent.
5385    #[serde_as(deserialize_as = "DefaultOnError")]
5386    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5387    #[serde(default)]
5388    pub prompt_capabilities: PromptCapabilities,
5389    /// MCP capabilities supported by the agent.
5390    #[serde_as(deserialize_as = "DefaultOnError")]
5391    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5392    #[serde(default)]
5393    pub mcp_capabilities: McpCapabilities,
5394    /// Session lifecycle and prompt capabilities advertised by the agent.
5395    #[serde_as(deserialize_as = "DefaultOnError")]
5396    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5397    #[serde(default)]
5398    pub session_capabilities: SessionCapabilities,
5399    /// Authentication-related capabilities supported by the agent.
5400    #[serde_as(deserialize_as = "DefaultOnError")]
5401    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5402    #[serde(default)]
5403    pub auth: AgentAuthCapabilities,
5404    /// **UNSTABLE**
5405    ///
5406    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5407    ///
5408    /// Provider configuration capabilities supported by the agent.
5409    ///
5410    /// Optional. Omitted or `null` both mean the agent does not advertise support.
5411    /// Supplying `{}` means the agent supports provider configuration methods.
5412    #[cfg(feature = "unstable_llm_providers")]
5413    #[serde_as(deserialize_as = "DefaultOnError")]
5414    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5415    #[serde(default)]
5416    pub providers: Option<ProvidersCapabilities>,
5417    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5418    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5419    /// these keys.
5420    ///
5421    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5422    #[serde_as(deserialize_as = "DefaultOnError")]
5423    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5424    #[serde(default)]
5425    #[serde(rename = "_meta")]
5426    pub meta: Option<Meta>,
5427}
5428
5429impl AgentCapabilities {
5430    /// Builds an empty [`AgentCapabilities`]. Use builder methods to advertise supported sub-capabilities.
5431    #[must_use]
5432    pub fn new() -> Self {
5433        Self::default()
5434    }
5435
5436    /// Whether the agent supports `session/load`.
5437    #[must_use]
5438    pub fn load_session(mut self, load_session: bool) -> Self {
5439        self.load_session = load_session;
5440        self
5441    }
5442
5443    /// Prompt capabilities supported by the agent.
5444    #[must_use]
5445    pub fn prompt_capabilities(mut self, prompt_capabilities: PromptCapabilities) -> Self {
5446        self.prompt_capabilities = prompt_capabilities;
5447        self
5448    }
5449
5450    /// MCP capabilities supported by the agent.
5451    #[must_use]
5452    pub fn mcp_capabilities(mut self, mcp_capabilities: McpCapabilities) -> Self {
5453        self.mcp_capabilities = mcp_capabilities;
5454        self
5455    }
5456
5457    /// Session capabilities supported by the agent.
5458    #[must_use]
5459    pub fn session_capabilities(mut self, session_capabilities: SessionCapabilities) -> Self {
5460        self.session_capabilities = session_capabilities;
5461        self
5462    }
5463
5464    /// Authentication-related capabilities supported by the agent.
5465    #[must_use]
5466    pub fn auth(mut self, auth: AgentAuthCapabilities) -> Self {
5467        self.auth = auth;
5468        self
5469    }
5470
5471    /// **UNSTABLE**
5472    ///
5473    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5474    ///
5475    /// Provider configuration capabilities supported by the agent.
5476    #[cfg(feature = "unstable_llm_providers")]
5477    #[must_use]
5478    pub fn providers(mut self, providers: impl IntoOption<ProvidersCapabilities>) -> Self {
5479        self.providers = providers.into_option();
5480        self
5481    }
5482
5483    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5484    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5485    /// these keys.
5486    ///
5487    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5488    #[must_use]
5489    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5490        self.meta = meta.into_option();
5491        self
5492    }
5493}
5494
5495/// **UNSTABLE**
5496///
5497/// This capability is not part of the spec yet, and may be removed or changed at any point.
5498///
5499/// Provider configuration capabilities supported by the agent.
5500///
5501/// Supplying `{}` means the agent supports provider configuration methods.
5502#[cfg(feature = "unstable_llm_providers")]
5503#[serde_as]
5504#[skip_serializing_none]
5505#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5506#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5507#[non_exhaustive]
5508pub struct ProvidersCapabilities {
5509    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5510    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5511    /// these keys.
5512    ///
5513    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5514    #[serde_as(deserialize_as = "DefaultOnError")]
5515    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5516    #[serde(default)]
5517    #[serde(rename = "_meta")]
5518    pub meta: Option<Meta>,
5519}
5520
5521#[cfg(feature = "unstable_llm_providers")]
5522impl ProvidersCapabilities {
5523    /// Builds an empty [`ProvidersCapabilities`]. Use builder methods to advertise supported sub-capabilities.
5524    #[must_use]
5525    pub fn new() -> Self {
5526        Self::default()
5527    }
5528
5529    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5530    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5531    /// these keys.
5532    ///
5533    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5534    #[must_use]
5535    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5536        self.meta = meta.into_option();
5537        self
5538    }
5539}
5540
5541/// Session capabilities supported by the agent.
5542///
5543/// As a baseline, all Agents **MUST** support `session/new`, `session/prompt`, `session/cancel`, and `session/update`.
5544///
5545/// Optionally, they **MAY** support other session methods and notifications by specifying additional capabilities.
5546///
5547/// Note: `session/load` is still handled by the top-level `loadSession` capability. This will be unified in future versions of the protocol.
5548///
5549/// See protocol docs: [Session Capabilities](https://agentclientprotocol.com/protocol/v1/initialization#session-capabilities)
5550#[serde_as]
5551#[skip_serializing_none]
5552#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5553#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5554#[serde(rename_all = "camelCase")]
5555#[non_exhaustive]
5556pub struct SessionCapabilities {
5557    /// Whether the agent supports `session/list`.
5558    ///
5559    /// Optional. Omitted or `null` both mean the agent does not advertise support.
5560    /// Supplying `{}` means the agent supports listing sessions.
5561    #[serde_as(deserialize_as = "DefaultOnError")]
5562    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5563    #[serde(default)]
5564    pub list: Option<SessionListCapabilities>,
5565    /// Whether the agent supports `session/delete`.
5566    ///
5567    /// Optional. Omitted or `null` both mean the agent does not advertise support.
5568    /// Supplying `{}` means the agent supports deleting sessions from `session/list`.
5569    #[serde_as(deserialize_as = "DefaultOnError")]
5570    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5571    #[serde(default)]
5572    pub delete: Option<SessionDeleteCapabilities>,
5573    /// Whether the agent supports `additionalDirectories` on supported session lifecycle requests.
5574    ///
5575    /// Optional. Omitted or `null` both mean the agent does not advertise support.
5576    /// Supplying `{}` means the agent supports `additionalDirectories` on
5577    /// supported session lifecycle requests.
5578    ///
5579    /// Agents that also support `session/list` may return
5580    /// `SessionInfo.additionalDirectories` to report the complete ordered
5581    /// additional-root list associated with a listed session.
5582    #[serde_as(deserialize_as = "DefaultOnError")]
5583    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5584    #[serde(default)]
5585    pub additional_directories: Option<SessionAdditionalDirectoriesCapabilities>,
5586    /// Whether the agent supports `systemPrompt` on session lifecycle requests.
5587    ///
5588    /// Optional. Omitted or `null` both mean the agent does not advertise support.
5589    /// Supplying `{}` means the agent supports `systemPrompt` in `append` mode.
5590    #[serde_as(deserialize_as = "DefaultOnError")]
5591    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5592    #[serde(default)]
5593    pub system_prompt: Option<SessionSystemPromptCapabilities>,
5594    /// **UNSTABLE**
5595    ///
5596    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5597    ///
5598    /// Whether the agent supports `session/fork`.
5599    ///
5600    /// Optional. Omitted or `null` both mean the agent does not advertise support.
5601    /// Supplying `{}` means the agent supports forking sessions.
5602    #[cfg(feature = "unstable_session_fork")]
5603    #[serde_as(deserialize_as = "DefaultOnError")]
5604    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5605    #[serde(default)]
5606    pub fork: Option<SessionForkCapabilities>,
5607    /// **UNSTABLE**
5608    ///
5609    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5610    ///
5611    /// Whether the agent supports `session/archive` and `session/unarchive`.
5612    ///
5613    /// Optional. Omitted or `null` both mean the agent does not advertise support.
5614    /// Supplying `{}` means the agent supports both methods, the `archived` filter on
5615    /// `session/list`, and `SessionInfo.archived`. Agents that advertise it MUST also advertise `sessionCapabilities.list`.
5616    #[cfg(feature = "unstable_session_archive")]
5617    #[serde_as(deserialize_as = "DefaultOnError")]
5618    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5619    #[serde(default)]
5620    pub archive: Option<SessionArchiveCapabilities>,
5621    /// **UNSTABLE**
5622    ///
5623    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5624    ///
5625    /// Whether the agent supports `session/status`.
5626    ///
5627    /// Optional. Omitted or `null` both mean the agent does not advertise support.
5628    /// Supplying `{}` means the agent supports checking session status.
5629    #[cfg(feature = "unstable_session_status")]
5630    #[serde_as(deserialize_as = "DefaultOnError")]
5631    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5632    #[serde(default)]
5633    pub status: Option<SessionStatusCapabilities>,
5634    /// **UNSTABLE**
5635    ///
5636    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5637    ///
5638    /// Whether the agent supports `session/options`.
5639    ///
5640    /// Optional. Omitted or `null` both mean the agent does not advertise support.
5641    /// Supplying `{}` means the agent supports `session/options` and accepts initial
5642    /// config option values on session setup requests.
5643    #[cfg(feature = "unstable_session_options")]
5644    #[serde_as(deserialize_as = "DefaultOnError")]
5645    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5646    #[serde(default)]
5647    pub options: Option<SessionOptionsCapabilities>,
5648    /// **UNSTABLE**
5649    ///
5650    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5651    ///
5652    /// Whether the agent supports `session/set_title`.
5653    ///
5654    /// Agents report titles through `session/list` and `session_info_update` without this
5655    /// capability. It only advertises that Clients can set titles.
5656    ///
5657    /// Optional. Omitted or `null` both mean the agent does not advertise support.
5658    /// Supplying `{}` means the agent supports setting session titles.
5659    #[cfg(feature = "unstable_session_set_title")]
5660    #[serde_as(deserialize_as = "DefaultOnError")]
5661    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5662    #[serde(default)]
5663    pub title: Option<SessionTitleCapabilities>,
5664    /// Whether the agent supports `session/resume`.
5665    ///
5666    /// Optional. Omitted or `null` both mean the agent does not advertise support.
5667    /// Supplying `{}` means the agent supports resuming sessions.
5668    #[serde_as(deserialize_as = "DefaultOnError")]
5669    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5670    #[serde(default)]
5671    pub resume: Option<SessionResumeCapabilities>,
5672    /// Whether the agent supports `session/close`.
5673    ///
5674    /// Optional. Omitted or `null` both mean the agent does not advertise support.
5675    /// Supplying `{}` means the agent supports closing sessions.
5676    #[serde_as(deserialize_as = "DefaultOnError")]
5677    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5678    #[serde(default)]
5679    pub close: Option<SessionCloseCapabilities>,
5680    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5681    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5682    /// these keys.
5683    ///
5684    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5685    #[serde_as(deserialize_as = "DefaultOnError")]
5686    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5687    #[serde(default)]
5688    #[serde(rename = "_meta")]
5689    pub meta: Option<Meta>,
5690}
5691
5692impl SessionCapabilities {
5693    /// Builds an empty [`SessionCapabilities`]. Use builder methods to advertise supported sub-capabilities.
5694    #[must_use]
5695    pub fn new() -> Self {
5696        Self::default()
5697    }
5698
5699    /// Whether the agent supports `session/list`.
5700    ///
5701    /// Omitted or `null` both mean the agent does not advertise support.
5702    /// Supplying `{}` means the agent supports listing sessions.
5703    #[must_use]
5704    pub fn list(mut self, list: impl IntoOption<SessionListCapabilities>) -> Self {
5705        self.list = list.into_option();
5706        self
5707    }
5708
5709    /// Whether the agent supports `session/delete`.
5710    ///
5711    /// Omitted or `null` both mean the agent does not advertise support.
5712    /// Supplying `{}` means the agent supports deleting sessions from `session/list`.
5713    #[must_use]
5714    pub fn delete(mut self, delete: impl IntoOption<SessionDeleteCapabilities>) -> Self {
5715        self.delete = delete.into_option();
5716        self
5717    }
5718
5719    /// Whether the agent supports `additionalDirectories` on supported session lifecycle requests.
5720    ///
5721    /// Omitted or `null` both mean the agent does not advertise support.
5722    /// Supplying `{}` means the agent supports `additionalDirectories` on
5723    /// supported session lifecycle requests.
5724    ///
5725    /// Agents that also support `session/list` may return
5726    /// `SessionInfo.additionalDirectories` to report the complete ordered
5727    /// additional-root list associated with a listed session.
5728    #[must_use]
5729    pub fn additional_directories(
5730        mut self,
5731        additional_directories: impl IntoOption<SessionAdditionalDirectoriesCapabilities>,
5732    ) -> Self {
5733        self.additional_directories = additional_directories.into_option();
5734        self
5735    }
5736
5737    /// Whether the agent supports `systemPrompt` on session lifecycle requests.
5738    ///
5739    /// Omitted or `null` both mean the agent does not advertise support.
5740    /// Supplying `{}` means the agent supports `systemPrompt` in `append` mode.
5741    #[must_use]
5742    pub fn system_prompt(
5743        mut self,
5744        system_prompt: impl IntoOption<SessionSystemPromptCapabilities>,
5745    ) -> Self {
5746        self.system_prompt = system_prompt.into_option();
5747        self
5748    }
5749
5750    #[cfg(feature = "unstable_session_fork")]
5751    /// Whether the agent supports `session/fork`.
5752    ///
5753    /// Omitted or `null` both mean the agent does not advertise support.
5754    /// Supplying `{}` means the agent supports forking sessions.
5755    #[must_use]
5756    pub fn fork(mut self, fork: impl IntoOption<SessionForkCapabilities>) -> Self {
5757        self.fork = fork.into_option();
5758        self
5759    }
5760
5761    /// **UNSTABLE**
5762    ///
5763    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5764    ///
5765    /// Whether the agent supports `session/archive` and `session/unarchive`.
5766    ///
5767    /// Omitted or `null` both mean the agent does not advertise support.
5768    /// Supplying `{}` means the agent supports both methods, the `archived` filter on
5769    /// `session/list`, and `SessionInfo.archived`.
5770    #[cfg(feature = "unstable_session_archive")]
5771    #[must_use]
5772    pub fn archive(mut self, archive: impl IntoOption<SessionArchiveCapabilities>) -> Self {
5773        self.archive = archive.into_option();
5774        self
5775    }
5776
5777    /// **UNSTABLE**
5778    ///
5779    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5780    ///
5781    /// Whether the agent supports `session/status`.
5782    ///
5783    /// Omitted or `null` both mean the agent does not advertise support.
5784    /// Supplying `{}` means the agent supports checking session status.
5785    #[cfg(feature = "unstable_session_status")]
5786    #[must_use]
5787    pub fn status(mut self, status: impl IntoOption<SessionStatusCapabilities>) -> Self {
5788        self.status = status.into_option();
5789        self
5790    }
5791
5792    /// **UNSTABLE**
5793    ///
5794    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5795    ///
5796    /// Whether the agent supports `session/options`.
5797    ///
5798    /// Omitted or `null` both mean the agent does not advertise support.
5799    /// Supplying `{}` means the agent supports `session/options` and accepts initial
5800    /// config option values on session setup requests.
5801    #[cfg(feature = "unstable_session_options")]
5802    #[must_use]
5803    pub fn options(mut self, options: impl IntoOption<SessionOptionsCapabilities>) -> Self {
5804        self.options = options.into_option();
5805        self
5806    }
5807
5808    /// **UNSTABLE**
5809    ///
5810    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5811    ///
5812    /// Whether the agent supports `session/set_title`.
5813    ///
5814    /// Agents report titles through `session/list` and `session_info_update` without this
5815    /// capability. It only advertises that Clients can set titles.
5816    ///
5817    /// Omitted or `null` both mean the agent does not advertise support.
5818    /// Supplying `{}` means the agent supports setting session titles.
5819    #[cfg(feature = "unstable_session_set_title")]
5820    #[must_use]
5821    pub fn title(mut self, title: impl IntoOption<SessionTitleCapabilities>) -> Self {
5822        self.title = title.into_option();
5823        self
5824    }
5825
5826    /// Whether the agent supports `session/resume`.
5827    ///
5828    /// Omitted or `null` both mean the agent does not advertise support.
5829    /// Supplying `{}` means the agent supports resuming sessions.
5830    #[must_use]
5831    pub fn resume(mut self, resume: impl IntoOption<SessionResumeCapabilities>) -> Self {
5832        self.resume = resume.into_option();
5833        self
5834    }
5835
5836    /// Whether the agent supports `session/close`.
5837    ///
5838    /// Omitted or `null` both mean the agent does not advertise support.
5839    /// Supplying `{}` means the agent supports closing sessions.
5840    #[must_use]
5841    pub fn close(mut self, close: impl IntoOption<SessionCloseCapabilities>) -> Self {
5842        self.close = close.into_option();
5843        self
5844    }
5845
5846    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5847    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5848    /// these keys.
5849    ///
5850    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5851    #[must_use]
5852    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5853        self.meta = meta.into_option();
5854        self
5855    }
5856}
5857
5858/// Capabilities for the `session/list` method.
5859///
5860/// Supplying `{}` means the agent supports listing sessions.
5861#[serde_as]
5862#[skip_serializing_none]
5863#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5864#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5865#[non_exhaustive]
5866pub struct SessionListCapabilities {
5867    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5868    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5869    /// these keys.
5870    ///
5871    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5872    #[serde_as(deserialize_as = "DefaultOnError")]
5873    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5874    #[serde(default)]
5875    #[serde(rename = "_meta")]
5876    pub meta: Option<Meta>,
5877}
5878
5879impl SessionListCapabilities {
5880    /// Builds an empty [`SessionListCapabilities`]. Use builder methods to advertise supported sub-capabilities.
5881    #[must_use]
5882    pub fn new() -> Self {
5883        Self::default()
5884    }
5885
5886    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5887    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5888    /// these keys.
5889    ///
5890    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5891    #[must_use]
5892    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5893        self.meta = meta.into_option();
5894        self
5895    }
5896}
5897
5898/// Capabilities for the `session/delete` method.
5899///
5900/// Supplying `{}` means the agent supports deleting sessions from `session/list`.
5901#[serde_as]
5902#[skip_serializing_none]
5903#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5904#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5905#[non_exhaustive]
5906pub struct SessionDeleteCapabilities {
5907    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5908    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5909    /// these keys.
5910    ///
5911    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5912    #[serde_as(deserialize_as = "DefaultOnError")]
5913    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5914    #[serde(default)]
5915    #[serde(rename = "_meta")]
5916    pub meta: Option<Meta>,
5917}
5918
5919impl SessionDeleteCapabilities {
5920    /// Builds an empty [`SessionDeleteCapabilities`]. Use builder methods to advertise supported sub-capabilities.
5921    #[must_use]
5922    pub fn new() -> Self {
5923        Self::default()
5924    }
5925
5926    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5927    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5928    /// these keys.
5929    ///
5930    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5931    #[must_use]
5932    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5933        self.meta = meta.into_option();
5934        self
5935    }
5936}
5937
5938/// Capabilities for additional session directories support.
5939///
5940/// Supplying `{}` means the agent supports the `additionalDirectories` field on
5941/// supported session lifecycle requests. Agents that also support
5942/// `session/list` may return `SessionInfo.additionalDirectories` to report the
5943/// complete ordered additional-root list associated with a listed session.
5944#[serde_as]
5945#[skip_serializing_none]
5946#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5947#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5948#[non_exhaustive]
5949pub struct SessionAdditionalDirectoriesCapabilities {
5950    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5951    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5952    /// these keys.
5953    ///
5954    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5955    #[serde_as(deserialize_as = "DefaultOnError")]
5956    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5957    #[serde(default)]
5958    #[serde(rename = "_meta")]
5959    pub meta: Option<Meta>,
5960}
5961
5962impl SessionAdditionalDirectoriesCapabilities {
5963    /// Builds an empty [`SessionAdditionalDirectoriesCapabilities`]. Use builder methods to advertise supported sub-capabilities.
5964    #[must_use]
5965    pub fn new() -> Self {
5966        Self::default()
5967    }
5968
5969    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5970    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5971    /// these keys.
5972    ///
5973    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5974    #[must_use]
5975    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5976        self.meta = meta.into_option();
5977        self
5978    }
5979}
5980
5981/// Capabilities for client-provided system prompts.
5982///
5983/// Supplying `{}` means the agent supports `systemPrompt` on session lifecycle
5984/// requests in `append` mode.
5985#[serde_as]
5986#[skip_serializing_none]
5987#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5988#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5989#[serde(rename_all = "camelCase")]
5990#[non_exhaustive]
5991pub struct SessionSystemPromptCapabilities {
5992    /// Delivery modes the agent supports in addition to `append`.
5993    ///
5994    /// Optional. Omitted or `null` both mean the agent supports only `append`.
5995    #[serde_as(deserialize_as = "DefaultOnError")]
5996    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5997    #[serde(default)]
5998    pub mode: Option<SessionSystemPromptModeCapabilities>,
5999    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6000    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6001    /// these keys.
6002    ///
6003    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6004    #[serde_as(deserialize_as = "DefaultOnError")]
6005    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6006    #[serde(default)]
6007    #[serde(rename = "_meta")]
6008    pub meta: Option<Meta>,
6009}
6010
6011impl SessionSystemPromptCapabilities {
6012    /// Builds an empty [`SessionSystemPromptCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6013    #[must_use]
6014    pub fn new() -> Self {
6015        Self::default()
6016    }
6017
6018    /// Delivery modes the agent supports in addition to `append`.
6019    ///
6020    /// Omitted or `null` both mean the agent supports only `append`.
6021    #[must_use]
6022    pub fn mode(mut self, mode: impl IntoOption<SessionSystemPromptModeCapabilities>) -> Self {
6023        self.mode = mode.into_option();
6024        self
6025    }
6026
6027    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6028    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6029    /// these keys.
6030    ///
6031    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6032    #[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/// System prompt delivery modes the agent supports in addition to `append`.
6040///
6041/// `append` has no entry because every agent advertising
6042/// `sessionCapabilities.systemPrompt` supports it.
6043#[serde_as]
6044#[skip_serializing_none]
6045#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6046#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6047#[serde(rename_all = "camelCase")]
6048#[non_exhaustive]
6049pub struct SessionSystemPromptModeCapabilities {
6050    /// Whether the agent supports `override` mode.
6051    ///
6052    /// Optional. Omitted or `null` both mean the agent does not advertise support.
6053    /// Supplying `{}` means the agent supports replacing its built-in default
6054    /// instructions with the client-provided system prompt.
6055    #[serde_as(deserialize_as = "DefaultOnError")]
6056    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6057    #[serde(default, rename = "override")]
6058    pub override_: Option<SessionSystemPromptOverrideCapabilities>,
6059    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6060    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6061    /// these keys.
6062    ///
6063    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6064    #[serde_as(deserialize_as = "DefaultOnError")]
6065    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6066    #[serde(default)]
6067    #[serde(rename = "_meta")]
6068    pub meta: Option<Meta>,
6069}
6070
6071impl SessionSystemPromptModeCapabilities {
6072    /// Builds an empty [`SessionSystemPromptModeCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6073    #[must_use]
6074    pub fn new() -> Self {
6075        Self::default()
6076    }
6077
6078    /// Whether the agent supports `override` mode.
6079    ///
6080    /// Omitted or `null` both mean the agent does not advertise support.
6081    /// Supplying `{}` means the agent supports replacing its built-in default
6082    /// instructions with the client-provided system prompt.
6083    #[must_use]
6084    pub fn override_(
6085        mut self,
6086        override_: impl IntoOption<SessionSystemPromptOverrideCapabilities>,
6087    ) -> Self {
6088        self.override_ = override_.into_option();
6089        self
6090    }
6091
6092    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6093    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6094    /// these keys.
6095    ///
6096    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6097    #[must_use]
6098    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6099        self.meta = meta.into_option();
6100        self
6101    }
6102}
6103
6104/// Capabilities for the `override` system prompt mode.
6105///
6106/// Supplying `{}` means the agent supports replacing its built-in default
6107/// instructions with the client-provided system prompt.
6108#[serde_as]
6109#[skip_serializing_none]
6110#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6111#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6112#[non_exhaustive]
6113pub struct SessionSystemPromptOverrideCapabilities {
6114    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6115    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6116    /// these keys.
6117    ///
6118    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6119    #[serde_as(deserialize_as = "DefaultOnError")]
6120    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6121    #[serde(default)]
6122    #[serde(rename = "_meta")]
6123    pub meta: Option<Meta>,
6124}
6125
6126impl SessionSystemPromptOverrideCapabilities {
6127    /// Builds an empty [`SessionSystemPromptOverrideCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6128    #[must_use]
6129    pub fn new() -> Self {
6130        Self::default()
6131    }
6132
6133    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6134    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6135    /// these keys.
6136    ///
6137    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6138    #[must_use]
6139    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6140        self.meta = meta.into_option();
6141        self
6142    }
6143}
6144
6145/// **UNSTABLE**
6146///
6147/// This capability is not part of the spec yet, and may be removed or changed at any point.
6148///
6149/// Capabilities for the `session/fork` method.
6150///
6151/// Supplying `{}` means the agent supports forking sessions.
6152#[cfg(feature = "unstable_session_fork")]
6153#[serde_as]
6154#[skip_serializing_none]
6155#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6156#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6157#[non_exhaustive]
6158pub struct SessionForkCapabilities {
6159    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6160    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6161    /// these keys.
6162    ///
6163    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6164    #[serde_as(deserialize_as = "DefaultOnError")]
6165    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6166    #[serde(default)]
6167    #[serde(rename = "_meta")]
6168    pub meta: Option<Meta>,
6169}
6170
6171#[cfg(feature = "unstable_session_fork")]
6172impl SessionForkCapabilities {
6173    /// Builds an empty [`SessionForkCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6174    #[must_use]
6175    pub fn new() -> Self {
6176        Self::default()
6177    }
6178
6179    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6180    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6181    /// these keys.
6182    ///
6183    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6184    #[must_use]
6185    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6186        self.meta = meta.into_option();
6187        self
6188    }
6189}
6190
6191/// **UNSTABLE**
6192///
6193/// This capability is not part of the spec yet, and may be removed or changed at any point.
6194///
6195/// Capabilities for `session/archive` and `session/unarchive`.
6196///
6197/// Supplying `{}` means the agent supports both methods, the `archived` filter on
6198/// `session/list`, and `SessionInfo.archived`.
6199#[cfg(feature = "unstable_session_archive")]
6200#[serde_as]
6201#[skip_serializing_none]
6202#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6203#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6204#[non_exhaustive]
6205pub struct SessionArchiveCapabilities {
6206    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6207    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6208    /// these keys.
6209    ///
6210    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6211    #[serde_as(deserialize_as = "DefaultOnError")]
6212    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6213    #[serde(default)]
6214    #[serde(rename = "_meta")]
6215    pub meta: Option<Meta>,
6216}
6217
6218#[cfg(feature = "unstable_session_archive")]
6219impl SessionArchiveCapabilities {
6220    /// Builds an empty [`SessionArchiveCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6221    #[must_use]
6222    pub fn new() -> Self {
6223        Self::default()
6224    }
6225
6226    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6227    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6228    /// these keys.
6229    ///
6230    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6231    #[must_use]
6232    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6233        self.meta = meta.into_option();
6234        self
6235    }
6236}
6237
6238/// **UNSTABLE**
6239///
6240/// This capability is not part of the spec yet, and may be removed or changed at any point.
6241///
6242/// Capabilities for the `session/status` method.
6243///
6244/// Supplying `{}` means the agent supports checking session status.
6245#[cfg(feature = "unstable_session_status")]
6246#[serde_as]
6247#[skip_serializing_none]
6248#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6249#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6250#[non_exhaustive]
6251pub struct SessionStatusCapabilities {
6252    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6253    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6254    /// these keys.
6255    ///
6256    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6257    #[serde_as(deserialize_as = "DefaultOnError")]
6258    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6259    #[serde(default)]
6260    #[serde(rename = "_meta")]
6261    pub meta: Option<Meta>,
6262}
6263
6264#[cfg(feature = "unstable_session_status")]
6265impl SessionStatusCapabilities {
6266    /// Builds an empty [`SessionStatusCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6267    #[must_use]
6268    pub fn new() -> Self {
6269        Self::default()
6270    }
6271
6272    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6273    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6274    /// these keys.
6275    ///
6276    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6277    #[must_use]
6278    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6279        self.meta = meta.into_option();
6280        self
6281    }
6282}
6283
6284/// **UNSTABLE**
6285///
6286/// This capability is not part of the spec yet, and may be removed or changed at any point.
6287///
6288/// Capabilities for the `session/options` method.
6289///
6290/// Supplying `{}` means the agent supports `session/options` and accepts initial config
6291/// option values on session setup requests.
6292#[cfg(feature = "unstable_session_options")]
6293#[serde_as]
6294#[skip_serializing_none]
6295#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6296#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6297#[non_exhaustive]
6298pub struct SessionOptionsCapabilities {
6299    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6300    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6301    /// these keys.
6302    ///
6303    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6304    #[serde_as(deserialize_as = "DefaultOnError")]
6305    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6306    #[serde(default)]
6307    #[serde(rename = "_meta")]
6308    pub meta: Option<Meta>,
6309}
6310
6311#[cfg(feature = "unstable_session_options")]
6312impl SessionOptionsCapabilities {
6313    /// Builds an empty [`SessionOptionsCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6314    #[must_use]
6315    pub fn new() -> Self {
6316        Self::default()
6317    }
6318
6319    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6320    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6321    /// these keys.
6322    ///
6323    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6324    #[must_use]
6325    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6326        self.meta = meta.into_option();
6327        self
6328    }
6329}
6330
6331/// **UNSTABLE**
6332///
6333/// This capability is not part of the spec yet, and may be removed or changed at any point.
6334///
6335/// Capabilities for Client-set session titles.
6336///
6337/// Supplying `{}` means the agent supports `session/set_title`. Agents report titles
6338/// through `session/list` and `session_info_update` without this capability.
6339#[cfg(feature = "unstable_session_set_title")]
6340#[serde_as]
6341#[skip_serializing_none]
6342#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6343#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6344#[non_exhaustive]
6345pub struct SessionTitleCapabilities {
6346    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6347    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6348    /// these keys.
6349    ///
6350    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6351    #[serde_as(deserialize_as = "DefaultOnError")]
6352    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6353    #[serde(default)]
6354    #[serde(rename = "_meta")]
6355    pub meta: Option<Meta>,
6356}
6357
6358#[cfg(feature = "unstable_session_set_title")]
6359impl SessionTitleCapabilities {
6360    /// Builds an empty [`SessionTitleCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6361    #[must_use]
6362    pub fn new() -> Self {
6363        Self::default()
6364    }
6365
6366    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6367    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6368    /// these keys.
6369    ///
6370    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6371    #[must_use]
6372    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6373        self.meta = meta.into_option();
6374        self
6375    }
6376}
6377
6378/// Capabilities for the `session/resume` method.
6379///
6380/// Supplying `{}` means the agent supports resuming sessions.
6381#[serde_as]
6382#[skip_serializing_none]
6383#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6384#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6385#[non_exhaustive]
6386pub struct SessionResumeCapabilities {
6387    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6388    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6389    /// these keys.
6390    ///
6391    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6392    #[serde_as(deserialize_as = "DefaultOnError")]
6393    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6394    #[serde(default)]
6395    #[serde(rename = "_meta")]
6396    pub meta: Option<Meta>,
6397}
6398
6399impl SessionResumeCapabilities {
6400    /// Builds an empty [`SessionResumeCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6401    #[must_use]
6402    pub fn new() -> Self {
6403        Self::default()
6404    }
6405
6406    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6407    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6408    /// these keys.
6409    ///
6410    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6411    #[must_use]
6412    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6413        self.meta = meta.into_option();
6414        self
6415    }
6416}
6417
6418/// Capabilities for the `session/close` method.
6419///
6420/// Supplying `{}` means the agent supports closing sessions.
6421#[serde_as]
6422#[skip_serializing_none]
6423#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6424#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6425#[non_exhaustive]
6426pub struct SessionCloseCapabilities {
6427    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6428    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6429    /// these keys.
6430    ///
6431    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6432    #[serde_as(deserialize_as = "DefaultOnError")]
6433    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6434    #[serde(default)]
6435    #[serde(rename = "_meta")]
6436    pub meta: Option<Meta>,
6437}
6438
6439impl SessionCloseCapabilities {
6440    /// Builds an empty [`SessionCloseCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6441    #[must_use]
6442    pub fn new() -> Self {
6443        Self::default()
6444    }
6445
6446    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6447    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6448    /// these keys.
6449    ///
6450    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6451    #[must_use]
6452    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6453        self.meta = meta.into_option();
6454        self
6455    }
6456}
6457
6458/// Prompt capabilities supported by the agent in `session/prompt` requests.
6459///
6460/// Baseline agent functionality requires support for `text`
6461/// and `resource_link` content blocks in prompt requests.
6462///
6463/// Other variants must be explicitly opted in to.
6464/// Capabilities for different types of content in prompt requests.
6465///
6466/// Indicates which content types beyond the baseline (text and resource links)
6467/// the agent can process.
6468///
6469/// See protocol docs: [Prompt Capabilities](https://agentclientprotocol.com/protocol/v1/initialization#prompt-capabilities)
6470#[serde_as]
6471#[skip_serializing_none]
6472#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6473#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6474#[serde(rename_all = "camelCase")]
6475#[non_exhaustive]
6476pub struct PromptCapabilities {
6477    /// Agent supports `image` content blocks.
6478    #[serde_as(deserialize_as = "DefaultOnError")]
6479    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6480    #[serde(default)]
6481    pub image: bool,
6482    /// Agent supports `audio` content blocks.
6483    #[serde_as(deserialize_as = "DefaultOnError")]
6484    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6485    #[serde(default)]
6486    pub audio: bool,
6487    /// Agent supports embedded context in `session/prompt` requests.
6488    ///
6489    /// When enabled, the Client is allowed to include `resource` content blocks
6490    /// in prompt requests for pieces of context that are referenced in the message.
6491    #[serde_as(deserialize_as = "DefaultOnError")]
6492    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6493    #[serde(default)]
6494    pub embedded_context: bool,
6495    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6496    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6497    /// these keys.
6498    ///
6499    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6500    #[serde_as(deserialize_as = "DefaultOnError")]
6501    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6502    #[serde(default)]
6503    #[serde(rename = "_meta")]
6504    pub meta: Option<Meta>,
6505}
6506
6507impl PromptCapabilities {
6508    /// Builds an empty [`PromptCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6509    #[must_use]
6510    pub fn new() -> Self {
6511        Self::default()
6512    }
6513
6514    /// Agent supports `image` content blocks.
6515    #[must_use]
6516    pub fn image(mut self, image: bool) -> Self {
6517        self.image = image;
6518        self
6519    }
6520
6521    /// Agent supports `audio` content blocks.
6522    #[must_use]
6523    pub fn audio(mut self, audio: bool) -> Self {
6524        self.audio = audio;
6525        self
6526    }
6527
6528    /// Agent supports embedded context in `session/prompt` requests.
6529    ///
6530    /// When enabled, the Client is allowed to include `resource` content blocks
6531    /// in prompt requests for pieces of context that are referenced in the message.
6532    #[must_use]
6533    pub fn embedded_context(mut self, embedded_context: bool) -> Self {
6534        self.embedded_context = embedded_context;
6535        self
6536    }
6537
6538    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6539    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6540    /// these keys.
6541    ///
6542    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6543    #[must_use]
6544    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6545        self.meta = meta.into_option();
6546        self
6547    }
6548}
6549
6550/// MCP capabilities supported by the agent
6551#[serde_as]
6552#[skip_serializing_none]
6553#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6554#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6555#[serde(rename_all = "camelCase")]
6556#[non_exhaustive]
6557pub struct McpCapabilities {
6558    /// Agent supports `http` MCP servers.
6559    #[serde_as(deserialize_as = "DefaultOnError")]
6560    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6561    #[serde(default)]
6562    pub http: bool,
6563    /// Agent supports `sse` MCP servers.
6564    #[serde_as(deserialize_as = "DefaultOnError")]
6565    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6566    #[serde(default)]
6567    pub sse: bool,
6568    /// **UNSTABLE**
6569    ///
6570    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6571    ///
6572    /// Agent supports `acp` MCP servers.
6573    #[cfg(feature = "unstable_mcp_over_acp")]
6574    #[serde_as(deserialize_as = "DefaultOnError")]
6575    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6576    #[serde(default)]
6577    pub acp: bool,
6578    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6579    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6580    /// these keys.
6581    ///
6582    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6583    #[serde_as(deserialize_as = "DefaultOnError")]
6584    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6585    #[serde(default)]
6586    #[serde(rename = "_meta")]
6587    pub meta: Option<Meta>,
6588}
6589
6590impl McpCapabilities {
6591    /// Builds an empty [`McpCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6592    #[must_use]
6593    pub fn new() -> Self {
6594        Self::default()
6595    }
6596
6597    /// Agent supports `http` MCP servers.
6598    #[must_use]
6599    pub fn http(mut self, http: bool) -> Self {
6600        self.http = http;
6601        self
6602    }
6603
6604    /// Agent supports `sse` MCP servers.
6605    #[must_use]
6606    pub fn sse(mut self, sse: bool) -> Self {
6607        self.sse = sse;
6608        self
6609    }
6610
6611    /// **UNSTABLE**
6612    ///
6613    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6614    ///
6615    /// Agent supports `acp` MCP servers.
6616    #[cfg(feature = "unstable_mcp_over_acp")]
6617    #[must_use]
6618    pub fn acp(mut self, acp: bool) -> Self {
6619        self.acp = acp;
6620        self
6621    }
6622
6623    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6624    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6625    /// these keys.
6626    ///
6627    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6628    #[must_use]
6629    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6630        self.meta = meta.into_option();
6631        self
6632    }
6633}
6634
6635// Method schema
6636
6637/// Names of all methods that agents handle.
6638///
6639/// Provides a centralized definition of method names used in the protocol.
6640#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6641#[non_exhaustive]
6642pub struct AgentMethodNames {
6643    /// Method for initializing the connection.
6644    pub initialize: &'static str,
6645    /// Method for authenticating with the agent.
6646    pub authenticate: &'static str,
6647    /// Method for listing configurable providers.
6648    #[cfg(feature = "unstable_llm_providers")]
6649    pub providers_list: &'static str,
6650    /// Method for setting provider configuration.
6651    #[cfg(feature = "unstable_llm_providers")]
6652    pub providers_set: &'static str,
6653    /// Method for disabling a provider.
6654    #[cfg(feature = "unstable_llm_providers")]
6655    pub providers_disable: &'static str,
6656    /// Method for creating a new session.
6657    pub session_new: &'static str,
6658    /// Method for loading an existing session.
6659    pub session_load: &'static str,
6660    /// Method for setting the mode for a session.
6661    pub session_set_mode: &'static str,
6662    /// Method for setting a configuration option for a session.
6663    pub session_set_config_option: &'static str,
6664    /// Method for sending a prompt to the agent.
6665    pub session_prompt: &'static str,
6666    /// Notification for cancelling operations.
6667    pub session_cancel: &'static str,
6668    /// Method for exchanging MCP-over-ACP messages.
6669    #[cfg(feature = "unstable_mcp_over_acp")]
6670    pub mcp_message: &'static str,
6671    /// Method for listing existing sessions.
6672    pub session_list: &'static str,
6673    /// Method for deleting an existing session.
6674    pub session_delete: &'static str,
6675    /// Method for forking an existing session.
6676    #[cfg(feature = "unstable_session_fork")]
6677    pub session_fork: &'static str,
6678    /// Method for archiving a session.
6679    #[cfg(feature = "unstable_session_archive")]
6680    pub session_archive: &'static str,
6681    /// Method for unarchiving a session.
6682    #[cfg(feature = "unstable_session_archive")]
6683    pub session_unarchive: &'static str,
6684    /// Method for checking the status of a session.
6685    #[cfg(feature = "unstable_session_status")]
6686    pub session_status: &'static str,
6687    /// Method for querying the config options a session would start with.
6688    #[cfg(feature = "unstable_session_options")]
6689    pub session_options: &'static str,
6690    /// Method for setting the title of a session.
6691    #[cfg(feature = "unstable_session_set_title")]
6692    pub session_set_title: &'static str,
6693    /// Method for resuming an existing session.
6694    pub session_resume: &'static str,
6695    /// Method for closing an active session.
6696    pub session_close: &'static str,
6697    /// Method for logging out of an authenticated session.
6698    pub logout: &'static str,
6699    /// Method for querying the agent's authentication state.
6700    #[cfg(feature = "unstable_auth_status")]
6701    pub auth_status: &'static str,
6702}
6703
6704/// Constant containing all agent method names.
6705pub const AGENT_METHOD_NAMES: AgentMethodNames = AgentMethodNames {
6706    initialize: INITIALIZE_METHOD_NAME,
6707    authenticate: AUTHENTICATE_METHOD_NAME,
6708    #[cfg(feature = "unstable_llm_providers")]
6709    providers_list: PROVIDERS_LIST_METHOD_NAME,
6710    #[cfg(feature = "unstable_llm_providers")]
6711    providers_set: PROVIDERS_SET_METHOD_NAME,
6712    #[cfg(feature = "unstable_llm_providers")]
6713    providers_disable: PROVIDERS_DISABLE_METHOD_NAME,
6714    session_new: SESSION_NEW_METHOD_NAME,
6715    session_load: SESSION_LOAD_METHOD_NAME,
6716    session_set_mode: SESSION_SET_MODE_METHOD_NAME,
6717    session_set_config_option: SESSION_SET_CONFIG_OPTION_METHOD_NAME,
6718    session_prompt: SESSION_PROMPT_METHOD_NAME,
6719    session_cancel: SESSION_CANCEL_METHOD_NAME,
6720    #[cfg(feature = "unstable_mcp_over_acp")]
6721    mcp_message: MCP_MESSAGE_METHOD_NAME,
6722    session_list: SESSION_LIST_METHOD_NAME,
6723    session_delete: SESSION_DELETE_METHOD_NAME,
6724    #[cfg(feature = "unstable_session_fork")]
6725    session_fork: SESSION_FORK_METHOD_NAME,
6726    #[cfg(feature = "unstable_session_archive")]
6727    session_archive: SESSION_ARCHIVE_METHOD_NAME,
6728    #[cfg(feature = "unstable_session_archive")]
6729    session_unarchive: SESSION_UNARCHIVE_METHOD_NAME,
6730    #[cfg(feature = "unstable_session_status")]
6731    session_status: SESSION_STATUS_METHOD_NAME,
6732    #[cfg(feature = "unstable_session_options")]
6733    session_options: SESSION_OPTIONS_METHOD_NAME,
6734    #[cfg(feature = "unstable_session_set_title")]
6735    session_set_title: SESSION_SET_TITLE_METHOD_NAME,
6736    session_resume: SESSION_RESUME_METHOD_NAME,
6737    session_close: SESSION_CLOSE_METHOD_NAME,
6738    logout: LOGOUT_METHOD_NAME,
6739    #[cfg(feature = "unstable_auth_status")]
6740    auth_status: AUTH_STATUS_METHOD_NAME,
6741};
6742
6743/// Method name for the initialize request.
6744pub(crate) const INITIALIZE_METHOD_NAME: &str = "initialize";
6745/// Method name for the authenticate request.
6746pub(crate) const AUTHENTICATE_METHOD_NAME: &str = "authenticate";
6747/// Method name for listing configurable providers.
6748#[cfg(feature = "unstable_llm_providers")]
6749pub(crate) const PROVIDERS_LIST_METHOD_NAME: &str = "providers/list";
6750/// Method name for setting provider configuration.
6751#[cfg(feature = "unstable_llm_providers")]
6752pub(crate) const PROVIDERS_SET_METHOD_NAME: &str = "providers/set";
6753/// Method name for disabling a provider.
6754#[cfg(feature = "unstable_llm_providers")]
6755pub(crate) const PROVIDERS_DISABLE_METHOD_NAME: &str = "providers/disable";
6756/// Method name for creating a new session.
6757pub(crate) const SESSION_NEW_METHOD_NAME: &str = "session/new";
6758/// Method name for loading an existing session.
6759pub(crate) const SESSION_LOAD_METHOD_NAME: &str = "session/load";
6760/// Method name for setting the mode for a session.
6761pub(crate) const SESSION_SET_MODE_METHOD_NAME: &str = "session/set_mode";
6762/// Method name for setting a configuration option for a session.
6763pub(crate) const SESSION_SET_CONFIG_OPTION_METHOD_NAME: &str = "session/set_config_option";
6764/// Method name for sending a prompt.
6765pub(crate) const SESSION_PROMPT_METHOD_NAME: &str = "session/prompt";
6766/// Method name for the cancel notification.
6767pub(crate) const SESSION_CANCEL_METHOD_NAME: &str = "session/cancel";
6768/// Method name for listing existing sessions.
6769pub(crate) const SESSION_LIST_METHOD_NAME: &str = "session/list";
6770/// Method name for deleting an existing session.
6771pub(crate) const SESSION_DELETE_METHOD_NAME: &str = "session/delete";
6772/// Method name for forking an existing session.
6773#[cfg(feature = "unstable_session_fork")]
6774pub(crate) const SESSION_FORK_METHOD_NAME: &str = "session/fork";
6775/// Method name for archiving a session.
6776#[cfg(feature = "unstable_session_archive")]
6777pub(crate) const SESSION_ARCHIVE_METHOD_NAME: &str = "session/archive";
6778/// Method name for unarchiving a session.
6779#[cfg(feature = "unstable_session_archive")]
6780pub(crate) const SESSION_UNARCHIVE_METHOD_NAME: &str = "session/unarchive";
6781/// Method name for checking the status of a session.
6782#[cfg(feature = "unstable_session_status")]
6783pub(crate) const SESSION_STATUS_METHOD_NAME: &str = "session/status";
6784/// Method name for querying the config options a session would start with.
6785#[cfg(feature = "unstable_session_options")]
6786pub(crate) const SESSION_OPTIONS_METHOD_NAME: &str = "session/options";
6787/// Method name for setting the title of a session.
6788#[cfg(feature = "unstable_session_set_title")]
6789pub(crate) const SESSION_SET_TITLE_METHOD_NAME: &str = "session/set_title";
6790/// Method name for resuming an existing session.
6791pub(crate) const SESSION_RESUME_METHOD_NAME: &str = "session/resume";
6792/// Method name for closing an active session.
6793pub(crate) const SESSION_CLOSE_METHOD_NAME: &str = "session/close";
6794/// Method name for logging out of an authenticated session.
6795pub(crate) const LOGOUT_METHOD_NAME: &str = "logout";
6796/// Method name for the `auth/status` request.
6797#[cfg(feature = "unstable_auth_status")]
6798pub(crate) const AUTH_STATUS_METHOD_NAME: &str = "auth/status";
6799
6800/// All possible requests that a client can send to an agent.
6801///
6802/// This enum is used internally for routing RPC requests. You typically won't need
6803/// to use this directly.
6804///
6805/// This enum encompasses all method calls from client to agent.
6806#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6807#[derive(Clone, Debug, Serialize, Deserialize)]
6808#[serde(untagged)]
6809#[cfg_attr(feature = "schemars", schemars(inline))]
6810#[non_exhaustive]
6811#[allow(clippy::large_enum_variant)]
6812pub enum ClientRequest {
6813    /// Establishes the connection with a client and negotiates protocol capabilities.
6814    ///
6815    /// This method is called once at the beginning of the connection to:
6816    /// - Negotiate the protocol version to use
6817    /// - Exchange capability information between client and agent
6818    /// - Determine available authentication methods
6819    ///
6820    /// The agent should respond with its supported protocol version and capabilities.
6821    ///
6822    /// See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/v1/initialization)
6823    InitializeRequest(InitializeRequest),
6824    /// Authenticates the client using the specified authentication method.
6825    ///
6826    /// Called when the agent requires authentication before allowing session creation.
6827    /// The client provides an authentication method ID that was advertised during
6828    /// initialization and whose type defines the `authenticate` flow.
6829    ///
6830    /// After successful authentication, the client can proceed to create sessions with
6831    /// `session/new` without receiving an `auth_required` (`-32000`) error.
6832    ///
6833    /// See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/v1/initialization)
6834    AuthenticateRequest(AuthenticateRequest),
6835    /// **UNSTABLE**
6836    ///
6837    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6838    ///
6839    /// Lists providers that can be configured by the client.
6840    #[cfg(feature = "unstable_llm_providers")]
6841    ListProvidersRequest(ListProvidersRequest),
6842    /// **UNSTABLE**
6843    ///
6844    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6845    ///
6846    /// Replaces the configuration for a provider.
6847    #[cfg(feature = "unstable_llm_providers")]
6848    SetProviderRequest(SetProviderRequest),
6849    /// **UNSTABLE**
6850    ///
6851    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6852    ///
6853    /// Disables a provider.
6854    #[cfg(feature = "unstable_llm_providers")]
6855    DisableProviderRequest(DisableProviderRequest),
6856    /// Logs out of the current authenticated state.
6857    ///
6858    /// After a successful logout, all new sessions will require authentication.
6859    /// There is no guarantee about the behavior of already running sessions.
6860    LogoutRequest(LogoutRequest),
6861    /// **UNSTABLE**
6862    ///
6863    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6864    ///
6865    /// Queries the agent's current authentication state.
6866    ///
6867    /// This method is only available if the agent advertises the `auth.status` capability.
6868    /// It MUST NOT change any agent state, and agents MUST NOT reject it with `auth_required`.
6869    #[cfg(feature = "unstable_auth_status")]
6870    AuthStatusRequest(AuthStatusRequest),
6871    /// Creates a new conversation session with the agent.
6872    ///
6873    /// Sessions represent independent conversation contexts with their own history and state.
6874    ///
6875    /// The agent should:
6876    /// - Create a new session context
6877    /// - Connect to any specified MCP servers
6878    /// - Return a unique session ID for future requests
6879    ///
6880    /// May return an `auth_required` (`-32000`) error if the agent requires authentication.
6881    ///
6882    /// See protocol docs: [Session Setup](https://agentclientprotocol.com/protocol/v1/session-setup)
6883    NewSessionRequest(NewSessionRequest),
6884    /// Loads an existing session to resume a previous conversation.
6885    ///
6886    /// This method is only available if the agent advertises the `loadSession` capability.
6887    ///
6888    /// The agent should:
6889    /// - Restore the session context and conversation history
6890    /// - Connect to the specified MCP servers
6891    /// - Stream the entire conversation history back to the client via notifications
6892    ///
6893    /// See protocol docs: [Loading Sessions](https://agentclientprotocol.com/protocol/v1/session-setup#loading-sessions)
6894    LoadSessionRequest(LoadSessionRequest),
6895    /// Lists existing sessions known to the agent.
6896    ///
6897    /// This method is only available if the agent advertises the `sessionCapabilities.list` capability.
6898    ///
6899    /// The agent should return metadata about sessions with optional filtering and pagination support.
6900    ListSessionsRequest(ListSessionsRequest),
6901    /// Deletes an existing session from `session/list`.
6902    ///
6903    /// This method is only available if the agent advertises the `sessionCapabilities.delete` capability.
6904    DeleteSessionRequest(DeleteSessionRequest),
6905    #[cfg(feature = "unstable_session_fork")]
6906    /// **UNSTABLE**
6907    ///
6908    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6909    ///
6910    /// Forks an existing session to create a new independent session.
6911    ///
6912    /// This method is only available if the agent advertises the `session.fork` capability.
6913    ///
6914    /// The agent should create a new session with the same conversation context as the
6915    /// original, allowing operations like generating summaries without affecting the
6916    /// original session's history.
6917    ///
6918    /// As with `session/new`, the forked session is active once the agent responds,
6919    /// set up with the request's `cwd`, `additionalDirectories`, and `mcpServers`.
6920    /// The client can prompt it without calling `session/load` or `session/resume` first.
6921    ForkSessionRequest(ForkSessionRequest),
6922    #[cfg(feature = "unstable_session_archive")]
6923    /// **UNSTABLE**
6924    ///
6925    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6926    ///
6927    /// Archives a session, hiding it from default `session/list` results.
6928    ///
6929    /// This method is only available if the agent advertises the `sessionCapabilities.archive` capability.
6930    ArchiveSessionRequest(ArchiveSessionRequest),
6931    #[cfg(feature = "unstable_session_archive")]
6932    /// **UNSTABLE**
6933    ///
6934    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6935    ///
6936    /// Unarchives a session, returning it to default `session/list` results.
6937    ///
6938    /// This method is only available if the agent advertises the `sessionCapabilities.archive` capability.
6939    UnarchiveSessionRequest(UnarchiveSessionRequest),
6940    #[cfg(feature = "unstable_session_status")]
6941    /// **UNSTABLE**
6942    ///
6943    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6944    ///
6945    /// Checks whether the Agent has a session in memory, without changing it.
6946    ///
6947    /// This method is only available if the agent advertises the `sessionCapabilities.status` capability.
6948    SessionStatusRequest(SessionStatusRequest),
6949    #[cfg(feature = "unstable_session_options")]
6950    /// **UNSTABLE**
6951    ///
6952    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6953    ///
6954    /// Returns the config options a session would start with, without creating or resuming a session.
6955    ///
6956    /// This method is only available if the agent advertises the `sessionCapabilities.options` capability.
6957    SessionOptionsRequest(SessionOptionsRequest),
6958    #[cfg(feature = "unstable_session_set_title")]
6959    /// **UNSTABLE**
6960    ///
6961    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6962    ///
6963    /// Sets the title of a session.
6964    ///
6965    /// This method is only available if the agent advertises the `sessionCapabilities.title` capability.
6966    ///
6967    /// The session does not need to be active on the connection. The agent stores the
6968    /// title and returns the stored title, which may be normalized.
6969    SetSessionTitleRequest(SetSessionTitleRequest),
6970    /// Resumes an existing session without returning previous messages.
6971    ///
6972    /// This method is only available if the agent advertises the `sessionCapabilities.resume` capability.
6973    ///
6974    /// The agent should resume the session context, allowing the conversation to continue
6975    /// without replaying the message history (unlike `session/load`).
6976    ResumeSessionRequest(ResumeSessionRequest),
6977    /// Closes an active session and frees up any resources associated with it.
6978    ///
6979    /// This method is only available if the agent advertises the `sessionCapabilities.close` capability.
6980    ///
6981    /// The agent must cancel any ongoing work (as if `session/cancel` was called)
6982    /// and then free up any resources associated with the session.
6983    CloseSessionRequest(CloseSessionRequest),
6984    /// Sets the current mode for a session.
6985    ///
6986    /// Allows switching between different agent modes (e.g., "ask", "architect", "code")
6987    /// that affect system prompts, tool availability, and permission behaviors.
6988    ///
6989    /// The mode must be one of the modes advertised in `availableModes` during session
6990    /// creation or loading. Agents may also change modes autonomously and notify the
6991    /// client via `current_mode_update` notifications.
6992    ///
6993    /// This method can be called at any time during a session, whether the Agent is
6994    /// idle or actively generating a response.
6995    ///
6996    /// See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/v1/session-modes)
6997    SetSessionModeRequest(SetSessionModeRequest),
6998    /// Sets the current value for a session configuration option.
6999    SetSessionConfigOptionRequest(SetSessionConfigOptionRequest),
7000    /// Processes a user prompt within a session.
7001    ///
7002    /// This method handles the whole lifecycle of a prompt:
7003    /// - Receives user messages with optional context (files, images, etc.)
7004    /// - Processes the prompt using language models
7005    /// - Reports language model content and tool calls to the Clients
7006    /// - Requests permission to run tools
7007    /// - Executes any requested tool calls
7008    /// - Returns when the turn is complete with a stop reason
7009    ///
7010    /// See protocol docs: [Prompt Turn](https://agentclientprotocol.com/protocol/v1/prompt-turn)
7011    PromptRequest(PromptRequest),
7012    /// Handles extension method requests from the client.
7013    ///
7014    /// Extension methods provide a way to add custom functionality while maintaining
7015    /// protocol compatibility.
7016    ///
7017    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
7018    ExtMethodRequest(ExtRequest),
7019}
7020
7021impl ClientRequest {
7022    /// Returns the corresponding method name of the request.
7023    #[must_use]
7024    pub fn method(&self) -> &str {
7025        match self {
7026            Self::InitializeRequest(_) => AGENT_METHOD_NAMES.initialize,
7027            Self::AuthenticateRequest(_) => AGENT_METHOD_NAMES.authenticate,
7028            #[cfg(feature = "unstable_llm_providers")]
7029            Self::ListProvidersRequest(_) => AGENT_METHOD_NAMES.providers_list,
7030            #[cfg(feature = "unstable_llm_providers")]
7031            Self::SetProviderRequest(_) => AGENT_METHOD_NAMES.providers_set,
7032            #[cfg(feature = "unstable_llm_providers")]
7033            Self::DisableProviderRequest(_) => AGENT_METHOD_NAMES.providers_disable,
7034            Self::LogoutRequest(_) => AGENT_METHOD_NAMES.logout,
7035            #[cfg(feature = "unstable_auth_status")]
7036            Self::AuthStatusRequest(_) => AGENT_METHOD_NAMES.auth_status,
7037            Self::NewSessionRequest(_) => AGENT_METHOD_NAMES.session_new,
7038            Self::LoadSessionRequest(_) => AGENT_METHOD_NAMES.session_load,
7039            Self::ListSessionsRequest(_) => AGENT_METHOD_NAMES.session_list,
7040            Self::DeleteSessionRequest(_) => AGENT_METHOD_NAMES.session_delete,
7041            #[cfg(feature = "unstable_session_fork")]
7042            Self::ForkSessionRequest(_) => AGENT_METHOD_NAMES.session_fork,
7043            #[cfg(feature = "unstable_session_archive")]
7044            Self::ArchiveSessionRequest(_) => AGENT_METHOD_NAMES.session_archive,
7045            #[cfg(feature = "unstable_session_archive")]
7046            Self::UnarchiveSessionRequest(_) => AGENT_METHOD_NAMES.session_unarchive,
7047            #[cfg(feature = "unstable_session_status")]
7048            Self::SessionStatusRequest(_) => AGENT_METHOD_NAMES.session_status,
7049            #[cfg(feature = "unstable_session_options")]
7050            Self::SessionOptionsRequest(_) => AGENT_METHOD_NAMES.session_options,
7051            #[cfg(feature = "unstable_session_set_title")]
7052            Self::SetSessionTitleRequest(_) => AGENT_METHOD_NAMES.session_set_title,
7053            Self::ResumeSessionRequest(_) => AGENT_METHOD_NAMES.session_resume,
7054            Self::CloseSessionRequest(_) => AGENT_METHOD_NAMES.session_close,
7055            Self::SetSessionModeRequest(_) => AGENT_METHOD_NAMES.session_set_mode,
7056            Self::SetSessionConfigOptionRequest(_) => AGENT_METHOD_NAMES.session_set_config_option,
7057            Self::PromptRequest(_) => AGENT_METHOD_NAMES.session_prompt,
7058            Self::ExtMethodRequest(ext_request) => &ext_request.method,
7059        }
7060    }
7061}
7062
7063/// All possible responses that an agent can send to a client.
7064///
7065/// This enum is used internally for routing RPC responses. You typically won't need
7066/// to use this directly - the responses are handled automatically by the connection.
7067///
7068/// These are responses to the corresponding `ClientRequest` variants.
7069#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7070#[derive(Clone, Debug, Serialize, Deserialize)]
7071#[serde(untagged)]
7072#[cfg_attr(feature = "schemars", schemars(inline))]
7073#[non_exhaustive]
7074#[allow(clippy::large_enum_variant)]
7075pub enum AgentResponse {
7076    /// Successful result returned for a `initialize` request.
7077    InitializeResponse(InitializeResponse),
7078    /// Successful result returned for a `authenticate` request.
7079    AuthenticateResponse(#[serde(default)] AuthenticateResponse),
7080    /// Successful result returned for a `providers/list` request.
7081    #[cfg(feature = "unstable_llm_providers")]
7082    ListProvidersResponse(ListProvidersResponse),
7083    /// Successful result returned for a `providers/set` request.
7084    #[cfg(feature = "unstable_llm_providers")]
7085    SetProviderResponse(#[serde(default)] SetProviderResponse),
7086    /// Successful result returned for a `providers/disable` request.
7087    #[cfg(feature = "unstable_llm_providers")]
7088    DisableProviderResponse(#[serde(default)] DisableProviderResponse),
7089    /// Successful result returned for a `logout` request.
7090    LogoutResponse(#[serde(default)] LogoutResponse),
7091    /// Successful result returned for an `auth/status` request.
7092    #[cfg(feature = "unstable_auth_status")]
7093    AuthStatusResponse(AuthStatusResponse),
7094    /// Successful result returned for a `session/new` request.
7095    NewSessionResponse(NewSessionResponse),
7096    /// Successful result returned for a `session/load` request.
7097    LoadSessionResponse(#[serde(default)] LoadSessionResponse),
7098    /// Successful result returned for a `session/list` request.
7099    ListSessionsResponse(ListSessionsResponse),
7100    /// Successful result returned for a `session/delete` request.
7101    DeleteSessionResponse(#[serde(default)] DeleteSessionResponse),
7102    /// Successful result returned for a `session/fork` request.
7103    #[cfg(feature = "unstable_session_fork")]
7104    ForkSessionResponse(ForkSessionResponse),
7105    /// Successful result returned for a `session/archive` request.
7106    #[cfg(feature = "unstable_session_archive")]
7107    ArchiveSessionResponse(#[serde(default)] ArchiveSessionResponse),
7108    /// Successful result returned for a `session/unarchive` request.
7109    #[cfg(feature = "unstable_session_archive")]
7110    UnarchiveSessionResponse(#[serde(default)] UnarchiveSessionResponse),
7111    /// Successful result returned for a `session/status` request.
7112    #[cfg(feature = "unstable_session_status")]
7113    SessionStatusResponse(SessionStatusResponse),
7114    /// Successful result returned for a `session/options` request.
7115    #[cfg(feature = "unstable_session_options")]
7116    SessionOptionsResponse(#[serde(default)] SessionOptionsResponse),
7117    /// Successful result returned for a `session/set_title` request.
7118    #[cfg(feature = "unstable_session_set_title")]
7119    SetSessionTitleResponse(SetSessionTitleResponse),
7120    /// Successful result returned for a `session/resume` request.
7121    ResumeSessionResponse(#[serde(default)] ResumeSessionResponse),
7122    /// Successful result returned for a `session/close` request.
7123    CloseSessionResponse(#[serde(default)] CloseSessionResponse),
7124    /// Successful result returned for a `session/set_mode` request.
7125    SetSessionModeResponse(#[serde(default)] SetSessionModeResponse),
7126    /// Successful result returned for a `session/set_config_option` request.
7127    SetSessionConfigOptionResponse(SetSessionConfigOptionResponse),
7128    /// Successful result returned for a `session/prompt` request.
7129    PromptResponse(PromptResponse),
7130    /// Successful result returned by an extension method outside the core ACP method set.
7131    ExtMethodResponse(ExtResponse),
7132}
7133
7134/// All possible notifications that a client can send to an agent.
7135///
7136/// This enum is used internally for routing RPC notifications. You typically won't need
7137/// to use this directly.
7138///
7139/// Notifications do not expect a response.
7140#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7141#[derive(Clone, Debug, Serialize, Deserialize)]
7142#[serde(untagged)]
7143#[cfg_attr(feature = "schemars", schemars(inline))]
7144#[non_exhaustive]
7145#[allow(clippy::large_enum_variant)]
7146pub enum ClientNotification {
7147    /// Cancels ongoing operations for a session.
7148    ///
7149    /// This is a notification sent by the client to cancel an ongoing prompt turn.
7150    ///
7151    /// Upon receiving this notification, the Agent SHOULD:
7152    /// - Stop all language model requests as soon as possible
7153    /// - Abort all tool call invocations in progress
7154    /// - Send any pending `session/update` notifications
7155    /// - Respond to the original `session/prompt` request with the `cancelled` stop reason
7156    ///
7157    /// See protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/v1/prompt-turn#cancellation)
7158    CancelNotification(CancelNotification),
7159    /// **UNSTABLE**
7160    ///
7161    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7162    ///
7163    /// Sends an MCP-over-ACP notification.
7164    #[cfg(feature = "unstable_mcp_over_acp")]
7165    MessageMcpNotification(MessageMcpNotification),
7166    /// Handles extension notifications from the client.
7167    ///
7168    /// Extension notifications provide a way to send one-way messages for custom functionality
7169    /// while maintaining protocol compatibility.
7170    ///
7171    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
7172    ExtNotification(ExtNotification),
7173}
7174
7175impl ClientNotification {
7176    /// Returns the corresponding method name of the notification.
7177    #[must_use]
7178    pub fn method(&self) -> &str {
7179        match self {
7180            Self::CancelNotification(_) => AGENT_METHOD_NAMES.session_cancel,
7181            #[cfg(feature = "unstable_mcp_over_acp")]
7182            Self::MessageMcpNotification(_) => AGENT_METHOD_NAMES.mcp_message,
7183            Self::ExtNotification(ext_notification) => &ext_notification.method,
7184        }
7185    }
7186}
7187
7188/// Notification to cancel ongoing operations for a session.
7189///
7190/// See protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/v1/prompt-turn#cancellation)
7191#[serde_as]
7192#[skip_serializing_none]
7193#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7194#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7195#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CANCEL_METHOD_NAME)))]
7196#[serde(rename_all = "camelCase")]
7197#[non_exhaustive]
7198pub struct CancelNotification {
7199    /// The ID of the session to cancel operations for.
7200    pub session_id: SessionId,
7201    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7202    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
7203    /// these keys.
7204    ///
7205    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
7206    #[serde_as(deserialize_as = "DefaultOnError")]
7207    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7208    #[serde(default)]
7209    #[serde(rename = "_meta")]
7210    pub meta: Option<Meta>,
7211}
7212
7213impl CancelNotification {
7214    /// Builds [`CancelNotification`] with the required notification fields set. Optional fields start unset or empty.
7215    #[must_use]
7216    pub fn new(session_id: impl Into<SessionId>) -> Self {
7217        Self {
7218            session_id: session_id.into(),
7219            meta: None,
7220        }
7221    }
7222
7223    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7224    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
7225    /// these keys.
7226    ///
7227    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
7228    #[must_use]
7229    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7230        self.meta = meta.into_option();
7231        self
7232    }
7233}
7234
7235#[cfg(test)]
7236mod test_serialization {
7237    use super::*;
7238    use serde_json::json;
7239
7240    fn test_meta() -> Meta {
7241        json!({ "source": "test" }).as_object().unwrap().clone()
7242    }
7243
7244    fn serialized_meta_key_count(value: &impl serde::Serialize) -> usize {
7245        serde_json::to_string(value)
7246            .unwrap()
7247            .matches("\"_meta\"")
7248            .count()
7249    }
7250
7251    /// v1 reports prompt failures as JSON-RPC errors. Only the unstable subagent
7252    /// snapshot has an `error` stop reason, because a child has no prompt response.
7253    #[test]
7254    fn prompt_response_has_no_error_stop_reason() {
7255        assert_eq!(
7256            serde_json::from_value::<PromptResponse>(json!({ "stopReason": "end_turn" }))
7257                .unwrap()
7258                .stop_reason,
7259            StopReason::EndTurn
7260        );
7261        assert!(
7262            serde_json::from_value::<PromptResponse>(json!({ "stopReason": "error" })).is_err()
7263        );
7264    }
7265
7266    #[test]
7267    fn test_initialize_capabilities_default_on_malformed_values() {
7268        let request: InitializeRequest = serde_json::from_value(json!({
7269            "protocolVersion": 1,
7270            "clientCapabilities": false
7271        }))
7272        .unwrap();
7273        assert_eq!(request.client_capabilities, ClientCapabilities::default());
7274
7275        let response: InitializeResponse = serde_json::from_value(json!({
7276            "protocolVersion": 1,
7277            "agentCapabilities": false
7278        }))
7279        .unwrap();
7280        assert_eq!(response.agent_capabilities, AgentCapabilities::default());
7281    }
7282
7283    #[test]
7284    fn test_agent_capabilities_default_on_malformed_values() {
7285        let capabilities: AgentCapabilities = serde_json::from_value(json!({
7286            "loadSession": "yes",
7287            "promptCapabilities": {
7288                "image": "yes",
7289                "audio": true,
7290                "embeddedContext": {}
7291            },
7292            "mcpCapabilities": {
7293                "http": "yes",
7294                "sse": true
7295            },
7296            "sessionCapabilities": false,
7297            "auth": false
7298        }))
7299        .unwrap();
7300
7301        assert!(!capabilities.load_session);
7302        assert!(!capabilities.prompt_capabilities.image);
7303        assert!(capabilities.prompt_capabilities.audio);
7304        assert!(!capabilities.prompt_capabilities.embedded_context);
7305        assert!(!capabilities.mcp_capabilities.http);
7306        assert!(capabilities.mcp_capabilities.sse);
7307        assert_eq!(
7308            capabilities.session_capabilities,
7309            SessionCapabilities::default()
7310        );
7311        assert_eq!(capabilities.auth, AgentAuthCapabilities::default());
7312    }
7313
7314    #[test]
7315    fn test_mcp_server_stdio_serialization() {
7316        let server = McpServer::Stdio(
7317            McpServerStdio::new("test-server", "/usr/bin/server")
7318                .args(vec!["--port".to_string(), "3000".to_string()])
7319                .env(vec![EnvVariable::new("API_KEY", "secret123")]),
7320        );
7321
7322        let json = serde_json::to_value(&server).unwrap();
7323        assert_eq!(
7324            json,
7325            json!({
7326                "name": "test-server",
7327                "command": "/usr/bin/server",
7328                "args": ["--port", "3000"],
7329                "env": [
7330                    {
7331                        "name": "API_KEY",
7332                        "value": "secret123"
7333                    }
7334                ]
7335            })
7336        );
7337
7338        let deserialized: McpServer = serde_json::from_value(json).unwrap();
7339        match deserialized {
7340            McpServer::Stdio(McpServerStdio {
7341                name,
7342                command,
7343                args,
7344                env,
7345                meta: _,
7346            }) => {
7347                assert_eq!(name, "test-server");
7348                assert_eq!(command, PathBuf::from("/usr/bin/server"));
7349                assert_eq!(args, vec!["--port", "3000"]);
7350                assert_eq!(env.len(), 1);
7351                assert_eq!(env[0].name, "API_KEY");
7352                assert_eq!(env[0].value, "secret123");
7353            }
7354            _ => panic!("Expected Stdio variant"),
7355        }
7356    }
7357
7358    #[test]
7359    fn test_mcp_server_http_serialization() {
7360        let server = McpServer::Http(
7361            McpServerHttp::new("http-server", "https://api.example.com").headers(vec![
7362                HttpHeader::new("Authorization", "Bearer token123"),
7363                HttpHeader::new("Content-Type", "application/json"),
7364            ]),
7365        );
7366
7367        let json = serde_json::to_value(&server).unwrap();
7368        assert_eq!(
7369            json,
7370            json!({
7371                "type": "http",
7372                "name": "http-server",
7373                "url": "https://api.example.com",
7374                "headers": [
7375                    {
7376                        "name": "Authorization",
7377                        "value": "Bearer token123"
7378                    },
7379                    {
7380                        "name": "Content-Type",
7381                        "value": "application/json"
7382                    }
7383                ]
7384            })
7385        );
7386
7387        let deserialized: McpServer = serde_json::from_value(json).unwrap();
7388        match deserialized {
7389            McpServer::Http(McpServerHttp {
7390                name,
7391                url,
7392                headers,
7393                meta: _,
7394            }) => {
7395                assert_eq!(name, "http-server");
7396                assert_eq!(url, "https://api.example.com");
7397                assert_eq!(headers.len(), 2);
7398                assert_eq!(headers[0].name, "Authorization");
7399                assert_eq!(headers[0].value, "Bearer token123");
7400                assert_eq!(headers[1].name, "Content-Type");
7401                assert_eq!(headers[1].value, "application/json");
7402            }
7403            _ => panic!("Expected Http variant"),
7404        }
7405    }
7406
7407    #[cfg(feature = "unstable_mcp_over_acp")]
7408    #[test]
7409    fn test_mcp_server_acp_serialization() {
7410        let server = McpServer::Acp(McpServerAcp::new("project-tools", "project-tools-id"));
7411
7412        let json = serde_json::to_value(&server).unwrap();
7413        assert_eq!(
7414            json,
7415            json!({
7416                "type": "acp",
7417                "name": "project-tools",
7418                "serverId": "project-tools-id"
7419            })
7420        );
7421
7422        let deserialized: McpServer = serde_json::from_value(json).unwrap();
7423        match deserialized {
7424            McpServer::Acp(McpServerAcp {
7425                name,
7426                server_id: id,
7427                meta: _,
7428            }) => {
7429                assert_eq!(name, "project-tools");
7430                assert_eq!(id, McpServerAcpId::new("project-tools-id"));
7431            }
7432            _ => panic!("Expected Acp variant"),
7433        }
7434    }
7435
7436    #[cfg(feature = "unstable_mcp_over_acp")]
7437    #[test]
7438    fn test_client_mcp_message_method_names() {
7439        use serde_json::json;
7440
7441        assert_eq!(AGENT_METHOD_NAMES.mcp_message, "mcp/message");
7442
7443        let notification =
7444            MessageMcpNotification::new("server-1", "req-1", "notifications/progress");
7445        assert_eq!(
7446            ClientNotification::MessageMcpNotification(notification.clone()).method(),
7447            "mcp/message"
7448        );
7449        assert_eq!(
7450            serde_json::to_value(notification).unwrap(),
7451            json!({
7452                "serverId": "server-1",
7453                "requestId": "req-1",
7454                "method": "notifications/progress"
7455            })
7456        );
7457        let notification: MessageMcpNotification = serde_json::from_value(json!({
7458            "serverId": "server-1", "requestId": "req-1", "method": "notifications/progress",
7459            "params": null, "_meta": null
7460        }))
7461        .unwrap();
7462        assert_eq!(notification.params, None);
7463        assert_eq!(notification.meta, None);
7464        for key in ["serverId", "requestId", "method"] {
7465            let mut value = json!({"serverId":"server-1", "requestId":"req-1", "method":"notifications/progress"});
7466            value.as_object_mut().unwrap().remove(key);
7467            assert!(serde_json::from_value::<MessageMcpNotification>(value).is_err());
7468        }
7469    }
7470
7471    #[cfg(all(feature = "unstable_mcp_over_acp", feature = "schemars"))]
7472    #[test]
7473    fn test_mcp_server_acp_schema() {
7474        let mcp_server_schema = serde_json::to_value(schemars::schema_for!(McpServer)).unwrap();
7475        assert!(json_contains_entry(
7476            &mcp_server_schema,
7477            "const",
7478            &json!("acp")
7479        ));
7480        assert!(json_contains_entry(
7481            &mcp_server_schema,
7482            "$ref",
7483            &json!("#/$defs/McpServerAcp")
7484        ));
7485
7486        let capabilities_schema =
7487            serde_json::to_value(schemars::schema_for!(McpCapabilities)).unwrap();
7488        assert!(json_contains_key(&capabilities_schema, "acp"));
7489    }
7490
7491    #[cfg(all(feature = "unstable_mcp_over_acp", feature = "schemars"))]
7492    fn json_contains_entry(
7493        value: &serde_json::Value,
7494        key: &str,
7495        expected: &serde_json::Value,
7496    ) -> bool {
7497        match value {
7498            serde_json::Value::Object(map) => {
7499                map.get(key) == Some(expected)
7500                    || map
7501                        .values()
7502                        .any(|value| json_contains_entry(value, key, expected))
7503            }
7504            serde_json::Value::Array(values) => values
7505                .iter()
7506                .any(|value| json_contains_entry(value, key, expected)),
7507            _ => false,
7508        }
7509    }
7510
7511    #[cfg(all(feature = "unstable_mcp_over_acp", feature = "schemars"))]
7512    fn json_contains_key(value: &serde_json::Value, key: &str) -> bool {
7513        match value {
7514            serde_json::Value::Object(map) => {
7515                map.contains_key(key) || map.values().any(|value| json_contains_key(value, key))
7516            }
7517            serde_json::Value::Array(values) => {
7518                values.iter().any(|value| json_contains_key(value, key))
7519            }
7520            _ => false,
7521        }
7522    }
7523
7524    #[test]
7525    fn test_mcp_server_sse_serialization() {
7526        let server = McpServer::Sse(
7527            McpServerSse::new("sse-server", "https://sse.example.com/events")
7528                .headers(vec![HttpHeader::new("X-API-Key", "apikey456")]),
7529        );
7530
7531        let json = serde_json::to_value(&server).unwrap();
7532        assert_eq!(
7533            json,
7534            json!({
7535                "type": "sse",
7536                "name": "sse-server",
7537                "url": "https://sse.example.com/events",
7538                "headers": [
7539                    {
7540                        "name": "X-API-Key",
7541                        "value": "apikey456"
7542                    }
7543                ]
7544            })
7545        );
7546
7547        let deserialized: McpServer = serde_json::from_value(json).unwrap();
7548        match deserialized {
7549            McpServer::Sse(McpServerSse {
7550                name,
7551                url,
7552                headers,
7553                meta: _,
7554            }) => {
7555                assert_eq!(name, "sse-server");
7556                assert_eq!(url, "https://sse.example.com/events");
7557                assert_eq!(headers.len(), 1);
7558                assert_eq!(headers[0].name, "X-API-Key");
7559                assert_eq!(headers[0].value, "apikey456");
7560            }
7561            _ => panic!("Expected Sse variant"),
7562        }
7563    }
7564
7565    #[test]
7566    fn test_session_config_option_category_known_variants() {
7567        // Test serialization of known variants
7568        assert_eq!(
7569            serde_json::to_value(&SessionConfigOptionCategory::Mode).unwrap(),
7570            json!("mode")
7571        );
7572        assert_eq!(
7573            serde_json::to_value(&SessionConfigOptionCategory::Model).unwrap(),
7574            json!("model")
7575        );
7576        assert_eq!(
7577            serde_json::to_value(&SessionConfigOptionCategory::ModelConfig).unwrap(),
7578            json!("model_config")
7579        );
7580        assert_eq!(
7581            serde_json::to_value(&SessionConfigOptionCategory::ThoughtLevel).unwrap(),
7582            json!("thought_level")
7583        );
7584
7585        // Test deserialization of known variants
7586        assert_eq!(
7587            serde_json::from_str::<SessionConfigOptionCategory>("\"mode\"").unwrap(),
7588            SessionConfigOptionCategory::Mode
7589        );
7590        assert_eq!(
7591            serde_json::from_str::<SessionConfigOptionCategory>("\"model\"").unwrap(),
7592            SessionConfigOptionCategory::Model
7593        );
7594        assert_eq!(
7595            serde_json::from_str::<SessionConfigOptionCategory>("\"model_config\"").unwrap(),
7596            SessionConfigOptionCategory::ModelConfig
7597        );
7598        assert_eq!(
7599            serde_json::from_str::<SessionConfigOptionCategory>("\"thought_level\"").unwrap(),
7600            SessionConfigOptionCategory::ThoughtLevel
7601        );
7602    }
7603
7604    #[test]
7605    fn test_session_config_option_category_unknown_variants() {
7606        // Test that unknown strings are captured in Other variant
7607        let unknown: SessionConfigOptionCategory =
7608            serde_json::from_str("\"some_future_category\"").unwrap();
7609        assert_eq!(
7610            unknown,
7611            SessionConfigOptionCategory::Other("some_future_category".to_string())
7612        );
7613
7614        // Test round-trip of unknown category
7615        let json = serde_json::to_value(&unknown).unwrap();
7616        assert_eq!(json, json!("some_future_category"));
7617    }
7618
7619    #[test]
7620    fn test_session_config_option_category_custom_categories() {
7621        // Category names beginning with `_` are free for custom use
7622        let custom: SessionConfigOptionCategory =
7623            serde_json::from_str("\"_my_custom_category\"").unwrap();
7624        assert_eq!(
7625            custom,
7626            SessionConfigOptionCategory::Other("_my_custom_category".to_string())
7627        );
7628
7629        // Test round-trip preserves the custom category name
7630        let json = serde_json::to_value(&custom).unwrap();
7631        assert_eq!(json, json!("_my_custom_category"));
7632
7633        // Deserialize back and verify
7634        let deserialized: SessionConfigOptionCategory = serde_json::from_value(json).unwrap();
7635        assert_eq!(
7636            deserialized,
7637            SessionConfigOptionCategory::Other("_my_custom_category".to_string()),
7638        );
7639    }
7640
7641    #[test]
7642    fn test_auth_method_agent_serialization() {
7643        let method = AuthMethod::Agent(AuthMethodAgent::new("default-auth", "Default Auth"));
7644
7645        let json = serde_json::to_value(&method).unwrap();
7646        assert_eq!(
7647            json,
7648            json!({
7649                "id": "default-auth",
7650                "name": "Default Auth"
7651            })
7652        );
7653        // description should be omitted when None
7654        assert!(!json.as_object().unwrap().contains_key("description"));
7655        // Agent variant should not emit a `type` field (backward compat)
7656        assert!(!json.as_object().unwrap().contains_key("type"));
7657
7658        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
7659        match deserialized {
7660            AuthMethod::Agent(AuthMethodAgent { id, name, .. }) => {
7661                assert_eq!(id.0.as_ref(), "default-auth");
7662                assert_eq!(name, "Default Auth");
7663            }
7664            _ => panic!("Expected Agent variant"),
7665        }
7666    }
7667
7668    #[test]
7669    fn test_auth_method_explicit_agent_deserialization() {
7670        // An explicit `"type": "agent"` should also deserialize to Agent
7671        let json = json!({
7672            "id": "agent-auth",
7673            "name": "Agent Auth",
7674            "type": "agent"
7675        });
7676
7677        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
7678        assert!(matches!(deserialized, AuthMethod::Agent(_)));
7679    }
7680
7681    #[test]
7682    fn test_session_delete_serialization() {
7683        assert_eq!(AGENT_METHOD_NAMES.session_delete, "session/delete");
7684        assert_eq!(
7685            ClientRequest::DeleteSessionRequest(DeleteSessionRequest::new("sess_abc123")).method(),
7686            "session/delete"
7687        );
7688        assert_eq!(
7689            serde_json::to_value(DeleteSessionRequest::new("sess_abc123")).unwrap(),
7690            json!({
7691                "sessionId": "sess_abc123"
7692            })
7693        );
7694        assert_eq!(
7695            serde_json::to_value(DeleteSessionResponse::new()).unwrap(),
7696            json!({})
7697        );
7698        assert_eq!(
7699            serde_json::to_value(
7700                SessionCapabilities::new().delete(SessionDeleteCapabilities::new())
7701            )
7702            .unwrap(),
7703            json!({
7704                "delete": {}
7705            })
7706        );
7707    }
7708    #[cfg(feature = "unstable_session_set_title")]
7709    #[test]
7710    fn test_session_set_title_serialization() {
7711        assert_eq!(AGENT_METHOD_NAMES.session_set_title, "session/set_title");
7712        assert_eq!(
7713            ClientRequest::SetSessionTitleRequest(SetSessionTitleRequest::new(
7714                "sess_abc123",
7715                "Investigate OAuth timeout"
7716            ))
7717            .method(),
7718            "session/set_title"
7719        );
7720        assert_eq!(
7721            serde_json::to_value(SetSessionTitleRequest::new(
7722                "sess_abc123",
7723                "Investigate OAuth timeout"
7724            ))
7725            .unwrap(),
7726            json!({
7727                "sessionId": "sess_abc123",
7728                "title": "Investigate OAuth timeout"
7729            })
7730        );
7731        assert_eq!(
7732            serde_json::to_value(SetSessionTitleResponse::new("Investigate OAuth timeout"))
7733                .unwrap(),
7734            json!({
7735                "title": "Investigate OAuth timeout"
7736            })
7737        );
7738        assert_eq!(
7739            serde_json::to_value(SessionCapabilities::new().title(SessionTitleCapabilities::new()))
7740                .unwrap(),
7741            json!({
7742                "title": {}
7743            })
7744        );
7745    }
7746
7747    #[cfg(feature = "unstable_session_set_title")]
7748    #[test]
7749    fn test_session_set_title_requires_title() {
7750        for params in [
7751            json!({"sessionId": "sess_abc123"}),
7752            json!({"sessionId": "sess_abc123", "title": null}),
7753            json!({"sessionId": "sess_abc123", "title": 42}),
7754        ] {
7755            assert!(serde_json::from_value::<SetSessionTitleRequest>(params).is_err());
7756        }
7757        for result in [json!({}), json!({"title": null})] {
7758            assert!(serde_json::from_value::<SetSessionTitleResponse>(result).is_err());
7759        }
7760    }
7761
7762    #[cfg(feature = "unstable_session_options")]
7763    #[test]
7764    fn test_session_options_serialization() {
7765        assert_eq!(AGENT_METHOD_NAMES.session_options, "session/options");
7766        assert_eq!(
7767            ClientRequest::SessionOptionsRequest(SessionOptionsRequest::new("/home/user/project"))
7768                .method(),
7769            "session/options"
7770        );
7771        assert_eq!(
7772            serde_json::to_value(
7773                SessionOptionsRequest::new("/home/user/project")
7774                    .session_id(SessionId::new("sess_abc123"))
7775            )
7776            .unwrap(),
7777            json!({"cwd": "/home/user/project", "sessionId": "sess_abc123"})
7778        );
7779        assert_eq!(
7780            serde_json::from_value::<SessionOptionsRequest>(
7781                json!({"cwd": "/home/user/project", "additionalDirectories": null, "sessionId": null})
7782            )
7783            .unwrap(),
7784            SessionOptionsRequest::new("/home/user/project")
7785        );
7786        let request = NewSessionRequest::new("/home/user/project").config_options(vec![
7787            InitialSessionConfigOption::new("model", SessionConfigOptionValue::value_id("model-2")),
7788            InitialSessionConfigOption::new("fast", SessionConfigOptionValue::boolean(true)),
7789        ]);
7790        let value = serde_json::to_value(&request).unwrap();
7791        assert_eq!(
7792            value["configOptions"],
7793            json!([
7794                {"configId": "model", "value": "model-2"},
7795                {"configId": "fast", "type": "boolean", "value": true}
7796            ])
7797        );
7798        assert_eq!(
7799            serde_json::from_value::<NewSessionRequest>(value).unwrap(),
7800            request
7801        );
7802        assert!(
7803            serde_json::from_value::<NewSessionRequest>(json!({
7804                "cwd": "/home/user/project",
7805                "mcpServers": [],
7806                "configOptions": [{"type": "boolean", "value": true}]
7807            }))
7808            .is_err()
7809        );
7810        assert_eq!(
7811            serde_json::to_value(SessionOptionsResponse::new()).unwrap(),
7812            json!({})
7813        );
7814        assert_eq!(
7815            serde_json::to_value(
7816                SessionCapabilities::new().options(SessionOptionsCapabilities::new())
7817            )
7818            .unwrap(),
7819            json!({"options": {}})
7820        );
7821    }
7822
7823    #[cfg(feature = "unstable_session_status")]
7824    #[test]
7825    fn test_session_status_serialization() {
7826        assert_eq!(AGENT_METHOD_NAMES.session_status, "session/status");
7827        assert_eq!(
7828            ClientRequest::SessionStatusRequest(SessionStatusRequest::new("sess_abc123")).method(),
7829            "session/status"
7830        );
7831        assert_eq!(
7832            serde_json::to_value(SessionStatusRequest::new("sess_abc123")).unwrap(),
7833            json!({"sessionId": "sess_abc123"})
7834        );
7835        assert_eq!(
7836            serde_json::to_value(SessionStatusResponse::new(SessionStatus::Saved)).unwrap(),
7837            json!({"status": "saved"})
7838        );
7839        assert_eq!(
7840            serde_json::to_value(
7841                SessionCapabilities::new().status(SessionStatusCapabilities::new())
7842            )
7843            .unwrap(),
7844            json!({"status": {}})
7845        );
7846    }
7847
7848    #[cfg(feature = "unstable_session_status")]
7849    #[test]
7850    fn test_session_status_is_strict_and_open() {
7851        let custom =
7852            serde_json::from_value::<SessionStatusResponse>(json!({"status": "_suspended"}))
7853                .unwrap();
7854        assert_eq!(
7855            custom.status,
7856            SessionStatus::Other("_suspended".to_string())
7857        );
7858        assert_eq!(
7859            serde_json::to_value(&custom).unwrap(),
7860            json!({"status": "_suspended"})
7861        );
7862        for result in [json!({}), json!({"status": null}), json!({"status": 1})] {
7863            assert!(serde_json::from_value::<SessionStatusResponse>(result).is_err());
7864        }
7865        for params in [json!({}), json!({"sessionId": null})] {
7866            assert!(serde_json::from_value::<SessionStatusRequest>(params).is_err());
7867        }
7868    }
7869
7870    #[cfg(feature = "unstable_session_archive")]
7871    #[test]
7872    fn test_session_archive_serialization() {
7873        assert_eq!(AGENT_METHOD_NAMES.session_archive, "session/archive");
7874        assert_eq!(AGENT_METHOD_NAMES.session_unarchive, "session/unarchive");
7875        assert_eq!(
7876            ClientRequest::ArchiveSessionRequest(ArchiveSessionRequest::new("sess_abc123"))
7877                .method(),
7878            "session/archive"
7879        );
7880        assert_eq!(
7881            ClientRequest::UnarchiveSessionRequest(UnarchiveSessionRequest::new("sess_abc123"))
7882                .method(),
7883            "session/unarchive"
7884        );
7885        assert_eq!(
7886            serde_json::to_value(ArchiveSessionRequest::new("sess_abc123")).unwrap(),
7887            json!({"sessionId": "sess_abc123"})
7888        );
7889        assert_eq!(
7890            serde_json::to_value(UnarchiveSessionResponse::new()).unwrap(),
7891            json!({})
7892        );
7893        assert_eq!(
7894            serde_json::to_value(
7895                SessionCapabilities::new().archive(SessionArchiveCapabilities::new())
7896            )
7897            .unwrap(),
7898            json!({"archive": {}})
7899        );
7900        assert_eq!(
7901            serde_json::to_value(
7902                ListSessionsRequest::new()
7903                    .cwd("/home/user/project")
7904                    .archived(SessionArchiveFilter::Only)
7905            )
7906            .unwrap(),
7907            json!({"cwd": "/home/user/project", "archived": "only"})
7908        );
7909        assert_eq!(
7910            serde_json::to_value(
7911                SessionInfo::new("sess_abc123", "/home/user/project").archived(true)
7912            )
7913            .unwrap(),
7914            json!({"sessionId": "sess_abc123", "cwd": "/home/user/project", "archived": true})
7915        );
7916    }
7917
7918    #[cfg(feature = "unstable_session_archive")]
7919    #[test]
7920    fn test_session_archive_filter_is_strict_and_open() {
7921        for (value, expected) in [
7922            (json!(null), None),
7923            (json!("include"), Some(SessionArchiveFilter::Include)),
7924            (
7925                json!("_recent"),
7926                Some(SessionArchiveFilter::Other("_recent".to_string())),
7927            ),
7928        ] {
7929            let request =
7930                serde_json::from_value::<ListSessionsRequest>(json!({"archived": value})).unwrap();
7931            assert_eq!(request.archived, expected);
7932        }
7933        for value in [json!(true), json!(1), json!({})] {
7934            assert!(
7935                serde_json::from_value::<ListSessionsRequest>(json!({"archived": value})).is_err()
7936            );
7937        }
7938        let info = serde_json::from_value::<SessionInfo>(
7939            json!({"sessionId": "sess_abc123", "cwd": "/home/user/project", "archived": "yes"}),
7940        )
7941        .unwrap();
7942        assert_eq!(info.archived, None);
7943    }
7944
7945    #[test]
7946    fn test_session_additional_directories_serialization() {
7947        assert_eq!(
7948            serde_json::to_value(NewSessionRequest::new("/home/user/project")).unwrap(),
7949            json!({
7950                "cwd": "/home/user/project",
7951                "mcpServers": []
7952            })
7953        );
7954        assert_eq!(
7955            serde_json::to_value(
7956                NewSessionRequest::new("/home/user/project").additional_directories(vec![
7957                    PathBuf::from("/home/user/shared-lib"),
7958                    PathBuf::from("/home/user/product-docs"),
7959                ])
7960            )
7961            .unwrap(),
7962            json!({
7963                "cwd": "/home/user/project",
7964                "additionalDirectories": [
7965                    "/home/user/shared-lib",
7966                    "/home/user/product-docs"
7967                ],
7968                "mcpServers": []
7969            })
7970        );
7971        assert_eq!(
7972            serde_json::to_value(SessionInfo::new("sess_abc123", "/home/user/project")).unwrap(),
7973            json!({
7974                "sessionId": "sess_abc123",
7975                "cwd": "/home/user/project"
7976            })
7977        );
7978        assert_eq!(
7979            serde_json::to_value(
7980                SessionInfo::new("sess_abc123", "/home/user/project").additional_directories(vec![
7981                    PathBuf::from("/home/user/shared-lib"),
7982                    PathBuf::from("/home/user/product-docs"),
7983                ])
7984            )
7985            .unwrap(),
7986            json!({
7987                "sessionId": "sess_abc123",
7988                "cwd": "/home/user/project",
7989                "additionalDirectories": [
7990                    "/home/user/shared-lib",
7991                    "/home/user/product-docs"
7992                ]
7993            })
7994        );
7995        assert_eq!(
7996            serde_json::from_value::<SessionInfo>(json!({
7997                "sessionId": "sess_abc123",
7998                "cwd": "/home/user/project"
7999            }))
8000            .unwrap()
8001            .additional_directories,
8002            Vec::<PathBuf>::new()
8003        );
8004    }
8005    #[test]
8006    fn test_session_additional_directories_capabilities_serialization() {
8007        assert_eq!(
8008            serde_json::to_value(
8009                SessionCapabilities::new()
8010                    .additional_directories(SessionAdditionalDirectoriesCapabilities::new())
8011            )
8012            .unwrap(),
8013            json!({
8014                "additionalDirectories": {}
8015            })
8016        );
8017    }
8018
8019    #[test]
8020    fn test_session_system_prompt_capabilities_serialization() {
8021        assert_eq!(
8022            serde_json::to_value(
8023                SessionCapabilities::new().system_prompt(SessionSystemPromptCapabilities::new())
8024            )
8025            .unwrap(),
8026            json!({ "systemPrompt": {} })
8027        );
8028        assert_eq!(
8029            serde_json::to_value(
8030                SessionCapabilities::new().system_prompt(
8031                    SessionSystemPromptCapabilities::new().mode(
8032                        SessionSystemPromptModeCapabilities::new()
8033                            .override_(SessionSystemPromptOverrideCapabilities::new())
8034                    )
8035                )
8036            )
8037            .unwrap(),
8038            json!({ "systemPrompt": { "mode": { "override": {} } } })
8039        );
8040        assert_eq!(
8041            serde_json::from_value::<SessionCapabilities>(
8042                json!({ "systemPrompt": { "mode": { "override": {} } } })
8043            )
8044            .unwrap()
8045            .system_prompt
8046            .and_then(|capabilities| capabilities.mode)
8047            .and_then(|mode| mode.override_),
8048            Some(SessionSystemPromptOverrideCapabilities::new())
8049        );
8050
8051        // Capabilities fall back to "not advertised" when malformed.
8052        assert_eq!(
8053            serde_json::from_value::<SessionCapabilities>(json!({ "systemPrompt": "yes" }))
8054                .unwrap()
8055                .system_prompt,
8056            None
8057        );
8058        assert_eq!(
8059            serde_json::from_value::<SessionCapabilities>(
8060                json!({ "systemPrompt": { "mode": { "override": true } } })
8061            )
8062            .unwrap()
8063            .system_prompt,
8064            Some(
8065                SessionSystemPromptCapabilities::new()
8066                    .mode(SessionSystemPromptModeCapabilities::new())
8067            )
8068        );
8069        assert_eq!(
8070            serde_json::from_value::<SessionCapabilities>(
8071                json!({ "systemPrompt": { "mode": "override" } })
8072            )
8073            .unwrap()
8074            .system_prompt,
8075            Some(SessionSystemPromptCapabilities::new())
8076        );
8077    }
8078
8079    #[test]
8080    fn test_system_prompt_lifecycle_request_serialization() {
8081        let system_prompt = SystemPrompt::new(vec![ContentBlock::from(
8082            "You are a code review specialist.",
8083        )]);
8084        let system_prompt_json = json!({
8085            "mode": "append",
8086            "content": [{ "type": "text", "text": "You are a code review specialist." }]
8087        });
8088
8089        let request =
8090            NewSessionRequest::new("/home/user/project").system_prompt(system_prompt.clone());
8091        let request_json = json!({
8092            "cwd": "/home/user/project",
8093            "mcpServers": [],
8094            "systemPrompt": system_prompt_json
8095        });
8096        assert_eq!(serde_json::to_value(&request).unwrap(), request_json);
8097        assert_eq!(
8098            serde_json::from_value::<NewSessionRequest>(request_json).unwrap(),
8099            request
8100        );
8101
8102        assert_eq!(
8103            serde_json::to_value(
8104                LoadSessionRequest::new("sess_abc123", "/home/user/project")
8105                    .system_prompt(system_prompt.clone())
8106            )
8107            .unwrap()["systemPrompt"],
8108            system_prompt_json
8109        );
8110        assert_eq!(
8111            serde_json::to_value(
8112                ResumeSessionRequest::new("sess_abc123", "/home/user/project")
8113                    .system_prompt(system_prompt.clone())
8114            )
8115            .unwrap()["systemPrompt"],
8116            system_prompt_json
8117        );
8118        #[cfg(feature = "unstable_session_fork")]
8119        assert_eq!(
8120            serde_json::to_value(
8121                ForkSessionRequest::new("sess_abc123", "/home/user/project")
8122                    .system_prompt(system_prompt.clone())
8123            )
8124            .unwrap()["systemPrompt"],
8125            system_prompt_json
8126        );
8127
8128        let override_prompt =
8129            SystemPrompt::new(vec![ContentBlock::from("...")]).mode(SystemPromptMode::Override);
8130        let override_json = json!({
8131            "mode": "override",
8132            "content": [{ "type": "text", "text": "..." }]
8133        });
8134        assert_eq!(
8135            serde_json::to_value(&override_prompt).unwrap(),
8136            override_json
8137        );
8138        assert_eq!(
8139            serde_json::from_value::<SystemPrompt>(override_json).unwrap(),
8140            override_prompt
8141        );
8142    }
8143
8144    /// `SystemPrompt::new` defaults to `append` in Rust, but `mode` is required on
8145    /// the wire, so it is always serialized.
8146    #[test]
8147    fn test_system_prompt_new_defaults_to_append() {
8148        let system_prompt = SystemPrompt::new(vec![ContentBlock::from("...")]);
8149        assert_eq!(system_prompt.mode, SystemPromptMode::Append);
8150        assert_eq!(
8151            serde_json::to_value(&system_prompt).unwrap(),
8152            json!({ "mode": "append", "content": [{ "type": "text", "text": "..." }] })
8153        );
8154    }
8155
8156    /// Unknown modes follow the enum variant extension rule: they parse as
8157    /// `SystemPromptMode::Other` so they are not dropped, and an agent that does
8158    /// not support them must reject the request.
8159    #[test]
8160    fn test_system_prompt_preserves_unknown_modes() {
8161        for mode in ["_vendor_mode", "prepend"] {
8162            let system_prompt_json =
8163                json!({ "mode": mode, "content": [{ "type": "text", "text": "..." }] });
8164            let system_prompt: SystemPrompt =
8165                serde_json::from_value(system_prompt_json.clone()).unwrap();
8166            assert_eq!(
8167                system_prompt.mode,
8168                SystemPromptMode::Other(mode.to_string())
8169            );
8170            assert_eq!(
8171                serde_json::to_value(&system_prompt).unwrap(),
8172                system_prompt_json
8173            );
8174        }
8175    }
8176
8177    /// The receiver acts on `systemPrompt`, so malformed values fail the request
8178    /// (`-32602`) instead of creating a session without the prompt, and `null`
8179    /// is equivalent to omitting the field.
8180    fn assert_system_prompt_is_strict<T>(base: &serde_json::Value)
8181    where
8182        T: serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
8183    {
8184        let name = std::any::type_name::<T>();
8185        let with = |system_prompt: serde_json::Value| {
8186            let mut request = base.clone();
8187            request["systemPrompt"] = system_prompt;
8188            serde_json::from_value::<T>(request)
8189        };
8190
8191        for system_prompt in [
8192            json!("You are a code review specialist."),
8193            json!({ "content": [{ "type": "text", "text": "..." }] }),
8194            json!({ "mode": null, "content": [{ "type": "text", "text": "..." }] }),
8195            json!({ "mode": 1, "content": [{ "type": "text", "text": "..." }] }),
8196            json!({ "mode": "append" }),
8197            json!({ "mode": "append", "content": "..." }),
8198            json!({ "mode": "append", "content": [{ "type": "text" }] }),
8199            json!({ "mode": "append", "content": [{ "type": "video", "uri": "..." }] }),
8200        ] {
8201            assert!(
8202                with(system_prompt.clone()).is_err(),
8203                "{name}.systemPrompt: {system_prompt}"
8204            );
8205        }
8206
8207        assert_eq!(
8208            with(serde_json::Value::Null).unwrap(),
8209            serde_json::from_value::<T>(base.clone()).unwrap(),
8210            "{name}.systemPrompt"
8211        );
8212    }
8213
8214    #[test]
8215    fn test_session_setup_requests_reject_malformed_system_prompts() {
8216        assert!(
8217            serde_json::to_value(NewSessionRequest::new("/repo"))
8218                .unwrap()
8219                .get("systemPrompt")
8220                .is_none()
8221        );
8222        assert_system_prompt_is_strict::<NewSessionRequest>(&json!({
8223            "cwd": "/repo",
8224            "mcpServers": []
8225        }));
8226        assert_system_prompt_is_strict::<LoadSessionRequest>(&json!({
8227            "sessionId": "sess-1",
8228            "cwd": "/repo",
8229            "mcpServers": []
8230        }));
8231        assert_system_prompt_is_strict::<ResumeSessionRequest>(&json!({
8232            "sessionId": "sess-1",
8233            "cwd": "/repo"
8234        }));
8235        #[cfg(feature = "unstable_session_fork")]
8236        assert_system_prompt_is_strict::<ForkSessionRequest>(&json!({
8237            "sessionId": "sess-1",
8238            "cwd": "/repo"
8239        }));
8240    }
8241
8242    #[test]
8243    fn test_auth_method_terminal_serialization() {
8244        let method = AuthMethod::Terminal(AuthMethodTerminal::new("tui-auth", "Terminal Auth"));
8245
8246        let json = serde_json::to_value(&method).unwrap();
8247        assert_eq!(
8248            json,
8249            json!({
8250                "id": "tui-auth",
8251                "name": "Terminal Auth",
8252                "type": "terminal"
8253            })
8254        );
8255        // args and env should be omitted when empty
8256        assert!(!json.as_object().unwrap().contains_key("args"));
8257        assert!(!json.as_object().unwrap().contains_key("env"));
8258
8259        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
8260        match deserialized {
8261            AuthMethod::Terminal(AuthMethodTerminal { args, env, .. }) => {
8262                assert_eq!(args, Vec::<String>::new());
8263                assert!(env.is_empty());
8264            }
8265            _ => panic!("Expected Terminal variant"),
8266        }
8267    }
8268
8269    #[test]
8270    fn test_auth_method_terminal_with_args_and_env_serialization() {
8271        use std::collections::HashMap;
8272
8273        let mut env = HashMap::new();
8274        env.insert("TERM".to_string(), "xterm-256color".to_string());
8275
8276        let method = AuthMethod::Terminal(
8277            AuthMethodTerminal::new("tui-auth", "Terminal Auth")
8278                .args(vec!["--interactive".to_string(), "--color".to_string()])
8279                .env(env),
8280        );
8281
8282        let json = serde_json::to_value(&method).unwrap();
8283        assert_eq!(
8284            json,
8285            json!({
8286                "id": "tui-auth",
8287                "name": "Terminal Auth",
8288                "type": "terminal",
8289                "args": ["--interactive", "--color"],
8290                "env": {
8291                    "TERM": "xterm-256color"
8292                }
8293            })
8294        );
8295
8296        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
8297        match deserialized {
8298            AuthMethod::Terminal(AuthMethodTerminal { args, env, .. }) => {
8299                assert_eq!(args, vec!["--interactive", "--color"]);
8300                assert_eq!(env.len(), 1);
8301                assert_eq!(env.get("TERM").unwrap(), "xterm-256color");
8302            }
8303            _ => panic!("Expected Terminal variant"),
8304        }
8305    }
8306
8307    #[test]
8308    fn test_session_config_option_value_id_serialize() {
8309        let val = SessionConfigOptionValue::value_id("model-1");
8310        let json = serde_json::to_value(&val).unwrap();
8311        // ValueId omits the "type" field (it's the default)
8312        assert_eq!(json, json!({ "value": "model-1" }));
8313        assert!(!json.as_object().unwrap().contains_key("type"));
8314    }
8315
8316    #[test]
8317    fn test_session_config_option_value_boolean_serialize() {
8318        let val = SessionConfigOptionValue::boolean(true);
8319        let json = serde_json::to_value(&val).unwrap();
8320        assert_eq!(json, json!({ "type": "boolean", "value": true }));
8321    }
8322
8323    #[test]
8324    fn test_session_config_option_value_deserialize_no_type() {
8325        // Missing "type" should default to ValueId
8326        let json = json!({ "value": "model-1" });
8327        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
8328        assert_eq!(val, SessionConfigOptionValue::value_id("model-1"));
8329        assert_eq!(val.as_value_id().unwrap().to_string(), "model-1");
8330    }
8331
8332    #[test]
8333    fn test_session_config_option_value_deserialize_boolean() {
8334        let json = json!({ "type": "boolean", "value": true });
8335        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
8336        assert_eq!(val, SessionConfigOptionValue::boolean(true));
8337        assert_eq!(val.as_bool(), Some(true));
8338    }
8339
8340    #[test]
8341    fn test_session_config_option_value_deserialize_boolean_false() {
8342        let json = json!({ "type": "boolean", "value": false });
8343        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
8344        assert_eq!(val, SessionConfigOptionValue::boolean(false));
8345        assert_eq!(val.as_bool(), Some(false));
8346    }
8347
8348    #[test]
8349    fn test_session_config_option_value_deserialize_unknown_type_with_string_value() {
8350        // Unknown type with a string value gracefully falls back to ValueId
8351        let json = json!({ "type": "text", "value": "freeform input" });
8352        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
8353        assert_eq!(val.as_value_id().unwrap().to_string(), "freeform input");
8354    }
8355
8356    #[test]
8357    fn test_session_config_option_value_roundtrip_value_id() {
8358        let original = SessionConfigOptionValue::value_id("option-a");
8359        let json = serde_json::to_value(&original).unwrap();
8360        let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
8361        assert_eq!(original, roundtripped);
8362    }
8363
8364    #[test]
8365    fn test_session_config_option_value_roundtrip_boolean() {
8366        let original = SessionConfigOptionValue::boolean(false);
8367        let json = serde_json::to_value(&original).unwrap();
8368        let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
8369        assert_eq!(original, roundtripped);
8370    }
8371
8372    #[test]
8373    fn test_session_config_option_value_type_mismatch_boolean_with_string() {
8374        // type says "boolean" but value is a string — falls to untagged ValueId
8375        let json = json!({ "type": "boolean", "value": "not a bool" });
8376        let result = serde_json::from_value::<SessionConfigOptionValue>(json);
8377        // serde tries Boolean first (fails), then falls to untagged ValueId (succeeds)
8378        assert!(result.is_ok());
8379        assert_eq!(
8380            result.unwrap().as_value_id().unwrap().to_string(),
8381            "not a bool"
8382        );
8383    }
8384
8385    #[test]
8386    fn test_session_config_option_value_from_impls() {
8387        let from_str: SessionConfigOptionValue = "model-1".into();
8388        assert_eq!(from_str.as_value_id().unwrap().to_string(), "model-1");
8389
8390        let from_id: SessionConfigOptionValue = SessionConfigValueId::new("model-2").into();
8391        assert_eq!(from_id.as_value_id().unwrap().to_string(), "model-2");
8392
8393        let from_bool: SessionConfigOptionValue = true.into();
8394        assert_eq!(from_bool.as_bool(), Some(true));
8395    }
8396
8397    #[test]
8398    fn test_set_session_config_option_request_value_id() {
8399        let req = SetSessionConfigOptionRequest::new("sess_1", "model", "model-1");
8400        let json = serde_json::to_value(&req).unwrap();
8401        assert_eq!(
8402            json,
8403            json!({
8404                "sessionId": "sess_1",
8405                "configId": "model",
8406                "value": "model-1"
8407            })
8408        );
8409        // No "type" field for value_id
8410        assert!(!json.as_object().unwrap().contains_key("type"));
8411    }
8412
8413    #[test]
8414    fn test_set_session_config_option_request_boolean() {
8415        let req = SetSessionConfigOptionRequest::new("sess_1", "brave_mode", true);
8416        let json = serde_json::to_value(&req).unwrap();
8417        assert_eq!(
8418            json,
8419            json!({
8420                "sessionId": "sess_1",
8421                "configId": "brave_mode",
8422                "type": "boolean",
8423                "value": true
8424            })
8425        );
8426    }
8427
8428    #[test]
8429    fn test_set_session_config_option_request_deserialize_no_type() {
8430        // Backwards-compatible: no "type" field → value_id
8431        let json = json!({
8432            "sessionId": "sess_1",
8433            "configId": "model",
8434            "value": "model-1"
8435        });
8436        let req: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
8437        assert_eq!(req.session_id.to_string(), "sess_1");
8438        assert_eq!(req.config_id.to_string(), "model");
8439        assert_eq!(req.value.as_value_id().unwrap().to_string(), "model-1");
8440    }
8441
8442    #[test]
8443    fn test_set_session_config_option_request_deserialize_boolean() {
8444        let json = json!({
8445            "sessionId": "sess_1",
8446            "configId": "brave_mode",
8447            "type": "boolean",
8448            "value": true
8449        });
8450        let req: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
8451        assert_eq!(req.value.as_bool(), Some(true));
8452    }
8453
8454    #[test]
8455    fn test_set_session_config_option_request_roundtrip_value_id() {
8456        let original = SetSessionConfigOptionRequest::new("s", "c", "v");
8457        let json = serde_json::to_value(&original).unwrap();
8458        let roundtripped: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
8459        assert_eq!(original, roundtripped);
8460    }
8461
8462    #[test]
8463    fn test_set_session_config_option_request_roundtrip_boolean() {
8464        let original = SetSessionConfigOptionRequest::new("s", "c", false);
8465        let json = serde_json::to_value(&original).unwrap();
8466        let roundtripped: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
8467        assert_eq!(original, roundtripped);
8468    }
8469
8470    #[test]
8471    fn test_session_config_boolean_serialization() {
8472        let cfg = SessionConfigBoolean::new(true);
8473        let json = serde_json::to_value(&cfg).unwrap();
8474        assert_eq!(json, json!({ "currentValue": true }));
8475
8476        let deserialized: SessionConfigBoolean = serde_json::from_value(json).unwrap();
8477        assert!(deserialized.current_value);
8478    }
8479
8480    #[test]
8481    fn test_session_config_option_boolean_variant() {
8482        let opt = SessionConfigOption::boolean("brave_mode", "Brave Mode", false)
8483            .description("Skip confirmation prompts")
8484            .meta(test_meta());
8485        assert_eq!(serialized_meta_key_count(&opt), 1);
8486
8487        let json = serde_json::to_value(&opt).unwrap();
8488        assert_eq!(
8489            json,
8490            json!({
8491                "id": "brave_mode",
8492                "name": "Brave Mode",
8493                "description": "Skip confirmation prompts",
8494                "type": "boolean",
8495                "currentValue": false,
8496                "_meta": {
8497                    "source": "test"
8498                }
8499            })
8500        );
8501
8502        let deserialized: SessionConfigOption = serde_json::from_value(json).unwrap();
8503        assert_eq!(deserialized.id.to_string(), "brave_mode");
8504        assert_eq!(deserialized.name, "Brave Mode");
8505        match deserialized.kind {
8506            SessionConfigKind::Boolean(ref b) => assert!(!b.current_value),
8507            _ => panic!("Expected Boolean kind"),
8508        }
8509    }
8510
8511    #[test]
8512    fn test_session_config_option_select_still_works() {
8513        // Make sure existing select options are unaffected
8514        let opt = SessionConfigOption::select(
8515            "model",
8516            "Model",
8517            "model-1",
8518            vec![
8519                SessionConfigSelectOption::new("model-1", "Model 1"),
8520                SessionConfigSelectOption::new("model-2", "Model 2"),
8521            ],
8522        )
8523        .meta(test_meta());
8524        assert_eq!(serialized_meta_key_count(&opt), 1);
8525
8526        let json = serde_json::to_value(&opt).unwrap();
8527        assert_eq!(json["type"], "select");
8528        assert_eq!(json["currentValue"], "model-1");
8529        assert_eq!(json["options"].as_array().unwrap().len(), 2);
8530        assert_eq!(json["_meta"]["source"], "test");
8531
8532        let deserialized: SessionConfigOption = serde_json::from_value(json).unwrap();
8533        match deserialized.kind {
8534            SessionConfigKind::Select(ref s) => {
8535                assert_eq!(s.current_value.to_string(), "model-1");
8536            }
8537            _ => panic!("Expected Select kind"),
8538        }
8539    }
8540
8541    #[cfg(feature = "unstable_llm_providers")]
8542    #[test]
8543    fn test_llm_protocol_known_variants() {
8544        assert_eq!(
8545            serde_json::to_value(&LlmProtocol::Anthropic).unwrap(),
8546            json!("anthropic")
8547        );
8548        assert_eq!(
8549            serde_json::to_value(&LlmProtocol::OpenAi).unwrap(),
8550            json!("openai")
8551        );
8552        assert_eq!(
8553            serde_json::to_value(&LlmProtocol::Azure).unwrap(),
8554            json!("azure")
8555        );
8556        assert_eq!(
8557            serde_json::to_value(&LlmProtocol::Vertex).unwrap(),
8558            json!("vertex")
8559        );
8560        assert_eq!(
8561            serde_json::to_value(&LlmProtocol::Bedrock).unwrap(),
8562            json!("bedrock")
8563        );
8564
8565        assert_eq!(
8566            serde_json::from_str::<LlmProtocol>("\"anthropic\"").unwrap(),
8567            LlmProtocol::Anthropic
8568        );
8569        assert_eq!(
8570            serde_json::from_str::<LlmProtocol>("\"openai\"").unwrap(),
8571            LlmProtocol::OpenAi
8572        );
8573        assert_eq!(
8574            serde_json::from_str::<LlmProtocol>("\"azure\"").unwrap(),
8575            LlmProtocol::Azure
8576        );
8577        assert_eq!(
8578            serde_json::from_str::<LlmProtocol>("\"vertex\"").unwrap(),
8579            LlmProtocol::Vertex
8580        );
8581        assert_eq!(
8582            serde_json::from_str::<LlmProtocol>("\"bedrock\"").unwrap(),
8583            LlmProtocol::Bedrock
8584        );
8585    }
8586
8587    #[cfg(feature = "unstable_llm_providers")]
8588    #[test]
8589    fn test_llm_protocol_unknown_variant() {
8590        let unknown: LlmProtocol = serde_json::from_str("\"cohere\"").unwrap();
8591        assert_eq!(unknown, LlmProtocol::Other("cohere".to_string()));
8592
8593        let json = serde_json::to_value(&unknown).unwrap();
8594        assert_eq!(json, json!("cohere"));
8595    }
8596
8597    #[cfg(feature = "unstable_llm_providers")]
8598    #[test]
8599    fn test_provider_current_config_serialization() {
8600        let config =
8601            ProviderCurrentConfig::new(LlmProtocol::Anthropic, "https://api.anthropic.com");
8602
8603        let json = serde_json::to_value(&config).unwrap();
8604        assert_eq!(
8605            json,
8606            json!({
8607                "apiType": "anthropic",
8608                "baseUrl": "https://api.anthropic.com"
8609            })
8610        );
8611
8612        let deserialized: ProviderCurrentConfig = serde_json::from_value(json).unwrap();
8613        assert_eq!(deserialized.api_type, LlmProtocol::Anthropic);
8614        assert_eq!(deserialized.base_url, "https://api.anthropic.com");
8615    }
8616
8617    #[cfg(feature = "unstable_llm_providers")]
8618    #[test]
8619    fn test_provider_info_with_current_config() {
8620        let info = ProviderInfo::new(
8621            "main",
8622            vec![LlmProtocol::Anthropic, LlmProtocol::OpenAi],
8623            true,
8624            Some(ProviderCurrentConfig::new(
8625                LlmProtocol::Anthropic,
8626                "https://api.anthropic.com",
8627            )),
8628        );
8629
8630        let json = serde_json::to_value(&info).unwrap();
8631        assert_eq!(
8632            json,
8633            json!({
8634                "providerId": "main",
8635                "supported": ["anthropic", "openai"],
8636                "required": true,
8637                "current": {
8638                    "apiType": "anthropic",
8639                    "baseUrl": "https://api.anthropic.com"
8640                }
8641            })
8642        );
8643
8644        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
8645        assert_eq!(deserialized.provider_id.to_string(), "main");
8646        assert_eq!(deserialized.supported.len(), 2);
8647        assert!(deserialized.required);
8648        assert!(deserialized.current.is_some());
8649        assert_eq!(
8650            deserialized.current.as_ref().unwrap().api_type,
8651            LlmProtocol::Anthropic
8652        );
8653    }
8654
8655    #[cfg(feature = "unstable_llm_providers")]
8656    #[test]
8657    fn test_provider_info_disabled() {
8658        let info = ProviderInfo::new(
8659            "secondary",
8660            vec![LlmProtocol::OpenAi],
8661            false,
8662            None::<ProviderCurrentConfig>,
8663        );
8664
8665        let json = serde_json::to_value(&info).unwrap();
8666        assert_eq!(
8667            json,
8668            json!({
8669                "providerId": "secondary",
8670                "supported": ["openai"],
8671                "required": false
8672            })
8673        );
8674
8675        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
8676        assert_eq!(deserialized.provider_id.to_string(), "secondary");
8677        assert!(!deserialized.required);
8678        assert!(deserialized.current.is_none());
8679    }
8680
8681    #[cfg(feature = "unstable_llm_providers")]
8682    #[test]
8683    fn test_provider_info_missing_current_defaults_to_none() {
8684        // current is optional; omitting it should decode as None
8685        let json = json!({
8686            "providerId": "main",
8687            "supported": ["anthropic"],
8688            "required": true
8689        });
8690        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
8691        assert!(deserialized.current.is_none());
8692    }
8693
8694    #[cfg(feature = "unstable_llm_providers")]
8695    #[test]
8696    fn test_provider_info_explicit_null_current_decodes_to_none() {
8697        // current: null and an omitted current are equivalent on the wire;
8698        // both must deserialize into None so the disabled state is preserved
8699        // regardless of which form the peer chose to send.
8700        let json = json!({
8701            "providerId": "main",
8702            "supported": ["anthropic"],
8703            "required": true,
8704            "current": null
8705        });
8706        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
8707        assert!(deserialized.current.is_none());
8708    }
8709
8710    #[cfg(feature = "unstable_llm_providers")]
8711    #[test]
8712    fn test_list_providers_response_serialization() {
8713        let response = ListProvidersResponse::new(vec![ProviderInfo::new(
8714            "main",
8715            vec![LlmProtocol::Anthropic],
8716            true,
8717            Some(ProviderCurrentConfig::new(
8718                LlmProtocol::Anthropic,
8719                "https://api.anthropic.com",
8720            )),
8721        )]);
8722
8723        let json = serde_json::to_value(&response).unwrap();
8724        assert_eq!(json["providers"].as_array().unwrap().len(), 1);
8725        assert_eq!(json["providers"][0]["providerId"], "main");
8726
8727        let deserialized: ListProvidersResponse = serde_json::from_value(json).unwrap();
8728        assert_eq!(deserialized.providers.len(), 1);
8729    }
8730
8731    #[cfg(feature = "unstable_llm_providers")]
8732    #[test]
8733    fn test_set_provider_request_serialization() {
8734        use std::collections::HashMap;
8735
8736        let mut headers = HashMap::new();
8737        headers.insert("Authorization".to_string(), "Bearer sk-test".to_string());
8738
8739        let request =
8740            SetProviderRequest::new("main", LlmProtocol::OpenAi, "https://api.openai.com/v1")
8741                .headers(headers);
8742
8743        let json = serde_json::to_value(&request).unwrap();
8744        assert_eq!(
8745            json,
8746            json!({
8747                "providerId": "main",
8748                "apiType": "openai",
8749                "baseUrl": "https://api.openai.com/v1",
8750                "headers": {
8751                    "Authorization": "Bearer sk-test"
8752                }
8753            })
8754        );
8755
8756        let deserialized: SetProviderRequest = serde_json::from_value(json).unwrap();
8757        assert_eq!(deserialized.provider_id.to_string(), "main");
8758        assert_eq!(deserialized.api_type, LlmProtocol::OpenAi);
8759        assert_eq!(deserialized.base_url, "https://api.openai.com/v1");
8760        assert_eq!(deserialized.headers.len(), 1);
8761        assert_eq!(
8762            deserialized.headers.get("Authorization").unwrap(),
8763            "Bearer sk-test"
8764        );
8765    }
8766
8767    #[cfg(feature = "unstable_llm_providers")]
8768    #[test]
8769    fn test_set_provider_request_omits_empty_headers() {
8770        let request =
8771            SetProviderRequest::new("main", LlmProtocol::Anthropic, "https://api.anthropic.com");
8772
8773        let json = serde_json::to_value(&request).unwrap();
8774        // headers should be omitted when empty
8775        assert!(!json.as_object().unwrap().contains_key("headers"));
8776    }
8777
8778    #[cfg(feature = "unstable_llm_providers")]
8779    #[test]
8780    fn test_disable_provider_request_serialization() {
8781        let request = DisableProviderRequest::new("secondary");
8782
8783        let json = serde_json::to_value(&request).unwrap();
8784        assert_eq!(json, json!({ "providerId": "secondary" }));
8785
8786        let deserialized: DisableProviderRequest = serde_json::from_value(json).unwrap();
8787        assert_eq!(deserialized.provider_id.to_string(), "secondary");
8788    }
8789
8790    #[cfg(feature = "unstable_llm_providers")]
8791    #[test]
8792    fn test_providers_capabilities_serialization() {
8793        let caps = ProvidersCapabilities::new();
8794
8795        let json = serde_json::to_value(&caps).unwrap();
8796        assert_eq!(json, json!({}));
8797
8798        let deserialized: ProvidersCapabilities = serde_json::from_value(json).unwrap();
8799        assert!(deserialized.meta.is_none());
8800    }
8801
8802    #[cfg(feature = "unstable_llm_providers")]
8803    #[test]
8804    fn test_agent_capabilities_with_providers() {
8805        let caps = AgentCapabilities::new().providers(ProvidersCapabilities::new());
8806
8807        let json = serde_json::to_value(&caps).unwrap();
8808        assert_eq!(json["providers"], json!({}));
8809
8810        let deserialized: AgentCapabilities = serde_json::from_value(json).unwrap();
8811        assert!(deserialized.providers.is_some());
8812    }
8813
8814    #[test]
8815    fn prompt_request_rejects_malformed_content_block() {
8816        use serde_json::json;
8817
8818        assert!(
8819            serde_json::from_value::<PromptRequest>(json!({
8820                "sessionId": "sess-1",
8821                "prompt": [{"type": "text"}]
8822            }))
8823            .is_err()
8824        );
8825    }
8826
8827    #[test]
8828    fn prompt_request_rejects_non_array_prompt() {
8829        use serde_json::json;
8830
8831        assert!(
8832            serde_json::from_value::<PromptRequest>(json!({
8833                "sessionId": "sess-1",
8834                "prompt": "hello"
8835            }))
8836            .is_err()
8837        );
8838    }
8839
8840    fn assert_session_setup_lists_are_strict<T>(base: &serde_json::Value)
8841    where
8842        T: serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
8843    {
8844        let name = std::any::type_name::<T>();
8845        let with = |field: &str, value: serde_json::Value| {
8846            let mut request = base.clone();
8847            request[field] = value;
8848            serde_json::from_value::<T>(request)
8849        };
8850
8851        for (field, value) in [
8852            // Dropping the malformed server would start the session without it.
8853            (
8854                "mcpServers",
8855                json!([
8856                    {"name": "github", "command": "/usr/bin/gh-mcp", "args": [], "env": [{"name": "GITHUB_TOKEN", "value": null}]},
8857                    {"name": "fs", "command": "/usr/bin/fs-mcp", "args": [], "env": []}
8858                ]),
8859            ),
8860            ("mcpServers", json!({"name": "fs"})),
8861            ("additionalDirectories", json!(["/repo/lib", 42])),
8862            ("additionalDirectories", json!("/repo/lib")),
8863        ] {
8864            assert!(
8865                with(field, value.clone()).is_err(),
8866                "{name}.{field}: {value}"
8867            );
8868        }
8869
8870        let empty = serde_json::from_value::<T>(base.clone()).unwrap();
8871        for field in ["mcpServers", "additionalDirectories"] {
8872            assert_eq!(
8873                with(field, serde_json::Value::Null).unwrap(),
8874                empty,
8875                "{name}.{field}"
8876            );
8877        }
8878    }
8879
8880    #[test]
8881    fn session_setup_requests_reject_malformed_mcp_servers_and_directories() {
8882        assert_session_setup_lists_are_strict::<NewSessionRequest>(&json!({
8883            "cwd": "/repo",
8884            "mcpServers": []
8885        }));
8886        assert_session_setup_lists_are_strict::<LoadSessionRequest>(&json!({
8887            "sessionId": "sess-1",
8888            "cwd": "/repo",
8889            "mcpServers": []
8890        }));
8891        assert_session_setup_lists_are_strict::<ResumeSessionRequest>(&json!({
8892            "sessionId": "sess-1",
8893            "cwd": "/repo"
8894        }));
8895        #[cfg(feature = "unstable_session_fork")]
8896        assert_session_setup_lists_are_strict::<ForkSessionRequest>(&json!({
8897            "sessionId": "sess-1",
8898            "cwd": "/repo"
8899        }));
8900    }
8901
8902    #[test]
8903    fn mcp_server_lists_treat_null_as_empty() {
8904        let servers: Vec<McpServer> = serde_json::from_value(json!([
8905            {"name": "fs", "command": "/usr/bin/fs-mcp", "args": null, "env": null},
8906            {"type": "http", "name": "api", "url": "https://example.com/mcp", "headers": null},
8907            {"type": "sse", "name": "events", "url": "https://example.com/sse", "headers": null}
8908        ]))
8909        .unwrap();
8910
8911        assert_eq!(
8912            servers,
8913            vec![
8914                McpServer::Stdio(McpServerStdio::new("fs", "/usr/bin/fs-mcp")),
8915                McpServer::Http(McpServerHttp::new("api", "https://example.com/mcp")),
8916                McpServer::Sse(McpServerSse::new("events", "https://example.com/sse")),
8917            ]
8918        );
8919    }
8920
8921    #[test]
8922    fn terminal_auth_methods_reject_malformed_launch_config() {
8923        // The client spawns a process from `args` and `env`, so a malformed
8924        // method is dropped from `authMethods` instead of launched with
8925        // altered arguments or reinterpreted as an `agent` method.
8926        let response: InitializeResponse = serde_json::from_value(json!({
8927            "protocolVersion": 1,
8928            "authMethods": [
8929                {"type": "terminal", "id": "bad-args", "name": "Log in", "args": ["auth", "--port", 8123]},
8930                {"type": "terminal", "id": "bad-env", "name": "Log in", "env": {"AUTH_MODE": "device", "DEBUG": 1}},
8931                {"type": "terminal", "id": "null-config", "name": "Log in", "args": null, "env": null},
8932                {"id": "agent", "name": "Agent login"}
8933            ]
8934        }))
8935        .unwrap();
8936
8937        assert_eq!(
8938            response.auth_methods,
8939            vec![
8940                AuthMethod::Terminal(AuthMethodTerminal::new("null-config", "Log in")),
8941                AuthMethod::Agent(AuthMethodAgent::new("agent", "Agent login")),
8942            ]
8943        );
8944        assert!(
8945            serde_json::from_value::<AuthMethod>(json!({
8946                "type": "terminal",
8947                "id": "bad-args",
8948                "name": "Log in",
8949                "args": ["auth", 8123]
8950            }))
8951            .is_err()
8952        );
8953    }
8954
8955    #[cfg(feature = "unstable_auth_status")]
8956    #[test]
8957    fn auth_status_response_round_trips() {
8958        let response = AuthStatusResponse::new(AuthState::Authenticated).accounts(vec![
8959            AuthAccount::new("Anthropic API key")
8960                .description("API key helper".to_string())
8961                .active(true),
8962            AuthAccount::new("Claude Max").email("user@example.com".to_string()),
8963        ]);
8964        let json = serde_json::to_value(&response).unwrap();
8965        assert_eq!(
8966            json,
8967            json!({
8968                "state": "authenticated",
8969                "accounts": [
8970                    {
8971                        "label": "Anthropic API key",
8972                        "description": "API key helper",
8973                        "active": true
8974                    },
8975                    {
8976                        "label": "Claude Max",
8977                        "email": "user@example.com"
8978                    }
8979                ]
8980            })
8981        );
8982        assert_eq!(
8983            serde_json::from_value::<AuthStatusResponse>(json).unwrap(),
8984            response
8985        );
8986        assert_eq!(
8987            serde_json::to_value(AuthStatusResponse::new(AuthState::NotRequired)).unwrap(),
8988            json!({"state": "not_required"})
8989        );
8990    }
8991
8992    #[cfg(feature = "unstable_auth_status")]
8993    #[test]
8994    fn auth_status_state_is_strict_and_accounts_are_lenient() {
8995        assert!(serde_json::from_value::<AuthStatusResponse>(json!({})).is_err());
8996        assert!(serde_json::from_value::<AuthStatusResponse>(json!({"state": null})).is_err());
8997        assert!(serde_json::from_value::<AuthStatusResponse>(json!({"state": 1})).is_err());
8998
8999        let response: AuthStatusResponse = serde_json::from_value(json!({
9000            "state": "_vendor_state",
9001            "accounts": [
9002                {"active": true},
9003                {
9004                    "label": "Vertex AI",
9005                    "description": 42,
9006                    "active": "yes",
9007                    "email": ["not", "a", "string"]
9008                }
9009            ]
9010        }))
9011        .unwrap();
9012        assert_eq!(
9013            response,
9014            AuthStatusResponse::new(AuthState::Other("_vendor_state".to_string()))
9015                .accounts(vec![AuthAccount::new("Vertex AI")])
9016        );
9017        assert_eq!(
9018            serde_json::from_value::<AuthStatusResponse>(
9019                json!({"state": "unknown", "accounts": null})
9020            )
9021            .unwrap(),
9022            AuthStatusResponse::new(AuthState::Unknown)
9023        );
9024    }
9025
9026    #[cfg(feature = "unstable_auth_status")]
9027    #[test]
9028    fn auth_status_update_notification_routes() {
9029        use crate::v1::{AgentNotification, CLIENT_METHOD_NAMES};
9030
9031        assert_eq!(AGENT_METHOD_NAMES.auth_status, "auth/status");
9032        assert_eq!(CLIENT_METHOD_NAMES.auth_status_update, "auth/status_update");
9033        let notification = AgentNotification::AuthStatusUpdateNotification(
9034            AuthStatusUpdateNotification::new(AuthState::Unauthenticated),
9035        );
9036        assert_eq!(notification.method(), "auth/status_update");
9037        assert_eq!(
9038            serde_json::to_value(&notification).unwrap(),
9039            json!({"state": "unauthenticated"})
9040        );
9041    }
9042}