Skip to main content

agent_client_protocol_schema/v2/
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::{borrow::Cow, sync::Arc};
7
8use derive_more::{Display, From};
9use indexmap::IndexMap;
10#[cfg(feature = "schemars")]
11use schemars::Schema;
12use serde::{Deserialize, Serialize};
13use serde_with::{DefaultOnError, DefaultOnNull, VecSkipError, serde_as, skip_serializing_none};
14
15use super::{
16    AbsolutePath, AvailableCommand, ClientCapabilities, ContentBlock, Error, ExtNotification,
17    ExtRequest, ExtResponse, MessageId, Meta, SessionId, TerminalId, ToolCallId,
18};
19use crate::{IntoOption, ProtocolVersion};
20
21#[cfg(all(
22    feature = "unstable_session_fork",
23    feature = "unstable_session_cursors"
24))]
25use super::CursorId;
26#[cfg(feature = "unstable_session_status")]
27use super::StateUpdate;
28
29#[cfg(all(feature = "unstable_auth_status", feature = "schemars"))]
30use super::AUTH_STATUS_UPDATE_NOTIFICATION;
31#[cfg(feature = "unstable_mcp_over_acp")]
32use super::mcp::{MCP_MESSAGE_METHOD_NAME, MessageMcpNotification};
33
34// Initialize
35
36/// Request parameters for the initialize method.
37///
38/// Sent by the Client to establish connection and negotiate capabilities.
39///
40/// See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/v2/initialization)
41#[serde_as]
42#[skip_serializing_none]
43#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
44#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
45#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = INITIALIZE_METHOD_NAME)))]
46#[serde(rename_all = "camelCase")]
47#[non_exhaustive]
48pub struct InitializeRequest {
49    /// The latest protocol version supported by the Client.
50    pub protocol_version: ProtocolVersion,
51    /// Information about the implementation sending this initialize request.
52    pub info: Implementation,
53    /// Capabilities supported by the Client.
54    #[serde_as(deserialize_as = "DefaultOnError")]
55    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
56    #[serde(default)]
57    pub capabilities: ClientCapabilities,
58    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
59    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
60    /// Implementations MUST NOT assign meaning to keys they do not recognize.
61    ///
62    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
63    #[serde_as(deserialize_as = "DefaultOnError")]
64    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
65    #[serde(default)]
66    #[serde(rename = "_meta")]
67    pub meta: Option<Meta>,
68}
69
70impl InitializeRequest {
71    /// Builds [`InitializeRequest`] with the required request fields set. Optional fields start unset or empty.
72    #[must_use]
73    pub fn new(protocol_version: ProtocolVersion, info: Implementation) -> Self {
74        Self {
75            protocol_version,
76            capabilities: ClientCapabilities::default(),
77            info,
78            meta: None,
79        }
80    }
81
82    /// Capabilities supported by the Client.
83    #[must_use]
84    pub fn capabilities(mut self, capabilities: ClientCapabilities) -> Self {
85        self.capabilities = capabilities;
86        self
87    }
88
89    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
90    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
91    /// do not recognize.
92    ///
93    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
94    #[must_use]
95    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
96        self.meta = meta.into_option();
97        self
98    }
99}
100
101/// Response to the `initialize` method.
102///
103/// Contains the negotiated protocol version and Agent capabilities.
104///
105/// See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/v2/initialization)
106#[serde_as]
107#[skip_serializing_none]
108#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
109#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
110#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = INITIALIZE_METHOD_NAME)))]
111#[serde(rename_all = "camelCase")]
112#[non_exhaustive]
113pub struct InitializeResponse {
114    /// The highest protocol version supported by the Agent that is at or below
115    /// the version requested by the Client. If no such version exists,
116    /// initialization fails with error code -32022.
117    ///
118    /// The Client MUST check that it supports this version and SHOULD disconnect
119    /// if it does not.
120    pub protocol_version: ProtocolVersion,
121    /// Information about the implementation sending this initialize response.
122    pub info: Implementation,
123    /// Capabilities supported by the Agent.
124    #[serde_as(deserialize_as = "DefaultOnError")]
125    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
126    #[serde(default)]
127    pub capabilities: AgentCapabilities,
128    /// Authentication methods supported by the Agent.
129    ///
130    /// Optional. Omitted or empty means the Agent does not advertise the
131    /// `auth/login` and `auth/logout` methods. Supplying one or more methods means
132    /// the Agent MUST support both `auth/login` and `auth/logout`.
133    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
134    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
135    #[serde(default, skip_serializing_if = "Vec::is_empty")]
136    pub auth_methods: Vec<AuthMethod>,
137    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
138    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
139    /// Implementations MUST NOT assign meaning to keys they do not recognize.
140    ///
141    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
142    #[serde_as(deserialize_as = "DefaultOnError")]
143    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
144    #[serde(default)]
145    #[serde(rename = "_meta")]
146    pub meta: Option<Meta>,
147}
148
149impl InitializeResponse {
150    /// Builds [`InitializeResponse`] with the required response fields set. Optional fields start unset or empty.
151    #[must_use]
152    pub fn new(protocol_version: ProtocolVersion, info: Implementation) -> Self {
153        Self {
154            protocol_version,
155            capabilities: AgentCapabilities::default(),
156            auth_methods: vec![],
157            info,
158            meta: None,
159        }
160    }
161
162    /// Capabilities supported by the Agent.
163    #[must_use]
164    pub fn capabilities(mut self, capabilities: AgentCapabilities) -> Self {
165        self.capabilities = capabilities;
166        self
167    }
168
169    /// Authentication methods supported by the Agent.
170    ///
171    /// Supplying one or more methods means the Agent MUST support both
172    /// `auth/login` and `auth/logout`.
173    #[must_use]
174    pub fn auth_methods(mut self, auth_methods: Vec<AuthMethod>) -> Self {
175        self.auth_methods = auth_methods;
176        self
177    }
178
179    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
180    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
181    /// do not recognize.
182    ///
183    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
184    #[must_use]
185    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
186        self.meta = meta.into_option();
187        self
188    }
189}
190
191/// Metadata about the implementation of the Client or Agent.
192/// Describes the name and version of an ACP implementation, with an optional
193/// title for UI representation.
194#[serde_as]
195#[skip_serializing_none]
196#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
197#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
198#[serde(rename_all = "camelCase")]
199#[non_exhaustive]
200pub struct Implementation {
201    /// Name intended for programmatic or logical use. It can also serve as the
202    /// plain-text display name when `title` is absent.
203    pub name: String,
204    /// Optional human-readable title chosen to make the implementation easy to
205    /// recognize in the user interface. The title is plain text.
206    ///
207    /// Omission and `null` are equivalent. When displaying an implementation without a title,
208    /// the receiver SHOULD use `name`.
209    #[serde_as(deserialize_as = "DefaultOnError")]
210    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
211    #[serde(default)]
212    pub title: Option<String>,
213    /// Version of the implementation. Can be displayed to the user or used
214    /// for debugging or metrics purposes. (e.g. "1.0.0").
215    pub version: String,
216    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
217    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
218    /// Implementations MUST NOT assign meaning to keys they do not recognize.
219    ///
220    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
221    #[serde_as(deserialize_as = "DefaultOnError")]
222    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
223    #[serde(default)]
224    #[serde(rename = "_meta")]
225    pub meta: Option<Meta>,
226}
227
228impl Implementation {
229    /// Builds [`Implementation`] with the required fields set. Optional fields start unset or empty.
230    #[must_use]
231    pub fn new(name: impl Into<String>, version: impl Into<String>) -> Self {
232        Self {
233            name: name.into(),
234            title: None,
235            version: version.into(),
236            meta: None,
237        }
238    }
239
240    /// Optional human-readable title chosen to make the implementation easy to
241    /// recognize in the user interface. The title is plain text.
242    ///
243    /// When displaying an implementation without a title, the receiver SHOULD use `name`.
244    #[must_use]
245    pub fn title(mut self, title: impl IntoOption<String>) -> Self {
246        self.title = title.into_option();
247        self
248    }
249
250    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
251    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
252    /// do not recognize.
253    ///
254    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
255    #[must_use]
256    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
257        self.meta = meta.into_option();
258        self
259    }
260}
261
262// Authentication
263
264/// Request parameters for the `auth/login` method.
265///
266/// Specifies which authentication method to use.
267///
268/// Agents MUST support this method when their `initialize` response included
269/// a non-empty `authMethods` list. Clients MUST NOT call this method
270/// when `authMethods` was omitted or empty.
271#[serde_as]
272#[skip_serializing_none]
273#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
274#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
275#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGIN_METHOD_NAME)))]
276#[serde(rename_all = "camelCase")]
277#[non_exhaustive]
278pub struct LoginAuthRequest {
279    /// The ID of the authentication method to use.
280    /// Must be one of the methods advertised in the initialize response.
281    pub method_id: AuthMethodId,
282    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
283    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
284    /// Implementations MUST NOT assign meaning to keys they do not recognize.
285    ///
286    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
287    #[serde_as(deserialize_as = "DefaultOnError")]
288    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
289    #[serde(default)]
290    #[serde(rename = "_meta")]
291    pub meta: Option<Meta>,
292}
293
294impl LoginAuthRequest {
295    /// Builds [`LoginAuthRequest`] with the required request fields set. Optional fields start unset or empty.
296    #[must_use]
297    pub fn new(method_id: impl Into<AuthMethodId>) -> Self {
298        Self {
299            method_id: method_id.into(),
300            meta: None,
301        }
302    }
303
304    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
305    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
306    /// do not recognize.
307    ///
308    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
309    #[must_use]
310    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
311        self.meta = meta.into_option();
312        self
313    }
314}
315
316crate::serde_util::default_on_null! {
317    /// Response to the `auth/login` method.
318    #[serde_as]
319    #[skip_serializing_none]
320    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
321    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
322    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGIN_METHOD_NAME)))]
323    #[serde(rename_all = "camelCase")]
324    #[non_exhaustive]
325    pub struct LoginAuthResponse {
326        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
327        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
328        /// Implementations MUST NOT assign meaning to keys they do not recognize.
329        ///
330        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
331        #[serde_as(deserialize_as = "DefaultOnError")]
332        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
333        #[serde(default)]
334        #[serde(rename = "_meta")]
335        pub meta: Option<Meta>,
336    }
337}
338
339impl LoginAuthResponse {
340    /// Builds [`LoginAuthResponse`] with the required response fields set. Optional fields start unset or empty.
341    #[must_use]
342    pub fn new() -> Self {
343        Self::default()
344    }
345
346    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
347    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
348    /// do not recognize.
349    ///
350    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
351    #[must_use]
352    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
353        self.meta = meta.into_option();
354        self
355    }
356}
357
358// Logout
359
360crate::serde_util::default_on_null! {
361    /// Request parameters for the `auth/logout` method.
362    ///
363    /// Terminates the current authenticated session.
364    ///
365    /// Agents MUST support this method when their `initialize` response included
366    /// a non-empty `authMethods` list. Clients MUST NOT call this method
367    /// when `authMethods` was omitted or empty.
368    #[serde_as]
369    #[skip_serializing_none]
370    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
371    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
372    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGOUT_METHOD_NAME)))]
373    #[serde(rename_all = "camelCase")]
374    #[non_exhaustive]
375    pub struct LogoutAuthRequest {
376        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
377        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
378        /// Implementations MUST NOT assign meaning to keys they do not recognize.
379        ///
380        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
381        #[serde_as(deserialize_as = "DefaultOnError")]
382        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
383        #[serde(default)]
384        #[serde(rename = "_meta")]
385        pub meta: Option<Meta>,
386    }
387}
388
389impl LogoutAuthRequest {
390    /// Builds [`LogoutAuthRequest`] with the required request fields set. Optional fields start unset or empty.
391    #[must_use]
392    pub fn new() -> Self {
393        Self::default()
394    }
395
396    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
397    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
398    /// do not recognize.
399    ///
400    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
401    #[must_use]
402    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
403        self.meta = meta.into_option();
404        self
405    }
406}
407
408crate::serde_util::default_on_null! {
409    /// Response to the `auth/logout` method.
410    #[serde_as]
411    #[skip_serializing_none]
412    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
413    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
414    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGOUT_METHOD_NAME)))]
415    #[serde(rename_all = "camelCase")]
416    #[non_exhaustive]
417    pub struct LogoutAuthResponse {
418        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
419        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
420        /// Implementations MUST NOT assign meaning to keys they do not recognize.
421        ///
422        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
423        #[serde_as(deserialize_as = "DefaultOnError")]
424        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
425        #[serde(default)]
426        #[serde(rename = "_meta")]
427        pub meta: Option<Meta>,
428    }
429}
430
431impl LogoutAuthResponse {
432    /// Builds [`LogoutAuthResponse`] with the required response fields set. Optional fields start unset or empty.
433    #[must_use]
434    pub fn new() -> Self {
435        Self::default()
436    }
437
438    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
439    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
440    /// do not recognize.
441    ///
442    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
443    #[must_use]
444    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
445        self.meta = meta.into_option();
446        self
447    }
448}
449
450// Auth status
451
452#[cfg(feature = "unstable_auth_status")]
453crate::serde_util::default_on_null! {
454    /// **UNSTABLE**
455    ///
456    /// This capability is not part of the spec yet, and may be removed or changed at any point.
457    ///
458    /// Request parameters for the `auth/status` method.
459    ///
460    /// Queries the Agent's current authentication state without changing it.
461    ///
462    /// Agents MUST NOT reject it with `-32000` (Authentication required), since Clients call it to learn
463    /// whether authentication is required.
464    #[serde_as]
465    #[skip_serializing_none]
466    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
467    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
468    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_STATUS_METHOD_NAME)))]
469    #[serde(rename_all = "camelCase")]
470    #[non_exhaustive]
471    pub struct AuthStatusRequest {
472        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
473        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
474        /// Implementations MUST NOT assign meaning to keys they do not recognize.
475        ///
476        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
477        #[serde_as(deserialize_as = "DefaultOnError")]
478        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
479        #[serde(default)]
480        #[serde(rename = "_meta")]
481        pub meta: Option<Meta>,
482    }
483}
484
485#[cfg(feature = "unstable_auth_status")]
486impl AuthStatusRequest {
487    /// Builds [`AuthStatusRequest`] with the required request fields set. Optional fields start unset or empty.
488    #[must_use]
489    pub fn new() -> Self {
490        Self::default()
491    }
492
493    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
494    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
495    /// do not recognize.
496    ///
497    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
498    #[must_use]
499    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
500        self.meta = meta.into_option();
501        self
502    }
503}
504
505/// **UNSTABLE**
506///
507/// This capability is not part of the spec yet, and may be removed or changed at any point.
508///
509/// Response to the `auth/status` method.
510#[cfg(feature = "unstable_auth_status")]
511#[serde_as]
512#[skip_serializing_none]
513#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
514#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
515#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_STATUS_METHOD_NAME)))]
516#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"agent": [{"action": "replace", "target": "authStatus"}]})))]
517#[serde(rename_all = "camelCase")]
518#[non_exhaustive]
519pub struct AuthStatusResponse {
520    /// Whether the Agent can start sessions without the user signing in first.
521    ///
522    /// Clients use this field to decide whether sign-in is needed. Clients MUST treat
523    /// values they do not recognize as `unknown`.
524    pub state: AuthState,
525    /// The accounts the Agent has configured, for display.
526    ///
527    /// Optional. Omitted and empty are equivalent and mean no accounts are reported.
528    /// Agents that hold credentials for several providers or accounts SHOULD list each
529    /// of them and mark the ones in effect with `active`.
530    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
531    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
532    #[serde(default, skip_serializing_if = "Vec::is_empty")]
533    pub accounts: Vec<AuthAccount>,
534    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
535    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
536    /// Implementations MUST NOT assign meaning to keys they do not recognize.
537    ///
538    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
539    #[serde_as(deserialize_as = "DefaultOnError")]
540    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
541    #[serde(default)]
542    #[serde(rename = "_meta")]
543    pub meta: Option<Meta>,
544}
545
546#[cfg(feature = "unstable_auth_status")]
547impl AuthStatusResponse {
548    /// Builds [`AuthStatusResponse`] with the required fields set. Optional fields start unset or empty.
549    #[must_use]
550    pub fn new(state: AuthState) -> Self {
551        Self {
552            state,
553            accounts: vec![],
554            meta: None,
555        }
556    }
557
558    /// The accounts the Agent has configured, for display.
559    #[must_use]
560    pub fn accounts(mut self, accounts: Vec<AuthAccount>) -> Self {
561        self.accounts = accounts;
562        self
563    }
564
565    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
566    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
567    /// do not recognize.
568    ///
569    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
570    #[must_use]
571    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
572        self.meta = meta.into_option();
573        self
574    }
575}
576
577/// **UNSTABLE**
578///
579/// This capability is not part of the spec yet, and may be removed or changed at any point.
580///
581/// Notification sent by the Agent when its authentication status changes.
582///
583/// Carries the same fields as the `auth/status` response. Agents that advertise the
584/// `auth.status` capability MAY send it at any time after `initialize`, and SHOULD only
585/// send it when the reported status differs from the last one sent on the connection.
586#[cfg(feature = "unstable_auth_status")]
587#[serde_as]
588#[skip_serializing_none]
589#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
590#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
591#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = AUTH_STATUS_UPDATE_NOTIFICATION)))]
592#[cfg_attr(feature = "schemars", schemars(extend("x-scope" = {})))]
593#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"agent": [{"action": "replace", "target": "authStatus"}]})))]
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. Omitted and `null` are equivalent and mean no metadata.
613    /// Implementations MUST NOT assign meaning to keys they do not recognize.
614    ///
615    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/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 assign meaning to keys they
644    /// do not recognize.
645    ///
646    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/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 as plain text,
702    /// for example `Claude Max`, `OpenAI API key`, or `Vertex AI`.
703    pub label: String,
704    /// Short plain-text description shown with the label, such as the credential source
705    /// `API key helper`. Agents MUST NOT put credentials in this field.
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. Omitted and `null` are equivalent and mean no metadata.
744    /// Implementations MUST NOT assign meaning to keys they do not recognize.
745    ///
746    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/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 plain-text description 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 assign meaning to keys they
807    /// do not recognize.
808    ///
809    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/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. Omitted and `null` are equivalent and mean no metadata.
833    /// Implementations MUST NOT assign meaning to keys they do not recognize.
834    ///
835    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/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 assign meaning to keys they
853    /// do not recognize.
854    ///
855    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/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 extension capabilities supported by the Agent.
864///
865/// This object does not advertise support for `auth/login` or `auth/logout`.
866/// Those methods are advertised by a non-empty `authMethods` list in the
867/// `initialize` response.
868#[serde_as]
869#[skip_serializing_none]
870#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
871#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
872#[serde(rename_all = "camelCase")]
873#[non_exhaustive]
874pub struct AgentAuthCapabilities {
875    /// **UNSTABLE**
876    ///
877    /// This capability is not part of the spec yet, and may be removed or changed at any point.
878    ///
879    /// Whether the Agent supports the `auth/status` method.
880    ///
881    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
882    /// Supplying `{}` means the Agent supports the `auth/status` method.
883    #[cfg(feature = "unstable_auth_status")]
884    #[serde_as(deserialize_as = "DefaultOnError")]
885    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
886    #[serde(default)]
887    pub status: Option<AuthStatusCapabilities>,
888    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
889    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
890    /// Implementations MUST NOT assign meaning to keys they do not recognize.
891    ///
892    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
893    #[serde_as(deserialize_as = "DefaultOnError")]
894    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
895    #[serde(default)]
896    #[serde(rename = "_meta")]
897    pub meta: Option<Meta>,
898}
899
900impl AgentAuthCapabilities {
901    /// Builds an empty [`AgentAuthCapabilities`].
902    #[must_use]
903    pub fn new() -> Self {
904        Self::default()
905    }
906
907    /// **UNSTABLE**
908    ///
909    /// This capability is not part of the spec yet, and may be removed or changed at any point.
910    ///
911    /// Whether the Agent supports the `auth/status` method.
912    #[cfg(feature = "unstable_auth_status")]
913    #[must_use]
914    pub fn status(mut self, status: impl IntoOption<AuthStatusCapabilities>) -> Self {
915        self.status = status.into_option();
916        self
917    }
918
919    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
920    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
921    /// do not recognize.
922    ///
923    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
924    #[must_use]
925    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
926        self.meta = meta.into_option();
927        self
928    }
929}
930
931/// Typed identifier used for auth method values on the wire.
932#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
933#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
934#[serde(transparent)]
935#[from(forward)]
936#[non_exhaustive]
937pub struct AuthMethodId(pub Arc<str>);
938
939impl AuthMethodId {
940    /// Wraps a protocol string as a typed [`AuthMethodId`].
941    #[must_use]
942    pub fn new(id: impl Into<Self>) -> Self {
943        id.into()
944    }
945}
946
947/// Describes an available authentication method.
948///
949/// The `type` field acts as the discriminator in the serialized JSON form.
950#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
951#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
952#[serde(tag = "type", rename_all = "snake_case")]
953#[non_exhaustive]
954pub enum AuthMethod {
955    /// Client runs the configured Agent program as a separate interactive
956    /// process, without passing this method to `auth/login`.
957    Terminal(AuthMethodTerminal),
958    /// Agent handles authentication itself through `auth/login`.
959    ///
960    /// The `type` discriminator value is `agent`.
961    Agent(AuthMethodAgent),
962    /// Custom or future authentication method.
963    ///
964    /// Values beginning with `_` are reserved for implementation-specific
965    /// extensions. Unknown values that do not begin with `_` are reserved for
966    /// future ACP variants.
967    ///
968    /// Clients that do not understand this method type SHOULD preserve the raw
969    /// payload when storing, replaying, proxying, or forwarding initialization
970    /// data, and otherwise ignore the method or display it generically.
971    #[serde(untagged)]
972    Other(OtherAuthMethod),
973}
974
975impl AuthMethod {
976    /// The unique identifier for this authentication method.
977    #[must_use]
978    pub fn method_id(&self) -> &AuthMethodId {
979        match self {
980            Self::Agent(a) => &a.method_id,
981            Self::Other(a) => &a.method_id,
982            Self::Terminal(t) => &t.method_id,
983        }
984    }
985
986    /// Human-readable name of the authentication method, shown to users as plain text.
987    #[must_use]
988    pub fn name(&self) -> &str {
989        match self {
990            Self::Agent(a) => &a.name,
991            Self::Other(a) => &a.name,
992            Self::Terminal(t) => &t.name,
993        }
994    }
995
996    /// Optional human-readable description of this authentication method.
997    /// May contain Markdown.
998    #[must_use]
999    pub fn description(&self) -> Option<&str> {
1000        match self {
1001            Self::Agent(a) => a.description.as_deref(),
1002            Self::Other(a) => a
1003                .fields
1004                .get("description")
1005                .and_then(serde_json::Value::as_str),
1006            Self::Terminal(t) => t.description.as_deref(),
1007        }
1008    }
1009
1010    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1011    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1012    /// do not recognize.
1013    ///
1014    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1015    #[must_use]
1016    pub fn meta(&self) -> Option<&Meta> {
1017        match self {
1018            Self::Agent(a) => a.meta.as_ref(),
1019            Self::Other(a) => a.fields.get("_meta").and_then(serde_json::Value::as_object),
1020            Self::Terminal(t) => t.meta.as_ref(),
1021        }
1022    }
1023}
1024
1025/// Custom or future authentication method payload.
1026#[serde_as]
1027#[skip_serializing_none]
1028#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1029#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1030#[cfg_attr(feature = "schemars", schemars(inline))]
1031#[cfg_attr(feature = "schemars", schemars(transform = other_auth_method_schema))]
1032#[serde(rename_all = "camelCase")]
1033#[non_exhaustive]
1034pub struct OtherAuthMethod {
1035    /// Custom or future authentication method type.
1036    ///
1037    /// Values beginning with `_` are reserved for implementation-specific
1038    /// extensions. Unknown values that do not begin with `_` are reserved for
1039    /// future ACP variants.
1040    #[serde(rename = "type")]
1041    pub type_: String,
1042    /// Unique identifier for this authentication method.
1043    pub method_id: AuthMethodId,
1044    /// Human-readable name of the authentication method, shown to users as plain text.
1045    pub name: String,
1046    /// The remaining fields of the unknown authentication method payload, preserved verbatim,
1047    /// including `description` and `_meta`.
1048    #[serde(flatten)]
1049    pub fields: IndexMap<String, serde_json::Value>,
1050}
1051
1052impl OtherAuthMethod {
1053    /// Builds [`OtherAuthMethod`] from an unknown discriminator and preserves the remaining extension fields.
1054    #[must_use]
1055    pub fn new(
1056        type_: impl Into<String>,
1057        method_id: impl Into<AuthMethodId>,
1058        name: impl Into<String>,
1059        mut fields: IndexMap<String, serde_json::Value>,
1060    ) -> Self {
1061        fields.shift_remove("type");
1062        fields.shift_remove("methodId");
1063        fields.shift_remove("name");
1064        Self {
1065            type_: type_.into(),
1066            method_id: method_id.into(),
1067            name: name.into(),
1068            fields,
1069        }
1070    }
1071}
1072
1073impl<'de> Deserialize<'de> for OtherAuthMethod {
1074    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1075    where
1076        D: serde::Deserializer<'de>,
1077    {
1078        #[derive(Deserialize)]
1079        #[serde(rename_all = "camelCase")]
1080        struct RawOtherAuthMethod {
1081            #[serde(rename = "type")]
1082            type_: String,
1083            method_id: AuthMethodId,
1084            name: String,
1085            #[serde(flatten)]
1086            fields: IndexMap<String, serde_json::Value>,
1087        }
1088
1089        let raw = RawOtherAuthMethod::deserialize(deserializer)?;
1090        if is_known_auth_method_type(&raw.type_) {
1091            return Err(serde::de::Error::custom(format!(
1092                "known authentication method `{}` did not match its schema",
1093                raw.type_
1094            )));
1095        }
1096
1097        Ok(Self {
1098            type_: raw.type_,
1099            method_id: raw.method_id,
1100            name: raw.name,
1101            fields: raw.fields,
1102        })
1103    }
1104}
1105
1106fn is_known_auth_method_type(type_: &str) -> bool {
1107    matches!(type_, "agent" | "terminal")
1108}
1109
1110#[cfg(feature = "schemars")]
1111fn other_auth_method_schema(schema: &mut Schema) {
1112    super::schema_util::reject_known_string_discriminators(schema, "type", &["agent", "terminal"]);
1113}
1114
1115/// Agent handles authentication itself through `auth/login`.
1116///
1117/// The `type` discriminator value is `agent`.
1118#[serde_as]
1119#[skip_serializing_none]
1120#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1121#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1122#[serde(rename_all = "camelCase")]
1123#[non_exhaustive]
1124pub struct AuthMethodAgent {
1125    /// Unique identifier for this authentication method.
1126    pub method_id: AuthMethodId,
1127    /// Human-readable name of the authentication method, shown to users as plain text.
1128    pub name: String,
1129    /// Optional human-readable description of this authentication method.
1130    /// May contain Markdown.
1131    ///
1132    /// Omitted and `null` are equivalent and mean no description is provided.
1133    #[serde_as(deserialize_as = "DefaultOnError")]
1134    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1135    #[serde(default)]
1136    pub description: Option<String>,
1137    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1138    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1139    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1140    ///
1141    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1142    #[serde_as(deserialize_as = "DefaultOnError")]
1143    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1144    #[serde(default)]
1145    #[serde(rename = "_meta")]
1146    pub meta: Option<Meta>,
1147}
1148
1149impl AuthMethodAgent {
1150    /// Builds [`AuthMethodAgent`] with the required fields set. Optional fields start unset or empty.
1151    #[must_use]
1152    pub fn new(method_id: impl Into<AuthMethodId>, name: impl Into<String>) -> Self {
1153        Self {
1154            method_id: method_id.into(),
1155            name: name.into(),
1156            description: None,
1157            meta: None,
1158        }
1159    }
1160
1161    /// Optional human-readable description of this authentication method.
1162    /// May contain Markdown.
1163    #[must_use]
1164    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
1165        self.description = description.into_option();
1166        self
1167    }
1168
1169    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1170    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1171    /// do not recognize.
1172    ///
1173    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1174    #[must_use]
1175    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1176        self.meta = meta.into_option();
1177        self
1178    }
1179}
1180
1181/// Terminal-based authentication method.
1182///
1183/// The Client runs the configured Agent program as a separate interactive
1184/// process for the user to authenticate via a TUI. Agents MUST advertise this
1185/// method only when the Client enabled its terminal authentication capability.
1186/// A zero exit status signals success. Any other termination signals failure.
1187/// The Client MUST NOT pass this method to `auth/login`.
1188#[serde_as]
1189#[skip_serializing_none]
1190#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1191#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1192#[serde(rename_all = "camelCase")]
1193#[non_exhaustive]
1194pub struct AuthMethodTerminal {
1195    /// Unique identifier for this authentication method.
1196    pub method_id: AuthMethodId,
1197    /// Human-readable name of the authentication method, shown to users as plain text.
1198    pub name: String,
1199    /// Optional human-readable description of this authentication method.
1200    /// May contain Markdown.
1201    ///
1202    /// Omitted and `null` are equivalent and mean no description is provided.
1203    #[serde_as(deserialize_as = "DefaultOnError")]
1204    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1205    #[serde(default)]
1206    pub description: Option<String>,
1207    /// Additional arguments to append to the configured Agent invocation for terminal auth.
1208    #[serde_as(deserialize_as = "DefaultOnNull")]
1209    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1210    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1211    pub args: Vec<String>,
1212    /// Additional environment variables to set on the configured Agent invocation for terminal auth.
1213    /// Names SHOULD be unique, and otherwise the last entry wins. These values override
1214    /// same-named variables in the base launch configuration.
1215    #[serde_as(deserialize_as = "DefaultOnNull")]
1216    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1217    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1218    pub env: Vec<EnvVariable>,
1219    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1220    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1221    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1222    ///
1223    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1224    #[serde_as(deserialize_as = "DefaultOnError")]
1225    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1226    #[serde(default)]
1227    #[serde(rename = "_meta")]
1228    pub meta: Option<Meta>,
1229}
1230
1231impl AuthMethodTerminal {
1232    /// Builds [`AuthMethodTerminal`] with the required fields set. Optional fields start unset or empty.
1233    #[must_use]
1234    pub fn new(method_id: impl Into<AuthMethodId>, name: impl Into<String>) -> Self {
1235        Self {
1236            method_id: method_id.into(),
1237            name: name.into(),
1238            description: None,
1239            args: Vec::new(),
1240            env: Vec::new(),
1241            meta: None,
1242        }
1243    }
1244
1245    /// Additional arguments to append to the configured Agent invocation for terminal auth.
1246    #[must_use]
1247    pub fn args(mut self, args: Vec<String>) -> Self {
1248        self.args = args;
1249        self
1250    }
1251
1252    /// Additional environment variables to set on the configured Agent invocation for terminal auth.
1253    /// Names SHOULD be unique, and otherwise the last entry wins. These values override
1254    /// same-named variables in the base launch configuration.
1255    #[must_use]
1256    pub fn env(mut self, env: Vec<EnvVariable>) -> Self {
1257        self.env = env;
1258        self
1259    }
1260
1261    /// Optional human-readable description of this authentication method.
1262    /// May contain Markdown.
1263    #[must_use]
1264    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
1265        self.description = description.into_option();
1266        self
1267    }
1268
1269    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1270    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1271    /// do not recognize.
1272    ///
1273    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1274    #[must_use]
1275    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1276        self.meta = meta.into_option();
1277        self
1278    }
1279}
1280
1281// New session
1282
1283/// Request parameters for creating a new session.
1284///
1285/// See protocol docs: [Creating a Session](https://agentclientprotocol.com/protocol/v2/session-setup#creating-a-session)
1286#[serde_as]
1287#[skip_serializing_none]
1288#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1289#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1290#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_NEW_METHOD_NAME)))]
1291#[serde(rename_all = "camelCase")]
1292#[non_exhaustive]
1293pub struct NewSessionRequest {
1294    /// The working directory for this session. Must be an absolute path.
1295    pub cwd: AbsolutePath,
1296    /// Additional workspace roots for this session. Each path MUST be absolute.
1297    ///
1298    /// These expand the session's workspace scope without changing `cwd`, which
1299    /// remains the base for relative paths. When omitted or empty, no
1300    /// additional roots are activated for the new session.
1301    #[serde_as(deserialize_as = "DefaultOnNull")]
1302    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1303    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1304    pub additional_directories: Vec<AbsolutePath>,
1305    /// List of MCP (Model Context Protocol) servers for the Agent to connect to.
1306    #[serde_as(deserialize_as = "DefaultOnNull")]
1307    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1308    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1309    pub mcp_servers: Vec<McpServer>,
1310    /// System-level instructions for the new session.
1311    ///
1312    /// Optional. Omitted and `null` are equivalent and mean the Agent uses its
1313    /// own default instructions. Clients MUST only send this when the Agent
1314    /// advertises `session.systemPrompt`.
1315    #[serde(default)]
1316    pub system_prompt: Option<SystemPrompt>,
1317    /// **UNSTABLE**
1318    ///
1319    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1320    ///
1321    /// Initial values for the session's config options.
1322    ///
1323    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1324    /// this when the Agent advertises `session.options`.
1325    ///
1326    /// The Agent applies the entries in list order, as if the Client had called
1327    /// `session/set_config_option` for each entry after the session was set up. Malformed
1328    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1329    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1330    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1331    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries,
1332    /// and SHOULD NOT send other `session/update` notifications caused by applying them
1333    /// before it responds.
1334    #[cfg(feature = "unstable_session_options")]
1335    #[serde_as(deserialize_as = "DefaultOnNull")]
1336    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1337    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1338    pub config_options: Vec<InitialSessionConfigOption>,
1339    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1340    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1341    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1342    ///
1343    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1344    #[serde_as(deserialize_as = "DefaultOnError")]
1345    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1346    #[serde(default)]
1347    #[serde(rename = "_meta")]
1348    pub meta: Option<Meta>,
1349}
1350
1351impl NewSessionRequest {
1352    /// Builds [`NewSessionRequest`] with the required request fields set. Optional fields start unset or empty.
1353    #[must_use]
1354    pub fn new(cwd: impl Into<AbsolutePath>) -> Self {
1355        Self {
1356            cwd: cwd.into(),
1357            additional_directories: vec![],
1358            mcp_servers: vec![],
1359            system_prompt: None,
1360            #[cfg(feature = "unstable_session_options")]
1361            config_options: vec![],
1362            meta: None,
1363        }
1364    }
1365
1366    /// Additional workspace roots for this session. Each path MUST be absolute.
1367    #[must_use]
1368    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1369    where
1370        I: IntoIterator<Item = P>,
1371        P: Into<AbsolutePath>,
1372    {
1373        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1374        self
1375    }
1376
1377    /// List of MCP (Model Context Protocol) servers for the Agent to connect to.
1378    #[must_use]
1379    pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1380        self.mcp_servers = mcp_servers;
1381        self
1382    }
1383
1384    /// System-level instructions for the new session.
1385    #[must_use]
1386    pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1387        self.system_prompt = system_prompt.into_option();
1388        self
1389    }
1390
1391    /// **UNSTABLE**
1392    ///
1393    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1394    ///
1395    /// Initial values for the session's config options.
1396    ///
1397    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1398    /// this when the Agent advertises `session.options`.
1399    ///
1400    /// The Agent applies the entries in list order, as if the Client had called
1401    /// `session/set_config_option` for each entry after the session was set up. Malformed
1402    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1403    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1404    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1405    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries,
1406    /// and SHOULD NOT send other `session/update` notifications caused by applying them
1407    /// before it responds.
1408    #[cfg(feature = "unstable_session_options")]
1409    #[must_use]
1410    pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1411        self.config_options = config_options;
1412        self
1413    }
1414
1415    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1416    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1417    /// do not recognize.
1418    ///
1419    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1420    #[must_use]
1421    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1422        self.meta = meta.into_option();
1423        self
1424    }
1425}
1426
1427/// Response from creating a new session.
1428///
1429/// New sessions default to `idle` until a state update reports otherwise.
1430/// Updates may arrive before or after this response. Clients MUST NOT overwrite
1431/// an already-reported state when the response arrives.
1432///
1433/// An Agent whose new session is not `idle` MUST send the session's
1434/// `state_update` after this response.
1435///
1436/// See protocol docs: [Creating a Session](https://agentclientprotocol.com/protocol/v2/session-setup#creating-a-session)
1437#[serde_as]
1438#[skip_serializing_none]
1439#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1440#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1441#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_NEW_METHOD_NAME)))]
1442#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}, {"action": "replace", "target": "availableCommands", "value": "availableCommands"}]})))]
1443#[serde(rename_all = "camelCase")]
1444#[non_exhaustive]
1445pub struct NewSessionResponse {
1446    /// Unique identifier for the created session.
1447    ///
1448    /// Used in all subsequent requests for this conversation.
1449    pub session_id: SessionId,
1450    /// Initial session configuration options.
1451    ///
1452    /// Optional. Omitted or empty means no config options are advertised.
1453    /// Senders MUST use an array, not `null`.
1454    /// Later `config_option_update` notifications replace this list.
1455    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1456    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1457    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1458    pub config_options: Vec<SessionConfigOption>,
1459    /// Initial commands the Agent can execute in this session.
1460    ///
1461    /// Optional. Omitted or empty means no initial commands are advertised.
1462    /// Senders MUST use an array, not `null`.
1463    /// Later `available_commands_update` notifications replace this list.
1464    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1465    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1466    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1467    pub available_commands: Vec<AvailableCommand>,
1468    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1469    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1470    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1471    ///
1472    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1473    #[serde_as(deserialize_as = "DefaultOnError")]
1474    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1475    #[serde(default)]
1476    #[serde(rename = "_meta")]
1477    pub meta: Option<Meta>,
1478}
1479
1480impl NewSessionResponse {
1481    /// Builds [`NewSessionResponse`] with the required response fields set. Optional fields start unset or empty.
1482    #[must_use]
1483    pub fn new(session_id: impl Into<SessionId>) -> Self {
1484        Self {
1485            session_id: session_id.into(),
1486            config_options: Vec::new(),
1487            available_commands: Vec::new(),
1488            meta: None,
1489        }
1490    }
1491
1492    /// Initial session configuration options.
1493    ///
1494    /// Optional. Omitted or empty means no config options are advertised.
1495    /// Senders MUST use an array, not `null`.
1496    /// Later `config_option_update` notifications replace this list.
1497    #[must_use]
1498    pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
1499        self.config_options = config_options;
1500        self
1501    }
1502
1503    /// Initial commands the Agent can execute in this session.
1504    #[must_use]
1505    pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
1506        self.available_commands = available_commands;
1507        self
1508    }
1509
1510    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1511    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1512    /// do not recognize.
1513    ///
1514    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1515    #[must_use]
1516    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1517        self.meta = meta.into_option();
1518        self
1519    }
1520}
1521
1522// Fork session
1523
1524/// **UNSTABLE**
1525///
1526/// This capability is not part of the spec yet, and may be removed or changed at any point.
1527///
1528/// Request parameters for forking an existing session.
1529///
1530/// Creates a new session based on the context of an existing one. The fork can be used
1531/// for operations like generating summaries without affecting the original session's history.
1532///
1533/// Only available if the Agent supports the `session.fork` capability.
1534#[cfg(feature = "unstable_session_fork")]
1535#[serde_as]
1536#[skip_serializing_none]
1537#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1538#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1539#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_FORK_METHOD_NAME)))]
1540#[serde(rename_all = "camelCase")]
1541#[non_exhaustive]
1542pub struct ForkSessionRequest {
1543    /// The ID of the session to fork.
1544    pub session_id: SessionId,
1545    /// **UNSTABLE**
1546    ///
1547    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1548    ///
1549    /// The session cursor to fork at. The new session's history is the source
1550    /// session's history before the cursor.
1551    ///
1552    /// Optional. Omitted and `null` are equivalent and fork the whole session.
1553    /// Clients MUST only send the ID of a cursor that the Agent announced on the
1554    /// source session and that currently advertises `capabilities.fork`. The Agent
1555    /// rejects any other ID with `-32602`. It does not fall back to forking the
1556    /// whole session.
1557    #[cfg(feature = "unstable_session_cursors")]
1558    #[serde(default)]
1559    pub cursor_id: Option<CursorId>,
1560    /// The working directory for this session. Must be an absolute path.
1561    pub cwd: AbsolutePath,
1562    /// Additional workspace roots to activate for this session. Each path MUST be absolute.
1563    ///
1564    /// When omitted or empty, no additional roots are activated. When non-empty,
1565    /// this is the complete resulting additional-root list for the forked
1566    /// session.
1567    #[serde_as(deserialize_as = "DefaultOnNull")]
1568    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1569    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1570    pub additional_directories: Vec<AbsolutePath>,
1571    /// List of MCP servers to connect to for this session.
1572    #[serde_as(deserialize_as = "DefaultOnNull")]
1573    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1574    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1575    pub mcp_servers: Vec<McpServer>,
1576    /// System-level instructions for the forked session.
1577    ///
1578    /// Optional. Omitted and `null` are equivalent. The Agent MAY then keep a
1579    /// system prompt it stored with the source session or use its default
1580    /// instructions. Clients MUST only send this when the Agent advertises
1581    /// `session.systemPrompt`, and SHOULD send the same value they used for the
1582    /// source session.
1583    #[serde(default)]
1584    pub system_prompt: Option<SystemPrompt>,
1585    /// **UNSTABLE**
1586    ///
1587    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1588    ///
1589    /// Initial values for the forked session's config options.
1590    ///
1591    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1592    /// this when the Agent advertises `session.options`.
1593    ///
1594    /// The Agent applies the entries in list order on top of the configuration the fork
1595    /// starts with, as if the Client had called `session/set_config_option` for each entry
1596    /// after the session was set up. Malformed entries and duplicate `configId` values fail
1597    /// the request with `-32602`. The Agent MUST ignore an entry whose `configId` is unknown,
1598    /// whose `type` does not match the option, or whose value is not allowed when it is
1599    /// applied. The `configOptions` in the response contain the values the session actually
1600    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries,
1601    /// and SHOULD NOT send other `session/update` notifications caused by applying them
1602    /// before it responds.
1603    #[cfg(feature = "unstable_session_options")]
1604    #[serde_as(deserialize_as = "DefaultOnNull")]
1605    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1606    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1607    pub config_options: Vec<InitialSessionConfigOption>,
1608    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1609    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1610    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1611    ///
1612    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1613    #[serde_as(deserialize_as = "DefaultOnError")]
1614    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1615    #[serde(default)]
1616    #[serde(rename = "_meta")]
1617    pub meta: Option<Meta>,
1618}
1619
1620#[cfg(feature = "unstable_session_fork")]
1621impl ForkSessionRequest {
1622    /// Builds [`ForkSessionRequest`] with the required request fields set. Optional fields start unset or empty.
1623    #[must_use]
1624    pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
1625        Self {
1626            session_id: session_id.into(),
1627            #[cfg(feature = "unstable_session_cursors")]
1628            cursor_id: None,
1629            cwd: cwd.into(),
1630            additional_directories: vec![],
1631            mcp_servers: vec![],
1632            system_prompt: None,
1633            #[cfg(feature = "unstable_session_options")]
1634            config_options: vec![],
1635            meta: None,
1636        }
1637    }
1638
1639    /// **UNSTABLE**
1640    ///
1641    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1642    ///
1643    /// The session cursor to fork at. Omitting it forks the whole session.
1644    ///
1645    /// Clients MUST only send the ID of a cursor that the Agent announced on the
1646    /// source session and that currently advertises `capabilities.fork`.
1647    #[cfg(feature = "unstable_session_cursors")]
1648    #[must_use]
1649    pub fn cursor_id(mut self, cursor_id: impl IntoOption<CursorId>) -> Self {
1650        self.cursor_id = cursor_id.into_option();
1651        self
1652    }
1653
1654    /// Additional workspace roots to activate for this session. Each path MUST be absolute.
1655    #[must_use]
1656    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1657    where
1658        I: IntoIterator<Item = P>,
1659        P: Into<AbsolutePath>,
1660    {
1661        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1662        self
1663    }
1664
1665    /// List of MCP servers to connect to for this session.
1666    #[must_use]
1667    pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1668        self.mcp_servers = mcp_servers;
1669        self
1670    }
1671
1672    /// System-level instructions for the forked session.
1673    #[must_use]
1674    pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1675        self.system_prompt = system_prompt.into_option();
1676        self
1677    }
1678
1679    /// **UNSTABLE**
1680    ///
1681    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1682    ///
1683    /// Initial values for the forked session's config options.
1684    ///
1685    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1686    /// this when the Agent advertises `session.options`.
1687    ///
1688    /// The Agent applies the entries in list order on top of the configuration the fork
1689    /// starts with, as if the Client had called `session/set_config_option` for each entry
1690    /// after the session was set up. Malformed entries and duplicate `configId` values fail
1691    /// the request with `-32602`. The Agent MUST ignore an entry whose `configId` is unknown,
1692    /// whose `type` does not match the option, or whose value is not allowed when it is
1693    /// applied. The `configOptions` in the response contain the values the session actually
1694    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries,
1695    /// and SHOULD NOT send other `session/update` notifications caused by applying them
1696    /// before it responds.
1697    #[cfg(feature = "unstable_session_options")]
1698    #[must_use]
1699    pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1700        self.config_options = config_options;
1701        self
1702    }
1703
1704    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1705    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1706    /// do not recognize.
1707    ///
1708    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1709    #[must_use]
1710    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1711        self.meta = meta.into_option();
1712        self
1713    }
1714}
1715
1716/// **UNSTABLE**
1717///
1718/// This capability is not part of the spec yet, and may be removed or changed at any point.
1719///
1720/// Response from forking an existing session.
1721#[cfg(feature = "unstable_session_fork")]
1722#[serde_as]
1723#[skip_serializing_none]
1724#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1725#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1726#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_FORK_METHOD_NAME)))]
1727#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}, {"action": "replace", "target": "availableCommands", "value": "availableCommands"}]})))]
1728#[serde(rename_all = "camelCase")]
1729#[non_exhaustive]
1730pub struct ForkSessionResponse {
1731    /// Unique identifier for the newly created forked session.
1732    pub session_id: SessionId,
1733    /// Initial session configuration options.
1734    ///
1735    /// Optional. Omitted or empty means no config options are advertised.
1736    /// Senders MUST use an array, not `null`.
1737    /// Later `config_option_update` notifications replace this list.
1738    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1739    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1740    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1741    pub config_options: Vec<SessionConfigOption>,
1742    /// Initial commands the Agent can execute in this session.
1743    ///
1744    /// Optional. Omitted or empty means no initial commands are advertised.
1745    /// Senders MUST use an array, not `null`.
1746    /// Later `available_commands_update` notifications replace this list.
1747    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1748    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1749    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1750    pub available_commands: Vec<AvailableCommand>,
1751    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1752    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1753    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1754    ///
1755    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1756    #[serde_as(deserialize_as = "DefaultOnError")]
1757    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1758    #[serde(default)]
1759    #[serde(rename = "_meta")]
1760    pub meta: Option<Meta>,
1761}
1762
1763#[cfg(feature = "unstable_session_fork")]
1764impl ForkSessionResponse {
1765    /// Builds [`ForkSessionResponse`] with the required response fields set. Optional fields start unset or empty.
1766    #[must_use]
1767    pub fn new(session_id: impl Into<SessionId>) -> Self {
1768        Self {
1769            session_id: session_id.into(),
1770            config_options: Vec::new(),
1771            available_commands: Vec::new(),
1772            meta: None,
1773        }
1774    }
1775
1776    /// Initial session configuration options.
1777    ///
1778    /// Optional. Omitted or empty means no config options are advertised.
1779    /// Senders MUST use an array, not `null`.
1780    /// Later `config_option_update` notifications replace this list.
1781    #[must_use]
1782    pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
1783        self.config_options = config_options;
1784        self
1785    }
1786
1787    /// Initial commands the Agent can execute in this session.
1788    #[must_use]
1789    pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
1790        self.available_commands = available_commands;
1791        self
1792    }
1793
1794    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1795    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1796    /// do not recognize.
1797    ///
1798    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1799    #[must_use]
1800    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1801        self.meta = meta.into_option();
1802        self
1803    }
1804}
1805
1806// Resume session
1807
1808/// Request parameters for resuming an existing session.
1809///
1810/// Resumes an existing session and optionally replays retained conversation
1811/// history according to `replayFrom`.
1812#[serde_as]
1813#[skip_serializing_none]
1814#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1815#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1816#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_RESUME_METHOD_NAME)))]
1817#[serde(rename_all = "camelCase")]
1818#[non_exhaustive]
1819pub struct ResumeSessionRequest {
1820    /// The ID of the session to resume.
1821    pub session_id: SessionId,
1822    /// The working directory for this session. Must be an absolute path.
1823    ///
1824    /// Clients MUST send the session's working directory. Agents MAY reject a different directory
1825    /// with `-32602`, and MAY normalize paths when comparing.
1826    pub cwd: AbsolutePath,
1827    /// Additional workspace roots to activate for this session. Each path MUST be absolute.
1828    ///
1829    /// When omitted or empty, no additional roots are activated. When non-empty,
1830    /// this is the complete resulting additional-root list for the resumed
1831    /// session. It MAY differ from any previously used or reported list as long as
1832    /// the request `cwd` matches the session's `cwd`.
1833    #[serde_as(deserialize_as = "DefaultOnNull")]
1834    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1835    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1836    pub additional_directories: Vec<AbsolutePath>,
1837    /// List of MCP servers to connect to for this session.
1838    ///
1839    /// The complete set of Client-provided servers. Omitted and `[]` mean none. Agents SHOULD
1840    /// NOT restore servers from earlier requests.
1841    #[serde_as(deserialize_as = "DefaultOnNull")]
1842    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1843    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1844    pub mcp_servers: Vec<McpServer>,
1845    /// Inclusive cursor describing where conversation replay begins.
1846    ///
1847    /// Optional. Omitted and `null` are equivalent, and the Agent MUST NOT replay
1848    /// previous conversation history. Replay cursors are inclusive:
1849    /// replay includes the position identified by the cursor. Supplying
1850    /// `{ "type": "start" }` means the Agent MUST replay all retained
1851    /// conversation history before responding.
1852    ///
1853    /// Agents MUST reject unsupported cursor types or malformed cursor values
1854    /// with `-32602` (Invalid params), rather than substituting another cursor
1855    /// or resuming without replay.
1856    #[serde(default)]
1857    pub replay_from: Option<ReplayFrom>,
1858    /// System-level instructions for the resumed session.
1859    ///
1860    /// Optional. Omitted and `null` are equivalent. The Agent MAY then keep a
1861    /// system prompt it stored with the session or use its default instructions.
1862    /// Clients MUST only send this when the Agent advertises
1863    /// `session.systemPrompt`, and SHOULD send the same value they used when the
1864    /// session was created.
1865    #[serde(default)]
1866    pub system_prompt: Option<SystemPrompt>,
1867    /// **UNSTABLE**
1868    ///
1869    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1870    ///
1871    /// Initial values for the session's config options.
1872    ///
1873    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1874    /// this when the Agent advertises `session.options`.
1875    ///
1876    /// The Agent applies the entries in list order, as if the Client had called
1877    /// `session/set_config_option` for each entry after the session was set up. Malformed
1878    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1879    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1880    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1881    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries
1882    /// on the requesting connection. If the session is active on other connections, the
1883    /// Agent SHOULD send `config_option_update` on those connections.
1884    ///
1885    /// The Agent applies the entries before it replays history for `replayFrom` and before
1886    /// it responds.
1887    #[cfg(feature = "unstable_session_options")]
1888    #[serde_as(deserialize_as = "DefaultOnNull")]
1889    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1890    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1891    pub config_options: Vec<InitialSessionConfigOption>,
1892    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1893    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1894    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1895    ///
1896    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1897    #[serde_as(deserialize_as = "DefaultOnError")]
1898    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1899    #[serde(default)]
1900    #[serde(rename = "_meta")]
1901    pub meta: Option<Meta>,
1902}
1903
1904impl ResumeSessionRequest {
1905    /// Builds [`ResumeSessionRequest`] with the required request fields set. Optional fields start unset or empty.
1906    #[must_use]
1907    pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
1908        Self {
1909            session_id: session_id.into(),
1910            cwd: cwd.into(),
1911            additional_directories: vec![],
1912            mcp_servers: vec![],
1913            replay_from: None,
1914            system_prompt: None,
1915            #[cfg(feature = "unstable_session_options")]
1916            config_options: vec![],
1917            meta: None,
1918        }
1919    }
1920
1921    /// Additional workspace roots to activate for this session. Each path MUST be absolute.
1922    #[must_use]
1923    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1924    where
1925        I: IntoIterator<Item = P>,
1926        P: Into<AbsolutePath>,
1927    {
1928        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1929        self
1930    }
1931
1932    /// List of MCP servers to connect to for this session.
1933    #[must_use]
1934    pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1935        self.mcp_servers = mcp_servers;
1936        self
1937    }
1938
1939    /// Inclusive cursor describing where conversation replay begins.
1940    ///
1941    /// Omitted and `null` are equivalent, and the Agent MUST NOT replay
1942    /// previous conversation history. Replay cursors are inclusive: replay
1943    /// includes the position identified by the cursor. Supplying
1944    /// `{ "type": "start" }` means the Agent MUST replay all retained
1945    /// conversation history before responding.
1946    #[must_use]
1947    pub fn replay_from(mut self, replay_from: impl IntoOption<ReplayFrom>) -> Self {
1948        self.replay_from = replay_from.into_option();
1949        self
1950    }
1951
1952    /// System-level instructions for the resumed session.
1953    #[must_use]
1954    pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1955        self.system_prompt = system_prompt.into_option();
1956        self
1957    }
1958
1959    /// **UNSTABLE**
1960    ///
1961    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1962    ///
1963    /// Initial values for the session's config options.
1964    ///
1965    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1966    /// this when the Agent advertises `session.options`.
1967    ///
1968    /// The Agent applies the entries in list order, as if the Client had called
1969    /// `session/set_config_option` for each entry after the session was set up. Malformed
1970    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1971    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1972    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1973    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries
1974    /// on the requesting connection. If the session is active on other connections, the
1975    /// Agent SHOULD send `config_option_update` on those connections.
1976    #[cfg(feature = "unstable_session_options")]
1977    #[must_use]
1978    pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1979        self.config_options = config_options;
1980        self
1981    }
1982
1983    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1984    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1985    /// do not recognize.
1986    ///
1987    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1988    #[must_use]
1989    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1990        self.meta = meta.into_option();
1991        self
1992    }
1993}
1994
1995/// Inclusive cursor describing where replayed session history begins.
1996///
1997/// Replay includes the position identified by the cursor.
1998#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1999#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2000#[serde(tag = "type", rename_all = "snake_case")]
2001#[non_exhaustive]
2002pub enum ReplayFrom {
2003    /// Replay all retained conversation history from its first replayable entry.
2004    Start(ReplayFromStart),
2005    /// Custom or future replay cursor.
2006    ///
2007    /// Values beginning with `_` are reserved for implementation-specific
2008    /// extensions. Unknown values that do not begin with `_` are reserved for
2009    /// future ACP variants.
2010    ///
2011    /// Intermediaries SHOULD preserve the raw payload when storing, replaying,
2012    /// proxying, or forwarding requests. Agents that do not support this cursor
2013    /// MUST reject the request with `-32602` (Invalid params), rather than
2014    /// substituting another cursor or resuming without replay.
2015    #[serde(untagged)]
2016    Other(OtherReplayFrom),
2017}
2018
2019impl From<ReplayFromStart> for ReplayFrom {
2020    fn from(replay_from: ReplayFromStart) -> Self {
2021        Self::Start(replay_from)
2022    }
2023}
2024
2025/// Inclusive replay cursor requesting replay from the start of retained conversation history.
2026#[serde_as]
2027#[skip_serializing_none]
2028#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2029#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2030#[serde(rename_all = "camelCase")]
2031#[non_exhaustive]
2032pub struct ReplayFromStart {
2033    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2034    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2035    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2036    ///
2037    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2038    #[serde_as(deserialize_as = "DefaultOnError")]
2039    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2040    #[serde(default)]
2041    #[serde(rename = "_meta")]
2042    pub meta: Option<Meta>,
2043}
2044
2045impl ReplayFromStart {
2046    /// Builds [`ReplayFromStart`].
2047    #[must_use]
2048    pub fn new() -> Self {
2049        Self::default()
2050    }
2051
2052    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2053    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2054    /// do not recognize.
2055    ///
2056    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2057    #[must_use]
2058    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2059        self.meta = meta.into_option();
2060        self
2061    }
2062}
2063
2064/// Custom or future replay cursor payload.
2065#[serde_as]
2066#[skip_serializing_none]
2067#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2068#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
2069#[cfg_attr(feature = "schemars", schemars(inline))]
2070#[cfg_attr(feature = "schemars", schemars(transform = other_replay_from_schema))]
2071#[serde(rename_all = "camelCase")]
2072#[non_exhaustive]
2073pub struct OtherReplayFrom {
2074    /// Custom or future replay cursor type.
2075    ///
2076    /// Values beginning with `_` are reserved for implementation-specific
2077    /// extensions. Unknown values that do not begin with `_` are reserved for
2078    /// future ACP variants.
2079    #[serde(rename = "type")]
2080    pub type_: String,
2081    /// The remaining fields of the unknown replay cursor payload, preserved verbatim,
2082    /// including `_meta`.
2083    #[serde(flatten)]
2084    pub fields: IndexMap<String, serde_json::Value>,
2085}
2086
2087impl OtherReplayFrom {
2088    /// Builds [`OtherReplayFrom`] from an unknown discriminator and preserves the remaining extension fields.
2089    #[must_use]
2090    pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
2091        fields.shift_remove("type");
2092        Self {
2093            type_: type_.into(),
2094            fields,
2095        }
2096    }
2097}
2098
2099impl<'de> Deserialize<'de> for OtherReplayFrom {
2100    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2101    where
2102        D: serde::Deserializer<'de>,
2103    {
2104        let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
2105        let type_ = fields
2106            .shift_remove("type")
2107            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
2108        let serde_json::Value::String(type_) = type_ else {
2109            return Err(serde::de::Error::custom("`type` must be a string"));
2110        };
2111
2112        if is_known_replay_from_type(&type_) {
2113            return Err(serde::de::Error::custom(format!(
2114                "known replay cursor `{type_}` did not match its schema"
2115            )));
2116        }
2117
2118        Ok(Self { type_, fields })
2119    }
2120}
2121
2122fn is_known_replay_from_type(type_: &str) -> bool {
2123    matches!(type_, "start")
2124}
2125
2126#[cfg(feature = "schemars")]
2127fn other_replay_from_schema(schema: &mut Schema) {
2128    super::schema_util::reject_known_string_discriminators(schema, "type", &["start"]);
2129}
2130
2131crate::serde_util::default_on_null! {
2132    /// Response from resuming an existing session.
2133    ///
2134    /// The Agent MUST send a current `state_update` after any requested history
2135    /// replay and before this response, even without replay. The update reports
2136    /// foreground state after resuming. The response alone does not imply `idle`.
2137    ///
2138    /// See protocol docs: [Current-State Synchronization](https://agentclientprotocol.com/protocol/v2/session-setup#current-state-synchronization)
2139    #[serde_as]
2140    #[skip_serializing_none]
2141    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2142    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2143    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_RESUME_METHOD_NAME)))]
2144    #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}, {"action": "replace", "target": "availableCommands", "value": "availableCommands"}]})))]
2145    #[serde(rename_all = "camelCase")]
2146    #[non_exhaustive]
2147    pub struct ResumeSessionResponse {
2148        /// Current session configuration options.
2149        ///
2150        /// Optional. Omitted or empty means no config options are advertised.
2151        /// Senders MUST use an array, not `null`.
2152        /// Later `config_option_update` notifications replace this list.
2153        #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2154        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2155        #[serde(default, skip_serializing_if = "Vec::is_empty")]
2156        pub config_options: Vec<SessionConfigOption>,
2157        /// Current commands the Agent can execute in this session.
2158        ///
2159        /// Optional. Omitted or empty means no initial commands are advertised.
2160        /// Senders MUST use an array, not `null`.
2161        /// Later `available_commands_update` notifications replace this list.
2162        #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2163        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2164        #[serde(default, skip_serializing_if = "Vec::is_empty")]
2165        pub available_commands: Vec<AvailableCommand>,
2166        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2167        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2168        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2169        ///
2170        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2171        #[serde_as(deserialize_as = "DefaultOnError")]
2172        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2173        #[serde(default)]
2174        #[serde(rename = "_meta")]
2175        pub meta: Option<Meta>,
2176    }
2177}
2178
2179impl ResumeSessionResponse {
2180    /// Builds [`ResumeSessionResponse`] with the required response fields set. Optional fields start unset or empty.
2181    #[must_use]
2182    pub fn new() -> Self {
2183        Self::default()
2184    }
2185
2186    /// Current session configuration options.
2187    ///
2188    /// Optional. Omitted or empty means no config options are advertised.
2189    /// Senders MUST use an array, not `null`.
2190    /// Later `config_option_update` notifications replace this list.
2191    #[must_use]
2192    pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
2193        self.config_options = config_options;
2194        self
2195    }
2196
2197    /// Current commands the Agent can execute in this session.
2198    #[must_use]
2199    pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
2200        self.available_commands = available_commands;
2201        self
2202    }
2203
2204    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2205    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2206    /// do not recognize.
2207    ///
2208    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2209    #[must_use]
2210    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2211        self.meta = meta.into_option();
2212        self
2213    }
2214}
2215
2216// Close session
2217
2218/// Request parameters for closing an active session.
2219///
2220/// The Agent MUST cancel any ongoing work related to the session as if `session/cancel`
2221/// was called, then free the resources associated with the session. Unlike `session/cancel`,
2222/// closing also stops the session's background work. After the close response, the Agent
2223/// sends no notifications or requests for the session on that connection. It still
2224/// answers `session/prompt` requests that were pending.
2225///
2226/// Closing a session that does not exist or is not active SHOULD succeed, and Clients SHOULD
2227/// treat a `-32002` response as a successful close.
2228///
2229/// When closing cancels active foreground work, the Agent MUST send the final
2230/// updates for that work and the idle `state_update` with `stopReason: "cancelled"`
2231/// before responding successfully to `session/close`. Closing an idle session
2232/// does not itself require another idle update.
2233///
2234/// Closing also cancels pending `session/prompt` requests whose messages have not
2235/// been inserted, including held prompts. If closing prevents a prompt's user message from being inserted, the
2236/// Agent MUST answer that request with `-32800` (Request cancelled). If the message
2237/// has already been inserted, the Agent MUST respond successfully with its
2238/// `messageId`. Prompt responses need not precede the close response.
2239#[serde_as]
2240#[skip_serializing_none]
2241#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2242#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2243#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CLOSE_METHOD_NAME)))]
2244#[serde(rename_all = "camelCase")]
2245#[non_exhaustive]
2246pub struct CloseSessionRequest {
2247    /// The ID of the session to close.
2248    pub session_id: SessionId,
2249    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2250    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2251    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2252    ///
2253    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2254    #[serde_as(deserialize_as = "DefaultOnError")]
2255    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2256    #[serde(default)]
2257    #[serde(rename = "_meta")]
2258    pub meta: Option<Meta>,
2259}
2260
2261impl CloseSessionRequest {
2262    /// Builds [`CloseSessionRequest`] with the required request fields set. Optional fields start unset or empty.
2263    #[must_use]
2264    pub fn new(session_id: impl Into<SessionId>) -> Self {
2265        Self {
2266            session_id: session_id.into(),
2267            meta: None,
2268        }
2269    }
2270
2271    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2272    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2273    /// do not recognize.
2274    ///
2275    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2276    #[must_use]
2277    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2278        self.meta = meta.into_option();
2279        self
2280    }
2281}
2282
2283crate::serde_util::default_on_null! {
2284    /// Response from closing a session.
2285    #[serde_as]
2286    #[skip_serializing_none]
2287    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2288    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2289    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CLOSE_METHOD_NAME)))]
2290    #[serde(rename_all = "camelCase")]
2291    #[non_exhaustive]
2292    pub struct CloseSessionResponse {
2293        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2294        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2295        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2296        ///
2297        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2298        #[serde_as(deserialize_as = "DefaultOnError")]
2299        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2300        #[serde(default)]
2301        #[serde(rename = "_meta")]
2302        pub meta: Option<Meta>,
2303    }
2304}
2305
2306impl CloseSessionResponse {
2307    /// Builds [`CloseSessionResponse`] with the required response fields set. Optional fields start unset or empty.
2308    #[must_use]
2309    pub fn new() -> Self {
2310        Self::default()
2311    }
2312
2313    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2314    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2315    /// do not recognize.
2316    ///
2317    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2318    #[must_use]
2319    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2320        self.meta = meta.into_option();
2321        self
2322    }
2323}
2324
2325// Session status
2326
2327/// **UNSTABLE**
2328///
2329/// This capability is not part of the spec yet, and may be removed or changed at any point.
2330///
2331/// Request parameters for checking the status of a session.
2332///
2333/// Only available if the Agent supports the `session.status` capability.
2334///
2335/// `session/status` MUST NOT have side effects. The Agent does not resume, create,
2336/// close, or change the session, and does not attach the requesting connection to it.
2337/// A session the Agent does not know gets `-32002` with the requested `sessionId` in `data`.
2338#[cfg(feature = "unstable_session_status")]
2339#[serde_as]
2340#[skip_serializing_none]
2341#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2342#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2343#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_STATUS_METHOD_NAME)))]
2344#[serde(rename_all = "camelCase")]
2345#[non_exhaustive]
2346pub struct SessionStatusRequest {
2347    /// The ID of the session to check.
2348    pub session_id: SessionId,
2349    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2350    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2351    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2352    ///
2353    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2354    #[serde_as(deserialize_as = "DefaultOnError")]
2355    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2356    #[serde(default)]
2357    #[serde(rename = "_meta")]
2358    pub meta: Option<Meta>,
2359}
2360
2361#[cfg(feature = "unstable_session_status")]
2362impl SessionStatusRequest {
2363    /// Builds [`SessionStatusRequest`] with the required request fields set. Optional fields start unset or empty.
2364    #[must_use]
2365    pub fn new(session_id: impl Into<SessionId>) -> Self {
2366        Self {
2367            session_id: session_id.into(),
2368            meta: None,
2369        }
2370    }
2371
2372    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2373    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2374    /// do not recognize.
2375    ///
2376    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2377    #[must_use]
2378    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2379        self.meta = meta.into_option();
2380        self
2381    }
2382}
2383
2384/// **UNSTABLE**
2385///
2386/// This capability is not part of the spec yet, and may be removed or changed at any point.
2387///
2388/// Response from checking the status of a session.
2389///
2390/// The result is a snapshot. A session reported `open` may be closed or evicted before
2391/// the Client's next request.
2392#[cfg(feature = "unstable_session_status")]
2393#[serde_as]
2394#[skip_serializing_none]
2395#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2396#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2397#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_STATUS_METHOD_NAME)))]
2398#[serde(rename_all = "camelCase")]
2399#[non_exhaustive]
2400pub struct SessionStatusResponse {
2401    /// Whether the Agent has the session in memory.
2402    ///
2403    /// Required. Clients MUST treat a value they do not recognize as `saved`.
2404    pub status: SessionStatus,
2405    /// The session's current foreground state, as the same snapshot the Agent sends in
2406    /// `state_update` notifications.
2407    ///
2408    /// Optional. Agents SHOULD include it when `status` is `open`. Omitted and `null`
2409    /// mean the Agent is not reporting foreground state, and Clients
2410    /// MUST NOT read that as `idle`. This is a snapshot, not a new transition. Clients
2411    /// MUST NOT count an `idle` snapshot as a new completion.
2412    #[serde_as(deserialize_as = "DefaultOnError")]
2413    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2414    #[serde(default)]
2415    pub state: Option<StateUpdate>,
2416    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2417    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2418    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2419    ///
2420    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2421    #[serde_as(deserialize_as = "DefaultOnError")]
2422    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2423    #[serde(default)]
2424    #[serde(rename = "_meta")]
2425    pub meta: Option<Meta>,
2426}
2427
2428#[cfg(feature = "unstable_session_status")]
2429impl SessionStatusResponse {
2430    /// Builds [`SessionStatusResponse`] with the required response fields set. Optional fields start unset or empty.
2431    #[must_use]
2432    pub fn new(status: SessionStatus) -> Self {
2433        Self {
2434            status,
2435            state: None,
2436            meta: None,
2437        }
2438    }
2439
2440    /// The session's current foreground state, as the same snapshot the Agent sends in
2441    /// `state_update` notifications.
2442    #[must_use]
2443    pub fn state(mut self, state: impl IntoOption<StateUpdate>) -> Self {
2444        self.state = state.into_option();
2445        self
2446    }
2447
2448    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2449    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2450    /// do not recognize.
2451    ///
2452    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2453    #[must_use]
2454    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2455        self.meta = meta.into_option();
2456        self
2457    }
2458}
2459
2460/// **UNSTABLE**
2461///
2462/// This capability is not part of the spec yet, and may be removed or changed at any point.
2463///
2464/// Whether the Agent has a session in memory, as reported by `session/status`.
2465#[cfg(feature = "unstable_session_status")]
2466#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2467#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2468#[serde(rename_all = "snake_case")]
2469#[non_exhaustive]
2470pub enum SessionStatus {
2471    /// The Agent has the session in memory, for any connection.
2472    ///
2473    /// This does not mean the requesting connection is attached to it. A Client that did
2474    /// not create or resume the session on its own connection MUST still call
2475    /// `session/resume` before sending `session/prompt` or expecting
2476    /// `session/update` notifications.
2477    Open,
2478    /// The Agent knows the session and can resume it, but does not have it in memory.
2479    ///
2480    /// The Client can call `session/resume` to start it.
2481    Saved,
2482    /// Custom or future session status.
2483    ///
2484    /// Values beginning with `_` are reserved for implementation-specific
2485    /// extensions. Unknown values that do not begin with `_` are reserved for
2486    /// future ACP variants. Clients MUST treat a value they do not recognize as
2487    /// `saved`.
2488    #[serde(untagged)]
2489    Other(String),
2490}
2491
2492/// **UNSTABLE**
2493///
2494/// This capability is not part of the spec yet, and may be removed or changed at any point.
2495///
2496/// Request parameters for `session/options`, which returns the config options a session
2497/// would start with, without creating or resuming a session.
2498///
2499/// Only available if the Agent supports the `session.options` capability.
2500///
2501/// `session/options` MUST NOT create or resume a session, send `session/update`
2502/// notifications, add an entry to `session/list`, or change an existing session. Agents
2503/// SHOULD NOT connect to MCP servers to answer it. Agents MAY start their runtime to resolve
2504/// the options. The rules above still hold for it.
2505#[cfg(feature = "unstable_session_options")]
2506#[serde_as]
2507#[skip_serializing_none]
2508#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2509#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2510#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_OPTIONS_METHOD_NAME)))]
2511#[serde(rename_all = "camelCase")]
2512#[non_exhaustive]
2513pub struct SessionOptionsRequest {
2514    /// The working directory to resolve options for. Must be an absolute path.
2515    pub cwd: AbsolutePath,
2516    /// Additional workspace roots to resolve options for. Each path MUST be absolute.
2517    ///
2518    /// Optional. Omitted and `null` are equivalent to an empty list.
2519    #[serde_as(deserialize_as = "DefaultOnNull")]
2520    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
2521    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2522    pub additional_directories: Vec<AbsolutePath>,
2523    /// The session to resolve options for.
2524    ///
2525    /// Optional. Omitted and `null` are equivalent and mean a new session. When present,
2526    /// the Agent returns what `session/resume` with the same `cwd` and
2527    /// `additionalDirectories` would return, with the same `cwd` rules. A session the
2528    /// Agent does not know gets `-32002`.
2529    #[serde(default)]
2530    pub session_id: Option<SessionId>,
2531    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2532    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2533    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2534    ///
2535    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2536    #[serde_as(deserialize_as = "DefaultOnError")]
2537    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2538    #[serde(default)]
2539    #[serde(rename = "_meta")]
2540    pub meta: Option<Meta>,
2541}
2542
2543#[cfg(feature = "unstable_session_options")]
2544impl SessionOptionsRequest {
2545    /// Builds [`SessionOptionsRequest`] with the required request fields set. Optional fields start unset or empty.
2546    #[must_use]
2547    pub fn new(cwd: impl Into<AbsolutePath>) -> Self {
2548        Self {
2549            cwd: cwd.into(),
2550            additional_directories: vec![],
2551            session_id: None,
2552            meta: None,
2553        }
2554    }
2555
2556    /// Additional workspace roots to resolve options for. Each path MUST be absolute.
2557    #[must_use]
2558    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
2559    where
2560        I: IntoIterator<Item = P>,
2561        P: Into<AbsolutePath>,
2562    {
2563        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
2564        self
2565    }
2566
2567    /// The session to resolve options for. Unset means a new session.
2568    #[must_use]
2569    pub fn session_id(mut self, session_id: impl IntoOption<SessionId>) -> Self {
2570        self.session_id = session_id.into_option();
2571        self
2572    }
2573
2574    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2575    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2576    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2577    ///
2578    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2579    #[must_use]
2580    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2581        self.meta = meta.into_option();
2582        self
2583    }
2584}
2585
2586#[cfg(feature = "unstable_session_options")]
2587crate::serde_util::default_on_null! {
2588    /// **UNSTABLE**
2589    ///
2590    /// This capability is not part of the spec yet, and may be removed or changed at any point.
2591    ///
2592    /// Response from `session/options`.
2593    ///
2594    /// The result is a snapshot. The options a session actually starts with are the ones in
2595    /// the session setup response.
2596    #[serde_as]
2597    #[skip_serializing_none]
2598    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2599    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2600    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_OPTIONS_METHOD_NAME)))]
2601    #[serde(rename_all = "camelCase")]
2602    #[non_exhaustive]
2603    pub struct SessionOptionsResponse {
2604        /// The config options the session would start with, with the same rules as on
2605        /// `NewSessionResponse`.
2606        ///
2607        /// Optional. Omitted or empty means no config options are advertised.
2608        /// Senders MUST use an array, not `null`.
2609        #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2610        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2611        #[serde(default, skip_serializing_if = "Vec::is_empty")]
2612        pub config_options: Vec<SessionConfigOption>,
2613        /// Commands the Agent knows the session would have.
2614        ///
2615        /// Optional. Omitted or empty means no commands are advertised.
2616        /// Senders MUST use an array, not `null`.
2617        ///
2618        /// Advisory. Agents MAY return a partial list. Clients MUST use the commands from the
2619        /// `session/new` or `session/resume` response and later `available_commands_update`
2620        /// notifications for the session itself.
2621        #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2622        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2623        #[serde(default, skip_serializing_if = "Vec::is_empty")]
2624        pub available_commands: Vec<AvailableCommand>,
2625        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2626        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2627        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2628        ///
2629        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2630        #[serde_as(deserialize_as = "DefaultOnError")]
2631        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2632        #[serde(default)]
2633        #[serde(rename = "_meta")]
2634        pub meta: Option<Meta>,
2635    }
2636}
2637
2638#[cfg(feature = "unstable_session_options")]
2639impl SessionOptionsResponse {
2640    /// Builds [`SessionOptionsResponse`] with the required response fields set. Optional fields start unset or empty.
2641    #[must_use]
2642    pub fn new() -> Self {
2643        Self::default()
2644    }
2645
2646    /// The config options the session would start with.
2647    #[must_use]
2648    pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
2649        self.config_options = config_options;
2650        self
2651    }
2652
2653    /// Commands the Agent knows the session would have. Advisory.
2654    #[must_use]
2655    pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
2656        self.available_commands = available_commands;
2657        self
2658    }
2659
2660    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2661    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2662    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2663    ///
2664    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2665    #[must_use]
2666    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2667        self.meta = meta.into_option();
2668        self
2669    }
2670}
2671
2672/// **UNSTABLE**
2673///
2674/// This capability is not part of the spec yet, and may be removed or changed at any point.
2675///
2676/// An initial value for a config option, sent on session setup requests.
2677///
2678/// Same shape as `session/set_config_option` without `sessionId`. Unlike
2679/// `session/set_config_option`, an unknown `configId`, a `type` that does not match the
2680/// option, or a value that is not allowed is ignored instead of rejected.
2681#[cfg(feature = "unstable_session_options")]
2682#[serde_as]
2683#[skip_serializing_none]
2684#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2685#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2686#[serde(rename_all = "camelCase")]
2687#[non_exhaustive]
2688pub struct InitialSessionConfigOption {
2689    /// The ID of the configuration option to set.
2690    pub config_id: SessionConfigId,
2691    /// The value to set, including a `type` discriminator and the raw `value`.
2692    ///
2693    /// Payloads MUST send `type: "id"` for id-based options. A value `type` the Agent
2694    /// does not support fails the request with `-32602`.
2695    #[serde(flatten)]
2696    pub value: SessionConfigOptionValue,
2697    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2698    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2699    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2700    ///
2701    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2702    #[serde_as(deserialize_as = "DefaultOnError")]
2703    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2704    #[serde(default)]
2705    #[serde(rename = "_meta")]
2706    pub meta: Option<Meta>,
2707}
2708
2709#[cfg(feature = "unstable_session_options")]
2710impl InitialSessionConfigOption {
2711    /// Builds [`InitialSessionConfigOption`] with the required fields set. Optional fields start unset or empty.
2712    #[must_use]
2713    pub fn new(
2714        config_id: impl Into<SessionConfigId>,
2715        value: impl Into<SessionConfigOptionValue>,
2716    ) -> Self {
2717        Self {
2718            config_id: config_id.into(),
2719            value: value.into(),
2720            meta: None,
2721        }
2722    }
2723
2724    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2725    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2726    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2727    ///
2728    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2729    #[must_use]
2730    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2731        self.meta = meta.into_option();
2732        self
2733    }
2734}
2735
2736// Cancel tool call
2737
2738/// Request parameters for cancelling one tool call.
2739///
2740/// Clients MUST NOT send it unless the tool call currently advertises `capabilities.cancel`.
2741///
2742/// The Agent responds once it has accepted the cancellation. The response does not mean
2743/// the work has stopped. The Agent confirms it with a `tool_call_update` to a final
2744/// status: normally `cancelled`, or `completed` or `failed` if the work finished first.
2745///
2746/// The Agent responds with `-32602` if the tool call is unknown, already final, or not
2747/// cancellable. Cancelling a tool call does not change the foreground state by itself.
2748///
2749/// See protocol docs: [Cancelling Tool Calls](https://agentclientprotocol.com/protocol/v2/tool-calls#cancelling-tool-calls)
2750#[serde_as]
2751#[skip_serializing_none]
2752#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2753#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2754#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TOOL_CALL_CANCEL_METHOD_NAME)))]
2755#[serde(rename_all = "camelCase")]
2756#[non_exhaustive]
2757pub struct CancelToolCallRequest {
2758    /// The ID of the session that owns the tool call.
2759    pub session_id: SessionId,
2760    /// The ID of the tool call to cancel.
2761    pub tool_call_id: ToolCallId,
2762    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2763    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2764    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2765    ///
2766    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2767    #[serde_as(deserialize_as = "DefaultOnError")]
2768    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2769    #[serde(default)]
2770    #[serde(rename = "_meta")]
2771    pub meta: Option<Meta>,
2772}
2773
2774impl CancelToolCallRequest {
2775    /// Builds [`CancelToolCallRequest`] with the required request fields set. Optional fields start unset or empty.
2776    #[must_use]
2777    pub fn new(session_id: impl Into<SessionId>, tool_call_id: impl Into<ToolCallId>) -> Self {
2778        Self {
2779            session_id: session_id.into(),
2780            tool_call_id: tool_call_id.into(),
2781            meta: None,
2782        }
2783    }
2784
2785    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2786    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2787    /// do not recognize.
2788    ///
2789    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2790    #[must_use]
2791    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2792        self.meta = meta.into_option();
2793        self
2794    }
2795}
2796
2797crate::serde_util::default_on_null! {
2798    /// Response from cancelling a tool call.
2799    #[serde_as]
2800    #[skip_serializing_none]
2801    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2802    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2803    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TOOL_CALL_CANCEL_METHOD_NAME)))]
2804    #[serde(rename_all = "camelCase")]
2805    #[non_exhaustive]
2806    pub struct CancelToolCallResponse {
2807        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2808        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2809        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2810        ///
2811        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2812        #[serde_as(deserialize_as = "DefaultOnError")]
2813        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2814        #[serde(default)]
2815        #[serde(rename = "_meta")]
2816        pub meta: Option<Meta>,
2817    }
2818}
2819
2820impl CancelToolCallResponse {
2821    /// Builds [`CancelToolCallResponse`] with the required response fields set. Optional fields start unset or empty.
2822    #[must_use]
2823    pub fn new() -> Self {
2824        Self::default()
2825    }
2826
2827    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2828    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2829    /// do not recognize.
2830    ///
2831    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2832    #[must_use]
2833    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2834        self.meta = meta.into_option();
2835        self
2836    }
2837}
2838
2839// Cancel terminal
2840
2841/// Request parameters for cancelling one terminal.
2842///
2843/// Clients MUST NOT send it unless the terminal currently advertises `capabilities.cancel`.
2844///
2845/// The Agent responds once it has accepted the cancellation. The response does not mean
2846/// the work has stopped. The Agent confirms it with a `terminal_update` that sets
2847/// `exitStatus`. Cancelling stops the process but does not release the terminal, and does
2848/// not change the status of a tool call that references it.
2849///
2850/// The Agent responds with `-32602` if the terminal is unknown, has already exited, or is not
2851/// cancellable. Cancelling a terminal does not change the foreground state by itself.
2852///
2853/// See protocol docs: [Cancelling Terminals](https://agentclientprotocol.com/protocol/v2/tool-calls#cancelling-terminals)
2854#[serde_as]
2855#[skip_serializing_none]
2856#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2857#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2858#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TERMINAL_CANCEL_METHOD_NAME)))]
2859#[serde(rename_all = "camelCase")]
2860#[non_exhaustive]
2861pub struct CancelTerminalRequest {
2862    /// The ID of the session that owns the terminal.
2863    pub session_id: SessionId,
2864    /// The ID of the terminal to cancel.
2865    pub terminal_id: TerminalId,
2866    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2867    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2868    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2869    ///
2870    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2871    #[serde_as(deserialize_as = "DefaultOnError")]
2872    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2873    #[serde(default)]
2874    #[serde(rename = "_meta")]
2875    pub meta: Option<Meta>,
2876}
2877
2878impl CancelTerminalRequest {
2879    /// Builds [`CancelTerminalRequest`] with the required request fields set. Optional fields start unset or empty.
2880    #[must_use]
2881    pub fn new(session_id: impl Into<SessionId>, terminal_id: impl Into<TerminalId>) -> Self {
2882        Self {
2883            session_id: session_id.into(),
2884            terminal_id: terminal_id.into(),
2885            meta: None,
2886        }
2887    }
2888
2889    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2890    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2891    /// do not recognize.
2892    ///
2893    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2894    #[must_use]
2895    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2896        self.meta = meta.into_option();
2897        self
2898    }
2899}
2900
2901crate::serde_util::default_on_null! {
2902    /// Response from cancelling a terminal.
2903    #[serde_as]
2904    #[skip_serializing_none]
2905    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2906    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2907    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TERMINAL_CANCEL_METHOD_NAME)))]
2908    #[serde(rename_all = "camelCase")]
2909    #[non_exhaustive]
2910    pub struct CancelTerminalResponse {
2911        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2912        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2913        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2914        ///
2915        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2916        #[serde_as(deserialize_as = "DefaultOnError")]
2917        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2918        #[serde(default)]
2919        #[serde(rename = "_meta")]
2920        pub meta: Option<Meta>,
2921    }
2922}
2923
2924impl CancelTerminalResponse {
2925    /// Builds [`CancelTerminalResponse`] with the required response fields set. Optional fields start unset or empty.
2926    #[must_use]
2927    pub fn new() -> Self {
2928        Self::default()
2929    }
2930
2931    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2932    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2933    /// do not recognize.
2934    ///
2935    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2936    #[must_use]
2937    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2938        self.meta = meta.into_option();
2939        self
2940    }
2941}
2942
2943// List sessions
2944
2945/// An opaque cursor used to paginate `session/list` results.
2946#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2947#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
2948#[serde(transparent)]
2949#[from(Arc<str>, String, &str, &mut str, Box<str>, Cow<'_, str>)]
2950#[non_exhaustive]
2951pub struct SessionListCursor(pub Arc<str>);
2952
2953impl SessionListCursor {
2954    /// Wraps a protocol string as a typed [`SessionListCursor`].
2955    #[must_use]
2956    pub fn new(cursor: impl Into<Self>) -> Self {
2957        cursor.into()
2958    }
2959}
2960
2961impl AsRef<str> for SessionListCursor {
2962    fn as_ref(&self) -> &str {
2963        &self.0
2964    }
2965}
2966
2967impl From<&String> for SessionListCursor {
2968    fn from(cursor: &String) -> Self {
2969        Self(cursor.as_str().into())
2970    }
2971}
2972
2973macro_rules! impl_session_list_cursor_option_conversion {
2974    ($source:ty) => {
2975        impl IntoOption<SessionListCursor> for $source {
2976            fn into_option(self) -> Option<SessionListCursor> {
2977                Some(self.into())
2978            }
2979        }
2980    };
2981}
2982
2983impl_session_list_cursor_option_conversion!(Arc<str>);
2984impl_session_list_cursor_option_conversion!(String);
2985impl_session_list_cursor_option_conversion!(&str);
2986impl_session_list_cursor_option_conversion!(&mut str);
2987impl_session_list_cursor_option_conversion!(&String);
2988impl_session_list_cursor_option_conversion!(Box<str>);
2989impl_session_list_cursor_option_conversion!(Cow<'_, str>);
2990
2991crate::serde_util::default_on_null! {
2992    /// Request parameters for listing existing sessions.
2993    #[serde_as]
2994    #[skip_serializing_none]
2995    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2996    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2997    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LIST_METHOD_NAME)))]
2998    #[serde(rename_all = "camelCase")]
2999    #[non_exhaustive]
3000    pub struct ListSessionsRequest {
3001        /// Filter sessions by working directory. Must be an absolute path.
3002        ///
3003        /// Only sessions whose `cwd` is this same directory match. Subdirectories and
3004        /// `additionalDirectories` don't. Agents MAY normalize paths when comparing.
3005        ///
3006        /// Omitted and `null` are equivalent and mean sessions are not filtered by working directory.
3007        /// Clients keep the same value when following `nextCursor`.
3008        #[serde(default)]
3009        pub cwd: Option<AbsolutePath>,
3010        /// Opaque cursor token from a previous response's nextCursor field for cursor-based pagination
3011        ///
3012        /// Omitted and `null` are equivalent and mean the first page is requested.
3013        #[serde(default)]
3014        pub cursor: Option<SessionListCursor>,
3015        /// **UNSTABLE**
3016        ///
3017        /// This capability is not part of the spec yet, and may be removed or changed at any point.
3018        ///
3019        /// Filter sessions by archive state.
3020        ///
3021        /// Optional. Omitted and `null` are equivalent and mean `exclude`. Only send this when
3022        /// the Agent advertises the `session.archive` capability. The filter combines with `cwd` and
3023        /// applies before pagination. Clients keep the same value when following `nextCursor`.
3024        #[cfg(feature = "unstable_session_archive")]
3025        #[serde(default)]
3026        pub archived: Option<SessionArchiveFilter>,
3027        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3028        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3029        /// Implementations MUST NOT assign meaning to keys they do not recognize.
3030        ///
3031        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3032        #[serde_as(deserialize_as = "DefaultOnError")]
3033        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3034        #[serde(default)]
3035        #[serde(rename = "_meta")]
3036        pub meta: Option<Meta>,
3037    }
3038}
3039
3040impl ListSessionsRequest {
3041    /// Builds [`ListSessionsRequest`] with the required request fields set. Optional fields start unset or empty.
3042    #[must_use]
3043    pub fn new() -> Self {
3044        Self::default()
3045    }
3046
3047    /// Filter sessions by working directory. Must be an absolute path.
3048    #[must_use]
3049    pub fn cwd(mut self, cwd: impl IntoOption<AbsolutePath>) -> Self {
3050        self.cwd = cwd.into_option();
3051        self
3052    }
3053
3054    /// Opaque cursor token from a previous response's nextCursor field for cursor-based pagination
3055    #[must_use]
3056    pub fn cursor(mut self, cursor: impl IntoOption<SessionListCursor>) -> Self {
3057        self.cursor = cursor.into_option();
3058        self
3059    }
3060
3061    /// **UNSTABLE**
3062    ///
3063    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3064    ///
3065    /// Filter sessions by archive state.
3066    #[cfg(feature = "unstable_session_archive")]
3067    #[must_use]
3068    pub fn archived(mut self, archived: impl IntoOption<SessionArchiveFilter>) -> Self {
3069        self.archived = archived.into_option();
3070        self
3071    }
3072
3073    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3074    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3075    /// do not recognize.
3076    ///
3077    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3078    #[must_use]
3079    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3080        self.meta = meta.into_option();
3081        self
3082    }
3083}
3084
3085/// Response from listing sessions.
3086#[serde_as]
3087#[skip_serializing_none]
3088#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3089#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3090#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LIST_METHOD_NAME)))]
3091#[serde(rename_all = "camelCase")]
3092#[non_exhaustive]
3093pub struct ListSessionsResponse {
3094    /// Array of session information objects.
3095    ///
3096    /// Agents SHOULD return the sessions with the most recent activity first.
3097    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
3098    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3099    pub sessions: Vec<SessionInfo>,
3100    /// Opaque cursor token. If present, pass this in the next request's cursor parameter
3101    /// to fetch the next page. Omitted and `null` are equivalent and mean there are no more
3102    /// results. An empty string is a valid cursor, not the end of results.
3103    #[serde(default)]
3104    pub next_cursor: Option<SessionListCursor>,
3105    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3106    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3107    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3108    ///
3109    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3110    #[serde_as(deserialize_as = "DefaultOnError")]
3111    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3112    #[serde(default)]
3113    #[serde(rename = "_meta")]
3114    pub meta: Option<Meta>,
3115}
3116
3117impl ListSessionsResponse {
3118    /// Builds [`ListSessionsResponse`] with the required response fields set. Optional fields start unset or empty.
3119    #[must_use]
3120    pub fn new(sessions: Vec<SessionInfo>) -> Self {
3121        Self {
3122            sessions,
3123            next_cursor: None,
3124            meta: None,
3125        }
3126    }
3127
3128    /// Sets or clears the optional `nextCursor` field.
3129    #[must_use]
3130    pub fn next_cursor(mut self, next_cursor: impl IntoOption<SessionListCursor>) -> Self {
3131        self.next_cursor = next_cursor.into_option();
3132        self
3133    }
3134
3135    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3136    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3137    /// do not recognize.
3138    ///
3139    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3140    #[must_use]
3141    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3142        self.meta = meta.into_option();
3143        self
3144    }
3145}
3146
3147// Delete session
3148
3149/// Request parameters for deleting an existing session from `session/list`.
3150///
3151/// Only available if the Agent supports the `session.delete` capability.
3152#[serde_as]
3153#[skip_serializing_none]
3154#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3155#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3156#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_DELETE_METHOD_NAME)))]
3157#[serde(rename_all = "camelCase")]
3158#[non_exhaustive]
3159pub struct DeleteSessionRequest {
3160    /// The ID of the session to delete.
3161    pub session_id: SessionId,
3162    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3163    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3164    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3165    ///
3166    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3167    #[serde_as(deserialize_as = "DefaultOnError")]
3168    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3169    #[serde(default)]
3170    #[serde(rename = "_meta")]
3171    pub meta: Option<Meta>,
3172}
3173
3174impl DeleteSessionRequest {
3175    /// Builds [`DeleteSessionRequest`] with the required request fields set. Optional fields start unset or empty.
3176    #[must_use]
3177    pub fn new(session_id: impl Into<SessionId>) -> Self {
3178        Self {
3179            session_id: session_id.into(),
3180            meta: None,
3181        }
3182    }
3183
3184    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3185    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3186    /// do not recognize.
3187    ///
3188    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3189    #[must_use]
3190    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3191        self.meta = meta.into_option();
3192        self
3193    }
3194}
3195
3196crate::serde_util::default_on_null! {
3197    /// Response from deleting a session.
3198    #[serde_as]
3199    #[skip_serializing_none]
3200    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3201    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3202    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_DELETE_METHOD_NAME)))]
3203    #[serde(rename_all = "camelCase")]
3204    #[non_exhaustive]
3205    pub struct DeleteSessionResponse {
3206        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3207        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3208        /// Implementations MUST NOT assign meaning to keys they do not recognize.
3209        ///
3210        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3211        #[serde_as(deserialize_as = "DefaultOnError")]
3212        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3213        #[serde(default)]
3214        #[serde(rename = "_meta")]
3215        pub meta: Option<Meta>,
3216    }
3217}
3218
3219impl DeleteSessionResponse {
3220    /// Builds [`DeleteSessionResponse`] with the required response fields set. Optional fields start unset or empty.
3221    #[must_use]
3222    pub fn new() -> Self {
3223        Self::default()
3224    }
3225
3226    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3227    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3228    /// do not recognize.
3229    ///
3230    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3231    #[must_use]
3232    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3233        self.meta = meta.into_option();
3234        self
3235    }
3236}
3237
3238// Archive session
3239
3240/// **UNSTABLE**
3241///
3242/// This capability is not part of the spec yet, and may be removed or changed at any point.
3243///
3244/// Request parameters for archiving a session.
3245///
3246/// Only available if the Agent supports the `session.archive` capability.
3247///
3248/// Archiving hides the session from default `session/list` results. It keeps the session ID
3249/// and saved history. If the session is active, the Agent MUST cancel any ongoing work and
3250/// free the session's resources as if `session/close` had been called, then archive it.
3251/// Archiving an archived session succeeds. A session that does not exist gets `-32002`.
3252///
3253#[cfg(feature = "unstable_session_archive")]
3254#[serde_as]
3255#[skip_serializing_none]
3256#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3257#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3258#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_ARCHIVE_METHOD_NAME)))]
3259#[serde(rename_all = "camelCase")]
3260#[non_exhaustive]
3261pub struct ArchiveSessionRequest {
3262    /// The ID of the session to archive.
3263    pub session_id: SessionId,
3264    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3265    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3266    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3267    ///
3268    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3269    #[serde_as(deserialize_as = "DefaultOnError")]
3270    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3271    #[serde(default)]
3272    #[serde(rename = "_meta")]
3273    pub meta: Option<Meta>,
3274}
3275
3276#[cfg(feature = "unstable_session_archive")]
3277impl ArchiveSessionRequest {
3278    /// Builds [`ArchiveSessionRequest`] with the required request fields set. Optional fields start unset or empty.
3279    #[must_use]
3280    pub fn new(session_id: impl Into<SessionId>) -> Self {
3281        Self {
3282            session_id: session_id.into(),
3283            meta: None,
3284        }
3285    }
3286
3287    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3288    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3289    /// do not recognize.
3290    ///
3291    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3292    #[must_use]
3293    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3294        self.meta = meta.into_option();
3295        self
3296    }
3297}
3298
3299#[cfg(feature = "unstable_session_archive")]
3300crate::serde_util::default_on_null! {
3301    /// **UNSTABLE**
3302    ///
3303    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3304    ///
3305    /// Response from archiving a session.
3306    #[serde_as]
3307    #[skip_serializing_none]
3308    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3309    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3310    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_ARCHIVE_METHOD_NAME)))]
3311    #[serde(rename_all = "camelCase")]
3312    #[non_exhaustive]
3313    pub struct ArchiveSessionResponse {
3314        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3315        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3316        /// Implementations MUST NOT assign meaning to keys they do not recognize.
3317        ///
3318        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3319        #[serde_as(deserialize_as = "DefaultOnError")]
3320        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3321        #[serde(default)]
3322        #[serde(rename = "_meta")]
3323        pub meta: Option<Meta>,
3324    }
3325}
3326
3327#[cfg(feature = "unstable_session_archive")]
3328impl ArchiveSessionResponse {
3329    /// Builds [`ArchiveSessionResponse`] with the required response fields set. Optional fields start unset or empty.
3330    #[must_use]
3331    pub fn new() -> Self {
3332        Self::default()
3333    }
3334
3335    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3336    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3337    /// do not recognize.
3338    ///
3339    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3340    #[must_use]
3341    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3342        self.meta = meta.into_option();
3343        self
3344    }
3345}
3346
3347/// **UNSTABLE**
3348///
3349/// This capability is not part of the spec yet, and may be removed or changed at any point.
3350///
3351/// Request parameters for unarchiving a session.
3352///
3353/// Only available if the Agent supports the `session.archive` capability.
3354///
3355/// Unarchiving returns the session to default `session/list` results with the same ID and
3356/// saved history. It never resumes the session. Clients that want to continue an
3357/// archived session SHOULD unarchive it before calling `session/resume`.
3358/// Unarchiving a session that is not archived succeeds. A session that does not exist
3359/// gets `-32002`.
3360///
3361#[cfg(feature = "unstable_session_archive")]
3362#[serde_as]
3363#[skip_serializing_none]
3364#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3365#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3366#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_UNARCHIVE_METHOD_NAME)))]
3367#[serde(rename_all = "camelCase")]
3368#[non_exhaustive]
3369pub struct UnarchiveSessionRequest {
3370    /// The ID of the session to unarchive.
3371    pub session_id: SessionId,
3372    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3373    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3374    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3375    ///
3376    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3377    #[serde_as(deserialize_as = "DefaultOnError")]
3378    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3379    #[serde(default)]
3380    #[serde(rename = "_meta")]
3381    pub meta: Option<Meta>,
3382}
3383
3384#[cfg(feature = "unstable_session_archive")]
3385impl UnarchiveSessionRequest {
3386    /// Builds [`UnarchiveSessionRequest`] with the required request fields set. Optional fields start unset or empty.
3387    #[must_use]
3388    pub fn new(session_id: impl Into<SessionId>) -> Self {
3389        Self {
3390            session_id: session_id.into(),
3391            meta: None,
3392        }
3393    }
3394
3395    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3396    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3397    /// do not recognize.
3398    ///
3399    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3400    #[must_use]
3401    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3402        self.meta = meta.into_option();
3403        self
3404    }
3405}
3406
3407#[cfg(feature = "unstable_session_archive")]
3408crate::serde_util::default_on_null! {
3409    /// **UNSTABLE**
3410    ///
3411    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3412    ///
3413    /// Response from unarchiving a session.
3414    #[serde_as]
3415    #[skip_serializing_none]
3416    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3417    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3418    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_UNARCHIVE_METHOD_NAME)))]
3419    #[serde(rename_all = "camelCase")]
3420    #[non_exhaustive]
3421    pub struct UnarchiveSessionResponse {
3422        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3423        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3424        /// Implementations MUST NOT assign meaning to keys they do not recognize.
3425        ///
3426        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3427        #[serde_as(deserialize_as = "DefaultOnError")]
3428        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3429        #[serde(default)]
3430        #[serde(rename = "_meta")]
3431        pub meta: Option<Meta>,
3432    }
3433}
3434
3435#[cfg(feature = "unstable_session_archive")]
3436impl UnarchiveSessionResponse {
3437    /// Builds [`UnarchiveSessionResponse`] with the required response fields set. Optional fields start unset or empty.
3438    #[must_use]
3439    pub fn new() -> Self {
3440        Self::default()
3441    }
3442
3443    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3444    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3445    /// do not recognize.
3446    ///
3447    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3448    #[must_use]
3449    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3450        self.meta = meta.into_option();
3451        self
3452    }
3453}
3454
3455/// **UNSTABLE**
3456///
3457/// This capability is not part of the spec yet, and may be removed or changed at any point.
3458///
3459/// Which sessions `session/list` returns based on their archive state.
3460///
3461/// Unknown values are preserved so they can be stored, proxied, or forwarded. An Agent MUST
3462/// return `-32602` for a value it does not support rather than treating it as `exclude`.
3463#[cfg(feature = "unstable_session_archive")]
3464#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3465#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
3466#[serde(rename_all = "snake_case")]
3467#[non_exhaustive]
3468pub enum SessionArchiveFilter {
3469    /// Only sessions that are not archived. This is the default.
3470    #[default]
3471    Exclude,
3472    /// Both archived sessions and sessions that are not archived.
3473    Include,
3474    /// Only archived sessions.
3475    Only,
3476    /// Custom or future archive filter.
3477    ///
3478    /// Values beginning with `_` are reserved for implementation-specific
3479    /// extensions. Unknown values that do not begin with `_` are reserved for
3480    /// future ACP variants.
3481    #[serde(untagged)]
3482    Other(String),
3483}
3484
3485/// Information about a session returned by session/list
3486#[serde_as]
3487#[skip_serializing_none]
3488#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3489#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3490#[serde(rename_all = "camelCase")]
3491#[non_exhaustive]
3492pub struct SessionInfo {
3493    /// Unique identifier for the session
3494    pub session_id: SessionId,
3495    /// The working directory for this session. Must be an absolute path.
3496    pub cwd: AbsolutePath,
3497    /// Additional workspace roots reported for this session. Each path MUST be absolute.
3498    ///
3499    /// When present, this is the complete ordered additional-root list reported
3500    /// by the Agent. Omitted and empty values are equivalent: the response
3501    /// reports no additional roots.
3502    #[serde_as(deserialize_as = "DefaultOnNull")]
3503    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
3504    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3505    pub additional_directories: Vec<AbsolutePath>,
3506
3507    /// Human-readable title for the session, in plain text.
3508    ///
3509    /// Omitted and `null` are equivalent and mean no title is provided.
3510    #[serde_as(deserialize_as = "DefaultOnError")]
3511    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3512    #[serde(default)]
3513    pub title: Option<String>,
3514    /// RFC 3339 timestamp of last activity.
3515    ///
3516    /// Omitted and `null` are equivalent and mean the last activity time is not reported.
3517    #[serde_as(deserialize_as = "DefaultOnError")]
3518    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "format" = "date-time")))]
3519    #[serde(default)]
3520    pub updated_at: Option<String>,
3521    /// **UNSTABLE**
3522    ///
3523    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3524    ///
3525    /// Whether the session is archived.
3526    ///
3527    /// Optional. Omitted and `null` are equivalent and mean the archive state is not reported.
3528    /// Agents that advertise the `session.archive` capability MUST include it on every listed session.
3529    #[cfg(feature = "unstable_session_archive")]
3530    #[serde_as(deserialize_as = "DefaultOnError")]
3531    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3532    #[serde(default)]
3533    pub archived: Option<bool>,
3534    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3535    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3536    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3537    ///
3538    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3539    #[serde_as(deserialize_as = "DefaultOnError")]
3540    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3541    #[serde(default)]
3542    #[serde(rename = "_meta")]
3543    pub meta: Option<Meta>,
3544}
3545
3546impl SessionInfo {
3547    /// Builds [`SessionInfo`] with the required fields set. Optional fields start unset or empty.
3548    #[must_use]
3549    pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
3550        Self {
3551            session_id: session_id.into(),
3552            cwd: cwd.into(),
3553            additional_directories: vec![],
3554            title: None,
3555            updated_at: None,
3556            #[cfg(feature = "unstable_session_archive")]
3557            archived: None,
3558            meta: None,
3559        }
3560    }
3561
3562    /// Additional workspace roots reported for this session. Each path MUST be absolute.
3563    #[must_use]
3564    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
3565    where
3566        I: IntoIterator<Item = P>,
3567        P: Into<AbsolutePath>,
3568    {
3569        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
3570        self
3571    }
3572
3573    /// Human-readable title for the session, in plain text.
3574    #[must_use]
3575    pub fn title(mut self, title: impl IntoOption<String>) -> Self {
3576        self.title = title.into_option();
3577        self
3578    }
3579
3580    /// RFC 3339 timestamp of last activity.
3581    #[must_use]
3582    pub fn updated_at(mut self, updated_at: impl IntoOption<String>) -> Self {
3583        self.updated_at = updated_at.into_option();
3584        self
3585    }
3586
3587    /// **UNSTABLE**
3588    ///
3589    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3590    ///
3591    /// Whether the session is archived.
3592    #[cfg(feature = "unstable_session_archive")]
3593    #[must_use]
3594    pub fn archived(mut self, archived: impl IntoOption<bool>) -> Self {
3595        self.archived = archived.into_option();
3596        self
3597    }
3598
3599    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3600    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3601    /// do not recognize.
3602    ///
3603    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3604    #[must_use]
3605    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3606        self.meta = meta.into_option();
3607        self
3608    }
3609}
3610
3611// Set session title
3612
3613/// **UNSTABLE**
3614///
3615/// This capability is not part of the spec yet, and may be removed or changed at any point.
3616///
3617/// Request parameters for setting the title of a session.
3618///
3619/// Only available if the Agent supports the `session.title` capability.
3620///
3621/// The session does not need to be active on the connection. Any session the Agent would
3622/// return from `session/list` can be retitled. A session that does not exist gets `-32002`.
3623///
3624/// The Agent responds only after it has stored the title. After a successful response, the
3625/// Agent SHOULD NOT replace the title with one it generates automatically.
3626#[cfg(feature = "unstable_session_set_title")]
3627#[serde_as]
3628#[skip_serializing_none]
3629#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3630#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3631#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_TITLE_METHOD_NAME)))]
3632#[serde(rename_all = "camelCase")]
3633#[non_exhaustive]
3634pub struct SetSessionTitleRequest {
3635    /// The ID of the session to retitle.
3636    pub session_id: SessionId,
3637    /// The new plain-text title for the session.
3638    ///
3639    /// Required and non-null. Omission and explicit `null` are both invalid. The Agent MAY
3640    /// normalize the title before storing it, for example by trimming whitespace or
3641    /// truncating it. The Agent rejects a title that fails its validation, including one
3642    /// that is empty after normalization, with `-32602`.
3643    pub title: String,
3644    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3645    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3646    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3647    ///
3648    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3649    #[serde_as(deserialize_as = "DefaultOnError")]
3650    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3651    #[serde(default)]
3652    #[serde(rename = "_meta")]
3653    pub meta: Option<Meta>,
3654}
3655
3656#[cfg(feature = "unstable_session_set_title")]
3657impl SetSessionTitleRequest {
3658    /// Builds [`SetSessionTitleRequest`] with the required request fields set. Optional fields start unset or empty.
3659    #[must_use]
3660    pub fn new(session_id: impl Into<SessionId>, title: impl Into<String>) -> Self {
3661        Self {
3662            session_id: session_id.into(),
3663            title: title.into(),
3664            meta: None,
3665        }
3666    }
3667
3668    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3669    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3670    /// do not recognize.
3671    ///
3672    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3673    #[must_use]
3674    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3675        self.meta = meta.into_option();
3676        self
3677    }
3678}
3679
3680/// **UNSTABLE**
3681///
3682/// This capability is not part of the spec yet, and may be removed or changed at any point.
3683///
3684/// Response from setting the title of a session.
3685#[cfg(feature = "unstable_session_set_title")]
3686#[serde_as]
3687#[skip_serializing_none]
3688#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3689#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3690#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_TITLE_METHOD_NAME)))]
3691#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "sessionInfo", "field": "title", "value": "title"}]})))]
3692#[serde(rename_all = "camelCase")]
3693#[non_exhaustive]
3694pub struct SetSessionTitleResponse {
3695    /// The plain-text title the Agent stored.
3696    ///
3697    /// This differs from the requested title if the Agent normalized it. Clients SHOULD
3698    /// display this value rather than the one they sent.
3699    pub title: String,
3700    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3701    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3702    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3703    ///
3704    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3705    #[serde_as(deserialize_as = "DefaultOnError")]
3706    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3707    #[serde(default)]
3708    #[serde(rename = "_meta")]
3709    pub meta: Option<Meta>,
3710}
3711
3712#[cfg(feature = "unstable_session_set_title")]
3713impl SetSessionTitleResponse {
3714    /// Builds [`SetSessionTitleResponse`] with the required response fields set. Optional fields start unset or empty.
3715    #[must_use]
3716    pub fn new(title: impl Into<String>) -> Self {
3717        Self {
3718            title: title.into(),
3719            meta: None,
3720        }
3721    }
3722
3723    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3724    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3725    /// do not recognize.
3726    ///
3727    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3728    #[must_use]
3729    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3730        self.meta = meta.into_option();
3731        self
3732    }
3733}
3734
3735// Session config options
3736
3737/// Unique identifier for a session configuration option.
3738#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3739#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3740#[serde(transparent)]
3741#[from(forward)]
3742#[non_exhaustive]
3743pub struct SessionConfigId(pub Arc<str>);
3744
3745impl SessionConfigId {
3746    /// Wraps a protocol string as a typed [`SessionConfigId`].
3747    #[must_use]
3748    pub fn new(id: impl Into<Self>) -> Self {
3749        id.into()
3750    }
3751}
3752
3753/// Unique identifier for a session configuration option value.
3754#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3755#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3756#[serde(transparent)]
3757#[from(forward)]
3758#[non_exhaustive]
3759pub struct SessionConfigValueId(pub Arc<str>);
3760
3761impl SessionConfigValueId {
3762    /// Wraps a protocol string as a typed [`SessionConfigValueId`].
3763    #[must_use]
3764    pub fn new(id: impl Into<Self>) -> Self {
3765        id.into()
3766    }
3767}
3768
3769/// Unique identifier for a session configuration option value group.
3770#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3771#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3772#[serde(transparent)]
3773#[from(forward)]
3774#[non_exhaustive]
3775pub struct SessionConfigGroupId(pub Arc<str>);
3776
3777impl SessionConfigGroupId {
3778    /// Wraps a protocol string as a typed [`SessionConfigGroupId`].
3779    #[must_use]
3780    pub fn new(id: impl Into<Self>) -> Self {
3781        id.into()
3782    }
3783}
3784
3785/// A possible value for a session configuration option.
3786#[serde_as]
3787#[skip_serializing_none]
3788#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3789#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3790#[serde(rename_all = "camelCase")]
3791#[non_exhaustive]
3792pub struct SessionConfigSelectOption {
3793    /// Unique identifier for this option value.
3794    pub value: SessionConfigValueId,
3795    /// Human-readable label the Client can display for this option value, in plain text.
3796    pub name: String,
3797    /// Optional description for this option value.
3798    /// May contain Markdown.
3799    ///
3800    /// Omitted and `null` are equivalent and mean no description is provided.
3801    #[serde_as(deserialize_as = "DefaultOnError")]
3802    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3803    #[serde(default)]
3804    pub description: Option<String>,
3805    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3806    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3807    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3808    ///
3809    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3810    #[serde_as(deserialize_as = "DefaultOnError")]
3811    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3812    #[serde(default)]
3813    #[serde(rename = "_meta")]
3814    pub meta: Option<Meta>,
3815}
3816
3817impl SessionConfigSelectOption {
3818    /// Builds [`SessionConfigSelectOption`] with the required fields set. Optional fields start unset or empty.
3819    #[must_use]
3820    pub fn new(value: impl Into<SessionConfigValueId>, name: impl Into<String>) -> Self {
3821        Self {
3822            value: value.into(),
3823            name: name.into(),
3824            description: None,
3825            meta: None,
3826        }
3827    }
3828
3829    /// Sets or clears the description of what this option value does.
3830    /// May contain Markdown.
3831    #[must_use]
3832    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
3833        self.description = description.into_option();
3834        self
3835    }
3836
3837    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3838    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3839    /// do not recognize.
3840    ///
3841    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3842    #[must_use]
3843    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3844        self.meta = meta.into_option();
3845        self
3846    }
3847}
3848
3849/// A group of possible values for a session configuration option.
3850#[serde_as]
3851#[skip_serializing_none]
3852#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3853#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3854#[serde(rename_all = "camelCase")]
3855#[non_exhaustive]
3856pub struct SessionConfigSelectGroup {
3857    /// Identifier for this group. MUST be unique within the option.
3858    pub group_id: SessionConfigGroupId,
3859    /// Human-readable label the Client can display as a plain-text group header.
3860    pub name: String,
3861    /// The set of option values in this group. MUST contain at least one value.
3862    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
3863    #[cfg_attr(feature = "schemars", schemars(length(min = 1), extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3864    pub options: Vec<SessionConfigSelectOption>,
3865    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3866    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3867    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3868    ///
3869    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3870    #[serde_as(deserialize_as = "DefaultOnError")]
3871    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3872    #[serde(default)]
3873    #[serde(rename = "_meta")]
3874    pub meta: Option<Meta>,
3875}
3876
3877impl SessionConfigSelectGroup {
3878    /// Builds [`SessionConfigSelectGroup`] with the required fields set. Optional fields start unset or empty.
3879    #[must_use]
3880    pub fn new(
3881        group_id: impl Into<SessionConfigGroupId>,
3882        name: impl Into<String>,
3883        options: Vec<SessionConfigSelectOption>,
3884    ) -> Self {
3885        Self {
3886            group_id: group_id.into(),
3887            name: name.into(),
3888            options,
3889            meta: None,
3890        }
3891    }
3892
3893    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3894    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3895    /// do not recognize.
3896    ///
3897    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3898    #[must_use]
3899    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3900        self.meta = meta.into_option();
3901        self
3902    }
3903}
3904
3905/// Possible values for a session configuration option.
3906#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3907#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3908#[serde(untagged)]
3909#[non_exhaustive]
3910pub enum SessionConfigSelectOptions {
3911    /// A flat list of options with no grouping.
3912    Ungrouped(
3913        #[cfg_attr(feature = "schemars", schemars(length(min = 1)))] Vec<SessionConfigSelectOption>,
3914    ),
3915    /// A list of options grouped under headers.
3916    Grouped(
3917        #[cfg_attr(feature = "schemars", schemars(length(min = 1)))] Vec<SessionConfigSelectGroup>,
3918    ),
3919}
3920
3921impl From<Vec<SessionConfigSelectOption>> for SessionConfigSelectOptions {
3922    fn from(options: Vec<SessionConfigSelectOption>) -> Self {
3923        SessionConfigSelectOptions::Ungrouped(options)
3924    }
3925}
3926
3927impl From<Vec<SessionConfigSelectGroup>> for SessionConfigSelectOptions {
3928    fn from(groups: Vec<SessionConfigSelectGroup>) -> Self {
3929        SessionConfigSelectOptions::Grouped(groups)
3930    }
3931}
3932
3933/// A single-value selector (dropdown) session configuration option payload.
3934#[skip_serializing_none]
3935#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3936#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3937#[serde(rename_all = "camelCase")]
3938#[non_exhaustive]
3939pub struct SessionConfigSelect {
3940    /// The currently selected value. MUST be one of the `value`s in `options`.
3941    pub current_value: SessionConfigValueId,
3942    /// The set of selectable options. MUST contain at least one value, and each `value` MUST be
3943    /// unique within the option, including across groups.
3944    pub options: SessionConfigSelectOptions,
3945}
3946
3947impl SessionConfigSelect {
3948    /// Builds [`SessionConfigSelect`] with the required fields set. Optional fields start unset or empty.
3949    #[must_use]
3950    pub fn new(
3951        current_value: impl Into<SessionConfigValueId>,
3952        options: impl Into<SessionConfigSelectOptions>,
3953    ) -> Self {
3954        Self {
3955            current_value: current_value.into(),
3956            options: options.into(),
3957        }
3958    }
3959}
3960
3961/// A boolean on/off toggle session configuration option payload.
3962#[skip_serializing_none]
3963#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3964#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3965#[serde(rename_all = "camelCase")]
3966#[non_exhaustive]
3967pub struct SessionConfigBoolean {
3968    /// The current value of the boolean option.
3969    pub current_value: bool,
3970}
3971
3972impl SessionConfigBoolean {
3973    /// Builds [`SessionConfigBoolean`] with the required fields set. Optional fields start unset or empty.
3974    #[must_use]
3975    pub fn new(current_value: bool) -> Self {
3976        Self { current_value }
3977    }
3978}
3979
3980/// Semantic category for a session configuration option.
3981///
3982/// This is intended to help Clients distinguish broadly common selectors (e.g. model selector vs
3983/// session mode selector vs thought/reasoning level) for UX purposes (keyboard shortcuts, icons,
3984/// placement). It MUST NOT be required for correctness. Clients MUST handle missing or unknown
3985/// categories gracefully.
3986///
3987/// Category names beginning with `_` are free for custom use, like other ACP extension methods.
3988/// Category names that do not begin with `_` are reserved for the ACP spec.
3989#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3990#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3991#[serde(rename_all = "snake_case")]
3992#[non_exhaustive]
3993pub enum SessionConfigOptionCategory {
3994    /// Session mode selector.
3995    Mode,
3996    /// Model selector.
3997    Model,
3998    /// Model-related configuration parameter.
3999    ModelConfig,
4000    /// **UNSTABLE**
4001    ///
4002    /// This capability is not part of the spec yet, and may be removed or changed at any point.
4003    ///
4004    /// Response speed selector, such as a fast mode toggle.
4005    #[cfg(feature = "unstable_speed_config_category")]
4006    Speed,
4007    /// Thought/reasoning level selector.
4008    ThoughtLevel,
4009    /// Custom or future category.
4010    ///
4011    /// Values beginning with `_` are reserved for implementation-specific
4012    /// extensions. Unknown values that do not begin with `_` are reserved for
4013    /// future ACP variants.
4014    #[serde(untagged)]
4015    Other(String),
4016}
4017
4018/// Type-specific session configuration option payload.
4019#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4020#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4021#[serde(tag = "type", rename_all = "snake_case")]
4022#[non_exhaustive]
4023pub enum SessionConfigKind {
4024    /// Single-value selector (dropdown).
4025    Select(SessionConfigSelect),
4026    /// Boolean on/off toggle.
4027    Boolean(SessionConfigBoolean),
4028    /// Custom or future session configuration option payload.
4029    ///
4030    /// Values beginning with `_` are reserved for implementation-specific
4031    /// extensions. Unknown values that do not begin with `_` are reserved for
4032    /// future ACP variants.
4033    ///
4034    /// Clients that do not understand this option type SHOULD preserve the raw
4035    /// payload when storing, replaying, proxying, or forwarding configuration
4036    /// data, and otherwise ignore the option. The Agent keeps using its `currentValue`.
4037    #[serde(untagged)]
4038    Other(OtherSessionConfigKind),
4039}
4040
4041/// Custom or future session configuration option payload.
4042#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4043#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4044#[cfg_attr(feature = "schemars", schemars(inline))]
4045#[cfg_attr(feature = "schemars", schemars(transform = other_session_config_kind_schema))]
4046#[serde(rename_all = "camelCase")]
4047#[non_exhaustive]
4048pub struct OtherSessionConfigKind {
4049    /// Custom or future session configuration option type.
4050    ///
4051    /// Values beginning with `_` are reserved for implementation-specific
4052    /// extensions. Unknown values that do not begin with `_` are reserved for
4053    /// future ACP variants.
4054    #[serde(rename = "type")]
4055    pub type_: String,
4056    /// Additional fields from the unknown session configuration option payload.
4057    #[serde(flatten)]
4058    pub fields: IndexMap<String, serde_json::Value>,
4059}
4060
4061impl OtherSessionConfigKind {
4062    /// Builds [`OtherSessionConfigKind`] from an unknown discriminator and preserves the remaining extension fields.
4063    #[must_use]
4064    pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
4065        fields.shift_remove("type");
4066        fields.shift_remove("_meta");
4067        Self {
4068            type_: type_.into(),
4069            fields,
4070        }
4071    }
4072}
4073
4074impl<'de> Deserialize<'de> for OtherSessionConfigKind {
4075    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4076    where
4077        D: serde::Deserializer<'de>,
4078    {
4079        let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4080        let type_ = fields
4081            .shift_remove("type")
4082            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4083        let serde_json::Value::String(type_) = type_ else {
4084            return Err(serde::de::Error::custom("`type` must be a string"));
4085        };
4086
4087        if is_known_session_config_kind_type(&type_) {
4088            return Err(serde::de::Error::custom(format!(
4089                "known session configuration option `{type_}` did not match its schema"
4090            )));
4091        }
4092
4093        Ok(Self { type_, fields })
4094    }
4095}
4096
4097fn is_known_session_config_kind_type(type_: &str) -> bool {
4098    matches!(type_, "select" | "boolean")
4099}
4100
4101#[cfg(feature = "schemars")]
4102fn other_session_config_kind_schema(schema: &mut Schema) {
4103    super::schema_util::reject_known_string_discriminators(schema, "type", &["select", "boolean"]);
4104}
4105
4106/// A session configuration option selector and its current state.
4107#[serde_as]
4108#[skip_serializing_none]
4109#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4110#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4111#[serde(rename_all = "camelCase")]
4112#[non_exhaustive]
4113pub struct SessionConfigOption {
4114    /// Identifier for the configuration option. MUST be unique within `configOptions`.
4115    pub config_id: SessionConfigId,
4116    /// Human-readable label the Client can display for the option, in plain text.
4117    pub name: String,
4118    /// Optional description for the Client to display to the user.
4119    /// May contain Markdown.
4120    ///
4121    /// Omitted and `null` are equivalent and mean no description is provided.
4122    #[serde_as(deserialize_as = "DefaultOnError")]
4123    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4124    #[serde(default)]
4125    pub description: Option<String>,
4126    /// Optional semantic category for this option (UX only).
4127    ///
4128    /// Omitted and `null` are equivalent and mean no category is provided.
4129    #[serde_as(deserialize_as = "DefaultOnError")]
4130    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4131    #[serde(default)]
4132    pub category: Option<SessionConfigOptionCategory>,
4133    /// Type-specific fields for this configuration option.
4134    #[serde(flatten)]
4135    pub kind: SessionConfigKind,
4136    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4137    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4138    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4139    ///
4140    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4141    #[serde_as(deserialize_as = "DefaultOnError")]
4142    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4143    #[serde(default)]
4144    #[serde(rename = "_meta")]
4145    pub meta: Option<Meta>,
4146}
4147
4148impl SessionConfigOption {
4149    /// Builds [`SessionConfigOption`] with the required fields set. Optional fields start unset or empty.
4150    #[must_use]
4151    pub fn new(
4152        config_id: impl Into<SessionConfigId>,
4153        name: impl Into<String>,
4154        kind: SessionConfigKind,
4155    ) -> Self {
4156        Self {
4157            config_id: config_id.into(),
4158            name: name.into(),
4159            description: None,
4160            category: None,
4161            kind,
4162            meta: None,
4163        }
4164    }
4165
4166    /// Builds a select-style session configuration option with its current value and choices.
4167    #[must_use]
4168    pub fn select(
4169        config_id: impl Into<SessionConfigId>,
4170        name: impl Into<String>,
4171        current_value: impl Into<SessionConfigValueId>,
4172        options: impl Into<SessionConfigSelectOptions>,
4173    ) -> Self {
4174        Self::new(
4175            config_id,
4176            name,
4177            SessionConfigKind::Select(SessionConfigSelect::new(current_value, options)),
4178        )
4179    }
4180
4181    /// Builds a boolean-style session configuration option with its current value.
4182    #[must_use]
4183    pub fn boolean(
4184        config_id: impl Into<SessionConfigId>,
4185        name: impl Into<String>,
4186        current_value: bool,
4187    ) -> Self {
4188        Self::new(
4189            config_id,
4190            name,
4191            SessionConfigKind::Boolean(SessionConfigBoolean::new(current_value)),
4192        )
4193    }
4194
4195    /// Sets or clears the description of what this option controls.
4196    /// May contain Markdown.
4197    #[must_use]
4198    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
4199        self.description = description.into_option();
4200        self
4201    }
4202
4203    /// Sets or clears the optional `category` field.
4204    #[must_use]
4205    pub fn category(mut self, category: impl IntoOption<SessionConfigOptionCategory>) -> Self {
4206        self.category = category.into_option();
4207        self
4208    }
4209
4210    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4211    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4212    /// do not recognize.
4213    ///
4214    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4215    #[must_use]
4216    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4217        self.meta = meta.into_option();
4218        self
4219    }
4220}
4221
4222/// The value to set for a session configuration option.
4223///
4224/// The `type` field acts as the discriminator in the serialized JSON form.
4225///
4226/// The `type` discriminator describes the *shape* of the value, not the option
4227/// kind. For example every option kind that picks from a list of ids
4228/// (`select`, `radio`, …) would use [`Id`](Self::Id), while a future freeform
4229/// text option would get its own variant.
4230#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4231#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4232#[serde(tag = "type", rename_all = "snake_case")]
4233#[non_exhaustive]
4234pub enum SessionConfigOptionValue {
4235    /// A `SessionConfigValueId` string value (`type: "id"`).
4236    Id {
4237        /// The value ID.
4238        value: SessionConfigValueId,
4239    },
4240    /// A boolean value (`type: "boolean"`).
4241    Boolean {
4242        /// The boolean value.
4243        value: bool,
4244    },
4245    /// Custom or future session configuration option value payload.
4246    ///
4247    /// Values beginning with `_` are reserved for implementation-specific
4248    /// extensions. Unknown values that do not begin with `_` are reserved for
4249    /// future ACP variants.
4250    ///
4251    /// Agents MUST reject a `session/set_config_option` request with a value type
4252    /// they do not support with `-32602`.
4253    #[serde(untagged)]
4254    Other(Box<OtherSessionConfigOptionValue>),
4255}
4256
4257/// Custom or future session configuration option value payload.
4258#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4259#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4260#[cfg_attr(feature = "schemars", schemars(inline))]
4261#[cfg_attr(feature = "schemars", schemars(transform = other_session_config_option_value_schema))]
4262#[serde(rename_all = "camelCase")]
4263#[non_exhaustive]
4264pub struct OtherSessionConfigOptionValue {
4265    /// Custom or future session configuration option value type.
4266    ///
4267    /// Values beginning with `_` are reserved for implementation-specific
4268    /// extensions. Unknown values that do not begin with `_` are reserved for
4269    /// future ACP variants.
4270    #[serde(rename = "type")]
4271    pub type_: String,
4272    /// Raw value payload for the custom or future value type.
4273    pub value: serde_json::Value,
4274    /// Additional fields from the unknown session configuration option value payload.
4275    #[serde(flatten)]
4276    pub fields: IndexMap<String, serde_json::Value>,
4277}
4278
4279impl OtherSessionConfigOptionValue {
4280    /// Builds [`OtherSessionConfigOptionValue`] from an unknown discriminator and preserves the remaining extension fields.
4281    #[must_use]
4282    pub fn new(
4283        type_: impl Into<String>,
4284        value: serde_json::Value,
4285        mut fields: IndexMap<String, serde_json::Value>,
4286    ) -> Self {
4287        fields.shift_remove("type");
4288        fields.shift_remove("value");
4289        fields.shift_remove("_meta");
4290        Self {
4291            type_: type_.into(),
4292            value,
4293            fields,
4294        }
4295    }
4296}
4297
4298impl<'de> Deserialize<'de> for OtherSessionConfigOptionValue {
4299    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4300    where
4301        D: serde::Deserializer<'de>,
4302    {
4303        let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4304        let type_ = fields
4305            .shift_remove("type")
4306            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4307        let serde_json::Value::String(type_) = type_ else {
4308            return Err(serde::de::Error::custom("`type` must be a string"));
4309        };
4310
4311        if is_known_session_config_option_value_type(&type_) {
4312            return Err(serde::de::Error::custom(format!(
4313                "known session configuration option value `{type_}` did not match its schema"
4314            )));
4315        }
4316
4317        let value = fields
4318            .shift_remove("value")
4319            .ok_or_else(|| serde::de::Error::missing_field("value"))?;
4320
4321        Ok(Self {
4322            type_,
4323            value,
4324            fields,
4325        })
4326    }
4327}
4328
4329impl<'de> Deserialize<'de> for SessionConfigOptionValue {
4330    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4331    where
4332        D: serde::Deserializer<'de>,
4333    {
4334        let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4335        let type_ = fields.shift_remove("type");
4336        let value = fields
4337            .shift_remove("value")
4338            .ok_or_else(|| serde::de::Error::missing_field("value"))?;
4339
4340        let type_ = type_.ok_or_else(|| serde::de::Error::missing_field("type"))?;
4341
4342        let serde_json::Value::String(type_) = type_ else {
4343            return Err(serde::de::Error::custom("`type` must be a string"));
4344        };
4345
4346        match type_.as_str() {
4347            "id" => {
4348                let value = serde_json::from_value(value).map_err(|error| {
4349                    serde::de::Error::custom(format!(
4350                        "`value` must be a string for `type: id`: {error}"
4351                    ))
4352                })?;
4353                Ok(Self::Id { value })
4354            }
4355            "boolean" => {
4356                let value = serde_json::from_value(value).map_err(|error| {
4357                    serde::de::Error::custom(format!(
4358                        "`value` must be a boolean for `type: boolean`: {error}"
4359                    ))
4360                })?;
4361                Ok(Self::Boolean { value })
4362            }
4363            _ => Ok(OtherSessionConfigOptionValue {
4364                type_,
4365                value,
4366                fields,
4367            }
4368            .into()),
4369        }
4370    }
4371}
4372
4373fn is_known_session_config_option_value_type(type_: &str) -> bool {
4374    matches!(type_, "id" | "boolean")
4375}
4376
4377#[cfg(feature = "schemars")]
4378fn other_session_config_option_value_schema(schema: &mut Schema) {
4379    super::schema_util::reject_known_string_discriminators(schema, "type", &["id", "boolean"]);
4380}
4381
4382impl SessionConfigOptionValue {
4383    /// Create an id option value (used by `select` and other id-based option types).
4384    #[must_use]
4385    pub fn id(id: impl Into<SessionConfigValueId>) -> Self {
4386        Self::Id { value: id.into() }
4387    }
4388
4389    /// Create a boolean option value.
4390    #[must_use]
4391    pub fn boolean(val: bool) -> Self {
4392        Self::Boolean { value: val }
4393    }
4394
4395    /// Return the inner [`SessionConfigValueId`] if this is a
4396    /// [`Id`](Self::Id) value.
4397    #[must_use]
4398    pub fn as_id(&self) -> Option<&SessionConfigValueId> {
4399        match self {
4400            Self::Id { value } => Some(value),
4401            _ => None,
4402        }
4403    }
4404
4405    /// Return the inner [`bool`] if this is a [`Boolean`](Self::Boolean) value.
4406    #[must_use]
4407    pub fn as_bool(&self) -> Option<bool> {
4408        match self {
4409            Self::Boolean { value } => Some(*value),
4410            _ => None,
4411        }
4412    }
4413}
4414
4415impl From<SessionConfigValueId> for SessionConfigOptionValue {
4416    fn from(value: SessionConfigValueId) -> Self {
4417        Self::Id { value }
4418    }
4419}
4420
4421impl From<bool> for SessionConfigOptionValue {
4422    fn from(value: bool) -> Self {
4423        Self::Boolean { value }
4424    }
4425}
4426
4427impl From<OtherSessionConfigOptionValue> for SessionConfigOptionValue {
4428    fn from(value: OtherSessionConfigOptionValue) -> Self {
4429        Self::Other(Box::new(value))
4430    }
4431}
4432
4433impl From<&str> for SessionConfigOptionValue {
4434    fn from(value: &str) -> Self {
4435        Self::Id {
4436            value: SessionConfigValueId::new(value),
4437        }
4438    }
4439}
4440
4441/// Request parameters for setting a session configuration option.
4442///
4443/// Agents MUST support this method for any session the Client created or resumed
4444/// where they advertise config options. For a child session, the child's
4445/// capabilities decide whether the Client can send it, and none defined today
4446/// permits it.
4447/// Agents MUST reject an unknown `configId` or invalid value with `-32602` and leave the
4448/// configuration unchanged.
4449///
4450/// See protocol docs: [Session Config Options](https://agentclientprotocol.com/protocol/v2/session-config-options#setting-a-config-option)
4451#[serde_as]
4452#[skip_serializing_none]
4453#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4454#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4455#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_CONFIG_OPTION_METHOD_NAME)))]
4456#[serde(rename_all = "camelCase")]
4457#[non_exhaustive]
4458pub struct SetSessionConfigOptionRequest {
4459    /// The ID of the session to set the configuration option for.
4460    pub session_id: SessionId,
4461    /// The ID of the configuration option to set.
4462    pub config_id: SessionConfigId,
4463    /// The value to set, including a `type` discriminator and the raw `value`.
4464    ///
4465    /// Payloads MUST send `type: "id"` for id-based options.
4466    #[serde(flatten)]
4467    pub value: SessionConfigOptionValue,
4468    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4469    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4470    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4471    ///
4472    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4473    #[serde_as(deserialize_as = "DefaultOnError")]
4474    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4475    #[serde(default)]
4476    #[serde(rename = "_meta")]
4477    pub meta: Option<Meta>,
4478}
4479
4480impl SetSessionConfigOptionRequest {
4481    /// Builds [`SetSessionConfigOptionRequest`] with the required request fields set. Optional fields start unset or empty.
4482    #[must_use]
4483    pub fn new(
4484        session_id: impl Into<SessionId>,
4485        config_id: impl Into<SessionConfigId>,
4486        value: impl Into<SessionConfigOptionValue>,
4487    ) -> Self {
4488        Self {
4489            session_id: session_id.into(),
4490            config_id: config_id.into(),
4491            value: value.into(),
4492            meta: None,
4493        }
4494    }
4495
4496    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4497    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4498    /// do not recognize.
4499    ///
4500    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4501    #[must_use]
4502    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4503        self.meta = meta.into_option();
4504        self
4505    }
4506}
4507
4508/// Response to `session/set_config_option` method.
4509#[serde_as]
4510#[skip_serializing_none]
4511#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4512#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4513#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_CONFIG_OPTION_METHOD_NAME)))]
4514#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}]})))]
4515#[serde(rename_all = "camelCase")]
4516#[non_exhaustive]
4517pub struct SetSessionConfigOptionResponse {
4518    /// The full set of configuration options and their current values.
4519    #[serde_as(deserialize_as = "VecSkipError<_>")]
4520    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
4521    pub config_options: Vec<SessionConfigOption>,
4522    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4523    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4524    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4525    ///
4526    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4527    #[serde_as(deserialize_as = "DefaultOnError")]
4528    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4529    #[serde(default)]
4530    #[serde(rename = "_meta")]
4531    pub meta: Option<Meta>,
4532}
4533
4534impl SetSessionConfigOptionResponse {
4535    /// Builds [`SetSessionConfigOptionResponse`] with the required response fields set. Optional fields start unset or empty.
4536    #[must_use]
4537    pub fn new(config_options: Vec<SessionConfigOption>) -> Self {
4538        Self {
4539            config_options,
4540            meta: None,
4541        }
4542    }
4543
4544    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4545    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4546    /// do not recognize.
4547    ///
4548    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4549    #[must_use]
4550    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4551        self.meta = meta.into_option();
4552        self
4553    }
4554}
4555
4556// MCP
4557
4558/// Configuration for connecting to an MCP (Model Context Protocol) server.
4559///
4560/// MCP servers provide tools and context that the Agent can use when
4561/// processing prompts.
4562///
4563/// See protocol docs: [MCP Servers](https://agentclientprotocol.com/protocol/v2/session-setup#mcp-servers)
4564#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4565#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4566#[serde(tag = "type", rename_all = "snake_case")]
4567#[non_exhaustive]
4568pub enum McpServer {
4569    /// HTTP transport configuration
4570    ///
4571    /// Only available when the Agent capabilities include `session.mcp.http`.
4572    Http(McpServerHttp),
4573    /// **UNSTABLE**
4574    ///
4575    /// This capability is not part of the spec yet, and may be removed or changed at any point.
4576    ///
4577    /// ACP transport configuration
4578    ///
4579    /// Only available when the Agent capabilities include `session.mcp.acp`.
4580    /// The MCP server is provided by an ACP component and communicates over the ACP channel.
4581    #[cfg(feature = "unstable_mcp_over_acp")]
4582    Acp(McpServerAcp),
4583    /// Stdio transport configuration
4584    ///
4585    /// Only available when the Agent capabilities include `session.mcp.stdio`.
4586    Stdio(McpServerStdio),
4587    /// Custom or future MCP server transport configuration.
4588    ///
4589    /// Values beginning with `_` are reserved for implementation-specific
4590    /// extensions. Unknown values that do not begin with `_` are reserved for
4591    /// future ACP variants.
4592    ///
4593    /// Receivers that do not understand this transport SHOULD preserve the raw
4594    /// payload when storing, replaying, proxying, or forwarding session setup
4595    /// data. Agents MUST reject a request with a transport they do not support
4596    /// with `-32602`.
4597    #[serde(untagged)]
4598    Other(OtherMcpServer),
4599}
4600
4601/// Custom or future MCP server transport payload.
4602#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4603#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4604#[cfg_attr(feature = "schemars", schemars(inline))]
4605#[cfg_attr(feature = "schemars", schemars(transform = other_mcp_server_schema))]
4606#[serde(rename_all = "camelCase")]
4607#[non_exhaustive]
4608pub struct OtherMcpServer {
4609    /// Custom or future MCP server transport type.
4610    ///
4611    /// Values beginning with `_` are reserved for implementation-specific
4612    /// extensions. Unknown values that do not begin with `_` are reserved for
4613    /// future ACP variants.
4614    #[serde(rename = "type")]
4615    pub type_: String,
4616    /// Additional fields from the unknown MCP server transport payload.
4617    #[serde(flatten)]
4618    pub fields: IndexMap<String, serde_json::Value>,
4619}
4620
4621impl OtherMcpServer {
4622    /// Builds [`OtherMcpServer`] from an unknown discriminator and preserves the remaining extension fields.
4623    #[must_use]
4624    pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
4625        fields.shift_remove("type");
4626        Self {
4627            type_: type_.into(),
4628            fields,
4629        }
4630    }
4631}
4632
4633impl<'de> Deserialize<'de> for OtherMcpServer {
4634    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4635    where
4636        D: serde::Deserializer<'de>,
4637    {
4638        let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4639        let type_ = fields
4640            .shift_remove("type")
4641            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4642        let serde_json::Value::String(type_) = type_ else {
4643            return Err(serde::de::Error::custom("`type` must be a string"));
4644        };
4645
4646        if is_known_mcp_server_type(&type_) {
4647            return Err(serde::de::Error::custom(format!(
4648                "known MCP server transport `{type_}` did not match its schema"
4649            )));
4650        }
4651
4652        Ok(Self { type_, fields })
4653    }
4654}
4655
4656fn is_known_mcp_server_type(type_: &str) -> bool {
4657    match type_ {
4658        "http" | "stdio" => true,
4659        #[cfg(feature = "unstable_mcp_over_acp")]
4660        "acp" => true,
4661        _ => false,
4662    }
4663}
4664
4665#[cfg(feature = "schemars")]
4666fn other_mcp_server_schema(schema: &mut Schema) {
4667    super::schema_util::reject_known_string_discriminators(
4668        schema,
4669        "type",
4670        &[
4671            "http",
4672            "stdio",
4673            #[cfg(feature = "unstable_mcp_over_acp")]
4674            "acp",
4675        ],
4676    );
4677}
4678
4679/// HTTP transport configuration for MCP.
4680#[serde_as]
4681#[skip_serializing_none]
4682#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4683#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4684#[serde(rename_all = "camelCase")]
4685#[non_exhaustive]
4686pub struct McpServerHttp {
4687    /// Human-readable name identifying this MCP server. MUST be unique within `mcpServers`.
4688    ///
4689    /// Agents reject a request with a duplicate `name` with `-32602`.
4690    pub name: String,
4691    /// URL to the MCP server.
4692    #[cfg_attr(feature = "schemars", schemars(url))]
4693    pub url: String,
4694    /// HTTP headers to set when making requests to the MCP server. Headers the MCP transport
4695    /// defines are owned by the transport, and Agents use the transport's values for them.
4696    #[serde_as(deserialize_as = "DefaultOnNull")]
4697    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4698    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4699    pub headers: Vec<HttpHeader>,
4700    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4701    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4702    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4703    ///
4704    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4705    #[serde_as(deserialize_as = "DefaultOnError")]
4706    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4707    #[serde(default)]
4708    #[serde(rename = "_meta")]
4709    pub meta: Option<Meta>,
4710}
4711
4712impl McpServerHttp {
4713    /// Builds [`McpServerHttp`] with the required fields set. Optional fields start unset or empty.
4714    #[must_use]
4715    pub fn new(name: impl Into<String>, url: impl Into<String>) -> Self {
4716        Self {
4717            name: name.into(),
4718            url: url.into(),
4719            headers: Vec::new(),
4720            meta: None,
4721        }
4722    }
4723
4724    /// HTTP headers to set when making requests to the MCP server. Headers the MCP transport
4725    /// defines are owned by the transport, and Agents use the transport's values for them.
4726    #[must_use]
4727    pub fn headers(mut self, headers: Vec<HttpHeader>) -> Self {
4728        self.headers = headers;
4729        self
4730    }
4731
4732    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4733    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4734    /// do not recognize.
4735    ///
4736    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4737    #[must_use]
4738    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4739        self.meta = meta.into_option();
4740        self
4741    }
4742}
4743
4744/// **UNSTABLE**
4745///
4746/// This capability is not part of the spec yet, and may be removed or changed at any point.
4747///
4748/// Unique identifier for an MCP server using the ACP transport.
4749///
4750/// The value is opaque and generated by the ACP component providing the MCP server. It is
4751/// used by `mcp/message` to route requests to the component that declared the server.
4752#[cfg(feature = "unstable_mcp_over_acp")]
4753#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4754#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
4755#[serde(transparent)]
4756#[from(forward)]
4757#[non_exhaustive]
4758pub struct McpServerAcpId(pub Arc<str>);
4759
4760#[cfg(feature = "unstable_mcp_over_acp")]
4761impl McpServerAcpId {
4762    /// Wraps a protocol string as a typed [`McpServerAcpId`].
4763    #[must_use]
4764    pub fn new(id: impl Into<Self>) -> Self {
4765        id.into()
4766    }
4767}
4768
4769/// **UNSTABLE**
4770///
4771/// This capability is not part of the spec yet, and may be removed or changed at any point.
4772///
4773/// ACP transport configuration for MCP.
4774///
4775/// The MCP server is provided by an ACP component and communicates over the ACP channel
4776/// using `mcp/message`.
4777#[serde_as]
4778#[skip_serializing_none]
4779#[cfg(feature = "unstable_mcp_over_acp")]
4780#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4781#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4782#[serde(rename_all = "camelCase")]
4783#[non_exhaustive]
4784pub struct McpServerAcp {
4785    /// Human-readable name identifying this MCP server. MUST be unique within `mcpServers`.
4786    ///
4787    /// Agents reject a request with a duplicate `name` with `-32602`.
4788    pub name: String,
4789    /// Unique identifier for this MCP server, generated by the component providing it.
4790    ///
4791    /// Providers MUST NOT reuse an ID for multiple ACP-transport MCP servers that are visible
4792    /// on the same ACP connection.
4793    pub server_id: McpServerAcpId,
4794    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4795    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4796    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4797    ///
4798    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4799    #[serde_as(deserialize_as = "DefaultOnError")]
4800    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4801    #[serde(default)]
4802    #[serde(rename = "_meta")]
4803    pub meta: Option<Meta>,
4804}
4805
4806#[cfg(feature = "unstable_mcp_over_acp")]
4807impl McpServerAcp {
4808    /// Builds [`McpServerAcp`] with the required fields set. Optional fields start unset or empty.
4809    #[must_use]
4810    pub fn new(name: impl Into<String>, server_id: impl Into<McpServerAcpId>) -> Self {
4811        Self {
4812            name: name.into(),
4813            server_id: server_id.into(),
4814            meta: None,
4815        }
4816    }
4817
4818    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4819    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4820    /// do not recognize.
4821    ///
4822    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4823    #[must_use]
4824    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4825        self.meta = meta.into_option();
4826        self
4827    }
4828}
4829
4830/// Stdio transport configuration for MCP.
4831#[serde_as]
4832#[skip_serializing_none]
4833#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4834#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4835#[serde(rename_all = "camelCase")]
4836#[non_exhaustive]
4837pub struct McpServerStdio {
4838    /// Human-readable name identifying this MCP server. MUST be unique within `mcpServers`.
4839    ///
4840    /// Agents reject a request with a duplicate `name` with `-32602`.
4841    pub name: String,
4842    /// Path to the MCP server executable. Must be an absolute path.
4843    ///
4844    /// Agents reject a request with a relative `command` with `-32602`.
4845    pub command: AbsolutePath,
4846    /// Command-line arguments to pass to the MCP server.
4847    #[serde_as(deserialize_as = "DefaultOnNull")]
4848    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4849    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4850    pub args: Vec<String>,
4851    /// Environment variables to set when launching the MCP server. Names SHOULD be unique.
4852    /// Agents MAY reject duplicates with `-32602`, and otherwise the last entry wins.
4853    #[serde_as(deserialize_as = "DefaultOnNull")]
4854    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4855    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4856    pub env: Vec<EnvVariable>,
4857    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4858    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4859    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4860    ///
4861    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4862    #[serde_as(deserialize_as = "DefaultOnError")]
4863    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4864    #[serde(default)]
4865    #[serde(rename = "_meta")]
4866    pub meta: Option<Meta>,
4867}
4868
4869impl McpServerStdio {
4870    /// Builds [`McpServerStdio`] with the required fields set. Optional fields start unset or empty.
4871    #[must_use]
4872    pub fn new(name: impl Into<String>, command: impl Into<AbsolutePath>) -> Self {
4873        Self {
4874            name: name.into(),
4875            command: command.into(),
4876            args: Vec::new(),
4877            env: Vec::new(),
4878            meta: None,
4879        }
4880    }
4881
4882    /// Command-line arguments to pass to the MCP server.
4883    #[must_use]
4884    pub fn args(mut self, args: Vec<String>) -> Self {
4885        self.args = args;
4886        self
4887    }
4888
4889    /// Environment variables to set when launching the MCP server. Names SHOULD be unique.
4890    /// Agents MAY reject duplicates with `-32602`, and otherwise the last entry wins.
4891    #[must_use]
4892    pub fn env(mut self, env: Vec<EnvVariable>) -> Self {
4893        self.env = env;
4894        self
4895    }
4896
4897    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4898    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4899    /// do not recognize.
4900    ///
4901    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4902    #[must_use]
4903    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4904        self.meta = meta.into_option();
4905        self
4906    }
4907}
4908
4909/// An environment variable to set when launching a process.
4910#[serde_as]
4911#[skip_serializing_none]
4912#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4913#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4914#[serde(rename_all = "camelCase")]
4915#[non_exhaustive]
4916pub struct EnvVariable {
4917    /// The name of the environment variable.
4918    pub name: String,
4919    /// The value to set for the environment variable.
4920    pub value: String,
4921    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4922    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4923    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4924    ///
4925    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4926    #[serde_as(deserialize_as = "DefaultOnError")]
4927    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4928    #[serde(default)]
4929    #[serde(rename = "_meta")]
4930    pub meta: Option<Meta>,
4931}
4932
4933impl EnvVariable {
4934    /// Builds [`EnvVariable`] with the required fields set. Optional fields start unset or empty.
4935    #[must_use]
4936    pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
4937        Self {
4938            name: name.into(),
4939            value: value.into(),
4940            meta: None,
4941        }
4942    }
4943
4944    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4945    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4946    /// do not recognize.
4947    ///
4948    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4949    #[must_use]
4950    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4951        self.meta = meta.into_option();
4952        self
4953    }
4954}
4955
4956/// An HTTP header to set when making requests to the MCP server.
4957#[serde_as]
4958#[skip_serializing_none]
4959#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4960#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4961#[serde(rename_all = "camelCase")]
4962#[non_exhaustive]
4963pub struct HttpHeader {
4964    /// The name of the HTTP header.
4965    pub name: String,
4966    /// The value to set for the HTTP header.
4967    pub value: String,
4968    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4969    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4970    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4971    ///
4972    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4973    #[serde_as(deserialize_as = "DefaultOnError")]
4974    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4975    #[serde(default)]
4976    #[serde(rename = "_meta")]
4977    pub meta: Option<Meta>,
4978}
4979
4980impl HttpHeader {
4981    /// Builds [`HttpHeader`] with the required fields set. Optional fields start unset or empty.
4982    #[must_use]
4983    pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
4984        Self {
4985            name: name.into(),
4986            value: value.into(),
4987            meta: None,
4988        }
4989    }
4990
4991    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4992    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4993    /// do not recognize.
4994    ///
4995    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4996    #[must_use]
4997    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4998        self.meta = meta.into_option();
4999        self
5000    }
5001}
5002
5003// System prompt
5004
5005/// Client-provided system-level instructions for a session.
5006///
5007/// Clients MUST only send this when the Agent advertises
5008/// `session.systemPrompt`. Agents that cannot apply it, for example because of
5009/// an unadvertised mode or an unsupported content block type, MUST return an
5010/// error instead of creating or resuming the session.
5011#[serde_as]
5012#[skip_serializing_none]
5013#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5014#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5015#[serde(rename_all = "camelCase")]
5016#[non_exhaustive]
5017pub struct SystemPrompt {
5018    /// How the Agent combines `content` with its own instructions.
5019    ///
5020    /// Required. Agents MUST return an error for a mode they do not support rather than
5021    /// treating it as `append` or `override`.
5022    pub mode: SystemPromptMode,
5023    /// The system prompt content.
5024    ///
5025    /// Agents advertising the capability MUST accept `text` content blocks.
5026    /// Clients MUST NOT send other content block types until a future
5027    /// capability allows them, and Agents MUST return an error for content
5028    /// blocks they do not support, including unknown types.
5029    ///
5030    /// Clients MUST NOT send an empty array. Agents MAY reject one with
5031    /// `-32602` without creating or resuming the session.
5032    #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
5033    pub content: Vec<ContentBlock>,
5034    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5035    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5036    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5037    ///
5038    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5039    #[serde_as(deserialize_as = "DefaultOnError")]
5040    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5041    #[serde(default)]
5042    #[serde(rename = "_meta")]
5043    pub meta: Option<Meta>,
5044}
5045
5046impl SystemPrompt {
5047    /// Builds [`SystemPrompt`] with the required fields set. Optional fields start unset or empty.
5048    ///
5049    /// `mode` starts as [`SystemPromptMode::Append`]. Use [`SystemPrompt::mode`]
5050    /// to request another mode.
5051    #[must_use]
5052    pub fn new(content: Vec<ContentBlock>) -> Self {
5053        Self {
5054            mode: SystemPromptMode::default(),
5055            content,
5056            meta: None,
5057        }
5058    }
5059
5060    /// How the Agent combines `content` with its own instructions.
5061    #[must_use]
5062    pub fn mode(mut self, mode: SystemPromptMode) -> Self {
5063        self.mode = mode;
5064        self
5065    }
5066
5067    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5068    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5069    /// do not recognize.
5070    ///
5071    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5072    #[must_use]
5073    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5074        self.meta = meta.into_option();
5075        self
5076    }
5077}
5078
5079/// How the Agent combines a Client-provided system prompt with its own instructions.
5080///
5081/// Unknown modes are preserved so they can be stored,
5082/// proxied, or forwarded. An Agent MUST return an error for a mode it does not
5083/// support rather than treating it as `append` or `override`.
5084#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5085#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
5086#[serde(rename_all = "snake_case")]
5087#[non_exhaustive]
5088pub enum SystemPromptMode {
5089    /// Add the content to the Agent's own instructions rather than replacing them.
5090    ///
5091    /// Every Agent that advertises `session.systemPrompt` supports this mode.
5092    /// Agents SHOULD give the content system-level precedence, for example in the
5093    /// model's system prompt or developer instructions rather than in user-turn
5094    /// content. Where it is placed and how it is formatted is implementation-defined.
5095    #[default]
5096    Append,
5097    /// Replace the Agent's built-in default instructions with the content.
5098    ///
5099    /// This does not change tool availability, MCP servers, permissions, or session
5100    /// configuration. Context the Agent supplies from the workspace or environment
5101    /// MAY still be included. Clients that use this mode take responsibility for any
5102    /// tool guidance or safety instructions the Agent's default instructions
5103    /// provided, and MUST only use it when the Agent advertises
5104    /// `session.systemPrompt.mode.override`.
5105    Override,
5106    /// Custom or future system prompt mode.
5107    ///
5108    /// Values beginning with `_` are reserved for implementation-specific
5109    /// extensions. Unknown values that do not begin with `_` are reserved for
5110    /// future ACP variants.
5111    #[serde(untagged)]
5112    Other(String),
5113}
5114
5115// Prompt
5116
5117/// A key the Client generates to identify one `session/prompt` submission across attempts.
5118///
5119/// The key is an opaque, case-sensitive string of 1 to 255 characters. It is scoped to the
5120/// session named by the request's `sessionId`.
5121///
5122/// See protocol docs: [Retrying a prompt](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#retrying-a-prompt)
5123#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5124#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash, Display)]
5125#[serde(transparent)]
5126pub struct IdempotencyKey(
5127    #[cfg_attr(feature = "schemars", schemars(length(min = 1, max = 255)))] Arc<str>,
5128);
5129
5130impl IdempotencyKey {
5131    /// The maximum length of a key, in characters.
5132    pub const MAX_LENGTH: usize = 255;
5133
5134    /// Wraps a string as a typed [`IdempotencyKey`].
5135    ///
5136    /// # Errors
5137    ///
5138    /// Returns [`InvalidIdempotencyKey`] if the key is empty or longer than
5139    /// [`Self::MAX_LENGTH`] characters.
5140    pub fn new(key: impl Into<Arc<str>>) -> Result<Self, InvalidIdempotencyKey> {
5141        let key = key.into();
5142        if key.is_empty() {
5143            return Err(InvalidIdempotencyKey::Empty);
5144        }
5145        // The limit counts characters, as JSON Schema `maxLength` does, not bytes.
5146        if key.chars().nth(Self::MAX_LENGTH).is_some() {
5147            return Err(InvalidIdempotencyKey::TooLong);
5148        }
5149        Ok(Self(key))
5150    }
5151
5152    /// Generates a key from a random version 4 UUID ([RFC 9562]).
5153    ///
5154    /// Generate one key per submission, when the user submits the input, and store it
5155    /// with the pending input. Every attempt for that submission sends the same key.
5156    ///
5157    /// [RFC 9562]: https://www.rfc-editor.org/rfc/rfc9562
5158    #[cfg(feature = "uuid")]
5159    #[must_use]
5160    pub fn generate() -> Self {
5161        uuid::Uuid::new_v4().into()
5162    }
5163
5164    /// Returns the key as a string slice.
5165    #[must_use]
5166    pub fn as_str(&self) -> &str {
5167        &self.0
5168    }
5169}
5170
5171impl AsRef<str> for IdempotencyKey {
5172    fn as_ref(&self) -> &str {
5173        &self.0
5174    }
5175}
5176
5177#[cfg(feature = "uuid")]
5178impl From<uuid::Uuid> for IdempotencyKey {
5179    /// Uses the UUID's hyphenated lowercase form. It is 36 characters, so it is always a
5180    /// valid key.
5181    fn from(uuid: uuid::Uuid) -> Self {
5182        Self(uuid.to_string().into())
5183    }
5184}
5185
5186impl TryFrom<String> for IdempotencyKey {
5187    type Error = InvalidIdempotencyKey;
5188
5189    fn try_from(key: String) -> Result<Self, Self::Error> {
5190        Self::new(key)
5191    }
5192}
5193
5194impl TryFrom<&str> for IdempotencyKey {
5195    type Error = InvalidIdempotencyKey;
5196
5197    fn try_from(key: &str) -> Result<Self, Self::Error> {
5198        Self::new(key)
5199    }
5200}
5201
5202impl std::str::FromStr for IdempotencyKey {
5203    type Err = InvalidIdempotencyKey;
5204
5205    fn from_str(key: &str) -> Result<Self, Self::Err> {
5206        Self::new(key)
5207    }
5208}
5209
5210// Deserialization validates the key, so a malformed value fails the request
5211// instead of being treated as omitted.
5212impl<'de> Deserialize<'de> for IdempotencyKey {
5213    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
5214    where
5215        D: serde::Deserializer<'de>,
5216    {
5217        let key = Arc::<str>::deserialize(deserializer)?;
5218        Self::new(key).map_err(serde::de::Error::custom)
5219    }
5220}
5221
5222/// Error returned when a string is not a valid [`IdempotencyKey`].
5223#[derive(Debug, Clone, Copy, PartialEq, Eq, Display)]
5224#[non_exhaustive]
5225pub enum InvalidIdempotencyKey {
5226    /// The key is an empty string.
5227    #[display("idempotency key must not be empty")]
5228    Empty,
5229    /// The key is longer than [`IdempotencyKey::MAX_LENGTH`] characters.
5230    #[display(
5231        "idempotency key must be at most {} characters",
5232        IdempotencyKey::MAX_LENGTH
5233    )]
5234    TooLong,
5235}
5236
5237impl std::error::Error for InvalidIdempotencyKey {}
5238
5239/// Request parameters for sending a user prompt to the Agent.
5240///
5241/// Contains the user's message and any additional context.
5242///
5243/// See protocol docs: [User Message](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#1-user-message)
5244#[serde_as]
5245#[skip_serializing_none]
5246#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5247#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5248#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_PROMPT_METHOD_NAME)))]
5249#[serde(rename_all = "camelCase")]
5250#[non_exhaustive]
5251pub struct PromptRequest {
5252    /// The ID of the session to send this user message to
5253    pub session_id: SessionId,
5254    /// The blocks of content that compose the user's message.
5255    ///
5256    /// As a baseline, the Agent MUST support `text` and `resource_link` content blocks,
5257    /// while other variants are optionally enabled via `PromptCapabilities`.
5258    ///
5259    /// The Client MUST adapt its interface according to `PromptCapabilities`.
5260    ///
5261    /// The Client MAY include referenced pieces of context as either
5262    /// `resource` or `resource_link` content blocks.
5263    ///
5264    /// When available, `resource` is preferred
5265    /// as it avoids extra round-trips and allows the message to include
5266    /// pieces of context from sources the Agent might not have access to.
5267    ///
5268    /// Clients MUST NOT send an empty array. Agents MAY reject one with `-32602` without
5269    /// inserting it.
5270    #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
5271    pub prompt: Vec<ContentBlock>,
5272    /// Identifies one prompt submission within this session.
5273    ///
5274    /// Optional. Omitted and `null` are equivalent and mean no key. The Agent then handles
5275    /// the prompt without duplicate detection.
5276    ///
5277    /// The Client generates the key and sends the same key on every attempt for the same
5278    /// submission. Agents that advertise `capabilities.session` MUST support the key.
5279    /// A retry of a recorded insertion returns the original `messageId` without inserting
5280    /// another message.
5281    ///
5282    /// The Agent MUST recognize the key for as long as it retains the message, including
5283    /// across connections and Agent restarts. For a live-only message, it MUST recognize
5284    /// the key while the session stays active on a connection. A retry with a forgotten
5285    /// key is a new submission, even immediately after reconnecting. If a duplicate
5286    /// would matter and the Client cannot rule it out, it SHOULD NOT retry automatically.
5287    ///
5288    /// When present, the value is an opaque, case-sensitive string of 1 to 255 characters.
5289    /// Agents MUST reject any other value with `-32602` (Invalid params) and MUST NOT treat
5290    /// it as omitted.
5291    ///
5292    /// See protocol docs: [Retrying a prompt](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#retrying-a-prompt)
5293    #[serde(default)]
5294    pub idempotency_key: Option<IdempotencyKey>,
5295    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5296    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5297    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5298    ///
5299    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5300    #[serde_as(deserialize_as = "DefaultOnError")]
5301    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5302    #[serde(default)]
5303    #[serde(rename = "_meta")]
5304    pub meta: Option<Meta>,
5305}
5306
5307impl PromptRequest {
5308    /// Builds [`PromptRequest`] with the required request fields set. Optional fields start unset or empty.
5309    #[must_use]
5310    pub fn new(session_id: impl Into<SessionId>, prompt: Vec<ContentBlock>) -> Self {
5311        Self {
5312            session_id: session_id.into(),
5313            prompt,
5314            idempotency_key: None,
5315            meta: None,
5316        }
5317    }
5318
5319    /// Sets the key for this submission. `None` means no key.
5320    ///
5321    /// See protocol docs: [Retrying a prompt](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#retrying-a-prompt)
5322    #[must_use]
5323    pub fn idempotency_key(mut self, idempotency_key: impl IntoOption<IdempotencyKey>) -> Self {
5324        self.idempotency_key = idempotency_key.into_option();
5325        self
5326    }
5327
5328    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5329    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5330    /// do not recognize.
5331    ///
5332    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5333    #[must_use]
5334    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5335        self.meta = meta.into_option();
5336        self
5337    }
5338}
5339
5340/// Response acknowledging that a user prompt was inserted into the ACP conversation.
5341///
5342/// This response does not indicate that the prompt was merely received or held, nor that the
5343/// Agent has finished processing it.
5344/// Processing and completion are reported through `state_update` session updates.
5345///
5346/// Insertion is the logical addition of a user message with a message ID and a position
5347/// relative to other messages in the ACP conversation.
5348///
5349/// See protocol docs: [Prompt Accepted](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#2-prompt-accepted)
5350#[serde_as]
5351#[skip_serializing_none]
5352#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5353#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5354#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_PROMPT_METHOD_NAME)))]
5355#[serde(rename_all = "camelCase")]
5356#[non_exhaustive]
5357pub struct PromptResponse {
5358    /// Identifies the user message inserted into the ACP conversation.
5359    ///
5360    /// Required and non-null. Omission and explicit `null` are both invalid.
5361    ///
5362    /// The corresponding user-message session update carries this same identifier and may arrive
5363    /// before or after this response. Agents MUST echo the message during the live session, but are
5364    /// not required to retain it. If retained and replayed, the message keeps this identifier.
5365    pub message_id: MessageId,
5366    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5367    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5368    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5369    ///
5370    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5371    #[serde_as(deserialize_as = "DefaultOnError")]
5372    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5373    #[serde(default)]
5374    #[serde(rename = "_meta")]
5375    pub meta: Option<Meta>,
5376}
5377
5378impl PromptResponse {
5379    /// Builds [`PromptResponse`] with the required response fields set. Optional fields start unset or empty.
5380    #[must_use]
5381    pub fn new(message_id: impl Into<MessageId>) -> Self {
5382        Self {
5383            message_id: message_id.into(),
5384            meta: None,
5385        }
5386    }
5387
5388    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5389    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5390    /// do not recognize.
5391    ///
5392    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5393    #[must_use]
5394    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5395        self.meta = meta.into_option();
5396        self
5397    }
5398}
5399
5400/// Reasons why an Agent stops active session work.
5401///
5402/// See protocol docs: [Stop Reasons](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#stop-reasons)
5403#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5404#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
5405#[serde(tag = "stopReason", rename_all = "snake_case")]
5406#[non_exhaustive]
5407pub enum StopReason {
5408    /// The active work ended successfully.
5409    /// Includes locally handled commands that required no model call.
5410    EndTurn,
5411    /// The active work ended because the Agent reached the maximum number of tokens.
5412    MaxTokens,
5413    /// The active work ended because the Agent reached the maximum number of
5414    /// model requests for the foreground work.
5415    MaxTurnRequests,
5416    /// The active work ended because the Agent refused to continue.
5417    Refusal,
5418    /// The user or Client chose to stop the work: via `session/cancel`, by
5419    /// closing the session, or through an interaction the Agent offers, such
5420    /// as a permission option that tells the Agent to stop. A child session
5421    /// also reports this reason when its parent cancels its work. Other work
5422    /// the Agent stops for its own reasons uses another reason, such as
5423    /// `error` for an internal timeout.
5424    ///
5425    /// Agents MUST report this stop reason on an idle `state_update` when
5426    /// cancellation ends active foreground work, even if aborting causes
5427    /// exceptions. Agents MUST catch these errors and report `cancelled`, not
5428    /// `error`.
5429    Cancelled,
5430    /// The active work ended because something failed.
5431    ///
5432    /// This includes pre-insertion foreground work. A prompt failure before
5433    /// insertion also requires an error response to `session/prompt`. After
5434    /// insertion, the prompt's response remains successful.
5435    Error(ErrorStopReason),
5436    /// Custom or future stop reason.
5437    ///
5438    /// Values beginning with `_` are reserved for implementation-specific
5439    /// extensions. Unknown values that do not begin with `_` are reserved for
5440    /// future ACP variants.
5441    #[serde(untagged)]
5442    Other(OtherStopReason),
5443}
5444
5445impl From<ErrorStopReason> for StopReason {
5446    fn from(value: ErrorStopReason) -> Self {
5447        Self::Error(value)
5448    }
5449}
5450
5451/// Details of a failure that ended active work.
5452#[serde_as]
5453#[skip_serializing_none]
5454#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5455#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
5456#[serde(rename_all = "camelCase")]
5457#[non_exhaustive]
5458pub struct ErrorStopReason {
5459    /// The failure, as a JSON-RPC error object.
5460    ///
5461    /// Optional. Omitted and `null` are equivalent and mean the Agent is not reporting failure details.
5462    /// Agents SHOULD include it.
5463    #[serde_as(deserialize_as = "DefaultOnError")]
5464    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5465    #[serde(default)]
5466    pub error: Option<Box<Error>>,
5467}
5468
5469impl ErrorStopReason {
5470    /// Builds [`ErrorStopReason`] with the required fields set. Optional fields start unset or empty.
5471    #[must_use]
5472    pub fn new() -> Self {
5473        Self::default()
5474    }
5475
5476    /// The failure, as a JSON-RPC error object.
5477    #[must_use]
5478    pub fn error(mut self, error: impl IntoOption<Error>) -> Self {
5479        self.error = error.into_option().map(Box::new);
5480        self
5481    }
5482}
5483
5484/// Custom or future stop reason payload.
5485#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5486#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
5487#[cfg_attr(feature = "schemars", schemars(inline))]
5488#[cfg_attr(feature = "schemars", schemars(transform = other_stop_reason_schema))]
5489#[serde(rename_all = "camelCase")]
5490#[non_exhaustive]
5491pub struct OtherStopReason {
5492    /// Custom or future stop reason.
5493    ///
5494    /// Values beginning with `_` are reserved for implementation-specific
5495    /// extensions. Unknown values that do not begin with `_` are reserved for
5496    /// future ACP variants.
5497    pub stop_reason: String,
5498    /// Additional fields from the unknown stop reason payload.
5499    #[serde(flatten)]
5500    pub fields: IndexMap<String, serde_json::Value>,
5501}
5502
5503impl OtherStopReason {
5504    /// Builds [`OtherStopReason`] from an unknown discriminator and preserves the remaining extension fields.
5505    #[must_use]
5506    pub fn new(
5507        stop_reason: impl Into<String>,
5508        mut fields: IndexMap<String, serde_json::Value>,
5509    ) -> Self {
5510        remove_idle_state_update_fields(&mut fields);
5511        Self {
5512            stop_reason: stop_reason.into(),
5513            fields,
5514        }
5515    }
5516}
5517
5518impl<'de> Deserialize<'de> for OtherStopReason {
5519    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
5520    where
5521        D: serde::Deserializer<'de>,
5522    {
5523        let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
5524        let stop_reason = fields
5525            .shift_remove("stopReason")
5526            .ok_or_else(|| serde::de::Error::missing_field("stopReason"))?;
5527        let serde_json::Value::String(stop_reason) = stop_reason else {
5528            return Err(serde::de::Error::custom("`stopReason` must be a string"));
5529        };
5530
5531        if KNOWN_STOP_REASONS.contains(&stop_reason.as_str()) {
5532            return Err(serde::de::Error::custom(format!(
5533                "known stop reason `{stop_reason}` did not match its schema"
5534            )));
5535        }
5536        remove_idle_state_update_fields(&mut fields);
5537
5538        Ok(Self {
5539            stop_reason,
5540            fields,
5541        })
5542    }
5543}
5544
5545const KNOWN_STOP_REASONS: &[&str] = &[
5546    "end_turn",
5547    "max_tokens",
5548    "max_turn_requests",
5549    "refusal",
5550    "cancelled",
5551    "error",
5552];
5553
5554/// Keeps the idle update's own fields out of an unknown stop reason's payload.
5555fn remove_idle_state_update_fields(fields: &mut IndexMap<String, serde_json::Value>) {
5556    fields.shift_remove("stopReason");
5557    fields.shift_remove("usage");
5558    fields.shift_remove("_meta");
5559}
5560
5561#[cfg(feature = "schemars")]
5562fn other_stop_reason_schema(schema: &mut Schema) {
5563    super::schema_util::reject_known_string_discriminators(
5564        schema,
5565        "stopReason",
5566        KNOWN_STOP_REASONS,
5567    );
5568}
5569
5570/// **UNSTABLE**
5571///
5572/// This capability is not part of the spec yet, and may be removed or changed at any point.
5573///
5574/// Token usage for the foreground work that just completed, not cumulative for the session.
5575#[cfg(feature = "unstable_end_turn_token_usage")]
5576#[serde_as]
5577#[skip_serializing_none]
5578#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5579#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5580#[serde(rename_all = "camelCase")]
5581#[non_exhaustive]
5582pub struct Usage {
5583    /// Sum of all token types for the completed work.
5584    pub total_tokens: u64,
5585    /// Input tokens for the completed work.
5586    pub input_tokens: u64,
5587    /// Output tokens for the completed work.
5588    pub output_tokens: u64,
5589    /// Thought/reasoning tokens for the completed work.
5590    ///
5591    /// Omitted and `null` are equivalent and mean the count is not reported.
5592    #[serde_as(deserialize_as = "DefaultOnError")]
5593    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5594    #[serde(default)]
5595    pub thought_tokens: Option<u64>,
5596    /// Cache read tokens for the completed work.
5597    ///
5598    /// Omitted and `null` are equivalent and mean the count is not reported.
5599    #[serde_as(deserialize_as = "DefaultOnError")]
5600    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5601    #[serde(default)]
5602    pub cached_read_tokens: Option<u64>,
5603    /// Cache write tokens for the completed work.
5604    ///
5605    /// Omitted and `null` are equivalent and mean the count is not reported.
5606    #[serde_as(deserialize_as = "DefaultOnError")]
5607    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5608    #[serde(default)]
5609    pub cached_write_tokens: Option<u64>,
5610    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5611    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5612    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5613    ///
5614    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5615    #[serde_as(deserialize_as = "DefaultOnError")]
5616    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5617    #[serde(default)]
5618    #[serde(rename = "_meta")]
5619    pub meta: Option<Meta>,
5620}
5621
5622#[cfg(feature = "unstable_end_turn_token_usage")]
5623impl Usage {
5624    /// Builds [`Usage`] with the required fields set. Optional fields start unset or empty.
5625    #[must_use]
5626    pub fn new(total_tokens: u64, input_tokens: u64, output_tokens: u64) -> Self {
5627        Self {
5628            total_tokens,
5629            input_tokens,
5630            output_tokens,
5631            thought_tokens: None,
5632            cached_read_tokens: None,
5633            cached_write_tokens: None,
5634            meta: None,
5635        }
5636    }
5637
5638    /// Thought/reasoning tokens for the completed work.
5639    #[must_use]
5640    pub fn thought_tokens(mut self, thought_tokens: impl IntoOption<u64>) -> Self {
5641        self.thought_tokens = thought_tokens.into_option();
5642        self
5643    }
5644
5645    /// Cache read tokens for the completed work.
5646    #[must_use]
5647    pub fn cached_read_tokens(mut self, cached_read_tokens: impl IntoOption<u64>) -> Self {
5648        self.cached_read_tokens = cached_read_tokens.into_option();
5649        self
5650    }
5651
5652    /// Cache write tokens for the completed work.
5653    #[must_use]
5654    pub fn cached_write_tokens(mut self, cached_write_tokens: impl IntoOption<u64>) -> Self {
5655        self.cached_write_tokens = cached_write_tokens.into_option();
5656        self
5657    }
5658
5659    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5660    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5661    /// do not recognize.
5662    ///
5663    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5664    #[must_use]
5665    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5666        self.meta = meta.into_option();
5667        self
5668    }
5669}
5670
5671// Providers
5672
5673/// **UNSTABLE**
5674///
5675/// This capability is not part of the spec yet, and may be removed or changed at any point.
5676///
5677/// Well-known API protocol identifiers for LLM providers.
5678///
5679/// Agents and Clients MUST handle unknown protocol identifiers gracefully.
5680///
5681/// Protocol names beginning with `_` are free for custom use, like other ACP extension methods.
5682/// Protocol names that do not begin with `_` are reserved for the ACP spec.
5683#[cfg(feature = "unstable_llm_providers")]
5684#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5685#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5686#[serde(rename_all = "snake_case")]
5687#[non_exhaustive]
5688pub enum LlmProtocol {
5689    /// Anthropic API protocol.
5690    Anthropic,
5691    /// OpenAI API protocol.
5692    #[serde(rename = "openai")]
5693    OpenAi,
5694    /// Azure OpenAI API protocol.
5695    Azure,
5696    /// Google Vertex AI API protocol.
5697    Vertex,
5698    /// AWS Bedrock API protocol.
5699    Bedrock,
5700    /// Custom or future protocol.
5701    ///
5702    /// Values beginning with `_` are reserved for implementation-specific
5703    /// extensions. Unknown values that do not begin with `_` are reserved for
5704    /// future ACP variants.
5705    #[serde(untagged)]
5706    Other(String),
5707}
5708
5709/// **UNSTABLE**
5710///
5711/// This capability is not part of the spec yet, and may be removed or changed at any point.
5712///
5713/// Current effective non-secret routing configuration for a provider.
5714#[cfg(feature = "unstable_llm_providers")]
5715#[serde_as]
5716#[skip_serializing_none]
5717#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5718#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5719#[serde(rename_all = "camelCase")]
5720#[non_exhaustive]
5721pub struct ProviderCurrentConfig {
5722    /// Protocol currently used by this provider.
5723    pub api_type: LlmProtocol,
5724    /// Base URL currently used by this provider.
5725    #[cfg_attr(feature = "schemars", schemars(url))]
5726    pub base_url: String,
5727    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5728    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5729    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5730    ///
5731    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5732    #[serde_as(deserialize_as = "DefaultOnError")]
5733    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5734    #[serde(default)]
5735    #[serde(rename = "_meta")]
5736    pub meta: Option<Meta>,
5737}
5738
5739#[cfg(feature = "unstable_llm_providers")]
5740impl ProviderCurrentConfig {
5741    /// Builds [`ProviderCurrentConfig`] with the required fields set. Optional fields start unset or empty.
5742    #[must_use]
5743    pub fn new(api_type: LlmProtocol, base_url: impl Into<String>) -> Self {
5744        Self {
5745            api_type,
5746            base_url: base_url.into(),
5747            meta: None,
5748        }
5749    }
5750
5751    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5752    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5753    /// do not recognize.
5754    ///
5755    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5756    #[must_use]
5757    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5758        self.meta = meta.into_option();
5759        self
5760    }
5761}
5762
5763/// **UNSTABLE**
5764///
5765/// This capability is not part of the spec yet, and may be removed or changed at any point.
5766///
5767/// Unique identifier for a configurable LLM provider.
5768#[cfg(feature = "unstable_llm_providers")]
5769#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5770#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
5771#[serde(transparent)]
5772#[from(forward)]
5773#[non_exhaustive]
5774pub struct ProviderId(pub Arc<str>);
5775
5776#[cfg(feature = "unstable_llm_providers")]
5777impl ProviderId {
5778    /// Wraps a protocol string as a typed [`ProviderId`].
5779    #[must_use]
5780    pub fn new(id: impl Into<Self>) -> Self {
5781        id.into()
5782    }
5783}
5784
5785/// **UNSTABLE**
5786///
5787/// This capability is not part of the spec yet, and may be removed or changed at any point.
5788///
5789/// Information about a configurable LLM provider.
5790#[cfg(feature = "unstable_llm_providers")]
5791#[serde_as]
5792#[skip_serializing_none]
5793#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5794#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5795#[serde(rename_all = "camelCase")]
5796#[non_exhaustive]
5797pub struct ProviderInfo {
5798    /// Provider identifier, for example "main" or "openai".
5799    pub provider_id: ProviderId,
5800    /// Supported protocol types for this provider.
5801    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
5802    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
5803    pub supported: Vec<LlmProtocol>,
5804    /// Whether this provider is mandatory and cannot be disabled via `providers/disable`.
5805    /// If true, Clients MUST NOT call `providers/disable` for this provider ID.
5806    pub required: bool,
5807    /// Current effective non-secret routing config.
5808    /// Null or omitted means provider is disabled.
5809    #[serde(default)]
5810    pub current: Option<ProviderCurrentConfig>,
5811    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5812    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5813    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5814    ///
5815    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5816    #[serde_as(deserialize_as = "DefaultOnError")]
5817    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5818    #[serde(default)]
5819    #[serde(rename = "_meta")]
5820    pub meta: Option<Meta>,
5821}
5822
5823#[cfg(feature = "unstable_llm_providers")]
5824impl ProviderInfo {
5825    /// Builds [`ProviderInfo`] with the required fields set. Optional fields start unset or empty.
5826    #[must_use]
5827    pub fn new(
5828        provider_id: impl Into<ProviderId>,
5829        supported: Vec<LlmProtocol>,
5830        required: bool,
5831        current: impl IntoOption<ProviderCurrentConfig>,
5832    ) -> Self {
5833        Self {
5834            provider_id: provider_id.into(),
5835            supported,
5836            required,
5837            current: current.into_option(),
5838            meta: None,
5839        }
5840    }
5841
5842    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5843    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5844    /// do not recognize.
5845    ///
5846    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5847    #[must_use]
5848    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5849        self.meta = meta.into_option();
5850        self
5851    }
5852}
5853
5854#[cfg(feature = "unstable_llm_providers")]
5855crate::serde_util::default_on_null! {
5856    /// **UNSTABLE**
5857    ///
5858    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5859    ///
5860    /// Request parameters for `providers/list`.
5861    #[serde_as]
5862    #[skip_serializing_none]
5863    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5864    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
5865    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_LIST_METHOD_NAME)))]
5866    #[serde(rename_all = "camelCase")]
5867    #[non_exhaustive]
5868    pub struct ListProvidersRequest {
5869        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5870        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5871        /// Implementations MUST NOT assign meaning to keys they do not recognize.
5872        ///
5873        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5874        #[serde_as(deserialize_as = "DefaultOnError")]
5875        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5876        #[serde(default)]
5877        #[serde(rename = "_meta")]
5878        pub meta: Option<Meta>,
5879    }
5880}
5881
5882#[cfg(feature = "unstable_llm_providers")]
5883impl ListProvidersRequest {
5884    /// Builds [`ListProvidersRequest`] with the required request fields set. Optional fields start unset or empty.
5885    #[must_use]
5886    pub fn new() -> Self {
5887        Self::default()
5888    }
5889
5890    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5891    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5892    /// do not recognize.
5893    ///
5894    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5895    #[must_use]
5896    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5897        self.meta = meta.into_option();
5898        self
5899    }
5900}
5901
5902/// **UNSTABLE**
5903///
5904/// This capability is not part of the spec yet, and may be removed or changed at any point.
5905///
5906/// Response to `providers/list`.
5907#[cfg(feature = "unstable_llm_providers")]
5908#[serde_as]
5909#[skip_serializing_none]
5910#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5911#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5912#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_LIST_METHOD_NAME)))]
5913#[serde(rename_all = "camelCase")]
5914#[non_exhaustive]
5915pub struct ListProvidersResponse {
5916    /// Configurable providers with current routing info suitable for UI display.
5917    pub providers: Vec<ProviderInfo>,
5918    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5919    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5920    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5921    ///
5922    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5923    #[serde_as(deserialize_as = "DefaultOnError")]
5924    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5925    #[serde(default)]
5926    #[serde(rename = "_meta")]
5927    pub meta: Option<Meta>,
5928}
5929
5930#[cfg(feature = "unstable_llm_providers")]
5931impl ListProvidersResponse {
5932    /// Builds [`ListProvidersResponse`] with the required response fields set. Optional fields start unset or empty.
5933    #[must_use]
5934    pub fn new(providers: Vec<ProviderInfo>) -> Self {
5935        Self {
5936            providers,
5937            meta: None,
5938        }
5939    }
5940
5941    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5942    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5943    /// do not recognize.
5944    ///
5945    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5946    #[must_use]
5947    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5948        self.meta = meta.into_option();
5949        self
5950    }
5951}
5952
5953/// **UNSTABLE**
5954///
5955/// This capability is not part of the spec yet, and may be removed or changed at any point.
5956///
5957/// Request parameters for `providers/set`.
5958///
5959/// Replaces the full configuration for one provider ID.
5960#[cfg(feature = "unstable_llm_providers")]
5961#[serde_as]
5962#[skip_serializing_none]
5963#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5964#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
5965#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_SET_METHOD_NAME)))]
5966#[serde(rename_all = "camelCase")]
5967#[non_exhaustive]
5968pub struct SetProviderRequest {
5969    /// Provider ID to configure.
5970    pub provider_id: ProviderId,
5971    /// Protocol type for this provider.
5972    pub api_type: LlmProtocol,
5973    /// Base URL for requests sent through this provider.
5974    #[cfg_attr(feature = "schemars", schemars(url))]
5975    pub base_url: String,
5976    /// Full headers map for this provider.
5977    /// May include authorization, routing, or other integration-specific headers.
5978    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
5979    pub headers: IndexMap<String, String>,
5980    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5981    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5982    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5983    ///
5984    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5985    #[serde_as(deserialize_as = "DefaultOnError")]
5986    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5987    #[serde(default)]
5988    #[serde(rename = "_meta")]
5989    pub meta: Option<Meta>,
5990}
5991
5992#[cfg(feature = "unstable_llm_providers")]
5993impl SetProviderRequest {
5994    /// Builds [`SetProviderRequest`] with the required request fields set. Optional fields start unset or empty.
5995    #[must_use]
5996    pub fn new(
5997        provider_id: impl Into<ProviderId>,
5998        api_type: LlmProtocol,
5999        base_url: impl Into<String>,
6000    ) -> Self {
6001        Self {
6002            provider_id: provider_id.into(),
6003            api_type,
6004            base_url: base_url.into(),
6005            headers: IndexMap::new(),
6006            meta: None,
6007        }
6008    }
6009
6010    /// Full headers map for this provider.
6011    /// May include authorization, routing, or other integration-specific headers.
6012    #[must_use]
6013    pub fn headers(mut self, headers: IndexMap<String, String>) -> Self {
6014        self.headers = headers;
6015        self
6016    }
6017
6018    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6019    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6020    /// do not recognize.
6021    ///
6022    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6023    #[must_use]
6024    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6025        self.meta = meta.into_option();
6026        self
6027    }
6028}
6029
6030#[cfg(feature = "unstable_llm_providers")]
6031crate::serde_util::default_on_null! {
6032    /// **UNSTABLE**
6033    ///
6034    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6035    ///
6036    /// Response to `providers/set`.
6037    #[serde_as]
6038    #[skip_serializing_none]
6039    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6040    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
6041    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_SET_METHOD_NAME)))]
6042    #[serde(rename_all = "camelCase")]
6043    #[non_exhaustive]
6044    pub struct SetProviderResponse {
6045        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6046        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6047        /// Implementations MUST NOT assign meaning to keys they do not recognize.
6048        ///
6049        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6050        #[serde_as(deserialize_as = "DefaultOnError")]
6051        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6052        #[serde(default)]
6053        #[serde(rename = "_meta")]
6054        pub meta: Option<Meta>,
6055    }
6056}
6057
6058#[cfg(feature = "unstable_llm_providers")]
6059impl SetProviderResponse {
6060    /// Builds [`SetProviderResponse`] with the required response fields set. Optional fields start unset or empty.
6061    #[must_use]
6062    pub fn new() -> Self {
6063        Self::default()
6064    }
6065
6066    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6067    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6068    /// do not recognize.
6069    ///
6070    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6071    #[must_use]
6072    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6073        self.meta = meta.into_option();
6074        self
6075    }
6076}
6077
6078/// **UNSTABLE**
6079///
6080/// This capability is not part of the spec yet, and may be removed or changed at any point.
6081///
6082/// Request parameters for `providers/disable`.
6083#[cfg(feature = "unstable_llm_providers")]
6084#[serde_as]
6085#[skip_serializing_none]
6086#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6087#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6088#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_DISABLE_METHOD_NAME)))]
6089#[serde(rename_all = "camelCase")]
6090#[non_exhaustive]
6091pub struct DisableProviderRequest {
6092    /// Provider ID to disable.
6093    pub provider_id: ProviderId,
6094    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6095    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6096    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6097    ///
6098    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6099    #[serde_as(deserialize_as = "DefaultOnError")]
6100    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6101    #[serde(default)]
6102    #[serde(rename = "_meta")]
6103    pub meta: Option<Meta>,
6104}
6105
6106#[cfg(feature = "unstable_llm_providers")]
6107impl DisableProviderRequest {
6108    /// Builds [`DisableProviderRequest`] with the required request fields set. Optional fields start unset or empty.
6109    #[must_use]
6110    pub fn new(provider_id: impl Into<ProviderId>) -> Self {
6111        Self {
6112            provider_id: provider_id.into(),
6113            meta: None,
6114        }
6115    }
6116
6117    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6118    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6119    /// do not recognize.
6120    ///
6121    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6122    #[must_use]
6123    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6124        self.meta = meta.into_option();
6125        self
6126    }
6127}
6128
6129#[cfg(feature = "unstable_llm_providers")]
6130crate::serde_util::default_on_null! {
6131    /// **UNSTABLE**
6132    ///
6133    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6134    ///
6135    /// Response to `providers/disable`.
6136    #[serde_as]
6137    #[skip_serializing_none]
6138    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6139    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
6140    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_DISABLE_METHOD_NAME)))]
6141    #[serde(rename_all = "camelCase")]
6142    #[non_exhaustive]
6143    pub struct DisableProviderResponse {
6144        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6145        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6146        /// Implementations MUST NOT assign meaning to keys they do not recognize.
6147        ///
6148        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6149        #[serde_as(deserialize_as = "DefaultOnError")]
6150        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6151        #[serde(default)]
6152        #[serde(rename = "_meta")]
6153        pub meta: Option<Meta>,
6154    }
6155}
6156
6157#[cfg(feature = "unstable_llm_providers")]
6158impl DisableProviderResponse {
6159    /// Builds [`DisableProviderResponse`] with the required response fields set. Optional fields start unset or empty.
6160    #[must_use]
6161    pub fn new() -> Self {
6162        Self::default()
6163    }
6164
6165    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6166    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6167    /// do not recognize.
6168    ///
6169    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6170    #[must_use]
6171    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6172        self.meta = meta.into_option();
6173        self
6174    }
6175}
6176
6177// Capabilities
6178
6179/// Capabilities supported by the Agent.
6180///
6181/// Advertised during initialization to inform the Client about
6182/// available features and content types.
6183///
6184/// See protocol docs: [Agent Capabilities](https://agentclientprotocol.com/protocol/v2/initialization#agent-capabilities)
6185#[serde_as]
6186#[skip_serializing_none]
6187#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6188#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6189#[serde(rename_all = "camelCase")]
6190#[non_exhaustive]
6191pub struct AgentCapabilities {
6192    /// Session capabilities supported by the Agent.
6193    ///
6194    /// Optional. Omitted and `null` are equivalent and mean the Agent does not support the
6195    /// `session/*` methods. Supplying `{}` means the Agent supports the
6196    /// baseline session methods: `session/new`, `session/list`,
6197    /// `session/resume`, `session/close`, `session/prompt`, `session/cancel`,
6198    /// and `session/update`.
6199    #[serde_as(deserialize_as = "DefaultOnError")]
6200    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6201    #[serde(default)]
6202    pub session: Option<SessionCapabilities>,
6203    /// Authentication-related extension capabilities supported by the Agent.
6204    ///
6205    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise any
6206    /// authentication-related extensions. This field does not advertise support
6207    /// for `auth/login` or `auth/logout`. Those methods are advertised by a
6208    /// non-empty `authMethods` list in the `initialize` response.
6209    #[serde_as(deserialize_as = "DefaultOnError")]
6210    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6211    #[serde(default)]
6212    pub auth: Option<AgentAuthCapabilities>,
6213    /// **UNSTABLE**
6214    ///
6215    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6216    ///
6217    /// Provider configuration capabilities supported by the Agent.
6218    ///
6219    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6220    /// Supplying `{}` means the Agent supports provider configuration methods.
6221    #[cfg(feature = "unstable_llm_providers")]
6222    #[serde_as(deserialize_as = "DefaultOnError")]
6223    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6224    #[serde(default)]
6225    pub providers: Option<ProvidersCapabilities>,
6226    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6227    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6228    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6229    ///
6230    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6231    #[serde_as(deserialize_as = "DefaultOnError")]
6232    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6233    #[serde(default)]
6234    #[serde(rename = "_meta")]
6235    pub meta: Option<Meta>,
6236}
6237
6238impl AgentCapabilities {
6239    /// Builds an empty [`AgentCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6240    #[must_use]
6241    pub fn new() -> Self {
6242        Self::default()
6243    }
6244
6245    /// Session capabilities supported by the Agent.
6246    ///
6247    /// Omitted and `null` are equivalent and mean the Agent does not support the `session/*`
6248    /// methods. Supplying `{}` means the Agent supports the baseline
6249    /// session methods: `session/new`, `session/list`, `session/resume`,
6250    /// `session/close`, `session/prompt`, `session/cancel`, and
6251    /// `session/update`.
6252    #[must_use]
6253    pub fn session(mut self, session: impl IntoOption<SessionCapabilities>) -> Self {
6254        self.session = session.into_option();
6255        self
6256    }
6257
6258    /// Authentication-related extension capabilities supported by the Agent.
6259    ///
6260    /// This field does not advertise support for `auth/login` or `auth/logout`.
6261    #[must_use]
6262    pub fn auth(mut self, auth: impl IntoOption<AgentAuthCapabilities>) -> Self {
6263        self.auth = auth.into_option();
6264        self
6265    }
6266
6267    /// **UNSTABLE**
6268    ///
6269    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6270    ///
6271    /// Provider configuration capabilities supported by the Agent.
6272    #[cfg(feature = "unstable_llm_providers")]
6273    #[must_use]
6274    pub fn providers(mut self, providers: impl IntoOption<ProvidersCapabilities>) -> Self {
6275        self.providers = providers.into_option();
6276        self
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 assign meaning to keys they
6281    /// do not recognize.
6282    ///
6283    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/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/// Provider configuration capabilities supported by the Agent.
6296///
6297/// Supplying `{}` means the Agent supports provider configuration methods.
6298#[cfg(feature = "unstable_llm_providers")]
6299#[serde_as]
6300#[skip_serializing_none]
6301#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6302#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6303#[non_exhaustive]
6304pub struct ProvidersCapabilities {
6305    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6306    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6307    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6308    ///
6309    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6310    #[serde_as(deserialize_as = "DefaultOnError")]
6311    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6312    #[serde(default)]
6313    #[serde(rename = "_meta")]
6314    pub meta: Option<Meta>,
6315}
6316
6317#[cfg(feature = "unstable_llm_providers")]
6318impl ProvidersCapabilities {
6319    /// Builds an empty [`ProvidersCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6320    #[must_use]
6321    pub fn new() -> Self {
6322        Self::default()
6323    }
6324
6325    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6326    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6327    /// do not recognize.
6328    ///
6329    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6330    #[must_use]
6331    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6332        self.meta = meta.into_option();
6333        self
6334    }
6335}
6336
6337/// Session capabilities supported by the Agent.
6338///
6339/// Supplying `{}` means the Agent supports the baseline session methods:
6340/// `session/new`, `session/list`, `session/resume`, `session/close`,
6341/// `session/prompt`, `session/cancel`, and `session/update`.
6342///
6343/// Agents that support sessions MAY support additional session methods,
6344/// prompt content types, and MCP transports by specifying additional
6345/// capabilities.
6346///
6347/// See protocol docs: [Session Capabilities](https://agentclientprotocol.com/protocol/v2/initialization#session-capabilities)
6348#[serde_as]
6349#[skip_serializing_none]
6350#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6351#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6352#[serde(rename_all = "camelCase")]
6353#[non_exhaustive]
6354pub struct SessionCapabilities {
6355    /// Prompt capabilities supported by the Agent in `session/prompt` requests.
6356    ///
6357    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise any
6358    /// prompt extensions beyond the baseline text and resource-link content
6359    /// required by `session/prompt`.
6360    #[serde_as(deserialize_as = "DefaultOnError")]
6361    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6362    #[serde(default)]
6363    pub prompt: Option<PromptCapabilities>,
6364    /// MCP capabilities supported by the Agent for session lifecycle requests.
6365    ///
6366    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise MCP
6367    /// server transport support for sessions.
6368    #[serde_as(deserialize_as = "DefaultOnError")]
6369    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6370    #[serde(default)]
6371    pub mcp: Option<McpCapabilities>,
6372    /// Whether the Agent supports `session/delete`.
6373    ///
6374    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6375    /// Supplying `{}` means the Agent supports deleting sessions from `session/list`.
6376    #[serde_as(deserialize_as = "DefaultOnError")]
6377    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6378    #[serde(default)]
6379    pub delete: Option<SessionDeleteCapabilities>,
6380    /// Whether the Agent supports `additionalDirectories` on supported session lifecycle requests.
6381    ///
6382    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6383    /// Supplying `{}` means the Agent supports `additionalDirectories` on
6384    /// supported session lifecycle requests.
6385    ///
6386    /// Agents MAY return `SessionInfo.additionalDirectories` to report the
6387    /// complete ordered additional-root list associated with a listed session.
6388    #[serde_as(deserialize_as = "DefaultOnError")]
6389    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6390    #[serde(default)]
6391    pub additional_directories: Option<SessionAdditionalDirectoriesCapabilities>,
6392    /// Whether the Agent supports `systemPrompt` on session lifecycle requests.
6393    ///
6394    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6395    /// Supplying `{}` means the Agent supports `systemPrompt` in `append` mode.
6396    #[serde_as(deserialize_as = "DefaultOnError")]
6397    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6398    #[serde(default)]
6399    pub system_prompt: Option<SessionSystemPromptCapabilities>,
6400    /// **UNSTABLE**
6401    ///
6402    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6403    ///
6404    /// Whether the Agent supports `session/fork`.
6405    ///
6406    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6407    /// Supplying `{}` means the Agent supports forking sessions.
6408    #[cfg(feature = "unstable_session_fork")]
6409    #[serde_as(deserialize_as = "DefaultOnError")]
6410    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6411    #[serde(default)]
6412    pub fork: Option<SessionForkCapabilities>,
6413    /// **UNSTABLE**
6414    ///
6415    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6416    ///
6417    /// Whether the Agent supports `session/archive` and `session/unarchive`.
6418    ///
6419    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6420    /// Supplying `{}` means the Agent supports both methods, the `archived` filter on
6421    /// `session/list`, and `SessionInfo.archived`.
6422    #[cfg(feature = "unstable_session_archive")]
6423    #[serde_as(deserialize_as = "DefaultOnError")]
6424    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6425    #[serde(default)]
6426    pub archive: Option<SessionArchiveCapabilities>,
6427    /// **UNSTABLE**
6428    ///
6429    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6430    ///
6431    /// Whether the Agent supports `session/status`.
6432    ///
6433    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6434    /// Supplying `{}` means the Agent supports checking session status.
6435    #[cfg(feature = "unstable_session_status")]
6436    #[serde_as(deserialize_as = "DefaultOnError")]
6437    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6438    #[serde(default)]
6439    pub status: Option<SessionStatusCapabilities>,
6440    /// **UNSTABLE**
6441    ///
6442    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6443    ///
6444    /// Whether the Agent supports `session/options`.
6445    ///
6446    /// Optional. Omitted or `null` both mean the Agent does not advertise support.
6447    /// Supplying `{}` means the Agent supports `session/options` and accepts initial
6448    /// config option values on session setup requests.
6449    #[cfg(feature = "unstable_session_options")]
6450    #[serde_as(deserialize_as = "DefaultOnError")]
6451    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6452    #[serde(default)]
6453    pub options: Option<SessionOptionsCapabilities>,
6454    /// **UNSTABLE**
6455    ///
6456    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6457    ///
6458    /// Whether the Agent supports `session/set_title`.
6459    ///
6460    /// Agents report titles through `session/list` and `session_info_update` without this
6461    /// capability. It only advertises that Clients can set titles.
6462    ///
6463    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6464    /// Supplying `{}` means the Agent supports setting session titles.
6465    #[cfg(feature = "unstable_session_set_title")]
6466    #[serde_as(deserialize_as = "DefaultOnError")]
6467    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6468    #[serde(default)]
6469    pub title: Option<SessionTitleCapabilities>,
6470    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6471    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6472    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6473    ///
6474    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6475    #[serde_as(deserialize_as = "DefaultOnError")]
6476    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6477    #[serde(default)]
6478    #[serde(rename = "_meta")]
6479    pub meta: Option<Meta>,
6480}
6481
6482impl SessionCapabilities {
6483    /// Builds an empty [`SessionCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6484    #[must_use]
6485    pub fn new() -> Self {
6486        Self::default()
6487    }
6488
6489    /// Prompt capabilities supported by the Agent in `session/prompt` requests.
6490    ///
6491    /// Omitted and `null` are equivalent and mean the Agent does not advertise any prompt
6492    /// extensions beyond the baseline text and resource-link content required by
6493    /// `session/prompt`.
6494    #[must_use]
6495    pub fn prompt(mut self, prompt: impl IntoOption<PromptCapabilities>) -> Self {
6496        self.prompt = prompt.into_option();
6497        self
6498    }
6499
6500    /// MCP capabilities supported by the Agent for session lifecycle requests.
6501    ///
6502    /// Omitted and `null` are equivalent and mean the Agent does not advertise MCP server
6503    /// transport support for sessions.
6504    #[must_use]
6505    pub fn mcp(mut self, mcp: impl IntoOption<McpCapabilities>) -> Self {
6506        self.mcp = mcp.into_option();
6507        self
6508    }
6509
6510    /// Whether the Agent supports `session/delete`.
6511    ///
6512    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
6513    /// Supplying `{}` means the Agent supports deleting sessions from `session/list`.
6514    #[must_use]
6515    pub fn delete(mut self, delete: impl IntoOption<SessionDeleteCapabilities>) -> Self {
6516        self.delete = delete.into_option();
6517        self
6518    }
6519
6520    /// Whether the Agent supports `additionalDirectories` on supported session lifecycle requests.
6521    ///
6522    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
6523    /// Supplying `{}` means the Agent supports `additionalDirectories` on
6524    /// supported session lifecycle requests.
6525    ///
6526    /// Agents MAY return `SessionInfo.additionalDirectories` to report the
6527    /// complete ordered additional-root list associated with a listed session.
6528    #[must_use]
6529    pub fn additional_directories(
6530        mut self,
6531        additional_directories: impl IntoOption<SessionAdditionalDirectoriesCapabilities>,
6532    ) -> Self {
6533        self.additional_directories = additional_directories.into_option();
6534        self
6535    }
6536
6537    /// Whether the Agent supports `systemPrompt` on session lifecycle requests.
6538    ///
6539    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
6540    /// Supplying `{}` means the Agent supports `systemPrompt` in `append` mode.
6541    #[must_use]
6542    pub fn system_prompt(
6543        mut self,
6544        system_prompt: impl IntoOption<SessionSystemPromptCapabilities>,
6545    ) -> Self {
6546        self.system_prompt = system_prompt.into_option();
6547        self
6548    }
6549
6550    #[cfg(feature = "unstable_session_fork")]
6551    /// Whether the Agent supports `session/fork`.
6552    ///
6553    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
6554    /// Supplying `{}` means the Agent supports forking sessions.
6555    #[must_use]
6556    pub fn fork(mut self, fork: impl IntoOption<SessionForkCapabilities>) -> Self {
6557        self.fork = fork.into_option();
6558        self
6559    }
6560
6561    /// **UNSTABLE**
6562    ///
6563    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6564    ///
6565    /// Whether the Agent supports `session/archive` and `session/unarchive`.
6566    ///
6567    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
6568    /// Supplying `{}` means the Agent supports both methods, the `archived` filter on
6569    /// `session/list`, and `SessionInfo.archived`.
6570    #[cfg(feature = "unstable_session_archive")]
6571    #[must_use]
6572    pub fn archive(mut self, archive: impl IntoOption<SessionArchiveCapabilities>) -> Self {
6573        self.archive = archive.into_option();
6574        self
6575    }
6576
6577    /// **UNSTABLE**
6578    ///
6579    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6580    ///
6581    /// Whether the Agent supports `session/status`.
6582    ///
6583    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
6584    /// Supplying `{}` means the Agent supports checking session status.
6585    #[cfg(feature = "unstable_session_status")]
6586    #[must_use]
6587    pub fn status(mut self, status: impl IntoOption<SessionStatusCapabilities>) -> Self {
6588        self.status = status.into_option();
6589        self
6590    }
6591
6592    /// **UNSTABLE**
6593    ///
6594    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6595    ///
6596    /// Whether the Agent supports `session/options`.
6597    ///
6598    /// Omitted or `null` both mean the Agent does not advertise support.
6599    /// Supplying `{}` means the Agent supports `session/options` and accepts initial
6600    /// config option values on session setup requests.
6601    #[cfg(feature = "unstable_session_options")]
6602    #[must_use]
6603    pub fn options(mut self, options: impl IntoOption<SessionOptionsCapabilities>) -> Self {
6604        self.options = options.into_option();
6605        self
6606    }
6607
6608    /// **UNSTABLE**
6609    ///
6610    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6611    ///
6612    /// Whether the Agent supports `session/set_title`.
6613    ///
6614    /// Agents report titles through `session/list` and `session_info_update` without this
6615    /// capability. It only advertises that Clients can set titles.
6616    ///
6617    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
6618    /// Supplying `{}` means the Agent supports setting session titles.
6619    #[cfg(feature = "unstable_session_set_title")]
6620    #[must_use]
6621    pub fn title(mut self, title: impl IntoOption<SessionTitleCapabilities>) -> Self {
6622        self.title = title.into_option();
6623        self
6624    }
6625
6626    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6627    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6628    /// do not recognize.
6629    ///
6630    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6631    #[must_use]
6632    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6633        self.meta = meta.into_option();
6634        self
6635    }
6636}
6637
6638/// Capabilities for the `session/delete` method.
6639///
6640/// Supplying `{}` means the Agent supports deleting sessions from `session/list`.
6641#[serde_as]
6642#[skip_serializing_none]
6643#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6644#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6645#[non_exhaustive]
6646pub struct SessionDeleteCapabilities {
6647    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6648    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6649    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6650    ///
6651    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6652    #[serde_as(deserialize_as = "DefaultOnError")]
6653    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6654    #[serde(default)]
6655    #[serde(rename = "_meta")]
6656    pub meta: Option<Meta>,
6657}
6658
6659impl SessionDeleteCapabilities {
6660    /// Builds an empty [`SessionDeleteCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6661    #[must_use]
6662    pub fn new() -> Self {
6663        Self::default()
6664    }
6665
6666    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6667    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6668    /// do not recognize.
6669    ///
6670    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6671    #[must_use]
6672    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6673        self.meta = meta.into_option();
6674        self
6675    }
6676}
6677
6678/// Capabilities for additional session directories support.
6679///
6680/// Supplying `{}` means the Agent supports the `additionalDirectories` field on
6681/// supported session lifecycle requests. Agents MAY return
6682/// `SessionInfo.additionalDirectories` in `session/list` to report the
6683/// complete ordered additional-root list associated with a listed session.
6684#[serde_as]
6685#[skip_serializing_none]
6686#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6687#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6688#[non_exhaustive]
6689pub struct SessionAdditionalDirectoriesCapabilities {
6690    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6691    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6692    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6693    ///
6694    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6695    #[serde_as(deserialize_as = "DefaultOnError")]
6696    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6697    #[serde(default)]
6698    #[serde(rename = "_meta")]
6699    pub meta: Option<Meta>,
6700}
6701
6702impl SessionAdditionalDirectoriesCapabilities {
6703    /// Builds an empty [`SessionAdditionalDirectoriesCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6704    #[must_use]
6705    pub fn new() -> Self {
6706        Self::default()
6707    }
6708
6709    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6710    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6711    /// do not recognize.
6712    ///
6713    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6714    #[must_use]
6715    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6716        self.meta = meta.into_option();
6717        self
6718    }
6719}
6720
6721/// Capabilities for Client-provided system prompts.
6722///
6723/// Supplying `{}` means the Agent supports `systemPrompt` on session lifecycle
6724/// requests in `append` mode.
6725#[serde_as]
6726#[skip_serializing_none]
6727#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6728#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6729#[serde(rename_all = "camelCase")]
6730#[non_exhaustive]
6731pub struct SessionSystemPromptCapabilities {
6732    /// Delivery modes the Agent supports in addition to `append`.
6733    ///
6734    /// Optional. Omitted and `null` are equivalent and mean the Agent supports only `append`.
6735    #[serde_as(deserialize_as = "DefaultOnError")]
6736    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6737    #[serde(default)]
6738    pub mode: Option<SessionSystemPromptModeCapabilities>,
6739    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6740    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6741    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6742    ///
6743    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6744    #[serde_as(deserialize_as = "DefaultOnError")]
6745    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6746    #[serde(default)]
6747    #[serde(rename = "_meta")]
6748    pub meta: Option<Meta>,
6749}
6750
6751impl SessionSystemPromptCapabilities {
6752    /// Builds an empty [`SessionSystemPromptCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6753    #[must_use]
6754    pub fn new() -> Self {
6755        Self::default()
6756    }
6757
6758    /// Delivery modes the Agent supports in addition to `append`.
6759    ///
6760    /// Omitted and `null` are equivalent and mean the Agent supports only `append`.
6761    #[must_use]
6762    pub fn mode(mut self, mode: impl IntoOption<SessionSystemPromptModeCapabilities>) -> Self {
6763        self.mode = mode.into_option();
6764        self
6765    }
6766
6767    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6768    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6769    /// do not recognize.
6770    ///
6771    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6772    #[must_use]
6773    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6774        self.meta = meta.into_option();
6775        self
6776    }
6777}
6778
6779/// System prompt delivery modes the Agent supports in addition to `append`.
6780///
6781/// `append` has no entry because every Agent advertising `session.systemPrompt`
6782/// supports it.
6783#[serde_as]
6784#[skip_serializing_none]
6785#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6786#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6787#[serde(rename_all = "camelCase")]
6788#[non_exhaustive]
6789pub struct SessionSystemPromptModeCapabilities {
6790    /// Whether the Agent supports `override` mode.
6791    ///
6792    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6793    /// Supplying `{}` means the Agent supports replacing its built-in default
6794    /// instructions with the Client-provided system prompt.
6795    #[serde_as(deserialize_as = "DefaultOnError")]
6796    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6797    #[serde(default, rename = "override")]
6798    pub override_: Option<SessionSystemPromptOverrideCapabilities>,
6799    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6800    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6801    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6802    ///
6803    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6804    #[serde_as(deserialize_as = "DefaultOnError")]
6805    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6806    #[serde(default)]
6807    #[serde(rename = "_meta")]
6808    pub meta: Option<Meta>,
6809}
6810
6811impl SessionSystemPromptModeCapabilities {
6812    /// Builds an empty [`SessionSystemPromptModeCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6813    #[must_use]
6814    pub fn new() -> Self {
6815        Self::default()
6816    }
6817
6818    /// Whether the Agent supports `override` mode.
6819    ///
6820    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
6821    /// Supplying `{}` means the Agent supports replacing its built-in default
6822    /// instructions with the Client-provided system prompt.
6823    #[must_use]
6824    pub fn override_(
6825        mut self,
6826        override_: impl IntoOption<SessionSystemPromptOverrideCapabilities>,
6827    ) -> Self {
6828        self.override_ = override_.into_option();
6829        self
6830    }
6831
6832    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6833    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6834    /// do not recognize.
6835    ///
6836    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6837    #[must_use]
6838    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6839        self.meta = meta.into_option();
6840        self
6841    }
6842}
6843
6844/// Capabilities for the `override` system prompt mode.
6845///
6846/// Supplying `{}` means the Agent supports replacing its built-in default
6847/// instructions with the Client-provided system prompt.
6848#[serde_as]
6849#[skip_serializing_none]
6850#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6851#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6852#[non_exhaustive]
6853pub struct SessionSystemPromptOverrideCapabilities {
6854    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6855    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6856    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6857    ///
6858    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6859    #[serde_as(deserialize_as = "DefaultOnError")]
6860    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6861    #[serde(default)]
6862    #[serde(rename = "_meta")]
6863    pub meta: Option<Meta>,
6864}
6865
6866impl SessionSystemPromptOverrideCapabilities {
6867    /// Builds an empty [`SessionSystemPromptOverrideCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6868    #[must_use]
6869    pub fn new() -> Self {
6870        Self::default()
6871    }
6872
6873    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6874    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6875    /// do not recognize.
6876    ///
6877    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6878    #[must_use]
6879    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6880        self.meta = meta.into_option();
6881        self
6882    }
6883}
6884
6885/// **UNSTABLE**
6886///
6887/// This capability is not part of the spec yet, and may be removed or changed at any point.
6888///
6889/// Capabilities for the `session/fork` method.
6890///
6891/// Supplying `{}` means the Agent supports forking sessions.
6892#[cfg(feature = "unstable_session_fork")]
6893#[serde_as]
6894#[skip_serializing_none]
6895#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6896#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6897#[non_exhaustive]
6898pub struct SessionForkCapabilities {
6899    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6900    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6901    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6902    ///
6903    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6904    #[serde_as(deserialize_as = "DefaultOnError")]
6905    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6906    #[serde(default)]
6907    #[serde(rename = "_meta")]
6908    pub meta: Option<Meta>,
6909}
6910
6911#[cfg(feature = "unstable_session_fork")]
6912impl SessionForkCapabilities {
6913    /// Builds an empty [`SessionForkCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6914    #[must_use]
6915    pub fn new() -> Self {
6916        Self::default()
6917    }
6918
6919    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6920    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6921    /// do not recognize.
6922    ///
6923    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6924    #[must_use]
6925    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6926        self.meta = meta.into_option();
6927        self
6928    }
6929}
6930
6931/// **UNSTABLE**
6932///
6933/// This capability is not part of the spec yet, and may be removed or changed at any point.
6934///
6935/// Capabilities for `session/archive` and `session/unarchive`.
6936///
6937/// Supplying `{}` means the Agent supports both methods, the `archived` filter on
6938/// `session/list`, and `SessionInfo.archived`.
6939#[cfg(feature = "unstable_session_archive")]
6940#[serde_as]
6941#[skip_serializing_none]
6942#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6943#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6944#[non_exhaustive]
6945pub struct SessionArchiveCapabilities {
6946    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6947    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6948    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6949    ///
6950    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6951    #[serde_as(deserialize_as = "DefaultOnError")]
6952    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6953    #[serde(default)]
6954    #[serde(rename = "_meta")]
6955    pub meta: Option<Meta>,
6956}
6957
6958#[cfg(feature = "unstable_session_archive")]
6959impl SessionArchiveCapabilities {
6960    /// Builds an empty [`SessionArchiveCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6961    #[must_use]
6962    pub fn new() -> Self {
6963        Self::default()
6964    }
6965
6966    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6967    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6968    /// do not recognize.
6969    ///
6970    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6971    #[must_use]
6972    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6973        self.meta = meta.into_option();
6974        self
6975    }
6976}
6977
6978/// **UNSTABLE**
6979///
6980/// This capability is not part of the spec yet, and may be removed or changed at any point.
6981///
6982/// Capabilities for the `session/status` method.
6983///
6984/// Supplying `{}` means the Agent supports checking session status.
6985#[cfg(feature = "unstable_session_status")]
6986#[serde_as]
6987#[skip_serializing_none]
6988#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6989#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6990#[non_exhaustive]
6991pub struct SessionStatusCapabilities {
6992    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6993    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6994    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6995    ///
6996    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6997    #[serde_as(deserialize_as = "DefaultOnError")]
6998    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6999    #[serde(default)]
7000    #[serde(rename = "_meta")]
7001    pub meta: Option<Meta>,
7002}
7003
7004#[cfg(feature = "unstable_session_status")]
7005impl SessionStatusCapabilities {
7006    /// Builds an empty [`SessionStatusCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7007    #[must_use]
7008    pub fn new() -> Self {
7009        Self::default()
7010    }
7011
7012    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7013    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7014    /// do not recognize.
7015    ///
7016    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7017    #[must_use]
7018    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7019        self.meta = meta.into_option();
7020        self
7021    }
7022}
7023
7024/// **UNSTABLE**
7025///
7026/// This capability is not part of the spec yet, and may be removed or changed at any point.
7027///
7028/// Capabilities for the `session/options` method.
7029///
7030/// Supplying `{}` means the Agent supports `session/options` and accepts initial config
7031/// option values on session setup requests.
7032#[cfg(feature = "unstable_session_options")]
7033#[serde_as]
7034#[skip_serializing_none]
7035#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7036#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7037#[non_exhaustive]
7038pub struct SessionOptionsCapabilities {
7039    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7040    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7041    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7042    ///
7043    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7044    #[serde_as(deserialize_as = "DefaultOnError")]
7045    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7046    #[serde(default)]
7047    #[serde(rename = "_meta")]
7048    pub meta: Option<Meta>,
7049}
7050
7051#[cfg(feature = "unstable_session_options")]
7052impl SessionOptionsCapabilities {
7053    /// Builds an empty [`SessionOptionsCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7054    #[must_use]
7055    pub fn new() -> Self {
7056        Self::default()
7057    }
7058
7059    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7060    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7061    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7062    ///
7063    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7064    #[must_use]
7065    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7066        self.meta = meta.into_option();
7067        self
7068    }
7069}
7070
7071/// **UNSTABLE**
7072///
7073/// This capability is not part of the spec yet, and may be removed or changed at any point.
7074///
7075/// Capabilities for Client-set session titles.
7076///
7077/// Supplying `{}` means the Agent supports `session/set_title`. Agents report titles
7078/// through `session/list` and `session_info_update` without this capability.
7079#[cfg(feature = "unstable_session_set_title")]
7080#[serde_as]
7081#[skip_serializing_none]
7082#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7083#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7084#[non_exhaustive]
7085pub struct SessionTitleCapabilities {
7086    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7087    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7088    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7089    ///
7090    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7091    #[serde_as(deserialize_as = "DefaultOnError")]
7092    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7093    #[serde(default)]
7094    #[serde(rename = "_meta")]
7095    pub meta: Option<Meta>,
7096}
7097
7098#[cfg(feature = "unstable_session_set_title")]
7099impl SessionTitleCapabilities {
7100    /// Builds an empty [`SessionTitleCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7101    #[must_use]
7102    pub fn new() -> Self {
7103        Self::default()
7104    }
7105
7106    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7107    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7108    /// do not recognize.
7109    ///
7110    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7111    #[must_use]
7112    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7113        self.meta = meta.into_option();
7114        self
7115    }
7116}
7117
7118/// Prompt capabilities supported by the Agent in `session/prompt` requests.
7119///
7120/// Baseline Agent functionality requires support for `text`
7121/// and `resource_link` content blocks in prompt requests.
7122///
7123/// Other content types need one of these capabilities.
7124/// Capabilities for different types of content in prompt requests.
7125///
7126/// Indicates which content types beyond the baseline (text and resource links)
7127/// the Agent can process.
7128///
7129/// See protocol docs: [Session Prompt Capabilities](https://agentclientprotocol.com/protocol/v2/initialization#session-prompt-capabilities)
7130#[serde_as]
7131#[skip_serializing_none]
7132#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7133#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7134#[serde(rename_all = "camelCase")]
7135#[non_exhaustive]
7136pub struct PromptCapabilities {
7137    /// Agent supports `image` content blocks.
7138    ///
7139    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
7140    /// Supplying `{}` means the Agent supports image content in prompts.
7141    #[serde_as(deserialize_as = "DefaultOnError")]
7142    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7143    #[serde(default)]
7144    pub image: Option<PromptImageCapabilities>,
7145    /// Agent supports `audio` content blocks.
7146    ///
7147    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
7148    /// Supplying `{}` means the Agent supports audio content in prompts.
7149    #[serde_as(deserialize_as = "DefaultOnError")]
7150    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7151    #[serde(default)]
7152    pub audio: Option<PromptAudioCapabilities>,
7153    /// Agent supports embedded context in `session/prompt` requests.
7154    ///
7155    /// When enabled, the Client is allowed to include `resource` content blocks
7156    /// in prompt requests for pieces of context that are referenced in the message.
7157    ///
7158    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
7159    /// Supplying `{}` means the Agent supports embedded context in prompts.
7160    #[serde_as(deserialize_as = "DefaultOnError")]
7161    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7162    #[serde(default)]
7163    pub embedded_context: Option<PromptEmbeddedContextCapabilities>,
7164    /// **UNSTABLE**
7165    ///
7166    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7167    ///
7168    /// Agent supports `skill` content blocks.
7169    ///
7170    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
7171    /// Supplying `{}` means a prompt may contain one `skill` content block, as its first block.
7172    /// An Agent that sends `skill` entries in `availableCommands` MUST advertise this capability.
7173    #[cfg(feature = "unstable_agent_skills")]
7174    #[serde_as(deserialize_as = "DefaultOnError")]
7175    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7176    #[serde(default)]
7177    pub skill: Option<PromptSkillCapabilities>,
7178    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7179    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7180    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7181    ///
7182    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7183    #[serde_as(deserialize_as = "DefaultOnError")]
7184    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7185    #[serde(default)]
7186    #[serde(rename = "_meta")]
7187    pub meta: Option<Meta>,
7188}
7189
7190impl PromptCapabilities {
7191    /// Builds an empty [`PromptCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7192    #[must_use]
7193    pub fn new() -> Self {
7194        Self::default()
7195    }
7196
7197    /// Agent supports `image` content blocks.
7198    ///
7199    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
7200    /// Supplying `{}` means the Agent supports image content in prompts.
7201    #[must_use]
7202    pub fn image(mut self, image: impl IntoOption<PromptImageCapabilities>) -> Self {
7203        self.image = image.into_option();
7204        self
7205    }
7206
7207    /// Agent supports `audio` content blocks.
7208    ///
7209    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
7210    /// Supplying `{}` means the Agent supports audio content in prompts.
7211    #[must_use]
7212    pub fn audio(mut self, audio: impl IntoOption<PromptAudioCapabilities>) -> Self {
7213        self.audio = audio.into_option();
7214        self
7215    }
7216
7217    /// Agent supports embedded context in `session/prompt` requests.
7218    ///
7219    /// When enabled, the Client is allowed to include `resource` content blocks
7220    /// in prompt requests for pieces of context that are referenced in the message.
7221    ///
7222    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
7223    /// Supplying `{}` means the Agent supports embedded context in prompts.
7224    #[must_use]
7225    pub fn embedded_context(
7226        mut self,
7227        embedded_context: impl IntoOption<PromptEmbeddedContextCapabilities>,
7228    ) -> Self {
7229        self.embedded_context = embedded_context.into_option();
7230        self
7231    }
7232
7233    /// **UNSTABLE**
7234    ///
7235    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7236    ///
7237    /// Agent supports `skill` content blocks.
7238    ///
7239    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
7240    /// Supplying `{}` means a prompt may contain one `skill` content block, as its first block.
7241    #[cfg(feature = "unstable_agent_skills")]
7242    #[must_use]
7243    pub fn skill(mut self, skill: impl IntoOption<PromptSkillCapabilities>) -> Self {
7244        self.skill = skill.into_option();
7245        self
7246    }
7247
7248    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7249    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7250    /// do not recognize.
7251    ///
7252    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7253    #[must_use]
7254    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7255        self.meta = meta.into_option();
7256        self
7257    }
7258}
7259
7260/// Capabilities for image content in prompt requests.
7261///
7262/// Supplying `{}` means the Agent supports image content in prompts.
7263#[serde_as]
7264#[skip_serializing_none]
7265#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7266#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7267#[non_exhaustive]
7268pub struct PromptImageCapabilities {
7269    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7270    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7271    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7272    ///
7273    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7274    #[serde_as(deserialize_as = "DefaultOnError")]
7275    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7276    #[serde(default)]
7277    #[serde(rename = "_meta")]
7278    pub meta: Option<Meta>,
7279}
7280
7281impl PromptImageCapabilities {
7282    /// Builds an empty [`PromptImageCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7283    #[must_use]
7284    pub fn new() -> Self {
7285        Self::default()
7286    }
7287
7288    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7289    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7290    /// do not recognize.
7291    ///
7292    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7293    #[must_use]
7294    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7295        self.meta = meta.into_option();
7296        self
7297    }
7298}
7299
7300/// Capabilities for audio content in prompt requests.
7301///
7302/// Supplying `{}` means the Agent supports audio content in prompts.
7303#[serde_as]
7304#[skip_serializing_none]
7305#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7306#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7307#[non_exhaustive]
7308pub struct PromptAudioCapabilities {
7309    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7310    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7311    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7312    ///
7313    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7314    #[serde_as(deserialize_as = "DefaultOnError")]
7315    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7316    #[serde(default)]
7317    #[serde(rename = "_meta")]
7318    pub meta: Option<Meta>,
7319}
7320
7321impl PromptAudioCapabilities {
7322    /// Builds an empty [`PromptAudioCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7323    #[must_use]
7324    pub fn new() -> Self {
7325        Self::default()
7326    }
7327
7328    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7329    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7330    /// do not recognize.
7331    ///
7332    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7333    #[must_use]
7334    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7335        self.meta = meta.into_option();
7336        self
7337    }
7338}
7339
7340/// Capabilities for embedded context in prompt requests.
7341///
7342/// Supplying `{}` means the Agent supports embedded context in prompts.
7343#[serde_as]
7344#[skip_serializing_none]
7345#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7346#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7347#[non_exhaustive]
7348pub struct PromptEmbeddedContextCapabilities {
7349    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7350    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7351    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7352    ///
7353    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7354    #[serde_as(deserialize_as = "DefaultOnError")]
7355    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7356    #[serde(default)]
7357    #[serde(rename = "_meta")]
7358    pub meta: Option<Meta>,
7359}
7360
7361impl PromptEmbeddedContextCapabilities {
7362    /// Builds an empty [`PromptEmbeddedContextCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7363    #[must_use]
7364    pub fn new() -> Self {
7365        Self::default()
7366    }
7367
7368    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7369    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7370    /// do not recognize.
7371    ///
7372    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7373    #[must_use]
7374    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7375        self.meta = meta.into_option();
7376        self
7377    }
7378}
7379
7380/// **UNSTABLE**
7381///
7382/// This capability is not part of the spec yet, and may be removed or changed at any point.
7383///
7384/// Capabilities for `skill` content blocks in prompt requests.
7385///
7386/// Supplying `{}` means a prompt may contain one `skill` content block, as
7387/// its first block. The Agent opts in to more with the `inline` field.
7388#[cfg(feature = "unstable_agent_skills")]
7389#[serde_as]
7390#[skip_serializing_none]
7391#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7392#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7393#[serde(rename_all = "camelCase")]
7394#[non_exhaustive]
7395pub struct PromptSkillCapabilities {
7396    /// Agent supports `skill` content blocks at any position in a prompt.
7397    ///
7398    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
7399    /// Supplying `{}` means a prompt may contain any number of `skill` content blocks, at any
7400    /// position.
7401    #[serde_as(deserialize_as = "DefaultOnError")]
7402    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7403    #[serde(default)]
7404    pub inline: Option<PromptSkillInlineCapabilities>,
7405    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7406    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7407    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7408    ///
7409    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7410    #[serde_as(deserialize_as = "DefaultOnError")]
7411    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7412    #[serde(default)]
7413    #[serde(rename = "_meta")]
7414    pub meta: Option<Meta>,
7415}
7416
7417#[cfg(feature = "unstable_agent_skills")]
7418impl PromptSkillCapabilities {
7419    /// Builds an empty [`PromptSkillCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7420    #[must_use]
7421    pub fn new() -> Self {
7422        Self::default()
7423    }
7424
7425    /// Agent supports `skill` content blocks at any position in a prompt.
7426    ///
7427    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
7428    /// Supplying `{}` means a prompt may contain any number of `skill` content blocks, at any
7429    /// position.
7430    #[must_use]
7431    pub fn inline(mut self, inline: impl IntoOption<PromptSkillInlineCapabilities>) -> Self {
7432        self.inline = inline.into_option();
7433        self
7434    }
7435
7436    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7437    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7438    /// do not recognize.
7439    ///
7440    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7441    #[must_use]
7442    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7443        self.meta = meta.into_option();
7444        self
7445    }
7446}
7447
7448/// **UNSTABLE**
7449///
7450/// This capability is not part of the spec yet, and may be removed or changed at any point.
7451///
7452/// Capabilities for `skill` content blocks at any position in a prompt.
7453///
7454/// Supplying `{}` means a prompt may contain any number of `skill` content
7455/// blocks, at any position.
7456#[cfg(feature = "unstable_agent_skills")]
7457#[serde_as]
7458#[skip_serializing_none]
7459#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7460#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7461#[non_exhaustive]
7462pub struct PromptSkillInlineCapabilities {
7463    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7464    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7465    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7466    ///
7467    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7468    #[serde_as(deserialize_as = "DefaultOnError")]
7469    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7470    #[serde(default)]
7471    #[serde(rename = "_meta")]
7472    pub meta: Option<Meta>,
7473}
7474
7475#[cfg(feature = "unstable_agent_skills")]
7476impl PromptSkillInlineCapabilities {
7477    /// Builds an empty [`PromptSkillInlineCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7478    #[must_use]
7479    pub fn new() -> Self {
7480        Self::default()
7481    }
7482
7483    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7484    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7485    /// do not recognize.
7486    ///
7487    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7488    #[must_use]
7489    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7490        self.meta = meta.into_option();
7491        self
7492    }
7493}
7494
7495/// MCP capabilities supported by the Agent for session lifecycle requests.
7496#[serde_as]
7497#[skip_serializing_none]
7498#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7499#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7500#[serde(rename_all = "camelCase")]
7501#[non_exhaustive]
7502pub struct McpCapabilities {
7503    /// Agent supports `stdio` MCP servers.
7504    ///
7505    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
7506    /// Supplying `{}` means the Agent supports stdio MCP server transports.
7507    #[serde_as(deserialize_as = "DefaultOnError")]
7508    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7509    #[serde(default)]
7510    pub stdio: Option<McpStdioCapabilities>,
7511    /// Agent supports `http` MCP servers.
7512    ///
7513    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
7514    /// Supplying `{}` means the Agent supports HTTP MCP server transports.
7515    #[serde_as(deserialize_as = "DefaultOnError")]
7516    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7517    #[serde(default)]
7518    pub http: Option<McpHttpCapabilities>,
7519    /// **UNSTABLE**
7520    ///
7521    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7522    ///
7523    /// Agent supports `acp` MCP servers.
7524    ///
7525    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
7526    /// Supplying `{}` means the Agent supports ACP MCP server transports.
7527    #[cfg(feature = "unstable_mcp_over_acp")]
7528    #[serde_as(deserialize_as = "DefaultOnError")]
7529    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7530    #[serde(default)]
7531    pub acp: Option<McpAcpCapabilities>,
7532    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7533    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7534    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7535    ///
7536    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7537    #[serde_as(deserialize_as = "DefaultOnError")]
7538    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7539    #[serde(default)]
7540    #[serde(rename = "_meta")]
7541    pub meta: Option<Meta>,
7542}
7543
7544impl McpCapabilities {
7545    /// Builds an empty [`McpCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7546    #[must_use]
7547    pub fn new() -> Self {
7548        Self::default()
7549    }
7550
7551    /// Agent supports `stdio` MCP servers.
7552    ///
7553    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
7554    /// Supplying `{}` means the Agent supports stdio MCP server transports.
7555    #[must_use]
7556    pub fn stdio(mut self, stdio: impl IntoOption<McpStdioCapabilities>) -> Self {
7557        self.stdio = stdio.into_option();
7558        self
7559    }
7560
7561    /// Agent supports `http` MCP servers.
7562    ///
7563    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
7564    /// Supplying `{}` means the Agent supports HTTP MCP server transports.
7565    #[must_use]
7566    pub fn http(mut self, http: impl IntoOption<McpHttpCapabilities>) -> Self {
7567        self.http = http.into_option();
7568        self
7569    }
7570
7571    /// **UNSTABLE**
7572    ///
7573    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7574    ///
7575    /// Agent supports `acp` MCP servers.
7576    #[cfg(feature = "unstable_mcp_over_acp")]
7577    ///
7578    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
7579    /// Supplying `{}` means the Agent supports ACP MCP server transports.
7580    #[must_use]
7581    pub fn acp(mut self, acp: impl IntoOption<McpAcpCapabilities>) -> Self {
7582        self.acp = acp.into_option();
7583        self
7584    }
7585
7586    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7587    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7588    /// do not recognize.
7589    ///
7590    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7591    #[must_use]
7592    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7593        self.meta = meta.into_option();
7594        self
7595    }
7596}
7597
7598/// Capabilities for stdio MCP server transports.
7599///
7600/// Supplying `{}` means the Agent supports stdio MCP server transports.
7601#[serde_as]
7602#[skip_serializing_none]
7603#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7604#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7605#[non_exhaustive]
7606pub struct McpStdioCapabilities {
7607    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7608    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7609    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7610    ///
7611    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7612    #[serde_as(deserialize_as = "DefaultOnError")]
7613    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7614    #[serde(default)]
7615    #[serde(rename = "_meta")]
7616    pub meta: Option<Meta>,
7617}
7618
7619impl McpStdioCapabilities {
7620    /// Builds an empty [`McpStdioCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7621    #[must_use]
7622    pub fn new() -> Self {
7623        Self::default()
7624    }
7625
7626    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7627    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7628    /// do not recognize.
7629    ///
7630    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7631    #[must_use]
7632    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7633        self.meta = meta.into_option();
7634        self
7635    }
7636}
7637
7638/// Capabilities for HTTP MCP server transports.
7639///
7640/// Supplying `{}` means the Agent supports HTTP MCP server transports.
7641#[serde_as]
7642#[skip_serializing_none]
7643#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7644#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7645#[non_exhaustive]
7646pub struct McpHttpCapabilities {
7647    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7648    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7649    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7650    ///
7651    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7652    #[serde_as(deserialize_as = "DefaultOnError")]
7653    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7654    #[serde(default)]
7655    #[serde(rename = "_meta")]
7656    pub meta: Option<Meta>,
7657}
7658
7659impl McpHttpCapabilities {
7660    /// Builds an empty [`McpHttpCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7661    #[must_use]
7662    pub fn new() -> Self {
7663        Self::default()
7664    }
7665
7666    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7667    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7668    /// do not recognize.
7669    ///
7670    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7671    #[must_use]
7672    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7673        self.meta = meta.into_option();
7674        self
7675    }
7676}
7677
7678/// **UNSTABLE**
7679///
7680/// This capability is not part of the spec yet, and may be removed or changed at any point.
7681///
7682/// Capabilities for ACP MCP server transports.
7683///
7684/// Supplying `{}` means the Agent supports ACP MCP server transports.
7685#[cfg(feature = "unstable_mcp_over_acp")]
7686#[serde_as]
7687#[skip_serializing_none]
7688#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7689#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7690#[non_exhaustive]
7691pub struct McpAcpCapabilities {
7692    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7693    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7694    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7695    ///
7696    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7697    #[serde_as(deserialize_as = "DefaultOnError")]
7698    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7699    #[serde(default)]
7700    #[serde(rename = "_meta")]
7701    pub meta: Option<Meta>,
7702}
7703
7704#[cfg(feature = "unstable_mcp_over_acp")]
7705impl McpAcpCapabilities {
7706    /// Builds an empty [`McpAcpCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7707    #[must_use]
7708    pub fn new() -> Self {
7709        Self::default()
7710    }
7711
7712    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7713    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7714    /// do not recognize.
7715    ///
7716    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7717    #[must_use]
7718    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7719        self.meta = meta.into_option();
7720        self
7721    }
7722}
7723
7724/// Cancels the named session's active foreground work and earlier prompts not yet inserted.
7725/// It does not cancel later submissions or work in the session's latest `background` list.
7726///
7727/// See protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#cancellation)
7728#[serde_as]
7729#[skip_serializing_none]
7730#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7731#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7732#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CANCEL_METHOD_NAME)))]
7733#[serde(rename_all = "camelCase")]
7734#[non_exhaustive]
7735pub struct CancelSessionNotification {
7736    /// The ID of the session whose foreground work to cancel.
7737    pub session_id: SessionId,
7738    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7739    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7740    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7741    ///
7742    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7743    #[serde_as(deserialize_as = "DefaultOnError")]
7744    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7745    #[serde(default)]
7746    #[serde(rename = "_meta")]
7747    pub meta: Option<Meta>,
7748}
7749
7750impl CancelSessionNotification {
7751    /// Builds [`CancelSessionNotification`] with the required notification fields set. Optional fields start unset or empty.
7752    #[must_use]
7753    pub fn new(session_id: impl Into<SessionId>) -> Self {
7754        Self {
7755            session_id: session_id.into(),
7756            meta: None,
7757        }
7758    }
7759
7760    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7761    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7762    /// do not recognize.
7763    ///
7764    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7765    #[must_use]
7766    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7767        self.meta = meta.into_option();
7768        self
7769    }
7770}
7771
7772// Method schema
7773
7774/// Names of all methods that Agents handle.
7775///
7776/// Provides a centralized definition of method names used in the protocol.
7777#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7778#[non_exhaustive]
7779pub struct AgentMethodNames {
7780    /// Method for initializing the connection.
7781    pub initialize: &'static str,
7782    /// Method for authenticating with the Agent.
7783    pub auth_login: &'static str,
7784    /// Method for listing configurable providers.
7785    #[cfg(feature = "unstable_llm_providers")]
7786    pub providers_list: &'static str,
7787    /// Method for setting provider configuration.
7788    #[cfg(feature = "unstable_llm_providers")]
7789    pub providers_set: &'static str,
7790    /// Method for disabling a provider.
7791    #[cfg(feature = "unstable_llm_providers")]
7792    pub providers_disable: &'static str,
7793    /// Method for creating a new session.
7794    pub session_new: &'static str,
7795    /// Method for setting a configuration option for a session.
7796    pub session_set_config_option: &'static str,
7797    /// Method for sending a prompt to the Agent.
7798    pub session_prompt: &'static str,
7799    /// Notification for cancelling operations.
7800    pub session_cancel: &'static str,
7801    /// Method for exchanging MCP-over-ACP messages.
7802    #[cfg(feature = "unstable_mcp_over_acp")]
7803    pub mcp_message: &'static str,
7804    /// Method for listing existing sessions.
7805    pub session_list: &'static str,
7806    /// Method for deleting an existing session.
7807    pub session_delete: &'static str,
7808    /// Method for forking an existing session.
7809    #[cfg(feature = "unstable_session_fork")]
7810    pub session_fork: &'static str,
7811    /// Method for archiving a session.
7812    #[cfg(feature = "unstable_session_archive")]
7813    pub session_archive: &'static str,
7814    /// Method for unarchiving a session.
7815    #[cfg(feature = "unstable_session_archive")]
7816    pub session_unarchive: &'static str,
7817    /// Method for checking the status of a session.
7818    #[cfg(feature = "unstable_session_status")]
7819    pub session_status: &'static str,
7820    /// Method for querying the config options a session would start with.
7821    #[cfg(feature = "unstable_session_options")]
7822    pub session_options: &'static str,
7823    /// Method for setting the title of a session.
7824    #[cfg(feature = "unstable_session_set_title")]
7825    pub session_set_title: &'static str,
7826    /// Method for resuming an existing session.
7827    pub session_resume: &'static str,
7828    /// Method for closing an active session.
7829    pub session_close: &'static str,
7830    /// Method for cancelling one tool call.
7831    pub tool_call_cancel: &'static str,
7832    /// Method for cancelling one terminal's process.
7833    pub terminal_cancel: &'static str,
7834    /// Method for logging out of an authenticated session.
7835    pub auth_logout: &'static str,
7836    /// Method for querying the Agent's authentication state.
7837    #[cfg(feature = "unstable_auth_status")]
7838    pub auth_status: &'static str,
7839}
7840
7841/// Constant containing all Agent method names.
7842pub const AGENT_METHOD_NAMES: AgentMethodNames = AgentMethodNames {
7843    initialize: INITIALIZE_METHOD_NAME,
7844    auth_login: AUTH_LOGIN_METHOD_NAME,
7845    #[cfg(feature = "unstable_llm_providers")]
7846    providers_list: PROVIDERS_LIST_METHOD_NAME,
7847    #[cfg(feature = "unstable_llm_providers")]
7848    providers_set: PROVIDERS_SET_METHOD_NAME,
7849    #[cfg(feature = "unstable_llm_providers")]
7850    providers_disable: PROVIDERS_DISABLE_METHOD_NAME,
7851    session_new: SESSION_NEW_METHOD_NAME,
7852    session_set_config_option: SESSION_SET_CONFIG_OPTION_METHOD_NAME,
7853    session_prompt: SESSION_PROMPT_METHOD_NAME,
7854    session_cancel: SESSION_CANCEL_METHOD_NAME,
7855    #[cfg(feature = "unstable_mcp_over_acp")]
7856    mcp_message: MCP_MESSAGE_METHOD_NAME,
7857    session_list: SESSION_LIST_METHOD_NAME,
7858    session_delete: SESSION_DELETE_METHOD_NAME,
7859    #[cfg(feature = "unstable_session_fork")]
7860    session_fork: SESSION_FORK_METHOD_NAME,
7861    #[cfg(feature = "unstable_session_archive")]
7862    session_archive: SESSION_ARCHIVE_METHOD_NAME,
7863    #[cfg(feature = "unstable_session_archive")]
7864    session_unarchive: SESSION_UNARCHIVE_METHOD_NAME,
7865    #[cfg(feature = "unstable_session_status")]
7866    session_status: SESSION_STATUS_METHOD_NAME,
7867    #[cfg(feature = "unstable_session_options")]
7868    session_options: SESSION_OPTIONS_METHOD_NAME,
7869    #[cfg(feature = "unstable_session_set_title")]
7870    session_set_title: SESSION_SET_TITLE_METHOD_NAME,
7871    session_resume: SESSION_RESUME_METHOD_NAME,
7872    session_close: SESSION_CLOSE_METHOD_NAME,
7873    tool_call_cancel: TOOL_CALL_CANCEL_METHOD_NAME,
7874    terminal_cancel: TERMINAL_CANCEL_METHOD_NAME,
7875    auth_logout: AUTH_LOGOUT_METHOD_NAME,
7876    #[cfg(feature = "unstable_auth_status")]
7877    auth_status: AUTH_STATUS_METHOD_NAME,
7878};
7879
7880/// Method name for the initialize request.
7881pub(crate) const INITIALIZE_METHOD_NAME: &str = "initialize";
7882/// Method name for the `auth/login` request.
7883pub(crate) const AUTH_LOGIN_METHOD_NAME: &str = "auth/login";
7884/// Method name for listing configurable providers.
7885#[cfg(feature = "unstable_llm_providers")]
7886pub(crate) const PROVIDERS_LIST_METHOD_NAME: &str = "providers/list";
7887/// Method name for setting provider configuration.
7888#[cfg(feature = "unstable_llm_providers")]
7889pub(crate) const PROVIDERS_SET_METHOD_NAME: &str = "providers/set";
7890/// Method name for disabling a provider.
7891#[cfg(feature = "unstable_llm_providers")]
7892pub(crate) const PROVIDERS_DISABLE_METHOD_NAME: &str = "providers/disable";
7893/// Method name for creating a new session.
7894pub(crate) const SESSION_NEW_METHOD_NAME: &str = "session/new";
7895/// Method name for setting a configuration option for a session.
7896pub(crate) const SESSION_SET_CONFIG_OPTION_METHOD_NAME: &str = "session/set_config_option";
7897/// Method name for sending a prompt.
7898pub(crate) const SESSION_PROMPT_METHOD_NAME: &str = "session/prompt";
7899/// Method name for the cancel notification.
7900pub(crate) const SESSION_CANCEL_METHOD_NAME: &str = "session/cancel";
7901/// Method name for listing existing sessions.
7902pub(crate) const SESSION_LIST_METHOD_NAME: &str = "session/list";
7903/// Method name for deleting an existing session.
7904pub(crate) const SESSION_DELETE_METHOD_NAME: &str = "session/delete";
7905/// Method name for forking an existing session.
7906#[cfg(feature = "unstable_session_fork")]
7907pub(crate) const SESSION_FORK_METHOD_NAME: &str = "session/fork";
7908/// Method name for archiving a session.
7909#[cfg(feature = "unstable_session_archive")]
7910pub(crate) const SESSION_ARCHIVE_METHOD_NAME: &str = "session/archive";
7911/// Method name for unarchiving a session.
7912#[cfg(feature = "unstable_session_archive")]
7913pub(crate) const SESSION_UNARCHIVE_METHOD_NAME: &str = "session/unarchive";
7914/// Method name for checking the status of a session.
7915#[cfg(feature = "unstable_session_status")]
7916pub(crate) const SESSION_STATUS_METHOD_NAME: &str = "session/status";
7917/// Method name for querying the config options a session would start with.
7918#[cfg(feature = "unstable_session_options")]
7919pub(crate) const SESSION_OPTIONS_METHOD_NAME: &str = "session/options";
7920/// Method name for setting the title of a session.
7921#[cfg(feature = "unstable_session_set_title")]
7922pub(crate) const SESSION_SET_TITLE_METHOD_NAME: &str = "session/set_title";
7923/// Method name for resuming an existing session.
7924pub(crate) const SESSION_RESUME_METHOD_NAME: &str = "session/resume";
7925/// Method name for closing an active session.
7926pub(crate) const SESSION_CLOSE_METHOD_NAME: &str = "session/close";
7927/// Method name for cancelling one tool call.
7928pub(crate) const TOOL_CALL_CANCEL_METHOD_NAME: &str = "tool_call/cancel";
7929/// Method name for cancelling one terminal's process.
7930pub(crate) const TERMINAL_CANCEL_METHOD_NAME: &str = "terminal/cancel";
7931/// Method name for the `auth/logout` request.
7932pub(crate) const AUTH_LOGOUT_METHOD_NAME: &str = "auth/logout";
7933/// Method name for the `auth/status` request.
7934#[cfg(feature = "unstable_auth_status")]
7935pub(crate) const AUTH_STATUS_METHOD_NAME: &str = "auth/status";
7936
7937/// All possible requests that a Client can send to an Agent.
7938///
7939/// This enum is used internally for routing RPC requests. You typically won't need
7940/// to use this directly.
7941///
7942/// This enum encompasses all method calls from Client to Agent.
7943#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7944#[derive(Clone, Debug, Serialize, Deserialize)]
7945#[serde(untagged)]
7946#[cfg_attr(feature = "schemars", schemars(inline))]
7947#[non_exhaustive]
7948pub enum ClientRequest {
7949    /// Establishes the connection with a Client and negotiates protocol capabilities.
7950    ///
7951    /// This method is called at the beginning of the connection, before any other request, to:
7952    /// - Negotiate the protocol version to use
7953    /// - Exchange capability information between Client and Agent
7954    /// - Determine available authentication methods
7955    ///
7956    /// The Client MAY repeat it before its first other request. The latest successful
7957    /// `initialize` is authoritative.
7958    ///
7959    /// The Agent responds with its supported protocol version and capabilities.
7960    ///
7961    /// See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/v2/initialization)
7962    InitializeRequest(Box<InitializeRequest>),
7963    /// Authenticates the Client using the specified authentication method.
7964    ///
7965    /// Agents MUST support this method when their `initialize` response included
7966    /// a non-empty `authMethods` list. Clients MUST call this method only
7967    /// with a method whose type defines a protocol-driven login flow, and MUST NOT
7968    /// call it when `authMethods` was omitted or empty.
7969    ///
7970    /// Called when the Agent requires authentication before allowing session creation.
7971    /// The Client provides the authentication method ID that was advertised during initialization.
7972    ///
7973    /// After successful authentication, the Client can proceed to create sessions with
7974    /// `session/new` without receiving a `-32000` (Authentication required) error.
7975    ///
7976    /// See protocol docs: [Authentication](https://agentclientprotocol.com/protocol/v2/authentication)
7977    LoginAuthRequest(Box<LoginAuthRequest>),
7978    /// **UNSTABLE**
7979    ///
7980    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7981    ///
7982    /// Lists providers that can be configured by the Client.
7983    #[cfg(feature = "unstable_llm_providers")]
7984    ListProvidersRequest(Box<ListProvidersRequest>),
7985    /// **UNSTABLE**
7986    ///
7987    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7988    ///
7989    /// Replaces the configuration for a provider.
7990    #[cfg(feature = "unstable_llm_providers")]
7991    SetProviderRequest(Box<SetProviderRequest>),
7992    /// **UNSTABLE**
7993    ///
7994    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7995    ///
7996    /// Disables a provider.
7997    #[cfg(feature = "unstable_llm_providers")]
7998    DisableProviderRequest(Box<DisableProviderRequest>),
7999    /// Logs out of the current authenticated state.
8000    ///
8001    /// Agents MUST support this method when their `initialize` response included
8002    /// a non-empty `authMethods` list. Clients MUST NOT call this method
8003    /// when `authMethods` was omitted or empty.
8004    ///
8005    /// After a successful logout, authentication-gated requests require the
8006    /// Client to complete an advertised authentication flow again. There is no
8007    /// guarantee about the behavior of already running sessions.
8008    LogoutAuthRequest(Box<LogoutAuthRequest>),
8009    /// **UNSTABLE**
8010    ///
8011    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8012    ///
8013    /// Queries the Agent's current authentication state.
8014    ///
8015    /// This method is only available if the Agent advertises the `auth.status` capability.
8016    /// It MUST NOT change any Agent state, and Agents MUST NOT reject it with `-32000` (Authentication required).
8017    #[cfg(feature = "unstable_auth_status")]
8018    AuthStatusRequest(Box<AuthStatusRequest>),
8019    /// Creates a new conversation session with the Agent.
8020    ///
8021    /// Sessions represent independent conversation contexts with their own history and state.
8022    ///
8023    /// The Agent:
8024    /// - Creates a new session context
8025    /// - Connects to the specified MCP servers
8026    /// - Returns a unique session ID for future requests
8027    ///
8028    /// Fails with `-32000` (Authentication required) if the Agent requires authentication.
8029    ///
8030    /// See protocol docs: [Session Setup](https://agentclientprotocol.com/protocol/v2/session-setup)
8031    NewSessionRequest(Box<NewSessionRequest>),
8032    /// Lists existing sessions known to the Agent.
8033    ///
8034    /// The Agent returns metadata about sessions, with optional filtering and pagination.
8035    ListSessionsRequest(Box<ListSessionsRequest>),
8036    /// Deletes an existing session from `session/list`.
8037    ///
8038    /// This method is only available if the Agent advertises the `session.delete` capability.
8039    DeleteSessionRequest(Box<DeleteSessionRequest>),
8040    #[cfg(feature = "unstable_session_fork")]
8041    /// **UNSTABLE**
8042    ///
8043    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8044    ///
8045    /// Forks an existing session to create a new independent session.
8046    ///
8047    /// This method is only available if the Agent advertises the `session.fork` capability.
8048    ///
8049    /// The Agent creates a new session with the same conversation context as the
8050    /// original. The fork can be used for operations like generating summaries without
8051    /// affecting the original session's history.
8052    ///
8053    /// As with `session/new`, the forked session is active once the Agent responds,
8054    /// set up with the request's `cwd`, `additionalDirectories`, and `mcpServers`.
8055    /// The Client can prompt it without calling `session/resume` first.
8056    ForkSessionRequest(Box<ForkSessionRequest>),
8057    #[cfg(feature = "unstable_session_archive")]
8058    /// **UNSTABLE**
8059    ///
8060    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8061    ///
8062    /// Archives a session, hiding it from default `session/list` results.
8063    ///
8064    /// This method is only available if the Agent advertises the `session.archive` capability.
8065    ArchiveSessionRequest(Box<ArchiveSessionRequest>),
8066    #[cfg(feature = "unstable_session_archive")]
8067    /// **UNSTABLE**
8068    ///
8069    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8070    ///
8071    /// Unarchives a session, returning it to default `session/list` results.
8072    ///
8073    /// This method is only available if the Agent advertises the `session.archive` capability.
8074    UnarchiveSessionRequest(Box<UnarchiveSessionRequest>),
8075    #[cfg(feature = "unstable_session_status")]
8076    /// **UNSTABLE**
8077    ///
8078    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8079    ///
8080    /// Checks whether the Agent has a session in memory, without changing it.
8081    ///
8082    /// This method is only available if the Agent advertises the `session.status` capability.
8083    SessionStatusRequest(Box<SessionStatusRequest>),
8084    #[cfg(feature = "unstable_session_options")]
8085    /// **UNSTABLE**
8086    ///
8087    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8088    ///
8089    /// Returns the config options a session would start with, without creating or resuming a session.
8090    ///
8091    /// This method is only available if the Agent advertises the `session.options` capability.
8092    SessionOptionsRequest(Box<SessionOptionsRequest>),
8093    #[cfg(feature = "unstable_session_set_title")]
8094    /// **UNSTABLE**
8095    ///
8096    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8097    ///
8098    /// Sets the title of a session.
8099    ///
8100    /// This method is only available if the Agent advertises the `session.title` capability.
8101    ///
8102    /// The session does not need to be active on the connection. The Agent stores the
8103    /// title and returns the stored title, which may be normalized.
8104    SetSessionTitleRequest(Box<SetSessionTitleRequest>),
8105    /// Resumes an existing session.
8106    ///
8107    /// The Agent resumes the session context so that the conversation
8108    /// can continue. If `replayFrom` is set, the Agent replays
8109    /// retained conversation history before responding.
8110    ResumeSessionRequest(Box<ResumeSessionRequest>),
8111    /// Closes an active session and frees up any resources associated with it.
8112    ///
8113    /// The Agent MUST cancel any ongoing work as if `session/cancel` was called, stop the
8114    /// session's background work, and then free the resources associated with the session.
8115    CloseSessionRequest(Box<CloseSessionRequest>),
8116    /// Cancels one tool call without cancelling the rest of the session's work.
8117    ///
8118    /// This method is only available while the tool call advertises `capabilities.cancel`.
8119    /// The response means the Agent accepted the cancellation. A final `tool_call_update`
8120    /// confirms it.
8121    CancelToolCallRequest(Box<CancelToolCallRequest>),
8122    /// Stops one terminal's process without cancelling the rest of the session's work.
8123    ///
8124    /// This method is only available while the terminal advertises `capabilities.cancel`.
8125    /// The response means the Agent accepted the cancellation. A `terminal_update` with
8126    /// `exitStatus` confirms it.
8127    CancelTerminalRequest(Box<CancelTerminalRequest>),
8128    /// Sets the current value for a session configuration option.
8129    SetSessionConfigOptionRequest(Box<SetSessionConfigOptionRequest>),
8130    /// Processes a user prompt within a session.
8131    ///
8132    /// Acceptance means adding a logical user message with an ID and a position
8133    /// relative to other messages in the ACP conversation, not receipt or queueing.
8134    /// The Agent MUST return the inserted message's ID without waiting for
8135    /// processing to finish.
8136    ///
8137    /// The Agent reports the user message with the same ID through `session/update`.
8138    /// This notification can arrive before or after the response, and MUST NOT
8139    /// precede insertion. Processing state, output, tool calls, and completion are
8140    /// also reported through session updates.
8141    ///
8142    /// An error response means the user message was not inserted. Once it is
8143    /// inserted, the Agent MUST NOT answer with an error, even if the work fails
8144    /// before the response is sent. It ends that work with the `error` stop reason.
8145    ///
8146    /// A rejected submission produces no user-message updates. Foreground state
8147    /// follows its normal lifecycle independently of the request outcome:
8148    /// `running` may precede insertion, and rejection alone does not imply `idle`.
8149    ///
8150    /// See protocol docs: [Prompt Lifecycle](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle)
8151    PromptRequest(Box<PromptRequest>),
8152    /// Handles extension method requests from the Client.
8153    ///
8154    /// Extension methods are custom methods that are not part of the ACP spec.
8155    ///
8156    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
8157    ExtMethodRequest(Box<ExtRequest>),
8158}
8159
8160impl_request_dispatch! {
8161    ClientRequest => AgentResponse {
8162        InitializeRequest => InitializeResponse: AGENT_METHOD_NAMES.initialize,
8163        LoginAuthRequest => LoginAuthResponse: AGENT_METHOD_NAMES.auth_login,
8164        #[cfg(feature = "unstable_llm_providers")]
8165        ListProvidersRequest => ListProvidersResponse: AGENT_METHOD_NAMES.providers_list,
8166        #[cfg(feature = "unstable_llm_providers")]
8167        SetProviderRequest => SetProviderResponse: AGENT_METHOD_NAMES.providers_set,
8168        #[cfg(feature = "unstable_llm_providers")]
8169        DisableProviderRequest => DisableProviderResponse: AGENT_METHOD_NAMES.providers_disable,
8170        LogoutAuthRequest => LogoutAuthResponse: AGENT_METHOD_NAMES.auth_logout,
8171        #[cfg(feature = "unstable_auth_status")]
8172        AuthStatusRequest => AuthStatusResponse: AGENT_METHOD_NAMES.auth_status,
8173        NewSessionRequest => NewSessionResponse: AGENT_METHOD_NAMES.session_new,
8174        ListSessionsRequest => ListSessionsResponse: AGENT_METHOD_NAMES.session_list,
8175        DeleteSessionRequest => DeleteSessionResponse: AGENT_METHOD_NAMES.session_delete,
8176        #[cfg(feature = "unstable_session_fork")]
8177        ForkSessionRequest => ForkSessionResponse: AGENT_METHOD_NAMES.session_fork,
8178        #[cfg(feature = "unstable_session_archive")]
8179        ArchiveSessionRequest => ArchiveSessionResponse: AGENT_METHOD_NAMES.session_archive,
8180        #[cfg(feature = "unstable_session_archive")]
8181        UnarchiveSessionRequest => UnarchiveSessionResponse: AGENT_METHOD_NAMES.session_unarchive,
8182        #[cfg(feature = "unstable_session_status")]
8183        SessionStatusRequest => SessionStatusResponse: AGENT_METHOD_NAMES.session_status,
8184        #[cfg(feature = "unstable_session_options")]
8185        SessionOptionsRequest => SessionOptionsResponse: AGENT_METHOD_NAMES.session_options,
8186        #[cfg(feature = "unstable_session_set_title")]
8187        SetSessionTitleRequest => SetSessionTitleResponse: AGENT_METHOD_NAMES.session_set_title,
8188        ResumeSessionRequest => ResumeSessionResponse: AGENT_METHOD_NAMES.session_resume,
8189        CloseSessionRequest => CloseSessionResponse: AGENT_METHOD_NAMES.session_close,
8190        CancelToolCallRequest => CancelToolCallResponse: AGENT_METHOD_NAMES.tool_call_cancel,
8191        CancelTerminalRequest => CancelTerminalResponse: AGENT_METHOD_NAMES.terminal_cancel,
8192        SetSessionConfigOptionRequest => SetSessionConfigOptionResponse: AGENT_METHOD_NAMES.session_set_config_option,
8193        PromptRequest => PromptResponse: AGENT_METHOD_NAMES.session_prompt,
8194    }
8195    extension ExtMethodRequest(Box<ExtRequest>) => ExtMethodResponse;
8196}
8197
8198/// All possible responses that an Agent can send to a Client.
8199///
8200/// This enum is used internally for routing RPC responses. You typically won't need
8201/// to use this directly. The connection handles the responses automatically.
8202///
8203/// These are responses to the corresponding `ClientRequest` variants.
8204#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
8205#[derive(Clone, Debug, Serialize, Deserialize)]
8206#[serde(untagged)]
8207#[cfg_attr(feature = "schemars", schemars(inline))]
8208#[non_exhaustive]
8209pub enum AgentResponse {
8210    /// Successful result returned for a `initialize` request.
8211    InitializeResponse(Box<InitializeResponse>),
8212    /// Successful result returned for an `auth/login` request.
8213    LoginAuthResponse(#[serde(default)] Box<LoginAuthResponse>),
8214    /// Successful result returned for a `providers/list` request.
8215    #[cfg(feature = "unstable_llm_providers")]
8216    ListProvidersResponse(Box<ListProvidersResponse>),
8217    /// Successful result returned for a `providers/set` request.
8218    #[cfg(feature = "unstable_llm_providers")]
8219    SetProviderResponse(#[serde(default)] Box<SetProviderResponse>),
8220    /// Successful result returned for a `providers/disable` request.
8221    #[cfg(feature = "unstable_llm_providers")]
8222    DisableProviderResponse(#[serde(default)] Box<DisableProviderResponse>),
8223    /// Successful result returned for an `auth/logout` request.
8224    LogoutAuthResponse(#[serde(default)] Box<LogoutAuthResponse>),
8225    /// Successful result returned for an `auth/status` request.
8226    #[cfg(feature = "unstable_auth_status")]
8227    AuthStatusResponse(Box<AuthStatusResponse>),
8228    /// Successful result returned for a `session/new` request.
8229    NewSessionResponse(Box<NewSessionResponse>),
8230    /// Successful result returned for a `session/list` request.
8231    ListSessionsResponse(Box<ListSessionsResponse>),
8232    /// Successful result returned for a `session/delete` request.
8233    DeleteSessionResponse(#[serde(default)] Box<DeleteSessionResponse>),
8234    /// Successful result returned for a `session/fork` request.
8235    #[cfg(feature = "unstable_session_fork")]
8236    ForkSessionResponse(Box<ForkSessionResponse>),
8237    /// Successful result returned for a `session/archive` request.
8238    #[cfg(feature = "unstable_session_archive")]
8239    ArchiveSessionResponse(#[serde(default)] Box<ArchiveSessionResponse>),
8240    /// Successful result returned for a `session/unarchive` request.
8241    #[cfg(feature = "unstable_session_archive")]
8242    UnarchiveSessionResponse(#[serde(default)] Box<UnarchiveSessionResponse>),
8243    /// Successful result returned for a `session/status` request.
8244    #[cfg(feature = "unstable_session_status")]
8245    SessionStatusResponse(Box<SessionStatusResponse>),
8246    /// Successful result returned for a `session/options` request.
8247    #[cfg(feature = "unstable_session_options")]
8248    SessionOptionsResponse(#[serde(default)] Box<SessionOptionsResponse>),
8249    /// Successful result returned for a `session/set_title` request.
8250    #[cfg(feature = "unstable_session_set_title")]
8251    SetSessionTitleResponse(Box<SetSessionTitleResponse>),
8252    /// Successful result returned for a `session/resume` request.
8253    ResumeSessionResponse(#[serde(default)] Box<ResumeSessionResponse>),
8254    /// Successful result returned for a `session/close` request.
8255    CloseSessionResponse(#[serde(default)] Box<CloseSessionResponse>),
8256    /// Successful result returned for a `tool_call/cancel` request.
8257    CancelToolCallResponse(#[serde(default)] Box<CancelToolCallResponse>),
8258    /// Successful result returned for a `terminal/cancel` request.
8259    CancelTerminalResponse(#[serde(default)] Box<CancelTerminalResponse>),
8260    /// Successful result returned for a `session/set_config_option` request.
8261    SetSessionConfigOptionResponse(Box<SetSessionConfigOptionResponse>),
8262    /// Successful result returned for a `session/prompt` request.
8263    PromptResponse(Box<PromptResponse>),
8264    /// Successful result returned by an extension method outside the core ACP method set.
8265    ExtMethodResponse(Box<ExtResponse>),
8266}
8267
8268/// All possible notifications that a Client can send to an Agent.
8269///
8270/// This enum is used internally for routing RPC notifications. You typically won't need
8271/// to use this directly.
8272///
8273/// Notifications do not expect a response.
8274#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
8275#[derive(Clone, Debug, Serialize, Deserialize)]
8276#[serde(untagged)]
8277#[cfg_attr(feature = "schemars", schemars(inline))]
8278#[non_exhaustive]
8279pub enum ClientNotification {
8280    /// Cancels the named session's active foreground work and earlier prompts not yet inserted.
8281    /// The Agent MUST answer those uninserted prompts with `-32800`. Inserted prompts still
8282    /// succeed with their `messageId`. This cancellation does not cover later submissions.
8283    ///
8284    /// Work in the latest `background` list is not covered and keeps running. The
8285    /// Agent MAY stop background activity it does not list.
8286    ///
8287    /// Upon receiving this notification, the Agent SHOULD stop all language model
8288    /// requests and all tool call invocations of the cancelled foreground work as soon
8289    /// as possible.
8290    ///
8291    /// The Agent MUST stop waiting for pending `session/request_permission` requests of
8292    /// the cancelled work and treat them as not approved. It MUST cancel each of them
8293    /// with `$/cancel_request`.
8294    ///
8295    /// When cancellation stops active foreground work, the Agent MUST send that work's
8296    /// pending updates, then an idle `state_update` with `stopReason: "cancelled"`,
8297    /// before starting new foreground work in the same session. A later prompt can be
8298    /// inserted and acknowledged before that idle update, or held with its response
8299    /// pending. Listed background work can report updates before or after it.
8300    /// No additional idle update is required if no foreground work was active.
8301    ///
8302    /// After cancellation completes, the Agent SHOULD ignore late answers rather
8303    /// than use them to resume the cancelled work.
8304    ///
8305    /// Agents MUST catch errors caused by aborting cancelled work and report the
8306    /// `cancelled` stop reason, not `error`.
8307    ///
8308    /// See protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#cancellation)
8309    CancelSessionNotification(Box<CancelSessionNotification>),
8310    /// **UNSTABLE**
8311    ///
8312    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8313    ///
8314    /// Sends an MCP-over-ACP notification.
8315    #[cfg(feature = "unstable_mcp_over_acp")]
8316    MessageMcpNotification(Box<MessageMcpNotification>),
8317    /// Handles extension notifications from the Client.
8318    ///
8319    /// Extension notifications are custom one-way messages that are not part of the ACP spec.
8320    ///
8321    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
8322    ExtNotification(Box<ExtNotification>),
8323}
8324
8325impl_message_dispatch! {
8326    ClientNotification {
8327        CancelSessionNotification => AGENT_METHOD_NAMES.session_cancel,
8328        #[cfg(feature = "unstable_mcp_over_acp")]
8329        MessageMcpNotification => AGENT_METHOD_NAMES.mcp_message,
8330    }
8331    extension ExtNotification(Box<ExtNotification>);
8332}
8333
8334#[cfg(test)]
8335mod test_serialization {
8336    use std::path::PathBuf;
8337
8338    use super::*;
8339    use serde_json::json;
8340
8341    fn test_meta() -> Meta {
8342        json!({ "source": "test" }).as_object().unwrap().clone()
8343    }
8344
8345    #[test]
8346    fn list_sessions_cursor_and_session_directories_are_strict() {
8347        for cursor in [json!(null), json!("next")] {
8348            let response = json!({ "sessions": [], "nextCursor": cursor });
8349            serde_json::from_value::<ListSessionsResponse>(response).unwrap();
8350        }
8351        let malformed = json!({ "sessions": [], "nextCursor": 42 });
8352        assert!(serde_json::from_value::<ListSessionsResponse>(malformed).is_err());
8353
8354        let session = |dirs: serde_json::Value| json!({ "sessionId": "s", "cwd": "/w", "additionalDirectories": dirs });
8355        let info: SessionInfo = serde_json::from_value(session(json!(null))).unwrap();
8356        assert_eq!(info.additional_directories, Vec::<AbsolutePath>::new());
8357        for bad in [json!(["/a", 42]), json!("/a")] {
8358            assert!(serde_json::from_value::<SessionInfo>(session(bad)).is_err());
8359        }
8360        // A session with malformed directories is skipped, not truncated.
8361        let response = json!({ "sessions": [session(json!(["/a", 42]))] });
8362        let response: ListSessionsResponse = serde_json::from_value(response).unwrap();
8363        assert_eq!(response.sessions, Vec::<SessionInfo>::new());
8364    }
8365
8366    #[test]
8367    fn other_fallbacks_preserve_optional_fields_verbatim() {
8368        let valid = json!({ "type": "_custom", "methodId": "m", "name": "M",
8369            "description": "d", "_meta": { "k": 1 } });
8370        let method: AuthMethod = serde_json::from_value(valid.clone()).unwrap();
8371        assert_eq!(method.description(), Some("d"));
8372        assert_eq!(
8373            method.meta(),
8374            Some(&json!({ "k": 1 }).as_object().unwrap().clone())
8375        );
8376        assert_eq!(serde_json::to_value(&method).unwrap(), valid);
8377
8378        // Malformed optional fields are kept as sent and read as absent.
8379        let malformed = json!({ "type": "_custom", "methodId": "m", "name": "M",
8380            "description": 42, "_meta": "bad", "extra": true });
8381        let method: AuthMethod = serde_json::from_value(malformed.clone()).unwrap();
8382        assert_eq!(method.description(), None);
8383        assert_eq!(method.meta(), None);
8384        assert_eq!(serde_json::to_value(&method).unwrap(), malformed);
8385
8386        let replay = json!({ "type": "_custom", "_meta": "bad", "cursor": 3 });
8387        let decoded: ReplayFrom = serde_json::from_value(replay.clone()).unwrap();
8388        assert_eq!(serde_json::to_value(&decoded).unwrap(), replay);
8389    }
8390
8391    fn serialized_meta_key_count(value: &impl serde::Serialize) -> usize {
8392        serde_json::to_string(value)
8393            .unwrap()
8394            .matches("\"_meta\"")
8395            .count()
8396    }
8397
8398    #[test]
8399    fn prompt_response_without_metadata_round_trips() {
8400        let response = PromptResponse::new(MessageId::new("message-1"));
8401        let serialized = serde_json::to_value(&response).unwrap();
8402        assert_eq!(serialized, json!({ "messageId": "message-1" }));
8403        assert_eq!(
8404            serde_json::from_value::<PromptResponse>(serialized).unwrap(),
8405            response
8406        );
8407        assert_eq!(
8408            serde_json::from_value::<PromptResponse>(json!({
8409                "messageId": "message-1",
8410                "_meta": null
8411            }))
8412            .unwrap(),
8413            response
8414        );
8415    }
8416
8417    #[test]
8418    fn prompt_response_requires_message_id_and_preserves_metadata_tolerance() {
8419        let response = PromptResponse::new("message-1").meta(test_meta());
8420        let serialized = serde_json::to_value(&response).unwrap();
8421        assert_eq!(
8422            serialized,
8423            json!({
8424                "messageId": "message-1",
8425                "_meta": { "source": "test" }
8426            })
8427        );
8428
8429        let deserialized: PromptResponse = serde_json::from_value(serialized).unwrap();
8430        assert_eq!(deserialized.message_id, MessageId::new("message-1"));
8431        assert_eq!(deserialized.meta, Some(test_meta()));
8432
8433        let malformed_meta: PromptResponse = serde_json::from_value(json!({
8434            "messageId": "message-2",
8435            "_meta": false
8436        }))
8437        .unwrap();
8438        assert_eq!(malformed_meta.message_id, MessageId::new("message-2"));
8439        assert_eq!(malformed_meta.meta, None);
8440
8441        for invalid in [
8442            json!({}),
8443            json!({ "messageId": null }),
8444            json!({ "messageId": 1 }),
8445            json!({ "messageId": false }),
8446            json!({ "messageId": {} }),
8447            json!({ "messageId": [] }),
8448        ] {
8449            assert!(
8450                serde_json::from_value::<PromptResponse>(invalid).is_err(),
8451                "missing, null, and non-string message IDs must be rejected"
8452            );
8453        }
8454    }
8455
8456    #[cfg(feature = "schemars")]
8457    #[test]
8458    fn prompt_response_schema_requires_non_null_string_message_id_reference() {
8459        let schema = serde_json::to_value(schemars::schema_for!(PromptResponse)).unwrap();
8460
8461        assert_eq!(schema["required"], json!(["messageId"]));
8462        assert_eq!(
8463            schema["properties"]["messageId"]["$ref"],
8464            "#/$defs/MessageId"
8465        );
8466        assert_eq!(schema["$defs"]["MessageId"]["type"], "string");
8467    }
8468
8469    #[test]
8470    fn test_initialize_capabilities_default_on_malformed_values() {
8471        let request: InitializeRequest = serde_json::from_value(json!({
8472            "protocolVersion": 2,
8473            "capabilities": false,
8474            "info": {
8475                "name": "client",
8476                "version": "1.0.0"
8477            }
8478        }))
8479        .unwrap();
8480        assert_eq!(request.capabilities, ClientCapabilities::default());
8481
8482        let response: InitializeResponse = serde_json::from_value(json!({
8483            "protocolVersion": 2,
8484            "capabilities": false,
8485            "info": {
8486                "name": "agent",
8487                "version": "1.0.0"
8488            }
8489        }))
8490        .unwrap();
8491        assert_eq!(response.capabilities, AgentCapabilities::default());
8492    }
8493
8494    #[test]
8495    fn test_agent_capabilities_default_on_malformed_values() {
8496        let capabilities: AgentCapabilities = serde_json::from_value(json!({
8497            "session": false,
8498            "auth": false
8499        }))
8500        .unwrap();
8501
8502        assert!(capabilities.session.is_none());
8503        assert_eq!(capabilities.auth, None);
8504    }
8505
8506    #[test]
8507    fn test_mcp_server_stdio_serialization() {
8508        let server = McpServer::Stdio(
8509            McpServerStdio::new("test-server", "/usr/bin/server")
8510                .args(vec!["--port".to_string(), "3000".to_string()])
8511                .env(vec![EnvVariable::new("API_KEY", "secret123")]),
8512        );
8513
8514        let json = serde_json::to_value(&server).unwrap();
8515        assert_eq!(
8516            json,
8517            json!({
8518                "type": "stdio",
8519                "name": "test-server",
8520                "command": "/usr/bin/server",
8521                "args": ["--port", "3000"],
8522                "env": [
8523                    {
8524                        "name": "API_KEY",
8525                        "value": "secret123"
8526                    }
8527                ]
8528            })
8529        );
8530
8531        let deserialized: McpServer = serde_json::from_value(json).unwrap();
8532        match deserialized {
8533            McpServer::Stdio(McpServerStdio {
8534                name,
8535                command,
8536                args,
8537                env,
8538                meta: _,
8539            }) => {
8540                assert_eq!(name, "test-server");
8541                assert_eq!(command, AbsolutePath::new("/usr/bin/server"));
8542                assert_eq!(args, vec!["--port", "3000"]);
8543                assert_eq!(env.len(), 1);
8544                assert_eq!(env[0].name, "API_KEY");
8545                assert_eq!(env[0].value, "secret123");
8546            }
8547            _ => panic!("Expected Stdio variant"),
8548        }
8549    }
8550
8551    #[test]
8552    fn test_mcp_server_empty_arrays_are_optional() {
8553        let stdio = McpServer::Stdio(McpServerStdio::new("test-server", "/usr/bin/server"));
8554        assert_eq!(
8555            serde_json::to_value(&stdio).unwrap(),
8556            json!({
8557                "type": "stdio",
8558                "name": "test-server",
8559                "command": "/usr/bin/server"
8560            })
8561        );
8562
8563        let McpServer::Stdio(McpServerStdio { args, env, .. }) =
8564            serde_json::from_value::<McpServer>(json!({
8565                "type": "stdio",
8566                "name": "test-server",
8567                "command": "/usr/bin/server"
8568            }))
8569            .unwrap()
8570        else {
8571            panic!("Expected Stdio variant");
8572        };
8573        assert_eq!(args, Vec::<String>::new());
8574        assert_eq!(env, []);
8575
8576        let http = McpServer::Http(McpServerHttp::new("http-server", "https://api.example.com"));
8577        assert_eq!(
8578            serde_json::to_value(&http).unwrap(),
8579            json!({
8580                "type": "http",
8581                "name": "http-server",
8582                "url": "https://api.example.com"
8583            })
8584        );
8585
8586        let McpServer::Http(McpServerHttp { headers, .. }) =
8587            serde_json::from_value::<McpServer>(json!({
8588                "type": "http",
8589                "name": "http-server",
8590                "url": "https://api.example.com"
8591            }))
8592            .unwrap()
8593        else {
8594            panic!("Expected Http variant");
8595        };
8596        assert_eq!(headers, []);
8597    }
8598
8599    #[test]
8600    fn test_mcp_server_unknown_transport_serialization() {
8601        let json = json!({
8602            "type": "websocket",
8603            "name": "future-server",
8604            "url": "wss://example.com/mcp",
8605            "protocolVersion": "2026-01-01"
8606        });
8607
8608        let deserialized: McpServer = serde_json::from_value(json.clone()).unwrap();
8609        let McpServer::Other(OtherMcpServer { type_, fields }) = &deserialized else {
8610            panic!("Expected Other variant");
8611        };
8612
8613        assert_eq!(type_, "websocket");
8614        assert_eq!(fields["name"], "future-server");
8615        assert_eq!(fields["url"], "wss://example.com/mcp");
8616        assert_eq!(fields["protocolVersion"], "2026-01-01");
8617        assert_eq!(serde_json::to_value(&deserialized).unwrap(), json);
8618    }
8619
8620    #[test]
8621    fn test_mcp_server_stdio_requires_type() {
8622        let result = serde_json::from_value::<McpServer>(json!({
8623            "name": "test-server",
8624            "command": "/usr/bin/server",
8625            "args": [],
8626            "env": []
8627        }));
8628
8629        assert!(result.is_err());
8630    }
8631
8632    #[test]
8633    fn test_mcp_server_unknown_does_not_hide_malformed_known_transport() {
8634        let result = serde_json::from_value::<McpServer>(json!({
8635            "type": "stdio",
8636            "name": "test-server",
8637            "args": [],
8638            "env": []
8639        }));
8640
8641        assert!(result.is_err());
8642    }
8643
8644    #[test]
8645    fn test_mcp_server_http_serialization() {
8646        let server = McpServer::Http(
8647            McpServerHttp::new("http-server", "https://api.example.com").headers(vec![
8648                HttpHeader::new("Authorization", "Bearer token123"),
8649                HttpHeader::new("Content-Type", "application/json"),
8650            ]),
8651        );
8652
8653        let json = serde_json::to_value(&server).unwrap();
8654        assert_eq!(
8655            json,
8656            json!({
8657                "type": "http",
8658                "name": "http-server",
8659                "url": "https://api.example.com",
8660                "headers": [
8661                    {
8662                        "name": "Authorization",
8663                        "value": "Bearer token123"
8664                    },
8665                    {
8666                        "name": "Content-Type",
8667                        "value": "application/json"
8668                    }
8669                ]
8670            })
8671        );
8672
8673        let deserialized: McpServer = serde_json::from_value(json).unwrap();
8674        match deserialized {
8675            McpServer::Http(McpServerHttp {
8676                name,
8677                url,
8678                headers,
8679                meta: _,
8680            }) => {
8681                assert_eq!(name, "http-server");
8682                assert_eq!(url, "https://api.example.com");
8683                assert_eq!(headers.len(), 2);
8684                assert_eq!(headers[0].name, "Authorization");
8685                assert_eq!(headers[0].value, "Bearer token123");
8686                assert_eq!(headers[1].name, "Content-Type");
8687                assert_eq!(headers[1].value, "application/json");
8688            }
8689            _ => panic!("Expected Http variant"),
8690        }
8691    }
8692
8693    #[cfg(feature = "schemars")]
8694    #[test]
8695    fn mcp_server_http_schema_marks_url_as_uri() {
8696        let schema = serde_json::to_value(schemars::schema_for!(McpServerHttp)).unwrap();
8697
8698        assert_eq!(schema["properties"]["url"]["format"], "uri");
8699    }
8700
8701    #[cfg(feature = "unstable_mcp_over_acp")]
8702    #[test]
8703    fn test_client_mcp_message_method_names() {
8704        use serde_json::json;
8705
8706        assert_eq!(AGENT_METHOD_NAMES.mcp_message, "mcp/message");
8707
8708        let notification =
8709            MessageMcpNotification::new("server-1", "req-1", "notifications/progress");
8710        assert_eq!(
8711            ClientNotification::MessageMcpNotification(Box::new(notification.clone())).method(),
8712            "mcp/message"
8713        );
8714        assert_eq!(
8715            serde_json::to_value(notification).unwrap(),
8716            json!({
8717                "serverId": "server-1",
8718                "requestId": "req-1",
8719                "method": "notifications/progress"
8720            })
8721        );
8722        let notification: MessageMcpNotification = serde_json::from_value(json!({
8723            "serverId": "server-1", "requestId": "req-1", "method": "notifications/progress",
8724            "params": null, "_meta": null
8725        }))
8726        .unwrap();
8727        assert_eq!(notification.params, None);
8728        assert_eq!(notification.meta, None);
8729        for key in ["serverId", "requestId", "method"] {
8730            let mut value = json!({"serverId":"server-1", "requestId":"req-1", "method":"notifications/progress"});
8731            value.as_object_mut().unwrap().remove(key);
8732            assert!(serde_json::from_value::<MessageMcpNotification>(value).is_err());
8733        }
8734    }
8735
8736    #[test]
8737    fn test_auth_method_names() {
8738        assert_eq!(AGENT_METHOD_NAMES.auth_login, "auth/login");
8739        assert_eq!(AGENT_METHOD_NAMES.auth_logout, "auth/logout");
8740
8741        assert_eq!(
8742            ClientRequest::LoginAuthRequest(Box::new(LoginAuthRequest::new("agent-login")))
8743                .method(),
8744            "auth/login"
8745        );
8746        assert_eq!(
8747            ClientRequest::LogoutAuthRequest(Box::new(LogoutAuthRequest::new())).method(),
8748            "auth/logout"
8749        );
8750    }
8751
8752    #[test]
8753    fn test_session_config_option_category_known_variants() {
8754        // Test serialization of known variants
8755        assert_eq!(
8756            serde_json::to_value(&SessionConfigOptionCategory::Mode).unwrap(),
8757            json!("mode")
8758        );
8759        assert_eq!(
8760            serde_json::to_value(&SessionConfigOptionCategory::Model).unwrap(),
8761            json!("model")
8762        );
8763        assert_eq!(
8764            serde_json::to_value(&SessionConfigOptionCategory::ModelConfig).unwrap(),
8765            json!("model_config")
8766        );
8767        #[cfg(feature = "unstable_speed_config_category")]
8768        assert_eq!(
8769            serde_json::to_value(&SessionConfigOptionCategory::Speed).unwrap(),
8770            json!("speed")
8771        );
8772        assert_eq!(
8773            serde_json::to_value(&SessionConfigOptionCategory::ThoughtLevel).unwrap(),
8774            json!("thought_level")
8775        );
8776
8777        // Test deserialization of known variants
8778        assert_eq!(
8779            serde_json::from_str::<SessionConfigOptionCategory>("\"mode\"").unwrap(),
8780            SessionConfigOptionCategory::Mode
8781        );
8782        assert_eq!(
8783            serde_json::from_str::<SessionConfigOptionCategory>("\"model\"").unwrap(),
8784            SessionConfigOptionCategory::Model
8785        );
8786        assert_eq!(
8787            serde_json::from_str::<SessionConfigOptionCategory>("\"model_config\"").unwrap(),
8788            SessionConfigOptionCategory::ModelConfig
8789        );
8790        #[cfg(feature = "unstable_speed_config_category")]
8791        assert_eq!(
8792            serde_json::from_str::<SessionConfigOptionCategory>("\"speed\"").unwrap(),
8793            SessionConfigOptionCategory::Speed
8794        );
8795        assert_eq!(
8796            serde_json::from_str::<SessionConfigOptionCategory>("\"thought_level\"").unwrap(),
8797            SessionConfigOptionCategory::ThoughtLevel
8798        );
8799    }
8800
8801    #[test]
8802    fn test_session_config_option_category_unknown_variants() {
8803        // Test that unknown strings are captured in Other variant
8804        let unknown: SessionConfigOptionCategory =
8805            serde_json::from_str("\"some_future_category\"").unwrap();
8806        assert_eq!(
8807            unknown,
8808            SessionConfigOptionCategory::Other("some_future_category".to_string())
8809        );
8810
8811        // Test round-trip of unknown category
8812        let json = serde_json::to_value(&unknown).unwrap();
8813        assert_eq!(json, json!("some_future_category"));
8814    }
8815
8816    #[cfg(not(feature = "unstable_speed_config_category"))]
8817    #[test]
8818    fn test_session_config_option_speed_is_unknown_without_feature() {
8819        let unknown: SessionConfigOptionCategory = serde_json::from_str("\"speed\"").unwrap();
8820        assert_eq!(
8821            unknown,
8822            SessionConfigOptionCategory::Other("speed".to_string())
8823        );
8824    }
8825
8826    #[test]
8827    fn test_session_config_option_category_custom_categories() {
8828        // Category names beginning with `_` are free for custom use
8829        let custom: SessionConfigOptionCategory =
8830            serde_json::from_str("\"_my_custom_category\"").unwrap();
8831        assert_eq!(
8832            custom,
8833            SessionConfigOptionCategory::Other("_my_custom_category".to_string())
8834        );
8835
8836        // Test round-trip preserves the custom category name
8837        let json = serde_json::to_value(&custom).unwrap();
8838        assert_eq!(json, json!("_my_custom_category"));
8839
8840        // Deserialize back and verify
8841        let deserialized: SessionConfigOptionCategory = serde_json::from_value(json).unwrap();
8842        assert_eq!(
8843            deserialized,
8844            SessionConfigOptionCategory::Other("_my_custom_category".to_string()),
8845        );
8846    }
8847
8848    fn test_config_option() -> SessionConfigOption {
8849        SessionConfigOption::select(
8850            "mode",
8851            "Mode",
8852            "ask",
8853            vec![SessionConfigSelectOption::new("ask", "Ask")],
8854        )
8855    }
8856
8857    #[test]
8858    fn test_session_response_initial_state_default_empty_and_skip_serializing() {
8859        assert_eq!(
8860            serde_json::to_value(NewSessionResponse::new("sess")).unwrap(),
8861            json!({ "sessionId": "sess" })
8862        );
8863        assert_eq!(
8864            serde_json::to_value(ResumeSessionResponse::new()).unwrap(),
8865            json!({})
8866        );
8867        #[cfg(feature = "unstable_session_fork")]
8868        assert_eq!(
8869            serde_json::to_value(ForkSessionResponse::new("fork")).unwrap(),
8870            json!({ "sessionId": "fork" })
8871        );
8872
8873        let json = serde_json::to_value(
8874            NewSessionResponse::new("sess").config_options(vec![test_config_option()]),
8875        )
8876        .unwrap();
8877        assert_eq!(json["configOptions"].as_array().unwrap().len(), 1);
8878    }
8879
8880    #[test]
8881    fn test_session_response_config_options_deserialize_missing_null_and_invalid() {
8882        let missing: NewSessionResponse =
8883            serde_json::from_value(json!({ "sessionId": "sess" })).unwrap();
8884        assert_eq!(missing.config_options, []);
8885
8886        let null: NewSessionResponse = serde_json::from_value(json!({
8887            "sessionId": "sess",
8888            "configOptions": null
8889        }))
8890        .unwrap();
8891        assert_eq!(null.config_options, []);
8892
8893        let wrong_shape: NewSessionResponse = serde_json::from_value(json!({
8894            "sessionId": "sess",
8895            "configOptions": "oops"
8896        }))
8897        .unwrap();
8898        assert_eq!(wrong_shape.config_options, []);
8899
8900        let valid_option = serde_json::to_value(test_config_option()).unwrap();
8901        let mixed: NewSessionResponse = serde_json::from_value(json!({
8902            "sessionId": "sess",
8903            "configOptions": ["oops", valid_option]
8904        }))
8905        .unwrap();
8906        assert_eq!(mixed.config_options.len(), 1);
8907
8908        let resume: ResumeSessionResponse = serde_json::from_value(json!({})).unwrap();
8909        assert_eq!(resume.config_options, []);
8910        #[cfg(feature = "unstable_session_fork")]
8911        {
8912            let fork: ForkSessionResponse =
8913                serde_json::from_value(json!({ "sessionId": "fork" })).unwrap();
8914            assert_eq!(fork.config_options, []);
8915        }
8916    }
8917
8918    #[test]
8919    fn test_session_response_available_commands_roundtrip_with_config_options() {
8920        use super::super::{AvailableCommandInput, Command, TextCommandInput};
8921
8922        let commands = vec![
8923            AvailableCommand::Command(
8924                Command::new("web", "Search the web")
8925                    .input(AvailableCommandInput::Text(TextCommandInput::new("Query"))),
8926            ),
8927            AvailableCommand::Command(Command::new("test", "Run project tests")),
8928        ];
8929        let mut expected = json!({
8930            "sessionId": "sess",
8931            "configOptions": [test_config_option()],
8932            "availableCommands": [
8933                {
8934                    "type": "command",
8935                    "name": "web",
8936                    "description": "Search the web",
8937                    "input": { "type": "text", "hint": "Query" }
8938                },
8939                { "type": "command", "name": "test", "description": "Run project tests" }
8940            ]
8941        });
8942
8943        let new = NewSessionResponse::new("sess")
8944            .config_options(vec![test_config_option()])
8945            .available_commands(commands.clone());
8946        assert_eq!(serde_json::to_value(&new).unwrap(), expected);
8947        assert_eq!(
8948            serde_json::from_value::<NewSessionResponse>(expected.clone()).unwrap(),
8949            new
8950        );
8951
8952        expected.as_object_mut().unwrap().remove("sessionId");
8953        let resume = ResumeSessionResponse::new()
8954            .config_options(vec![test_config_option()])
8955            .available_commands(commands.clone());
8956        assert_eq!(serde_json::to_value(&resume).unwrap(), expected);
8957        assert_eq!(
8958            serde_json::from_value::<ResumeSessionResponse>(expected.clone()).unwrap(),
8959            resume
8960        );
8961
8962        #[cfg(feature = "unstable_session_fork")]
8963        {
8964            expected["sessionId"] = json!("fork");
8965            let fork = ForkSessionResponse::new("fork")
8966                .config_options(vec![test_config_option()])
8967                .available_commands(commands);
8968            assert_eq!(serde_json::to_value(&fork).unwrap(), expected);
8969            assert_eq!(
8970                serde_json::from_value::<ForkSessionResponse>(expected).unwrap(),
8971                fork
8972            );
8973        }
8974    }
8975
8976    #[test]
8977    fn test_session_response_available_commands_deserialize_missing_null_and_invalid() {
8978        let command =
8979            AvailableCommand::Command(super::super::Command::new("test", "Run project tests"));
8980        let config_options = vec![test_config_option()];
8981
8982        for (commands, expected) in [
8983            (None, vec![]),
8984            (Some(json!(null)), vec![]),
8985            (Some(json!([])), vec![]),
8986            (Some(json!("oops")), vec![]),
8987            (Some(json!({})), vec![]),
8988            (Some(json!([null, {}, { "name": "invalid" }])), vec![]),
8989            (
8990                Some(json!([{ "name": "test", "description": "Run project tests" }])),
8991                vec![],
8992            ),
8993            (
8994                Some(json!([null, command, { "name": "invalid" }])),
8995                vec![command.clone()],
8996            ),
8997        ] {
8998            let mut value = json!({
8999                "sessionId": "sess",
9000                "configOptions": config_options
9001            });
9002            if let Some(commands) = commands {
9003                value["availableCommands"] = commands;
9004            }
9005
9006            let new: NewSessionResponse = serde_json::from_value(value.clone()).unwrap();
9007            assert_eq!(new.available_commands, expected);
9008            assert_eq!(new.config_options, config_options);
9009
9010            #[cfg(feature = "unstable_session_fork")]
9011            {
9012                let fork: ForkSessionResponse = serde_json::from_value(value.clone()).unwrap();
9013                assert_eq!(fork.available_commands, expected);
9014                assert_eq!(fork.config_options, config_options);
9015            }
9016
9017            value.as_object_mut().unwrap().remove("sessionId");
9018            let resume: ResumeSessionResponse = serde_json::from_value(value).unwrap();
9019            assert_eq!(resume.available_commands, expected);
9020            assert_eq!(resume.config_options, config_options);
9021        }
9022
9023        let resume: ResumeSessionResponse = serde_json::from_value(json!(null)).unwrap();
9024        assert_eq!(resume.available_commands, []);
9025    }
9026
9027    #[test]
9028    fn test_resume_session_replay_from_serialization() {
9029        assert_eq!(
9030            serde_json::to_value(ResumeSessionRequest::new(
9031                "sess_abc123",
9032                "/home/user/project"
9033            ))
9034            .unwrap(),
9035            json!({
9036                "sessionId": "sess_abc123",
9037                "cwd": "/home/user/project"
9038            })
9039        );
9040        assert_eq!(
9041            serde_json::to_value(
9042                ResumeSessionRequest::new("sess_abc123", "/home/user/project")
9043                    .replay_from(ReplayFrom::from(ReplayFromStart::new()))
9044            )
9045            .unwrap(),
9046            json!({
9047                "sessionId": "sess_abc123",
9048                "cwd": "/home/user/project",
9049                "replayFrom": {
9050                    "type": "start"
9051                }
9052            })
9053        );
9054
9055        let replay: ResumeSessionRequest = serde_json::from_value(json!({
9056            "sessionId": "sess_abc123",
9057            "cwd": "/home/user/project",
9058            "replayFrom": {
9059                "type": "start"
9060            }
9061        }))
9062        .unwrap();
9063        assert!(matches!(replay.replay_from, Some(ReplayFrom::Start(_))));
9064
9065        let none: ResumeSessionRequest = serde_json::from_value(json!({
9066            "sessionId": "sess_abc123",
9067            "cwd": "/home/user/project",
9068            "replayFrom": null
9069        }))
9070        .unwrap();
9071        assert!(none.replay_from.is_none());
9072    }
9073
9074    #[test]
9075    fn test_auth_method_agent_serialization() {
9076        let method = AuthMethod::Agent(AuthMethodAgent::new("default-auth", "Default Auth"));
9077
9078        let json = serde_json::to_value(&method).unwrap();
9079        assert_eq!(
9080            json,
9081            json!({
9082                "methodId": "default-auth",
9083                "name": "Default Auth",
9084                "type": "agent"
9085            })
9086        );
9087        // description should be omitted when None
9088        assert!(!json.as_object().unwrap().contains_key("description"));
9089
9090        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9091        match deserialized {
9092            AuthMethod::Agent(AuthMethodAgent {
9093                method_id, name, ..
9094            }) => {
9095                assert_eq!(method_id.0.as_ref(), "default-auth");
9096                assert_eq!(name, "Default Auth");
9097            }
9098            _ => panic!("Expected Agent variant"),
9099        }
9100    }
9101
9102    #[test]
9103    fn test_auth_method_agent_deserialization() {
9104        let json = json!({
9105            "methodId": "agent-auth",
9106            "name": "Agent Auth",
9107            "type": "agent"
9108        });
9109
9110        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9111        assert!(matches!(deserialized, AuthMethod::Agent(_)));
9112    }
9113
9114    #[test]
9115    fn test_auth_method_agent_requires_type() {
9116        assert!(
9117            serde_json::from_value::<AuthMethod>(json!({
9118                "methodId": "agent-auth",
9119                "name": "Agent Auth"
9120            }))
9121            .is_err()
9122        );
9123    }
9124
9125    #[test]
9126    fn test_auth_method_agent_rejects_null_type() {
9127        assert!(
9128            serde_json::from_value::<AuthMethod>(json!({
9129                "methodId": "agent-auth",
9130                "name": "Agent Auth",
9131                "type": null
9132            }))
9133            .is_err()
9134        );
9135    }
9136
9137    #[test]
9138    fn test_auth_method_unknown_does_not_hide_malformed_agent() {
9139        assert!(
9140            serde_json::from_value::<AuthMethod>(json!({
9141                "methodId": "agent-auth",
9142                "type": "agent"
9143            }))
9144            .is_err()
9145        );
9146        assert!(
9147            serde_json::from_value::<AuthMethod>(json!({
9148                "methodId": "api-key",
9149                "type": "env_var",
9150                "vars": [{"name": "API_KEY"}]
9151            }))
9152            .is_err()
9153        );
9154    }
9155
9156    #[test]
9157    fn test_auth_method_unknown_variant_roundtrip() {
9158        let method: AuthMethod = serde_json::from_value(json!({
9159            "methodId": "oauth",
9160            "name": "OAuth",
9161            "type": "_oauth",
9162            "authorizationUrl": "https://example.com/auth"
9163        }))
9164        .unwrap();
9165
9166        assert_eq!(method.method_id().0.as_ref(), "oauth");
9167        assert_eq!(method.name(), "OAuth");
9168        let AuthMethod::Other(unknown) = method else {
9169            panic!("expected unknown auth method");
9170        };
9171        assert_eq!(unknown.type_, "_oauth");
9172        assert_eq!(
9173            unknown.fields.get("authorizationUrl"),
9174            Some(&json!("https://example.com/auth"))
9175        );
9176
9177        assert_eq!(
9178            serde_json::to_value(AuthMethod::Other(unknown)).unwrap(),
9179            json!({
9180                "methodId": "oauth",
9181                "name": "OAuth",
9182                "type": "_oauth",
9183                "authorizationUrl": "https://example.com/auth"
9184            })
9185        );
9186    }
9187
9188    #[test]
9189    fn test_auth_method_unknown_does_not_hide_malformed_known_variant() {
9190        assert!(
9191            serde_json::from_value::<AuthMethod>(json!({
9192                "methodId": "terminal-auth",
9193                "type": "terminal"
9194            }))
9195            .is_err()
9196        );
9197    }
9198
9199    #[test]
9200    fn test_tool_call_and_terminal_cancel_serialization() {
9201        assert_eq!(AGENT_METHOD_NAMES.tool_call_cancel, "tool_call/cancel");
9202        assert_eq!(AGENT_METHOD_NAMES.terminal_cancel, "terminal/cancel");
9203        assert_eq!(
9204            ClientRequest::CancelToolCallRequest(Box::new(CancelToolCallRequest::new(
9205                "sess_abc123",
9206                "call_012"
9207            )))
9208            .method(),
9209            "tool_call/cancel"
9210        );
9211        assert_eq!(
9212            ClientRequest::CancelTerminalRequest(Box::new(CancelTerminalRequest::new(
9213                "sess_abc123",
9214                "term_003"
9215            )))
9216            .method(),
9217            "terminal/cancel"
9218        );
9219        assert_eq!(
9220            serde_json::to_value(CancelToolCallRequest::new("sess_abc123", "call_012")).unwrap(),
9221            json!({"sessionId": "sess_abc123", "toolCallId": "call_012"})
9222        );
9223        assert_eq!(
9224            serde_json::to_value(CancelTerminalRequest::new("sess_abc123", "term_003")).unwrap(),
9225            json!({"sessionId": "sess_abc123", "terminalId": "term_003"})
9226        );
9227        assert!(
9228            serde_json::from_value::<CancelToolCallRequest>(json!({"sessionId": "sess_abc123"}))
9229                .is_err()
9230        );
9231        assert_eq!(
9232            serde_json::to_value(CancelTerminalResponse::new()).unwrap(),
9233            json!({})
9234        );
9235    }
9236
9237    #[test]
9238    fn test_session_delete_serialization() {
9239        assert_eq!(AGENT_METHOD_NAMES.session_delete, "session/delete");
9240        assert_eq!(
9241            ClientRequest::DeleteSessionRequest(Box::new(DeleteSessionRequest::new("sess_abc123")))
9242                .method(),
9243            "session/delete"
9244        );
9245        assert_eq!(
9246            serde_json::to_value(DeleteSessionRequest::new("sess_abc123")).unwrap(),
9247            json!({
9248                "sessionId": "sess_abc123"
9249            })
9250        );
9251        assert_eq!(
9252            serde_json::to_value(DeleteSessionResponse::new()).unwrap(),
9253            json!({})
9254        );
9255        assert_eq!(
9256            serde_json::to_value(
9257                SessionCapabilities::new().delete(SessionDeleteCapabilities::new())
9258            )
9259            .unwrap(),
9260            json!({
9261                "delete": {}
9262            })
9263        );
9264    }
9265    #[cfg(feature = "unstable_session_set_title")]
9266    #[test]
9267    fn test_session_set_title_serialization() {
9268        assert_eq!(AGENT_METHOD_NAMES.session_set_title, "session/set_title");
9269        assert_eq!(
9270            ClientRequest::SetSessionTitleRequest(Box::new(SetSessionTitleRequest::new(
9271                "sess_abc123",
9272                "Investigate OAuth timeout"
9273            )))
9274            .method(),
9275            "session/set_title"
9276        );
9277        assert_eq!(
9278            serde_json::to_value(SetSessionTitleRequest::new(
9279                "sess_abc123",
9280                "Investigate OAuth timeout"
9281            ))
9282            .unwrap(),
9283            json!({
9284                "sessionId": "sess_abc123",
9285                "title": "Investigate OAuth timeout"
9286            })
9287        );
9288        assert_eq!(
9289            serde_json::to_value(SetSessionTitleResponse::new("Investigate OAuth timeout"))
9290                .unwrap(),
9291            json!({
9292                "title": "Investigate OAuth timeout"
9293            })
9294        );
9295        assert_eq!(
9296            serde_json::to_value(SessionCapabilities::new().title(SessionTitleCapabilities::new()))
9297                .unwrap(),
9298            json!({
9299                "title": {}
9300            })
9301        );
9302    }
9303
9304    #[cfg(feature = "unstable_session_set_title")]
9305    #[test]
9306    fn test_session_set_title_requires_title() {
9307        for params in [
9308            json!({"sessionId": "sess_abc123"}),
9309            json!({"sessionId": "sess_abc123", "title": null}),
9310            json!({"sessionId": "sess_abc123", "title": 42}),
9311        ] {
9312            assert!(serde_json::from_value::<SetSessionTitleRequest>(params).is_err());
9313        }
9314        for result in [json!({}), json!({"title": null})] {
9315            assert!(serde_json::from_value::<SetSessionTitleResponse>(result).is_err());
9316        }
9317    }
9318
9319    #[cfg(feature = "unstable_session_options")]
9320    #[test]
9321    fn test_session_options_serialization() {
9322        assert_eq!(AGENT_METHOD_NAMES.session_options, "session/options");
9323        assert_eq!(
9324            ClientRequest::SessionOptionsRequest(Box::new(SessionOptionsRequest::new(
9325                "/home/user/project"
9326            )))
9327            .method(),
9328            "session/options"
9329        );
9330        assert_eq!(
9331            serde_json::to_value(
9332                SessionOptionsRequest::new("/home/user/project")
9333                    .session_id(SessionId::new("sess_abc123"))
9334            )
9335            .unwrap(),
9336            json!({"cwd": "/home/user/project", "sessionId": "sess_abc123"})
9337        );
9338        assert_eq!(
9339            serde_json::from_value::<SessionOptionsRequest>(
9340                json!({"cwd": "/home/user/project", "additionalDirectories": null, "sessionId": null})
9341            )
9342            .unwrap(),
9343            SessionOptionsRequest::new("/home/user/project")
9344        );
9345        let request = NewSessionRequest::new("/home/user/project").config_options(vec![
9346            InitialSessionConfigOption::new("model", SessionConfigOptionValue::id("model-2")),
9347            InitialSessionConfigOption::new("fast", SessionConfigOptionValue::boolean(true)),
9348        ]);
9349        let value = serde_json::to_value(&request).unwrap();
9350        assert_eq!(
9351            value["configOptions"],
9352            json!([
9353                {"configId": "model", "type": "id", "value": "model-2"},
9354                {"configId": "fast", "type": "boolean", "value": true}
9355            ])
9356        );
9357        assert_eq!(
9358            serde_json::from_value::<NewSessionRequest>(value).unwrap(),
9359            request
9360        );
9361        assert!(
9362            serde_json::from_value::<NewSessionRequest>(json!({
9363                "cwd": "/home/user/project",
9364                "mcpServers": [],
9365                "configOptions": [{"type": "boolean", "value": true}]
9366            }))
9367            .is_err()
9368        );
9369        assert_eq!(
9370            serde_json::to_value(SessionOptionsResponse::new()).unwrap(),
9371            json!({})
9372        );
9373        #[cfg(feature = "unstable_session_fork")]
9374        {
9375            let fork =
9376                ForkSessionRequest::new("sess_abc123", "/home/user/project").config_options(vec![
9377                    InitialSessionConfigOption::new(
9378                        "model",
9379                        SessionConfigOptionValue::id("model-2"),
9380                    ),
9381                ]);
9382            let value = serde_json::to_value(&fork).unwrap();
9383            assert_eq!(
9384                value["configOptions"],
9385                json!([{"configId": "model", "type": "id", "value": "model-2"}])
9386            );
9387            assert_eq!(
9388                serde_json::from_value::<ForkSessionRequest>(value).unwrap(),
9389                fork
9390            );
9391            // `null` is an empty list, and a malformed entry fails the request.
9392            assert_eq!(
9393                serde_json::from_value::<ForkSessionRequest>(json!({
9394                    "sessionId": "sess_abc123",
9395                    "cwd": "/home/user/project",
9396                    "configOptions": null
9397                }))
9398                .unwrap(),
9399                ForkSessionRequest::new("sess_abc123", "/home/user/project")
9400            );
9401            assert!(
9402                serde_json::from_value::<ForkSessionRequest>(json!({
9403                    "sessionId": "sess_abc123",
9404                    "cwd": "/home/user/project",
9405                    "configOptions": [{"type": "boolean", "value": true}]
9406                }))
9407                .is_err()
9408            );
9409        }
9410        assert_eq!(
9411            serde_json::to_value(
9412                SessionCapabilities::new().options(SessionOptionsCapabilities::new())
9413            )
9414            .unwrap(),
9415            json!({"options": {}})
9416        );
9417    }
9418
9419    #[cfg(feature = "unstable_session_status")]
9420    #[test]
9421    fn test_session_status_serialization() {
9422        assert_eq!(AGENT_METHOD_NAMES.session_status, "session/status");
9423        assert_eq!(
9424            ClientRequest::SessionStatusRequest(Box::new(SessionStatusRequest::new("sess_abc123")))
9425                .method(),
9426            "session/status"
9427        );
9428        assert_eq!(
9429            serde_json::to_value(SessionStatusRequest::new("sess_abc123")).unwrap(),
9430            json!({"sessionId": "sess_abc123"})
9431        );
9432        assert_eq!(
9433            serde_json::to_value(SessionStatusResponse::new(SessionStatus::Saved)).unwrap(),
9434            json!({"status": "saved"})
9435        );
9436        assert_eq!(
9437            serde_json::to_value(
9438                SessionCapabilities::new().status(SessionStatusCapabilities::new())
9439            )
9440            .unwrap(),
9441            json!({"status": {}})
9442        );
9443        assert_eq!(
9444            serde_json::to_value(SessionStatusResponse::new(SessionStatus::Open).state(
9445                StateUpdate::RequiresAction(crate::v2::RequiresActionStateUpdate::new())
9446            ))
9447            .unwrap(),
9448            json!({
9449                "status": "open",
9450                "state": {"state": "requires_action"}
9451            })
9452        );
9453        for state in [json!(null), json!("running"), json!({"state": 7})] {
9454            let response = serde_json::from_value::<SessionStatusResponse>(
9455                json!({"status": "open", "state": state}),
9456            )
9457            .unwrap();
9458            assert_eq!(response.state, None);
9459        }
9460    }
9461
9462    #[cfg(feature = "unstable_session_status")]
9463    #[test]
9464    fn test_session_status_is_strict_and_open() {
9465        let custom =
9466            serde_json::from_value::<SessionStatusResponse>(json!({"status": "_suspended"}))
9467                .unwrap();
9468        assert_eq!(
9469            custom.status,
9470            SessionStatus::Other("_suspended".to_string())
9471        );
9472        assert_eq!(
9473            serde_json::to_value(&custom).unwrap(),
9474            json!({"status": "_suspended"})
9475        );
9476        for result in [json!({}), json!({"status": null}), json!({"status": 1})] {
9477            assert!(serde_json::from_value::<SessionStatusResponse>(result).is_err());
9478        }
9479        for params in [json!({}), json!({"sessionId": null})] {
9480            assert!(serde_json::from_value::<SessionStatusRequest>(params).is_err());
9481        }
9482    }
9483
9484    #[cfg(feature = "unstable_session_archive")]
9485    #[test]
9486    fn test_session_archive_serialization() {
9487        assert_eq!(AGENT_METHOD_NAMES.session_archive, "session/archive");
9488        assert_eq!(AGENT_METHOD_NAMES.session_unarchive, "session/unarchive");
9489        assert_eq!(
9490            ClientRequest::ArchiveSessionRequest(Box::new(ArchiveSessionRequest::new(
9491                "sess_abc123"
9492            )))
9493            .method(),
9494            "session/archive"
9495        );
9496        assert_eq!(
9497            ClientRequest::UnarchiveSessionRequest(Box::new(UnarchiveSessionRequest::new(
9498                "sess_abc123"
9499            )))
9500            .method(),
9501            "session/unarchive"
9502        );
9503        assert_eq!(
9504            serde_json::to_value(ArchiveSessionRequest::new("sess_abc123")).unwrap(),
9505            json!({"sessionId": "sess_abc123"})
9506        );
9507        assert_eq!(
9508            serde_json::to_value(UnarchiveSessionResponse::new()).unwrap(),
9509            json!({})
9510        );
9511        assert_eq!(
9512            serde_json::to_value(
9513                SessionCapabilities::new().archive(SessionArchiveCapabilities::new())
9514            )
9515            .unwrap(),
9516            json!({"archive": {}})
9517        );
9518        assert_eq!(
9519            serde_json::to_value(
9520                ListSessionsRequest::new()
9521                    .cwd("/home/user/project")
9522                    .archived(SessionArchiveFilter::Only)
9523            )
9524            .unwrap(),
9525            json!({"cwd": "/home/user/project", "archived": "only"})
9526        );
9527        assert_eq!(
9528            serde_json::to_value(
9529                SessionInfo::new("sess_abc123", "/home/user/project").archived(true)
9530            )
9531            .unwrap(),
9532            json!({"sessionId": "sess_abc123", "cwd": "/home/user/project", "archived": true})
9533        );
9534    }
9535
9536    #[cfg(feature = "unstable_session_archive")]
9537    #[test]
9538    fn test_session_archive_filter_is_strict_and_open() {
9539        for (value, expected) in [
9540            (json!(null), None),
9541            (json!("include"), Some(SessionArchiveFilter::Include)),
9542            (
9543                json!("_recent"),
9544                Some(SessionArchiveFilter::Other("_recent".to_string())),
9545            ),
9546        ] {
9547            let request =
9548                serde_json::from_value::<ListSessionsRequest>(json!({"archived": value})).unwrap();
9549            assert_eq!(request.archived, expected);
9550        }
9551        for value in [json!(true), json!(1), json!({})] {
9552            assert!(
9553                serde_json::from_value::<ListSessionsRequest>(json!({"archived": value})).is_err()
9554            );
9555        }
9556        let info = serde_json::from_value::<SessionInfo>(
9557            json!({"sessionId": "sess_abc123", "cwd": "/home/user/project", "archived": "yes"}),
9558        )
9559        .unwrap();
9560        assert_eq!(info.archived, None);
9561    }
9562
9563    #[test]
9564    fn test_session_additional_directories_serialization() {
9565        assert_eq!(
9566            serde_json::to_value(NewSessionRequest::new("/home/user/project")).unwrap(),
9567            json!({
9568                "cwd": "/home/user/project",
9569            })
9570        );
9571        assert_eq!(
9572            serde_json::to_value(
9573                NewSessionRequest::new("/home/user/project").additional_directories(vec![
9574                    PathBuf::from("/home/user/shared-lib"),
9575                    PathBuf::from("/home/user/product-docs"),
9576                ])
9577            )
9578            .unwrap(),
9579            json!({
9580                "cwd": "/home/user/project",
9581                "additionalDirectories": [
9582                    "/home/user/shared-lib",
9583                    "/home/user/product-docs"
9584                ],
9585            })
9586        );
9587        assert_eq!(
9588            serde_json::to_value(ResumeSessionRequest::new(
9589                "sess_abc123",
9590                "/home/user/project"
9591            ))
9592            .unwrap(),
9593            json!({
9594                "sessionId": "sess_abc123",
9595                "cwd": "/home/user/project",
9596            })
9597        );
9598        assert_eq!(
9599            serde_json::from_value::<ResumeSessionRequest>(json!({
9600                "sessionId": "sess_abc123",
9601                "cwd": "/home/user/project"
9602            }))
9603            .unwrap()
9604            .mcp_servers,
9605            Vec::<McpServer>::new()
9606        );
9607        assert_eq!(
9608            serde_json::from_value::<ResumeSessionRequest>(json!({
9609                "sessionId": "sess_abc123",
9610                "cwd": "/home/user/project",
9611                "mcpServers": null
9612            }))
9613            .unwrap()
9614            .mcp_servers,
9615            Vec::<McpServer>::new()
9616        );
9617        assert_eq!(
9618            serde_json::to_value(SessionInfo::new("sess_abc123", "/home/user/project")).unwrap(),
9619            json!({
9620                "sessionId": "sess_abc123",
9621                "cwd": "/home/user/project"
9622            })
9623        );
9624        assert_eq!(
9625            serde_json::to_value(
9626                SessionInfo::new("sess_abc123", "/home/user/project").additional_directories(vec![
9627                    PathBuf::from("/home/user/shared-lib"),
9628                    PathBuf::from("/home/user/product-docs"),
9629                ])
9630            )
9631            .unwrap(),
9632            json!({
9633                "sessionId": "sess_abc123",
9634                "cwd": "/home/user/project",
9635                "additionalDirectories": [
9636                    "/home/user/shared-lib",
9637                    "/home/user/product-docs"
9638                ]
9639            })
9640        );
9641        assert_eq!(
9642            serde_json::from_value::<SessionInfo>(json!({
9643                "sessionId": "sess_abc123",
9644                "cwd": "/home/user/project"
9645            }))
9646            .unwrap()
9647            .additional_directories,
9648            Vec::<AbsolutePath>::new()
9649        );
9650    }
9651    #[test]
9652    fn test_session_additional_directories_capabilities_serialization() {
9653        assert_eq!(
9654            serde_json::to_value(
9655                SessionCapabilities::new()
9656                    .additional_directories(SessionAdditionalDirectoriesCapabilities::new())
9657            )
9658            .unwrap(),
9659            json!({
9660                "additionalDirectories": {}
9661            })
9662        );
9663    }
9664
9665    #[test]
9666    fn test_session_system_prompt_capabilities_serialization() {
9667        assert_eq!(
9668            serde_json::to_value(
9669                SessionCapabilities::new().system_prompt(SessionSystemPromptCapabilities::new())
9670            )
9671            .unwrap(),
9672            json!({ "systemPrompt": {} })
9673        );
9674        assert_eq!(
9675            serde_json::to_value(
9676                SessionCapabilities::new().system_prompt(
9677                    SessionSystemPromptCapabilities::new().mode(
9678                        SessionSystemPromptModeCapabilities::new()
9679                            .override_(SessionSystemPromptOverrideCapabilities::new())
9680                    )
9681                )
9682            )
9683            .unwrap(),
9684            json!({ "systemPrompt": { "mode": { "override": {} } } })
9685        );
9686        assert_eq!(
9687            serde_json::from_value::<SessionCapabilities>(
9688                json!({ "systemPrompt": { "mode": { "override": {} } } })
9689            )
9690            .unwrap()
9691            .system_prompt
9692            .and_then(|capabilities| capabilities.mode)
9693            .and_then(|mode| mode.override_),
9694            Some(SessionSystemPromptOverrideCapabilities::new())
9695        );
9696
9697        // Capabilities fall back to "not advertised" when malformed.
9698        assert_eq!(
9699            serde_json::from_value::<SessionCapabilities>(json!({ "systemPrompt": "yes" }))
9700                .unwrap()
9701                .system_prompt,
9702            None
9703        );
9704        assert_eq!(
9705            serde_json::from_value::<SessionCapabilities>(
9706                json!({ "systemPrompt": { "mode": { "override": true } } })
9707            )
9708            .unwrap()
9709            .system_prompt,
9710            Some(
9711                SessionSystemPromptCapabilities::new()
9712                    .mode(SessionSystemPromptModeCapabilities::new())
9713            )
9714        );
9715        assert_eq!(
9716            serde_json::from_value::<SessionCapabilities>(
9717                json!({ "systemPrompt": { "mode": "override" } })
9718            )
9719            .unwrap()
9720            .system_prompt,
9721            Some(SessionSystemPromptCapabilities::new())
9722        );
9723    }
9724
9725    #[test]
9726    fn test_system_prompt_lifecycle_request_serialization() {
9727        let system_prompt = SystemPrompt::new(vec![ContentBlock::from(
9728            "You are a code review specialist.",
9729        )]);
9730        let system_prompt_json = json!({
9731            "mode": "append",
9732            "content": [{ "type": "text", "text": "You are a code review specialist." }]
9733        });
9734
9735        let request =
9736            NewSessionRequest::new("/home/user/project").system_prompt(system_prompt.clone());
9737        let request_json = json!({
9738            "cwd": "/home/user/project",
9739            "systemPrompt": system_prompt_json
9740        });
9741        assert_eq!(serde_json::to_value(&request).unwrap(), request_json);
9742        assert_eq!(
9743            serde_json::from_value::<NewSessionRequest>(request_json).unwrap(),
9744            request
9745        );
9746
9747        assert_eq!(
9748            serde_json::to_value(
9749                ResumeSessionRequest::new("sess_abc123", "/home/user/project")
9750                    .system_prompt(system_prompt.clone())
9751            )
9752            .unwrap()["systemPrompt"],
9753            system_prompt_json
9754        );
9755        #[cfg(feature = "unstable_session_fork")]
9756        assert_eq!(
9757            serde_json::to_value(
9758                ForkSessionRequest::new("sess_abc123", "/home/user/project")
9759                    .system_prompt(system_prompt.clone())
9760            )
9761            .unwrap()["systemPrompt"],
9762            system_prompt_json
9763        );
9764
9765        let override_prompt =
9766            SystemPrompt::new(vec![ContentBlock::from("...")]).mode(SystemPromptMode::Override);
9767        let override_json = json!({
9768            "mode": "override",
9769            "content": [{ "type": "text", "text": "..." }]
9770        });
9771        assert_eq!(
9772            serde_json::to_value(&override_prompt).unwrap(),
9773            override_json
9774        );
9775        assert_eq!(
9776            serde_json::from_value::<SystemPrompt>(override_json).unwrap(),
9777            override_prompt
9778        );
9779    }
9780
9781    /// `SystemPrompt::new` defaults to `append` in Rust, but `mode` is required on
9782    /// the wire, so it is always serialized.
9783    #[test]
9784    fn test_system_prompt_new_defaults_to_append() {
9785        let system_prompt = SystemPrompt::new(vec![ContentBlock::from("...")]);
9786        assert_eq!(system_prompt.mode, SystemPromptMode::Append);
9787        assert_eq!(
9788            serde_json::to_value(&system_prompt).unwrap(),
9789            json!({ "mode": "append", "content": [{ "type": "text", "text": "..." }] })
9790        );
9791    }
9792
9793    /// Unknown modes follow the enum variant extension rule: they parse as
9794    /// `SystemPromptMode::Other` so they are not dropped, and an Agent that does
9795    /// not support them must reject the request.
9796    #[test]
9797    fn test_system_prompt_preserves_unknown_modes() {
9798        for mode in ["_vendor_mode", "prepend"] {
9799            let system_prompt_json =
9800                json!({ "mode": mode, "content": [{ "type": "text", "text": "..." }] });
9801            let system_prompt: SystemPrompt =
9802                serde_json::from_value(system_prompt_json.clone()).unwrap();
9803            assert_eq!(
9804                system_prompt.mode,
9805                SystemPromptMode::Other(mode.to_string())
9806            );
9807            assert_eq!(
9808                serde_json::to_value(&system_prompt).unwrap(),
9809                system_prompt_json
9810            );
9811        }
9812    }
9813
9814    /// The receiver acts on `systemPrompt`, so malformed values fail the request
9815    /// (`-32602`) instead of creating a session without the prompt, and `null`
9816    /// is equivalent to omitting the field.
9817    fn assert_system_prompt_is_strict<T>(base: &serde_json::Value)
9818    where
9819        T: serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
9820    {
9821        let name = std::any::type_name::<T>();
9822        let with = |system_prompt: serde_json::Value| {
9823            let mut request = base.clone();
9824            request["systemPrompt"] = system_prompt;
9825            serde_json::from_value::<T>(request)
9826        };
9827
9828        for system_prompt in [
9829            json!("You are a code review specialist."),
9830            json!({ "content": [{ "type": "text", "text": "..." }] }),
9831            json!({ "mode": null, "content": [{ "type": "text", "text": "..." }] }),
9832            json!({ "mode": 1, "content": [{ "type": "text", "text": "..." }] }),
9833            json!({ "mode": "append" }),
9834            json!({ "mode": "append", "content": "..." }),
9835            json!({ "mode": "append", "content": [{ "type": "text" }] }),
9836        ] {
9837            assert!(
9838                with(system_prompt.clone()).is_err(),
9839                "{name}.systemPrompt: {system_prompt}"
9840            );
9841        }
9842
9843        assert_eq!(
9844            with(serde_json::Value::Null).unwrap(),
9845            serde_json::from_value::<T>(base.clone()).unwrap(),
9846            "{name}.systemPrompt"
9847        );
9848    }
9849
9850    #[test]
9851    fn test_session_setup_requests_reject_malformed_system_prompts() {
9852        assert!(
9853            serde_json::to_value(NewSessionRequest::new("/repo"))
9854                .unwrap()
9855                .get("systemPrompt")
9856                .is_none()
9857        );
9858        assert_system_prompt_is_strict::<NewSessionRequest>(&json!({ "cwd": "/repo" }));
9859        assert_system_prompt_is_strict::<ResumeSessionRequest>(&json!({
9860            "sessionId": "sess-1",
9861            "cwd": "/repo"
9862        }));
9863        #[cfg(feature = "unstable_session_fork")]
9864        assert_system_prompt_is_strict::<ForkSessionRequest>(&json!({
9865            "sessionId": "sess-1",
9866            "cwd": "/repo"
9867        }));
9868    }
9869
9870    /// Unknown content block types parse as `ContentBlock::Other` so they are not
9871    /// dropped. An Agent that does not support them must reject the request.
9872    #[test]
9873    fn test_system_prompt_preserves_unknown_content_blocks() {
9874        let request: NewSessionRequest = serde_json::from_value(json!({
9875            "cwd": "/home/user/project",
9876            "systemPrompt": {
9877                "mode": "append",
9878                "content": [{ "type": "_vendor_video", "uri": "https://example.com/intro.mp4" }]
9879            }
9880        }))
9881        .unwrap();
9882        let content = request.system_prompt.unwrap().content;
9883        assert_eq!(content.len(), 1);
9884        assert!(matches!(content[0], ContentBlock::Other(_)));
9885    }
9886
9887    #[test]
9888    fn test_auth_method_terminal_serialization() {
9889        let method = AuthMethod::Terminal(AuthMethodTerminal::new("tui-auth", "Terminal Auth"));
9890
9891        let json = serde_json::to_value(&method).unwrap();
9892        assert_eq!(
9893            json,
9894            json!({
9895                "methodId": "tui-auth",
9896                "name": "Terminal Auth",
9897                "type": "terminal"
9898            })
9899        );
9900        // args and env should be omitted when empty
9901        assert!(!json.as_object().unwrap().contains_key("args"));
9902        assert!(!json.as_object().unwrap().contains_key("env"));
9903
9904        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9905        match deserialized {
9906            AuthMethod::Terminal(AuthMethodTerminal { args, env, .. }) => {
9907                assert_eq!(args, Vec::<String>::new());
9908                assert_eq!(env, []);
9909            }
9910            _ => panic!("Expected Terminal variant"),
9911        }
9912    }
9913
9914    #[test]
9915    fn test_auth_method_terminal_with_args_and_env_serialization() {
9916        let method = AuthMethod::Terminal(
9917            AuthMethodTerminal::new("tui-auth", "Terminal Auth")
9918                .args(vec!["--interactive".to_string(), "--color".to_string()])
9919                .env(vec![EnvVariable::new("TERM", "xterm-256color")]),
9920        );
9921
9922        let json = serde_json::to_value(&method).unwrap();
9923        assert_eq!(
9924            json,
9925            json!({
9926                "methodId": "tui-auth",
9927                "name": "Terminal Auth",
9928                "type": "terminal",
9929                "args": ["--interactive", "--color"],
9930                "env": [
9931                    {
9932                        "name": "TERM",
9933                        "value": "xterm-256color"
9934                    }
9935                ]
9936            })
9937        );
9938
9939        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9940        match deserialized {
9941            AuthMethod::Terminal(AuthMethodTerminal { args, env, .. }) => {
9942                assert_eq!(args, vec!["--interactive", "--color"]);
9943                assert_eq!(env.len(), 1);
9944                assert_eq!(env[0].name, "TERM");
9945                assert_eq!(env[0].value, "xterm-256color");
9946            }
9947            _ => panic!("Expected Terminal variant"),
9948        }
9949    }
9950
9951    #[test]
9952    fn test_session_config_option_id_serialize() {
9953        let val = SessionConfigOptionValue::id("model-1");
9954        let json = serde_json::to_value(&val).unwrap();
9955        assert_eq!(json, json!({ "type": "id", "value": "model-1" }));
9956    }
9957
9958    #[test]
9959    fn test_session_config_option_value_boolean_serialize() {
9960        let val = SessionConfigOptionValue::boolean(true);
9961        let json = serde_json::to_value(&val).unwrap();
9962        assert_eq!(json, json!({ "type": "boolean", "value": true }));
9963    }
9964
9965    #[test]
9966    fn test_session_config_option_value_deserialize_id() {
9967        let json = json!({ "type": "id", "value": "model-1" });
9968        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9969        assert_eq!(val, SessionConfigOptionValue::id("model-1"));
9970        assert_eq!(val.as_id().unwrap().to_string(), "model-1");
9971    }
9972
9973    #[test]
9974    fn test_session_config_option_value_deserialize_requires_type() {
9975        let json = json!({ "value": "model-1" });
9976        let result = serde_json::from_value::<SessionConfigOptionValue>(json);
9977        assert!(result.is_err());
9978    }
9979
9980    #[test]
9981    fn test_session_config_option_value_deserialize_boolean() {
9982        let json = json!({ "type": "boolean", "value": true });
9983        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9984        assert_eq!(val, SessionConfigOptionValue::boolean(true));
9985        assert_eq!(val.as_bool(), Some(true));
9986    }
9987
9988    #[test]
9989    fn test_session_config_option_value_deserialize_boolean_false() {
9990        let json = json!({ "type": "boolean", "value": false });
9991        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9992        assert_eq!(val, SessionConfigOptionValue::boolean(false));
9993        assert_eq!(val.as_bool(), Some(false));
9994    }
9995
9996    #[test]
9997    fn test_session_config_option_value_deserialize_unknown_type_with_string_value() {
9998        let json = json!({
9999            "type": "text",
10000            "value": "freeform input",
10001            "maxLength": 200
10002        });
10003        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10004        let SessionConfigOptionValue::Other(unknown) = val else {
10005            panic!("Expected Other variant");
10006        };
10007        assert_eq!(unknown.type_, "text");
10008        assert_eq!(unknown.value, json!("freeform input"));
10009        assert_eq!(unknown.fields["maxLength"], json!(200));
10010    }
10011
10012    #[test]
10013    fn test_session_config_option_value_deserialize_unknown_type_with_object_value() {
10014        let json = json!({
10015            "type": "range",
10016            "value": { "min": 1, "max": 5 }
10017        });
10018        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10019        let SessionConfigOptionValue::Other(unknown) = val else {
10020            panic!("Expected Other variant");
10021        };
10022        assert_eq!(unknown.type_, "range");
10023        assert_eq!(unknown.value, json!({ "min": 1, "max": 5 }));
10024    }
10025
10026    #[test]
10027    fn test_session_config_option_value_roundtrip_id() {
10028        let original = SessionConfigOptionValue::id("option-a");
10029        let json = serde_json::to_value(&original).unwrap();
10030        let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10031        assert_eq!(original, roundtripped);
10032    }
10033
10034    #[test]
10035    fn test_session_config_option_value_roundtrip_boolean() {
10036        let original = SessionConfigOptionValue::boolean(false);
10037        let json = serde_json::to_value(&original).unwrap();
10038        let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10039        assert_eq!(original, roundtripped);
10040    }
10041
10042    #[test]
10043    fn test_session_config_option_value_roundtrip_other() {
10044        let mut fields = IndexMap::new();
10045        fields.insert("maxLength".to_string(), json!(200));
10046        let original = SessionConfigOptionValue::from(OtherSessionConfigOptionValue::new(
10047            "text",
10048            json!("freeform input"),
10049            fields,
10050        ));
10051        let json = serde_json::to_value(&original).unwrap();
10052        assert_eq!(
10053            json,
10054            json!({"type": "text", "value": "freeform input", "maxLength": 200})
10055        );
10056        let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10057        assert_eq!(original, roundtripped);
10058    }
10059
10060    #[test]
10061    fn test_session_config_option_value_type_mismatch_boolean_with_string() {
10062        let json = json!({ "type": "boolean", "value": "not a bool" });
10063        let result = serde_json::from_value::<SessionConfigOptionValue>(json);
10064        assert!(result.is_err());
10065    }
10066
10067    #[test]
10068    fn test_session_config_option_value_from_impls() {
10069        let from_str: SessionConfigOptionValue = "model-1".into();
10070        assert_eq!(from_str.as_id().unwrap().to_string(), "model-1");
10071
10072        let from_id: SessionConfigOptionValue = SessionConfigValueId::new("model-2").into();
10073        assert_eq!(from_id.as_id().unwrap().to_string(), "model-2");
10074
10075        let from_bool: SessionConfigOptionValue = true.into();
10076        assert_eq!(from_bool.as_bool(), Some(true));
10077    }
10078
10079    #[test]
10080    fn test_set_session_config_option_request_id() {
10081        let req = SetSessionConfigOptionRequest::new("sess_1", "model", "model-1");
10082        let json = serde_json::to_value(&req).unwrap();
10083        assert_eq!(
10084            json,
10085            json!({
10086                "sessionId": "sess_1",
10087                "configId": "model",
10088                "type": "id",
10089                "value": "model-1"
10090            })
10091        );
10092    }
10093
10094    #[test]
10095    fn test_set_session_config_option_request_boolean() {
10096        let req = SetSessionConfigOptionRequest::new("sess_1", "brave_mode", true);
10097        let json = serde_json::to_value(&req).unwrap();
10098        assert_eq!(
10099            json,
10100            json!({
10101                "sessionId": "sess_1",
10102                "configId": "brave_mode",
10103                "type": "boolean",
10104                "value": true
10105            })
10106        );
10107    }
10108
10109    #[test]
10110    fn test_set_session_config_option_request_deserialize_requires_type() {
10111        let json = json!({
10112            "sessionId": "sess_1",
10113            "configId": "model",
10114            "value": "model-1"
10115        });
10116        let result = serde_json::from_value::<SetSessionConfigOptionRequest>(json);
10117        assert!(result.is_err());
10118    }
10119
10120    #[test]
10121    fn test_set_session_config_option_request_deserialize_boolean() {
10122        let json = json!({
10123            "sessionId": "sess_1",
10124            "configId": "brave_mode",
10125            "type": "boolean",
10126            "value": true
10127        });
10128        let req: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
10129        assert_eq!(req.value.as_bool(), Some(true));
10130    }
10131
10132    #[test]
10133    fn test_set_session_config_option_request_roundtrip_id() {
10134        let original = SetSessionConfigOptionRequest::new("s", "c", "v");
10135        let json = serde_json::to_value(&original).unwrap();
10136        let roundtripped: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
10137        assert_eq!(original, roundtripped);
10138    }
10139
10140    #[test]
10141    fn test_set_session_config_option_request_roundtrip_boolean() {
10142        let original = SetSessionConfigOptionRequest::new("s", "c", false);
10143        let json = serde_json::to_value(&original).unwrap();
10144        let roundtripped: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
10145        assert_eq!(original, roundtripped);
10146    }
10147
10148    #[test]
10149    fn test_session_config_boolean_serialization() {
10150        let cfg = SessionConfigBoolean::new(true);
10151        let json = serde_json::to_value(&cfg).unwrap();
10152        assert_eq!(json, json!({ "currentValue": true }));
10153
10154        let deserialized: SessionConfigBoolean = serde_json::from_value(json).unwrap();
10155        assert!(deserialized.current_value);
10156    }
10157
10158    #[test]
10159    fn test_session_config_option_boolean_variant() {
10160        let opt = SessionConfigOption::boolean("brave_mode", "Brave Mode", false)
10161            .description("Skip confirmation prompts")
10162            .meta(test_meta());
10163        assert_eq!(serialized_meta_key_count(&opt), 1);
10164
10165        let json = serde_json::to_value(&opt).unwrap();
10166        assert_eq!(
10167            json,
10168            json!({
10169                "configId": "brave_mode",
10170                "name": "Brave Mode",
10171                "description": "Skip confirmation prompts",
10172                "type": "boolean",
10173                "currentValue": false,
10174                "_meta": {
10175                    "source": "test"
10176                }
10177            })
10178        );
10179
10180        let deserialized: SessionConfigOption = serde_json::from_value(json).unwrap();
10181        assert_eq!(deserialized.config_id.to_string(), "brave_mode");
10182        assert_eq!(deserialized.name, "Brave Mode");
10183        match deserialized.kind {
10184            SessionConfigKind::Boolean(ref b) => assert!(!b.current_value),
10185            _ => panic!("Expected Boolean kind"),
10186        }
10187    }
10188
10189    #[test]
10190    fn test_session_config_option_select_still_works() {
10191        // Make sure existing select options are unaffected
10192        let opt = SessionConfigOption::select(
10193            "model",
10194            "Model",
10195            "model-1",
10196            vec![
10197                SessionConfigSelectOption::new("model-1", "Model 1"),
10198                SessionConfigSelectOption::new("model-2", "Model 2"),
10199            ],
10200        )
10201        .meta(test_meta());
10202        assert_eq!(serialized_meta_key_count(&opt), 1);
10203
10204        let json = serde_json::to_value(&opt).unwrap();
10205        assert_eq!(json["type"], "select");
10206        assert_eq!(json["currentValue"], "model-1");
10207        assert_eq!(json["options"].as_array().unwrap().len(), 2);
10208        assert_eq!(json["_meta"]["source"], "test");
10209
10210        let deserialized: SessionConfigOption = serde_json::from_value(json).unwrap();
10211        match deserialized.kind {
10212            SessionConfigKind::Select(ref s) => {
10213                assert_eq!(s.current_value.to_string(), "model-1");
10214            }
10215            _ => panic!("Expected Select kind"),
10216        }
10217    }
10218
10219    #[test]
10220    fn test_session_config_option_unknown_kind_roundtrip() {
10221        let option: SessionConfigOption = serde_json::from_value(json!({
10222            "configId": "verbosity",
10223            "name": "Verbosity",
10224            "type": "_slider",
10225            "currentValue": 3,
10226            "min": 0,
10227            "max": 5,
10228            "_meta": {
10229                "source": "test"
10230            }
10231        }))
10232        .unwrap();
10233
10234        assert_eq!(option.config_id.to_string(), "verbosity");
10235        assert_eq!(option.meta.as_ref().unwrap()["source"], "test");
10236        let SessionConfigKind::Other(unknown) = &option.kind else {
10237            panic!("expected unknown config kind");
10238        };
10239        assert_eq!(unknown.type_, "_slider");
10240        assert_eq!(unknown.fields.get("currentValue"), Some(&json!(3)));
10241        assert!(!unknown.fields.contains_key("_meta"));
10242        assert_eq!(serialized_meta_key_count(&option), 1);
10243
10244        let json = serde_json::to_value(&option).unwrap();
10245        assert_eq!(json["type"], "_slider");
10246        assert_eq!(json["currentValue"], 3);
10247        assert_eq!(json["min"], 0);
10248        assert_eq!(json["max"], 5);
10249        assert_eq!(json["_meta"]["source"], "test");
10250    }
10251
10252    #[test]
10253    fn test_session_config_option_unknown_kind_does_not_duplicate_flattened_meta() {
10254        let mut fields = IndexMap::new();
10255        fields.insert("currentValue".to_string(), json!(3));
10256        fields.insert("_meta".to_string(), json!({ "inner": "ignored" }));
10257
10258        let option = SessionConfigOption::new(
10259            "verbosity",
10260            "Verbosity",
10261            SessionConfigKind::Other(OtherSessionConfigKind::new("_slider", fields)),
10262        )
10263        .meta(test_meta());
10264
10265        let SessionConfigKind::Other(unknown) = &option.kind else {
10266            panic!("expected unknown config kind");
10267        };
10268        assert!(!unknown.fields.contains_key("_meta"));
10269        assert_eq!(serialized_meta_key_count(&option), 1);
10270
10271        let json = serde_json::to_value(&option).unwrap();
10272        assert_eq!(json["type"], "_slider");
10273        assert_eq!(json["currentValue"], 3);
10274        assert_eq!(json["_meta"]["source"], "test");
10275    }
10276
10277    #[test]
10278    fn test_session_config_option_unknown_does_not_hide_malformed_known_kind() {
10279        assert!(
10280            serde_json::from_value::<SessionConfigOption>(json!({
10281                "configId": "model",
10282                "name": "Model",
10283                "type": "select"
10284            }))
10285            .is_err()
10286        );
10287    }
10288
10289    #[cfg(feature = "unstable_llm_providers")]
10290    #[test]
10291    fn test_llm_protocol_known_variants() {
10292        assert_eq!(
10293            serde_json::to_value(&LlmProtocol::Anthropic).unwrap(),
10294            json!("anthropic")
10295        );
10296        assert_eq!(
10297            serde_json::to_value(&LlmProtocol::OpenAi).unwrap(),
10298            json!("openai")
10299        );
10300        assert_eq!(
10301            serde_json::to_value(&LlmProtocol::Azure).unwrap(),
10302            json!("azure")
10303        );
10304        assert_eq!(
10305            serde_json::to_value(&LlmProtocol::Vertex).unwrap(),
10306            json!("vertex")
10307        );
10308        assert_eq!(
10309            serde_json::to_value(&LlmProtocol::Bedrock).unwrap(),
10310            json!("bedrock")
10311        );
10312
10313        assert_eq!(
10314            serde_json::from_str::<LlmProtocol>("\"anthropic\"").unwrap(),
10315            LlmProtocol::Anthropic
10316        );
10317        assert_eq!(
10318            serde_json::from_str::<LlmProtocol>("\"openai\"").unwrap(),
10319            LlmProtocol::OpenAi
10320        );
10321        assert_eq!(
10322            serde_json::from_str::<LlmProtocol>("\"azure\"").unwrap(),
10323            LlmProtocol::Azure
10324        );
10325        assert_eq!(
10326            serde_json::from_str::<LlmProtocol>("\"vertex\"").unwrap(),
10327            LlmProtocol::Vertex
10328        );
10329        assert_eq!(
10330            serde_json::from_str::<LlmProtocol>("\"bedrock\"").unwrap(),
10331            LlmProtocol::Bedrock
10332        );
10333    }
10334
10335    #[cfg(feature = "unstable_llm_providers")]
10336    #[test]
10337    fn test_llm_protocol_unknown_variant() {
10338        let unknown: LlmProtocol = serde_json::from_str("\"cohere\"").unwrap();
10339        assert_eq!(unknown, LlmProtocol::Other("cohere".to_string()));
10340
10341        let json = serde_json::to_value(&unknown).unwrap();
10342        assert_eq!(json, json!("cohere"));
10343    }
10344
10345    #[cfg(feature = "unstable_llm_providers")]
10346    #[test]
10347    fn test_provider_current_config_serialization() {
10348        let config =
10349            ProviderCurrentConfig::new(LlmProtocol::Anthropic, "https://api.anthropic.com");
10350
10351        let json = serde_json::to_value(&config).unwrap();
10352        assert_eq!(
10353            json,
10354            json!({
10355                "apiType": "anthropic",
10356                "baseUrl": "https://api.anthropic.com"
10357            })
10358        );
10359
10360        let deserialized: ProviderCurrentConfig = serde_json::from_value(json).unwrap();
10361        assert_eq!(deserialized.api_type, LlmProtocol::Anthropic);
10362        assert_eq!(deserialized.base_url, "https://api.anthropic.com");
10363    }
10364
10365    #[cfg(feature = "unstable_llm_providers")]
10366    #[test]
10367    fn test_provider_info_with_current_config() {
10368        let info = ProviderInfo::new(
10369            "main",
10370            vec![LlmProtocol::Anthropic, LlmProtocol::OpenAi],
10371            true,
10372            Some(ProviderCurrentConfig::new(
10373                LlmProtocol::Anthropic,
10374                "https://api.anthropic.com",
10375            )),
10376        );
10377
10378        let json = serde_json::to_value(&info).unwrap();
10379        assert_eq!(
10380            json,
10381            json!({
10382                "providerId": "main",
10383                "supported": ["anthropic", "openai"],
10384                "required": true,
10385                "current": {
10386                    "apiType": "anthropic",
10387                    "baseUrl": "https://api.anthropic.com"
10388                }
10389            })
10390        );
10391
10392        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10393        assert_eq!(deserialized.provider_id.to_string(), "main");
10394        assert_eq!(deserialized.supported.len(), 2);
10395        assert!(deserialized.required);
10396        assert!(deserialized.current.is_some());
10397        assert_eq!(
10398            deserialized.current.as_ref().unwrap().api_type,
10399            LlmProtocol::Anthropic
10400        );
10401    }
10402
10403    #[cfg(feature = "unstable_llm_providers")]
10404    #[test]
10405    fn test_provider_info_disabled() {
10406        let info = ProviderInfo::new(
10407            "secondary",
10408            vec![LlmProtocol::OpenAi],
10409            false,
10410            None::<ProviderCurrentConfig>,
10411        );
10412
10413        let json = serde_json::to_value(&info).unwrap();
10414        assert_eq!(
10415            json,
10416            json!({
10417                "providerId": "secondary",
10418                "supported": ["openai"],
10419                "required": false
10420            })
10421        );
10422
10423        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10424        assert_eq!(deserialized.provider_id.to_string(), "secondary");
10425        assert!(!deserialized.required);
10426        assert!(deserialized.current.is_none());
10427    }
10428
10429    #[cfg(feature = "unstable_llm_providers")]
10430    #[test]
10431    fn test_provider_info_missing_current_defaults_to_none() {
10432        // current is optional; omitting it should decode as None
10433        let json = json!({
10434            "providerId": "main",
10435            "supported": ["anthropic"],
10436            "required": true
10437        });
10438        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10439        assert!(deserialized.current.is_none());
10440    }
10441
10442    #[cfg(feature = "unstable_llm_providers")]
10443    #[test]
10444    fn test_provider_info_explicit_null_current_decodes_to_none() {
10445        // current: null and an omitted current are equivalent on the wire;
10446        // both must deserialize into None so the disabled state is preserved
10447        // regardless of which form the peer chose to send.
10448        let json = json!({
10449            "providerId": "main",
10450            "supported": ["anthropic"],
10451            "required": true,
10452            "current": null
10453        });
10454        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10455        assert!(deserialized.current.is_none());
10456    }
10457
10458    #[cfg(feature = "unstable_llm_providers")]
10459    #[test]
10460    fn test_list_providers_response_serialization() {
10461        let response = ListProvidersResponse::new(vec![ProviderInfo::new(
10462            "main",
10463            vec![LlmProtocol::Anthropic],
10464            true,
10465            Some(ProviderCurrentConfig::new(
10466                LlmProtocol::Anthropic,
10467                "https://api.anthropic.com",
10468            )),
10469        )]);
10470
10471        let json = serde_json::to_value(&response).unwrap();
10472        assert_eq!(json["providers"].as_array().unwrap().len(), 1);
10473        assert_eq!(json["providers"][0]["providerId"], "main");
10474
10475        let deserialized: ListProvidersResponse = serde_json::from_value(json).unwrap();
10476        assert_eq!(deserialized.providers.len(), 1);
10477    }
10478
10479    #[cfg(feature = "unstable_llm_providers")]
10480    #[test]
10481    fn test_set_provider_request_serialization() {
10482        let mut headers = IndexMap::new();
10483        headers.insert("Authorization".to_string(), "Bearer sk-test".to_string());
10484
10485        let request =
10486            SetProviderRequest::new("main", LlmProtocol::OpenAi, "https://api.openai.com/v1")
10487                .headers(headers);
10488
10489        let json = serde_json::to_value(&request).unwrap();
10490        assert_eq!(
10491            json,
10492            json!({
10493                "providerId": "main",
10494                "apiType": "openai",
10495                "baseUrl": "https://api.openai.com/v1",
10496                "headers": {
10497                    "Authorization": "Bearer sk-test"
10498                }
10499            })
10500        );
10501
10502        let deserialized: SetProviderRequest = serde_json::from_value(json).unwrap();
10503        assert_eq!(deserialized.provider_id.to_string(), "main");
10504        assert_eq!(deserialized.api_type, LlmProtocol::OpenAi);
10505        assert_eq!(deserialized.base_url, "https://api.openai.com/v1");
10506        assert_eq!(deserialized.headers.len(), 1);
10507        assert_eq!(
10508            deserialized.headers.get("Authorization").unwrap(),
10509            "Bearer sk-test"
10510        );
10511    }
10512
10513    #[cfg(feature = "unstable_llm_providers")]
10514    #[test]
10515    fn test_set_provider_request_omits_empty_headers() {
10516        let request =
10517            SetProviderRequest::new("main", LlmProtocol::Anthropic, "https://api.anthropic.com");
10518
10519        let json = serde_json::to_value(&request).unwrap();
10520        // headers should be omitted when empty
10521        assert!(!json.as_object().unwrap().contains_key("headers"));
10522    }
10523
10524    #[cfg(feature = "unstable_llm_providers")]
10525    #[test]
10526    fn test_disable_provider_request_serialization() {
10527        let request = DisableProviderRequest::new("secondary");
10528
10529        let json = serde_json::to_value(&request).unwrap();
10530        assert_eq!(json, json!({ "providerId": "secondary" }));
10531
10532        let deserialized: DisableProviderRequest = serde_json::from_value(json).unwrap();
10533        assert_eq!(deserialized.provider_id.to_string(), "secondary");
10534    }
10535
10536    #[cfg(feature = "unstable_llm_providers")]
10537    #[test]
10538    fn test_providers_capabilities_serialization() {
10539        let caps = ProvidersCapabilities::new();
10540
10541        let json = serde_json::to_value(&caps).unwrap();
10542        assert_eq!(json, json!({}));
10543
10544        let deserialized: ProvidersCapabilities = serde_json::from_value(json).unwrap();
10545        assert!(deserialized.meta.is_none());
10546    }
10547
10548    #[cfg(feature = "unstable_llm_providers")]
10549    #[test]
10550    fn test_agent_capabilities_with_providers() {
10551        let caps = AgentCapabilities::new().providers(ProvidersCapabilities::new());
10552
10553        let json = serde_json::to_value(&caps).unwrap();
10554        assert_eq!(json["providers"], json!({}));
10555
10556        let deserialized: AgentCapabilities = serde_json::from_value(json).unwrap();
10557        assert!(deserialized.providers.is_some());
10558    }
10559
10560    #[test]
10561    fn test_agent_capabilities_session_is_explicit() {
10562        let json = serde_json::to_value(AgentCapabilities::new()).unwrap();
10563        assert!(json.get("session").is_none());
10564
10565        let caps = AgentCapabilities::new().session(
10566            SessionCapabilities::new()
10567                .prompt(PromptCapabilities::new().image(PromptImageCapabilities::new()))
10568                .mcp(McpCapabilities::new().stdio(McpStdioCapabilities::new())),
10569        );
10570
10571        assert_eq!(
10572            serde_json::to_value(&caps).unwrap(),
10573            json!({
10574                "session": {
10575                    "prompt": {
10576                        "image": {}
10577                    },
10578                    "mcp": {
10579                        "stdio": {}
10580                    }
10581                }
10582            })
10583        );
10584
10585        let deserialized: AgentCapabilities = serde_json::from_value(json!({
10586            "session": false
10587        }))
10588        .unwrap();
10589        assert!(deserialized.session.is_none());
10590    }
10591
10592    #[test]
10593    fn test_prompt_capabilities_serialize_supported_content_as_objects() {
10594        let caps = PromptCapabilities::new()
10595            .image(PromptImageCapabilities::new())
10596            .audio(PromptAudioCapabilities::new())
10597            .embedded_context(PromptEmbeddedContextCapabilities::new());
10598
10599        assert_eq!(
10600            serde_json::to_value(&caps).unwrap(),
10601            json!({
10602                "image": {},
10603                "audio": {},
10604                "embeddedContext": {}
10605            })
10606        );
10607
10608        let deserialized: PromptCapabilities = serde_json::from_value(json!({
10609            "image": null,
10610            "audio": false,
10611            "embeddedContext": {}
10612        }))
10613        .unwrap();
10614        assert!(deserialized.image.is_none());
10615        assert!(deserialized.audio.is_none());
10616        assert!(deserialized.embedded_context.is_some());
10617    }
10618
10619    #[cfg(feature = "unstable_agent_skills")]
10620    #[test]
10621    fn prompt_skill_capability_has_two_levels() {
10622        // `{}` allows one leading skill block. `inline` allows them anywhere.
10623        let leading = PromptCapabilities::new().skill(PromptSkillCapabilities::new());
10624        assert_eq!(
10625            serde_json::to_value(&leading).unwrap(),
10626            json!({ "skill": {} })
10627        );
10628
10629        let inline = PromptCapabilities::new()
10630            .skill(PromptSkillCapabilities::new().inline(PromptSkillInlineCapabilities::new()));
10631        let wire = json!({ "skill": { "inline": {} } });
10632        assert_eq!(serde_json::to_value(&inline).unwrap(), wire);
10633        assert_eq!(
10634            serde_json::from_value::<PromptCapabilities>(wire).unwrap(),
10635            inline
10636        );
10637
10638        for unsupported in [
10639            json!({}),
10640            json!({ "skill": null }),
10641            json!({ "skill": false }),
10642            json!({ "skill": true }),
10643        ] {
10644            let caps: PromptCapabilities = serde_json::from_value(unsupported).unwrap();
10645            assert!(caps.skill.is_none());
10646        }
10647
10648        // A malformed `inline` does not withdraw the first level.
10649        for leading_only in [
10650            json!({ "skill": { "inline": null } }),
10651            json!({ "skill": { "inline": true } }),
10652        ] {
10653            assert_eq!(
10654                serde_json::from_value::<PromptCapabilities>(leading_only).unwrap(),
10655                leading
10656            );
10657        }
10658    }
10659
10660    #[test]
10661    fn test_mcp_capabilities_serialize_supported_transports_as_objects() {
10662        let caps = McpCapabilities::new()
10663            .stdio(McpStdioCapabilities::new())
10664            .http(McpHttpCapabilities::new());
10665
10666        assert_eq!(
10667            serde_json::to_value(&caps).unwrap(),
10668            json!({
10669                "stdio": {},
10670                "http": {}
10671            })
10672        );
10673
10674        let deserialized: McpCapabilities = serde_json::from_value(json!({
10675            "stdio": null,
10676            "http": false
10677        }))
10678        .unwrap();
10679        assert!(deserialized.stdio.is_none());
10680        assert!(deserialized.http.is_none());
10681    }
10682
10683    #[cfg(feature = "unstable_mcp_over_acp")]
10684    #[test]
10685    fn test_mcp_capabilities_serialize_acp_support_as_object() {
10686        let caps = McpCapabilities::new().acp(McpAcpCapabilities::new());
10687
10688        assert_eq!(
10689            serde_json::to_value(&caps).unwrap(),
10690            json!({
10691                "acp": {}
10692            })
10693        );
10694    }
10695
10696    #[test]
10697    fn prompt_request_rejects_malformed_content_block() {
10698        use serde_json::json;
10699
10700        assert!(
10701            serde_json::from_value::<PromptRequest>(json!({
10702                "sessionId": "sess-1",
10703                "prompt": [{"type": "text"}]
10704            }))
10705            .is_err()
10706        );
10707    }
10708
10709    #[test]
10710    fn prompt_request_rejects_non_array_prompt() {
10711        use serde_json::json;
10712
10713        assert!(
10714            serde_json::from_value::<PromptRequest>(json!({
10715                "sessionId": "sess-1",
10716                "prompt": "hello"
10717            }))
10718            .is_err()
10719        );
10720    }
10721
10722    fn prompt_request_with_idempotency_key(key: &serde_json::Value) -> serde_json::Value {
10723        serde_json::json!({
10724            "sessionId": "sess-1",
10725            "idempotencyKey": key,
10726            "prompt": [{"type": "text", "text": "hello"}]
10727        })
10728    }
10729
10730    #[test]
10731    fn prompt_request_idempotency_key_round_trips() {
10732        use serde_json::json;
10733
10734        let key = "0b6f3c1e-8d2a-4c57-9a41-5e2f7d90c3ab";
10735        let value = prompt_request_with_idempotency_key(&json!(key));
10736
10737        let request: PromptRequest = serde_json::from_value(value.clone()).unwrap();
10738        assert_eq!(
10739            request.idempotency_key.as_ref().map(IdempotencyKey::as_str),
10740            Some(key)
10741        );
10742        assert_eq!(serde_json::to_value(&request).unwrap(), value);
10743
10744        let built = PromptRequest::new("sess-1", vec![ContentBlock::from("hello")])
10745            .idempotency_key(IdempotencyKey::new(key).unwrap());
10746        assert_eq!(built, request);
10747    }
10748
10749    #[test]
10750    fn prompt_request_omitted_and_null_idempotency_key_mean_no_key() {
10751        use serde_json::json;
10752
10753        let omitted = json!({
10754            "sessionId": "sess-1",
10755            "prompt": [{"type": "text", "text": "hello"}]
10756        });
10757        let request: PromptRequest = serde_json::from_value(omitted.clone()).unwrap();
10758        assert_eq!(request.idempotency_key, None);
10759        // No key is serialized as an omitted field, not as `null`.
10760        assert_eq!(serde_json::to_value(&request).unwrap(), omitted);
10761
10762        let null: PromptRequest =
10763            serde_json::from_value(prompt_request_with_idempotency_key(&json!(null))).unwrap();
10764        assert_eq!(null, request);
10765    }
10766
10767    #[test]
10768    fn prompt_request_rejects_malformed_idempotency_key() {
10769        use serde_json::json;
10770
10771        let too_long = "k".repeat(IdempotencyKey::MAX_LENGTH + 1);
10772        for (name, key) in [
10773            ("an empty string", json!("")),
10774            ("a string over 255 characters", json!(too_long)),
10775            ("a number", json!(7)),
10776            ("a boolean", json!(true)),
10777            ("an object", json!({"key": "k"})),
10778            ("an array", json!(["k"])),
10779        ] {
10780            assert!(
10781                serde_json::from_value::<PromptRequest>(prompt_request_with_idempotency_key(&key))
10782                    .is_err(),
10783                "{name} must fail the request instead of being treated as no key"
10784            );
10785        }
10786    }
10787
10788    #[test]
10789    fn idempotency_key_length_is_counted_in_characters() {
10790        use serde_json::json;
10791
10792        assert_eq!(IdempotencyKey::new(""), Err(InvalidIdempotencyKey::Empty));
10793        assert_eq!(IdempotencyKey::new("k").unwrap().as_str(), "k");
10794
10795        let longest = "k".repeat(IdempotencyKey::MAX_LENGTH);
10796        assert_eq!(
10797            IdempotencyKey::new(longest.as_str()).unwrap().as_str(),
10798            longest
10799        );
10800        assert_eq!(
10801            IdempotencyKey::new(format!("{longest}k")),
10802            Err(InvalidIdempotencyKey::TooLong)
10803        );
10804
10805        // 255 two-byte characters are 510 bytes and still within the limit.
10806        let multibyte = "é".repeat(IdempotencyKey::MAX_LENGTH);
10807        assert!(IdempotencyKey::new(multibyte.as_str()).is_ok());
10808        assert!(
10809            serde_json::from_value::<PromptRequest>(prompt_request_with_idempotency_key(&json!(
10810                multibyte
10811            )))
10812            .is_ok()
10813        );
10814        assert_eq!(
10815            IdempotencyKey::new(format!("{multibyte}é")),
10816            Err(InvalidIdempotencyKey::TooLong)
10817        );
10818
10819        assert_eq!("k".parse::<IdempotencyKey>().unwrap().to_string(), "k");
10820        assert_eq!(
10821            IdempotencyKey::try_from(String::new()),
10822            Err(InvalidIdempotencyKey::Empty)
10823        );
10824        assert_eq!(
10825            InvalidIdempotencyKey::TooLong.to_string(),
10826            "idempotency key must be at most 255 characters"
10827        );
10828    }
10829
10830    #[cfg(feature = "uuid")]
10831    #[test]
10832    fn generated_idempotency_keys_are_distinct_valid_v4_uuids() {
10833        let first = IdempotencyKey::generate();
10834        let second = IdempotencyKey::generate();
10835        assert_ne!(first, second);
10836
10837        for key in [&first, &second] {
10838            let uuid = uuid::Uuid::parse_str(key.as_str()).unwrap();
10839            assert_eq!(uuid.get_version_num(), 4);
10840            // A generated key passes the same validation as any other key.
10841            assert_eq!(IdempotencyKey::new(key.as_str()).as_ref(), Ok(key));
10842            let request = PromptRequest::new("sess-1", vec![ContentBlock::from("hello")])
10843                .idempotency_key(key.clone());
10844            let value = serde_json::to_value(&request).unwrap();
10845            assert_eq!(value["idempotencyKey"], key.as_str());
10846            assert_eq!(
10847                serde_json::from_value::<PromptRequest>(value).unwrap(),
10848                request
10849            );
10850        }
10851
10852        assert_eq!(
10853            IdempotencyKey::from(uuid::Uuid::nil()).as_str(),
10854            "00000000-0000-0000-0000-000000000000"
10855        );
10856    }
10857
10858    #[cfg(feature = "schemars")]
10859    #[test]
10860    fn idempotency_key_schema_is_a_strict_bounded_string() {
10861        use serde_json::json;
10862
10863        let key = serde_json::to_value(schemars::schema_for!(IdempotencyKey)).unwrap();
10864        assert_eq!(key["type"], "string");
10865        assert_eq!(key["minLength"], 1);
10866        assert_eq!(key["maxLength"], json!(IdempotencyKey::MAX_LENGTH));
10867
10868        let request = serde_json::to_value(schemars::schema_for!(PromptRequest)).unwrap();
10869        assert_eq!(request["required"], json!(["sessionId", "prompt"]));
10870        let property = &request["properties"]["idempotencyKey"];
10871        assert_eq!(
10872            property["anyOf"],
10873            json!([{"$ref": "#/$defs/IdempotencyKey"}, {"type": "null"}])
10874        );
10875        // The Agent acts on the key, so the schema must not mark it as tolerant
10876        // of malformed values.
10877        assert!(property.get("x-deserialize-default-on-error").is_none());
10878    }
10879
10880    fn assert_session_setup_lists_are_strict<T>(base: &serde_json::Value)
10881    where
10882        T: serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
10883    {
10884        let name = std::any::type_name::<T>();
10885        let with = |field: &str, value: serde_json::Value| {
10886            let mut request = base.clone();
10887            request[field] = value;
10888            serde_json::from_value::<T>(request)
10889        };
10890
10891        for (field, value) in [
10892            // Dropping the malformed server would start the session without it.
10893            (
10894                "mcpServers",
10895                json!([
10896                    {"type": "stdio", "name": "github", "command": "/usr/bin/gh-mcp", "env": [{"name": "GITHUB_TOKEN", "value": null}]},
10897                    {"type": "stdio", "name": "fs", "command": "/usr/bin/fs-mcp"}
10898                ]),
10899            ),
10900            ("mcpServers", json!({"type": "stdio", "name": "fs"})),
10901            ("additionalDirectories", json!(["/repo/lib", 42])),
10902            ("additionalDirectories", json!("/repo/lib")),
10903        ] {
10904            assert!(
10905                with(field, value.clone()).is_err(),
10906                "{name}.{field}: {value}"
10907            );
10908        }
10909
10910        let empty = serde_json::from_value::<T>(base.clone()).unwrap();
10911        for field in ["mcpServers", "additionalDirectories"] {
10912            assert_eq!(
10913                with(field, serde_json::Value::Null).unwrap(),
10914                empty,
10915                "{name}.{field}"
10916            );
10917        }
10918    }
10919
10920    #[test]
10921    fn session_setup_requests_reject_malformed_mcp_servers_and_directories() {
10922        assert_session_setup_lists_are_strict::<NewSessionRequest>(&json!({"cwd": "/repo"}));
10923        assert_session_setup_lists_are_strict::<ResumeSessionRequest>(&json!({
10924            "sessionId": "sess-1",
10925            "cwd": "/repo"
10926        }));
10927        #[cfg(feature = "unstable_session_fork")]
10928        assert_session_setup_lists_are_strict::<ForkSessionRequest>(&json!({
10929            "sessionId": "sess-1",
10930            "cwd": "/repo"
10931        }));
10932    }
10933
10934    #[test]
10935    fn resume_session_request_rejects_malformed_replay_from() {
10936        let request = |replay_from: serde_json::Value| {
10937            serde_json::from_value::<ResumeSessionRequest>(json!({
10938                "sessionId": "sess-1",
10939                "cwd": "/repo",
10940                "replayFrom": replay_from
10941            }))
10942        };
10943
10944        // Treating this as omitted would reconnect without the requested replay.
10945        assert!(request(json!("start")).is_err());
10946        assert_eq!(request(serde_json::Value::Null).unwrap().replay_from, None);
10947        assert!(matches!(
10948            request(json!({"type": "start"})).unwrap().replay_from,
10949            Some(ReplayFrom::Start(_))
10950        ));
10951    }
10952
10953    #[test]
10954    fn mcp_server_lists_treat_null_as_empty() {
10955        let servers: Vec<McpServer> = serde_json::from_value(json!([
10956            {"type": "stdio", "name": "fs", "command": "/usr/bin/fs-mcp", "args": null, "env": null},
10957            {"type": "http", "name": "api", "url": "https://example.com/mcp", "headers": null}
10958        ]))
10959        .unwrap();
10960
10961        assert_eq!(
10962            servers,
10963            vec![
10964                McpServer::Stdio(McpServerStdio::new("fs", "/usr/bin/fs-mcp")),
10965                McpServer::Http(McpServerHttp::new("api", "https://example.com/mcp")),
10966            ]
10967        );
10968    }
10969
10970    #[test]
10971    fn terminal_auth_methods_reject_malformed_launch_config() {
10972        // The client spawns a process from `args` and `env`, so a malformed
10973        // method is dropped from `authMethods` instead of launched with
10974        // altered arguments or preserved as an unknown method.
10975        let response: InitializeResponse = serde_json::from_value(json!({
10976            "protocolVersion": 2,
10977            "info": {"name": "agent", "version": "1.0.0"},
10978            "authMethods": [
10979                {"type": "terminal", "methodId": "bad-args", "name": "Log in", "args": ["auth", "--port", 8123]},
10980                {"type": "terminal", "methodId": "bad-env", "name": "Log in", "env": [{"name": "DEBUG", "value": 1}]},
10981                {"type": "terminal", "methodId": "null-config", "name": "Log in", "args": null, "env": null},
10982                {"type": "agent", "methodId": "agent", "name": "Agent login"}
10983            ]
10984        }))
10985        .unwrap();
10986
10987        assert_eq!(
10988            response.auth_methods,
10989            vec![
10990                AuthMethod::Terminal(AuthMethodTerminal::new("null-config", "Log in")),
10991                AuthMethod::Agent(AuthMethodAgent::new("agent", "Agent login")),
10992            ]
10993        );
10994    }
10995
10996    #[cfg(feature = "unstable_auth_status")]
10997    #[test]
10998    fn auth_status_response_round_trips() {
10999        let response = AuthStatusResponse::new(AuthState::Authenticated).accounts(vec![
11000            AuthAccount::new("Anthropic API key")
11001                .description("API key helper".to_string())
11002                .active(true),
11003            AuthAccount::new("Claude Max").email("user@example.com".to_string()),
11004        ]);
11005        let json = serde_json::to_value(&response).unwrap();
11006        assert_eq!(
11007            json,
11008            json!({
11009                "state": "authenticated",
11010                "accounts": [
11011                    {
11012                        "label": "Anthropic API key",
11013                        "description": "API key helper",
11014                        "active": true
11015                    },
11016                    {
11017                        "label": "Claude Max",
11018                        "email": "user@example.com"
11019                    }
11020                ]
11021            })
11022        );
11023        assert_eq!(
11024            serde_json::from_value::<AuthStatusResponse>(json).unwrap(),
11025            response
11026        );
11027        assert_eq!(
11028            serde_json::to_value(AuthStatusResponse::new(AuthState::NotRequired)).unwrap(),
11029            json!({"state": "not_required"})
11030        );
11031    }
11032
11033    #[cfg(feature = "unstable_auth_status")]
11034    #[test]
11035    fn auth_status_state_is_strict_and_accounts_are_lenient() {
11036        assert!(serde_json::from_value::<AuthStatusResponse>(json!({})).is_err());
11037        assert!(serde_json::from_value::<AuthStatusResponse>(json!({"state": null})).is_err());
11038        assert!(serde_json::from_value::<AuthStatusResponse>(json!({"state": 1})).is_err());
11039
11040        let response: AuthStatusResponse = serde_json::from_value(json!({
11041            "state": "_vendor_state",
11042            "accounts": [
11043                {"active": true},
11044                {
11045                    "label": "Vertex AI",
11046                    "description": 42,
11047                    "active": "yes",
11048                    "email": ["not", "a", "string"]
11049                }
11050            ]
11051        }))
11052        .unwrap();
11053        assert_eq!(
11054            response,
11055            AuthStatusResponse::new(AuthState::Other("_vendor_state".to_string()))
11056                .accounts(vec![AuthAccount::new("Vertex AI")])
11057        );
11058        assert_eq!(
11059            serde_json::from_value::<AuthStatusResponse>(
11060                json!({"state": "unknown", "accounts": null})
11061            )
11062            .unwrap(),
11063            AuthStatusResponse::new(AuthState::Unknown)
11064        );
11065    }
11066
11067    #[cfg(feature = "unstable_auth_status")]
11068    #[test]
11069    fn auth_status_update_notification_routes() {
11070        use crate::v2::{AgentNotification, CLIENT_METHOD_NAMES};
11071
11072        assert_eq!(AGENT_METHOD_NAMES.auth_status, "auth/status");
11073        assert_eq!(CLIENT_METHOD_NAMES.auth_status_update, "auth/status_update");
11074        let notification = AgentNotification::AuthStatusUpdateNotification(Box::new(
11075            AuthStatusUpdateNotification::new(AuthState::Unauthenticated),
11076        ));
11077        assert_eq!(notification.method(), "auth/status_update");
11078        assert_eq!(
11079            serde_json::to_value(&notification).unwrap(),
11080            json!({"state": "unauthenticated"})
11081        );
11082    }
11083
11084    #[cfg(all(
11085        feature = "unstable_session_fork",
11086        feature = "unstable_session_cursors"
11087    ))]
11088    #[test]
11089    fn fork_session_request_cursor_id_is_optional_and_strict() {
11090        let request = ForkSessionRequest::new("sess_abc123", "/home/user/project")
11091            .cursor_id(CursorId::new("cur_1"));
11092        let wire = json!({
11093            "sessionId": "sess_abc123",
11094            "cursorId": "cur_1",
11095            "cwd": "/home/user/project"
11096        });
11097        assert_eq!(serde_json::to_value(&request).unwrap(), wire);
11098        assert_eq!(
11099            serde_json::from_value::<ForkSessionRequest>(wire).unwrap(),
11100            request
11101        );
11102
11103        // Omitted and `null` both fork the whole session.
11104        for wire in [
11105            json!({ "sessionId": "sess_abc123", "cwd": "/home/user/project" }),
11106            json!({ "sessionId": "sess_abc123", "cwd": "/home/user/project", "cursorId": null }),
11107        ] {
11108            assert_eq!(
11109                serde_json::from_value::<ForkSessionRequest>(wire)
11110                    .unwrap()
11111                    .cursor_id,
11112                None
11113            );
11114        }
11115
11116        // A malformed cursor ID fails the request. It never forks the whole session.
11117        assert!(
11118            serde_json::from_value::<ForkSessionRequest>(json!({
11119                "sessionId": "sess_abc123",
11120                "cwd": "/home/user/project",
11121                "cursorId": 7
11122            }))
11123            .is_err()
11124        );
11125    }
11126}