Skip to main content

agent_client_protocol_schema/v1/
agent.rs

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