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