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    /// Intended for programmatic or logical use, but can be used as a display
202    /// name fallback if title isn't present.
203    pub name: String,
204    /// Intended for UI and end-user contexts and optimized to be human-readable
205    /// and easily understood.
206    ///
207    /// If not provided, the name SHOULD be used for display.
208    ///
209    /// Omitted and `null` are equivalent and mean the `name` is used for display.
210    #[serde_as(deserialize_as = "DefaultOnError")]
211    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
212    #[serde(default)]
213    pub title: Option<String>,
214    /// Version of the implementation. Can be displayed to the user or used
215    /// for debugging or metrics purposes. (e.g. "1.0.0").
216    pub version: String,
217    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
218    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
219    /// Implementations MUST NOT assign meaning to keys they do not recognize.
220    ///
221    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
222    #[serde_as(deserialize_as = "DefaultOnError")]
223    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
224    #[serde(default)]
225    #[serde(rename = "_meta")]
226    pub meta: Option<Meta>,
227}
228
229impl Implementation {
230    /// Builds [`Implementation`] with the required fields set. Optional fields start unset or empty.
231    #[must_use]
232    pub fn new(name: impl Into<String>, version: impl Into<String>) -> Self {
233        Self {
234            name: name.into(),
235            title: None,
236            version: version.into(),
237            meta: None,
238        }
239    }
240
241    /// Intended for UI and end-user contexts and optimized to be human-readable
242    /// and easily understood.
243    ///
244    /// If not provided, the name SHOULD be used for display.
245    #[must_use]
246    pub fn title(mut self, title: impl IntoOption<String>) -> Self {
247        self.title = title.into_option();
248        self
249    }
250
251    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
252    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
253    /// do not recognize.
254    ///
255    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
256    #[must_use]
257    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
258        self.meta = meta.into_option();
259        self
260    }
261}
262
263// Authentication
264
265/// Request parameters for the `auth/login` method.
266///
267/// Specifies which authentication method to use.
268///
269/// Agents MUST support this method when their `initialize` response included
270/// a non-empty `authMethods` list. Clients MUST NOT call this method
271/// when `authMethods` was omitted or empty.
272#[serde_as]
273#[skip_serializing_none]
274#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
275#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
276#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGIN_METHOD_NAME)))]
277#[serde(rename_all = "camelCase")]
278#[non_exhaustive]
279pub struct LoginAuthRequest {
280    /// The ID of the authentication method to use.
281    /// Must be one of the methods advertised in the initialize response.
282    pub method_id: AuthMethodId,
283    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
284    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
285    /// Implementations MUST NOT assign meaning to keys they do not recognize.
286    ///
287    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
288    #[serde_as(deserialize_as = "DefaultOnError")]
289    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
290    #[serde(default)]
291    #[serde(rename = "_meta")]
292    pub meta: Option<Meta>,
293}
294
295impl LoginAuthRequest {
296    /// Builds [`LoginAuthRequest`] with the required request fields set. Optional fields start unset or empty.
297    #[must_use]
298    pub fn new(method_id: impl Into<AuthMethodId>) -> Self {
299        Self {
300            method_id: method_id.into(),
301            meta: None,
302        }
303    }
304
305    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
306    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
307    /// do not recognize.
308    ///
309    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
310    #[must_use]
311    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
312        self.meta = meta.into_option();
313        self
314    }
315}
316
317crate::serde_util::default_on_null! {
318    /// Response to the `auth/login` method.
319    #[serde_as]
320    #[skip_serializing_none]
321    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
322    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
323    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGIN_METHOD_NAME)))]
324    #[serde(rename_all = "camelCase")]
325    #[non_exhaustive]
326    pub struct LoginAuthResponse {
327        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
328        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
329        /// Implementations MUST NOT assign meaning to keys they do not recognize.
330        ///
331        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
332        #[serde_as(deserialize_as = "DefaultOnError")]
333        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
334        #[serde(default)]
335        #[serde(rename = "_meta")]
336        pub meta: Option<Meta>,
337    }
338}
339
340impl LoginAuthResponse {
341    /// Builds [`LoginAuthResponse`] with the required response fields set. Optional fields start unset or empty.
342    #[must_use]
343    pub fn new() -> Self {
344        Self::default()
345    }
346
347    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
348    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
349    /// do not recognize.
350    ///
351    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
352    #[must_use]
353    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
354        self.meta = meta.into_option();
355        self
356    }
357}
358
359// Logout
360
361crate::serde_util::default_on_null! {
362    /// Request parameters for the `auth/logout` method.
363    ///
364    /// Terminates the current authenticated session.
365    ///
366    /// Agents MUST support this method when their `initialize` response included
367    /// a non-empty `authMethods` list. Clients MUST NOT call this method
368    /// when `authMethods` was omitted or empty.
369    #[serde_as]
370    #[skip_serializing_none]
371    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
372    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
373    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGOUT_METHOD_NAME)))]
374    #[serde(rename_all = "camelCase")]
375    #[non_exhaustive]
376    pub struct LogoutAuthRequest {
377        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
378        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
379        /// Implementations MUST NOT assign meaning to keys they do not recognize.
380        ///
381        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
382        #[serde_as(deserialize_as = "DefaultOnError")]
383        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
384        #[serde(default)]
385        #[serde(rename = "_meta")]
386        pub meta: Option<Meta>,
387    }
388}
389
390impl LogoutAuthRequest {
391    /// Builds [`LogoutAuthRequest`] with the required request fields set. Optional fields start unset or empty.
392    #[must_use]
393    pub fn new() -> Self {
394        Self::default()
395    }
396
397    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
398    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
399    /// do not recognize.
400    ///
401    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
402    #[must_use]
403    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
404        self.meta = meta.into_option();
405        self
406    }
407}
408
409crate::serde_util::default_on_null! {
410    /// Response to the `auth/logout` method.
411    #[serde_as]
412    #[skip_serializing_none]
413    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
414    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
415    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGOUT_METHOD_NAME)))]
416    #[serde(rename_all = "camelCase")]
417    #[non_exhaustive]
418    pub struct LogoutAuthResponse {
419        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
420        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
421        /// Implementations MUST NOT assign meaning to keys they do not recognize.
422        ///
423        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
424        #[serde_as(deserialize_as = "DefaultOnError")]
425        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
426        #[serde(default)]
427        #[serde(rename = "_meta")]
428        pub meta: Option<Meta>,
429    }
430}
431
432impl LogoutAuthResponse {
433    /// Builds [`LogoutAuthResponse`] with the required response fields set. Optional fields start unset or empty.
434    #[must_use]
435    pub fn new() -> Self {
436        Self::default()
437    }
438
439    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
440    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
441    /// do not recognize.
442    ///
443    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
444    #[must_use]
445    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
446        self.meta = meta.into_option();
447        self
448    }
449}
450
451// Auth status
452
453#[cfg(feature = "unstable_auth_status")]
454crate::serde_util::default_on_null! {
455    /// **UNSTABLE**
456    ///
457    /// This capability is not part of the spec yet, and may be removed or changed at any point.
458    ///
459    /// Request parameters for the `auth/status` method.
460    ///
461    /// Queries the Agent's current authentication state without changing it.
462    ///
463    /// Agents MUST NOT reject it with `-32000` (Authentication required), since Clients call it to learn
464    /// whether authentication is required.
465    #[serde_as]
466    #[skip_serializing_none]
467    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
468    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
469    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_STATUS_METHOD_NAME)))]
470    #[serde(rename_all = "camelCase")]
471    #[non_exhaustive]
472    pub struct AuthStatusRequest {
473        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
474        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
475        /// Implementations MUST NOT assign meaning to keys they do not recognize.
476        ///
477        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
478        #[serde_as(deserialize_as = "DefaultOnError")]
479        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
480        #[serde(default)]
481        #[serde(rename = "_meta")]
482        pub meta: Option<Meta>,
483    }
484}
485
486#[cfg(feature = "unstable_auth_status")]
487impl AuthStatusRequest {
488    /// Builds [`AuthStatusRequest`] with the required request fields set. Optional fields start unset or empty.
489    #[must_use]
490    pub fn new() -> Self {
491        Self::default()
492    }
493
494    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
495    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
496    /// do not recognize.
497    ///
498    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
499    #[must_use]
500    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
501        self.meta = meta.into_option();
502        self
503    }
504}
505
506/// **UNSTABLE**
507///
508/// This capability is not part of the spec yet, and may be removed or changed at any point.
509///
510/// Response to the `auth/status` method.
511#[cfg(feature = "unstable_auth_status")]
512#[serde_as]
513#[skip_serializing_none]
514#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
515#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
516#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_STATUS_METHOD_NAME)))]
517#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"agent": [{"action": "replace", "target": "authStatus"}]})))]
518#[serde(rename_all = "camelCase")]
519#[non_exhaustive]
520pub struct AuthStatusResponse {
521    /// Whether the Agent can start sessions without the user signing in first.
522    ///
523    /// Clients use this field to decide whether sign-in is needed. Clients MUST treat
524    /// values they do not recognize as `unknown`.
525    pub state: AuthState,
526    /// The accounts the Agent has configured, for display.
527    ///
528    /// Optional. Omitted and empty are equivalent and mean no accounts are reported.
529    /// Agents that hold credentials for several providers or accounts SHOULD list each
530    /// of them and mark the ones in effect with `active`.
531    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
532    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
533    #[serde(default, skip_serializing_if = "Vec::is_empty")]
534    pub accounts: Vec<AuthAccount>,
535    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
536    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
537    /// Implementations MUST NOT assign meaning to keys they do not recognize.
538    ///
539    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
540    #[serde_as(deserialize_as = "DefaultOnError")]
541    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
542    #[serde(default)]
543    #[serde(rename = "_meta")]
544    pub meta: Option<Meta>,
545}
546
547#[cfg(feature = "unstable_auth_status")]
548impl AuthStatusResponse {
549    /// Builds [`AuthStatusResponse`] with the required fields set. Optional fields start unset or empty.
550    #[must_use]
551    pub fn new(state: AuthState) -> Self {
552        Self {
553            state,
554            accounts: vec![],
555            meta: None,
556        }
557    }
558
559    /// The accounts the Agent has configured, for display.
560    #[must_use]
561    pub fn accounts(mut self, accounts: Vec<AuthAccount>) -> Self {
562        self.accounts = accounts;
563        self
564    }
565
566    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
567    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
568    /// do not recognize.
569    ///
570    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
571    #[must_use]
572    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
573        self.meta = meta.into_option();
574        self
575    }
576}
577
578/// **UNSTABLE**
579///
580/// This capability is not part of the spec yet, and may be removed or changed at any point.
581///
582/// Notification sent by the Agent when its authentication status changes.
583///
584/// Carries the same fields as the `auth/status` response. Agents that advertise the
585/// `auth.status` capability MAY send it at any time after `initialize`, and SHOULD only
586/// send it when the reported status differs from the last one sent on the connection.
587#[cfg(feature = "unstable_auth_status")]
588#[serde_as]
589#[skip_serializing_none]
590#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
591#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
592#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = AUTH_STATUS_UPDATE_NOTIFICATION)))]
593#[cfg_attr(feature = "schemars", schemars(extend("x-scope" = {})))]
594#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"agent": [{"action": "replace", "target": "authStatus"}]})))]
595#[serde(rename_all = "camelCase")]
596#[non_exhaustive]
597pub struct AuthStatusUpdateNotification {
598    /// Whether the Agent can start sessions without the user signing in first.
599    ///
600    /// Clients use this field to decide whether sign-in is needed. Clients MUST treat
601    /// values they do not recognize as `unknown`.
602    pub state: AuthState,
603    /// The accounts the Agent has configured, for display.
604    ///
605    /// Optional. Omitted and empty are equivalent and mean no accounts are reported.
606    /// Agents that hold credentials for several providers or accounts SHOULD list each
607    /// of them and mark the ones in effect with `active`.
608    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
609    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
610    #[serde(default, skip_serializing_if = "Vec::is_empty")]
611    pub accounts: Vec<AuthAccount>,
612    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
613    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
614    /// Implementations MUST NOT assign meaning to keys they do not recognize.
615    ///
616    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
617    #[serde_as(deserialize_as = "DefaultOnError")]
618    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
619    #[serde(default)]
620    #[serde(rename = "_meta")]
621    pub meta: Option<Meta>,
622}
623
624#[cfg(feature = "unstable_auth_status")]
625impl AuthStatusUpdateNotification {
626    /// Builds [`AuthStatusUpdateNotification`] with the required fields set. Optional fields start unset or empty.
627    #[must_use]
628    pub fn new(state: AuthState) -> Self {
629        Self {
630            state,
631            accounts: vec![],
632            meta: None,
633        }
634    }
635
636    /// The accounts the Agent has configured, for display.
637    #[must_use]
638    pub fn accounts(mut self, accounts: Vec<AuthAccount>) -> Self {
639        self.accounts = accounts;
640        self
641    }
642
643    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
644    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
645    /// do not recognize.
646    ///
647    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
648    #[must_use]
649    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
650        self.meta = meta.into_option();
651        self
652    }
653}
654
655/// **UNSTABLE**
656///
657/// This capability is not part of the spec yet, and may be removed or changed at any point.
658///
659/// The Agent's overall authentication state.
660#[cfg(feature = "unstable_auth_status")]
661#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
662#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
663#[serde(rename_all = "snake_case")]
664#[non_exhaustive]
665pub enum AuthState {
666    /// Credentials are configured. This does not guarantee that they are valid.
667    Authenticated,
668    /// The user needs to sign in. This includes credentials that are missing,
669    /// expired, or known to be invalid.
670    Unauthenticated,
671    /// No authentication is needed, for example because the Agent uses a local model.
672    NotRequired,
673    /// The Agent cannot currently determine the state.
674    Unknown,
675    /// Custom or future authentication state.
676    ///
677    /// Values beginning with `_` are reserved for implementation-specific
678    /// extensions. Unknown values that do not begin with `_` are reserved for
679    /// future ACP variants.
680    #[serde(untagged)]
681    Other(String),
682}
683
684/// **UNSTABLE**
685///
686/// This capability is not part of the spec yet, and may be removed or changed at any point.
687///
688/// An account or credential the Agent has configured, such as a signed-in user
689/// account or an API key.
690///
691/// All fields are display information only. Clients MUST NOT use them as stable
692/// account identifiers, and SHOULD NOT log them or send them elsewhere, such as to
693/// telemetry.
694#[cfg(feature = "unstable_auth_status")]
695#[serde_as]
696#[skip_serializing_none]
697#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
698#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
699#[serde(rename_all = "camelCase")]
700#[non_exhaustive]
701pub struct AuthAccount {
702    /// Human-readable name for the account, suitable for display on its own,
703    /// for example `Claude Max`, `OpenAI API key`, or `Vertex AI`.
704    pub label: String,
705    /// Short text shown with the label, such as the credential source, for example
706    /// `API key helper`. MUST NOT contain credentials.
707    ///
708    /// Optional. Omitted and `null` are equivalent and mean no description is reported.
709    #[serde_as(deserialize_as = "DefaultOnError")]
710    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
711    #[serde(default)]
712    pub description: Option<String>,
713    /// Whether the Agent currently uses this account by default.
714    ///
715    /// Several accounts MAY be active, for example one per provider.
716    ///
717    /// Optional. Omitted and `null` are equivalent and mean the Agent does not indicate whether this account is in effect.
718    #[serde_as(deserialize_as = "DefaultOnError")]
719    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
720    #[serde(default)]
721    pub active: Option<bool>,
722    /// Display name of the user, such as a username or full name.
723    ///
724    /// Optional. Omitted and `null` are equivalent and mean no name is reported.
725    #[serde_as(deserialize_as = "DefaultOnError")]
726    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
727    #[serde(default)]
728    pub name: Option<String>,
729    /// Email address of the user.
730    ///
731    /// Optional. Omitted and `null` are equivalent and mean no email is reported.
732    #[serde_as(deserialize_as = "DefaultOnError")]
733    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
734    #[serde(default)]
735    pub email: Option<String>,
736    /// Display name of the organization, team, or workspace the account is using.
737    ///
738    /// Optional. Omitted and `null` are equivalent and mean no organization is reported.
739    #[serde_as(deserialize_as = "DefaultOnError")]
740    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
741    #[serde(default)]
742    pub organization: Option<String>,
743    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
744    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
745    /// Implementations MUST NOT assign meaning to keys they do not recognize.
746    ///
747    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
748    #[serde_as(deserialize_as = "DefaultOnError")]
749    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
750    #[serde(default)]
751    #[serde(rename = "_meta")]
752    pub meta: Option<Meta>,
753}
754
755#[cfg(feature = "unstable_auth_status")]
756impl AuthAccount {
757    /// Builds [`AuthAccount`] with the required fields set. Optional fields start unset or empty.
758    #[must_use]
759    pub fn new(label: impl Into<String>) -> Self {
760        Self {
761            label: label.into(),
762            description: None,
763            active: None,
764            name: None,
765            email: None,
766            organization: None,
767            meta: None,
768        }
769    }
770
771    /// Short text shown with the label, such as the credential source.
772    #[must_use]
773    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
774        self.description = description.into_option();
775        self
776    }
777
778    /// Whether the Agent currently uses this account by default.
779    #[must_use]
780    pub fn active(mut self, active: impl IntoOption<bool>) -> Self {
781        self.active = active.into_option();
782        self
783    }
784
785    /// Display name of the user, such as a username or full name.
786    #[must_use]
787    pub fn name(mut self, name: impl IntoOption<String>) -> Self {
788        self.name = name.into_option();
789        self
790    }
791
792    /// Email address of the user.
793    #[must_use]
794    pub fn email(mut self, email: impl IntoOption<String>) -> Self {
795        self.email = email.into_option();
796        self
797    }
798
799    /// Display name of the organization, team, or workspace the account is using.
800    #[must_use]
801    pub fn organization(mut self, organization: impl IntoOption<String>) -> Self {
802        self.organization = organization.into_option();
803        self
804    }
805
806    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
807    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
808    /// do not recognize.
809    ///
810    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
811    #[must_use]
812    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
813        self.meta = meta.into_option();
814        self
815    }
816}
817
818/// **UNSTABLE**
819///
820/// This capability is not part of the spec yet, and may be removed or changed at any point.
821///
822/// Auth status capabilities supported by the Agent.
823///
824/// Supplying `{}` means the Agent supports the `auth/status` method.
825#[cfg(feature = "unstable_auth_status")]
826#[serde_as]
827#[skip_serializing_none]
828#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
829#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
830#[non_exhaustive]
831pub struct AuthStatusCapabilities {
832    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
833    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
834    /// Implementations MUST NOT assign meaning to keys they do not recognize.
835    ///
836    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
837    #[serde_as(deserialize_as = "DefaultOnError")]
838    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
839    #[serde(default)]
840    #[serde(rename = "_meta")]
841    pub meta: Option<Meta>,
842}
843
844#[cfg(feature = "unstable_auth_status")]
845impl AuthStatusCapabilities {
846    /// Builds an empty [`AuthStatusCapabilities`]. Use builder methods to advertise supported sub-capabilities.
847    #[must_use]
848    pub fn new() -> Self {
849        Self::default()
850    }
851
852    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
853    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
854    /// do not recognize.
855    ///
856    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
857    #[must_use]
858    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
859        self.meta = meta.into_option();
860        self
861    }
862}
863
864/// Authentication-related extension capabilities supported by the Agent.
865///
866/// This object does not advertise support for `auth/login` or `auth/logout`.
867/// Those methods are advertised by a non-empty `authMethods` list in the
868/// `initialize` response.
869#[serde_as]
870#[skip_serializing_none]
871#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
872#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
873#[serde(rename_all = "camelCase")]
874#[non_exhaustive]
875pub struct AgentAuthCapabilities {
876    /// **UNSTABLE**
877    ///
878    /// This capability is not part of the spec yet, and may be removed or changed at any point.
879    ///
880    /// Whether the Agent supports the `auth/status` method.
881    ///
882    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
883    /// Supplying `{}` means the Agent supports the `auth/status` method.
884    #[cfg(feature = "unstable_auth_status")]
885    #[serde_as(deserialize_as = "DefaultOnError")]
886    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
887    #[serde(default)]
888    pub status: Option<AuthStatusCapabilities>,
889    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
890    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
891    /// Implementations MUST NOT assign meaning to keys they do not recognize.
892    ///
893    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
894    #[serde_as(deserialize_as = "DefaultOnError")]
895    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
896    #[serde(default)]
897    #[serde(rename = "_meta")]
898    pub meta: Option<Meta>,
899}
900
901impl AgentAuthCapabilities {
902    /// Builds an empty [`AgentAuthCapabilities`].
903    #[must_use]
904    pub fn new() -> Self {
905        Self::default()
906    }
907
908    /// **UNSTABLE**
909    ///
910    /// This capability is not part of the spec yet, and may be removed or changed at any point.
911    ///
912    /// Whether the Agent supports the `auth/status` method.
913    #[cfg(feature = "unstable_auth_status")]
914    #[must_use]
915    pub fn status(mut self, status: impl IntoOption<AuthStatusCapabilities>) -> Self {
916        self.status = status.into_option();
917        self
918    }
919
920    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
921    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
922    /// do not recognize.
923    ///
924    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
925    #[must_use]
926    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
927        self.meta = meta.into_option();
928        self
929    }
930}
931
932/// Typed identifier used for auth method values on the wire.
933#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
934#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
935#[serde(transparent)]
936#[from(forward)]
937#[non_exhaustive]
938pub struct AuthMethodId(pub Arc<str>);
939
940impl AuthMethodId {
941    /// Wraps a protocol string as a typed [`AuthMethodId`].
942    #[must_use]
943    pub fn new(id: impl Into<Self>) -> Self {
944        id.into()
945    }
946}
947
948/// Describes an available authentication method.
949///
950/// The `type` field acts as the discriminator in the serialized JSON form.
951#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
952#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
953#[serde(tag = "type", rename_all = "snake_case")]
954#[non_exhaustive]
955pub enum AuthMethod {
956    /// Client runs the configured Agent program as a separate interactive
957    /// process, without passing this method to `auth/login`.
958    Terminal(AuthMethodTerminal),
959    /// Agent handles authentication itself through `auth/login`.
960    ///
961    /// The `type` discriminator value is `agent`.
962    Agent(AuthMethodAgent),
963    /// Custom or future authentication method.
964    ///
965    /// Values beginning with `_` are reserved for implementation-specific
966    /// extensions. Unknown values that do not begin with `_` are reserved for
967    /// future ACP variants.
968    ///
969    /// Clients that do not understand this method type SHOULD preserve the raw
970    /// payload when storing, replaying, proxying, or forwarding initialization
971    /// data, and otherwise ignore the method or display it generically.
972    #[serde(untagged)]
973    Other(OtherAuthMethod),
974}
975
976impl AuthMethod {
977    /// The unique identifier for this authentication method.
978    #[must_use]
979    pub fn method_id(&self) -> &AuthMethodId {
980        match self {
981            Self::Agent(a) => &a.method_id,
982            Self::Other(a) => &a.method_id,
983            Self::Terminal(t) => &t.method_id,
984        }
985    }
986
987    /// The human-readable name of this authentication method.
988    #[must_use]
989    pub fn name(&self) -> &str {
990        match self {
991            Self::Agent(a) => &a.name,
992            Self::Other(a) => &a.name,
993            Self::Terminal(t) => &t.name,
994        }
995    }
996
997    /// Optional human-readable description of this authentication method.
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.
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.
1128    pub name: String,
1129    /// Optional human-readable description of this authentication method.
1130    ///
1131    /// Omitted and `null` are equivalent and mean no description is provided.
1132    #[serde_as(deserialize_as = "DefaultOnError")]
1133    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1134    #[serde(default)]
1135    pub description: Option<String>,
1136    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1137    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1138    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1139    ///
1140    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1141    #[serde_as(deserialize_as = "DefaultOnError")]
1142    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1143    #[serde(default)]
1144    #[serde(rename = "_meta")]
1145    pub meta: Option<Meta>,
1146}
1147
1148impl AuthMethodAgent {
1149    /// Builds [`AuthMethodAgent`] with the required fields set. Optional fields start unset or empty.
1150    #[must_use]
1151    pub fn new(method_id: impl Into<AuthMethodId>, name: impl Into<String>) -> Self {
1152        Self {
1153            method_id: method_id.into(),
1154            name: name.into(),
1155            description: None,
1156            meta: None,
1157        }
1158    }
1159
1160    /// Optional human-readable description of this authentication method.
1161    #[must_use]
1162    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
1163        self.description = description.into_option();
1164        self
1165    }
1166
1167    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1168    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1169    /// do not recognize.
1170    ///
1171    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1172    #[must_use]
1173    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1174        self.meta = meta.into_option();
1175        self
1176    }
1177}
1178
1179/// Terminal-based authentication method.
1180///
1181/// The Client runs the configured Agent program as a separate interactive
1182/// process for the user to authenticate via a TUI. Agents MUST advertise this
1183/// method only when the Client enabled its terminal authentication capability.
1184/// A zero exit status signals success. Any other termination signals failure.
1185/// The Client MUST NOT pass this method to `auth/login`.
1186#[serde_as]
1187#[skip_serializing_none]
1188#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1189#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1190#[serde(rename_all = "camelCase")]
1191#[non_exhaustive]
1192pub struct AuthMethodTerminal {
1193    /// Unique identifier for this authentication method.
1194    pub method_id: AuthMethodId,
1195    /// Human-readable name of the authentication method.
1196    pub name: String,
1197    /// Optional human-readable description of this authentication method.
1198    ///
1199    /// Omitted and `null` are equivalent and mean no description is provided.
1200    #[serde_as(deserialize_as = "DefaultOnError")]
1201    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1202    #[serde(default)]
1203    pub description: Option<String>,
1204    /// Additional arguments to append to the configured Agent invocation for terminal auth.
1205    #[serde_as(deserialize_as = "DefaultOnNull")]
1206    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1207    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1208    pub args: Vec<String>,
1209    /// Additional environment variables to set on the configured Agent invocation for terminal auth.
1210    /// Names SHOULD be unique, and otherwise the last entry wins. These values override
1211    /// same-named variables in the base launch configuration.
1212    #[serde_as(deserialize_as = "DefaultOnNull")]
1213    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1214    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1215    pub env: Vec<EnvVariable>,
1216    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1217    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1218    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1219    ///
1220    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1221    #[serde_as(deserialize_as = "DefaultOnError")]
1222    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1223    #[serde(default)]
1224    #[serde(rename = "_meta")]
1225    pub meta: Option<Meta>,
1226}
1227
1228impl AuthMethodTerminal {
1229    /// Builds [`AuthMethodTerminal`] with the required fields set. Optional fields start unset or empty.
1230    #[must_use]
1231    pub fn new(method_id: impl Into<AuthMethodId>, name: impl Into<String>) -> Self {
1232        Self {
1233            method_id: method_id.into(),
1234            name: name.into(),
1235            description: None,
1236            args: Vec::new(),
1237            env: Vec::new(),
1238            meta: None,
1239        }
1240    }
1241
1242    /// Additional arguments to append to the configured Agent invocation for terminal auth.
1243    #[must_use]
1244    pub fn args(mut self, args: Vec<String>) -> Self {
1245        self.args = args;
1246        self
1247    }
1248
1249    /// Additional environment variables to set on the configured Agent invocation for terminal auth.
1250    /// Names SHOULD be unique, and otherwise the last entry wins. These values override
1251    /// same-named variables in the base launch configuration.
1252    #[must_use]
1253    pub fn env(mut self, env: Vec<EnvVariable>) -> Self {
1254        self.env = env;
1255        self
1256    }
1257
1258    /// Optional human-readable description of this authentication method.
1259    #[must_use]
1260    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
1261        self.description = description.into_option();
1262        self
1263    }
1264
1265    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1266    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1267    /// do not recognize.
1268    ///
1269    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1270    #[must_use]
1271    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1272        self.meta = meta.into_option();
1273        self
1274    }
1275}
1276
1277// New session
1278
1279/// Request parameters for creating a new session.
1280///
1281/// See protocol docs: [Creating a Session](https://agentclientprotocol.com/protocol/v2/session-setup#creating-a-session)
1282#[serde_as]
1283#[skip_serializing_none]
1284#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1285#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1286#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_NEW_METHOD_NAME)))]
1287#[serde(rename_all = "camelCase")]
1288#[non_exhaustive]
1289pub struct NewSessionRequest {
1290    /// The working directory for this session. Must be an absolute path.
1291    pub cwd: AbsolutePath,
1292    /// Additional workspace roots for this session. Each path MUST be absolute.
1293    ///
1294    /// These expand the session's workspace scope without changing `cwd`, which
1295    /// remains the base for relative paths. When omitted or empty, no
1296    /// additional roots are activated for the new session.
1297    #[serde_as(deserialize_as = "DefaultOnNull")]
1298    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1299    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1300    pub additional_directories: Vec<AbsolutePath>,
1301    /// List of MCP (Model Context Protocol) servers for the Agent to connect to.
1302    #[serde_as(deserialize_as = "DefaultOnNull")]
1303    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1304    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1305    pub mcp_servers: Vec<McpServer>,
1306    /// System-level instructions for the new session.
1307    ///
1308    /// Optional. Omitted and `null` are equivalent and mean the Agent uses its
1309    /// own default instructions. Clients MUST only send this when the Agent
1310    /// advertises `session.systemPrompt`.
1311    #[serde(default)]
1312    pub system_prompt: Option<SystemPrompt>,
1313    /// **UNSTABLE**
1314    ///
1315    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1316    ///
1317    /// Initial values for the session's config options.
1318    ///
1319    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1320    /// this when the Agent advertises `session.options`.
1321    ///
1322    /// The Agent applies the entries in list order, as if the Client had called
1323    /// `session/set_config_option` for each entry after the session was set up. Malformed
1324    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1325    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1326    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1327    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries,
1328    /// and SHOULD NOT send other `session/update` notifications caused by applying them
1329    /// before it responds.
1330    #[cfg(feature = "unstable_session_options")]
1331    #[serde_as(deserialize_as = "DefaultOnNull")]
1332    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1333    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1334    pub config_options: Vec<InitialSessionConfigOption>,
1335    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1336    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1337    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1338    ///
1339    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1340    #[serde_as(deserialize_as = "DefaultOnError")]
1341    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1342    #[serde(default)]
1343    #[serde(rename = "_meta")]
1344    pub meta: Option<Meta>,
1345}
1346
1347impl NewSessionRequest {
1348    /// Builds [`NewSessionRequest`] with the required request fields set. Optional fields start unset or empty.
1349    #[must_use]
1350    pub fn new(cwd: impl Into<AbsolutePath>) -> Self {
1351        Self {
1352            cwd: cwd.into(),
1353            additional_directories: vec![],
1354            mcp_servers: vec![],
1355            system_prompt: None,
1356            #[cfg(feature = "unstable_session_options")]
1357            config_options: vec![],
1358            meta: None,
1359        }
1360    }
1361
1362    /// Additional workspace roots for this session. Each path MUST be absolute.
1363    #[must_use]
1364    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1365    where
1366        I: IntoIterator<Item = P>,
1367        P: Into<AbsolutePath>,
1368    {
1369        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1370        self
1371    }
1372
1373    /// List of MCP (Model Context Protocol) servers for the Agent to connect to.
1374    #[must_use]
1375    pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1376        self.mcp_servers = mcp_servers;
1377        self
1378    }
1379
1380    /// System-level instructions for the new session.
1381    #[must_use]
1382    pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1383        self.system_prompt = system_prompt.into_option();
1384        self
1385    }
1386
1387    /// **UNSTABLE**
1388    ///
1389    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1390    ///
1391    /// Initial values for the session's config options.
1392    ///
1393    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1394    /// this when the Agent advertises `session.options`.
1395    ///
1396    /// The Agent applies the entries in list order, as if the Client had called
1397    /// `session/set_config_option` for each entry after the session was set up. Malformed
1398    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1399    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1400    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1401    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries,
1402    /// and SHOULD NOT send other `session/update` notifications caused by applying them
1403    /// before it responds.
1404    #[cfg(feature = "unstable_session_options")]
1405    #[must_use]
1406    pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1407        self.config_options = config_options;
1408        self
1409    }
1410
1411    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1412    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1413    /// do not recognize.
1414    ///
1415    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1416    #[must_use]
1417    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1418        self.meta = meta.into_option();
1419        self
1420    }
1421}
1422
1423/// Response from creating a new session.
1424///
1425/// New sessions default to `idle` until a state update reports otherwise.
1426/// Updates may arrive before or after this response. Clients MUST NOT overwrite
1427/// an already-reported state when the response arrives.
1428///
1429/// An Agent whose new session is not `idle` MUST send the session's
1430/// `state_update` after this response.
1431///
1432/// See protocol docs: [Creating a Session](https://agentclientprotocol.com/protocol/v2/session-setup#creating-a-session)
1433#[serde_as]
1434#[skip_serializing_none]
1435#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1436#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1437#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_NEW_METHOD_NAME)))]
1438#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}, {"action": "replace", "target": "availableCommands", "value": "availableCommands"}]})))]
1439#[serde(rename_all = "camelCase")]
1440#[non_exhaustive]
1441pub struct NewSessionResponse {
1442    /// Unique identifier for the created session.
1443    ///
1444    /// Used in all subsequent requests for this conversation.
1445    pub session_id: SessionId,
1446    /// Initial session configuration options.
1447    ///
1448    /// Optional. Omitted or empty means no config options are advertised.
1449    /// Senders MUST use an array, not `null`.
1450    /// Later `config_option_update` notifications replace this list.
1451    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1452    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1453    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1454    pub config_options: Vec<SessionConfigOption>,
1455    /// Initial commands the Agent can execute in this session.
1456    ///
1457    /// Optional. Omitted or empty means no initial commands are advertised.
1458    /// Senders MUST use an array, not `null`.
1459    /// Later `available_commands_update` notifications replace this list.
1460    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1461    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1462    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1463    pub available_commands: Vec<AvailableCommand>,
1464    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1465    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1466    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1467    ///
1468    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1469    #[serde_as(deserialize_as = "DefaultOnError")]
1470    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1471    #[serde(default)]
1472    #[serde(rename = "_meta")]
1473    pub meta: Option<Meta>,
1474}
1475
1476impl NewSessionResponse {
1477    /// Builds [`NewSessionResponse`] with the required response fields set. Optional fields start unset or empty.
1478    #[must_use]
1479    pub fn new(session_id: impl Into<SessionId>) -> Self {
1480        Self {
1481            session_id: session_id.into(),
1482            config_options: Vec::new(),
1483            available_commands: Vec::new(),
1484            meta: None,
1485        }
1486    }
1487
1488    /// Initial session configuration options.
1489    ///
1490    /// Optional. Omitted or empty means no config options are advertised.
1491    /// Senders MUST use an array, not `null`.
1492    /// Later `config_option_update` notifications replace this list.
1493    #[must_use]
1494    pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
1495        self.config_options = config_options;
1496        self
1497    }
1498
1499    /// Initial commands the Agent can execute in this session.
1500    #[must_use]
1501    pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
1502        self.available_commands = available_commands;
1503        self
1504    }
1505
1506    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1507    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1508    /// do not recognize.
1509    ///
1510    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1511    #[must_use]
1512    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1513        self.meta = meta.into_option();
1514        self
1515    }
1516}
1517
1518// Fork session
1519
1520/// **UNSTABLE**
1521///
1522/// This capability is not part of the spec yet, and may be removed or changed at any point.
1523///
1524/// Request parameters for forking an existing session.
1525///
1526/// Creates a new session based on the context of an existing one. The fork can be used
1527/// for operations like generating summaries without affecting the original session's history.
1528///
1529/// Only available if the Agent supports the `session.fork` capability.
1530#[cfg(feature = "unstable_session_fork")]
1531#[serde_as]
1532#[skip_serializing_none]
1533#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1534#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1535#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_FORK_METHOD_NAME)))]
1536#[serde(rename_all = "camelCase")]
1537#[non_exhaustive]
1538pub struct ForkSessionRequest {
1539    /// The ID of the session to fork.
1540    pub session_id: SessionId,
1541    /// **UNSTABLE**
1542    ///
1543    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1544    ///
1545    /// The session cursor to fork at. The new session's history is the source
1546    /// session's history before the cursor.
1547    ///
1548    /// Optional. Omitted and `null` are equivalent and fork the whole session.
1549    /// Clients MUST only send the ID of a cursor that the Agent announced on the
1550    /// source session and that currently advertises `capabilities.fork`. The Agent
1551    /// rejects any other ID with `-32602`. It does not fall back to forking the
1552    /// whole session.
1553    #[cfg(feature = "unstable_session_cursors")]
1554    #[serde(default)]
1555    pub cursor_id: Option<CursorId>,
1556    /// The working directory for this session. Must be an absolute path.
1557    pub cwd: AbsolutePath,
1558    /// Additional workspace roots to activate for this session. Each path MUST be absolute.
1559    ///
1560    /// When omitted or empty, no additional roots are activated. When non-empty,
1561    /// this is the complete resulting additional-root list for the forked
1562    /// session.
1563    #[serde_as(deserialize_as = "DefaultOnNull")]
1564    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1565    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1566    pub additional_directories: Vec<AbsolutePath>,
1567    /// List of MCP servers to connect to for this session.
1568    #[serde_as(deserialize_as = "DefaultOnNull")]
1569    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1570    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1571    pub mcp_servers: Vec<McpServer>,
1572    /// System-level instructions for the forked session.
1573    ///
1574    /// Optional. Omitted and `null` are equivalent. The Agent MAY then keep a
1575    /// system prompt it stored with the source session or use its default
1576    /// instructions. Clients MUST only send this when the Agent advertises
1577    /// `session.systemPrompt`, and SHOULD send the same value they used for the
1578    /// source session.
1579    #[serde(default)]
1580    pub system_prompt: Option<SystemPrompt>,
1581    /// **UNSTABLE**
1582    ///
1583    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1584    ///
1585    /// Initial values for the forked session's config options.
1586    ///
1587    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1588    /// this when the Agent advertises `session.options`.
1589    ///
1590    /// The Agent applies the entries in list order on top of the configuration the fork
1591    /// starts with, as if the Client had called `session/set_config_option` for each entry
1592    /// after the session was set up. Malformed entries and duplicate `configId` values fail
1593    /// the request with `-32602`. The Agent MUST ignore an entry whose `configId` is unknown,
1594    /// whose `type` does not match the option, or whose value is not allowed when it is
1595    /// applied. The `configOptions` in the response contain the values the session actually
1596    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries,
1597    /// and SHOULD NOT send other `session/update` notifications caused by applying them
1598    /// before it responds.
1599    #[cfg(feature = "unstable_session_options")]
1600    #[serde_as(deserialize_as = "DefaultOnNull")]
1601    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1602    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1603    pub config_options: Vec<InitialSessionConfigOption>,
1604    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1605    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1606    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1607    ///
1608    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1609    #[serde_as(deserialize_as = "DefaultOnError")]
1610    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1611    #[serde(default)]
1612    #[serde(rename = "_meta")]
1613    pub meta: Option<Meta>,
1614}
1615
1616#[cfg(feature = "unstable_session_fork")]
1617impl ForkSessionRequest {
1618    /// Builds [`ForkSessionRequest`] with the required request fields set. Optional fields start unset or empty.
1619    #[must_use]
1620    pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
1621        Self {
1622            session_id: session_id.into(),
1623            #[cfg(feature = "unstable_session_cursors")]
1624            cursor_id: None,
1625            cwd: cwd.into(),
1626            additional_directories: vec![],
1627            mcp_servers: vec![],
1628            system_prompt: None,
1629            #[cfg(feature = "unstable_session_options")]
1630            config_options: vec![],
1631            meta: None,
1632        }
1633    }
1634
1635    /// **UNSTABLE**
1636    ///
1637    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1638    ///
1639    /// The session cursor to fork at. Omitting it forks the whole session.
1640    ///
1641    /// Clients MUST only send the ID of a cursor that the Agent announced on the
1642    /// source session and that currently advertises `capabilities.fork`.
1643    #[cfg(feature = "unstable_session_cursors")]
1644    #[must_use]
1645    pub fn cursor_id(mut self, cursor_id: impl IntoOption<CursorId>) -> Self {
1646        self.cursor_id = cursor_id.into_option();
1647        self
1648    }
1649
1650    /// Additional workspace roots to activate for this session. Each path MUST be absolute.
1651    #[must_use]
1652    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1653    where
1654        I: IntoIterator<Item = P>,
1655        P: Into<AbsolutePath>,
1656    {
1657        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1658        self
1659    }
1660
1661    /// List of MCP servers to connect to for this session.
1662    #[must_use]
1663    pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1664        self.mcp_servers = mcp_servers;
1665        self
1666    }
1667
1668    /// System-level instructions for the forked session.
1669    #[must_use]
1670    pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1671        self.system_prompt = system_prompt.into_option();
1672        self
1673    }
1674
1675    /// **UNSTABLE**
1676    ///
1677    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1678    ///
1679    /// Initial values for the forked session's config options.
1680    ///
1681    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1682    /// this when the Agent advertises `session.options`.
1683    ///
1684    /// The Agent applies the entries in list order on top of the configuration the fork
1685    /// starts with, as if the Client had called `session/set_config_option` for each entry
1686    /// after the session was set up. Malformed entries and duplicate `configId` values fail
1687    /// the request with `-32602`. The Agent MUST ignore an entry whose `configId` is unknown,
1688    /// whose `type` does not match the option, or whose value is not allowed when it is
1689    /// applied. The `configOptions` in the response contain the values the session actually
1690    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries,
1691    /// and SHOULD NOT send other `session/update` notifications caused by applying them
1692    /// before it responds.
1693    #[cfg(feature = "unstable_session_options")]
1694    #[must_use]
1695    pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1696        self.config_options = config_options;
1697        self
1698    }
1699
1700    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1701    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1702    /// do not recognize.
1703    ///
1704    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1705    #[must_use]
1706    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1707        self.meta = meta.into_option();
1708        self
1709    }
1710}
1711
1712/// **UNSTABLE**
1713///
1714/// This capability is not part of the spec yet, and may be removed or changed at any point.
1715///
1716/// Response from forking an existing session.
1717#[cfg(feature = "unstable_session_fork")]
1718#[serde_as]
1719#[skip_serializing_none]
1720#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1721#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1722#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_FORK_METHOD_NAME)))]
1723#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}, {"action": "replace", "target": "availableCommands", "value": "availableCommands"}]})))]
1724#[serde(rename_all = "camelCase")]
1725#[non_exhaustive]
1726pub struct ForkSessionResponse {
1727    /// Unique identifier for the newly created forked session.
1728    pub session_id: SessionId,
1729    /// Initial session configuration options.
1730    ///
1731    /// Optional. Omitted or empty means no config options are advertised.
1732    /// Senders MUST use an array, not `null`.
1733    /// Later `config_option_update` notifications replace this list.
1734    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1735    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1736    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1737    pub config_options: Vec<SessionConfigOption>,
1738    /// Initial commands the Agent can execute in this session.
1739    ///
1740    /// Optional. Omitted or empty means no initial commands are advertised.
1741    /// Senders MUST use an array, not `null`.
1742    /// Later `available_commands_update` notifications replace this list.
1743    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1744    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1745    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1746    pub available_commands: Vec<AvailableCommand>,
1747    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1748    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1749    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1750    ///
1751    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1752    #[serde_as(deserialize_as = "DefaultOnError")]
1753    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1754    #[serde(default)]
1755    #[serde(rename = "_meta")]
1756    pub meta: Option<Meta>,
1757}
1758
1759#[cfg(feature = "unstable_session_fork")]
1760impl ForkSessionResponse {
1761    /// Builds [`ForkSessionResponse`] with the required response fields set. Optional fields start unset or empty.
1762    #[must_use]
1763    pub fn new(session_id: impl Into<SessionId>) -> Self {
1764        Self {
1765            session_id: session_id.into(),
1766            config_options: Vec::new(),
1767            available_commands: Vec::new(),
1768            meta: None,
1769        }
1770    }
1771
1772    /// Initial session configuration options.
1773    ///
1774    /// Optional. Omitted or empty means no config options are advertised.
1775    /// Senders MUST use an array, not `null`.
1776    /// Later `config_option_update` notifications replace this list.
1777    #[must_use]
1778    pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
1779        self.config_options = config_options;
1780        self
1781    }
1782
1783    /// Initial commands the Agent can execute in this session.
1784    #[must_use]
1785    pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
1786        self.available_commands = available_commands;
1787        self
1788    }
1789
1790    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1791    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1792    /// do not recognize.
1793    ///
1794    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1795    #[must_use]
1796    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1797        self.meta = meta.into_option();
1798        self
1799    }
1800}
1801
1802// Resume session
1803
1804/// Request parameters for resuming an existing session.
1805///
1806/// Resumes an existing session and optionally replays retained conversation
1807/// history according to `replayFrom`.
1808#[serde_as]
1809#[skip_serializing_none]
1810#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1811#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1812#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_RESUME_METHOD_NAME)))]
1813#[serde(rename_all = "camelCase")]
1814#[non_exhaustive]
1815pub struct ResumeSessionRequest {
1816    /// The ID of the session to resume.
1817    pub session_id: SessionId,
1818    /// The working directory for this session. Must be an absolute path.
1819    ///
1820    /// Clients MUST send the session's working directory. Agents MAY reject a different directory
1821    /// with `-32602`, and MAY normalize paths when comparing.
1822    pub cwd: AbsolutePath,
1823    /// Additional workspace roots to activate for this session. Each path MUST be absolute.
1824    ///
1825    /// When omitted or empty, no additional roots are activated. When non-empty,
1826    /// this is the complete resulting additional-root list for the resumed
1827    /// session. It MAY differ from any previously used or reported list as long as
1828    /// the request `cwd` matches the session's `cwd`.
1829    #[serde_as(deserialize_as = "DefaultOnNull")]
1830    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1831    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1832    pub additional_directories: Vec<AbsolutePath>,
1833    /// List of MCP servers to connect to for this session.
1834    ///
1835    /// The complete set of Client-provided servers. Omitted and `[]` mean none. Agents SHOULD
1836    /// NOT restore servers from earlier requests.
1837    #[serde_as(deserialize_as = "DefaultOnNull")]
1838    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1839    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1840    pub mcp_servers: Vec<McpServer>,
1841    /// Inclusive cursor describing where conversation replay begins.
1842    ///
1843    /// Optional. Omitted and `null` are equivalent, and the Agent MUST NOT replay
1844    /// previous conversation history. Replay cursors are inclusive:
1845    /// replay includes the position identified by the cursor. Supplying
1846    /// `{ "type": "start" }` means the Agent MUST replay all retained
1847    /// conversation history before responding.
1848    ///
1849    /// Agents MUST reject unsupported cursor types or malformed cursor values
1850    /// with `-32602` (Invalid params), rather than substituting another cursor
1851    /// or resuming without replay.
1852    #[serde(default)]
1853    pub replay_from: Option<ReplayFrom>,
1854    /// System-level instructions for the resumed session.
1855    ///
1856    /// Optional. Omitted and `null` are equivalent. The Agent MAY then keep a
1857    /// system prompt it stored with the session or use its default instructions.
1858    /// Clients MUST only send this when the Agent advertises
1859    /// `session.systemPrompt`, and SHOULD send the same value they used when the
1860    /// session was created.
1861    #[serde(default)]
1862    pub system_prompt: Option<SystemPrompt>,
1863    /// **UNSTABLE**
1864    ///
1865    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1866    ///
1867    /// Initial values for the session's config options.
1868    ///
1869    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1870    /// this when the Agent advertises `session.options`.
1871    ///
1872    /// The Agent applies the entries in list order, as if the Client had called
1873    /// `session/set_config_option` for each entry after the session was set up. Malformed
1874    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1875    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1876    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1877    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries
1878    /// on the requesting connection. If the session is active on other connections, the
1879    /// Agent SHOULD send `config_option_update` on those connections.
1880    ///
1881    /// The Agent applies the entries before it replays history for `replayFrom` and before
1882    /// it responds.
1883    #[cfg(feature = "unstable_session_options")]
1884    #[serde_as(deserialize_as = "DefaultOnNull")]
1885    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1886    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1887    pub config_options: Vec<InitialSessionConfigOption>,
1888    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1889    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1890    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1891    ///
1892    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1893    #[serde_as(deserialize_as = "DefaultOnError")]
1894    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1895    #[serde(default)]
1896    #[serde(rename = "_meta")]
1897    pub meta: Option<Meta>,
1898}
1899
1900impl ResumeSessionRequest {
1901    /// Builds [`ResumeSessionRequest`] with the required request fields set. Optional fields start unset or empty.
1902    #[must_use]
1903    pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
1904        Self {
1905            session_id: session_id.into(),
1906            cwd: cwd.into(),
1907            additional_directories: vec![],
1908            mcp_servers: vec![],
1909            replay_from: None,
1910            system_prompt: None,
1911            #[cfg(feature = "unstable_session_options")]
1912            config_options: vec![],
1913            meta: None,
1914        }
1915    }
1916
1917    /// Additional workspace roots to activate for this session. Each path MUST be absolute.
1918    #[must_use]
1919    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1920    where
1921        I: IntoIterator<Item = P>,
1922        P: Into<AbsolutePath>,
1923    {
1924        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1925        self
1926    }
1927
1928    /// List of MCP servers to connect to for this session.
1929    #[must_use]
1930    pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1931        self.mcp_servers = mcp_servers;
1932        self
1933    }
1934
1935    /// Inclusive cursor describing where conversation replay begins.
1936    ///
1937    /// Omitted and `null` are equivalent, and the Agent MUST NOT replay
1938    /// previous conversation history. Replay cursors are inclusive: replay
1939    /// includes the position identified by the cursor. Supplying
1940    /// `{ "type": "start" }` means the Agent MUST replay all retained
1941    /// conversation history before responding.
1942    #[must_use]
1943    pub fn replay_from(mut self, replay_from: impl IntoOption<ReplayFrom>) -> Self {
1944        self.replay_from = replay_from.into_option();
1945        self
1946    }
1947
1948    /// System-level instructions for the resumed session.
1949    #[must_use]
1950    pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1951        self.system_prompt = system_prompt.into_option();
1952        self
1953    }
1954
1955    /// **UNSTABLE**
1956    ///
1957    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1958    ///
1959    /// Initial values for the session's config options.
1960    ///
1961    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1962    /// this when the Agent advertises `session.options`.
1963    ///
1964    /// The Agent applies the entries in list order, as if the Client had called
1965    /// `session/set_config_option` for each entry after the session was set up. Malformed
1966    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1967    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1968    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1969    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries
1970    /// on the requesting connection. If the session is active on other connections, the
1971    /// Agent SHOULD send `config_option_update` on those connections.
1972    #[cfg(feature = "unstable_session_options")]
1973    #[must_use]
1974    pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1975        self.config_options = config_options;
1976        self
1977    }
1978
1979    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1980    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1981    /// do not recognize.
1982    ///
1983    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1984    #[must_use]
1985    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1986        self.meta = meta.into_option();
1987        self
1988    }
1989}
1990
1991/// Inclusive cursor describing where replayed session history begins.
1992///
1993/// Replay includes the position identified by the cursor.
1994#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1995#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1996#[serde(tag = "type", rename_all = "snake_case")]
1997#[non_exhaustive]
1998pub enum ReplayFrom {
1999    /// Replay all retained conversation history from its first replayable entry.
2000    Start(ReplayFromStart),
2001    /// Custom or future replay cursor.
2002    ///
2003    /// Values beginning with `_` are reserved for implementation-specific
2004    /// extensions. Unknown values that do not begin with `_` are reserved for
2005    /// future ACP variants.
2006    ///
2007    /// Intermediaries SHOULD preserve the raw payload when storing, replaying,
2008    /// proxying, or forwarding requests. Agents that do not support this cursor
2009    /// MUST reject the request with `-32602` (Invalid params), rather than
2010    /// substituting another cursor or resuming without replay.
2011    #[serde(untagged)]
2012    Other(OtherReplayFrom),
2013}
2014
2015impl From<ReplayFromStart> for ReplayFrom {
2016    fn from(replay_from: ReplayFromStart) -> Self {
2017        Self::Start(replay_from)
2018    }
2019}
2020
2021/// Inclusive replay cursor requesting replay from the start of retained conversation history.
2022#[serde_as]
2023#[skip_serializing_none]
2024#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2025#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2026#[serde(rename_all = "camelCase")]
2027#[non_exhaustive]
2028pub struct ReplayFromStart {
2029    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2030    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2031    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2032    ///
2033    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2034    #[serde_as(deserialize_as = "DefaultOnError")]
2035    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2036    #[serde(default)]
2037    #[serde(rename = "_meta")]
2038    pub meta: Option<Meta>,
2039}
2040
2041impl ReplayFromStart {
2042    /// Builds [`ReplayFromStart`].
2043    #[must_use]
2044    pub fn new() -> Self {
2045        Self::default()
2046    }
2047
2048    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2049    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2050    /// do not recognize.
2051    ///
2052    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2053    #[must_use]
2054    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2055        self.meta = meta.into_option();
2056        self
2057    }
2058}
2059
2060/// Custom or future replay cursor payload.
2061#[serde_as]
2062#[skip_serializing_none]
2063#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2064#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
2065#[cfg_attr(feature = "schemars", schemars(inline))]
2066#[cfg_attr(feature = "schemars", schemars(transform = other_replay_from_schema))]
2067#[serde(rename_all = "camelCase")]
2068#[non_exhaustive]
2069pub struct OtherReplayFrom {
2070    /// Custom or future replay cursor type.
2071    ///
2072    /// Values beginning with `_` are reserved for implementation-specific
2073    /// extensions. Unknown values that do not begin with `_` are reserved for
2074    /// future ACP variants.
2075    #[serde(rename = "type")]
2076    pub type_: String,
2077    /// The remaining fields of the unknown replay cursor payload, preserved verbatim,
2078    /// including `_meta`.
2079    #[serde(flatten)]
2080    pub fields: IndexMap<String, serde_json::Value>,
2081}
2082
2083impl OtherReplayFrom {
2084    /// Builds [`OtherReplayFrom`] from an unknown discriminator and preserves the remaining extension fields.
2085    #[must_use]
2086    pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
2087        fields.shift_remove("type");
2088        Self {
2089            type_: type_.into(),
2090            fields,
2091        }
2092    }
2093}
2094
2095impl<'de> Deserialize<'de> for OtherReplayFrom {
2096    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2097    where
2098        D: serde::Deserializer<'de>,
2099    {
2100        let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
2101        let type_ = fields
2102            .shift_remove("type")
2103            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
2104        let serde_json::Value::String(type_) = type_ else {
2105            return Err(serde::de::Error::custom("`type` must be a string"));
2106        };
2107
2108        if is_known_replay_from_type(&type_) {
2109            return Err(serde::de::Error::custom(format!(
2110                "known replay cursor `{type_}` did not match its schema"
2111            )));
2112        }
2113
2114        Ok(Self { type_, fields })
2115    }
2116}
2117
2118fn is_known_replay_from_type(type_: &str) -> bool {
2119    matches!(type_, "start")
2120}
2121
2122#[cfg(feature = "schemars")]
2123fn other_replay_from_schema(schema: &mut Schema) {
2124    super::schema_util::reject_known_string_discriminators(schema, "type", &["start"]);
2125}
2126
2127crate::serde_util::default_on_null! {
2128    /// Response from resuming an existing session.
2129    ///
2130    /// The Agent MUST send a current `state_update` after any requested history
2131    /// replay and before this response, even without replay. The update reports
2132    /// foreground state after resuming. The response alone does not imply `idle`.
2133    ///
2134    /// See protocol docs: [Current-State Synchronization](https://agentclientprotocol.com/protocol/v2/session-setup#current-state-synchronization)
2135    #[serde_as]
2136    #[skip_serializing_none]
2137    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2138    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2139    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_RESUME_METHOD_NAME)))]
2140    #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}, {"action": "replace", "target": "availableCommands", "value": "availableCommands"}]})))]
2141    #[serde(rename_all = "camelCase")]
2142    #[non_exhaustive]
2143    pub struct ResumeSessionResponse {
2144        /// Current session configuration options.
2145        ///
2146        /// Optional. Omitted or empty means no config options are advertised.
2147        /// Senders MUST use an array, not `null`.
2148        /// Later `config_option_update` notifications replace this list.
2149        #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2150        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2151        #[serde(default, skip_serializing_if = "Vec::is_empty")]
2152        pub config_options: Vec<SessionConfigOption>,
2153        /// Current commands the Agent can execute in this session.
2154        ///
2155        /// Optional. Omitted or empty means no initial commands are advertised.
2156        /// Senders MUST use an array, not `null`.
2157        /// Later `available_commands_update` notifications replace this list.
2158        #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2159        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2160        #[serde(default, skip_serializing_if = "Vec::is_empty")]
2161        pub available_commands: Vec<AvailableCommand>,
2162        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2163        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2164        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2165        ///
2166        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2167        #[serde_as(deserialize_as = "DefaultOnError")]
2168        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2169        #[serde(default)]
2170        #[serde(rename = "_meta")]
2171        pub meta: Option<Meta>,
2172    }
2173}
2174
2175impl ResumeSessionResponse {
2176    /// Builds [`ResumeSessionResponse`] with the required response fields set. Optional fields start unset or empty.
2177    #[must_use]
2178    pub fn new() -> Self {
2179        Self::default()
2180    }
2181
2182    /// Current session configuration options.
2183    ///
2184    /// Optional. Omitted or empty means no config options are advertised.
2185    /// Senders MUST use an array, not `null`.
2186    /// Later `config_option_update` notifications replace this list.
2187    #[must_use]
2188    pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
2189        self.config_options = config_options;
2190        self
2191    }
2192
2193    /// Current commands the Agent can execute in this session.
2194    #[must_use]
2195    pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
2196        self.available_commands = available_commands;
2197        self
2198    }
2199
2200    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2201    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2202    /// do not recognize.
2203    ///
2204    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2205    #[must_use]
2206    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2207        self.meta = meta.into_option();
2208        self
2209    }
2210}
2211
2212// Close session
2213
2214/// Request parameters for closing an active session.
2215///
2216/// The Agent MUST cancel any ongoing work related to the session as if `session/cancel`
2217/// was called, then free the resources associated with the session. Unlike `session/cancel`,
2218/// closing also stops the session's background work. After the close response, the Agent
2219/// sends no notifications or requests for the session on that connection. It still
2220/// answers `session/prompt` requests that were pending.
2221///
2222/// Closing a session that does not exist or is not active SHOULD succeed, and Clients SHOULD
2223/// treat a `-32002` response as a successful close.
2224///
2225/// When closing cancels active foreground work, the Agent MUST send the final
2226/// updates for that work and the idle `state_update` with `stopReason: "cancelled"`
2227/// before responding successfully to `session/close`. Closing an idle session
2228/// does not itself require another idle update.
2229///
2230/// Closing also cancels pending `session/prompt` requests whose messages have not
2231/// been inserted, including held prompts. If closing prevents a prompt's user message from being inserted, the
2232/// Agent MUST answer that request with `-32800` (Request cancelled). If the message
2233/// has already been inserted, the Agent MUST respond successfully with its
2234/// `messageId`. Prompt responses need not precede the close response.
2235#[serde_as]
2236#[skip_serializing_none]
2237#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2238#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2239#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CLOSE_METHOD_NAME)))]
2240#[serde(rename_all = "camelCase")]
2241#[non_exhaustive]
2242pub struct CloseSessionRequest {
2243    /// The ID of the session to close.
2244    pub session_id: SessionId,
2245    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2246    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2247    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2248    ///
2249    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2250    #[serde_as(deserialize_as = "DefaultOnError")]
2251    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2252    #[serde(default)]
2253    #[serde(rename = "_meta")]
2254    pub meta: Option<Meta>,
2255}
2256
2257impl CloseSessionRequest {
2258    /// Builds [`CloseSessionRequest`] with the required request fields set. Optional fields start unset or empty.
2259    #[must_use]
2260    pub fn new(session_id: impl Into<SessionId>) -> Self {
2261        Self {
2262            session_id: session_id.into(),
2263            meta: None,
2264        }
2265    }
2266
2267    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2268    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2269    /// do not recognize.
2270    ///
2271    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2272    #[must_use]
2273    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2274        self.meta = meta.into_option();
2275        self
2276    }
2277}
2278
2279crate::serde_util::default_on_null! {
2280    /// Response from closing a session.
2281    #[serde_as]
2282    #[skip_serializing_none]
2283    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2284    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2285    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CLOSE_METHOD_NAME)))]
2286    #[serde(rename_all = "camelCase")]
2287    #[non_exhaustive]
2288    pub struct CloseSessionResponse {
2289        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2290        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2291        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2292        ///
2293        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2294        #[serde_as(deserialize_as = "DefaultOnError")]
2295        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2296        #[serde(default)]
2297        #[serde(rename = "_meta")]
2298        pub meta: Option<Meta>,
2299    }
2300}
2301
2302impl CloseSessionResponse {
2303    /// Builds [`CloseSessionResponse`] with the required response fields set. Optional fields start unset or empty.
2304    #[must_use]
2305    pub fn new() -> Self {
2306        Self::default()
2307    }
2308
2309    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2310    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2311    /// do not recognize.
2312    ///
2313    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2314    #[must_use]
2315    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2316        self.meta = meta.into_option();
2317        self
2318    }
2319}
2320
2321// Session status
2322
2323/// **UNSTABLE**
2324///
2325/// This capability is not part of the spec yet, and may be removed or changed at any point.
2326///
2327/// Request parameters for checking the status of a session.
2328///
2329/// Only available if the Agent supports the `session.status` capability.
2330///
2331/// `session/status` MUST NOT have side effects. The Agent does not resume, create,
2332/// close, or change the session, and does not attach the requesting connection to it.
2333/// A session the Agent does not know gets `-32002` with the requested `sessionId` in `data`.
2334#[cfg(feature = "unstable_session_status")]
2335#[serde_as]
2336#[skip_serializing_none]
2337#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2338#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2339#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_STATUS_METHOD_NAME)))]
2340#[serde(rename_all = "camelCase")]
2341#[non_exhaustive]
2342pub struct SessionStatusRequest {
2343    /// The ID of the session to check.
2344    pub session_id: SessionId,
2345    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2346    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2347    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2348    ///
2349    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2350    #[serde_as(deserialize_as = "DefaultOnError")]
2351    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2352    #[serde(default)]
2353    #[serde(rename = "_meta")]
2354    pub meta: Option<Meta>,
2355}
2356
2357#[cfg(feature = "unstable_session_status")]
2358impl SessionStatusRequest {
2359    /// Builds [`SessionStatusRequest`] with the required request fields set. Optional fields start unset or empty.
2360    #[must_use]
2361    pub fn new(session_id: impl Into<SessionId>) -> Self {
2362        Self {
2363            session_id: session_id.into(),
2364            meta: None,
2365        }
2366    }
2367
2368    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2369    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2370    /// do not recognize.
2371    ///
2372    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2373    #[must_use]
2374    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2375        self.meta = meta.into_option();
2376        self
2377    }
2378}
2379
2380/// **UNSTABLE**
2381///
2382/// This capability is not part of the spec yet, and may be removed or changed at any point.
2383///
2384/// Response from checking the status of a session.
2385///
2386/// The result is a snapshot. A session reported `open` may be closed or evicted before
2387/// the Client's next request.
2388#[cfg(feature = "unstable_session_status")]
2389#[serde_as]
2390#[skip_serializing_none]
2391#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2392#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2393#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_STATUS_METHOD_NAME)))]
2394#[serde(rename_all = "camelCase")]
2395#[non_exhaustive]
2396pub struct SessionStatusResponse {
2397    /// Whether the Agent has the session in memory.
2398    ///
2399    /// Required. Clients MUST treat a value they do not recognize as `saved`.
2400    pub status: SessionStatus,
2401    /// The session's current foreground state, as the same snapshot the Agent sends in
2402    /// `state_update` notifications.
2403    ///
2404    /// Optional. Agents SHOULD include it when `status` is `open`. Omitted and `null`
2405    /// mean the Agent is not reporting foreground state, and Clients
2406    /// MUST NOT read that as `idle`. This is a snapshot, not a new transition. Clients
2407    /// MUST NOT count an `idle` snapshot as a new completion.
2408    #[serde_as(deserialize_as = "DefaultOnError")]
2409    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2410    #[serde(default)]
2411    pub state: Option<StateUpdate>,
2412    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2413    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2414    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2415    ///
2416    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2417    #[serde_as(deserialize_as = "DefaultOnError")]
2418    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2419    #[serde(default)]
2420    #[serde(rename = "_meta")]
2421    pub meta: Option<Meta>,
2422}
2423
2424#[cfg(feature = "unstable_session_status")]
2425impl SessionStatusResponse {
2426    /// Builds [`SessionStatusResponse`] with the required response fields set. Optional fields start unset or empty.
2427    #[must_use]
2428    pub fn new(status: SessionStatus) -> Self {
2429        Self {
2430            status,
2431            state: None,
2432            meta: None,
2433        }
2434    }
2435
2436    /// The session's current foreground state, as the same snapshot the Agent sends in
2437    /// `state_update` notifications.
2438    #[must_use]
2439    pub fn state(mut self, state: impl IntoOption<StateUpdate>) -> Self {
2440        self.state = state.into_option();
2441        self
2442    }
2443
2444    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2445    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2446    /// do not recognize.
2447    ///
2448    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2449    #[must_use]
2450    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2451        self.meta = meta.into_option();
2452        self
2453    }
2454}
2455
2456/// **UNSTABLE**
2457///
2458/// This capability is not part of the spec yet, and may be removed or changed at any point.
2459///
2460/// Whether the Agent has a session in memory, as reported by `session/status`.
2461#[cfg(feature = "unstable_session_status")]
2462#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2463#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2464#[serde(rename_all = "snake_case")]
2465#[non_exhaustive]
2466pub enum SessionStatus {
2467    /// The Agent has the session in memory, for any connection.
2468    ///
2469    /// This does not mean the requesting connection is attached to it. A Client that did
2470    /// not create or resume the session on its own connection MUST still call
2471    /// `session/resume` before sending `session/prompt` or expecting
2472    /// `session/update` notifications.
2473    Open,
2474    /// The Agent knows the session and can resume it, but does not have it in memory.
2475    ///
2476    /// The Client can call `session/resume` to start it.
2477    Saved,
2478    /// Custom or future session status.
2479    ///
2480    /// Values beginning with `_` are reserved for implementation-specific
2481    /// extensions. Unknown values that do not begin with `_` are reserved for
2482    /// future ACP variants. Clients MUST treat a value they do not recognize as
2483    /// `saved`.
2484    #[serde(untagged)]
2485    Other(String),
2486}
2487
2488/// **UNSTABLE**
2489///
2490/// This capability is not part of the spec yet, and may be removed or changed at any point.
2491///
2492/// Request parameters for `session/options`, which returns the config options a session
2493/// would start with, without creating or resuming a session.
2494///
2495/// Only available if the Agent supports the `session.options` capability.
2496///
2497/// `session/options` MUST NOT create or resume a session, send `session/update`
2498/// notifications, add an entry to `session/list`, or change an existing session. Agents
2499/// SHOULD NOT connect to MCP servers to answer it. Agents MAY start their runtime to resolve
2500/// the options. The rules above still hold for it.
2501#[cfg(feature = "unstable_session_options")]
2502#[serde_as]
2503#[skip_serializing_none]
2504#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2505#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2506#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_OPTIONS_METHOD_NAME)))]
2507#[serde(rename_all = "camelCase")]
2508#[non_exhaustive]
2509pub struct SessionOptionsRequest {
2510    /// The working directory to resolve options for. Must be an absolute path.
2511    pub cwd: AbsolutePath,
2512    /// Additional workspace roots to resolve options for. Each path MUST be absolute.
2513    ///
2514    /// Optional. Omitted and `null` are equivalent to an empty list.
2515    #[serde_as(deserialize_as = "DefaultOnNull")]
2516    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
2517    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2518    pub additional_directories: Vec<AbsolutePath>,
2519    /// The session to resolve options for.
2520    ///
2521    /// Optional. Omitted and `null` are equivalent and mean a new session. When present,
2522    /// the Agent returns what `session/resume` with the same `cwd` and
2523    /// `additionalDirectories` would return, with the same `cwd` rules. A session the
2524    /// Agent does not know gets `-32002`.
2525    #[serde(default)]
2526    pub session_id: Option<SessionId>,
2527    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2528    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2529    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2530    ///
2531    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2532    #[serde_as(deserialize_as = "DefaultOnError")]
2533    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2534    #[serde(default)]
2535    #[serde(rename = "_meta")]
2536    pub meta: Option<Meta>,
2537}
2538
2539#[cfg(feature = "unstable_session_options")]
2540impl SessionOptionsRequest {
2541    /// Builds [`SessionOptionsRequest`] with the required request fields set. Optional fields start unset or empty.
2542    #[must_use]
2543    pub fn new(cwd: impl Into<AbsolutePath>) -> Self {
2544        Self {
2545            cwd: cwd.into(),
2546            additional_directories: vec![],
2547            session_id: None,
2548            meta: None,
2549        }
2550    }
2551
2552    /// Additional workspace roots to resolve options for. Each path MUST be absolute.
2553    #[must_use]
2554    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
2555    where
2556        I: IntoIterator<Item = P>,
2557        P: Into<AbsolutePath>,
2558    {
2559        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
2560        self
2561    }
2562
2563    /// The session to resolve options for. Unset means a new session.
2564    #[must_use]
2565    pub fn session_id(mut self, session_id: impl IntoOption<SessionId>) -> Self {
2566        self.session_id = session_id.into_option();
2567        self
2568    }
2569
2570    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2571    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2572    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2573    ///
2574    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2575    #[must_use]
2576    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2577        self.meta = meta.into_option();
2578        self
2579    }
2580}
2581
2582#[cfg(feature = "unstable_session_options")]
2583crate::serde_util::default_on_null! {
2584    /// **UNSTABLE**
2585    ///
2586    /// This capability is not part of the spec yet, and may be removed or changed at any point.
2587    ///
2588    /// Response from `session/options`.
2589    ///
2590    /// The result is a snapshot. The options a session actually starts with are the ones in
2591    /// the session setup response.
2592    #[serde_as]
2593    #[skip_serializing_none]
2594    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2595    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2596    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_OPTIONS_METHOD_NAME)))]
2597    #[serde(rename_all = "camelCase")]
2598    #[non_exhaustive]
2599    pub struct SessionOptionsResponse {
2600        /// The config options the session would start with, with the same rules as on
2601        /// `NewSessionResponse`.
2602        ///
2603        /// Optional. Omitted or empty means no config options are advertised.
2604        /// Senders MUST use an array, not `null`.
2605        #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2606        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2607        #[serde(default, skip_serializing_if = "Vec::is_empty")]
2608        pub config_options: Vec<SessionConfigOption>,
2609        /// Commands the Agent knows the session would have.
2610        ///
2611        /// Optional. Omitted or empty means no commands are advertised.
2612        /// Senders MUST use an array, not `null`.
2613        ///
2614        /// Advisory. Agents MAY return a partial list. Clients MUST use the commands from the
2615        /// `session/new` or `session/resume` response and later `available_commands_update`
2616        /// notifications for the session itself.
2617        #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2618        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2619        #[serde(default, skip_serializing_if = "Vec::is_empty")]
2620        pub available_commands: Vec<AvailableCommand>,
2621        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2622        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2623        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2624        ///
2625        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2626        #[serde_as(deserialize_as = "DefaultOnError")]
2627        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2628        #[serde(default)]
2629        #[serde(rename = "_meta")]
2630        pub meta: Option<Meta>,
2631    }
2632}
2633
2634#[cfg(feature = "unstable_session_options")]
2635impl SessionOptionsResponse {
2636    /// Builds [`SessionOptionsResponse`] with the required response fields set. Optional fields start unset or empty.
2637    #[must_use]
2638    pub fn new() -> Self {
2639        Self::default()
2640    }
2641
2642    /// The config options the session would start with.
2643    #[must_use]
2644    pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
2645        self.config_options = config_options;
2646        self
2647    }
2648
2649    /// Commands the Agent knows the session would have. Advisory.
2650    #[must_use]
2651    pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
2652        self.available_commands = available_commands;
2653        self
2654    }
2655
2656    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2657    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2658    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2659    ///
2660    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2661    #[must_use]
2662    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2663        self.meta = meta.into_option();
2664        self
2665    }
2666}
2667
2668/// **UNSTABLE**
2669///
2670/// This capability is not part of the spec yet, and may be removed or changed at any point.
2671///
2672/// An initial value for a config option, sent on session setup requests.
2673///
2674/// Same shape as `session/set_config_option` without `sessionId`. Unlike
2675/// `session/set_config_option`, an unknown `configId`, a `type` that does not match the
2676/// option, or a value that is not allowed is ignored instead of rejected.
2677#[cfg(feature = "unstable_session_options")]
2678#[serde_as]
2679#[skip_serializing_none]
2680#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2681#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2682#[serde(rename_all = "camelCase")]
2683#[non_exhaustive]
2684pub struct InitialSessionConfigOption {
2685    /// The ID of the configuration option to set.
2686    pub config_id: SessionConfigId,
2687    /// The value to set, including a `type` discriminator and the raw `value`.
2688    ///
2689    /// Payloads MUST send `type: "id"` for id-based options. A value `type` the Agent
2690    /// does not support fails the request with `-32602`.
2691    #[serde(flatten)]
2692    pub value: SessionConfigOptionValue,
2693    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2694    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2695    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2696    ///
2697    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2698    #[serde_as(deserialize_as = "DefaultOnError")]
2699    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2700    #[serde(default)]
2701    #[serde(rename = "_meta")]
2702    pub meta: Option<Meta>,
2703}
2704
2705#[cfg(feature = "unstable_session_options")]
2706impl InitialSessionConfigOption {
2707    /// Builds [`InitialSessionConfigOption`] with the required fields set. Optional fields start unset or empty.
2708    #[must_use]
2709    pub fn new(
2710        config_id: impl Into<SessionConfigId>,
2711        value: impl Into<SessionConfigOptionValue>,
2712    ) -> Self {
2713        Self {
2714            config_id: config_id.into(),
2715            value: value.into(),
2716            meta: None,
2717        }
2718    }
2719
2720    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2721    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2722    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2723    ///
2724    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2725    #[must_use]
2726    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2727        self.meta = meta.into_option();
2728        self
2729    }
2730}
2731
2732// Cancel tool call
2733
2734/// Request parameters for cancelling one tool call.
2735///
2736/// Clients MUST NOT send it unless the tool call currently advertises `capabilities.cancel`.
2737///
2738/// The Agent responds once it has accepted the cancellation. The response does not mean
2739/// the work has stopped. The Agent confirms it with a `tool_call_update` to a final
2740/// status: normally `cancelled`, or `completed` or `failed` if the work finished first.
2741///
2742/// The Agent responds with `-32602` if the tool call is unknown, already final, or not
2743/// cancellable. Cancelling a tool call does not change the foreground state by itself.
2744///
2745/// See protocol docs: [Cancelling Tool Calls](https://agentclientprotocol.com/protocol/v2/tool-calls#cancelling-tool-calls)
2746#[serde_as]
2747#[skip_serializing_none]
2748#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2749#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2750#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TOOL_CALL_CANCEL_METHOD_NAME)))]
2751#[serde(rename_all = "camelCase")]
2752#[non_exhaustive]
2753pub struct CancelToolCallRequest {
2754    /// The ID of the session that owns the tool call.
2755    pub session_id: SessionId,
2756    /// The ID of the tool call to cancel.
2757    pub tool_call_id: ToolCallId,
2758    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2759    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2760    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2761    ///
2762    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2763    #[serde_as(deserialize_as = "DefaultOnError")]
2764    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2765    #[serde(default)]
2766    #[serde(rename = "_meta")]
2767    pub meta: Option<Meta>,
2768}
2769
2770impl CancelToolCallRequest {
2771    /// Builds [`CancelToolCallRequest`] with the required request fields set. Optional fields start unset or empty.
2772    #[must_use]
2773    pub fn new(session_id: impl Into<SessionId>, tool_call_id: impl Into<ToolCallId>) -> Self {
2774        Self {
2775            session_id: session_id.into(),
2776            tool_call_id: tool_call_id.into(),
2777            meta: None,
2778        }
2779    }
2780
2781    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2782    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2783    /// do not recognize.
2784    ///
2785    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2786    #[must_use]
2787    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2788        self.meta = meta.into_option();
2789        self
2790    }
2791}
2792
2793crate::serde_util::default_on_null! {
2794    /// Response from cancelling a tool call.
2795    #[serde_as]
2796    #[skip_serializing_none]
2797    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2798    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2799    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TOOL_CALL_CANCEL_METHOD_NAME)))]
2800    #[serde(rename_all = "camelCase")]
2801    #[non_exhaustive]
2802    pub struct CancelToolCallResponse {
2803        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2804        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2805        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2806        ///
2807        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2808        #[serde_as(deserialize_as = "DefaultOnError")]
2809        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2810        #[serde(default)]
2811        #[serde(rename = "_meta")]
2812        pub meta: Option<Meta>,
2813    }
2814}
2815
2816impl CancelToolCallResponse {
2817    /// Builds [`CancelToolCallResponse`] with the required response fields set. Optional fields start unset or empty.
2818    #[must_use]
2819    pub fn new() -> Self {
2820        Self::default()
2821    }
2822
2823    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2824    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2825    /// do not recognize.
2826    ///
2827    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2828    #[must_use]
2829    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2830        self.meta = meta.into_option();
2831        self
2832    }
2833}
2834
2835// Cancel terminal
2836
2837/// Request parameters for cancelling one terminal.
2838///
2839/// Clients MUST NOT send it unless the terminal currently advertises `capabilities.cancel`.
2840///
2841/// The Agent responds once it has accepted the cancellation. The response does not mean
2842/// the work has stopped. The Agent confirms it with a `terminal_update` that sets
2843/// `exitStatus`. Cancelling stops the process but does not release the terminal, and does
2844/// not change the status of a tool call that references it.
2845///
2846/// The Agent responds with `-32602` if the terminal is unknown, has already exited, or is not
2847/// cancellable. Cancelling a terminal does not change the foreground state by itself.
2848///
2849/// See protocol docs: [Cancelling Terminals](https://agentclientprotocol.com/protocol/v2/tool-calls#cancelling-terminals)
2850#[serde_as]
2851#[skip_serializing_none]
2852#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2853#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2854#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TERMINAL_CANCEL_METHOD_NAME)))]
2855#[serde(rename_all = "camelCase")]
2856#[non_exhaustive]
2857pub struct CancelTerminalRequest {
2858    /// The ID of the session that owns the terminal.
2859    pub session_id: SessionId,
2860    /// The ID of the terminal to cancel.
2861    pub terminal_id: TerminalId,
2862    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2863    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2864    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2865    ///
2866    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2867    #[serde_as(deserialize_as = "DefaultOnError")]
2868    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2869    #[serde(default)]
2870    #[serde(rename = "_meta")]
2871    pub meta: Option<Meta>,
2872}
2873
2874impl CancelTerminalRequest {
2875    /// Builds [`CancelTerminalRequest`] with the required request fields set. Optional fields start unset or empty.
2876    #[must_use]
2877    pub fn new(session_id: impl Into<SessionId>, terminal_id: impl Into<TerminalId>) -> Self {
2878        Self {
2879            session_id: session_id.into(),
2880            terminal_id: terminal_id.into(),
2881            meta: None,
2882        }
2883    }
2884
2885    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2886    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2887    /// do not recognize.
2888    ///
2889    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2890    #[must_use]
2891    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2892        self.meta = meta.into_option();
2893        self
2894    }
2895}
2896
2897crate::serde_util::default_on_null! {
2898    /// Response from cancelling a terminal.
2899    #[serde_as]
2900    #[skip_serializing_none]
2901    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2902    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2903    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TERMINAL_CANCEL_METHOD_NAME)))]
2904    #[serde(rename_all = "camelCase")]
2905    #[non_exhaustive]
2906    pub struct CancelTerminalResponse {
2907        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2908        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2909        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2910        ///
2911        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2912        #[serde_as(deserialize_as = "DefaultOnError")]
2913        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2914        #[serde(default)]
2915        #[serde(rename = "_meta")]
2916        pub meta: Option<Meta>,
2917    }
2918}
2919
2920impl CancelTerminalResponse {
2921    /// Builds [`CancelTerminalResponse`] with the required response fields set. Optional fields start unset or empty.
2922    #[must_use]
2923    pub fn new() -> Self {
2924        Self::default()
2925    }
2926
2927    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2928    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2929    /// do not recognize.
2930    ///
2931    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2932    #[must_use]
2933    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2934        self.meta = meta.into_option();
2935        self
2936    }
2937}
2938
2939// List sessions
2940
2941/// An opaque cursor used to paginate `session/list` results.
2942#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2943#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
2944#[serde(transparent)]
2945#[from(Arc<str>, String, &str, &mut str, Box<str>, Cow<'_, str>)]
2946#[non_exhaustive]
2947pub struct SessionListCursor(pub Arc<str>);
2948
2949impl SessionListCursor {
2950    /// Wraps a protocol string as a typed [`SessionListCursor`].
2951    #[must_use]
2952    pub fn new(cursor: impl Into<Self>) -> Self {
2953        cursor.into()
2954    }
2955}
2956
2957impl AsRef<str> for SessionListCursor {
2958    fn as_ref(&self) -> &str {
2959        &self.0
2960    }
2961}
2962
2963impl From<&String> for SessionListCursor {
2964    fn from(cursor: &String) -> Self {
2965        Self(cursor.as_str().into())
2966    }
2967}
2968
2969macro_rules! impl_session_list_cursor_option_conversion {
2970    ($source:ty) => {
2971        impl IntoOption<SessionListCursor> for $source {
2972            fn into_option(self) -> Option<SessionListCursor> {
2973                Some(self.into())
2974            }
2975        }
2976    };
2977}
2978
2979impl_session_list_cursor_option_conversion!(Arc<str>);
2980impl_session_list_cursor_option_conversion!(String);
2981impl_session_list_cursor_option_conversion!(&str);
2982impl_session_list_cursor_option_conversion!(&mut str);
2983impl_session_list_cursor_option_conversion!(&String);
2984impl_session_list_cursor_option_conversion!(Box<str>);
2985impl_session_list_cursor_option_conversion!(Cow<'_, str>);
2986
2987crate::serde_util::default_on_null! {
2988    /// Request parameters for listing existing sessions.
2989    #[serde_as]
2990    #[skip_serializing_none]
2991    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2992    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2993    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LIST_METHOD_NAME)))]
2994    #[serde(rename_all = "camelCase")]
2995    #[non_exhaustive]
2996    pub struct ListSessionsRequest {
2997        /// Filter sessions by working directory. Must be an absolute path.
2998        ///
2999        /// Only sessions whose `cwd` is this same directory match. Subdirectories and
3000        /// `additionalDirectories` don't. Agents MAY normalize paths when comparing.
3001        ///
3002        /// Omitted and `null` are equivalent and mean sessions are not filtered by working directory.
3003        /// Clients keep the same value when following `nextCursor`.
3004        #[serde(default)]
3005        pub cwd: Option<AbsolutePath>,
3006        /// Opaque cursor token from a previous response's nextCursor field for cursor-based pagination
3007        ///
3008        /// Omitted and `null` are equivalent and mean the first page is requested.
3009        #[serde(default)]
3010        pub cursor: Option<SessionListCursor>,
3011        /// **UNSTABLE**
3012        ///
3013        /// This capability is not part of the spec yet, and may be removed or changed at any point.
3014        ///
3015        /// Filter sessions by archive state.
3016        ///
3017        /// Optional. Omitted and `null` are equivalent and mean `exclude`. Only send this when
3018        /// the Agent advertises the `session.archive` capability. The filter combines with `cwd` and
3019        /// applies before pagination. Clients keep the same value when following `nextCursor`.
3020        #[cfg(feature = "unstable_session_archive")]
3021        #[serde(default)]
3022        pub archived: Option<SessionArchiveFilter>,
3023        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3024        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3025        /// Implementations MUST NOT assign meaning to keys they do not recognize.
3026        ///
3027        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3028        #[serde_as(deserialize_as = "DefaultOnError")]
3029        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3030        #[serde(default)]
3031        #[serde(rename = "_meta")]
3032        pub meta: Option<Meta>,
3033    }
3034}
3035
3036impl ListSessionsRequest {
3037    /// Builds [`ListSessionsRequest`] with the required request fields set. Optional fields start unset or empty.
3038    #[must_use]
3039    pub fn new() -> Self {
3040        Self::default()
3041    }
3042
3043    /// Filter sessions by working directory. Must be an absolute path.
3044    #[must_use]
3045    pub fn cwd(mut self, cwd: impl IntoOption<AbsolutePath>) -> Self {
3046        self.cwd = cwd.into_option();
3047        self
3048    }
3049
3050    /// Opaque cursor token from a previous response's nextCursor field for cursor-based pagination
3051    #[must_use]
3052    pub fn cursor(mut self, cursor: impl IntoOption<SessionListCursor>) -> Self {
3053        self.cursor = cursor.into_option();
3054        self
3055    }
3056
3057    /// **UNSTABLE**
3058    ///
3059    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3060    ///
3061    /// Filter sessions by archive state.
3062    #[cfg(feature = "unstable_session_archive")]
3063    #[must_use]
3064    pub fn archived(mut self, archived: impl IntoOption<SessionArchiveFilter>) -> Self {
3065        self.archived = archived.into_option();
3066        self
3067    }
3068
3069    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3070    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3071    /// do not recognize.
3072    ///
3073    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3074    #[must_use]
3075    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3076        self.meta = meta.into_option();
3077        self
3078    }
3079}
3080
3081/// Response from listing sessions.
3082#[serde_as]
3083#[skip_serializing_none]
3084#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3085#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3086#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LIST_METHOD_NAME)))]
3087#[serde(rename_all = "camelCase")]
3088#[non_exhaustive]
3089pub struct ListSessionsResponse {
3090    /// Array of session information objects.
3091    ///
3092    /// Agents SHOULD return the sessions with the most recent activity first.
3093    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
3094    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3095    pub sessions: Vec<SessionInfo>,
3096    /// Opaque cursor token. If present, pass this in the next request's cursor parameter
3097    /// to fetch the next page. Omitted and `null` are equivalent and mean there are no more
3098    /// results. An empty string is a valid cursor, not the end of results.
3099    #[serde(default)]
3100    pub next_cursor: Option<SessionListCursor>,
3101    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3102    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3103    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3104    ///
3105    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3106    #[serde_as(deserialize_as = "DefaultOnError")]
3107    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3108    #[serde(default)]
3109    #[serde(rename = "_meta")]
3110    pub meta: Option<Meta>,
3111}
3112
3113impl ListSessionsResponse {
3114    /// Builds [`ListSessionsResponse`] with the required response fields set. Optional fields start unset or empty.
3115    #[must_use]
3116    pub fn new(sessions: Vec<SessionInfo>) -> Self {
3117        Self {
3118            sessions,
3119            next_cursor: None,
3120            meta: None,
3121        }
3122    }
3123
3124    /// Sets or clears the optional `nextCursor` field.
3125    #[must_use]
3126    pub fn next_cursor(mut self, next_cursor: impl IntoOption<SessionListCursor>) -> Self {
3127        self.next_cursor = next_cursor.into_option();
3128        self
3129    }
3130
3131    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3132    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3133    /// do not recognize.
3134    ///
3135    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3136    #[must_use]
3137    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3138        self.meta = meta.into_option();
3139        self
3140    }
3141}
3142
3143// Delete session
3144
3145/// Request parameters for deleting an existing session from `session/list`.
3146///
3147/// Only available if the Agent supports the `session.delete` capability.
3148#[serde_as]
3149#[skip_serializing_none]
3150#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3151#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3152#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_DELETE_METHOD_NAME)))]
3153#[serde(rename_all = "camelCase")]
3154#[non_exhaustive]
3155pub struct DeleteSessionRequest {
3156    /// The ID of the session to delete.
3157    pub session_id: SessionId,
3158    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3159    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3160    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3161    ///
3162    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3163    #[serde_as(deserialize_as = "DefaultOnError")]
3164    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3165    #[serde(default)]
3166    #[serde(rename = "_meta")]
3167    pub meta: Option<Meta>,
3168}
3169
3170impl DeleteSessionRequest {
3171    /// Builds [`DeleteSessionRequest`] with the required request fields set. Optional fields start unset or empty.
3172    #[must_use]
3173    pub fn new(session_id: impl Into<SessionId>) -> Self {
3174        Self {
3175            session_id: session_id.into(),
3176            meta: None,
3177        }
3178    }
3179
3180    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3181    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3182    /// do not recognize.
3183    ///
3184    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3185    #[must_use]
3186    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3187        self.meta = meta.into_option();
3188        self
3189    }
3190}
3191
3192crate::serde_util::default_on_null! {
3193    /// Response from deleting a session.
3194    #[serde_as]
3195    #[skip_serializing_none]
3196    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3197    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3198    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_DELETE_METHOD_NAME)))]
3199    #[serde(rename_all = "camelCase")]
3200    #[non_exhaustive]
3201    pub struct DeleteSessionResponse {
3202        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3203        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3204        /// Implementations MUST NOT assign meaning to keys they do not recognize.
3205        ///
3206        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3207        #[serde_as(deserialize_as = "DefaultOnError")]
3208        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3209        #[serde(default)]
3210        #[serde(rename = "_meta")]
3211        pub meta: Option<Meta>,
3212    }
3213}
3214
3215impl DeleteSessionResponse {
3216    /// Builds [`DeleteSessionResponse`] with the required response fields set. Optional fields start unset or empty.
3217    #[must_use]
3218    pub fn new() -> Self {
3219        Self::default()
3220    }
3221
3222    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3223    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3224    /// do not recognize.
3225    ///
3226    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3227    #[must_use]
3228    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3229        self.meta = meta.into_option();
3230        self
3231    }
3232}
3233
3234// Archive session
3235
3236/// **UNSTABLE**
3237///
3238/// This capability is not part of the spec yet, and may be removed or changed at any point.
3239///
3240/// Request parameters for archiving a session.
3241///
3242/// Only available if the Agent supports the `session.archive` capability.
3243///
3244/// Archiving hides the session from default `session/list` results. It keeps the session ID
3245/// and saved history. If the session is active, the Agent MUST cancel any ongoing work and
3246/// free the session's resources as if `session/close` had been called, then archive it.
3247/// Archiving an archived session succeeds. A session that does not exist gets `-32002`.
3248///
3249#[cfg(feature = "unstable_session_archive")]
3250#[serde_as]
3251#[skip_serializing_none]
3252#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3253#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3254#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_ARCHIVE_METHOD_NAME)))]
3255#[serde(rename_all = "camelCase")]
3256#[non_exhaustive]
3257pub struct ArchiveSessionRequest {
3258    /// The ID of the session to archive.
3259    pub session_id: SessionId,
3260    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3261    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3262    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3263    ///
3264    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3265    #[serde_as(deserialize_as = "DefaultOnError")]
3266    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3267    #[serde(default)]
3268    #[serde(rename = "_meta")]
3269    pub meta: Option<Meta>,
3270}
3271
3272#[cfg(feature = "unstable_session_archive")]
3273impl ArchiveSessionRequest {
3274    /// Builds [`ArchiveSessionRequest`] with the required request fields set. Optional fields start unset or empty.
3275    #[must_use]
3276    pub fn new(session_id: impl Into<SessionId>) -> Self {
3277        Self {
3278            session_id: session_id.into(),
3279            meta: None,
3280        }
3281    }
3282
3283    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3284    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3285    /// do not recognize.
3286    ///
3287    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3288    #[must_use]
3289    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3290        self.meta = meta.into_option();
3291        self
3292    }
3293}
3294
3295#[cfg(feature = "unstable_session_archive")]
3296crate::serde_util::default_on_null! {
3297    /// **UNSTABLE**
3298    ///
3299    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3300    ///
3301    /// Response from archiving a session.
3302    #[serde_as]
3303    #[skip_serializing_none]
3304    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3305    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3306    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_ARCHIVE_METHOD_NAME)))]
3307    #[serde(rename_all = "camelCase")]
3308    #[non_exhaustive]
3309    pub struct ArchiveSessionResponse {
3310        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3311        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3312        /// Implementations MUST NOT assign meaning to keys they do not recognize.
3313        ///
3314        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3315        #[serde_as(deserialize_as = "DefaultOnError")]
3316        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3317        #[serde(default)]
3318        #[serde(rename = "_meta")]
3319        pub meta: Option<Meta>,
3320    }
3321}
3322
3323#[cfg(feature = "unstable_session_archive")]
3324impl ArchiveSessionResponse {
3325    /// Builds [`ArchiveSessionResponse`] with the required response fields set. Optional fields start unset or empty.
3326    #[must_use]
3327    pub fn new() -> Self {
3328        Self::default()
3329    }
3330
3331    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3332    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3333    /// do not recognize.
3334    ///
3335    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3336    #[must_use]
3337    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3338        self.meta = meta.into_option();
3339        self
3340    }
3341}
3342
3343/// **UNSTABLE**
3344///
3345/// This capability is not part of the spec yet, and may be removed or changed at any point.
3346///
3347/// Request parameters for unarchiving a session.
3348///
3349/// Only available if the Agent supports the `session.archive` capability.
3350///
3351/// Unarchiving returns the session to default `session/list` results with the same ID and
3352/// saved history. It never resumes the session. Clients that want to continue an
3353/// archived session SHOULD unarchive it before calling `session/resume`.
3354/// Unarchiving a session that is not archived succeeds. A session that does not exist
3355/// gets `-32002`.
3356///
3357#[cfg(feature = "unstable_session_archive")]
3358#[serde_as]
3359#[skip_serializing_none]
3360#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3361#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3362#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_UNARCHIVE_METHOD_NAME)))]
3363#[serde(rename_all = "camelCase")]
3364#[non_exhaustive]
3365pub struct UnarchiveSessionRequest {
3366    /// The ID of the session to unarchive.
3367    pub session_id: SessionId,
3368    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3369    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3370    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3371    ///
3372    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3373    #[serde_as(deserialize_as = "DefaultOnError")]
3374    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3375    #[serde(default)]
3376    #[serde(rename = "_meta")]
3377    pub meta: Option<Meta>,
3378}
3379
3380#[cfg(feature = "unstable_session_archive")]
3381impl UnarchiveSessionRequest {
3382    /// Builds [`UnarchiveSessionRequest`] with the required request fields set. Optional fields start unset or empty.
3383    #[must_use]
3384    pub fn new(session_id: impl Into<SessionId>) -> Self {
3385        Self {
3386            session_id: session_id.into(),
3387            meta: None,
3388        }
3389    }
3390
3391    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3392    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3393    /// do not recognize.
3394    ///
3395    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3396    #[must_use]
3397    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3398        self.meta = meta.into_option();
3399        self
3400    }
3401}
3402
3403#[cfg(feature = "unstable_session_archive")]
3404crate::serde_util::default_on_null! {
3405    /// **UNSTABLE**
3406    ///
3407    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3408    ///
3409    /// Response from unarchiving a session.
3410    #[serde_as]
3411    #[skip_serializing_none]
3412    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3413    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3414    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_UNARCHIVE_METHOD_NAME)))]
3415    #[serde(rename_all = "camelCase")]
3416    #[non_exhaustive]
3417    pub struct UnarchiveSessionResponse {
3418        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3419        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3420        /// Implementations MUST NOT assign meaning to keys they do not recognize.
3421        ///
3422        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3423        #[serde_as(deserialize_as = "DefaultOnError")]
3424        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3425        #[serde(default)]
3426        #[serde(rename = "_meta")]
3427        pub meta: Option<Meta>,
3428    }
3429}
3430
3431#[cfg(feature = "unstable_session_archive")]
3432impl UnarchiveSessionResponse {
3433    /// Builds [`UnarchiveSessionResponse`] with the required response fields set. Optional fields start unset or empty.
3434    #[must_use]
3435    pub fn new() -> Self {
3436        Self::default()
3437    }
3438
3439    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3440    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3441    /// do not recognize.
3442    ///
3443    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3444    #[must_use]
3445    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3446        self.meta = meta.into_option();
3447        self
3448    }
3449}
3450
3451/// **UNSTABLE**
3452///
3453/// This capability is not part of the spec yet, and may be removed or changed at any point.
3454///
3455/// Which sessions `session/list` returns based on their archive state.
3456///
3457/// Unknown values are preserved so they can be stored, proxied, or forwarded. An Agent MUST
3458/// return `-32602` for a value it does not support rather than treating it as `exclude`.
3459#[cfg(feature = "unstable_session_archive")]
3460#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3461#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
3462#[serde(rename_all = "snake_case")]
3463#[non_exhaustive]
3464pub enum SessionArchiveFilter {
3465    /// Only sessions that are not archived. This is the default.
3466    #[default]
3467    Exclude,
3468    /// Both archived sessions and sessions that are not archived.
3469    Include,
3470    /// Only archived sessions.
3471    Only,
3472    /// Custom or future archive filter.
3473    ///
3474    /// Values beginning with `_` are reserved for implementation-specific
3475    /// extensions. Unknown values that do not begin with `_` are reserved for
3476    /// future ACP variants.
3477    #[serde(untagged)]
3478    Other(String),
3479}
3480
3481/// Information about a session returned by session/list
3482#[serde_as]
3483#[skip_serializing_none]
3484#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3485#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3486#[serde(rename_all = "camelCase")]
3487#[non_exhaustive]
3488pub struct SessionInfo {
3489    /// Unique identifier for the session
3490    pub session_id: SessionId,
3491    /// The working directory for this session. Must be an absolute path.
3492    pub cwd: AbsolutePath,
3493    /// Additional workspace roots reported for this session. Each path MUST be absolute.
3494    ///
3495    /// When present, this is the complete ordered additional-root list reported
3496    /// by the Agent. Omitted and empty values are equivalent: the response
3497    /// reports no additional roots.
3498    #[serde_as(deserialize_as = "DefaultOnNull")]
3499    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
3500    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3501    pub additional_directories: Vec<AbsolutePath>,
3502
3503    /// Human-readable title for the session
3504    ///
3505    /// Omitted and `null` are equivalent and mean no title is provided.
3506    #[serde_as(deserialize_as = "DefaultOnError")]
3507    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3508    #[serde(default)]
3509    pub title: Option<String>,
3510    /// RFC 3339 timestamp of last activity.
3511    ///
3512    /// Omitted and `null` are equivalent and mean the last activity time is not reported.
3513    #[serde_as(deserialize_as = "DefaultOnError")]
3514    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "format" = "date-time")))]
3515    #[serde(default)]
3516    pub updated_at: Option<String>,
3517    /// **UNSTABLE**
3518    ///
3519    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3520    ///
3521    /// Whether the session is archived.
3522    ///
3523    /// Optional. Omitted and `null` are equivalent and mean the archive state is not reported.
3524    /// Agents that advertise the `session.archive` capability MUST include it on every listed session.
3525    #[cfg(feature = "unstable_session_archive")]
3526    #[serde_as(deserialize_as = "DefaultOnError")]
3527    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3528    #[serde(default)]
3529    pub archived: Option<bool>,
3530    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3531    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3532    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3533    ///
3534    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3535    #[serde_as(deserialize_as = "DefaultOnError")]
3536    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3537    #[serde(default)]
3538    #[serde(rename = "_meta")]
3539    pub meta: Option<Meta>,
3540}
3541
3542impl SessionInfo {
3543    /// Builds [`SessionInfo`] with the required fields set. Optional fields start unset or empty.
3544    #[must_use]
3545    pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
3546        Self {
3547            session_id: session_id.into(),
3548            cwd: cwd.into(),
3549            additional_directories: vec![],
3550            title: None,
3551            updated_at: None,
3552            #[cfg(feature = "unstable_session_archive")]
3553            archived: None,
3554            meta: None,
3555        }
3556    }
3557
3558    /// Additional workspace roots reported for this session. Each path MUST be absolute.
3559    #[must_use]
3560    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
3561    where
3562        I: IntoIterator<Item = P>,
3563        P: Into<AbsolutePath>,
3564    {
3565        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
3566        self
3567    }
3568
3569    /// Human-readable title for the session
3570    #[must_use]
3571    pub fn title(mut self, title: impl IntoOption<String>) -> Self {
3572        self.title = title.into_option();
3573        self
3574    }
3575
3576    /// RFC 3339 timestamp of last activity.
3577    #[must_use]
3578    pub fn updated_at(mut self, updated_at: impl IntoOption<String>) -> Self {
3579        self.updated_at = updated_at.into_option();
3580        self
3581    }
3582
3583    /// **UNSTABLE**
3584    ///
3585    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3586    ///
3587    /// Whether the session is archived.
3588    #[cfg(feature = "unstable_session_archive")]
3589    #[must_use]
3590    pub fn archived(mut self, archived: impl IntoOption<bool>) -> Self {
3591        self.archived = archived.into_option();
3592        self
3593    }
3594
3595    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3596    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3597    /// do not recognize.
3598    ///
3599    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3600    #[must_use]
3601    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3602        self.meta = meta.into_option();
3603        self
3604    }
3605}
3606
3607// Set session title
3608
3609/// **UNSTABLE**
3610///
3611/// This capability is not part of the spec yet, and may be removed or changed at any point.
3612///
3613/// Request parameters for setting the title of a session.
3614///
3615/// Only available if the Agent supports the `session.title` capability.
3616///
3617/// The session does not need to be active on the connection. Any session the Agent would
3618/// return from `session/list` can be retitled. A session that does not exist gets `-32002`.
3619///
3620/// The Agent responds only after it has stored the title. After a successful response, the
3621/// Agent SHOULD NOT replace the title with one it generates automatically.
3622#[cfg(feature = "unstable_session_set_title")]
3623#[serde_as]
3624#[skip_serializing_none]
3625#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3626#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3627#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_TITLE_METHOD_NAME)))]
3628#[serde(rename_all = "camelCase")]
3629#[non_exhaustive]
3630pub struct SetSessionTitleRequest {
3631    /// The ID of the session to retitle.
3632    pub session_id: SessionId,
3633    /// The new title for the session.
3634    ///
3635    /// Required and non-null. Omission and explicit `null` are both invalid. The Agent MAY
3636    /// normalize the title before storing it, for example by trimming whitespace or
3637    /// truncating it. The Agent rejects a title that fails its validation, including one
3638    /// that is empty after normalization, with `-32602`.
3639    pub title: String,
3640    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3641    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3642    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3643    ///
3644    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3645    #[serde_as(deserialize_as = "DefaultOnError")]
3646    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3647    #[serde(default)]
3648    #[serde(rename = "_meta")]
3649    pub meta: Option<Meta>,
3650}
3651
3652#[cfg(feature = "unstable_session_set_title")]
3653impl SetSessionTitleRequest {
3654    /// Builds [`SetSessionTitleRequest`] with the required request fields set. Optional fields start unset or empty.
3655    #[must_use]
3656    pub fn new(session_id: impl Into<SessionId>, title: impl Into<String>) -> Self {
3657        Self {
3658            session_id: session_id.into(),
3659            title: title.into(),
3660            meta: None,
3661        }
3662    }
3663
3664    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3665    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3666    /// do not recognize.
3667    ///
3668    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3669    #[must_use]
3670    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3671        self.meta = meta.into_option();
3672        self
3673    }
3674}
3675
3676/// **UNSTABLE**
3677///
3678/// This capability is not part of the spec yet, and may be removed or changed at any point.
3679///
3680/// Response from setting the title of a session.
3681#[cfg(feature = "unstable_session_set_title")]
3682#[serde_as]
3683#[skip_serializing_none]
3684#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3685#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3686#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_TITLE_METHOD_NAME)))]
3687#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "sessionInfo", "field": "title", "value": "title"}]})))]
3688#[serde(rename_all = "camelCase")]
3689#[non_exhaustive]
3690pub struct SetSessionTitleResponse {
3691    /// The title the Agent stored.
3692    ///
3693    /// This differs from the requested title if the Agent normalized it. Clients SHOULD
3694    /// display this value rather than the one they sent.
3695    pub title: String,
3696    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3697    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3698    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3699    ///
3700    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3701    #[serde_as(deserialize_as = "DefaultOnError")]
3702    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3703    #[serde(default)]
3704    #[serde(rename = "_meta")]
3705    pub meta: Option<Meta>,
3706}
3707
3708#[cfg(feature = "unstable_session_set_title")]
3709impl SetSessionTitleResponse {
3710    /// Builds [`SetSessionTitleResponse`] with the required response fields set. Optional fields start unset or empty.
3711    #[must_use]
3712    pub fn new(title: impl Into<String>) -> Self {
3713        Self {
3714            title: title.into(),
3715            meta: None,
3716        }
3717    }
3718
3719    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3720    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3721    /// do not recognize.
3722    ///
3723    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3724    #[must_use]
3725    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3726        self.meta = meta.into_option();
3727        self
3728    }
3729}
3730
3731// Session config options
3732
3733/// Unique identifier for a session configuration option.
3734#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3735#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3736#[serde(transparent)]
3737#[from(forward)]
3738#[non_exhaustive]
3739pub struct SessionConfigId(pub Arc<str>);
3740
3741impl SessionConfigId {
3742    /// Wraps a protocol string as a typed [`SessionConfigId`].
3743    #[must_use]
3744    pub fn new(id: impl Into<Self>) -> Self {
3745        id.into()
3746    }
3747}
3748
3749/// Unique identifier for a session configuration option value.
3750#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3751#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3752#[serde(transparent)]
3753#[from(forward)]
3754#[non_exhaustive]
3755pub struct SessionConfigValueId(pub Arc<str>);
3756
3757impl SessionConfigValueId {
3758    /// Wraps a protocol string as a typed [`SessionConfigValueId`].
3759    #[must_use]
3760    pub fn new(id: impl Into<Self>) -> Self {
3761        id.into()
3762    }
3763}
3764
3765/// Unique identifier for a session configuration option value group.
3766#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3767#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3768#[serde(transparent)]
3769#[from(forward)]
3770#[non_exhaustive]
3771pub struct SessionConfigGroupId(pub Arc<str>);
3772
3773impl SessionConfigGroupId {
3774    /// Wraps a protocol string as a typed [`SessionConfigGroupId`].
3775    #[must_use]
3776    pub fn new(id: impl Into<Self>) -> Self {
3777        id.into()
3778    }
3779}
3780
3781/// A possible value for a session configuration option.
3782#[serde_as]
3783#[skip_serializing_none]
3784#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3785#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3786#[serde(rename_all = "camelCase")]
3787#[non_exhaustive]
3788pub struct SessionConfigSelectOption {
3789    /// Unique identifier for this option value.
3790    pub value: SessionConfigValueId,
3791    /// Human-readable label for this option value.
3792    pub name: String,
3793    /// Optional description for this option value.
3794    ///
3795    /// Omitted and `null` are equivalent and mean no description is provided.
3796    #[serde_as(deserialize_as = "DefaultOnError")]
3797    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3798    #[serde(default)]
3799    pub description: Option<String>,
3800    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3801    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3802    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3803    ///
3804    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3805    #[serde_as(deserialize_as = "DefaultOnError")]
3806    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3807    #[serde(default)]
3808    #[serde(rename = "_meta")]
3809    pub meta: Option<Meta>,
3810}
3811
3812impl SessionConfigSelectOption {
3813    /// Builds [`SessionConfigSelectOption`] with the required fields set. Optional fields start unset or empty.
3814    #[must_use]
3815    pub fn new(value: impl Into<SessionConfigValueId>, name: impl Into<String>) -> Self {
3816        Self {
3817            value: value.into(),
3818            name: name.into(),
3819            description: None,
3820            meta: None,
3821        }
3822    }
3823
3824    /// Sets or clears the optional `description` field.
3825    #[must_use]
3826    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
3827        self.description = description.into_option();
3828        self
3829    }
3830
3831    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3832    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3833    /// do not recognize.
3834    ///
3835    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3836    #[must_use]
3837    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3838        self.meta = meta.into_option();
3839        self
3840    }
3841}
3842
3843/// A group of possible values for a session configuration option.
3844#[serde_as]
3845#[skip_serializing_none]
3846#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3847#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3848#[serde(rename_all = "camelCase")]
3849#[non_exhaustive]
3850pub struct SessionConfigSelectGroup {
3851    /// Identifier for this group. MUST be unique within the option.
3852    pub group_id: SessionConfigGroupId,
3853    /// Human-readable label for this group.
3854    pub name: String,
3855    /// The set of option values in this group. MUST contain at least one value.
3856    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
3857    #[cfg_attr(feature = "schemars", schemars(length(min = 1), extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3858    pub options: Vec<SessionConfigSelectOption>,
3859    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3860    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3861    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3862    ///
3863    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3864    #[serde_as(deserialize_as = "DefaultOnError")]
3865    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3866    #[serde(default)]
3867    #[serde(rename = "_meta")]
3868    pub meta: Option<Meta>,
3869}
3870
3871impl SessionConfigSelectGroup {
3872    /// Builds [`SessionConfigSelectGroup`] with the required fields set. Optional fields start unset or empty.
3873    #[must_use]
3874    pub fn new(
3875        group_id: impl Into<SessionConfigGroupId>,
3876        name: impl Into<String>,
3877        options: Vec<SessionConfigSelectOption>,
3878    ) -> Self {
3879        Self {
3880            group_id: group_id.into(),
3881            name: name.into(),
3882            options,
3883            meta: None,
3884        }
3885    }
3886
3887    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3888    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3889    /// do not recognize.
3890    ///
3891    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3892    #[must_use]
3893    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3894        self.meta = meta.into_option();
3895        self
3896    }
3897}
3898
3899/// Possible values for a session configuration option.
3900#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3901#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3902#[serde(untagged)]
3903#[non_exhaustive]
3904pub enum SessionConfigSelectOptions {
3905    /// A flat list of options with no grouping.
3906    Ungrouped(
3907        #[cfg_attr(feature = "schemars", schemars(length(min = 1)))] Vec<SessionConfigSelectOption>,
3908    ),
3909    /// A list of options grouped under headers.
3910    Grouped(
3911        #[cfg_attr(feature = "schemars", schemars(length(min = 1)))] Vec<SessionConfigSelectGroup>,
3912    ),
3913}
3914
3915impl From<Vec<SessionConfigSelectOption>> for SessionConfigSelectOptions {
3916    fn from(options: Vec<SessionConfigSelectOption>) -> Self {
3917        SessionConfigSelectOptions::Ungrouped(options)
3918    }
3919}
3920
3921impl From<Vec<SessionConfigSelectGroup>> for SessionConfigSelectOptions {
3922    fn from(groups: Vec<SessionConfigSelectGroup>) -> Self {
3923        SessionConfigSelectOptions::Grouped(groups)
3924    }
3925}
3926
3927/// A single-value selector (dropdown) session configuration option payload.
3928#[skip_serializing_none]
3929#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3930#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3931#[serde(rename_all = "camelCase")]
3932#[non_exhaustive]
3933pub struct SessionConfigSelect {
3934    /// The currently selected value. MUST be one of the `value`s in `options`.
3935    pub current_value: SessionConfigValueId,
3936    /// The set of selectable options. MUST contain at least one value, and each `value` MUST be
3937    /// unique within the option, including across groups.
3938    pub options: SessionConfigSelectOptions,
3939}
3940
3941impl SessionConfigSelect {
3942    /// Builds [`SessionConfigSelect`] with the required fields set. Optional fields start unset or empty.
3943    #[must_use]
3944    pub fn new(
3945        current_value: impl Into<SessionConfigValueId>,
3946        options: impl Into<SessionConfigSelectOptions>,
3947    ) -> Self {
3948        Self {
3949            current_value: current_value.into(),
3950            options: options.into(),
3951        }
3952    }
3953}
3954
3955/// A boolean on/off toggle session configuration option payload.
3956#[skip_serializing_none]
3957#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3958#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3959#[serde(rename_all = "camelCase")]
3960#[non_exhaustive]
3961pub struct SessionConfigBoolean {
3962    /// The current value of the boolean option.
3963    pub current_value: bool,
3964}
3965
3966impl SessionConfigBoolean {
3967    /// Builds [`SessionConfigBoolean`] with the required fields set. Optional fields start unset or empty.
3968    #[must_use]
3969    pub fn new(current_value: bool) -> Self {
3970        Self { current_value }
3971    }
3972}
3973
3974/// Semantic category for a session configuration option.
3975///
3976/// This is intended to help Clients distinguish broadly common selectors (e.g. model selector vs
3977/// session mode selector vs thought/reasoning level) for UX purposes (keyboard shortcuts, icons,
3978/// placement). It MUST NOT be required for correctness. Clients MUST handle missing or unknown
3979/// categories gracefully.
3980///
3981/// Category names beginning with `_` are free for custom use, like other ACP extension methods.
3982/// Category names that do not begin with `_` are reserved for the ACP spec.
3983#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3984#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3985#[serde(rename_all = "snake_case")]
3986#[non_exhaustive]
3987pub enum SessionConfigOptionCategory {
3988    /// Session mode selector.
3989    Mode,
3990    /// Model selector.
3991    Model,
3992    /// Model-related configuration parameter.
3993    ModelConfig,
3994    /// **UNSTABLE**
3995    ///
3996    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3997    ///
3998    /// Response speed selector, such as a fast mode toggle.
3999    #[cfg(feature = "unstable_speed_config_category")]
4000    Speed,
4001    /// Thought/reasoning level selector.
4002    ThoughtLevel,
4003    /// Custom or future category.
4004    ///
4005    /// Values beginning with `_` are reserved for implementation-specific
4006    /// extensions. Unknown values that do not begin with `_` are reserved for
4007    /// future ACP variants.
4008    #[serde(untagged)]
4009    Other(String),
4010}
4011
4012/// Type-specific session configuration option payload.
4013#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4014#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4015#[serde(tag = "type", rename_all = "snake_case")]
4016#[non_exhaustive]
4017pub enum SessionConfigKind {
4018    /// Single-value selector (dropdown).
4019    Select(SessionConfigSelect),
4020    /// Boolean on/off toggle.
4021    Boolean(SessionConfigBoolean),
4022    /// Custom or future session configuration option payload.
4023    ///
4024    /// Values beginning with `_` are reserved for implementation-specific
4025    /// extensions. Unknown values that do not begin with `_` are reserved for
4026    /// future ACP variants.
4027    ///
4028    /// Clients that do not understand this option type SHOULD preserve the raw
4029    /// payload when storing, replaying, proxying, or forwarding configuration
4030    /// data, and otherwise ignore the option. The Agent keeps using its `currentValue`.
4031    #[serde(untagged)]
4032    Other(OtherSessionConfigKind),
4033}
4034
4035/// Custom or future session configuration option payload.
4036#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4037#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4038#[cfg_attr(feature = "schemars", schemars(inline))]
4039#[cfg_attr(feature = "schemars", schemars(transform = other_session_config_kind_schema))]
4040#[serde(rename_all = "camelCase")]
4041#[non_exhaustive]
4042pub struct OtherSessionConfigKind {
4043    /// Custom or future session configuration option type.
4044    ///
4045    /// Values beginning with `_` are reserved for implementation-specific
4046    /// extensions. Unknown values that do not begin with `_` are reserved for
4047    /// future ACP variants.
4048    #[serde(rename = "type")]
4049    pub type_: String,
4050    /// Additional fields from the unknown session configuration option payload.
4051    #[serde(flatten)]
4052    pub fields: IndexMap<String, serde_json::Value>,
4053}
4054
4055impl OtherSessionConfigKind {
4056    /// Builds [`OtherSessionConfigKind`] from an unknown discriminator and preserves the remaining extension fields.
4057    #[must_use]
4058    pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
4059        fields.shift_remove("type");
4060        fields.shift_remove("_meta");
4061        Self {
4062            type_: type_.into(),
4063            fields,
4064        }
4065    }
4066}
4067
4068impl<'de> Deserialize<'de> for OtherSessionConfigKind {
4069    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4070    where
4071        D: serde::Deserializer<'de>,
4072    {
4073        let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4074        let type_ = fields
4075            .shift_remove("type")
4076            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4077        let serde_json::Value::String(type_) = type_ else {
4078            return Err(serde::de::Error::custom("`type` must be a string"));
4079        };
4080
4081        if is_known_session_config_kind_type(&type_) {
4082            return Err(serde::de::Error::custom(format!(
4083                "known session configuration option `{type_}` did not match its schema"
4084            )));
4085        }
4086
4087        Ok(Self { type_, fields })
4088    }
4089}
4090
4091fn is_known_session_config_kind_type(type_: &str) -> bool {
4092    matches!(type_, "select" | "boolean")
4093}
4094
4095#[cfg(feature = "schemars")]
4096fn other_session_config_kind_schema(schema: &mut Schema) {
4097    super::schema_util::reject_known_string_discriminators(schema, "type", &["select", "boolean"]);
4098}
4099
4100/// A session configuration option selector and its current state.
4101#[serde_as]
4102#[skip_serializing_none]
4103#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4104#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4105#[serde(rename_all = "camelCase")]
4106#[non_exhaustive]
4107pub struct SessionConfigOption {
4108    /// Identifier for the configuration option. MUST be unique within `configOptions`.
4109    pub config_id: SessionConfigId,
4110    /// Human-readable label for the option.
4111    pub name: String,
4112    /// Optional description for the Client to display to the user.
4113    ///
4114    /// Omitted and `null` are equivalent and mean no description is provided.
4115    #[serde_as(deserialize_as = "DefaultOnError")]
4116    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4117    #[serde(default)]
4118    pub description: Option<String>,
4119    /// Optional semantic category for this option (UX only).
4120    ///
4121    /// Omitted and `null` are equivalent and mean no category 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 category: Option<SessionConfigOptionCategory>,
4126    /// Type-specific fields for this configuration option.
4127    #[serde(flatten)]
4128    pub kind: SessionConfigKind,
4129    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4130    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4131    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4132    ///
4133    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4134    #[serde_as(deserialize_as = "DefaultOnError")]
4135    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4136    #[serde(default)]
4137    #[serde(rename = "_meta")]
4138    pub meta: Option<Meta>,
4139}
4140
4141impl SessionConfigOption {
4142    /// Builds [`SessionConfigOption`] with the required fields set. Optional fields start unset or empty.
4143    #[must_use]
4144    pub fn new(
4145        config_id: impl Into<SessionConfigId>,
4146        name: impl Into<String>,
4147        kind: SessionConfigKind,
4148    ) -> Self {
4149        Self {
4150            config_id: config_id.into(),
4151            name: name.into(),
4152            description: None,
4153            category: None,
4154            kind,
4155            meta: None,
4156        }
4157    }
4158
4159    /// Builds a select-style session configuration option with its current value and choices.
4160    #[must_use]
4161    pub fn select(
4162        config_id: impl Into<SessionConfigId>,
4163        name: impl Into<String>,
4164        current_value: impl Into<SessionConfigValueId>,
4165        options: impl Into<SessionConfigSelectOptions>,
4166    ) -> Self {
4167        Self::new(
4168            config_id,
4169            name,
4170            SessionConfigKind::Select(SessionConfigSelect::new(current_value, options)),
4171        )
4172    }
4173
4174    /// Builds a boolean-style session configuration option with its current value.
4175    #[must_use]
4176    pub fn boolean(
4177        config_id: impl Into<SessionConfigId>,
4178        name: impl Into<String>,
4179        current_value: bool,
4180    ) -> Self {
4181        Self::new(
4182            config_id,
4183            name,
4184            SessionConfigKind::Boolean(SessionConfigBoolean::new(current_value)),
4185        )
4186    }
4187
4188    /// Sets or clears the optional `description` field.
4189    #[must_use]
4190    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
4191        self.description = description.into_option();
4192        self
4193    }
4194
4195    /// Sets or clears the optional `category` field.
4196    #[must_use]
4197    pub fn category(mut self, category: impl IntoOption<SessionConfigOptionCategory>) -> Self {
4198        self.category = category.into_option();
4199        self
4200    }
4201
4202    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4203    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4204    /// do not recognize.
4205    ///
4206    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4207    #[must_use]
4208    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4209        self.meta = meta.into_option();
4210        self
4211    }
4212}
4213
4214/// The value to set for a session configuration option.
4215///
4216/// The `type` field acts as the discriminator in the serialized JSON form.
4217///
4218/// The `type` discriminator describes the *shape* of the value, not the option
4219/// kind. For example every option kind that picks from a list of ids
4220/// (`select`, `radio`, …) would use [`Id`](Self::Id), while a future freeform
4221/// text option would get its own variant.
4222#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4223#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4224#[serde(tag = "type", rename_all = "snake_case")]
4225#[non_exhaustive]
4226pub enum SessionConfigOptionValue {
4227    /// A `SessionConfigValueId` string value (`type: "id"`).
4228    Id {
4229        /// The value ID.
4230        value: SessionConfigValueId,
4231    },
4232    /// A boolean value (`type: "boolean"`).
4233    Boolean {
4234        /// The boolean value.
4235        value: bool,
4236    },
4237    /// Custom or future session configuration option value payload.
4238    ///
4239    /// Values beginning with `_` are reserved for implementation-specific
4240    /// extensions. Unknown values that do not begin with `_` are reserved for
4241    /// future ACP variants.
4242    ///
4243    /// Agents MUST reject a `session/set_config_option` request with a value type
4244    /// they do not support with `-32602`.
4245    #[serde(untagged)]
4246    Other(Box<OtherSessionConfigOptionValue>),
4247}
4248
4249/// Custom or future session configuration option value payload.
4250#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4251#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4252#[cfg_attr(feature = "schemars", schemars(inline))]
4253#[cfg_attr(feature = "schemars", schemars(transform = other_session_config_option_value_schema))]
4254#[serde(rename_all = "camelCase")]
4255#[non_exhaustive]
4256pub struct OtherSessionConfigOptionValue {
4257    /// Custom or future session configuration option value type.
4258    ///
4259    /// Values beginning with `_` are reserved for implementation-specific
4260    /// extensions. Unknown values that do not begin with `_` are reserved for
4261    /// future ACP variants.
4262    #[serde(rename = "type")]
4263    pub type_: String,
4264    /// Raw value payload for the custom or future value type.
4265    pub value: serde_json::Value,
4266    /// Additional fields from the unknown session configuration option value payload.
4267    #[serde(flatten)]
4268    pub fields: IndexMap<String, serde_json::Value>,
4269}
4270
4271impl OtherSessionConfigOptionValue {
4272    /// Builds [`OtherSessionConfigOptionValue`] from an unknown discriminator and preserves the remaining extension fields.
4273    #[must_use]
4274    pub fn new(
4275        type_: impl Into<String>,
4276        value: serde_json::Value,
4277        mut fields: IndexMap<String, serde_json::Value>,
4278    ) -> Self {
4279        fields.shift_remove("type");
4280        fields.shift_remove("value");
4281        fields.shift_remove("_meta");
4282        Self {
4283            type_: type_.into(),
4284            value,
4285            fields,
4286        }
4287    }
4288}
4289
4290impl<'de> Deserialize<'de> for OtherSessionConfigOptionValue {
4291    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4292    where
4293        D: serde::Deserializer<'de>,
4294    {
4295        let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4296        let type_ = fields
4297            .shift_remove("type")
4298            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4299        let serde_json::Value::String(type_) = type_ else {
4300            return Err(serde::de::Error::custom("`type` must be a string"));
4301        };
4302
4303        if is_known_session_config_option_value_type(&type_) {
4304            return Err(serde::de::Error::custom(format!(
4305                "known session configuration option value `{type_}` did not match its schema"
4306            )));
4307        }
4308
4309        let value = fields
4310            .shift_remove("value")
4311            .ok_or_else(|| serde::de::Error::missing_field("value"))?;
4312
4313        Ok(Self {
4314            type_,
4315            value,
4316            fields,
4317        })
4318    }
4319}
4320
4321impl<'de> Deserialize<'de> for SessionConfigOptionValue {
4322    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4323    where
4324        D: serde::Deserializer<'de>,
4325    {
4326        let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4327        let type_ = fields.shift_remove("type");
4328        let value = fields
4329            .shift_remove("value")
4330            .ok_or_else(|| serde::de::Error::missing_field("value"))?;
4331
4332        let type_ = type_.ok_or_else(|| serde::de::Error::missing_field("type"))?;
4333
4334        let serde_json::Value::String(type_) = type_ else {
4335            return Err(serde::de::Error::custom("`type` must be a string"));
4336        };
4337
4338        match type_.as_str() {
4339            "id" => {
4340                let value = serde_json::from_value(value).map_err(|error| {
4341                    serde::de::Error::custom(format!(
4342                        "`value` must be a string for `type: id`: {error}"
4343                    ))
4344                })?;
4345                Ok(Self::Id { value })
4346            }
4347            "boolean" => {
4348                let value = serde_json::from_value(value).map_err(|error| {
4349                    serde::de::Error::custom(format!(
4350                        "`value` must be a boolean for `type: boolean`: {error}"
4351                    ))
4352                })?;
4353                Ok(Self::Boolean { value })
4354            }
4355            _ => Ok(OtherSessionConfigOptionValue {
4356                type_,
4357                value,
4358                fields,
4359            }
4360            .into()),
4361        }
4362    }
4363}
4364
4365fn is_known_session_config_option_value_type(type_: &str) -> bool {
4366    matches!(type_, "id" | "boolean")
4367}
4368
4369#[cfg(feature = "schemars")]
4370fn other_session_config_option_value_schema(schema: &mut Schema) {
4371    super::schema_util::reject_known_string_discriminators(schema, "type", &["id", "boolean"]);
4372}
4373
4374impl SessionConfigOptionValue {
4375    /// Create an id option value (used by `select` and other id-based option types).
4376    #[must_use]
4377    pub fn id(id: impl Into<SessionConfigValueId>) -> Self {
4378        Self::Id { value: id.into() }
4379    }
4380
4381    /// Create a boolean option value.
4382    #[must_use]
4383    pub fn boolean(val: bool) -> Self {
4384        Self::Boolean { value: val }
4385    }
4386
4387    /// Return the inner [`SessionConfigValueId`] if this is a
4388    /// [`Id`](Self::Id) value.
4389    #[must_use]
4390    pub fn as_id(&self) -> Option<&SessionConfigValueId> {
4391        match self {
4392            Self::Id { value } => Some(value),
4393            _ => None,
4394        }
4395    }
4396
4397    /// Return the inner [`bool`] if this is a [`Boolean`](Self::Boolean) value.
4398    #[must_use]
4399    pub fn as_bool(&self) -> Option<bool> {
4400        match self {
4401            Self::Boolean { value } => Some(*value),
4402            _ => None,
4403        }
4404    }
4405}
4406
4407impl From<SessionConfigValueId> for SessionConfigOptionValue {
4408    fn from(value: SessionConfigValueId) -> Self {
4409        Self::Id { value }
4410    }
4411}
4412
4413impl From<bool> for SessionConfigOptionValue {
4414    fn from(value: bool) -> Self {
4415        Self::Boolean { value }
4416    }
4417}
4418
4419impl From<OtherSessionConfigOptionValue> for SessionConfigOptionValue {
4420    fn from(value: OtherSessionConfigOptionValue) -> Self {
4421        Self::Other(Box::new(value))
4422    }
4423}
4424
4425impl From<&str> for SessionConfigOptionValue {
4426    fn from(value: &str) -> Self {
4427        Self::Id {
4428            value: SessionConfigValueId::new(value),
4429        }
4430    }
4431}
4432
4433/// Request parameters for setting a session configuration option.
4434///
4435/// Agents MUST support this method for any session the Client created or resumed
4436/// where they advertise config options. For a child session, the child's
4437/// capabilities decide whether the Client can send it, and none defined today
4438/// permits it.
4439/// Agents MUST reject an unknown `configId` or invalid value with `-32602` and leave the
4440/// configuration unchanged.
4441///
4442/// See protocol docs: [Session Config Options](https://agentclientprotocol.com/protocol/v2/session-config-options#setting-a-config-option)
4443#[serde_as]
4444#[skip_serializing_none]
4445#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4446#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4447#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_CONFIG_OPTION_METHOD_NAME)))]
4448#[serde(rename_all = "camelCase")]
4449#[non_exhaustive]
4450pub struct SetSessionConfigOptionRequest {
4451    /// The ID of the session to set the configuration option for.
4452    pub session_id: SessionId,
4453    /// The ID of the configuration option to set.
4454    pub config_id: SessionConfigId,
4455    /// The value to set, including a `type` discriminator and the raw `value`.
4456    ///
4457    /// Payloads MUST send `type: "id"` for id-based options.
4458    #[serde(flatten)]
4459    pub value: SessionConfigOptionValue,
4460    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4461    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4462    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4463    ///
4464    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4465    #[serde_as(deserialize_as = "DefaultOnError")]
4466    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4467    #[serde(default)]
4468    #[serde(rename = "_meta")]
4469    pub meta: Option<Meta>,
4470}
4471
4472impl SetSessionConfigOptionRequest {
4473    /// Builds [`SetSessionConfigOptionRequest`] with the required request fields set. Optional fields start unset or empty.
4474    #[must_use]
4475    pub fn new(
4476        session_id: impl Into<SessionId>,
4477        config_id: impl Into<SessionConfigId>,
4478        value: impl Into<SessionConfigOptionValue>,
4479    ) -> Self {
4480        Self {
4481            session_id: session_id.into(),
4482            config_id: config_id.into(),
4483            value: value.into(),
4484            meta: None,
4485        }
4486    }
4487
4488    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4489    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4490    /// do not recognize.
4491    ///
4492    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4493    #[must_use]
4494    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4495        self.meta = meta.into_option();
4496        self
4497    }
4498}
4499
4500/// Response to `session/set_config_option` method.
4501#[serde_as]
4502#[skip_serializing_none]
4503#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4504#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4505#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_CONFIG_OPTION_METHOD_NAME)))]
4506#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}]})))]
4507#[serde(rename_all = "camelCase")]
4508#[non_exhaustive]
4509pub struct SetSessionConfigOptionResponse {
4510    /// The full set of configuration options and their current values.
4511    #[serde_as(deserialize_as = "VecSkipError<_>")]
4512    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
4513    pub config_options: Vec<SessionConfigOption>,
4514    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4515    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4516    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4517    ///
4518    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4519    #[serde_as(deserialize_as = "DefaultOnError")]
4520    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4521    #[serde(default)]
4522    #[serde(rename = "_meta")]
4523    pub meta: Option<Meta>,
4524}
4525
4526impl SetSessionConfigOptionResponse {
4527    /// Builds [`SetSessionConfigOptionResponse`] with the required response fields set. Optional fields start unset or empty.
4528    #[must_use]
4529    pub fn new(config_options: Vec<SessionConfigOption>) -> Self {
4530        Self {
4531            config_options,
4532            meta: None,
4533        }
4534    }
4535
4536    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4537    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4538    /// do not recognize.
4539    ///
4540    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4541    #[must_use]
4542    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4543        self.meta = meta.into_option();
4544        self
4545    }
4546}
4547
4548// MCP
4549
4550/// Configuration for connecting to an MCP (Model Context Protocol) server.
4551///
4552/// MCP servers provide tools and context that the Agent can use when
4553/// processing prompts.
4554///
4555/// See protocol docs: [MCP Servers](https://agentclientprotocol.com/protocol/v2/session-setup#mcp-servers)
4556#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4557#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4558#[serde(tag = "type", rename_all = "snake_case")]
4559#[non_exhaustive]
4560pub enum McpServer {
4561    /// HTTP transport configuration
4562    ///
4563    /// Only available when the Agent capabilities include `session.mcp.http`.
4564    Http(McpServerHttp),
4565    /// **UNSTABLE**
4566    ///
4567    /// This capability is not part of the spec yet, and may be removed or changed at any point.
4568    ///
4569    /// ACP transport configuration
4570    ///
4571    /// Only available when the Agent capabilities include `session.mcp.acp`.
4572    /// The MCP server is provided by an ACP component and communicates over the ACP channel.
4573    #[cfg(feature = "unstable_mcp_over_acp")]
4574    Acp(McpServerAcp),
4575    /// Stdio transport configuration
4576    ///
4577    /// Only available when the Agent capabilities include `session.mcp.stdio`.
4578    Stdio(McpServerStdio),
4579    /// Custom or future MCP server transport configuration.
4580    ///
4581    /// Values beginning with `_` are reserved for implementation-specific
4582    /// extensions. Unknown values that do not begin with `_` are reserved for
4583    /// future ACP variants.
4584    ///
4585    /// Receivers that do not understand this transport SHOULD preserve the raw
4586    /// payload when storing, replaying, proxying, or forwarding session setup
4587    /// data. Agents MUST reject a request with a transport they do not support
4588    /// with `-32602`.
4589    #[serde(untagged)]
4590    Other(OtherMcpServer),
4591}
4592
4593/// Custom or future MCP server transport payload.
4594#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4595#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4596#[cfg_attr(feature = "schemars", schemars(inline))]
4597#[cfg_attr(feature = "schemars", schemars(transform = other_mcp_server_schema))]
4598#[serde(rename_all = "camelCase")]
4599#[non_exhaustive]
4600pub struct OtherMcpServer {
4601    /// Custom or future MCP server transport type.
4602    ///
4603    /// Values beginning with `_` are reserved for implementation-specific
4604    /// extensions. Unknown values that do not begin with `_` are reserved for
4605    /// future ACP variants.
4606    #[serde(rename = "type")]
4607    pub type_: String,
4608    /// Additional fields from the unknown MCP server transport payload.
4609    #[serde(flatten)]
4610    pub fields: IndexMap<String, serde_json::Value>,
4611}
4612
4613impl OtherMcpServer {
4614    /// Builds [`OtherMcpServer`] from an unknown discriminator and preserves the remaining extension fields.
4615    #[must_use]
4616    pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
4617        fields.shift_remove("type");
4618        Self {
4619            type_: type_.into(),
4620            fields,
4621        }
4622    }
4623}
4624
4625impl<'de> Deserialize<'de> for OtherMcpServer {
4626    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4627    where
4628        D: serde::Deserializer<'de>,
4629    {
4630        let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4631        let type_ = fields
4632            .shift_remove("type")
4633            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4634        let serde_json::Value::String(type_) = type_ else {
4635            return Err(serde::de::Error::custom("`type` must be a string"));
4636        };
4637
4638        if is_known_mcp_server_type(&type_) {
4639            return Err(serde::de::Error::custom(format!(
4640                "known MCP server transport `{type_}` did not match its schema"
4641            )));
4642        }
4643
4644        Ok(Self { type_, fields })
4645    }
4646}
4647
4648fn is_known_mcp_server_type(type_: &str) -> bool {
4649    match type_ {
4650        "http" | "stdio" => true,
4651        #[cfg(feature = "unstable_mcp_over_acp")]
4652        "acp" => true,
4653        _ => false,
4654    }
4655}
4656
4657#[cfg(feature = "schemars")]
4658fn other_mcp_server_schema(schema: &mut Schema) {
4659    super::schema_util::reject_known_string_discriminators(
4660        schema,
4661        "type",
4662        &[
4663            "http",
4664            "stdio",
4665            #[cfg(feature = "unstable_mcp_over_acp")]
4666            "acp",
4667        ],
4668    );
4669}
4670
4671/// HTTP transport configuration for MCP.
4672#[serde_as]
4673#[skip_serializing_none]
4674#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4675#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4676#[serde(rename_all = "camelCase")]
4677#[non_exhaustive]
4678pub struct McpServerHttp {
4679    /// Human-readable name identifying this MCP server. MUST be unique within `mcpServers`.
4680    ///
4681    /// Agents reject a request with a duplicate `name` with `-32602`.
4682    pub name: String,
4683    /// URL to the MCP server.
4684    #[cfg_attr(feature = "schemars", schemars(url))]
4685    pub url: String,
4686    /// HTTP headers to set when making requests to the MCP server. Headers the MCP transport
4687    /// defines are owned by the transport, and Agents use the transport's values for them.
4688    #[serde_as(deserialize_as = "DefaultOnNull")]
4689    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4690    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4691    pub headers: Vec<HttpHeader>,
4692    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4693    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4694    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4695    ///
4696    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4697    #[serde_as(deserialize_as = "DefaultOnError")]
4698    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4699    #[serde(default)]
4700    #[serde(rename = "_meta")]
4701    pub meta: Option<Meta>,
4702}
4703
4704impl McpServerHttp {
4705    /// Builds [`McpServerHttp`] with the required fields set. Optional fields start unset or empty.
4706    #[must_use]
4707    pub fn new(name: impl Into<String>, url: impl Into<String>) -> Self {
4708        Self {
4709            name: name.into(),
4710            url: url.into(),
4711            headers: Vec::new(),
4712            meta: None,
4713        }
4714    }
4715
4716    /// HTTP headers to set when making requests to the MCP server. Headers the MCP transport
4717    /// defines are owned by the transport, and Agents use the transport's values for them.
4718    #[must_use]
4719    pub fn headers(mut self, headers: Vec<HttpHeader>) -> Self {
4720        self.headers = headers;
4721        self
4722    }
4723
4724    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4725    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4726    /// do not recognize.
4727    ///
4728    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4729    #[must_use]
4730    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4731        self.meta = meta.into_option();
4732        self
4733    }
4734}
4735
4736/// **UNSTABLE**
4737///
4738/// This capability is not part of the spec yet, and may be removed or changed at any point.
4739///
4740/// Unique identifier for an MCP server using the ACP transport.
4741///
4742/// The value is opaque and generated by the ACP component providing the MCP server. It is
4743/// used by `mcp/message` to route requests to the component that declared the server.
4744#[cfg(feature = "unstable_mcp_over_acp")]
4745#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4746#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
4747#[serde(transparent)]
4748#[from(forward)]
4749#[non_exhaustive]
4750pub struct McpServerAcpId(pub Arc<str>);
4751
4752#[cfg(feature = "unstable_mcp_over_acp")]
4753impl McpServerAcpId {
4754    /// Wraps a protocol string as a typed [`McpServerAcpId`].
4755    #[must_use]
4756    pub fn new(id: impl Into<Self>) -> Self {
4757        id.into()
4758    }
4759}
4760
4761/// **UNSTABLE**
4762///
4763/// This capability is not part of the spec yet, and may be removed or changed at any point.
4764///
4765/// ACP transport configuration for MCP.
4766///
4767/// The MCP server is provided by an ACP component and communicates over the ACP channel
4768/// using `mcp/message`.
4769#[serde_as]
4770#[skip_serializing_none]
4771#[cfg(feature = "unstable_mcp_over_acp")]
4772#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4773#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4774#[serde(rename_all = "camelCase")]
4775#[non_exhaustive]
4776pub struct McpServerAcp {
4777    /// Human-readable name identifying this MCP server. MUST be unique within `mcpServers`.
4778    ///
4779    /// Agents reject a request with a duplicate `name` with `-32602`.
4780    pub name: String,
4781    /// Unique identifier for this MCP server, generated by the component providing it.
4782    ///
4783    /// Providers MUST NOT reuse an ID for multiple ACP-transport MCP servers that are visible
4784    /// on the same ACP connection.
4785    pub server_id: McpServerAcpId,
4786    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4787    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4788    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4789    ///
4790    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4791    #[serde_as(deserialize_as = "DefaultOnError")]
4792    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4793    #[serde(default)]
4794    #[serde(rename = "_meta")]
4795    pub meta: Option<Meta>,
4796}
4797
4798#[cfg(feature = "unstable_mcp_over_acp")]
4799impl McpServerAcp {
4800    /// Builds [`McpServerAcp`] with the required fields set. Optional fields start unset or empty.
4801    #[must_use]
4802    pub fn new(name: impl Into<String>, server_id: impl Into<McpServerAcpId>) -> Self {
4803        Self {
4804            name: name.into(),
4805            server_id: server_id.into(),
4806            meta: None,
4807        }
4808    }
4809
4810    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4811    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4812    /// do not recognize.
4813    ///
4814    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4815    #[must_use]
4816    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4817        self.meta = meta.into_option();
4818        self
4819    }
4820}
4821
4822/// Stdio transport configuration for MCP.
4823#[serde_as]
4824#[skip_serializing_none]
4825#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4826#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4827#[serde(rename_all = "camelCase")]
4828#[non_exhaustive]
4829pub struct McpServerStdio {
4830    /// Human-readable name identifying this MCP server. MUST be unique within `mcpServers`.
4831    ///
4832    /// Agents reject a request with a duplicate `name` with `-32602`.
4833    pub name: String,
4834    /// Path to the MCP server executable. Must be an absolute path.
4835    ///
4836    /// Agents reject a request with a relative `command` with `-32602`.
4837    pub command: AbsolutePath,
4838    /// Command-line arguments to pass to the MCP server.
4839    #[serde_as(deserialize_as = "DefaultOnNull")]
4840    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4841    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4842    pub args: Vec<String>,
4843    /// Environment variables to set when launching the MCP server. Names SHOULD be unique.
4844    /// Agents MAY reject duplicates with `-32602`, and otherwise the last entry wins.
4845    #[serde_as(deserialize_as = "DefaultOnNull")]
4846    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4847    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4848    pub env: Vec<EnvVariable>,
4849    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4850    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4851    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4852    ///
4853    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4854    #[serde_as(deserialize_as = "DefaultOnError")]
4855    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4856    #[serde(default)]
4857    #[serde(rename = "_meta")]
4858    pub meta: Option<Meta>,
4859}
4860
4861impl McpServerStdio {
4862    /// Builds [`McpServerStdio`] with the required fields set. Optional fields start unset or empty.
4863    #[must_use]
4864    pub fn new(name: impl Into<String>, command: impl Into<AbsolutePath>) -> Self {
4865        Self {
4866            name: name.into(),
4867            command: command.into(),
4868            args: Vec::new(),
4869            env: Vec::new(),
4870            meta: None,
4871        }
4872    }
4873
4874    /// Command-line arguments to pass to the MCP server.
4875    #[must_use]
4876    pub fn args(mut self, args: Vec<String>) -> Self {
4877        self.args = args;
4878        self
4879    }
4880
4881    /// Environment variables to set when launching the MCP server. Names SHOULD be unique.
4882    /// Agents MAY reject duplicates with `-32602`, and otherwise the last entry wins.
4883    #[must_use]
4884    pub fn env(mut self, env: Vec<EnvVariable>) -> Self {
4885        self.env = env;
4886        self
4887    }
4888
4889    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4890    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4891    /// do not recognize.
4892    ///
4893    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4894    #[must_use]
4895    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4896        self.meta = meta.into_option();
4897        self
4898    }
4899}
4900
4901/// An environment variable to set when launching a process.
4902#[serde_as]
4903#[skip_serializing_none]
4904#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4905#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4906#[serde(rename_all = "camelCase")]
4907#[non_exhaustive]
4908pub struct EnvVariable {
4909    /// The name of the environment variable.
4910    pub name: String,
4911    /// The value to set for the environment variable.
4912    pub value: String,
4913    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4914    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4915    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4916    ///
4917    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4918    #[serde_as(deserialize_as = "DefaultOnError")]
4919    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4920    #[serde(default)]
4921    #[serde(rename = "_meta")]
4922    pub meta: Option<Meta>,
4923}
4924
4925impl EnvVariable {
4926    /// Builds [`EnvVariable`] with the required fields set. Optional fields start unset or empty.
4927    #[must_use]
4928    pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
4929        Self {
4930            name: name.into(),
4931            value: value.into(),
4932            meta: None,
4933        }
4934    }
4935
4936    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4937    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4938    /// do not recognize.
4939    ///
4940    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4941    #[must_use]
4942    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4943        self.meta = meta.into_option();
4944        self
4945    }
4946}
4947
4948/// An HTTP header to set when making requests to the MCP server.
4949#[serde_as]
4950#[skip_serializing_none]
4951#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4952#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4953#[serde(rename_all = "camelCase")]
4954#[non_exhaustive]
4955pub struct HttpHeader {
4956    /// The name of the HTTP header.
4957    pub name: String,
4958    /// The value to set for the HTTP header.
4959    pub value: String,
4960    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4961    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4962    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4963    ///
4964    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4965    #[serde_as(deserialize_as = "DefaultOnError")]
4966    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4967    #[serde(default)]
4968    #[serde(rename = "_meta")]
4969    pub meta: Option<Meta>,
4970}
4971
4972impl HttpHeader {
4973    /// Builds [`HttpHeader`] with the required fields set. Optional fields start unset or empty.
4974    #[must_use]
4975    pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
4976        Self {
4977            name: name.into(),
4978            value: value.into(),
4979            meta: None,
4980        }
4981    }
4982
4983    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4984    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4985    /// do not recognize.
4986    ///
4987    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4988    #[must_use]
4989    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4990        self.meta = meta.into_option();
4991        self
4992    }
4993}
4994
4995// System prompt
4996
4997/// Client-provided system-level instructions for a session.
4998///
4999/// Clients MUST only send this when the Agent advertises
5000/// `session.systemPrompt`. Agents that cannot apply it, for example because of
5001/// an unadvertised mode or an unsupported content block type, MUST return an
5002/// error instead of creating or resuming the session.
5003#[serde_as]
5004#[skip_serializing_none]
5005#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5006#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5007#[serde(rename_all = "camelCase")]
5008#[non_exhaustive]
5009pub struct SystemPrompt {
5010    /// How the Agent combines `content` with its own instructions.
5011    ///
5012    /// Required. Agents MUST return an error for a mode they do not support rather than
5013    /// treating it as `append` or `override`.
5014    pub mode: SystemPromptMode,
5015    /// The system prompt content.
5016    ///
5017    /// Agents advertising the capability MUST accept `text` content blocks.
5018    /// Clients MUST NOT send other content block types until a future
5019    /// capability allows them, and Agents MUST return an error for content
5020    /// blocks they do not support, including unknown types.
5021    ///
5022    /// Clients MUST NOT send an empty array. Agents MAY reject one with
5023    /// `-32602` without creating or resuming the session.
5024    #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
5025    pub content: Vec<ContentBlock>,
5026    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5027    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5028    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5029    ///
5030    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5031    #[serde_as(deserialize_as = "DefaultOnError")]
5032    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5033    #[serde(default)]
5034    #[serde(rename = "_meta")]
5035    pub meta: Option<Meta>,
5036}
5037
5038impl SystemPrompt {
5039    /// Builds [`SystemPrompt`] with the required fields set. Optional fields start unset or empty.
5040    ///
5041    /// `mode` starts as [`SystemPromptMode::Append`]. Use [`SystemPrompt::mode`]
5042    /// to request another mode.
5043    #[must_use]
5044    pub fn new(content: Vec<ContentBlock>) -> Self {
5045        Self {
5046            mode: SystemPromptMode::default(),
5047            content,
5048            meta: None,
5049        }
5050    }
5051
5052    /// How the Agent combines `content` with its own instructions.
5053    #[must_use]
5054    pub fn mode(mut self, mode: SystemPromptMode) -> Self {
5055        self.mode = mode;
5056        self
5057    }
5058
5059    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5060    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5061    /// do not recognize.
5062    ///
5063    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5064    #[must_use]
5065    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5066        self.meta = meta.into_option();
5067        self
5068    }
5069}
5070
5071/// How the Agent combines a Client-provided system prompt with its own instructions.
5072///
5073/// Unknown modes are preserved so they can be stored,
5074/// proxied, or forwarded. An Agent MUST return an error for a mode it does not
5075/// support rather than treating it as `append` or `override`.
5076#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5077#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
5078#[serde(rename_all = "snake_case")]
5079#[non_exhaustive]
5080pub enum SystemPromptMode {
5081    /// Add the content to the Agent's own instructions rather than replacing them.
5082    ///
5083    /// Every Agent that advertises `session.systemPrompt` supports this mode.
5084    /// Agents SHOULD give the content system-level precedence, for example in the
5085    /// model's system prompt or developer instructions rather than in user-turn
5086    /// content. Where it is placed and how it is formatted is implementation-defined.
5087    #[default]
5088    Append,
5089    /// Replace the Agent's built-in default instructions with the content.
5090    ///
5091    /// This does not change tool availability, MCP servers, permissions, or session
5092    /// configuration. Context the Agent supplies from the workspace or environment
5093    /// MAY still be included. Clients that use this mode take responsibility for any
5094    /// tool guidance or safety instructions the Agent's default instructions
5095    /// provided, and MUST only use it when the Agent advertises
5096    /// `session.systemPrompt.mode.override`.
5097    Override,
5098    /// Custom or future system prompt mode.
5099    ///
5100    /// Values beginning with `_` are reserved for implementation-specific
5101    /// extensions. Unknown values that do not begin with `_` are reserved for
5102    /// future ACP variants.
5103    #[serde(untagged)]
5104    Other(String),
5105}
5106
5107// Prompt
5108
5109/// A key the Client generates to identify one `session/prompt` submission across attempts.
5110///
5111/// The key is an opaque, case-sensitive string of 1 to 255 characters. It is scoped to the
5112/// session named by the request's `sessionId`.
5113///
5114/// See protocol docs: [Retrying a prompt](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#retrying-a-prompt)
5115#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5116#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash, Display)]
5117#[serde(transparent)]
5118pub struct IdempotencyKey(
5119    #[cfg_attr(feature = "schemars", schemars(length(min = 1, max = 255)))] Arc<str>,
5120);
5121
5122impl IdempotencyKey {
5123    /// The maximum length of a key, in characters.
5124    pub const MAX_LENGTH: usize = 255;
5125
5126    /// Wraps a string as a typed [`IdempotencyKey`].
5127    ///
5128    /// # Errors
5129    ///
5130    /// Returns [`InvalidIdempotencyKey`] if the key is empty or longer than
5131    /// [`Self::MAX_LENGTH`] characters.
5132    pub fn new(key: impl Into<Arc<str>>) -> Result<Self, InvalidIdempotencyKey> {
5133        let key = key.into();
5134        if key.is_empty() {
5135            return Err(InvalidIdempotencyKey::Empty);
5136        }
5137        // The limit counts characters, as JSON Schema `maxLength` does, not bytes.
5138        if key.chars().nth(Self::MAX_LENGTH).is_some() {
5139            return Err(InvalidIdempotencyKey::TooLong);
5140        }
5141        Ok(Self(key))
5142    }
5143
5144    /// Generates a key from a random version 4 UUID ([RFC 9562]).
5145    ///
5146    /// Generate one key per submission, when the user submits the input, and store it
5147    /// with the pending input. Every attempt for that submission sends the same key.
5148    ///
5149    /// [RFC 9562]: https://www.rfc-editor.org/rfc/rfc9562
5150    #[cfg(feature = "uuid")]
5151    #[must_use]
5152    pub fn generate() -> Self {
5153        uuid::Uuid::new_v4().into()
5154    }
5155
5156    /// Returns the key as a string slice.
5157    #[must_use]
5158    pub fn as_str(&self) -> &str {
5159        &self.0
5160    }
5161}
5162
5163impl AsRef<str> for IdempotencyKey {
5164    fn as_ref(&self) -> &str {
5165        &self.0
5166    }
5167}
5168
5169#[cfg(feature = "uuid")]
5170impl From<uuid::Uuid> for IdempotencyKey {
5171    /// Uses the UUID's hyphenated lowercase form. It is 36 characters, so it is always a
5172    /// valid key.
5173    fn from(uuid: uuid::Uuid) -> Self {
5174        Self(uuid.to_string().into())
5175    }
5176}
5177
5178impl TryFrom<String> for IdempotencyKey {
5179    type Error = InvalidIdempotencyKey;
5180
5181    fn try_from(key: String) -> Result<Self, Self::Error> {
5182        Self::new(key)
5183    }
5184}
5185
5186impl TryFrom<&str> for IdempotencyKey {
5187    type Error = InvalidIdempotencyKey;
5188
5189    fn try_from(key: &str) -> Result<Self, Self::Error> {
5190        Self::new(key)
5191    }
5192}
5193
5194impl std::str::FromStr for IdempotencyKey {
5195    type Err = InvalidIdempotencyKey;
5196
5197    fn from_str(key: &str) -> Result<Self, Self::Err> {
5198        Self::new(key)
5199    }
5200}
5201
5202// Deserialization validates the key, so a malformed value fails the request
5203// instead of being treated as omitted.
5204impl<'de> Deserialize<'de> for IdempotencyKey {
5205    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
5206    where
5207        D: serde::Deserializer<'de>,
5208    {
5209        let key = Arc::<str>::deserialize(deserializer)?;
5210        Self::new(key).map_err(serde::de::Error::custom)
5211    }
5212}
5213
5214/// Error returned when a string is not a valid [`IdempotencyKey`].
5215#[derive(Debug, Clone, Copy, PartialEq, Eq, Display)]
5216#[non_exhaustive]
5217pub enum InvalidIdempotencyKey {
5218    /// The key is an empty string.
5219    #[display("idempotency key must not be empty")]
5220    Empty,
5221    /// The key is longer than [`IdempotencyKey::MAX_LENGTH`] characters.
5222    #[display(
5223        "idempotency key must be at most {} characters",
5224        IdempotencyKey::MAX_LENGTH
5225    )]
5226    TooLong,
5227}
5228
5229impl std::error::Error for InvalidIdempotencyKey {}
5230
5231/// Request parameters for sending a user prompt to the Agent.
5232///
5233/// Contains the user's message and any additional context.
5234///
5235/// See protocol docs: [User Message](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#1-user-message)
5236#[serde_as]
5237#[skip_serializing_none]
5238#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5239#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5240#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_PROMPT_METHOD_NAME)))]
5241#[serde(rename_all = "camelCase")]
5242#[non_exhaustive]
5243pub struct PromptRequest {
5244    /// The ID of the session to send this user message to
5245    pub session_id: SessionId,
5246    /// The blocks of content that compose the user's message.
5247    ///
5248    /// As a baseline, the Agent MUST support `text` and `resource_link` content blocks,
5249    /// while other variants are optionally enabled via `PromptCapabilities`.
5250    ///
5251    /// The Client MUST adapt its interface according to `PromptCapabilities`.
5252    ///
5253    /// The Client MAY include referenced pieces of context as either
5254    /// `resource` or `resource_link` content blocks.
5255    ///
5256    /// When available, `resource` is preferred
5257    /// as it avoids extra round-trips and allows the message to include
5258    /// pieces of context from sources the Agent might not have access to.
5259    ///
5260    /// Clients MUST NOT send an empty array. Agents MAY reject one with `-32602` without
5261    /// inserting it.
5262    #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
5263    pub prompt: Vec<ContentBlock>,
5264    /// Identifies one prompt submission within this session.
5265    ///
5266    /// Optional. Omitted and `null` are equivalent and mean no key. The Agent then handles
5267    /// the prompt without duplicate detection.
5268    ///
5269    /// The Client generates the key and sends the same key on every attempt for the same
5270    /// submission. Agents that advertise `capabilities.session` MUST support the key.
5271    /// A retry of a recorded insertion returns the original `messageId` without inserting
5272    /// another message.
5273    ///
5274    /// The Agent MUST recognize the key for as long as it retains the message, including
5275    /// across connections and Agent restarts. For a live-only message, it MUST recognize
5276    /// the key while the session stays active on a connection. A retry with a forgotten
5277    /// key is a new submission, even immediately after reconnecting. If a duplicate
5278    /// would matter and the Client cannot rule it out, it SHOULD NOT retry automatically.
5279    ///
5280    /// When present, the value is an opaque, case-sensitive string of 1 to 255 characters.
5281    /// Agents MUST reject any other value with `-32602` (Invalid params) and MUST NOT treat
5282    /// it as omitted.
5283    ///
5284    /// See protocol docs: [Retrying a prompt](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#retrying-a-prompt)
5285    #[serde(default)]
5286    pub idempotency_key: Option<IdempotencyKey>,
5287    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5288    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5289    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5290    ///
5291    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5292    #[serde_as(deserialize_as = "DefaultOnError")]
5293    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5294    #[serde(default)]
5295    #[serde(rename = "_meta")]
5296    pub meta: Option<Meta>,
5297}
5298
5299impl PromptRequest {
5300    /// Builds [`PromptRequest`] with the required request fields set. Optional fields start unset or empty.
5301    #[must_use]
5302    pub fn new(session_id: impl Into<SessionId>, prompt: Vec<ContentBlock>) -> Self {
5303        Self {
5304            session_id: session_id.into(),
5305            prompt,
5306            idempotency_key: None,
5307            meta: None,
5308        }
5309    }
5310
5311    /// Sets the key for this submission. `None` means no key.
5312    ///
5313    /// See protocol docs: [Retrying a prompt](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#retrying-a-prompt)
5314    #[must_use]
5315    pub fn idempotency_key(mut self, idempotency_key: impl IntoOption<IdempotencyKey>) -> Self {
5316        self.idempotency_key = idempotency_key.into_option();
5317        self
5318    }
5319
5320    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5321    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5322    /// do not recognize.
5323    ///
5324    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5325    #[must_use]
5326    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5327        self.meta = meta.into_option();
5328        self
5329    }
5330}
5331
5332/// Response acknowledging that a user prompt was inserted into the ACP conversation.
5333///
5334/// This response does not indicate that the prompt was merely received or held, nor that the
5335/// Agent has finished processing it.
5336/// Processing and completion are reported through `state_update` session updates.
5337///
5338/// Insertion is the logical addition of a user message with a message ID and a position
5339/// relative to other messages in the ACP conversation.
5340///
5341/// See protocol docs: [Prompt Accepted](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#2-prompt-accepted)
5342#[serde_as]
5343#[skip_serializing_none]
5344#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5345#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5346#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_PROMPT_METHOD_NAME)))]
5347#[serde(rename_all = "camelCase")]
5348#[non_exhaustive]
5349pub struct PromptResponse {
5350    /// Identifies the user message inserted into the ACP conversation.
5351    ///
5352    /// Required and non-null. Omission and explicit `null` are both invalid.
5353    ///
5354    /// The corresponding user-message session update carries this same identifier and may arrive
5355    /// before or after this response. Agents MUST echo the message during the live session, but are
5356    /// not required to retain it. If retained and replayed, the message keeps this identifier.
5357    pub message_id: MessageId,
5358    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5359    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5360    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5361    ///
5362    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5363    #[serde_as(deserialize_as = "DefaultOnError")]
5364    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5365    #[serde(default)]
5366    #[serde(rename = "_meta")]
5367    pub meta: Option<Meta>,
5368}
5369
5370impl PromptResponse {
5371    /// Builds [`PromptResponse`] with the required response fields set. Optional fields start unset or empty.
5372    #[must_use]
5373    pub fn new(message_id: impl Into<MessageId>) -> Self {
5374        Self {
5375            message_id: message_id.into(),
5376            meta: None,
5377        }
5378    }
5379
5380    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5381    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5382    /// do not recognize.
5383    ///
5384    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5385    #[must_use]
5386    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5387        self.meta = meta.into_option();
5388        self
5389    }
5390}
5391
5392/// Reasons why an Agent stops active session work.
5393///
5394/// See protocol docs: [Stop Reasons](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#stop-reasons)
5395#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5396#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
5397#[serde(tag = "stopReason", rename_all = "snake_case")]
5398#[non_exhaustive]
5399pub enum StopReason {
5400    /// The active work ended successfully.
5401    /// Includes locally handled commands that required no model call.
5402    EndTurn,
5403    /// The active work ended because the Agent reached the maximum number of tokens.
5404    MaxTokens,
5405    /// The active work ended because the Agent reached the maximum number of
5406    /// model requests for the foreground work.
5407    MaxTurnRequests,
5408    /// The active work ended because the Agent refused to continue.
5409    Refusal,
5410    /// The user or Client chose to stop the work: via `session/cancel`, by
5411    /// closing the session, or through an interaction the Agent offers, such
5412    /// as a permission option that tells the Agent to stop. A child session
5413    /// also reports this reason when its parent cancels its work. Other work
5414    /// the Agent stops for its own reasons uses another reason, such as
5415    /// `error` for an internal timeout.
5416    ///
5417    /// Agents MUST report this stop reason on an idle `state_update` when
5418    /// cancellation ends active foreground work, even if aborting causes
5419    /// exceptions. Agents MUST catch these errors and report `cancelled`, not
5420    /// `error`.
5421    Cancelled,
5422    /// The active work ended because something failed.
5423    ///
5424    /// This includes pre-insertion foreground work. A prompt failure before
5425    /// insertion also requires an error response to `session/prompt`. After
5426    /// insertion, the prompt's response remains successful.
5427    Error(ErrorStopReason),
5428    /// Custom or future stop reason.
5429    ///
5430    /// Values beginning with `_` are reserved for implementation-specific
5431    /// extensions. Unknown values that do not begin with `_` are reserved for
5432    /// future ACP variants.
5433    #[serde(untagged)]
5434    Other(OtherStopReason),
5435}
5436
5437impl From<ErrorStopReason> for StopReason {
5438    fn from(value: ErrorStopReason) -> Self {
5439        Self::Error(value)
5440    }
5441}
5442
5443/// Details of a failure that ended active work.
5444#[serde_as]
5445#[skip_serializing_none]
5446#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5447#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
5448#[serde(rename_all = "camelCase")]
5449#[non_exhaustive]
5450pub struct ErrorStopReason {
5451    /// The failure, as a JSON-RPC error object.
5452    ///
5453    /// Optional. Omitted and `null` are equivalent and mean the Agent is not reporting failure details.
5454    /// Agents SHOULD include it.
5455    #[serde_as(deserialize_as = "DefaultOnError")]
5456    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5457    #[serde(default)]
5458    pub error: Option<Box<Error>>,
5459}
5460
5461impl ErrorStopReason {
5462    /// Builds [`ErrorStopReason`] with the required fields set. Optional fields start unset or empty.
5463    #[must_use]
5464    pub fn new() -> Self {
5465        Self::default()
5466    }
5467
5468    /// The failure, as a JSON-RPC error object.
5469    #[must_use]
5470    pub fn error(mut self, error: impl IntoOption<Error>) -> Self {
5471        self.error = error.into_option().map(Box::new);
5472        self
5473    }
5474}
5475
5476/// Custom or future stop reason payload.
5477#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5478#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
5479#[cfg_attr(feature = "schemars", schemars(inline))]
5480#[cfg_attr(feature = "schemars", schemars(transform = other_stop_reason_schema))]
5481#[serde(rename_all = "camelCase")]
5482#[non_exhaustive]
5483pub struct OtherStopReason {
5484    /// Custom or future stop reason.
5485    ///
5486    /// Values beginning with `_` are reserved for implementation-specific
5487    /// extensions. Unknown values that do not begin with `_` are reserved for
5488    /// future ACP variants.
5489    pub stop_reason: String,
5490    /// Additional fields from the unknown stop reason payload.
5491    #[serde(flatten)]
5492    pub fields: IndexMap<String, serde_json::Value>,
5493}
5494
5495impl OtherStopReason {
5496    /// Builds [`OtherStopReason`] from an unknown discriminator and preserves the remaining extension fields.
5497    #[must_use]
5498    pub fn new(
5499        stop_reason: impl Into<String>,
5500        mut fields: IndexMap<String, serde_json::Value>,
5501    ) -> Self {
5502        remove_idle_state_update_fields(&mut fields);
5503        Self {
5504            stop_reason: stop_reason.into(),
5505            fields,
5506        }
5507    }
5508}
5509
5510impl<'de> Deserialize<'de> for OtherStopReason {
5511    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
5512    where
5513        D: serde::Deserializer<'de>,
5514    {
5515        let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
5516        let stop_reason = fields
5517            .shift_remove("stopReason")
5518            .ok_or_else(|| serde::de::Error::missing_field("stopReason"))?;
5519        let serde_json::Value::String(stop_reason) = stop_reason else {
5520            return Err(serde::de::Error::custom("`stopReason` must be a string"));
5521        };
5522
5523        if KNOWN_STOP_REASONS.contains(&stop_reason.as_str()) {
5524            return Err(serde::de::Error::custom(format!(
5525                "known stop reason `{stop_reason}` did not match its schema"
5526            )));
5527        }
5528        remove_idle_state_update_fields(&mut fields);
5529
5530        Ok(Self {
5531            stop_reason,
5532            fields,
5533        })
5534    }
5535}
5536
5537const KNOWN_STOP_REASONS: &[&str] = &[
5538    "end_turn",
5539    "max_tokens",
5540    "max_turn_requests",
5541    "refusal",
5542    "cancelled",
5543    "error",
5544];
5545
5546/// Keeps the idle update's own fields out of an unknown stop reason's payload.
5547fn remove_idle_state_update_fields(fields: &mut IndexMap<String, serde_json::Value>) {
5548    fields.shift_remove("stopReason");
5549    fields.shift_remove("usage");
5550    fields.shift_remove("_meta");
5551}
5552
5553#[cfg(feature = "schemars")]
5554fn other_stop_reason_schema(schema: &mut Schema) {
5555    super::schema_util::reject_known_string_discriminators(
5556        schema,
5557        "stopReason",
5558        KNOWN_STOP_REASONS,
5559    );
5560}
5561
5562/// **UNSTABLE**
5563///
5564/// This capability is not part of the spec yet, and may be removed or changed at any point.
5565///
5566/// Token usage for the foreground work that just completed, not cumulative for the session.
5567#[cfg(feature = "unstable_end_turn_token_usage")]
5568#[serde_as]
5569#[skip_serializing_none]
5570#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5571#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5572#[serde(rename_all = "camelCase")]
5573#[non_exhaustive]
5574pub struct Usage {
5575    /// Sum of all token types for the completed work.
5576    pub total_tokens: u64,
5577    /// Input tokens for the completed work.
5578    pub input_tokens: u64,
5579    /// Output tokens for the completed work.
5580    pub output_tokens: u64,
5581    /// Thought/reasoning tokens for the completed work.
5582    ///
5583    /// Omitted and `null` are equivalent and mean the count is not reported.
5584    #[serde_as(deserialize_as = "DefaultOnError")]
5585    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5586    #[serde(default)]
5587    pub thought_tokens: Option<u64>,
5588    /// Cache read tokens for the completed work.
5589    ///
5590    /// Omitted and `null` are equivalent and mean the count is not reported.
5591    #[serde_as(deserialize_as = "DefaultOnError")]
5592    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5593    #[serde(default)]
5594    pub cached_read_tokens: Option<u64>,
5595    /// Cache write tokens for the completed work.
5596    ///
5597    /// Omitted and `null` are equivalent and mean the count is not reported.
5598    #[serde_as(deserialize_as = "DefaultOnError")]
5599    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5600    #[serde(default)]
5601    pub cached_write_tokens: Option<u64>,
5602    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5603    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5604    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5605    ///
5606    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5607    #[serde_as(deserialize_as = "DefaultOnError")]
5608    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5609    #[serde(default)]
5610    #[serde(rename = "_meta")]
5611    pub meta: Option<Meta>,
5612}
5613
5614#[cfg(feature = "unstable_end_turn_token_usage")]
5615impl Usage {
5616    /// Builds [`Usage`] with the required fields set. Optional fields start unset or empty.
5617    #[must_use]
5618    pub fn new(total_tokens: u64, input_tokens: u64, output_tokens: u64) -> Self {
5619        Self {
5620            total_tokens,
5621            input_tokens,
5622            output_tokens,
5623            thought_tokens: None,
5624            cached_read_tokens: None,
5625            cached_write_tokens: None,
5626            meta: None,
5627        }
5628    }
5629
5630    /// Thought/reasoning tokens for the completed work.
5631    #[must_use]
5632    pub fn thought_tokens(mut self, thought_tokens: impl IntoOption<u64>) -> Self {
5633        self.thought_tokens = thought_tokens.into_option();
5634        self
5635    }
5636
5637    /// Cache read tokens for the completed work.
5638    #[must_use]
5639    pub fn cached_read_tokens(mut self, cached_read_tokens: impl IntoOption<u64>) -> Self {
5640        self.cached_read_tokens = cached_read_tokens.into_option();
5641        self
5642    }
5643
5644    /// Cache write tokens for the completed work.
5645    #[must_use]
5646    pub fn cached_write_tokens(mut self, cached_write_tokens: impl IntoOption<u64>) -> Self {
5647        self.cached_write_tokens = cached_write_tokens.into_option();
5648        self
5649    }
5650
5651    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5652    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5653    /// do not recognize.
5654    ///
5655    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5656    #[must_use]
5657    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5658        self.meta = meta.into_option();
5659        self
5660    }
5661}
5662
5663// Providers
5664
5665/// **UNSTABLE**
5666///
5667/// This capability is not part of the spec yet, and may be removed or changed at any point.
5668///
5669/// Well-known API protocol identifiers for LLM providers.
5670///
5671/// Agents and Clients MUST handle unknown protocol identifiers gracefully.
5672///
5673/// Protocol names beginning with `_` are free for custom use, like other ACP extension methods.
5674/// Protocol names that do not begin with `_` are reserved for the ACP spec.
5675#[cfg(feature = "unstable_llm_providers")]
5676#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5677#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5678#[serde(rename_all = "snake_case")]
5679#[non_exhaustive]
5680pub enum LlmProtocol {
5681    /// Anthropic API protocol.
5682    Anthropic,
5683    /// OpenAI API protocol.
5684    #[serde(rename = "openai")]
5685    OpenAi,
5686    /// Azure OpenAI API protocol.
5687    Azure,
5688    /// Google Vertex AI API protocol.
5689    Vertex,
5690    /// AWS Bedrock API protocol.
5691    Bedrock,
5692    /// Custom or future protocol.
5693    ///
5694    /// Values beginning with `_` are reserved for implementation-specific
5695    /// extensions. Unknown values that do not begin with `_` are reserved for
5696    /// future ACP variants.
5697    #[serde(untagged)]
5698    Other(String),
5699}
5700
5701/// **UNSTABLE**
5702///
5703/// This capability is not part of the spec yet, and may be removed or changed at any point.
5704///
5705/// Current effective non-secret routing configuration for a provider.
5706#[cfg(feature = "unstable_llm_providers")]
5707#[serde_as]
5708#[skip_serializing_none]
5709#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5710#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5711#[serde(rename_all = "camelCase")]
5712#[non_exhaustive]
5713pub struct ProviderCurrentConfig {
5714    /// Protocol currently used by this provider.
5715    pub api_type: LlmProtocol,
5716    /// Base URL currently used by this provider.
5717    #[cfg_attr(feature = "schemars", schemars(url))]
5718    pub base_url: String,
5719    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5720    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5721    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5722    ///
5723    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5724    #[serde_as(deserialize_as = "DefaultOnError")]
5725    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5726    #[serde(default)]
5727    #[serde(rename = "_meta")]
5728    pub meta: Option<Meta>,
5729}
5730
5731#[cfg(feature = "unstable_llm_providers")]
5732impl ProviderCurrentConfig {
5733    /// Builds [`ProviderCurrentConfig`] with the required fields set. Optional fields start unset or empty.
5734    #[must_use]
5735    pub fn new(api_type: LlmProtocol, base_url: impl Into<String>) -> Self {
5736        Self {
5737            api_type,
5738            base_url: base_url.into(),
5739            meta: None,
5740        }
5741    }
5742
5743    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5744    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5745    /// do not recognize.
5746    ///
5747    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5748    #[must_use]
5749    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5750        self.meta = meta.into_option();
5751        self
5752    }
5753}
5754
5755/// **UNSTABLE**
5756///
5757/// This capability is not part of the spec yet, and may be removed or changed at any point.
5758///
5759/// Unique identifier for a configurable LLM provider.
5760#[cfg(feature = "unstable_llm_providers")]
5761#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5762#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
5763#[serde(transparent)]
5764#[from(forward)]
5765#[non_exhaustive]
5766pub struct ProviderId(pub Arc<str>);
5767
5768#[cfg(feature = "unstable_llm_providers")]
5769impl ProviderId {
5770    /// Wraps a protocol string as a typed [`ProviderId`].
5771    #[must_use]
5772    pub fn new(id: impl Into<Self>) -> Self {
5773        id.into()
5774    }
5775}
5776
5777/// **UNSTABLE**
5778///
5779/// This capability is not part of the spec yet, and may be removed or changed at any point.
5780///
5781/// Information about a configurable LLM provider.
5782#[cfg(feature = "unstable_llm_providers")]
5783#[serde_as]
5784#[skip_serializing_none]
5785#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5786#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5787#[serde(rename_all = "camelCase")]
5788#[non_exhaustive]
5789pub struct ProviderInfo {
5790    /// Provider identifier, for example "main" or "openai".
5791    pub provider_id: ProviderId,
5792    /// Supported protocol types for this provider.
5793    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
5794    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
5795    pub supported: Vec<LlmProtocol>,
5796    /// Whether this provider is mandatory and cannot be disabled via `providers/disable`.
5797    /// If true, Clients MUST NOT call `providers/disable` for this provider ID.
5798    pub required: bool,
5799    /// Current effective non-secret routing config.
5800    /// Null or omitted means provider is disabled.
5801    #[serde(default)]
5802    pub current: Option<ProviderCurrentConfig>,
5803    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5804    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5805    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5806    ///
5807    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5808    #[serde_as(deserialize_as = "DefaultOnError")]
5809    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5810    #[serde(default)]
5811    #[serde(rename = "_meta")]
5812    pub meta: Option<Meta>,
5813}
5814
5815#[cfg(feature = "unstable_llm_providers")]
5816impl ProviderInfo {
5817    /// Builds [`ProviderInfo`] with the required fields set. Optional fields start unset or empty.
5818    #[must_use]
5819    pub fn new(
5820        provider_id: impl Into<ProviderId>,
5821        supported: Vec<LlmProtocol>,
5822        required: bool,
5823        current: impl IntoOption<ProviderCurrentConfig>,
5824    ) -> Self {
5825        Self {
5826            provider_id: provider_id.into(),
5827            supported,
5828            required,
5829            current: current.into_option(),
5830            meta: None,
5831        }
5832    }
5833
5834    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5835    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5836    /// do not recognize.
5837    ///
5838    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5839    #[must_use]
5840    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5841        self.meta = meta.into_option();
5842        self
5843    }
5844}
5845
5846#[cfg(feature = "unstable_llm_providers")]
5847crate::serde_util::default_on_null! {
5848    /// **UNSTABLE**
5849    ///
5850    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5851    ///
5852    /// Request parameters for `providers/list`.
5853    #[serde_as]
5854    #[skip_serializing_none]
5855    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5856    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
5857    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_LIST_METHOD_NAME)))]
5858    #[serde(rename_all = "camelCase")]
5859    #[non_exhaustive]
5860    pub struct ListProvidersRequest {
5861        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5862        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5863        /// Implementations MUST NOT assign meaning to keys they do not recognize.
5864        ///
5865        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5866        #[serde_as(deserialize_as = "DefaultOnError")]
5867        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5868        #[serde(default)]
5869        #[serde(rename = "_meta")]
5870        pub meta: Option<Meta>,
5871    }
5872}
5873
5874#[cfg(feature = "unstable_llm_providers")]
5875impl ListProvidersRequest {
5876    /// Builds [`ListProvidersRequest`] with the required request fields set. Optional fields start unset or empty.
5877    #[must_use]
5878    pub fn new() -> Self {
5879        Self::default()
5880    }
5881
5882    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5883    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5884    /// do not recognize.
5885    ///
5886    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5887    #[must_use]
5888    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5889        self.meta = meta.into_option();
5890        self
5891    }
5892}
5893
5894/// **UNSTABLE**
5895///
5896/// This capability is not part of the spec yet, and may be removed or changed at any point.
5897///
5898/// Response to `providers/list`.
5899#[cfg(feature = "unstable_llm_providers")]
5900#[serde_as]
5901#[skip_serializing_none]
5902#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5903#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5904#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_LIST_METHOD_NAME)))]
5905#[serde(rename_all = "camelCase")]
5906#[non_exhaustive]
5907pub struct ListProvidersResponse {
5908    /// Configurable providers with current routing info suitable for UI display.
5909    pub providers: Vec<ProviderInfo>,
5910    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5911    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5912    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5913    ///
5914    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5915    #[serde_as(deserialize_as = "DefaultOnError")]
5916    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5917    #[serde(default)]
5918    #[serde(rename = "_meta")]
5919    pub meta: Option<Meta>,
5920}
5921
5922#[cfg(feature = "unstable_llm_providers")]
5923impl ListProvidersResponse {
5924    /// Builds [`ListProvidersResponse`] with the required response fields set. Optional fields start unset or empty.
5925    #[must_use]
5926    pub fn new(providers: Vec<ProviderInfo>) -> Self {
5927        Self {
5928            providers,
5929            meta: None,
5930        }
5931    }
5932
5933    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5934    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5935    /// do not recognize.
5936    ///
5937    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5938    #[must_use]
5939    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5940        self.meta = meta.into_option();
5941        self
5942    }
5943}
5944
5945/// **UNSTABLE**
5946///
5947/// This capability is not part of the spec yet, and may be removed or changed at any point.
5948///
5949/// Request parameters for `providers/set`.
5950///
5951/// Replaces the full configuration for one provider ID.
5952#[cfg(feature = "unstable_llm_providers")]
5953#[serde_as]
5954#[skip_serializing_none]
5955#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5956#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
5957#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_SET_METHOD_NAME)))]
5958#[serde(rename_all = "camelCase")]
5959#[non_exhaustive]
5960pub struct SetProviderRequest {
5961    /// Provider ID to configure.
5962    pub provider_id: ProviderId,
5963    /// Protocol type for this provider.
5964    pub api_type: LlmProtocol,
5965    /// Base URL for requests sent through this provider.
5966    #[cfg_attr(feature = "schemars", schemars(url))]
5967    pub base_url: String,
5968    /// Full headers map for this provider.
5969    /// May include authorization, routing, or other integration-specific headers.
5970    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
5971    pub headers: IndexMap<String, String>,
5972    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5973    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5974    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5975    ///
5976    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5977    #[serde_as(deserialize_as = "DefaultOnError")]
5978    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5979    #[serde(default)]
5980    #[serde(rename = "_meta")]
5981    pub meta: Option<Meta>,
5982}
5983
5984#[cfg(feature = "unstable_llm_providers")]
5985impl SetProviderRequest {
5986    /// Builds [`SetProviderRequest`] with the required request fields set. Optional fields start unset or empty.
5987    #[must_use]
5988    pub fn new(
5989        provider_id: impl Into<ProviderId>,
5990        api_type: LlmProtocol,
5991        base_url: impl Into<String>,
5992    ) -> Self {
5993        Self {
5994            provider_id: provider_id.into(),
5995            api_type,
5996            base_url: base_url.into(),
5997            headers: IndexMap::new(),
5998            meta: None,
5999        }
6000    }
6001
6002    /// Full headers map for this provider.
6003    /// May include authorization, routing, or other integration-specific headers.
6004    #[must_use]
6005    pub fn headers(mut self, headers: IndexMap<String, String>) -> Self {
6006        self.headers = headers;
6007        self
6008    }
6009
6010    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6011    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6012    /// do not recognize.
6013    ///
6014    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6015    #[must_use]
6016    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6017        self.meta = meta.into_option();
6018        self
6019    }
6020}
6021
6022#[cfg(feature = "unstable_llm_providers")]
6023crate::serde_util::default_on_null! {
6024    /// **UNSTABLE**
6025    ///
6026    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6027    ///
6028    /// Response to `providers/set`.
6029    #[serde_as]
6030    #[skip_serializing_none]
6031    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6032    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
6033    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_SET_METHOD_NAME)))]
6034    #[serde(rename_all = "camelCase")]
6035    #[non_exhaustive]
6036    pub struct SetProviderResponse {
6037        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6038        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6039        /// Implementations MUST NOT assign meaning to keys they do not recognize.
6040        ///
6041        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6042        #[serde_as(deserialize_as = "DefaultOnError")]
6043        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6044        #[serde(default)]
6045        #[serde(rename = "_meta")]
6046        pub meta: Option<Meta>,
6047    }
6048}
6049
6050#[cfg(feature = "unstable_llm_providers")]
6051impl SetProviderResponse {
6052    /// Builds [`SetProviderResponse`] with the required response fields set. Optional fields start unset or empty.
6053    #[must_use]
6054    pub fn new() -> Self {
6055        Self::default()
6056    }
6057
6058    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6059    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6060    /// do not recognize.
6061    ///
6062    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6063    #[must_use]
6064    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6065        self.meta = meta.into_option();
6066        self
6067    }
6068}
6069
6070/// **UNSTABLE**
6071///
6072/// This capability is not part of the spec yet, and may be removed or changed at any point.
6073///
6074/// Request parameters for `providers/disable`.
6075#[cfg(feature = "unstable_llm_providers")]
6076#[serde_as]
6077#[skip_serializing_none]
6078#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6079#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6080#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_DISABLE_METHOD_NAME)))]
6081#[serde(rename_all = "camelCase")]
6082#[non_exhaustive]
6083pub struct DisableProviderRequest {
6084    /// Provider ID to disable.
6085    pub provider_id: ProviderId,
6086    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6087    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6088    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6089    ///
6090    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6091    #[serde_as(deserialize_as = "DefaultOnError")]
6092    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6093    #[serde(default)]
6094    #[serde(rename = "_meta")]
6095    pub meta: Option<Meta>,
6096}
6097
6098#[cfg(feature = "unstable_llm_providers")]
6099impl DisableProviderRequest {
6100    /// Builds [`DisableProviderRequest`] with the required request fields set. Optional fields start unset or empty.
6101    #[must_use]
6102    pub fn new(provider_id: impl Into<ProviderId>) -> Self {
6103        Self {
6104            provider_id: provider_id.into(),
6105            meta: None,
6106        }
6107    }
6108
6109    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6110    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6111    /// do not recognize.
6112    ///
6113    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6114    #[must_use]
6115    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6116        self.meta = meta.into_option();
6117        self
6118    }
6119}
6120
6121#[cfg(feature = "unstable_llm_providers")]
6122crate::serde_util::default_on_null! {
6123    /// **UNSTABLE**
6124    ///
6125    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6126    ///
6127    /// Response to `providers/disable`.
6128    #[serde_as]
6129    #[skip_serializing_none]
6130    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6131    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
6132    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_DISABLE_METHOD_NAME)))]
6133    #[serde(rename_all = "camelCase")]
6134    #[non_exhaustive]
6135    pub struct DisableProviderResponse {
6136        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6137        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6138        /// Implementations MUST NOT assign meaning to keys they do not recognize.
6139        ///
6140        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6141        #[serde_as(deserialize_as = "DefaultOnError")]
6142        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6143        #[serde(default)]
6144        #[serde(rename = "_meta")]
6145        pub meta: Option<Meta>,
6146    }
6147}
6148
6149#[cfg(feature = "unstable_llm_providers")]
6150impl DisableProviderResponse {
6151    /// Builds [`DisableProviderResponse`] with the required response fields set. Optional fields start unset or empty.
6152    #[must_use]
6153    pub fn new() -> Self {
6154        Self::default()
6155    }
6156
6157    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6158    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6159    /// do not recognize.
6160    ///
6161    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6162    #[must_use]
6163    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6164        self.meta = meta.into_option();
6165        self
6166    }
6167}
6168
6169// Capabilities
6170
6171/// Capabilities supported by the Agent.
6172///
6173/// Advertised during initialization to inform the Client about
6174/// available features and content types.
6175///
6176/// See protocol docs: [Agent Capabilities](https://agentclientprotocol.com/protocol/v2/initialization#agent-capabilities)
6177#[serde_as]
6178#[skip_serializing_none]
6179#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6180#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6181#[serde(rename_all = "camelCase")]
6182#[non_exhaustive]
6183pub struct AgentCapabilities {
6184    /// Session capabilities supported by the Agent.
6185    ///
6186    /// Optional. Omitted and `null` are equivalent and mean the Agent does not support the
6187    /// `session/*` methods. Supplying `{}` means the Agent supports the
6188    /// baseline session methods: `session/new`, `session/list`,
6189    /// `session/resume`, `session/close`, `session/prompt`, `session/cancel`,
6190    /// and `session/update`.
6191    #[serde_as(deserialize_as = "DefaultOnError")]
6192    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6193    #[serde(default)]
6194    pub session: Option<SessionCapabilities>,
6195    /// Authentication-related extension capabilities supported by the Agent.
6196    ///
6197    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise any
6198    /// authentication-related extensions. This field does not advertise support
6199    /// for `auth/login` or `auth/logout`. Those methods are advertised by a
6200    /// non-empty `authMethods` list in the `initialize` response.
6201    #[serde_as(deserialize_as = "DefaultOnError")]
6202    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6203    #[serde(default)]
6204    pub auth: Option<AgentAuthCapabilities>,
6205    /// **UNSTABLE**
6206    ///
6207    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6208    ///
6209    /// Provider configuration capabilities supported by the Agent.
6210    ///
6211    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6212    /// Supplying `{}` means the Agent supports provider configuration methods.
6213    #[cfg(feature = "unstable_llm_providers")]
6214    #[serde_as(deserialize_as = "DefaultOnError")]
6215    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6216    #[serde(default)]
6217    pub providers: Option<ProvidersCapabilities>,
6218    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6219    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6220    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6221    ///
6222    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6223    #[serde_as(deserialize_as = "DefaultOnError")]
6224    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6225    #[serde(default)]
6226    #[serde(rename = "_meta")]
6227    pub meta: Option<Meta>,
6228}
6229
6230impl AgentCapabilities {
6231    /// Builds an empty [`AgentCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6232    #[must_use]
6233    pub fn new() -> Self {
6234        Self::default()
6235    }
6236
6237    /// Session capabilities supported by the Agent.
6238    ///
6239    /// Omitted and `null` are equivalent and mean the Agent does not support the `session/*`
6240    /// methods. Supplying `{}` means the Agent supports the baseline
6241    /// session methods: `session/new`, `session/list`, `session/resume`,
6242    /// `session/close`, `session/prompt`, `session/cancel`, and
6243    /// `session/update`.
6244    #[must_use]
6245    pub fn session(mut self, session: impl IntoOption<SessionCapabilities>) -> Self {
6246        self.session = session.into_option();
6247        self
6248    }
6249
6250    /// Authentication-related extension capabilities supported by the Agent.
6251    ///
6252    /// This field does not advertise support for `auth/login` or `auth/logout`.
6253    #[must_use]
6254    pub fn auth(mut self, auth: impl IntoOption<AgentAuthCapabilities>) -> Self {
6255        self.auth = auth.into_option();
6256        self
6257    }
6258
6259    /// **UNSTABLE**
6260    ///
6261    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6262    ///
6263    /// Provider configuration capabilities supported by the Agent.
6264    #[cfg(feature = "unstable_llm_providers")]
6265    #[must_use]
6266    pub fn providers(mut self, providers: impl IntoOption<ProvidersCapabilities>) -> Self {
6267        self.providers = providers.into_option();
6268        self
6269    }
6270
6271    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6272    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6273    /// do not recognize.
6274    ///
6275    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6276    #[must_use]
6277    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6278        self.meta = meta.into_option();
6279        self
6280    }
6281}
6282
6283/// **UNSTABLE**
6284///
6285/// This capability is not part of the spec yet, and may be removed or changed at any point.
6286///
6287/// Provider configuration capabilities supported by the Agent.
6288///
6289/// Supplying `{}` means the Agent supports provider configuration methods.
6290#[cfg(feature = "unstable_llm_providers")]
6291#[serde_as]
6292#[skip_serializing_none]
6293#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6294#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6295#[non_exhaustive]
6296pub struct ProvidersCapabilities {
6297    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6298    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6299    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6300    ///
6301    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6302    #[serde_as(deserialize_as = "DefaultOnError")]
6303    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6304    #[serde(default)]
6305    #[serde(rename = "_meta")]
6306    pub meta: Option<Meta>,
6307}
6308
6309#[cfg(feature = "unstable_llm_providers")]
6310impl ProvidersCapabilities {
6311    /// Builds an empty [`ProvidersCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6312    #[must_use]
6313    pub fn new() -> Self {
6314        Self::default()
6315    }
6316
6317    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6318    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6319    /// do not recognize.
6320    ///
6321    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6322    #[must_use]
6323    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6324        self.meta = meta.into_option();
6325        self
6326    }
6327}
6328
6329/// Session capabilities supported by the Agent.
6330///
6331/// Supplying `{}` means the Agent supports the baseline session methods:
6332/// `session/new`, `session/list`, `session/resume`, `session/close`,
6333/// `session/prompt`, `session/cancel`, and `session/update`.
6334///
6335/// Agents that support sessions MAY support additional session methods,
6336/// prompt content types, and MCP transports by specifying additional
6337/// capabilities.
6338///
6339/// See protocol docs: [Session Capabilities](https://agentclientprotocol.com/protocol/v2/initialization#session-capabilities)
6340#[serde_as]
6341#[skip_serializing_none]
6342#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6343#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6344#[serde(rename_all = "camelCase")]
6345#[non_exhaustive]
6346pub struct SessionCapabilities {
6347    /// Prompt capabilities supported by the Agent in `session/prompt` requests.
6348    ///
6349    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise any
6350    /// prompt extensions beyond the baseline text and resource-link content
6351    /// required by `session/prompt`.
6352    #[serde_as(deserialize_as = "DefaultOnError")]
6353    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6354    #[serde(default)]
6355    pub prompt: Option<PromptCapabilities>,
6356    /// MCP capabilities supported by the Agent for session lifecycle requests.
6357    ///
6358    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise MCP
6359    /// server transport support for sessions.
6360    #[serde_as(deserialize_as = "DefaultOnError")]
6361    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6362    #[serde(default)]
6363    pub mcp: Option<McpCapabilities>,
6364    /// Whether the Agent supports `session/delete`.
6365    ///
6366    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6367    /// Supplying `{}` means the Agent supports deleting sessions from `session/list`.
6368    #[serde_as(deserialize_as = "DefaultOnError")]
6369    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6370    #[serde(default)]
6371    pub delete: Option<SessionDeleteCapabilities>,
6372    /// Whether the Agent supports `additionalDirectories` on supported session lifecycle requests.
6373    ///
6374    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6375    /// Supplying `{}` means the Agent supports `additionalDirectories` on
6376    /// supported session lifecycle requests.
6377    ///
6378    /// Agents MAY return `SessionInfo.additionalDirectories` to report the
6379    /// complete ordered additional-root list associated with a listed session.
6380    #[serde_as(deserialize_as = "DefaultOnError")]
6381    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6382    #[serde(default)]
6383    pub additional_directories: Option<SessionAdditionalDirectoriesCapabilities>,
6384    /// Whether the Agent supports `systemPrompt` on session lifecycle requests.
6385    ///
6386    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6387    /// Supplying `{}` means the Agent supports `systemPrompt` in `append` mode.
6388    #[serde_as(deserialize_as = "DefaultOnError")]
6389    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6390    #[serde(default)]
6391    pub system_prompt: Option<SessionSystemPromptCapabilities>,
6392    /// **UNSTABLE**
6393    ///
6394    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6395    ///
6396    /// Whether the Agent supports `session/fork`.
6397    ///
6398    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6399    /// Supplying `{}` means the Agent supports forking sessions.
6400    #[cfg(feature = "unstable_session_fork")]
6401    #[serde_as(deserialize_as = "DefaultOnError")]
6402    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6403    #[serde(default)]
6404    pub fork: Option<SessionForkCapabilities>,
6405    /// **UNSTABLE**
6406    ///
6407    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6408    ///
6409    /// Whether the Agent supports `session/archive` and `session/unarchive`.
6410    ///
6411    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6412    /// Supplying `{}` means the Agent supports both methods, the `archived` filter on
6413    /// `session/list`, and `SessionInfo.archived`.
6414    #[cfg(feature = "unstable_session_archive")]
6415    #[serde_as(deserialize_as = "DefaultOnError")]
6416    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6417    #[serde(default)]
6418    pub archive: Option<SessionArchiveCapabilities>,
6419    /// **UNSTABLE**
6420    ///
6421    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6422    ///
6423    /// Whether the Agent supports `session/status`.
6424    ///
6425    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6426    /// Supplying `{}` means the Agent supports checking session status.
6427    #[cfg(feature = "unstable_session_status")]
6428    #[serde_as(deserialize_as = "DefaultOnError")]
6429    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6430    #[serde(default)]
6431    pub status: Option<SessionStatusCapabilities>,
6432    /// **UNSTABLE**
6433    ///
6434    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6435    ///
6436    /// Whether the Agent supports `session/options`.
6437    ///
6438    /// Optional. Omitted or `null` both mean the Agent does not advertise support.
6439    /// Supplying `{}` means the Agent supports `session/options` and accepts initial
6440    /// config option values on session setup requests.
6441    #[cfg(feature = "unstable_session_options")]
6442    #[serde_as(deserialize_as = "DefaultOnError")]
6443    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6444    #[serde(default)]
6445    pub options: Option<SessionOptionsCapabilities>,
6446    /// **UNSTABLE**
6447    ///
6448    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6449    ///
6450    /// Whether the Agent supports `session/set_title`.
6451    ///
6452    /// Agents report titles through `session/list` and `session_info_update` without this
6453    /// capability. It only advertises that Clients can set titles.
6454    ///
6455    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6456    /// Supplying `{}` means the Agent supports setting session titles.
6457    #[cfg(feature = "unstable_session_set_title")]
6458    #[serde_as(deserialize_as = "DefaultOnError")]
6459    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6460    #[serde(default)]
6461    pub title: Option<SessionTitleCapabilities>,
6462    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6463    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6464    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6465    ///
6466    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6467    #[serde_as(deserialize_as = "DefaultOnError")]
6468    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6469    #[serde(default)]
6470    #[serde(rename = "_meta")]
6471    pub meta: Option<Meta>,
6472}
6473
6474impl SessionCapabilities {
6475    /// Builds an empty [`SessionCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6476    #[must_use]
6477    pub fn new() -> Self {
6478        Self::default()
6479    }
6480
6481    /// Prompt capabilities supported by the Agent in `session/prompt` requests.
6482    ///
6483    /// Omitted and `null` are equivalent and mean the Agent does not advertise any prompt
6484    /// extensions beyond the baseline text and resource-link content required by
6485    /// `session/prompt`.
6486    #[must_use]
6487    pub fn prompt(mut self, prompt: impl IntoOption<PromptCapabilities>) -> Self {
6488        self.prompt = prompt.into_option();
6489        self
6490    }
6491
6492    /// MCP capabilities supported by the Agent for session lifecycle requests.
6493    ///
6494    /// Omitted and `null` are equivalent and mean the Agent does not advertise MCP server
6495    /// transport support for sessions.
6496    #[must_use]
6497    pub fn mcp(mut self, mcp: impl IntoOption<McpCapabilities>) -> Self {
6498        self.mcp = mcp.into_option();
6499        self
6500    }
6501
6502    /// Whether the Agent supports `session/delete`.
6503    ///
6504    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
6505    /// Supplying `{}` means the Agent supports deleting sessions from `session/list`.
6506    #[must_use]
6507    pub fn delete(mut self, delete: impl IntoOption<SessionDeleteCapabilities>) -> Self {
6508        self.delete = delete.into_option();
6509        self
6510    }
6511
6512    /// Whether the Agent supports `additionalDirectories` on supported session lifecycle requests.
6513    ///
6514    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
6515    /// Supplying `{}` means the Agent supports `additionalDirectories` on
6516    /// supported session lifecycle requests.
6517    ///
6518    /// Agents MAY return `SessionInfo.additionalDirectories` to report the
6519    /// complete ordered additional-root list associated with a listed session.
6520    #[must_use]
6521    pub fn additional_directories(
6522        mut self,
6523        additional_directories: impl IntoOption<SessionAdditionalDirectoriesCapabilities>,
6524    ) -> Self {
6525        self.additional_directories = additional_directories.into_option();
6526        self
6527    }
6528
6529    /// Whether the Agent supports `systemPrompt` on session lifecycle requests.
6530    ///
6531    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
6532    /// Supplying `{}` means the Agent supports `systemPrompt` in `append` mode.
6533    #[must_use]
6534    pub fn system_prompt(
6535        mut self,
6536        system_prompt: impl IntoOption<SessionSystemPromptCapabilities>,
6537    ) -> Self {
6538        self.system_prompt = system_prompt.into_option();
6539        self
6540    }
6541
6542    #[cfg(feature = "unstable_session_fork")]
6543    /// Whether the Agent supports `session/fork`.
6544    ///
6545    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
6546    /// Supplying `{}` means the Agent supports forking sessions.
6547    #[must_use]
6548    pub fn fork(mut self, fork: impl IntoOption<SessionForkCapabilities>) -> Self {
6549        self.fork = fork.into_option();
6550        self
6551    }
6552
6553    /// **UNSTABLE**
6554    ///
6555    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6556    ///
6557    /// Whether the Agent supports `session/archive` and `session/unarchive`.
6558    ///
6559    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
6560    /// Supplying `{}` means the Agent supports both methods, the `archived` filter on
6561    /// `session/list`, and `SessionInfo.archived`.
6562    #[cfg(feature = "unstable_session_archive")]
6563    #[must_use]
6564    pub fn archive(mut self, archive: impl IntoOption<SessionArchiveCapabilities>) -> Self {
6565        self.archive = archive.into_option();
6566        self
6567    }
6568
6569    /// **UNSTABLE**
6570    ///
6571    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6572    ///
6573    /// Whether the Agent supports `session/status`.
6574    ///
6575    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
6576    /// Supplying `{}` means the Agent supports checking session status.
6577    #[cfg(feature = "unstable_session_status")]
6578    #[must_use]
6579    pub fn status(mut self, status: impl IntoOption<SessionStatusCapabilities>) -> Self {
6580        self.status = status.into_option();
6581        self
6582    }
6583
6584    /// **UNSTABLE**
6585    ///
6586    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6587    ///
6588    /// Whether the Agent supports `session/options`.
6589    ///
6590    /// Omitted or `null` both mean the Agent does not advertise support.
6591    /// Supplying `{}` means the Agent supports `session/options` and accepts initial
6592    /// config option values on session setup requests.
6593    #[cfg(feature = "unstable_session_options")]
6594    #[must_use]
6595    pub fn options(mut self, options: impl IntoOption<SessionOptionsCapabilities>) -> Self {
6596        self.options = options.into_option();
6597        self
6598    }
6599
6600    /// **UNSTABLE**
6601    ///
6602    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6603    ///
6604    /// Whether the Agent supports `session/set_title`.
6605    ///
6606    /// Agents report titles through `session/list` and `session_info_update` without this
6607    /// capability. It only advertises that Clients can set titles.
6608    ///
6609    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
6610    /// Supplying `{}` means the Agent supports setting session titles.
6611    #[cfg(feature = "unstable_session_set_title")]
6612    #[must_use]
6613    pub fn title(mut self, title: impl IntoOption<SessionTitleCapabilities>) -> Self {
6614        self.title = title.into_option();
6615        self
6616    }
6617
6618    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6619    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6620    /// do not recognize.
6621    ///
6622    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6623    #[must_use]
6624    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6625        self.meta = meta.into_option();
6626        self
6627    }
6628}
6629
6630/// Capabilities for the `session/delete` method.
6631///
6632/// Supplying `{}` means the Agent supports deleting sessions from `session/list`.
6633#[serde_as]
6634#[skip_serializing_none]
6635#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6636#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6637#[non_exhaustive]
6638pub struct SessionDeleteCapabilities {
6639    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6640    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6641    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6642    ///
6643    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6644    #[serde_as(deserialize_as = "DefaultOnError")]
6645    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6646    #[serde(default)]
6647    #[serde(rename = "_meta")]
6648    pub meta: Option<Meta>,
6649}
6650
6651impl SessionDeleteCapabilities {
6652    /// Builds an empty [`SessionDeleteCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6653    #[must_use]
6654    pub fn new() -> Self {
6655        Self::default()
6656    }
6657
6658    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6659    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6660    /// do not recognize.
6661    ///
6662    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6663    #[must_use]
6664    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6665        self.meta = meta.into_option();
6666        self
6667    }
6668}
6669
6670/// Capabilities for additional session directories support.
6671///
6672/// Supplying `{}` means the Agent supports the `additionalDirectories` field on
6673/// supported session lifecycle requests. Agents MAY return
6674/// `SessionInfo.additionalDirectories` in `session/list` to report the
6675/// complete ordered additional-root list associated with a listed session.
6676#[serde_as]
6677#[skip_serializing_none]
6678#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6679#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6680#[non_exhaustive]
6681pub struct SessionAdditionalDirectoriesCapabilities {
6682    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6683    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6684    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6685    ///
6686    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6687    #[serde_as(deserialize_as = "DefaultOnError")]
6688    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6689    #[serde(default)]
6690    #[serde(rename = "_meta")]
6691    pub meta: Option<Meta>,
6692}
6693
6694impl SessionAdditionalDirectoriesCapabilities {
6695    /// Builds an empty [`SessionAdditionalDirectoriesCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6696    #[must_use]
6697    pub fn new() -> Self {
6698        Self::default()
6699    }
6700
6701    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6702    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6703    /// do not recognize.
6704    ///
6705    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6706    #[must_use]
6707    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6708        self.meta = meta.into_option();
6709        self
6710    }
6711}
6712
6713/// Capabilities for Client-provided system prompts.
6714///
6715/// Supplying `{}` means the Agent supports `systemPrompt` on session lifecycle
6716/// requests in `append` mode.
6717#[serde_as]
6718#[skip_serializing_none]
6719#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6720#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6721#[serde(rename_all = "camelCase")]
6722#[non_exhaustive]
6723pub struct SessionSystemPromptCapabilities {
6724    /// Delivery modes the Agent supports in addition to `append`.
6725    ///
6726    /// Optional. Omitted and `null` are equivalent and mean the Agent supports only `append`.
6727    #[serde_as(deserialize_as = "DefaultOnError")]
6728    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6729    #[serde(default)]
6730    pub mode: Option<SessionSystemPromptModeCapabilities>,
6731    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6732    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6733    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6734    ///
6735    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6736    #[serde_as(deserialize_as = "DefaultOnError")]
6737    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6738    #[serde(default)]
6739    #[serde(rename = "_meta")]
6740    pub meta: Option<Meta>,
6741}
6742
6743impl SessionSystemPromptCapabilities {
6744    /// Builds an empty [`SessionSystemPromptCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6745    #[must_use]
6746    pub fn new() -> Self {
6747        Self::default()
6748    }
6749
6750    /// Delivery modes the Agent supports in addition to `append`.
6751    ///
6752    /// Omitted and `null` are equivalent and mean the Agent supports only `append`.
6753    #[must_use]
6754    pub fn mode(mut self, mode: impl IntoOption<SessionSystemPromptModeCapabilities>) -> Self {
6755        self.mode = mode.into_option();
6756        self
6757    }
6758
6759    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6760    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6761    /// do not recognize.
6762    ///
6763    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6764    #[must_use]
6765    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6766        self.meta = meta.into_option();
6767        self
6768    }
6769}
6770
6771/// System prompt delivery modes the Agent supports in addition to `append`.
6772///
6773/// `append` has no entry because every Agent advertising `session.systemPrompt`
6774/// supports it.
6775#[serde_as]
6776#[skip_serializing_none]
6777#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6778#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6779#[serde(rename_all = "camelCase")]
6780#[non_exhaustive]
6781pub struct SessionSystemPromptModeCapabilities {
6782    /// Whether the Agent supports `override` mode.
6783    ///
6784    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6785    /// Supplying `{}` means the Agent supports replacing its built-in default
6786    /// instructions with the Client-provided system prompt.
6787    #[serde_as(deserialize_as = "DefaultOnError")]
6788    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6789    #[serde(default, rename = "override")]
6790    pub override_: Option<SessionSystemPromptOverrideCapabilities>,
6791    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6792    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6793    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6794    ///
6795    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6796    #[serde_as(deserialize_as = "DefaultOnError")]
6797    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6798    #[serde(default)]
6799    #[serde(rename = "_meta")]
6800    pub meta: Option<Meta>,
6801}
6802
6803impl SessionSystemPromptModeCapabilities {
6804    /// Builds an empty [`SessionSystemPromptModeCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6805    #[must_use]
6806    pub fn new() -> Self {
6807        Self::default()
6808    }
6809
6810    /// Whether the Agent supports `override` mode.
6811    ///
6812    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
6813    /// Supplying `{}` means the Agent supports replacing its built-in default
6814    /// instructions with the Client-provided system prompt.
6815    #[must_use]
6816    pub fn override_(
6817        mut self,
6818        override_: impl IntoOption<SessionSystemPromptOverrideCapabilities>,
6819    ) -> Self {
6820        self.override_ = override_.into_option();
6821        self
6822    }
6823
6824    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6825    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6826    /// do not recognize.
6827    ///
6828    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6829    #[must_use]
6830    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6831        self.meta = meta.into_option();
6832        self
6833    }
6834}
6835
6836/// Capabilities for the `override` system prompt mode.
6837///
6838/// Supplying `{}` means the Agent supports replacing its built-in default
6839/// instructions with the Client-provided system prompt.
6840#[serde_as]
6841#[skip_serializing_none]
6842#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6843#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6844#[non_exhaustive]
6845pub struct SessionSystemPromptOverrideCapabilities {
6846    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6847    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6848    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6849    ///
6850    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6851    #[serde_as(deserialize_as = "DefaultOnError")]
6852    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6853    #[serde(default)]
6854    #[serde(rename = "_meta")]
6855    pub meta: Option<Meta>,
6856}
6857
6858impl SessionSystemPromptOverrideCapabilities {
6859    /// Builds an empty [`SessionSystemPromptOverrideCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6860    #[must_use]
6861    pub fn new() -> Self {
6862        Self::default()
6863    }
6864
6865    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6866    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6867    /// do not recognize.
6868    ///
6869    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6870    #[must_use]
6871    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6872        self.meta = meta.into_option();
6873        self
6874    }
6875}
6876
6877/// **UNSTABLE**
6878///
6879/// This capability is not part of the spec yet, and may be removed or changed at any point.
6880///
6881/// Capabilities for the `session/fork` method.
6882///
6883/// Supplying `{}` means the Agent supports forking sessions.
6884#[cfg(feature = "unstable_session_fork")]
6885#[serde_as]
6886#[skip_serializing_none]
6887#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6888#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6889#[non_exhaustive]
6890pub struct SessionForkCapabilities {
6891    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6892    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6893    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6894    ///
6895    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6896    #[serde_as(deserialize_as = "DefaultOnError")]
6897    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6898    #[serde(default)]
6899    #[serde(rename = "_meta")]
6900    pub meta: Option<Meta>,
6901}
6902
6903#[cfg(feature = "unstable_session_fork")]
6904impl SessionForkCapabilities {
6905    /// Builds an empty [`SessionForkCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6906    #[must_use]
6907    pub fn new() -> Self {
6908        Self::default()
6909    }
6910
6911    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6912    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6913    /// do not recognize.
6914    ///
6915    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6916    #[must_use]
6917    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6918        self.meta = meta.into_option();
6919        self
6920    }
6921}
6922
6923/// **UNSTABLE**
6924///
6925/// This capability is not part of the spec yet, and may be removed or changed at any point.
6926///
6927/// Capabilities for `session/archive` and `session/unarchive`.
6928///
6929/// Supplying `{}` means the Agent supports both methods, the `archived` filter on
6930/// `session/list`, and `SessionInfo.archived`.
6931#[cfg(feature = "unstable_session_archive")]
6932#[serde_as]
6933#[skip_serializing_none]
6934#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6935#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6936#[non_exhaustive]
6937pub struct SessionArchiveCapabilities {
6938    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6939    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6940    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6941    ///
6942    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6943    #[serde_as(deserialize_as = "DefaultOnError")]
6944    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6945    #[serde(default)]
6946    #[serde(rename = "_meta")]
6947    pub meta: Option<Meta>,
6948}
6949
6950#[cfg(feature = "unstable_session_archive")]
6951impl SessionArchiveCapabilities {
6952    /// Builds an empty [`SessionArchiveCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6953    #[must_use]
6954    pub fn new() -> Self {
6955        Self::default()
6956    }
6957
6958    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6959    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6960    /// do not recognize.
6961    ///
6962    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6963    #[must_use]
6964    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6965        self.meta = meta.into_option();
6966        self
6967    }
6968}
6969
6970/// **UNSTABLE**
6971///
6972/// This capability is not part of the spec yet, and may be removed or changed at any point.
6973///
6974/// Capabilities for the `session/status` method.
6975///
6976/// Supplying `{}` means the Agent supports checking session status.
6977#[cfg(feature = "unstable_session_status")]
6978#[serde_as]
6979#[skip_serializing_none]
6980#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6981#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6982#[non_exhaustive]
6983pub struct SessionStatusCapabilities {
6984    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6985    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6986    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6987    ///
6988    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6989    #[serde_as(deserialize_as = "DefaultOnError")]
6990    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6991    #[serde(default)]
6992    #[serde(rename = "_meta")]
6993    pub meta: Option<Meta>,
6994}
6995
6996#[cfg(feature = "unstable_session_status")]
6997impl SessionStatusCapabilities {
6998    /// Builds an empty [`SessionStatusCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6999    #[must_use]
7000    pub fn new() -> Self {
7001        Self::default()
7002    }
7003
7004    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7005    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7006    /// do not recognize.
7007    ///
7008    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7009    #[must_use]
7010    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7011        self.meta = meta.into_option();
7012        self
7013    }
7014}
7015
7016/// **UNSTABLE**
7017///
7018/// This capability is not part of the spec yet, and may be removed or changed at any point.
7019///
7020/// Capabilities for the `session/options` method.
7021///
7022/// Supplying `{}` means the Agent supports `session/options` and accepts initial config
7023/// option values on session setup requests.
7024#[cfg(feature = "unstable_session_options")]
7025#[serde_as]
7026#[skip_serializing_none]
7027#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7028#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7029#[non_exhaustive]
7030pub struct SessionOptionsCapabilities {
7031    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7032    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7033    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7034    ///
7035    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7036    #[serde_as(deserialize_as = "DefaultOnError")]
7037    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7038    #[serde(default)]
7039    #[serde(rename = "_meta")]
7040    pub meta: Option<Meta>,
7041}
7042
7043#[cfg(feature = "unstable_session_options")]
7044impl SessionOptionsCapabilities {
7045    /// Builds an empty [`SessionOptionsCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7046    #[must_use]
7047    pub fn new() -> Self {
7048        Self::default()
7049    }
7050
7051    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7052    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7053    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7054    ///
7055    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7056    #[must_use]
7057    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7058        self.meta = meta.into_option();
7059        self
7060    }
7061}
7062
7063/// **UNSTABLE**
7064///
7065/// This capability is not part of the spec yet, and may be removed or changed at any point.
7066///
7067/// Capabilities for Client-set session titles.
7068///
7069/// Supplying `{}` means the Agent supports `session/set_title`. Agents report titles
7070/// through `session/list` and `session_info_update` without this capability.
7071#[cfg(feature = "unstable_session_set_title")]
7072#[serde_as]
7073#[skip_serializing_none]
7074#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7075#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7076#[non_exhaustive]
7077pub struct SessionTitleCapabilities {
7078    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7079    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7080    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7081    ///
7082    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7083    #[serde_as(deserialize_as = "DefaultOnError")]
7084    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7085    #[serde(default)]
7086    #[serde(rename = "_meta")]
7087    pub meta: Option<Meta>,
7088}
7089
7090#[cfg(feature = "unstable_session_set_title")]
7091impl SessionTitleCapabilities {
7092    /// Builds an empty [`SessionTitleCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7093    #[must_use]
7094    pub fn new() -> Self {
7095        Self::default()
7096    }
7097
7098    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7099    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7100    /// do not recognize.
7101    ///
7102    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7103    #[must_use]
7104    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7105        self.meta = meta.into_option();
7106        self
7107    }
7108}
7109
7110/// Prompt capabilities supported by the Agent in `session/prompt` requests.
7111///
7112/// Baseline Agent functionality requires support for `text`
7113/// and `resource_link` content blocks in prompt requests.
7114///
7115/// Other content types need one of these capabilities.
7116/// Capabilities for different types of content in prompt requests.
7117///
7118/// Indicates which content types beyond the baseline (text and resource links)
7119/// the Agent can process.
7120///
7121/// See protocol docs: [Session Prompt Capabilities](https://agentclientprotocol.com/protocol/v2/initialization#session-prompt-capabilities)
7122#[serde_as]
7123#[skip_serializing_none]
7124#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7125#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7126#[serde(rename_all = "camelCase")]
7127#[non_exhaustive]
7128pub struct PromptCapabilities {
7129    /// Agent supports `image` content blocks.
7130    ///
7131    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
7132    /// Supplying `{}` means the Agent supports image content in prompts.
7133    #[serde_as(deserialize_as = "DefaultOnError")]
7134    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7135    #[serde(default)]
7136    pub image: Option<PromptImageCapabilities>,
7137    /// Agent supports `audio` content blocks.
7138    ///
7139    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
7140    /// Supplying `{}` means the Agent supports audio 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 audio: Option<PromptAudioCapabilities>,
7145    /// Agent supports embedded context in `session/prompt` requests.
7146    ///
7147    /// When enabled, the Client is allowed to include `resource` content blocks
7148    /// in prompt requests for pieces of context that are referenced in the message.
7149    ///
7150    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
7151    /// Supplying `{}` means the Agent supports embedded context in prompts.
7152    #[serde_as(deserialize_as = "DefaultOnError")]
7153    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7154    #[serde(default)]
7155    pub embedded_context: Option<PromptEmbeddedContextCapabilities>,
7156    /// **UNSTABLE**
7157    ///
7158    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7159    ///
7160    /// Agent supports `skill` content blocks.
7161    ///
7162    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
7163    /// Supplying `{}` means a prompt may contain one `skill` content block, as its first block.
7164    /// An Agent that sends `skill` entries in `availableCommands` MUST advertise this capability.
7165    #[cfg(feature = "unstable_agent_skills")]
7166    #[serde_as(deserialize_as = "DefaultOnError")]
7167    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7168    #[serde(default)]
7169    pub skill: Option<PromptSkillCapabilities>,
7170    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7171    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7172    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7173    ///
7174    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7175    #[serde_as(deserialize_as = "DefaultOnError")]
7176    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7177    #[serde(default)]
7178    #[serde(rename = "_meta")]
7179    pub meta: Option<Meta>,
7180}
7181
7182impl PromptCapabilities {
7183    /// Builds an empty [`PromptCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7184    #[must_use]
7185    pub fn new() -> Self {
7186        Self::default()
7187    }
7188
7189    /// Agent supports `image` content blocks.
7190    ///
7191    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
7192    /// Supplying `{}` means the Agent supports image content in prompts.
7193    #[must_use]
7194    pub fn image(mut self, image: impl IntoOption<PromptImageCapabilities>) -> Self {
7195        self.image = image.into_option();
7196        self
7197    }
7198
7199    /// Agent supports `audio` content blocks.
7200    ///
7201    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
7202    /// Supplying `{}` means the Agent supports audio content in prompts.
7203    #[must_use]
7204    pub fn audio(mut self, audio: impl IntoOption<PromptAudioCapabilities>) -> Self {
7205        self.audio = audio.into_option();
7206        self
7207    }
7208
7209    /// Agent supports embedded context in `session/prompt` requests.
7210    ///
7211    /// When enabled, the Client is allowed to include `resource` content blocks
7212    /// in prompt requests for pieces of context that are referenced in the message.
7213    ///
7214    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
7215    /// Supplying `{}` means the Agent supports embedded context in prompts.
7216    #[must_use]
7217    pub fn embedded_context(
7218        mut self,
7219        embedded_context: impl IntoOption<PromptEmbeddedContextCapabilities>,
7220    ) -> Self {
7221        self.embedded_context = embedded_context.into_option();
7222        self
7223    }
7224
7225    /// **UNSTABLE**
7226    ///
7227    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7228    ///
7229    /// Agent supports `skill` content blocks.
7230    ///
7231    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
7232    /// Supplying `{}` means a prompt may contain one `skill` content block, as its first block.
7233    #[cfg(feature = "unstable_agent_skills")]
7234    #[must_use]
7235    pub fn skill(mut self, skill: impl IntoOption<PromptSkillCapabilities>) -> Self {
7236        self.skill = skill.into_option();
7237        self
7238    }
7239
7240    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7241    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7242    /// do not recognize.
7243    ///
7244    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7245    #[must_use]
7246    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7247        self.meta = meta.into_option();
7248        self
7249    }
7250}
7251
7252/// Capabilities for image content in prompt requests.
7253///
7254/// Supplying `{}` means the Agent supports image content in prompts.
7255#[serde_as]
7256#[skip_serializing_none]
7257#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7258#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7259#[non_exhaustive]
7260pub struct PromptImageCapabilities {
7261    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7262    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7263    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7264    ///
7265    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7266    #[serde_as(deserialize_as = "DefaultOnError")]
7267    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7268    #[serde(default)]
7269    #[serde(rename = "_meta")]
7270    pub meta: Option<Meta>,
7271}
7272
7273impl PromptImageCapabilities {
7274    /// Builds an empty [`PromptImageCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7275    #[must_use]
7276    pub fn new() -> Self {
7277        Self::default()
7278    }
7279
7280    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7281    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7282    /// do not recognize.
7283    ///
7284    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7285    #[must_use]
7286    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7287        self.meta = meta.into_option();
7288        self
7289    }
7290}
7291
7292/// Capabilities for audio content in prompt requests.
7293///
7294/// Supplying `{}` means the Agent supports audio content in prompts.
7295#[serde_as]
7296#[skip_serializing_none]
7297#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7298#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7299#[non_exhaustive]
7300pub struct PromptAudioCapabilities {
7301    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7302    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7303    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7304    ///
7305    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7306    #[serde_as(deserialize_as = "DefaultOnError")]
7307    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7308    #[serde(default)]
7309    #[serde(rename = "_meta")]
7310    pub meta: Option<Meta>,
7311}
7312
7313impl PromptAudioCapabilities {
7314    /// Builds an empty [`PromptAudioCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7315    #[must_use]
7316    pub fn new() -> Self {
7317        Self::default()
7318    }
7319
7320    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7321    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7322    /// do not recognize.
7323    ///
7324    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7325    #[must_use]
7326    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7327        self.meta = meta.into_option();
7328        self
7329    }
7330}
7331
7332/// Capabilities for embedded context in prompt requests.
7333///
7334/// Supplying `{}` means the Agent supports embedded context in prompts.
7335#[serde_as]
7336#[skip_serializing_none]
7337#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7338#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7339#[non_exhaustive]
7340pub struct PromptEmbeddedContextCapabilities {
7341    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7342    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7343    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7344    ///
7345    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7346    #[serde_as(deserialize_as = "DefaultOnError")]
7347    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7348    #[serde(default)]
7349    #[serde(rename = "_meta")]
7350    pub meta: Option<Meta>,
7351}
7352
7353impl PromptEmbeddedContextCapabilities {
7354    /// Builds an empty [`PromptEmbeddedContextCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7355    #[must_use]
7356    pub fn new() -> Self {
7357        Self::default()
7358    }
7359
7360    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7361    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7362    /// do not recognize.
7363    ///
7364    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7365    #[must_use]
7366    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7367        self.meta = meta.into_option();
7368        self
7369    }
7370}
7371
7372/// **UNSTABLE**
7373///
7374/// This capability is not part of the spec yet, and may be removed or changed at any point.
7375///
7376/// Capabilities for `skill` content blocks in prompt requests.
7377///
7378/// Supplying `{}` means a prompt may contain one `skill` content block, as
7379/// its first block. The Agent opts in to more with the `inline` field.
7380#[cfg(feature = "unstable_agent_skills")]
7381#[serde_as]
7382#[skip_serializing_none]
7383#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7384#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7385#[serde(rename_all = "camelCase")]
7386#[non_exhaustive]
7387pub struct PromptSkillCapabilities {
7388    /// Agent supports `skill` content blocks at any position in a prompt.
7389    ///
7390    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
7391    /// Supplying `{}` means a prompt may contain any number of `skill` content blocks, at any
7392    /// position.
7393    #[serde_as(deserialize_as = "DefaultOnError")]
7394    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7395    #[serde(default)]
7396    pub inline: Option<PromptSkillInlineCapabilities>,
7397    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7398    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7399    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7400    ///
7401    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7402    #[serde_as(deserialize_as = "DefaultOnError")]
7403    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7404    #[serde(default)]
7405    #[serde(rename = "_meta")]
7406    pub meta: Option<Meta>,
7407}
7408
7409#[cfg(feature = "unstable_agent_skills")]
7410impl PromptSkillCapabilities {
7411    /// Builds an empty [`PromptSkillCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7412    #[must_use]
7413    pub fn new() -> Self {
7414        Self::default()
7415    }
7416
7417    /// Agent supports `skill` content blocks at any position in a prompt.
7418    ///
7419    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
7420    /// Supplying `{}` means a prompt may contain any number of `skill` content blocks, at any
7421    /// position.
7422    #[must_use]
7423    pub fn inline(mut self, inline: impl IntoOption<PromptSkillInlineCapabilities>) -> Self {
7424        self.inline = inline.into_option();
7425        self
7426    }
7427
7428    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7429    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7430    /// do not recognize.
7431    ///
7432    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7433    #[must_use]
7434    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7435        self.meta = meta.into_option();
7436        self
7437    }
7438}
7439
7440/// **UNSTABLE**
7441///
7442/// This capability is not part of the spec yet, and may be removed or changed at any point.
7443///
7444/// Capabilities for `skill` content blocks at any position in a prompt.
7445///
7446/// Supplying `{}` means a prompt may contain any number of `skill` content
7447/// blocks, at any position.
7448#[cfg(feature = "unstable_agent_skills")]
7449#[serde_as]
7450#[skip_serializing_none]
7451#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7452#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7453#[non_exhaustive]
7454pub struct PromptSkillInlineCapabilities {
7455    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7456    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7457    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7458    ///
7459    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7460    #[serde_as(deserialize_as = "DefaultOnError")]
7461    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7462    #[serde(default)]
7463    #[serde(rename = "_meta")]
7464    pub meta: Option<Meta>,
7465}
7466
7467#[cfg(feature = "unstable_agent_skills")]
7468impl PromptSkillInlineCapabilities {
7469    /// Builds an empty [`PromptSkillInlineCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7470    #[must_use]
7471    pub fn new() -> Self {
7472        Self::default()
7473    }
7474
7475    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7476    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7477    /// do not recognize.
7478    ///
7479    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7480    #[must_use]
7481    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7482        self.meta = meta.into_option();
7483        self
7484    }
7485}
7486
7487/// MCP capabilities supported by the Agent for session lifecycle requests.
7488#[serde_as]
7489#[skip_serializing_none]
7490#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7491#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7492#[serde(rename_all = "camelCase")]
7493#[non_exhaustive]
7494pub struct McpCapabilities {
7495    /// Agent supports `stdio` MCP servers.
7496    ///
7497    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
7498    /// Supplying `{}` means the Agent supports stdio MCP server transports.
7499    #[serde_as(deserialize_as = "DefaultOnError")]
7500    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7501    #[serde(default)]
7502    pub stdio: Option<McpStdioCapabilities>,
7503    /// Agent supports `http` MCP servers.
7504    ///
7505    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
7506    /// Supplying `{}` means the Agent supports HTTP 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 http: Option<McpHttpCapabilities>,
7511    /// **UNSTABLE**
7512    ///
7513    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7514    ///
7515    /// Agent supports `acp` MCP servers.
7516    ///
7517    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
7518    /// Supplying `{}` means the Agent supports ACP MCP server transports.
7519    #[cfg(feature = "unstable_mcp_over_acp")]
7520    #[serde_as(deserialize_as = "DefaultOnError")]
7521    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7522    #[serde(default)]
7523    pub acp: Option<McpAcpCapabilities>,
7524    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7525    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7526    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7527    ///
7528    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7529    #[serde_as(deserialize_as = "DefaultOnError")]
7530    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7531    #[serde(default)]
7532    #[serde(rename = "_meta")]
7533    pub meta: Option<Meta>,
7534}
7535
7536impl McpCapabilities {
7537    /// Builds an empty [`McpCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7538    #[must_use]
7539    pub fn new() -> Self {
7540        Self::default()
7541    }
7542
7543    /// Agent supports `stdio` MCP servers.
7544    ///
7545    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
7546    /// Supplying `{}` means the Agent supports stdio MCP server transports.
7547    #[must_use]
7548    pub fn stdio(mut self, stdio: impl IntoOption<McpStdioCapabilities>) -> Self {
7549        self.stdio = stdio.into_option();
7550        self
7551    }
7552
7553    /// Agent supports `http` MCP servers.
7554    ///
7555    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
7556    /// Supplying `{}` means the Agent supports HTTP MCP server transports.
7557    #[must_use]
7558    pub fn http(mut self, http: impl IntoOption<McpHttpCapabilities>) -> Self {
7559        self.http = http.into_option();
7560        self
7561    }
7562
7563    /// **UNSTABLE**
7564    ///
7565    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7566    ///
7567    /// Agent supports `acp` MCP servers.
7568    #[cfg(feature = "unstable_mcp_over_acp")]
7569    ///
7570    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
7571    /// Supplying `{}` means the Agent supports ACP MCP server transports.
7572    #[must_use]
7573    pub fn acp(mut self, acp: impl IntoOption<McpAcpCapabilities>) -> Self {
7574        self.acp = acp.into_option();
7575        self
7576    }
7577
7578    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7579    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7580    /// do not recognize.
7581    ///
7582    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7583    #[must_use]
7584    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7585        self.meta = meta.into_option();
7586        self
7587    }
7588}
7589
7590/// Capabilities for stdio MCP server transports.
7591///
7592/// Supplying `{}` means the Agent supports stdio MCP server transports.
7593#[serde_as]
7594#[skip_serializing_none]
7595#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7596#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7597#[non_exhaustive]
7598pub struct McpStdioCapabilities {
7599    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7600    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7601    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7602    ///
7603    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7604    #[serde_as(deserialize_as = "DefaultOnError")]
7605    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7606    #[serde(default)]
7607    #[serde(rename = "_meta")]
7608    pub meta: Option<Meta>,
7609}
7610
7611impl McpStdioCapabilities {
7612    /// Builds an empty [`McpStdioCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7613    #[must_use]
7614    pub fn new() -> Self {
7615        Self::default()
7616    }
7617
7618    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7619    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7620    /// do not recognize.
7621    ///
7622    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7623    #[must_use]
7624    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7625        self.meta = meta.into_option();
7626        self
7627    }
7628}
7629
7630/// Capabilities for HTTP MCP server transports.
7631///
7632/// Supplying `{}` means the Agent supports HTTP MCP server transports.
7633#[serde_as]
7634#[skip_serializing_none]
7635#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7636#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7637#[non_exhaustive]
7638pub struct McpHttpCapabilities {
7639    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7640    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7641    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7642    ///
7643    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7644    #[serde_as(deserialize_as = "DefaultOnError")]
7645    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7646    #[serde(default)]
7647    #[serde(rename = "_meta")]
7648    pub meta: Option<Meta>,
7649}
7650
7651impl McpHttpCapabilities {
7652    /// Builds an empty [`McpHttpCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7653    #[must_use]
7654    pub fn new() -> Self {
7655        Self::default()
7656    }
7657
7658    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7659    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7660    /// do not recognize.
7661    ///
7662    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7663    #[must_use]
7664    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7665        self.meta = meta.into_option();
7666        self
7667    }
7668}
7669
7670/// **UNSTABLE**
7671///
7672/// This capability is not part of the spec yet, and may be removed or changed at any point.
7673///
7674/// Capabilities for ACP MCP server transports.
7675///
7676/// Supplying `{}` means the Agent supports ACP MCP server transports.
7677#[cfg(feature = "unstable_mcp_over_acp")]
7678#[serde_as]
7679#[skip_serializing_none]
7680#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7681#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7682#[non_exhaustive]
7683pub struct McpAcpCapabilities {
7684    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7685    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7686    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7687    ///
7688    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7689    #[serde_as(deserialize_as = "DefaultOnError")]
7690    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7691    #[serde(default)]
7692    #[serde(rename = "_meta")]
7693    pub meta: Option<Meta>,
7694}
7695
7696#[cfg(feature = "unstable_mcp_over_acp")]
7697impl McpAcpCapabilities {
7698    /// Builds an empty [`McpAcpCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7699    #[must_use]
7700    pub fn new() -> Self {
7701        Self::default()
7702    }
7703
7704    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7705    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7706    /// do not recognize.
7707    ///
7708    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7709    #[must_use]
7710    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7711        self.meta = meta.into_option();
7712        self
7713    }
7714}
7715
7716/// Cancels the named session's active foreground work and earlier prompts not yet inserted.
7717/// It does not cancel later submissions or work in the session's latest `background` list.
7718///
7719/// See protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#cancellation)
7720#[serde_as]
7721#[skip_serializing_none]
7722#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7723#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7724#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CANCEL_METHOD_NAME)))]
7725#[serde(rename_all = "camelCase")]
7726#[non_exhaustive]
7727pub struct CancelSessionNotification {
7728    /// The ID of the session whose foreground work to cancel.
7729    pub session_id: SessionId,
7730    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7731    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7732    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7733    ///
7734    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7735    #[serde_as(deserialize_as = "DefaultOnError")]
7736    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7737    #[serde(default)]
7738    #[serde(rename = "_meta")]
7739    pub meta: Option<Meta>,
7740}
7741
7742impl CancelSessionNotification {
7743    /// Builds [`CancelSessionNotification`] with the required notification fields set. Optional fields start unset or empty.
7744    #[must_use]
7745    pub fn new(session_id: impl Into<SessionId>) -> Self {
7746        Self {
7747            session_id: session_id.into(),
7748            meta: None,
7749        }
7750    }
7751
7752    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7753    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7754    /// do not recognize.
7755    ///
7756    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7757    #[must_use]
7758    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7759        self.meta = meta.into_option();
7760        self
7761    }
7762}
7763
7764// Method schema
7765
7766/// Names of all methods that Agents handle.
7767///
7768/// Provides a centralized definition of method names used in the protocol.
7769#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7770#[non_exhaustive]
7771pub struct AgentMethodNames {
7772    /// Method for initializing the connection.
7773    pub initialize: &'static str,
7774    /// Method for authenticating with the Agent.
7775    pub auth_login: &'static str,
7776    /// Method for listing configurable providers.
7777    #[cfg(feature = "unstable_llm_providers")]
7778    pub providers_list: &'static str,
7779    /// Method for setting provider configuration.
7780    #[cfg(feature = "unstable_llm_providers")]
7781    pub providers_set: &'static str,
7782    /// Method for disabling a provider.
7783    #[cfg(feature = "unstable_llm_providers")]
7784    pub providers_disable: &'static str,
7785    /// Method for creating a new session.
7786    pub session_new: &'static str,
7787    /// Method for setting a configuration option for a session.
7788    pub session_set_config_option: &'static str,
7789    /// Method for sending a prompt to the Agent.
7790    pub session_prompt: &'static str,
7791    /// Notification for cancelling operations.
7792    pub session_cancel: &'static str,
7793    /// Method for exchanging MCP-over-ACP messages.
7794    #[cfg(feature = "unstable_mcp_over_acp")]
7795    pub mcp_message: &'static str,
7796    /// Method for listing existing sessions.
7797    pub session_list: &'static str,
7798    /// Method for deleting an existing session.
7799    pub session_delete: &'static str,
7800    /// Method for forking an existing session.
7801    #[cfg(feature = "unstable_session_fork")]
7802    pub session_fork: &'static str,
7803    /// Method for archiving a session.
7804    #[cfg(feature = "unstable_session_archive")]
7805    pub session_archive: &'static str,
7806    /// Method for unarchiving a session.
7807    #[cfg(feature = "unstable_session_archive")]
7808    pub session_unarchive: &'static str,
7809    /// Method for checking the status of a session.
7810    #[cfg(feature = "unstable_session_status")]
7811    pub session_status: &'static str,
7812    /// Method for querying the config options a session would start with.
7813    #[cfg(feature = "unstable_session_options")]
7814    pub session_options: &'static str,
7815    /// Method for setting the title of a session.
7816    #[cfg(feature = "unstable_session_set_title")]
7817    pub session_set_title: &'static str,
7818    /// Method for resuming an existing session.
7819    pub session_resume: &'static str,
7820    /// Method for closing an active session.
7821    pub session_close: &'static str,
7822    /// Method for cancelling one tool call.
7823    pub tool_call_cancel: &'static str,
7824    /// Method for cancelling one terminal's process.
7825    pub terminal_cancel: &'static str,
7826    /// Method for logging out of an authenticated session.
7827    pub auth_logout: &'static str,
7828    /// Method for querying the Agent's authentication state.
7829    #[cfg(feature = "unstable_auth_status")]
7830    pub auth_status: &'static str,
7831}
7832
7833/// Constant containing all Agent method names.
7834pub const AGENT_METHOD_NAMES: AgentMethodNames = AgentMethodNames {
7835    initialize: INITIALIZE_METHOD_NAME,
7836    auth_login: AUTH_LOGIN_METHOD_NAME,
7837    #[cfg(feature = "unstable_llm_providers")]
7838    providers_list: PROVIDERS_LIST_METHOD_NAME,
7839    #[cfg(feature = "unstable_llm_providers")]
7840    providers_set: PROVIDERS_SET_METHOD_NAME,
7841    #[cfg(feature = "unstable_llm_providers")]
7842    providers_disable: PROVIDERS_DISABLE_METHOD_NAME,
7843    session_new: SESSION_NEW_METHOD_NAME,
7844    session_set_config_option: SESSION_SET_CONFIG_OPTION_METHOD_NAME,
7845    session_prompt: SESSION_PROMPT_METHOD_NAME,
7846    session_cancel: SESSION_CANCEL_METHOD_NAME,
7847    #[cfg(feature = "unstable_mcp_over_acp")]
7848    mcp_message: MCP_MESSAGE_METHOD_NAME,
7849    session_list: SESSION_LIST_METHOD_NAME,
7850    session_delete: SESSION_DELETE_METHOD_NAME,
7851    #[cfg(feature = "unstable_session_fork")]
7852    session_fork: SESSION_FORK_METHOD_NAME,
7853    #[cfg(feature = "unstable_session_archive")]
7854    session_archive: SESSION_ARCHIVE_METHOD_NAME,
7855    #[cfg(feature = "unstable_session_archive")]
7856    session_unarchive: SESSION_UNARCHIVE_METHOD_NAME,
7857    #[cfg(feature = "unstable_session_status")]
7858    session_status: SESSION_STATUS_METHOD_NAME,
7859    #[cfg(feature = "unstable_session_options")]
7860    session_options: SESSION_OPTIONS_METHOD_NAME,
7861    #[cfg(feature = "unstable_session_set_title")]
7862    session_set_title: SESSION_SET_TITLE_METHOD_NAME,
7863    session_resume: SESSION_RESUME_METHOD_NAME,
7864    session_close: SESSION_CLOSE_METHOD_NAME,
7865    tool_call_cancel: TOOL_CALL_CANCEL_METHOD_NAME,
7866    terminal_cancel: TERMINAL_CANCEL_METHOD_NAME,
7867    auth_logout: AUTH_LOGOUT_METHOD_NAME,
7868    #[cfg(feature = "unstable_auth_status")]
7869    auth_status: AUTH_STATUS_METHOD_NAME,
7870};
7871
7872/// Method name for the initialize request.
7873pub(crate) const INITIALIZE_METHOD_NAME: &str = "initialize";
7874/// Method name for the `auth/login` request.
7875pub(crate) const AUTH_LOGIN_METHOD_NAME: &str = "auth/login";
7876/// Method name for listing configurable providers.
7877#[cfg(feature = "unstable_llm_providers")]
7878pub(crate) const PROVIDERS_LIST_METHOD_NAME: &str = "providers/list";
7879/// Method name for setting provider configuration.
7880#[cfg(feature = "unstable_llm_providers")]
7881pub(crate) const PROVIDERS_SET_METHOD_NAME: &str = "providers/set";
7882/// Method name for disabling a provider.
7883#[cfg(feature = "unstable_llm_providers")]
7884pub(crate) const PROVIDERS_DISABLE_METHOD_NAME: &str = "providers/disable";
7885/// Method name for creating a new session.
7886pub(crate) const SESSION_NEW_METHOD_NAME: &str = "session/new";
7887/// Method name for setting a configuration option for a session.
7888pub(crate) const SESSION_SET_CONFIG_OPTION_METHOD_NAME: &str = "session/set_config_option";
7889/// Method name for sending a prompt.
7890pub(crate) const SESSION_PROMPT_METHOD_NAME: &str = "session/prompt";
7891/// Method name for the cancel notification.
7892pub(crate) const SESSION_CANCEL_METHOD_NAME: &str = "session/cancel";
7893/// Method name for listing existing sessions.
7894pub(crate) const SESSION_LIST_METHOD_NAME: &str = "session/list";
7895/// Method name for deleting an existing session.
7896pub(crate) const SESSION_DELETE_METHOD_NAME: &str = "session/delete";
7897/// Method name for forking an existing session.
7898#[cfg(feature = "unstable_session_fork")]
7899pub(crate) const SESSION_FORK_METHOD_NAME: &str = "session/fork";
7900/// Method name for archiving a session.
7901#[cfg(feature = "unstable_session_archive")]
7902pub(crate) const SESSION_ARCHIVE_METHOD_NAME: &str = "session/archive";
7903/// Method name for unarchiving a session.
7904#[cfg(feature = "unstable_session_archive")]
7905pub(crate) const SESSION_UNARCHIVE_METHOD_NAME: &str = "session/unarchive";
7906/// Method name for checking the status of a session.
7907#[cfg(feature = "unstable_session_status")]
7908pub(crate) const SESSION_STATUS_METHOD_NAME: &str = "session/status";
7909/// Method name for querying the config options a session would start with.
7910#[cfg(feature = "unstable_session_options")]
7911pub(crate) const SESSION_OPTIONS_METHOD_NAME: &str = "session/options";
7912/// Method name for setting the title of a session.
7913#[cfg(feature = "unstable_session_set_title")]
7914pub(crate) const SESSION_SET_TITLE_METHOD_NAME: &str = "session/set_title";
7915/// Method name for resuming an existing session.
7916pub(crate) const SESSION_RESUME_METHOD_NAME: &str = "session/resume";
7917/// Method name for closing an active session.
7918pub(crate) const SESSION_CLOSE_METHOD_NAME: &str = "session/close";
7919/// Method name for cancelling one tool call.
7920pub(crate) const TOOL_CALL_CANCEL_METHOD_NAME: &str = "tool_call/cancel";
7921/// Method name for cancelling one terminal's process.
7922pub(crate) const TERMINAL_CANCEL_METHOD_NAME: &str = "terminal/cancel";
7923/// Method name for the `auth/logout` request.
7924pub(crate) const AUTH_LOGOUT_METHOD_NAME: &str = "auth/logout";
7925/// Method name for the `auth/status` request.
7926#[cfg(feature = "unstable_auth_status")]
7927pub(crate) const AUTH_STATUS_METHOD_NAME: &str = "auth/status";
7928
7929/// All possible requests that a Client can send to an Agent.
7930///
7931/// This enum is used internally for routing RPC requests. You typically won't need
7932/// to use this directly.
7933///
7934/// This enum encompasses all method calls from Client to Agent.
7935#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7936#[derive(Clone, Debug, Serialize, Deserialize)]
7937#[serde(untagged)]
7938#[cfg_attr(feature = "schemars", schemars(inline))]
7939#[non_exhaustive]
7940pub enum ClientRequest {
7941    /// Establishes the connection with a Client and negotiates protocol capabilities.
7942    ///
7943    /// This method is called at the beginning of the connection, before any other request, to:
7944    /// - Negotiate the protocol version to use
7945    /// - Exchange capability information between Client and Agent
7946    /// - Determine available authentication methods
7947    ///
7948    /// The Client MAY repeat it before its first other request. The latest successful
7949    /// `initialize` is authoritative.
7950    ///
7951    /// The Agent responds with its supported protocol version and capabilities.
7952    ///
7953    /// See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/v2/initialization)
7954    InitializeRequest(Box<InitializeRequest>),
7955    /// Authenticates the Client using the specified authentication method.
7956    ///
7957    /// Agents MUST support this method when their `initialize` response included
7958    /// a non-empty `authMethods` list. Clients MUST call this method only
7959    /// with a method whose type defines a protocol-driven login flow, and MUST NOT
7960    /// call it when `authMethods` was omitted or empty.
7961    ///
7962    /// Called when the Agent requires authentication before allowing session creation.
7963    /// The Client provides the authentication method ID that was advertised during initialization.
7964    ///
7965    /// After successful authentication, the Client can proceed to create sessions with
7966    /// `session/new` without receiving a `-32000` (Authentication required) error.
7967    ///
7968    /// See protocol docs: [Authentication](https://agentclientprotocol.com/protocol/v2/authentication)
7969    LoginAuthRequest(Box<LoginAuthRequest>),
7970    /// **UNSTABLE**
7971    ///
7972    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7973    ///
7974    /// Lists providers that can be configured by the Client.
7975    #[cfg(feature = "unstable_llm_providers")]
7976    ListProvidersRequest(Box<ListProvidersRequest>),
7977    /// **UNSTABLE**
7978    ///
7979    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7980    ///
7981    /// Replaces the configuration for a provider.
7982    #[cfg(feature = "unstable_llm_providers")]
7983    SetProviderRequest(Box<SetProviderRequest>),
7984    /// **UNSTABLE**
7985    ///
7986    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7987    ///
7988    /// Disables a provider.
7989    #[cfg(feature = "unstable_llm_providers")]
7990    DisableProviderRequest(Box<DisableProviderRequest>),
7991    /// Logs out of the current authenticated state.
7992    ///
7993    /// Agents MUST support this method when their `initialize` response included
7994    /// a non-empty `authMethods` list. Clients MUST NOT call this method
7995    /// when `authMethods` was omitted or empty.
7996    ///
7997    /// After a successful logout, authentication-gated requests require the
7998    /// Client to complete an advertised authentication flow again. There is no
7999    /// guarantee about the behavior of already running sessions.
8000    LogoutAuthRequest(Box<LogoutAuthRequest>),
8001    /// **UNSTABLE**
8002    ///
8003    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8004    ///
8005    /// Queries the Agent's current authentication state.
8006    ///
8007    /// This method is only available if the Agent advertises the `auth.status` capability.
8008    /// It MUST NOT change any Agent state, and Agents MUST NOT reject it with `-32000` (Authentication required).
8009    #[cfg(feature = "unstable_auth_status")]
8010    AuthStatusRequest(Box<AuthStatusRequest>),
8011    /// Creates a new conversation session with the Agent.
8012    ///
8013    /// Sessions represent independent conversation contexts with their own history and state.
8014    ///
8015    /// The Agent:
8016    /// - Creates a new session context
8017    /// - Connects to the specified MCP servers
8018    /// - Returns a unique session ID for future requests
8019    ///
8020    /// Fails with `-32000` (Authentication required) if the Agent requires authentication.
8021    ///
8022    /// See protocol docs: [Session Setup](https://agentclientprotocol.com/protocol/v2/session-setup)
8023    NewSessionRequest(Box<NewSessionRequest>),
8024    /// Lists existing sessions known to the Agent.
8025    ///
8026    /// The Agent returns metadata about sessions, with optional filtering and pagination.
8027    ListSessionsRequest(Box<ListSessionsRequest>),
8028    /// Deletes an existing session from `session/list`.
8029    ///
8030    /// This method is only available if the Agent advertises the `session.delete` capability.
8031    DeleteSessionRequest(Box<DeleteSessionRequest>),
8032    #[cfg(feature = "unstable_session_fork")]
8033    /// **UNSTABLE**
8034    ///
8035    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8036    ///
8037    /// Forks an existing session to create a new independent session.
8038    ///
8039    /// This method is only available if the Agent advertises the `session.fork` capability.
8040    ///
8041    /// The Agent creates a new session with the same conversation context as the
8042    /// original. The fork can be used for operations like generating summaries without
8043    /// affecting the original session's history.
8044    ///
8045    /// As with `session/new`, the forked session is active once the Agent responds,
8046    /// set up with the request's `cwd`, `additionalDirectories`, and `mcpServers`.
8047    /// The Client can prompt it without calling `session/resume` first.
8048    ForkSessionRequest(Box<ForkSessionRequest>),
8049    #[cfg(feature = "unstable_session_archive")]
8050    /// **UNSTABLE**
8051    ///
8052    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8053    ///
8054    /// Archives a session, hiding it from default `session/list` results.
8055    ///
8056    /// This method is only available if the Agent advertises the `session.archive` capability.
8057    ArchiveSessionRequest(Box<ArchiveSessionRequest>),
8058    #[cfg(feature = "unstable_session_archive")]
8059    /// **UNSTABLE**
8060    ///
8061    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8062    ///
8063    /// Unarchives a session, returning it to default `session/list` results.
8064    ///
8065    /// This method is only available if the Agent advertises the `session.archive` capability.
8066    UnarchiveSessionRequest(Box<UnarchiveSessionRequest>),
8067    #[cfg(feature = "unstable_session_status")]
8068    /// **UNSTABLE**
8069    ///
8070    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8071    ///
8072    /// Checks whether the Agent has a session in memory, without changing it.
8073    ///
8074    /// This method is only available if the Agent advertises the `session.status` capability.
8075    SessionStatusRequest(Box<SessionStatusRequest>),
8076    #[cfg(feature = "unstable_session_options")]
8077    /// **UNSTABLE**
8078    ///
8079    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8080    ///
8081    /// Returns the config options a session would start with, without creating or resuming a session.
8082    ///
8083    /// This method is only available if the Agent advertises the `session.options` capability.
8084    SessionOptionsRequest(Box<SessionOptionsRequest>),
8085    #[cfg(feature = "unstable_session_set_title")]
8086    /// **UNSTABLE**
8087    ///
8088    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8089    ///
8090    /// Sets the title of a session.
8091    ///
8092    /// This method is only available if the Agent advertises the `session.title` capability.
8093    ///
8094    /// The session does not need to be active on the connection. The Agent stores the
8095    /// title and returns the stored title, which may be normalized.
8096    SetSessionTitleRequest(Box<SetSessionTitleRequest>),
8097    /// Resumes an existing session.
8098    ///
8099    /// The Agent resumes the session context so that the conversation
8100    /// can continue. If `replayFrom` is set, the Agent replays
8101    /// retained conversation history before responding.
8102    ResumeSessionRequest(Box<ResumeSessionRequest>),
8103    /// Closes an active session and frees up any resources associated with it.
8104    ///
8105    /// The Agent MUST cancel any ongoing work as if `session/cancel` was called, stop the
8106    /// session's background work, and then free the resources associated with the session.
8107    CloseSessionRequest(Box<CloseSessionRequest>),
8108    /// Cancels one tool call without cancelling the rest of the session's work.
8109    ///
8110    /// This method is only available while the tool call advertises `capabilities.cancel`.
8111    /// The response means the Agent accepted the cancellation. A final `tool_call_update`
8112    /// confirms it.
8113    CancelToolCallRequest(Box<CancelToolCallRequest>),
8114    /// Stops one terminal's process without cancelling the rest of the session's work.
8115    ///
8116    /// This method is only available while the terminal advertises `capabilities.cancel`.
8117    /// The response means the Agent accepted the cancellation. A `terminal_update` with
8118    /// `exitStatus` confirms it.
8119    CancelTerminalRequest(Box<CancelTerminalRequest>),
8120    /// Sets the current value for a session configuration option.
8121    SetSessionConfigOptionRequest(Box<SetSessionConfigOptionRequest>),
8122    /// Processes a user prompt within a session.
8123    ///
8124    /// Acceptance means adding a logical user message with an ID and a position
8125    /// relative to other messages in the ACP conversation, not receipt or queueing.
8126    /// The Agent MUST return the inserted message's ID without waiting for
8127    /// processing to finish.
8128    ///
8129    /// The Agent reports the user message with the same ID through `session/update`.
8130    /// This notification can arrive before or after the response, and MUST NOT
8131    /// precede insertion. Processing state, output, tool calls, and completion are
8132    /// also reported through session updates.
8133    ///
8134    /// An error response means the user message was not inserted. Once it is
8135    /// inserted, the Agent MUST NOT answer with an error, even if the work fails
8136    /// before the response is sent. It ends that work with the `error` stop reason.
8137    ///
8138    /// A rejected submission produces no user-message updates. Foreground state
8139    /// follows its normal lifecycle independently of the request outcome:
8140    /// `running` may precede insertion, and rejection alone does not imply `idle`.
8141    ///
8142    /// See protocol docs: [Prompt Lifecycle](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle)
8143    PromptRequest(Box<PromptRequest>),
8144    /// Handles extension method requests from the Client.
8145    ///
8146    /// Extension methods are custom methods that are not part of the ACP spec.
8147    ///
8148    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
8149    ExtMethodRequest(Box<ExtRequest>),
8150}
8151
8152impl_request_dispatch! {
8153    ClientRequest => AgentResponse {
8154        InitializeRequest => InitializeResponse: AGENT_METHOD_NAMES.initialize,
8155        LoginAuthRequest => LoginAuthResponse: AGENT_METHOD_NAMES.auth_login,
8156        #[cfg(feature = "unstable_llm_providers")]
8157        ListProvidersRequest => ListProvidersResponse: AGENT_METHOD_NAMES.providers_list,
8158        #[cfg(feature = "unstable_llm_providers")]
8159        SetProviderRequest => SetProviderResponse: AGENT_METHOD_NAMES.providers_set,
8160        #[cfg(feature = "unstable_llm_providers")]
8161        DisableProviderRequest => DisableProviderResponse: AGENT_METHOD_NAMES.providers_disable,
8162        LogoutAuthRequest => LogoutAuthResponse: AGENT_METHOD_NAMES.auth_logout,
8163        #[cfg(feature = "unstable_auth_status")]
8164        AuthStatusRequest => AuthStatusResponse: AGENT_METHOD_NAMES.auth_status,
8165        NewSessionRequest => NewSessionResponse: AGENT_METHOD_NAMES.session_new,
8166        ListSessionsRequest => ListSessionsResponse: AGENT_METHOD_NAMES.session_list,
8167        DeleteSessionRequest => DeleteSessionResponse: AGENT_METHOD_NAMES.session_delete,
8168        #[cfg(feature = "unstable_session_fork")]
8169        ForkSessionRequest => ForkSessionResponse: AGENT_METHOD_NAMES.session_fork,
8170        #[cfg(feature = "unstable_session_archive")]
8171        ArchiveSessionRequest => ArchiveSessionResponse: AGENT_METHOD_NAMES.session_archive,
8172        #[cfg(feature = "unstable_session_archive")]
8173        UnarchiveSessionRequest => UnarchiveSessionResponse: AGENT_METHOD_NAMES.session_unarchive,
8174        #[cfg(feature = "unstable_session_status")]
8175        SessionStatusRequest => SessionStatusResponse: AGENT_METHOD_NAMES.session_status,
8176        #[cfg(feature = "unstable_session_options")]
8177        SessionOptionsRequest => SessionOptionsResponse: AGENT_METHOD_NAMES.session_options,
8178        #[cfg(feature = "unstable_session_set_title")]
8179        SetSessionTitleRequest => SetSessionTitleResponse: AGENT_METHOD_NAMES.session_set_title,
8180        ResumeSessionRequest => ResumeSessionResponse: AGENT_METHOD_NAMES.session_resume,
8181        CloseSessionRequest => CloseSessionResponse: AGENT_METHOD_NAMES.session_close,
8182        CancelToolCallRequest => CancelToolCallResponse: AGENT_METHOD_NAMES.tool_call_cancel,
8183        CancelTerminalRequest => CancelTerminalResponse: AGENT_METHOD_NAMES.terminal_cancel,
8184        SetSessionConfigOptionRequest => SetSessionConfigOptionResponse: AGENT_METHOD_NAMES.session_set_config_option,
8185        PromptRequest => PromptResponse: AGENT_METHOD_NAMES.session_prompt,
8186    }
8187    extension ExtMethodRequest(Box<ExtRequest>) => ExtMethodResponse;
8188}
8189
8190/// All possible responses that an Agent can send to a Client.
8191///
8192/// This enum is used internally for routing RPC responses. You typically won't need
8193/// to use this directly. The connection handles the responses automatically.
8194///
8195/// These are responses to the corresponding `ClientRequest` variants.
8196#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
8197#[derive(Clone, Debug, Serialize, Deserialize)]
8198#[serde(untagged)]
8199#[cfg_attr(feature = "schemars", schemars(inline))]
8200#[non_exhaustive]
8201pub enum AgentResponse {
8202    /// Successful result returned for a `initialize` request.
8203    InitializeResponse(Box<InitializeResponse>),
8204    /// Successful result returned for an `auth/login` request.
8205    LoginAuthResponse(#[serde(default)] Box<LoginAuthResponse>),
8206    /// Successful result returned for a `providers/list` request.
8207    #[cfg(feature = "unstable_llm_providers")]
8208    ListProvidersResponse(Box<ListProvidersResponse>),
8209    /// Successful result returned for a `providers/set` request.
8210    #[cfg(feature = "unstable_llm_providers")]
8211    SetProviderResponse(#[serde(default)] Box<SetProviderResponse>),
8212    /// Successful result returned for a `providers/disable` request.
8213    #[cfg(feature = "unstable_llm_providers")]
8214    DisableProviderResponse(#[serde(default)] Box<DisableProviderResponse>),
8215    /// Successful result returned for an `auth/logout` request.
8216    LogoutAuthResponse(#[serde(default)] Box<LogoutAuthResponse>),
8217    /// Successful result returned for an `auth/status` request.
8218    #[cfg(feature = "unstable_auth_status")]
8219    AuthStatusResponse(Box<AuthStatusResponse>),
8220    /// Successful result returned for a `session/new` request.
8221    NewSessionResponse(Box<NewSessionResponse>),
8222    /// Successful result returned for a `session/list` request.
8223    ListSessionsResponse(Box<ListSessionsResponse>),
8224    /// Successful result returned for a `session/delete` request.
8225    DeleteSessionResponse(#[serde(default)] Box<DeleteSessionResponse>),
8226    /// Successful result returned for a `session/fork` request.
8227    #[cfg(feature = "unstable_session_fork")]
8228    ForkSessionResponse(Box<ForkSessionResponse>),
8229    /// Successful result returned for a `session/archive` request.
8230    #[cfg(feature = "unstable_session_archive")]
8231    ArchiveSessionResponse(#[serde(default)] Box<ArchiveSessionResponse>),
8232    /// Successful result returned for a `session/unarchive` request.
8233    #[cfg(feature = "unstable_session_archive")]
8234    UnarchiveSessionResponse(#[serde(default)] Box<UnarchiveSessionResponse>),
8235    /// Successful result returned for a `session/status` request.
8236    #[cfg(feature = "unstable_session_status")]
8237    SessionStatusResponse(Box<SessionStatusResponse>),
8238    /// Successful result returned for a `session/options` request.
8239    #[cfg(feature = "unstable_session_options")]
8240    SessionOptionsResponse(#[serde(default)] Box<SessionOptionsResponse>),
8241    /// Successful result returned for a `session/set_title` request.
8242    #[cfg(feature = "unstable_session_set_title")]
8243    SetSessionTitleResponse(Box<SetSessionTitleResponse>),
8244    /// Successful result returned for a `session/resume` request.
8245    ResumeSessionResponse(#[serde(default)] Box<ResumeSessionResponse>),
8246    /// Successful result returned for a `session/close` request.
8247    CloseSessionResponse(#[serde(default)] Box<CloseSessionResponse>),
8248    /// Successful result returned for a `tool_call/cancel` request.
8249    CancelToolCallResponse(#[serde(default)] Box<CancelToolCallResponse>),
8250    /// Successful result returned for a `terminal/cancel` request.
8251    CancelTerminalResponse(#[serde(default)] Box<CancelTerminalResponse>),
8252    /// Successful result returned for a `session/set_config_option` request.
8253    SetSessionConfigOptionResponse(Box<SetSessionConfigOptionResponse>),
8254    /// Successful result returned for a `session/prompt` request.
8255    PromptResponse(Box<PromptResponse>),
8256    /// Successful result returned by an extension method outside the core ACP method set.
8257    ExtMethodResponse(Box<ExtResponse>),
8258}
8259
8260/// All possible notifications that a Client can send to an Agent.
8261///
8262/// This enum is used internally for routing RPC notifications. You typically won't need
8263/// to use this directly.
8264///
8265/// Notifications do not expect a response.
8266#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
8267#[derive(Clone, Debug, Serialize, Deserialize)]
8268#[serde(untagged)]
8269#[cfg_attr(feature = "schemars", schemars(inline))]
8270#[non_exhaustive]
8271pub enum ClientNotification {
8272    /// Cancels the named session's active foreground work and earlier prompts not yet inserted.
8273    /// The Agent MUST answer those uninserted prompts with `-32800`. Inserted prompts still
8274    /// succeed with their `messageId`. This cancellation does not cover later submissions.
8275    ///
8276    /// Work in the latest `background` list is not covered and keeps running. The
8277    /// Agent MAY stop background activity it does not list.
8278    ///
8279    /// Upon receiving this notification, the Agent SHOULD stop all language model
8280    /// requests and all tool call invocations of the cancelled foreground work as soon
8281    /// as possible.
8282    ///
8283    /// The Agent MUST stop waiting for pending `session/request_permission` requests of
8284    /// the cancelled work and treat them as not approved. It MUST cancel each of them
8285    /// with `$/cancel_request`.
8286    ///
8287    /// When cancellation stops active foreground work, the Agent MUST send that work's
8288    /// pending updates, then an idle `state_update` with `stopReason: "cancelled"`,
8289    /// before starting new foreground work in the same session. A later prompt can be
8290    /// inserted and acknowledged before that idle update, or held with its response
8291    /// pending. Listed background work can report updates before or after it.
8292    /// No additional idle update is required if no foreground work was active.
8293    ///
8294    /// After cancellation completes, the Agent SHOULD ignore late answers rather
8295    /// than use them to resume the cancelled work.
8296    ///
8297    /// Agents MUST catch errors caused by aborting cancelled work and report the
8298    /// `cancelled` stop reason, not `error`.
8299    ///
8300    /// See protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#cancellation)
8301    CancelSessionNotification(Box<CancelSessionNotification>),
8302    /// **UNSTABLE**
8303    ///
8304    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8305    ///
8306    /// Sends an MCP-over-ACP notification.
8307    #[cfg(feature = "unstable_mcp_over_acp")]
8308    MessageMcpNotification(Box<MessageMcpNotification>),
8309    /// Handles extension notifications from the Client.
8310    ///
8311    /// Extension notifications are custom one-way messages that are not part of the ACP spec.
8312    ///
8313    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
8314    ExtNotification(Box<ExtNotification>),
8315}
8316
8317impl_message_dispatch! {
8318    ClientNotification {
8319        CancelSessionNotification => AGENT_METHOD_NAMES.session_cancel,
8320        #[cfg(feature = "unstable_mcp_over_acp")]
8321        MessageMcpNotification => AGENT_METHOD_NAMES.mcp_message,
8322    }
8323    extension ExtNotification(Box<ExtNotification>);
8324}
8325
8326#[cfg(test)]
8327mod test_serialization {
8328    use std::path::PathBuf;
8329
8330    use super::*;
8331    use serde_json::json;
8332
8333    fn test_meta() -> Meta {
8334        json!({ "source": "test" }).as_object().unwrap().clone()
8335    }
8336
8337    #[test]
8338    fn list_sessions_cursor_and_session_directories_are_strict() {
8339        for cursor in [json!(null), json!("next")] {
8340            let response = json!({ "sessions": [], "nextCursor": cursor });
8341            serde_json::from_value::<ListSessionsResponse>(response).unwrap();
8342        }
8343        let malformed = json!({ "sessions": [], "nextCursor": 42 });
8344        assert!(serde_json::from_value::<ListSessionsResponse>(malformed).is_err());
8345
8346        let session = |dirs: serde_json::Value| json!({ "sessionId": "s", "cwd": "/w", "additionalDirectories": dirs });
8347        let info: SessionInfo = serde_json::from_value(session(json!(null))).unwrap();
8348        assert_eq!(info.additional_directories, Vec::<AbsolutePath>::new());
8349        for bad in [json!(["/a", 42]), json!("/a")] {
8350            assert!(serde_json::from_value::<SessionInfo>(session(bad)).is_err());
8351        }
8352        // A session with malformed directories is skipped, not truncated.
8353        let response = json!({ "sessions": [session(json!(["/a", 42]))] });
8354        let response: ListSessionsResponse = serde_json::from_value(response).unwrap();
8355        assert_eq!(response.sessions, Vec::<SessionInfo>::new());
8356    }
8357
8358    #[test]
8359    fn other_fallbacks_preserve_optional_fields_verbatim() {
8360        let valid = json!({ "type": "_custom", "methodId": "m", "name": "M",
8361            "description": "d", "_meta": { "k": 1 } });
8362        let method: AuthMethod = serde_json::from_value(valid.clone()).unwrap();
8363        assert_eq!(method.description(), Some("d"));
8364        assert_eq!(
8365            method.meta(),
8366            Some(&json!({ "k": 1 }).as_object().unwrap().clone())
8367        );
8368        assert_eq!(serde_json::to_value(&method).unwrap(), valid);
8369
8370        // Malformed optional fields are kept as sent and read as absent.
8371        let malformed = json!({ "type": "_custom", "methodId": "m", "name": "M",
8372            "description": 42, "_meta": "bad", "extra": true });
8373        let method: AuthMethod = serde_json::from_value(malformed.clone()).unwrap();
8374        assert_eq!(method.description(), None);
8375        assert_eq!(method.meta(), None);
8376        assert_eq!(serde_json::to_value(&method).unwrap(), malformed);
8377
8378        let replay = json!({ "type": "_custom", "_meta": "bad", "cursor": 3 });
8379        let decoded: ReplayFrom = serde_json::from_value(replay.clone()).unwrap();
8380        assert_eq!(serde_json::to_value(&decoded).unwrap(), replay);
8381    }
8382
8383    fn serialized_meta_key_count(value: &impl serde::Serialize) -> usize {
8384        serde_json::to_string(value)
8385            .unwrap()
8386            .matches("\"_meta\"")
8387            .count()
8388    }
8389
8390    #[test]
8391    fn prompt_response_without_metadata_round_trips() {
8392        let response = PromptResponse::new(MessageId::new("message-1"));
8393        let serialized = serde_json::to_value(&response).unwrap();
8394        assert_eq!(serialized, json!({ "messageId": "message-1" }));
8395        assert_eq!(
8396            serde_json::from_value::<PromptResponse>(serialized).unwrap(),
8397            response
8398        );
8399        assert_eq!(
8400            serde_json::from_value::<PromptResponse>(json!({
8401                "messageId": "message-1",
8402                "_meta": null
8403            }))
8404            .unwrap(),
8405            response
8406        );
8407    }
8408
8409    #[test]
8410    fn prompt_response_requires_message_id_and_preserves_metadata_tolerance() {
8411        let response = PromptResponse::new("message-1").meta(test_meta());
8412        let serialized = serde_json::to_value(&response).unwrap();
8413        assert_eq!(
8414            serialized,
8415            json!({
8416                "messageId": "message-1",
8417                "_meta": { "source": "test" }
8418            })
8419        );
8420
8421        let deserialized: PromptResponse = serde_json::from_value(serialized).unwrap();
8422        assert_eq!(deserialized.message_id, MessageId::new("message-1"));
8423        assert_eq!(deserialized.meta, Some(test_meta()));
8424
8425        let malformed_meta: PromptResponse = serde_json::from_value(json!({
8426            "messageId": "message-2",
8427            "_meta": false
8428        }))
8429        .unwrap();
8430        assert_eq!(malformed_meta.message_id, MessageId::new("message-2"));
8431        assert_eq!(malformed_meta.meta, None);
8432
8433        for invalid in [
8434            json!({}),
8435            json!({ "messageId": null }),
8436            json!({ "messageId": 1 }),
8437            json!({ "messageId": false }),
8438            json!({ "messageId": {} }),
8439            json!({ "messageId": [] }),
8440        ] {
8441            assert!(
8442                serde_json::from_value::<PromptResponse>(invalid).is_err(),
8443                "missing, null, and non-string message IDs must be rejected"
8444            );
8445        }
8446    }
8447
8448    #[cfg(feature = "schemars")]
8449    #[test]
8450    fn prompt_response_schema_requires_non_null_string_message_id_reference() {
8451        let schema = serde_json::to_value(schemars::schema_for!(PromptResponse)).unwrap();
8452
8453        assert_eq!(schema["required"], json!(["messageId"]));
8454        assert_eq!(
8455            schema["properties"]["messageId"]["$ref"],
8456            "#/$defs/MessageId"
8457        );
8458        assert_eq!(schema["$defs"]["MessageId"]["type"], "string");
8459    }
8460
8461    #[test]
8462    fn test_initialize_capabilities_default_on_malformed_values() {
8463        let request: InitializeRequest = serde_json::from_value(json!({
8464            "protocolVersion": 2,
8465            "capabilities": false,
8466            "info": {
8467                "name": "client",
8468                "version": "1.0.0"
8469            }
8470        }))
8471        .unwrap();
8472        assert_eq!(request.capabilities, ClientCapabilities::default());
8473
8474        let response: InitializeResponse = serde_json::from_value(json!({
8475            "protocolVersion": 2,
8476            "capabilities": false,
8477            "info": {
8478                "name": "agent",
8479                "version": "1.0.0"
8480            }
8481        }))
8482        .unwrap();
8483        assert_eq!(response.capabilities, AgentCapabilities::default());
8484    }
8485
8486    #[test]
8487    fn test_agent_capabilities_default_on_malformed_values() {
8488        let capabilities: AgentCapabilities = serde_json::from_value(json!({
8489            "session": false,
8490            "auth": false
8491        }))
8492        .unwrap();
8493
8494        assert!(capabilities.session.is_none());
8495        assert_eq!(capabilities.auth, None);
8496    }
8497
8498    #[test]
8499    fn test_mcp_server_stdio_serialization() {
8500        let server = McpServer::Stdio(
8501            McpServerStdio::new("test-server", "/usr/bin/server")
8502                .args(vec!["--port".to_string(), "3000".to_string()])
8503                .env(vec![EnvVariable::new("API_KEY", "secret123")]),
8504        );
8505
8506        let json = serde_json::to_value(&server).unwrap();
8507        assert_eq!(
8508            json,
8509            json!({
8510                "type": "stdio",
8511                "name": "test-server",
8512                "command": "/usr/bin/server",
8513                "args": ["--port", "3000"],
8514                "env": [
8515                    {
8516                        "name": "API_KEY",
8517                        "value": "secret123"
8518                    }
8519                ]
8520            })
8521        );
8522
8523        let deserialized: McpServer = serde_json::from_value(json).unwrap();
8524        match deserialized {
8525            McpServer::Stdio(McpServerStdio {
8526                name,
8527                command,
8528                args,
8529                env,
8530                meta: _,
8531            }) => {
8532                assert_eq!(name, "test-server");
8533                assert_eq!(command, AbsolutePath::new("/usr/bin/server"));
8534                assert_eq!(args, vec!["--port", "3000"]);
8535                assert_eq!(env.len(), 1);
8536                assert_eq!(env[0].name, "API_KEY");
8537                assert_eq!(env[0].value, "secret123");
8538            }
8539            _ => panic!("Expected Stdio variant"),
8540        }
8541    }
8542
8543    #[test]
8544    fn test_mcp_server_empty_arrays_are_optional() {
8545        let stdio = McpServer::Stdio(McpServerStdio::new("test-server", "/usr/bin/server"));
8546        assert_eq!(
8547            serde_json::to_value(&stdio).unwrap(),
8548            json!({
8549                "type": "stdio",
8550                "name": "test-server",
8551                "command": "/usr/bin/server"
8552            })
8553        );
8554
8555        let McpServer::Stdio(McpServerStdio { args, env, .. }) =
8556            serde_json::from_value::<McpServer>(json!({
8557                "type": "stdio",
8558                "name": "test-server",
8559                "command": "/usr/bin/server"
8560            }))
8561            .unwrap()
8562        else {
8563            panic!("Expected Stdio variant");
8564        };
8565        assert_eq!(args, Vec::<String>::new());
8566        assert_eq!(env, []);
8567
8568        let http = McpServer::Http(McpServerHttp::new("http-server", "https://api.example.com"));
8569        assert_eq!(
8570            serde_json::to_value(&http).unwrap(),
8571            json!({
8572                "type": "http",
8573                "name": "http-server",
8574                "url": "https://api.example.com"
8575            })
8576        );
8577
8578        let McpServer::Http(McpServerHttp { headers, .. }) =
8579            serde_json::from_value::<McpServer>(json!({
8580                "type": "http",
8581                "name": "http-server",
8582                "url": "https://api.example.com"
8583            }))
8584            .unwrap()
8585        else {
8586            panic!("Expected Http variant");
8587        };
8588        assert_eq!(headers, []);
8589    }
8590
8591    #[test]
8592    fn test_mcp_server_unknown_transport_serialization() {
8593        let json = json!({
8594            "type": "websocket",
8595            "name": "future-server",
8596            "url": "wss://example.com/mcp",
8597            "protocolVersion": "2026-01-01"
8598        });
8599
8600        let deserialized: McpServer = serde_json::from_value(json.clone()).unwrap();
8601        let McpServer::Other(OtherMcpServer { type_, fields }) = &deserialized else {
8602            panic!("Expected Other variant");
8603        };
8604
8605        assert_eq!(type_, "websocket");
8606        assert_eq!(fields["name"], "future-server");
8607        assert_eq!(fields["url"], "wss://example.com/mcp");
8608        assert_eq!(fields["protocolVersion"], "2026-01-01");
8609        assert_eq!(serde_json::to_value(&deserialized).unwrap(), json);
8610    }
8611
8612    #[test]
8613    fn test_mcp_server_stdio_requires_type() {
8614        let result = serde_json::from_value::<McpServer>(json!({
8615            "name": "test-server",
8616            "command": "/usr/bin/server",
8617            "args": [],
8618            "env": []
8619        }));
8620
8621        assert!(result.is_err());
8622    }
8623
8624    #[test]
8625    fn test_mcp_server_unknown_does_not_hide_malformed_known_transport() {
8626        let result = serde_json::from_value::<McpServer>(json!({
8627            "type": "stdio",
8628            "name": "test-server",
8629            "args": [],
8630            "env": []
8631        }));
8632
8633        assert!(result.is_err());
8634    }
8635
8636    #[test]
8637    fn test_mcp_server_http_serialization() {
8638        let server = McpServer::Http(
8639            McpServerHttp::new("http-server", "https://api.example.com").headers(vec![
8640                HttpHeader::new("Authorization", "Bearer token123"),
8641                HttpHeader::new("Content-Type", "application/json"),
8642            ]),
8643        );
8644
8645        let json = serde_json::to_value(&server).unwrap();
8646        assert_eq!(
8647            json,
8648            json!({
8649                "type": "http",
8650                "name": "http-server",
8651                "url": "https://api.example.com",
8652                "headers": [
8653                    {
8654                        "name": "Authorization",
8655                        "value": "Bearer token123"
8656                    },
8657                    {
8658                        "name": "Content-Type",
8659                        "value": "application/json"
8660                    }
8661                ]
8662            })
8663        );
8664
8665        let deserialized: McpServer = serde_json::from_value(json).unwrap();
8666        match deserialized {
8667            McpServer::Http(McpServerHttp {
8668                name,
8669                url,
8670                headers,
8671                meta: _,
8672            }) => {
8673                assert_eq!(name, "http-server");
8674                assert_eq!(url, "https://api.example.com");
8675                assert_eq!(headers.len(), 2);
8676                assert_eq!(headers[0].name, "Authorization");
8677                assert_eq!(headers[0].value, "Bearer token123");
8678                assert_eq!(headers[1].name, "Content-Type");
8679                assert_eq!(headers[1].value, "application/json");
8680            }
8681            _ => panic!("Expected Http variant"),
8682        }
8683    }
8684
8685    #[cfg(feature = "schemars")]
8686    #[test]
8687    fn mcp_server_http_schema_marks_url_as_uri() {
8688        let schema = serde_json::to_value(schemars::schema_for!(McpServerHttp)).unwrap();
8689
8690        assert_eq!(schema["properties"]["url"]["format"], "uri");
8691    }
8692
8693    #[cfg(feature = "unstable_mcp_over_acp")]
8694    #[test]
8695    fn test_client_mcp_message_method_names() {
8696        use serde_json::json;
8697
8698        assert_eq!(AGENT_METHOD_NAMES.mcp_message, "mcp/message");
8699
8700        let notification =
8701            MessageMcpNotification::new("server-1", "req-1", "notifications/progress");
8702        assert_eq!(
8703            ClientNotification::MessageMcpNotification(Box::new(notification.clone())).method(),
8704            "mcp/message"
8705        );
8706        assert_eq!(
8707            serde_json::to_value(notification).unwrap(),
8708            json!({
8709                "serverId": "server-1",
8710                "requestId": "req-1",
8711                "method": "notifications/progress"
8712            })
8713        );
8714        let notification: MessageMcpNotification = serde_json::from_value(json!({
8715            "serverId": "server-1", "requestId": "req-1", "method": "notifications/progress",
8716            "params": null, "_meta": null
8717        }))
8718        .unwrap();
8719        assert_eq!(notification.params, None);
8720        assert_eq!(notification.meta, None);
8721        for key in ["serverId", "requestId", "method"] {
8722            let mut value = json!({"serverId":"server-1", "requestId":"req-1", "method":"notifications/progress"});
8723            value.as_object_mut().unwrap().remove(key);
8724            assert!(serde_json::from_value::<MessageMcpNotification>(value).is_err());
8725        }
8726    }
8727
8728    #[test]
8729    fn test_auth_method_names() {
8730        assert_eq!(AGENT_METHOD_NAMES.auth_login, "auth/login");
8731        assert_eq!(AGENT_METHOD_NAMES.auth_logout, "auth/logout");
8732
8733        assert_eq!(
8734            ClientRequest::LoginAuthRequest(Box::new(LoginAuthRequest::new("agent-login")))
8735                .method(),
8736            "auth/login"
8737        );
8738        assert_eq!(
8739            ClientRequest::LogoutAuthRequest(Box::new(LogoutAuthRequest::new())).method(),
8740            "auth/logout"
8741        );
8742    }
8743
8744    #[test]
8745    fn test_session_config_option_category_known_variants() {
8746        // Test serialization of known variants
8747        assert_eq!(
8748            serde_json::to_value(&SessionConfigOptionCategory::Mode).unwrap(),
8749            json!("mode")
8750        );
8751        assert_eq!(
8752            serde_json::to_value(&SessionConfigOptionCategory::Model).unwrap(),
8753            json!("model")
8754        );
8755        assert_eq!(
8756            serde_json::to_value(&SessionConfigOptionCategory::ModelConfig).unwrap(),
8757            json!("model_config")
8758        );
8759        #[cfg(feature = "unstable_speed_config_category")]
8760        assert_eq!(
8761            serde_json::to_value(&SessionConfigOptionCategory::Speed).unwrap(),
8762            json!("speed")
8763        );
8764        assert_eq!(
8765            serde_json::to_value(&SessionConfigOptionCategory::ThoughtLevel).unwrap(),
8766            json!("thought_level")
8767        );
8768
8769        // Test deserialization of known variants
8770        assert_eq!(
8771            serde_json::from_str::<SessionConfigOptionCategory>("\"mode\"").unwrap(),
8772            SessionConfigOptionCategory::Mode
8773        );
8774        assert_eq!(
8775            serde_json::from_str::<SessionConfigOptionCategory>("\"model\"").unwrap(),
8776            SessionConfigOptionCategory::Model
8777        );
8778        assert_eq!(
8779            serde_json::from_str::<SessionConfigOptionCategory>("\"model_config\"").unwrap(),
8780            SessionConfigOptionCategory::ModelConfig
8781        );
8782        #[cfg(feature = "unstable_speed_config_category")]
8783        assert_eq!(
8784            serde_json::from_str::<SessionConfigOptionCategory>("\"speed\"").unwrap(),
8785            SessionConfigOptionCategory::Speed
8786        );
8787        assert_eq!(
8788            serde_json::from_str::<SessionConfigOptionCategory>("\"thought_level\"").unwrap(),
8789            SessionConfigOptionCategory::ThoughtLevel
8790        );
8791    }
8792
8793    #[test]
8794    fn test_session_config_option_category_unknown_variants() {
8795        // Test that unknown strings are captured in Other variant
8796        let unknown: SessionConfigOptionCategory =
8797            serde_json::from_str("\"some_future_category\"").unwrap();
8798        assert_eq!(
8799            unknown,
8800            SessionConfigOptionCategory::Other("some_future_category".to_string())
8801        );
8802
8803        // Test round-trip of unknown category
8804        let json = serde_json::to_value(&unknown).unwrap();
8805        assert_eq!(json, json!("some_future_category"));
8806    }
8807
8808    #[cfg(not(feature = "unstable_speed_config_category"))]
8809    #[test]
8810    fn test_session_config_option_speed_is_unknown_without_feature() {
8811        let unknown: SessionConfigOptionCategory = serde_json::from_str("\"speed\"").unwrap();
8812        assert_eq!(
8813            unknown,
8814            SessionConfigOptionCategory::Other("speed".to_string())
8815        );
8816    }
8817
8818    #[test]
8819    fn test_session_config_option_category_custom_categories() {
8820        // Category names beginning with `_` are free for custom use
8821        let custom: SessionConfigOptionCategory =
8822            serde_json::from_str("\"_my_custom_category\"").unwrap();
8823        assert_eq!(
8824            custom,
8825            SessionConfigOptionCategory::Other("_my_custom_category".to_string())
8826        );
8827
8828        // Test round-trip preserves the custom category name
8829        let json = serde_json::to_value(&custom).unwrap();
8830        assert_eq!(json, json!("_my_custom_category"));
8831
8832        // Deserialize back and verify
8833        let deserialized: SessionConfigOptionCategory = serde_json::from_value(json).unwrap();
8834        assert_eq!(
8835            deserialized,
8836            SessionConfigOptionCategory::Other("_my_custom_category".to_string()),
8837        );
8838    }
8839
8840    fn test_config_option() -> SessionConfigOption {
8841        SessionConfigOption::select(
8842            "mode",
8843            "Mode",
8844            "ask",
8845            vec![SessionConfigSelectOption::new("ask", "Ask")],
8846        )
8847    }
8848
8849    #[test]
8850    fn test_session_response_initial_state_default_empty_and_skip_serializing() {
8851        assert_eq!(
8852            serde_json::to_value(NewSessionResponse::new("sess")).unwrap(),
8853            json!({ "sessionId": "sess" })
8854        );
8855        assert_eq!(
8856            serde_json::to_value(ResumeSessionResponse::new()).unwrap(),
8857            json!({})
8858        );
8859        #[cfg(feature = "unstable_session_fork")]
8860        assert_eq!(
8861            serde_json::to_value(ForkSessionResponse::new("fork")).unwrap(),
8862            json!({ "sessionId": "fork" })
8863        );
8864
8865        let json = serde_json::to_value(
8866            NewSessionResponse::new("sess").config_options(vec![test_config_option()]),
8867        )
8868        .unwrap();
8869        assert_eq!(json["configOptions"].as_array().unwrap().len(), 1);
8870    }
8871
8872    #[test]
8873    fn test_session_response_config_options_deserialize_missing_null_and_invalid() {
8874        let missing: NewSessionResponse =
8875            serde_json::from_value(json!({ "sessionId": "sess" })).unwrap();
8876        assert_eq!(missing.config_options, []);
8877
8878        let null: NewSessionResponse = serde_json::from_value(json!({
8879            "sessionId": "sess",
8880            "configOptions": null
8881        }))
8882        .unwrap();
8883        assert_eq!(null.config_options, []);
8884
8885        let wrong_shape: NewSessionResponse = serde_json::from_value(json!({
8886            "sessionId": "sess",
8887            "configOptions": "oops"
8888        }))
8889        .unwrap();
8890        assert_eq!(wrong_shape.config_options, []);
8891
8892        let valid_option = serde_json::to_value(test_config_option()).unwrap();
8893        let mixed: NewSessionResponse = serde_json::from_value(json!({
8894            "sessionId": "sess",
8895            "configOptions": ["oops", valid_option]
8896        }))
8897        .unwrap();
8898        assert_eq!(mixed.config_options.len(), 1);
8899
8900        let resume: ResumeSessionResponse = serde_json::from_value(json!({})).unwrap();
8901        assert_eq!(resume.config_options, []);
8902        #[cfg(feature = "unstable_session_fork")]
8903        {
8904            let fork: ForkSessionResponse =
8905                serde_json::from_value(json!({ "sessionId": "fork" })).unwrap();
8906            assert_eq!(fork.config_options, []);
8907        }
8908    }
8909
8910    #[test]
8911    fn test_session_response_available_commands_roundtrip_with_config_options() {
8912        use super::super::{AvailableCommandInput, Command, TextCommandInput};
8913
8914        let commands = vec![
8915            AvailableCommand::Command(
8916                Command::new("web", "Search the web")
8917                    .input(AvailableCommandInput::Text(TextCommandInput::new("Query"))),
8918            ),
8919            AvailableCommand::Command(Command::new("test", "Run project tests")),
8920        ];
8921        let mut expected = json!({
8922            "sessionId": "sess",
8923            "configOptions": [test_config_option()],
8924            "availableCommands": [
8925                {
8926                    "type": "command",
8927                    "name": "web",
8928                    "description": "Search the web",
8929                    "input": { "type": "text", "hint": "Query" }
8930                },
8931                { "type": "command", "name": "test", "description": "Run project tests" }
8932            ]
8933        });
8934
8935        let new = NewSessionResponse::new("sess")
8936            .config_options(vec![test_config_option()])
8937            .available_commands(commands.clone());
8938        assert_eq!(serde_json::to_value(&new).unwrap(), expected);
8939        assert_eq!(
8940            serde_json::from_value::<NewSessionResponse>(expected.clone()).unwrap(),
8941            new
8942        );
8943
8944        expected.as_object_mut().unwrap().remove("sessionId");
8945        let resume = ResumeSessionResponse::new()
8946            .config_options(vec![test_config_option()])
8947            .available_commands(commands.clone());
8948        assert_eq!(serde_json::to_value(&resume).unwrap(), expected);
8949        assert_eq!(
8950            serde_json::from_value::<ResumeSessionResponse>(expected.clone()).unwrap(),
8951            resume
8952        );
8953
8954        #[cfg(feature = "unstable_session_fork")]
8955        {
8956            expected["sessionId"] = json!("fork");
8957            let fork = ForkSessionResponse::new("fork")
8958                .config_options(vec![test_config_option()])
8959                .available_commands(commands);
8960            assert_eq!(serde_json::to_value(&fork).unwrap(), expected);
8961            assert_eq!(
8962                serde_json::from_value::<ForkSessionResponse>(expected).unwrap(),
8963                fork
8964            );
8965        }
8966    }
8967
8968    #[test]
8969    fn test_session_response_available_commands_deserialize_missing_null_and_invalid() {
8970        let command =
8971            AvailableCommand::Command(super::super::Command::new("test", "Run project tests"));
8972        let config_options = vec![test_config_option()];
8973
8974        for (commands, expected) in [
8975            (None, vec![]),
8976            (Some(json!(null)), vec![]),
8977            (Some(json!([])), vec![]),
8978            (Some(json!("oops")), vec![]),
8979            (Some(json!({})), vec![]),
8980            (Some(json!([null, {}, { "name": "invalid" }])), vec![]),
8981            (
8982                Some(json!([{ "name": "test", "description": "Run project tests" }])),
8983                vec![],
8984            ),
8985            (
8986                Some(json!([null, command, { "name": "invalid" }])),
8987                vec![command.clone()],
8988            ),
8989        ] {
8990            let mut value = json!({
8991                "sessionId": "sess",
8992                "configOptions": config_options
8993            });
8994            if let Some(commands) = commands {
8995                value["availableCommands"] = commands;
8996            }
8997
8998            let new: NewSessionResponse = serde_json::from_value(value.clone()).unwrap();
8999            assert_eq!(new.available_commands, expected);
9000            assert_eq!(new.config_options, config_options);
9001
9002            #[cfg(feature = "unstable_session_fork")]
9003            {
9004                let fork: ForkSessionResponse = serde_json::from_value(value.clone()).unwrap();
9005                assert_eq!(fork.available_commands, expected);
9006                assert_eq!(fork.config_options, config_options);
9007            }
9008
9009            value.as_object_mut().unwrap().remove("sessionId");
9010            let resume: ResumeSessionResponse = serde_json::from_value(value).unwrap();
9011            assert_eq!(resume.available_commands, expected);
9012            assert_eq!(resume.config_options, config_options);
9013        }
9014
9015        let resume: ResumeSessionResponse = serde_json::from_value(json!(null)).unwrap();
9016        assert_eq!(resume.available_commands, []);
9017    }
9018
9019    #[test]
9020    fn test_resume_session_replay_from_serialization() {
9021        assert_eq!(
9022            serde_json::to_value(ResumeSessionRequest::new(
9023                "sess_abc123",
9024                "/home/user/project"
9025            ))
9026            .unwrap(),
9027            json!({
9028                "sessionId": "sess_abc123",
9029                "cwd": "/home/user/project"
9030            })
9031        );
9032        assert_eq!(
9033            serde_json::to_value(
9034                ResumeSessionRequest::new("sess_abc123", "/home/user/project")
9035                    .replay_from(ReplayFrom::from(ReplayFromStart::new()))
9036            )
9037            .unwrap(),
9038            json!({
9039                "sessionId": "sess_abc123",
9040                "cwd": "/home/user/project",
9041                "replayFrom": {
9042                    "type": "start"
9043                }
9044            })
9045        );
9046
9047        let replay: ResumeSessionRequest = serde_json::from_value(json!({
9048            "sessionId": "sess_abc123",
9049            "cwd": "/home/user/project",
9050            "replayFrom": {
9051                "type": "start"
9052            }
9053        }))
9054        .unwrap();
9055        assert!(matches!(replay.replay_from, Some(ReplayFrom::Start(_))));
9056
9057        let none: ResumeSessionRequest = serde_json::from_value(json!({
9058            "sessionId": "sess_abc123",
9059            "cwd": "/home/user/project",
9060            "replayFrom": null
9061        }))
9062        .unwrap();
9063        assert!(none.replay_from.is_none());
9064    }
9065
9066    #[test]
9067    fn test_auth_method_agent_serialization() {
9068        let method = AuthMethod::Agent(AuthMethodAgent::new("default-auth", "Default Auth"));
9069
9070        let json = serde_json::to_value(&method).unwrap();
9071        assert_eq!(
9072            json,
9073            json!({
9074                "methodId": "default-auth",
9075                "name": "Default Auth",
9076                "type": "agent"
9077            })
9078        );
9079        // description should be omitted when None
9080        assert!(!json.as_object().unwrap().contains_key("description"));
9081
9082        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9083        match deserialized {
9084            AuthMethod::Agent(AuthMethodAgent {
9085                method_id, name, ..
9086            }) => {
9087                assert_eq!(method_id.0.as_ref(), "default-auth");
9088                assert_eq!(name, "Default Auth");
9089            }
9090            _ => panic!("Expected Agent variant"),
9091        }
9092    }
9093
9094    #[test]
9095    fn test_auth_method_agent_deserialization() {
9096        let json = json!({
9097            "methodId": "agent-auth",
9098            "name": "Agent Auth",
9099            "type": "agent"
9100        });
9101
9102        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9103        assert!(matches!(deserialized, AuthMethod::Agent(_)));
9104    }
9105
9106    #[test]
9107    fn test_auth_method_agent_requires_type() {
9108        assert!(
9109            serde_json::from_value::<AuthMethod>(json!({
9110                "methodId": "agent-auth",
9111                "name": "Agent Auth"
9112            }))
9113            .is_err()
9114        );
9115    }
9116
9117    #[test]
9118    fn test_auth_method_agent_rejects_null_type() {
9119        assert!(
9120            serde_json::from_value::<AuthMethod>(json!({
9121                "methodId": "agent-auth",
9122                "name": "Agent Auth",
9123                "type": null
9124            }))
9125            .is_err()
9126        );
9127    }
9128
9129    #[test]
9130    fn test_auth_method_unknown_does_not_hide_malformed_agent() {
9131        assert!(
9132            serde_json::from_value::<AuthMethod>(json!({
9133                "methodId": "agent-auth",
9134                "type": "agent"
9135            }))
9136            .is_err()
9137        );
9138        assert!(
9139            serde_json::from_value::<AuthMethod>(json!({
9140                "methodId": "api-key",
9141                "type": "env_var",
9142                "vars": [{"name": "API_KEY"}]
9143            }))
9144            .is_err()
9145        );
9146    }
9147
9148    #[test]
9149    fn test_auth_method_unknown_variant_roundtrip() {
9150        let method: AuthMethod = serde_json::from_value(json!({
9151            "methodId": "oauth",
9152            "name": "OAuth",
9153            "type": "_oauth",
9154            "authorizationUrl": "https://example.com/auth"
9155        }))
9156        .unwrap();
9157
9158        assert_eq!(method.method_id().0.as_ref(), "oauth");
9159        assert_eq!(method.name(), "OAuth");
9160        let AuthMethod::Other(unknown) = method else {
9161            panic!("expected unknown auth method");
9162        };
9163        assert_eq!(unknown.type_, "_oauth");
9164        assert_eq!(
9165            unknown.fields.get("authorizationUrl"),
9166            Some(&json!("https://example.com/auth"))
9167        );
9168
9169        assert_eq!(
9170            serde_json::to_value(AuthMethod::Other(unknown)).unwrap(),
9171            json!({
9172                "methodId": "oauth",
9173                "name": "OAuth",
9174                "type": "_oauth",
9175                "authorizationUrl": "https://example.com/auth"
9176            })
9177        );
9178    }
9179
9180    #[test]
9181    fn test_auth_method_unknown_does_not_hide_malformed_known_variant() {
9182        assert!(
9183            serde_json::from_value::<AuthMethod>(json!({
9184                "methodId": "terminal-auth",
9185                "type": "terminal"
9186            }))
9187            .is_err()
9188        );
9189    }
9190
9191    #[test]
9192    fn test_tool_call_and_terminal_cancel_serialization() {
9193        assert_eq!(AGENT_METHOD_NAMES.tool_call_cancel, "tool_call/cancel");
9194        assert_eq!(AGENT_METHOD_NAMES.terminal_cancel, "terminal/cancel");
9195        assert_eq!(
9196            ClientRequest::CancelToolCallRequest(Box::new(CancelToolCallRequest::new(
9197                "sess_abc123",
9198                "call_012"
9199            )))
9200            .method(),
9201            "tool_call/cancel"
9202        );
9203        assert_eq!(
9204            ClientRequest::CancelTerminalRequest(Box::new(CancelTerminalRequest::new(
9205                "sess_abc123",
9206                "term_003"
9207            )))
9208            .method(),
9209            "terminal/cancel"
9210        );
9211        assert_eq!(
9212            serde_json::to_value(CancelToolCallRequest::new("sess_abc123", "call_012")).unwrap(),
9213            json!({"sessionId": "sess_abc123", "toolCallId": "call_012"})
9214        );
9215        assert_eq!(
9216            serde_json::to_value(CancelTerminalRequest::new("sess_abc123", "term_003")).unwrap(),
9217            json!({"sessionId": "sess_abc123", "terminalId": "term_003"})
9218        );
9219        assert!(
9220            serde_json::from_value::<CancelToolCallRequest>(json!({"sessionId": "sess_abc123"}))
9221                .is_err()
9222        );
9223        assert_eq!(
9224            serde_json::to_value(CancelTerminalResponse::new()).unwrap(),
9225            json!({})
9226        );
9227    }
9228
9229    #[test]
9230    fn test_session_delete_serialization() {
9231        assert_eq!(AGENT_METHOD_NAMES.session_delete, "session/delete");
9232        assert_eq!(
9233            ClientRequest::DeleteSessionRequest(Box::new(DeleteSessionRequest::new("sess_abc123")))
9234                .method(),
9235            "session/delete"
9236        );
9237        assert_eq!(
9238            serde_json::to_value(DeleteSessionRequest::new("sess_abc123")).unwrap(),
9239            json!({
9240                "sessionId": "sess_abc123"
9241            })
9242        );
9243        assert_eq!(
9244            serde_json::to_value(DeleteSessionResponse::new()).unwrap(),
9245            json!({})
9246        );
9247        assert_eq!(
9248            serde_json::to_value(
9249                SessionCapabilities::new().delete(SessionDeleteCapabilities::new())
9250            )
9251            .unwrap(),
9252            json!({
9253                "delete": {}
9254            })
9255        );
9256    }
9257    #[cfg(feature = "unstable_session_set_title")]
9258    #[test]
9259    fn test_session_set_title_serialization() {
9260        assert_eq!(AGENT_METHOD_NAMES.session_set_title, "session/set_title");
9261        assert_eq!(
9262            ClientRequest::SetSessionTitleRequest(Box::new(SetSessionTitleRequest::new(
9263                "sess_abc123",
9264                "Investigate OAuth timeout"
9265            )))
9266            .method(),
9267            "session/set_title"
9268        );
9269        assert_eq!(
9270            serde_json::to_value(SetSessionTitleRequest::new(
9271                "sess_abc123",
9272                "Investigate OAuth timeout"
9273            ))
9274            .unwrap(),
9275            json!({
9276                "sessionId": "sess_abc123",
9277                "title": "Investigate OAuth timeout"
9278            })
9279        );
9280        assert_eq!(
9281            serde_json::to_value(SetSessionTitleResponse::new("Investigate OAuth timeout"))
9282                .unwrap(),
9283            json!({
9284                "title": "Investigate OAuth timeout"
9285            })
9286        );
9287        assert_eq!(
9288            serde_json::to_value(SessionCapabilities::new().title(SessionTitleCapabilities::new()))
9289                .unwrap(),
9290            json!({
9291                "title": {}
9292            })
9293        );
9294    }
9295
9296    #[cfg(feature = "unstable_session_set_title")]
9297    #[test]
9298    fn test_session_set_title_requires_title() {
9299        for params in [
9300            json!({"sessionId": "sess_abc123"}),
9301            json!({"sessionId": "sess_abc123", "title": null}),
9302            json!({"sessionId": "sess_abc123", "title": 42}),
9303        ] {
9304            assert!(serde_json::from_value::<SetSessionTitleRequest>(params).is_err());
9305        }
9306        for result in [json!({}), json!({"title": null})] {
9307            assert!(serde_json::from_value::<SetSessionTitleResponse>(result).is_err());
9308        }
9309    }
9310
9311    #[cfg(feature = "unstable_session_options")]
9312    #[test]
9313    fn test_session_options_serialization() {
9314        assert_eq!(AGENT_METHOD_NAMES.session_options, "session/options");
9315        assert_eq!(
9316            ClientRequest::SessionOptionsRequest(Box::new(SessionOptionsRequest::new(
9317                "/home/user/project"
9318            )))
9319            .method(),
9320            "session/options"
9321        );
9322        assert_eq!(
9323            serde_json::to_value(
9324                SessionOptionsRequest::new("/home/user/project")
9325                    .session_id(SessionId::new("sess_abc123"))
9326            )
9327            .unwrap(),
9328            json!({"cwd": "/home/user/project", "sessionId": "sess_abc123"})
9329        );
9330        assert_eq!(
9331            serde_json::from_value::<SessionOptionsRequest>(
9332                json!({"cwd": "/home/user/project", "additionalDirectories": null, "sessionId": null})
9333            )
9334            .unwrap(),
9335            SessionOptionsRequest::new("/home/user/project")
9336        );
9337        let request = NewSessionRequest::new("/home/user/project").config_options(vec![
9338            InitialSessionConfigOption::new("model", SessionConfigOptionValue::id("model-2")),
9339            InitialSessionConfigOption::new("fast", SessionConfigOptionValue::boolean(true)),
9340        ]);
9341        let value = serde_json::to_value(&request).unwrap();
9342        assert_eq!(
9343            value["configOptions"],
9344            json!([
9345                {"configId": "model", "type": "id", "value": "model-2"},
9346                {"configId": "fast", "type": "boolean", "value": true}
9347            ])
9348        );
9349        assert_eq!(
9350            serde_json::from_value::<NewSessionRequest>(value).unwrap(),
9351            request
9352        );
9353        assert!(
9354            serde_json::from_value::<NewSessionRequest>(json!({
9355                "cwd": "/home/user/project",
9356                "mcpServers": [],
9357                "configOptions": [{"type": "boolean", "value": true}]
9358            }))
9359            .is_err()
9360        );
9361        assert_eq!(
9362            serde_json::to_value(SessionOptionsResponse::new()).unwrap(),
9363            json!({})
9364        );
9365        #[cfg(feature = "unstable_session_fork")]
9366        {
9367            let fork =
9368                ForkSessionRequest::new("sess_abc123", "/home/user/project").config_options(vec![
9369                    InitialSessionConfigOption::new(
9370                        "model",
9371                        SessionConfigOptionValue::id("model-2"),
9372                    ),
9373                ]);
9374            let value = serde_json::to_value(&fork).unwrap();
9375            assert_eq!(
9376                value["configOptions"],
9377                json!([{"configId": "model", "type": "id", "value": "model-2"}])
9378            );
9379            assert_eq!(
9380                serde_json::from_value::<ForkSessionRequest>(value).unwrap(),
9381                fork
9382            );
9383            // `null` is an empty list, and a malformed entry fails the request.
9384            assert_eq!(
9385                serde_json::from_value::<ForkSessionRequest>(json!({
9386                    "sessionId": "sess_abc123",
9387                    "cwd": "/home/user/project",
9388                    "configOptions": null
9389                }))
9390                .unwrap(),
9391                ForkSessionRequest::new("sess_abc123", "/home/user/project")
9392            );
9393            assert!(
9394                serde_json::from_value::<ForkSessionRequest>(json!({
9395                    "sessionId": "sess_abc123",
9396                    "cwd": "/home/user/project",
9397                    "configOptions": [{"type": "boolean", "value": true}]
9398                }))
9399                .is_err()
9400            );
9401        }
9402        assert_eq!(
9403            serde_json::to_value(
9404                SessionCapabilities::new().options(SessionOptionsCapabilities::new())
9405            )
9406            .unwrap(),
9407            json!({"options": {}})
9408        );
9409    }
9410
9411    #[cfg(feature = "unstable_session_status")]
9412    #[test]
9413    fn test_session_status_serialization() {
9414        assert_eq!(AGENT_METHOD_NAMES.session_status, "session/status");
9415        assert_eq!(
9416            ClientRequest::SessionStatusRequest(Box::new(SessionStatusRequest::new("sess_abc123")))
9417                .method(),
9418            "session/status"
9419        );
9420        assert_eq!(
9421            serde_json::to_value(SessionStatusRequest::new("sess_abc123")).unwrap(),
9422            json!({"sessionId": "sess_abc123"})
9423        );
9424        assert_eq!(
9425            serde_json::to_value(SessionStatusResponse::new(SessionStatus::Saved)).unwrap(),
9426            json!({"status": "saved"})
9427        );
9428        assert_eq!(
9429            serde_json::to_value(
9430                SessionCapabilities::new().status(SessionStatusCapabilities::new())
9431            )
9432            .unwrap(),
9433            json!({"status": {}})
9434        );
9435        assert_eq!(
9436            serde_json::to_value(SessionStatusResponse::new(SessionStatus::Open).state(
9437                StateUpdate::RequiresAction(crate::v2::RequiresActionStateUpdate::new())
9438            ))
9439            .unwrap(),
9440            json!({
9441                "status": "open",
9442                "state": {"state": "requires_action"}
9443            })
9444        );
9445        for state in [json!(null), json!("running"), json!({"state": 7})] {
9446            let response = serde_json::from_value::<SessionStatusResponse>(
9447                json!({"status": "open", "state": state}),
9448            )
9449            .unwrap();
9450            assert_eq!(response.state, None);
9451        }
9452    }
9453
9454    #[cfg(feature = "unstable_session_status")]
9455    #[test]
9456    fn test_session_status_is_strict_and_open() {
9457        let custom =
9458            serde_json::from_value::<SessionStatusResponse>(json!({"status": "_suspended"}))
9459                .unwrap();
9460        assert_eq!(
9461            custom.status,
9462            SessionStatus::Other("_suspended".to_string())
9463        );
9464        assert_eq!(
9465            serde_json::to_value(&custom).unwrap(),
9466            json!({"status": "_suspended"})
9467        );
9468        for result in [json!({}), json!({"status": null}), json!({"status": 1})] {
9469            assert!(serde_json::from_value::<SessionStatusResponse>(result).is_err());
9470        }
9471        for params in [json!({}), json!({"sessionId": null})] {
9472            assert!(serde_json::from_value::<SessionStatusRequest>(params).is_err());
9473        }
9474    }
9475
9476    #[cfg(feature = "unstable_session_archive")]
9477    #[test]
9478    fn test_session_archive_serialization() {
9479        assert_eq!(AGENT_METHOD_NAMES.session_archive, "session/archive");
9480        assert_eq!(AGENT_METHOD_NAMES.session_unarchive, "session/unarchive");
9481        assert_eq!(
9482            ClientRequest::ArchiveSessionRequest(Box::new(ArchiveSessionRequest::new(
9483                "sess_abc123"
9484            )))
9485            .method(),
9486            "session/archive"
9487        );
9488        assert_eq!(
9489            ClientRequest::UnarchiveSessionRequest(Box::new(UnarchiveSessionRequest::new(
9490                "sess_abc123"
9491            )))
9492            .method(),
9493            "session/unarchive"
9494        );
9495        assert_eq!(
9496            serde_json::to_value(ArchiveSessionRequest::new("sess_abc123")).unwrap(),
9497            json!({"sessionId": "sess_abc123"})
9498        );
9499        assert_eq!(
9500            serde_json::to_value(UnarchiveSessionResponse::new()).unwrap(),
9501            json!({})
9502        );
9503        assert_eq!(
9504            serde_json::to_value(
9505                SessionCapabilities::new().archive(SessionArchiveCapabilities::new())
9506            )
9507            .unwrap(),
9508            json!({"archive": {}})
9509        );
9510        assert_eq!(
9511            serde_json::to_value(
9512                ListSessionsRequest::new()
9513                    .cwd("/home/user/project")
9514                    .archived(SessionArchiveFilter::Only)
9515            )
9516            .unwrap(),
9517            json!({"cwd": "/home/user/project", "archived": "only"})
9518        );
9519        assert_eq!(
9520            serde_json::to_value(
9521                SessionInfo::new("sess_abc123", "/home/user/project").archived(true)
9522            )
9523            .unwrap(),
9524            json!({"sessionId": "sess_abc123", "cwd": "/home/user/project", "archived": true})
9525        );
9526    }
9527
9528    #[cfg(feature = "unstable_session_archive")]
9529    #[test]
9530    fn test_session_archive_filter_is_strict_and_open() {
9531        for (value, expected) in [
9532            (json!(null), None),
9533            (json!("include"), Some(SessionArchiveFilter::Include)),
9534            (
9535                json!("_recent"),
9536                Some(SessionArchiveFilter::Other("_recent".to_string())),
9537            ),
9538        ] {
9539            let request =
9540                serde_json::from_value::<ListSessionsRequest>(json!({"archived": value})).unwrap();
9541            assert_eq!(request.archived, expected);
9542        }
9543        for value in [json!(true), json!(1), json!({})] {
9544            assert!(
9545                serde_json::from_value::<ListSessionsRequest>(json!({"archived": value})).is_err()
9546            );
9547        }
9548        let info = serde_json::from_value::<SessionInfo>(
9549            json!({"sessionId": "sess_abc123", "cwd": "/home/user/project", "archived": "yes"}),
9550        )
9551        .unwrap();
9552        assert_eq!(info.archived, None);
9553    }
9554
9555    #[test]
9556    fn test_session_additional_directories_serialization() {
9557        assert_eq!(
9558            serde_json::to_value(NewSessionRequest::new("/home/user/project")).unwrap(),
9559            json!({
9560                "cwd": "/home/user/project",
9561            })
9562        );
9563        assert_eq!(
9564            serde_json::to_value(
9565                NewSessionRequest::new("/home/user/project").additional_directories(vec![
9566                    PathBuf::from("/home/user/shared-lib"),
9567                    PathBuf::from("/home/user/product-docs"),
9568                ])
9569            )
9570            .unwrap(),
9571            json!({
9572                "cwd": "/home/user/project",
9573                "additionalDirectories": [
9574                    "/home/user/shared-lib",
9575                    "/home/user/product-docs"
9576                ],
9577            })
9578        );
9579        assert_eq!(
9580            serde_json::to_value(ResumeSessionRequest::new(
9581                "sess_abc123",
9582                "/home/user/project"
9583            ))
9584            .unwrap(),
9585            json!({
9586                "sessionId": "sess_abc123",
9587                "cwd": "/home/user/project",
9588            })
9589        );
9590        assert_eq!(
9591            serde_json::from_value::<ResumeSessionRequest>(json!({
9592                "sessionId": "sess_abc123",
9593                "cwd": "/home/user/project"
9594            }))
9595            .unwrap()
9596            .mcp_servers,
9597            Vec::<McpServer>::new()
9598        );
9599        assert_eq!(
9600            serde_json::from_value::<ResumeSessionRequest>(json!({
9601                "sessionId": "sess_abc123",
9602                "cwd": "/home/user/project",
9603                "mcpServers": null
9604            }))
9605            .unwrap()
9606            .mcp_servers,
9607            Vec::<McpServer>::new()
9608        );
9609        assert_eq!(
9610            serde_json::to_value(SessionInfo::new("sess_abc123", "/home/user/project")).unwrap(),
9611            json!({
9612                "sessionId": "sess_abc123",
9613                "cwd": "/home/user/project"
9614            })
9615        );
9616        assert_eq!(
9617            serde_json::to_value(
9618                SessionInfo::new("sess_abc123", "/home/user/project").additional_directories(vec![
9619                    PathBuf::from("/home/user/shared-lib"),
9620                    PathBuf::from("/home/user/product-docs"),
9621                ])
9622            )
9623            .unwrap(),
9624            json!({
9625                "sessionId": "sess_abc123",
9626                "cwd": "/home/user/project",
9627                "additionalDirectories": [
9628                    "/home/user/shared-lib",
9629                    "/home/user/product-docs"
9630                ]
9631            })
9632        );
9633        assert_eq!(
9634            serde_json::from_value::<SessionInfo>(json!({
9635                "sessionId": "sess_abc123",
9636                "cwd": "/home/user/project"
9637            }))
9638            .unwrap()
9639            .additional_directories,
9640            Vec::<AbsolutePath>::new()
9641        );
9642    }
9643    #[test]
9644    fn test_session_additional_directories_capabilities_serialization() {
9645        assert_eq!(
9646            serde_json::to_value(
9647                SessionCapabilities::new()
9648                    .additional_directories(SessionAdditionalDirectoriesCapabilities::new())
9649            )
9650            .unwrap(),
9651            json!({
9652                "additionalDirectories": {}
9653            })
9654        );
9655    }
9656
9657    #[test]
9658    fn test_session_system_prompt_capabilities_serialization() {
9659        assert_eq!(
9660            serde_json::to_value(
9661                SessionCapabilities::new().system_prompt(SessionSystemPromptCapabilities::new())
9662            )
9663            .unwrap(),
9664            json!({ "systemPrompt": {} })
9665        );
9666        assert_eq!(
9667            serde_json::to_value(
9668                SessionCapabilities::new().system_prompt(
9669                    SessionSystemPromptCapabilities::new().mode(
9670                        SessionSystemPromptModeCapabilities::new()
9671                            .override_(SessionSystemPromptOverrideCapabilities::new())
9672                    )
9673                )
9674            )
9675            .unwrap(),
9676            json!({ "systemPrompt": { "mode": { "override": {} } } })
9677        );
9678        assert_eq!(
9679            serde_json::from_value::<SessionCapabilities>(
9680                json!({ "systemPrompt": { "mode": { "override": {} } } })
9681            )
9682            .unwrap()
9683            .system_prompt
9684            .and_then(|capabilities| capabilities.mode)
9685            .and_then(|mode| mode.override_),
9686            Some(SessionSystemPromptOverrideCapabilities::new())
9687        );
9688
9689        // Capabilities fall back to "not advertised" when malformed.
9690        assert_eq!(
9691            serde_json::from_value::<SessionCapabilities>(json!({ "systemPrompt": "yes" }))
9692                .unwrap()
9693                .system_prompt,
9694            None
9695        );
9696        assert_eq!(
9697            serde_json::from_value::<SessionCapabilities>(
9698                json!({ "systemPrompt": { "mode": { "override": true } } })
9699            )
9700            .unwrap()
9701            .system_prompt,
9702            Some(
9703                SessionSystemPromptCapabilities::new()
9704                    .mode(SessionSystemPromptModeCapabilities::new())
9705            )
9706        );
9707        assert_eq!(
9708            serde_json::from_value::<SessionCapabilities>(
9709                json!({ "systemPrompt": { "mode": "override" } })
9710            )
9711            .unwrap()
9712            .system_prompt,
9713            Some(SessionSystemPromptCapabilities::new())
9714        );
9715    }
9716
9717    #[test]
9718    fn test_system_prompt_lifecycle_request_serialization() {
9719        let system_prompt = SystemPrompt::new(vec![ContentBlock::from(
9720            "You are a code review specialist.",
9721        )]);
9722        let system_prompt_json = json!({
9723            "mode": "append",
9724            "content": [{ "type": "text", "text": "You are a code review specialist." }]
9725        });
9726
9727        let request =
9728            NewSessionRequest::new("/home/user/project").system_prompt(system_prompt.clone());
9729        let request_json = json!({
9730            "cwd": "/home/user/project",
9731            "systemPrompt": system_prompt_json
9732        });
9733        assert_eq!(serde_json::to_value(&request).unwrap(), request_json);
9734        assert_eq!(
9735            serde_json::from_value::<NewSessionRequest>(request_json).unwrap(),
9736            request
9737        );
9738
9739        assert_eq!(
9740            serde_json::to_value(
9741                ResumeSessionRequest::new("sess_abc123", "/home/user/project")
9742                    .system_prompt(system_prompt.clone())
9743            )
9744            .unwrap()["systemPrompt"],
9745            system_prompt_json
9746        );
9747        #[cfg(feature = "unstable_session_fork")]
9748        assert_eq!(
9749            serde_json::to_value(
9750                ForkSessionRequest::new("sess_abc123", "/home/user/project")
9751                    .system_prompt(system_prompt.clone())
9752            )
9753            .unwrap()["systemPrompt"],
9754            system_prompt_json
9755        );
9756
9757        let override_prompt =
9758            SystemPrompt::new(vec![ContentBlock::from("...")]).mode(SystemPromptMode::Override);
9759        let override_json = json!({
9760            "mode": "override",
9761            "content": [{ "type": "text", "text": "..." }]
9762        });
9763        assert_eq!(
9764            serde_json::to_value(&override_prompt).unwrap(),
9765            override_json
9766        );
9767        assert_eq!(
9768            serde_json::from_value::<SystemPrompt>(override_json).unwrap(),
9769            override_prompt
9770        );
9771    }
9772
9773    /// `SystemPrompt::new` defaults to `append` in Rust, but `mode` is required on
9774    /// the wire, so it is always serialized.
9775    #[test]
9776    fn test_system_prompt_new_defaults_to_append() {
9777        let system_prompt = SystemPrompt::new(vec![ContentBlock::from("...")]);
9778        assert_eq!(system_prompt.mode, SystemPromptMode::Append);
9779        assert_eq!(
9780            serde_json::to_value(&system_prompt).unwrap(),
9781            json!({ "mode": "append", "content": [{ "type": "text", "text": "..." }] })
9782        );
9783    }
9784
9785    /// Unknown modes follow the enum variant extension rule: they parse as
9786    /// `SystemPromptMode::Other` so they are not dropped, and an Agent that does
9787    /// not support them must reject the request.
9788    #[test]
9789    fn test_system_prompt_preserves_unknown_modes() {
9790        for mode in ["_vendor_mode", "prepend"] {
9791            let system_prompt_json =
9792                json!({ "mode": mode, "content": [{ "type": "text", "text": "..." }] });
9793            let system_prompt: SystemPrompt =
9794                serde_json::from_value(system_prompt_json.clone()).unwrap();
9795            assert_eq!(
9796                system_prompt.mode,
9797                SystemPromptMode::Other(mode.to_string())
9798            );
9799            assert_eq!(
9800                serde_json::to_value(&system_prompt).unwrap(),
9801                system_prompt_json
9802            );
9803        }
9804    }
9805
9806    /// The receiver acts on `systemPrompt`, so malformed values fail the request
9807    /// (`-32602`) instead of creating a session without the prompt, and `null`
9808    /// is equivalent to omitting the field.
9809    fn assert_system_prompt_is_strict<T>(base: &serde_json::Value)
9810    where
9811        T: serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
9812    {
9813        let name = std::any::type_name::<T>();
9814        let with = |system_prompt: serde_json::Value| {
9815            let mut request = base.clone();
9816            request["systemPrompt"] = system_prompt;
9817            serde_json::from_value::<T>(request)
9818        };
9819
9820        for system_prompt in [
9821            json!("You are a code review specialist."),
9822            json!({ "content": [{ "type": "text", "text": "..." }] }),
9823            json!({ "mode": null, "content": [{ "type": "text", "text": "..." }] }),
9824            json!({ "mode": 1, "content": [{ "type": "text", "text": "..." }] }),
9825            json!({ "mode": "append" }),
9826            json!({ "mode": "append", "content": "..." }),
9827            json!({ "mode": "append", "content": [{ "type": "text" }] }),
9828        ] {
9829            assert!(
9830                with(system_prompt.clone()).is_err(),
9831                "{name}.systemPrompt: {system_prompt}"
9832            );
9833        }
9834
9835        assert_eq!(
9836            with(serde_json::Value::Null).unwrap(),
9837            serde_json::from_value::<T>(base.clone()).unwrap(),
9838            "{name}.systemPrompt"
9839        );
9840    }
9841
9842    #[test]
9843    fn test_session_setup_requests_reject_malformed_system_prompts() {
9844        assert!(
9845            serde_json::to_value(NewSessionRequest::new("/repo"))
9846                .unwrap()
9847                .get("systemPrompt")
9848                .is_none()
9849        );
9850        assert_system_prompt_is_strict::<NewSessionRequest>(&json!({ "cwd": "/repo" }));
9851        assert_system_prompt_is_strict::<ResumeSessionRequest>(&json!({
9852            "sessionId": "sess-1",
9853            "cwd": "/repo"
9854        }));
9855        #[cfg(feature = "unstable_session_fork")]
9856        assert_system_prompt_is_strict::<ForkSessionRequest>(&json!({
9857            "sessionId": "sess-1",
9858            "cwd": "/repo"
9859        }));
9860    }
9861
9862    /// Unknown content block types parse as `ContentBlock::Other` so they are not
9863    /// dropped. An Agent that does not support them must reject the request.
9864    #[test]
9865    fn test_system_prompt_preserves_unknown_content_blocks() {
9866        let request: NewSessionRequest = serde_json::from_value(json!({
9867            "cwd": "/home/user/project",
9868            "systemPrompt": {
9869                "mode": "append",
9870                "content": [{ "type": "_vendor_video", "uri": "https://example.com/intro.mp4" }]
9871            }
9872        }))
9873        .unwrap();
9874        let content = request.system_prompt.unwrap().content;
9875        assert_eq!(content.len(), 1);
9876        assert!(matches!(content[0], ContentBlock::Other(_)));
9877    }
9878
9879    #[test]
9880    fn test_auth_method_terminal_serialization() {
9881        let method = AuthMethod::Terminal(AuthMethodTerminal::new("tui-auth", "Terminal Auth"));
9882
9883        let json = serde_json::to_value(&method).unwrap();
9884        assert_eq!(
9885            json,
9886            json!({
9887                "methodId": "tui-auth",
9888                "name": "Terminal Auth",
9889                "type": "terminal"
9890            })
9891        );
9892        // args and env should be omitted when empty
9893        assert!(!json.as_object().unwrap().contains_key("args"));
9894        assert!(!json.as_object().unwrap().contains_key("env"));
9895
9896        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9897        match deserialized {
9898            AuthMethod::Terminal(AuthMethodTerminal { args, env, .. }) => {
9899                assert_eq!(args, Vec::<String>::new());
9900                assert_eq!(env, []);
9901            }
9902            _ => panic!("Expected Terminal variant"),
9903        }
9904    }
9905
9906    #[test]
9907    fn test_auth_method_terminal_with_args_and_env_serialization() {
9908        let method = AuthMethod::Terminal(
9909            AuthMethodTerminal::new("tui-auth", "Terminal Auth")
9910                .args(vec!["--interactive".to_string(), "--color".to_string()])
9911                .env(vec![EnvVariable::new("TERM", "xterm-256color")]),
9912        );
9913
9914        let json = serde_json::to_value(&method).unwrap();
9915        assert_eq!(
9916            json,
9917            json!({
9918                "methodId": "tui-auth",
9919                "name": "Terminal Auth",
9920                "type": "terminal",
9921                "args": ["--interactive", "--color"],
9922                "env": [
9923                    {
9924                        "name": "TERM",
9925                        "value": "xterm-256color"
9926                    }
9927                ]
9928            })
9929        );
9930
9931        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9932        match deserialized {
9933            AuthMethod::Terminal(AuthMethodTerminal { args, env, .. }) => {
9934                assert_eq!(args, vec!["--interactive", "--color"]);
9935                assert_eq!(env.len(), 1);
9936                assert_eq!(env[0].name, "TERM");
9937                assert_eq!(env[0].value, "xterm-256color");
9938            }
9939            _ => panic!("Expected Terminal variant"),
9940        }
9941    }
9942
9943    #[test]
9944    fn test_session_config_option_id_serialize() {
9945        let val = SessionConfigOptionValue::id("model-1");
9946        let json = serde_json::to_value(&val).unwrap();
9947        assert_eq!(json, json!({ "type": "id", "value": "model-1" }));
9948    }
9949
9950    #[test]
9951    fn test_session_config_option_value_boolean_serialize() {
9952        let val = SessionConfigOptionValue::boolean(true);
9953        let json = serde_json::to_value(&val).unwrap();
9954        assert_eq!(json, json!({ "type": "boolean", "value": true }));
9955    }
9956
9957    #[test]
9958    fn test_session_config_option_value_deserialize_id() {
9959        let json = json!({ "type": "id", "value": "model-1" });
9960        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9961        assert_eq!(val, SessionConfigOptionValue::id("model-1"));
9962        assert_eq!(val.as_id().unwrap().to_string(), "model-1");
9963    }
9964
9965    #[test]
9966    fn test_session_config_option_value_deserialize_requires_type() {
9967        let json = json!({ "value": "model-1" });
9968        let result = serde_json::from_value::<SessionConfigOptionValue>(json);
9969        assert!(result.is_err());
9970    }
9971
9972    #[test]
9973    fn test_session_config_option_value_deserialize_boolean() {
9974        let json = json!({ "type": "boolean", "value": true });
9975        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9976        assert_eq!(val, SessionConfigOptionValue::boolean(true));
9977        assert_eq!(val.as_bool(), Some(true));
9978    }
9979
9980    #[test]
9981    fn test_session_config_option_value_deserialize_boolean_false() {
9982        let json = json!({ "type": "boolean", "value": false });
9983        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9984        assert_eq!(val, SessionConfigOptionValue::boolean(false));
9985        assert_eq!(val.as_bool(), Some(false));
9986    }
9987
9988    #[test]
9989    fn test_session_config_option_value_deserialize_unknown_type_with_string_value() {
9990        let json = json!({
9991            "type": "text",
9992            "value": "freeform input",
9993            "maxLength": 200
9994        });
9995        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9996        let SessionConfigOptionValue::Other(unknown) = val else {
9997            panic!("Expected Other variant");
9998        };
9999        assert_eq!(unknown.type_, "text");
10000        assert_eq!(unknown.value, json!("freeform input"));
10001        assert_eq!(unknown.fields["maxLength"], json!(200));
10002    }
10003
10004    #[test]
10005    fn test_session_config_option_value_deserialize_unknown_type_with_object_value() {
10006        let json = json!({
10007            "type": "range",
10008            "value": { "min": 1, "max": 5 }
10009        });
10010        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10011        let SessionConfigOptionValue::Other(unknown) = val else {
10012            panic!("Expected Other variant");
10013        };
10014        assert_eq!(unknown.type_, "range");
10015        assert_eq!(unknown.value, json!({ "min": 1, "max": 5 }));
10016    }
10017
10018    #[test]
10019    fn test_session_config_option_value_roundtrip_id() {
10020        let original = SessionConfigOptionValue::id("option-a");
10021        let json = serde_json::to_value(&original).unwrap();
10022        let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10023        assert_eq!(original, roundtripped);
10024    }
10025
10026    #[test]
10027    fn test_session_config_option_value_roundtrip_boolean() {
10028        let original = SessionConfigOptionValue::boolean(false);
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_other() {
10036        let mut fields = IndexMap::new();
10037        fields.insert("maxLength".to_string(), json!(200));
10038        let original = SessionConfigOptionValue::from(OtherSessionConfigOptionValue::new(
10039            "text",
10040            json!("freeform input"),
10041            fields,
10042        ));
10043        let json = serde_json::to_value(&original).unwrap();
10044        assert_eq!(
10045            json,
10046            json!({"type": "text", "value": "freeform input", "maxLength": 200})
10047        );
10048        let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10049        assert_eq!(original, roundtripped);
10050    }
10051
10052    #[test]
10053    fn test_session_config_option_value_type_mismatch_boolean_with_string() {
10054        let json = json!({ "type": "boolean", "value": "not a bool" });
10055        let result = serde_json::from_value::<SessionConfigOptionValue>(json);
10056        assert!(result.is_err());
10057    }
10058
10059    #[test]
10060    fn test_session_config_option_value_from_impls() {
10061        let from_str: SessionConfigOptionValue = "model-1".into();
10062        assert_eq!(from_str.as_id().unwrap().to_string(), "model-1");
10063
10064        let from_id: SessionConfigOptionValue = SessionConfigValueId::new("model-2").into();
10065        assert_eq!(from_id.as_id().unwrap().to_string(), "model-2");
10066
10067        let from_bool: SessionConfigOptionValue = true.into();
10068        assert_eq!(from_bool.as_bool(), Some(true));
10069    }
10070
10071    #[test]
10072    fn test_set_session_config_option_request_id() {
10073        let req = SetSessionConfigOptionRequest::new("sess_1", "model", "model-1");
10074        let json = serde_json::to_value(&req).unwrap();
10075        assert_eq!(
10076            json,
10077            json!({
10078                "sessionId": "sess_1",
10079                "configId": "model",
10080                "type": "id",
10081                "value": "model-1"
10082            })
10083        );
10084    }
10085
10086    #[test]
10087    fn test_set_session_config_option_request_boolean() {
10088        let req = SetSessionConfigOptionRequest::new("sess_1", "brave_mode", true);
10089        let json = serde_json::to_value(&req).unwrap();
10090        assert_eq!(
10091            json,
10092            json!({
10093                "sessionId": "sess_1",
10094                "configId": "brave_mode",
10095                "type": "boolean",
10096                "value": true
10097            })
10098        );
10099    }
10100
10101    #[test]
10102    fn test_set_session_config_option_request_deserialize_requires_type() {
10103        let json = json!({
10104            "sessionId": "sess_1",
10105            "configId": "model",
10106            "value": "model-1"
10107        });
10108        let result = serde_json::from_value::<SetSessionConfigOptionRequest>(json);
10109        assert!(result.is_err());
10110    }
10111
10112    #[test]
10113    fn test_set_session_config_option_request_deserialize_boolean() {
10114        let json = json!({
10115            "sessionId": "sess_1",
10116            "configId": "brave_mode",
10117            "type": "boolean",
10118            "value": true
10119        });
10120        let req: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
10121        assert_eq!(req.value.as_bool(), Some(true));
10122    }
10123
10124    #[test]
10125    fn test_set_session_config_option_request_roundtrip_id() {
10126        let original = SetSessionConfigOptionRequest::new("s", "c", "v");
10127        let json = serde_json::to_value(&original).unwrap();
10128        let roundtripped: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
10129        assert_eq!(original, roundtripped);
10130    }
10131
10132    #[test]
10133    fn test_set_session_config_option_request_roundtrip_boolean() {
10134        let original = SetSessionConfigOptionRequest::new("s", "c", false);
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_session_config_boolean_serialization() {
10142        let cfg = SessionConfigBoolean::new(true);
10143        let json = serde_json::to_value(&cfg).unwrap();
10144        assert_eq!(json, json!({ "currentValue": true }));
10145
10146        let deserialized: SessionConfigBoolean = serde_json::from_value(json).unwrap();
10147        assert!(deserialized.current_value);
10148    }
10149
10150    #[test]
10151    fn test_session_config_option_boolean_variant() {
10152        let opt = SessionConfigOption::boolean("brave_mode", "Brave Mode", false)
10153            .description("Skip confirmation prompts")
10154            .meta(test_meta());
10155        assert_eq!(serialized_meta_key_count(&opt), 1);
10156
10157        let json = serde_json::to_value(&opt).unwrap();
10158        assert_eq!(
10159            json,
10160            json!({
10161                "configId": "brave_mode",
10162                "name": "Brave Mode",
10163                "description": "Skip confirmation prompts",
10164                "type": "boolean",
10165                "currentValue": false,
10166                "_meta": {
10167                    "source": "test"
10168                }
10169            })
10170        );
10171
10172        let deserialized: SessionConfigOption = serde_json::from_value(json).unwrap();
10173        assert_eq!(deserialized.config_id.to_string(), "brave_mode");
10174        assert_eq!(deserialized.name, "Brave Mode");
10175        match deserialized.kind {
10176            SessionConfigKind::Boolean(ref b) => assert!(!b.current_value),
10177            _ => panic!("Expected Boolean kind"),
10178        }
10179    }
10180
10181    #[test]
10182    fn test_session_config_option_select_still_works() {
10183        // Make sure existing select options are unaffected
10184        let opt = SessionConfigOption::select(
10185            "model",
10186            "Model",
10187            "model-1",
10188            vec![
10189                SessionConfigSelectOption::new("model-1", "Model 1"),
10190                SessionConfigSelectOption::new("model-2", "Model 2"),
10191            ],
10192        )
10193        .meta(test_meta());
10194        assert_eq!(serialized_meta_key_count(&opt), 1);
10195
10196        let json = serde_json::to_value(&opt).unwrap();
10197        assert_eq!(json["type"], "select");
10198        assert_eq!(json["currentValue"], "model-1");
10199        assert_eq!(json["options"].as_array().unwrap().len(), 2);
10200        assert_eq!(json["_meta"]["source"], "test");
10201
10202        let deserialized: SessionConfigOption = serde_json::from_value(json).unwrap();
10203        match deserialized.kind {
10204            SessionConfigKind::Select(ref s) => {
10205                assert_eq!(s.current_value.to_string(), "model-1");
10206            }
10207            _ => panic!("Expected Select kind"),
10208        }
10209    }
10210
10211    #[test]
10212    fn test_session_config_option_unknown_kind_roundtrip() {
10213        let option: SessionConfigOption = serde_json::from_value(json!({
10214            "configId": "verbosity",
10215            "name": "Verbosity",
10216            "type": "_slider",
10217            "currentValue": 3,
10218            "min": 0,
10219            "max": 5,
10220            "_meta": {
10221                "source": "test"
10222            }
10223        }))
10224        .unwrap();
10225
10226        assert_eq!(option.config_id.to_string(), "verbosity");
10227        assert_eq!(option.meta.as_ref().unwrap()["source"], "test");
10228        let SessionConfigKind::Other(unknown) = &option.kind else {
10229            panic!("expected unknown config kind");
10230        };
10231        assert_eq!(unknown.type_, "_slider");
10232        assert_eq!(unknown.fields.get("currentValue"), Some(&json!(3)));
10233        assert!(!unknown.fields.contains_key("_meta"));
10234        assert_eq!(serialized_meta_key_count(&option), 1);
10235
10236        let json = serde_json::to_value(&option).unwrap();
10237        assert_eq!(json["type"], "_slider");
10238        assert_eq!(json["currentValue"], 3);
10239        assert_eq!(json["min"], 0);
10240        assert_eq!(json["max"], 5);
10241        assert_eq!(json["_meta"]["source"], "test");
10242    }
10243
10244    #[test]
10245    fn test_session_config_option_unknown_kind_does_not_duplicate_flattened_meta() {
10246        let mut fields = IndexMap::new();
10247        fields.insert("currentValue".to_string(), json!(3));
10248        fields.insert("_meta".to_string(), json!({ "inner": "ignored" }));
10249
10250        let option = SessionConfigOption::new(
10251            "verbosity",
10252            "Verbosity",
10253            SessionConfigKind::Other(OtherSessionConfigKind::new("_slider", fields)),
10254        )
10255        .meta(test_meta());
10256
10257        let SessionConfigKind::Other(unknown) = &option.kind else {
10258            panic!("expected unknown config kind");
10259        };
10260        assert!(!unknown.fields.contains_key("_meta"));
10261        assert_eq!(serialized_meta_key_count(&option), 1);
10262
10263        let json = serde_json::to_value(&option).unwrap();
10264        assert_eq!(json["type"], "_slider");
10265        assert_eq!(json["currentValue"], 3);
10266        assert_eq!(json["_meta"]["source"], "test");
10267    }
10268
10269    #[test]
10270    fn test_session_config_option_unknown_does_not_hide_malformed_known_kind() {
10271        assert!(
10272            serde_json::from_value::<SessionConfigOption>(json!({
10273                "configId": "model",
10274                "name": "Model",
10275                "type": "select"
10276            }))
10277            .is_err()
10278        );
10279    }
10280
10281    #[cfg(feature = "unstable_llm_providers")]
10282    #[test]
10283    fn test_llm_protocol_known_variants() {
10284        assert_eq!(
10285            serde_json::to_value(&LlmProtocol::Anthropic).unwrap(),
10286            json!("anthropic")
10287        );
10288        assert_eq!(
10289            serde_json::to_value(&LlmProtocol::OpenAi).unwrap(),
10290            json!("openai")
10291        );
10292        assert_eq!(
10293            serde_json::to_value(&LlmProtocol::Azure).unwrap(),
10294            json!("azure")
10295        );
10296        assert_eq!(
10297            serde_json::to_value(&LlmProtocol::Vertex).unwrap(),
10298            json!("vertex")
10299        );
10300        assert_eq!(
10301            serde_json::to_value(&LlmProtocol::Bedrock).unwrap(),
10302            json!("bedrock")
10303        );
10304
10305        assert_eq!(
10306            serde_json::from_str::<LlmProtocol>("\"anthropic\"").unwrap(),
10307            LlmProtocol::Anthropic
10308        );
10309        assert_eq!(
10310            serde_json::from_str::<LlmProtocol>("\"openai\"").unwrap(),
10311            LlmProtocol::OpenAi
10312        );
10313        assert_eq!(
10314            serde_json::from_str::<LlmProtocol>("\"azure\"").unwrap(),
10315            LlmProtocol::Azure
10316        );
10317        assert_eq!(
10318            serde_json::from_str::<LlmProtocol>("\"vertex\"").unwrap(),
10319            LlmProtocol::Vertex
10320        );
10321        assert_eq!(
10322            serde_json::from_str::<LlmProtocol>("\"bedrock\"").unwrap(),
10323            LlmProtocol::Bedrock
10324        );
10325    }
10326
10327    #[cfg(feature = "unstable_llm_providers")]
10328    #[test]
10329    fn test_llm_protocol_unknown_variant() {
10330        let unknown: LlmProtocol = serde_json::from_str("\"cohere\"").unwrap();
10331        assert_eq!(unknown, LlmProtocol::Other("cohere".to_string()));
10332
10333        let json = serde_json::to_value(&unknown).unwrap();
10334        assert_eq!(json, json!("cohere"));
10335    }
10336
10337    #[cfg(feature = "unstable_llm_providers")]
10338    #[test]
10339    fn test_provider_current_config_serialization() {
10340        let config =
10341            ProviderCurrentConfig::new(LlmProtocol::Anthropic, "https://api.anthropic.com");
10342
10343        let json = serde_json::to_value(&config).unwrap();
10344        assert_eq!(
10345            json,
10346            json!({
10347                "apiType": "anthropic",
10348                "baseUrl": "https://api.anthropic.com"
10349            })
10350        );
10351
10352        let deserialized: ProviderCurrentConfig = serde_json::from_value(json).unwrap();
10353        assert_eq!(deserialized.api_type, LlmProtocol::Anthropic);
10354        assert_eq!(deserialized.base_url, "https://api.anthropic.com");
10355    }
10356
10357    #[cfg(feature = "unstable_llm_providers")]
10358    #[test]
10359    fn test_provider_info_with_current_config() {
10360        let info = ProviderInfo::new(
10361            "main",
10362            vec![LlmProtocol::Anthropic, LlmProtocol::OpenAi],
10363            true,
10364            Some(ProviderCurrentConfig::new(
10365                LlmProtocol::Anthropic,
10366                "https://api.anthropic.com",
10367            )),
10368        );
10369
10370        let json = serde_json::to_value(&info).unwrap();
10371        assert_eq!(
10372            json,
10373            json!({
10374                "providerId": "main",
10375                "supported": ["anthropic", "openai"],
10376                "required": true,
10377                "current": {
10378                    "apiType": "anthropic",
10379                    "baseUrl": "https://api.anthropic.com"
10380                }
10381            })
10382        );
10383
10384        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10385        assert_eq!(deserialized.provider_id.to_string(), "main");
10386        assert_eq!(deserialized.supported.len(), 2);
10387        assert!(deserialized.required);
10388        assert!(deserialized.current.is_some());
10389        assert_eq!(
10390            deserialized.current.as_ref().unwrap().api_type,
10391            LlmProtocol::Anthropic
10392        );
10393    }
10394
10395    #[cfg(feature = "unstable_llm_providers")]
10396    #[test]
10397    fn test_provider_info_disabled() {
10398        let info = ProviderInfo::new(
10399            "secondary",
10400            vec![LlmProtocol::OpenAi],
10401            false,
10402            None::<ProviderCurrentConfig>,
10403        );
10404
10405        let json = serde_json::to_value(&info).unwrap();
10406        assert_eq!(
10407            json,
10408            json!({
10409                "providerId": "secondary",
10410                "supported": ["openai"],
10411                "required": false
10412            })
10413        );
10414
10415        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10416        assert_eq!(deserialized.provider_id.to_string(), "secondary");
10417        assert!(!deserialized.required);
10418        assert!(deserialized.current.is_none());
10419    }
10420
10421    #[cfg(feature = "unstable_llm_providers")]
10422    #[test]
10423    fn test_provider_info_missing_current_defaults_to_none() {
10424        // current is optional; omitting it should decode as None
10425        let json = json!({
10426            "providerId": "main",
10427            "supported": ["anthropic"],
10428            "required": true
10429        });
10430        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10431        assert!(deserialized.current.is_none());
10432    }
10433
10434    #[cfg(feature = "unstable_llm_providers")]
10435    #[test]
10436    fn test_provider_info_explicit_null_current_decodes_to_none() {
10437        // current: null and an omitted current are equivalent on the wire;
10438        // both must deserialize into None so the disabled state is preserved
10439        // regardless of which form the peer chose to send.
10440        let json = json!({
10441            "providerId": "main",
10442            "supported": ["anthropic"],
10443            "required": true,
10444            "current": null
10445        });
10446        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10447        assert!(deserialized.current.is_none());
10448    }
10449
10450    #[cfg(feature = "unstable_llm_providers")]
10451    #[test]
10452    fn test_list_providers_response_serialization() {
10453        let response = ListProvidersResponse::new(vec![ProviderInfo::new(
10454            "main",
10455            vec![LlmProtocol::Anthropic],
10456            true,
10457            Some(ProviderCurrentConfig::new(
10458                LlmProtocol::Anthropic,
10459                "https://api.anthropic.com",
10460            )),
10461        )]);
10462
10463        let json = serde_json::to_value(&response).unwrap();
10464        assert_eq!(json["providers"].as_array().unwrap().len(), 1);
10465        assert_eq!(json["providers"][0]["providerId"], "main");
10466
10467        let deserialized: ListProvidersResponse = serde_json::from_value(json).unwrap();
10468        assert_eq!(deserialized.providers.len(), 1);
10469    }
10470
10471    #[cfg(feature = "unstable_llm_providers")]
10472    #[test]
10473    fn test_set_provider_request_serialization() {
10474        let mut headers = IndexMap::new();
10475        headers.insert("Authorization".to_string(), "Bearer sk-test".to_string());
10476
10477        let request =
10478            SetProviderRequest::new("main", LlmProtocol::OpenAi, "https://api.openai.com/v1")
10479                .headers(headers);
10480
10481        let json = serde_json::to_value(&request).unwrap();
10482        assert_eq!(
10483            json,
10484            json!({
10485                "providerId": "main",
10486                "apiType": "openai",
10487                "baseUrl": "https://api.openai.com/v1",
10488                "headers": {
10489                    "Authorization": "Bearer sk-test"
10490                }
10491            })
10492        );
10493
10494        let deserialized: SetProviderRequest = serde_json::from_value(json).unwrap();
10495        assert_eq!(deserialized.provider_id.to_string(), "main");
10496        assert_eq!(deserialized.api_type, LlmProtocol::OpenAi);
10497        assert_eq!(deserialized.base_url, "https://api.openai.com/v1");
10498        assert_eq!(deserialized.headers.len(), 1);
10499        assert_eq!(
10500            deserialized.headers.get("Authorization").unwrap(),
10501            "Bearer sk-test"
10502        );
10503    }
10504
10505    #[cfg(feature = "unstable_llm_providers")]
10506    #[test]
10507    fn test_set_provider_request_omits_empty_headers() {
10508        let request =
10509            SetProviderRequest::new("main", LlmProtocol::Anthropic, "https://api.anthropic.com");
10510
10511        let json = serde_json::to_value(&request).unwrap();
10512        // headers should be omitted when empty
10513        assert!(!json.as_object().unwrap().contains_key("headers"));
10514    }
10515
10516    #[cfg(feature = "unstable_llm_providers")]
10517    #[test]
10518    fn test_disable_provider_request_serialization() {
10519        let request = DisableProviderRequest::new("secondary");
10520
10521        let json = serde_json::to_value(&request).unwrap();
10522        assert_eq!(json, json!({ "providerId": "secondary" }));
10523
10524        let deserialized: DisableProviderRequest = serde_json::from_value(json).unwrap();
10525        assert_eq!(deserialized.provider_id.to_string(), "secondary");
10526    }
10527
10528    #[cfg(feature = "unstable_llm_providers")]
10529    #[test]
10530    fn test_providers_capabilities_serialization() {
10531        let caps = ProvidersCapabilities::new();
10532
10533        let json = serde_json::to_value(&caps).unwrap();
10534        assert_eq!(json, json!({}));
10535
10536        let deserialized: ProvidersCapabilities = serde_json::from_value(json).unwrap();
10537        assert!(deserialized.meta.is_none());
10538    }
10539
10540    #[cfg(feature = "unstable_llm_providers")]
10541    #[test]
10542    fn test_agent_capabilities_with_providers() {
10543        let caps = AgentCapabilities::new().providers(ProvidersCapabilities::new());
10544
10545        let json = serde_json::to_value(&caps).unwrap();
10546        assert_eq!(json["providers"], json!({}));
10547
10548        let deserialized: AgentCapabilities = serde_json::from_value(json).unwrap();
10549        assert!(deserialized.providers.is_some());
10550    }
10551
10552    #[test]
10553    fn test_agent_capabilities_session_is_explicit() {
10554        let json = serde_json::to_value(AgentCapabilities::new()).unwrap();
10555        assert!(json.get("session").is_none());
10556
10557        let caps = AgentCapabilities::new().session(
10558            SessionCapabilities::new()
10559                .prompt(PromptCapabilities::new().image(PromptImageCapabilities::new()))
10560                .mcp(McpCapabilities::new().stdio(McpStdioCapabilities::new())),
10561        );
10562
10563        assert_eq!(
10564            serde_json::to_value(&caps).unwrap(),
10565            json!({
10566                "session": {
10567                    "prompt": {
10568                        "image": {}
10569                    },
10570                    "mcp": {
10571                        "stdio": {}
10572                    }
10573                }
10574            })
10575        );
10576
10577        let deserialized: AgentCapabilities = serde_json::from_value(json!({
10578            "session": false
10579        }))
10580        .unwrap();
10581        assert!(deserialized.session.is_none());
10582    }
10583
10584    #[test]
10585    fn test_prompt_capabilities_serialize_supported_content_as_objects() {
10586        let caps = PromptCapabilities::new()
10587            .image(PromptImageCapabilities::new())
10588            .audio(PromptAudioCapabilities::new())
10589            .embedded_context(PromptEmbeddedContextCapabilities::new());
10590
10591        assert_eq!(
10592            serde_json::to_value(&caps).unwrap(),
10593            json!({
10594                "image": {},
10595                "audio": {},
10596                "embeddedContext": {}
10597            })
10598        );
10599
10600        let deserialized: PromptCapabilities = serde_json::from_value(json!({
10601            "image": null,
10602            "audio": false,
10603            "embeddedContext": {}
10604        }))
10605        .unwrap();
10606        assert!(deserialized.image.is_none());
10607        assert!(deserialized.audio.is_none());
10608        assert!(deserialized.embedded_context.is_some());
10609    }
10610
10611    #[cfg(feature = "unstable_agent_skills")]
10612    #[test]
10613    fn prompt_skill_capability_has_two_levels() {
10614        // `{}` allows one leading skill block. `inline` allows them anywhere.
10615        let leading = PromptCapabilities::new().skill(PromptSkillCapabilities::new());
10616        assert_eq!(
10617            serde_json::to_value(&leading).unwrap(),
10618            json!({ "skill": {} })
10619        );
10620
10621        let inline = PromptCapabilities::new()
10622            .skill(PromptSkillCapabilities::new().inline(PromptSkillInlineCapabilities::new()));
10623        let wire = json!({ "skill": { "inline": {} } });
10624        assert_eq!(serde_json::to_value(&inline).unwrap(), wire);
10625        assert_eq!(
10626            serde_json::from_value::<PromptCapabilities>(wire).unwrap(),
10627            inline
10628        );
10629
10630        for unsupported in [
10631            json!({}),
10632            json!({ "skill": null }),
10633            json!({ "skill": false }),
10634            json!({ "skill": true }),
10635        ] {
10636            let caps: PromptCapabilities = serde_json::from_value(unsupported).unwrap();
10637            assert!(caps.skill.is_none());
10638        }
10639
10640        // A malformed `inline` does not withdraw the first level.
10641        for leading_only in [
10642            json!({ "skill": { "inline": null } }),
10643            json!({ "skill": { "inline": true } }),
10644        ] {
10645            assert_eq!(
10646                serde_json::from_value::<PromptCapabilities>(leading_only).unwrap(),
10647                leading
10648            );
10649        }
10650    }
10651
10652    #[test]
10653    fn test_mcp_capabilities_serialize_supported_transports_as_objects() {
10654        let caps = McpCapabilities::new()
10655            .stdio(McpStdioCapabilities::new())
10656            .http(McpHttpCapabilities::new());
10657
10658        assert_eq!(
10659            serde_json::to_value(&caps).unwrap(),
10660            json!({
10661                "stdio": {},
10662                "http": {}
10663            })
10664        );
10665
10666        let deserialized: McpCapabilities = serde_json::from_value(json!({
10667            "stdio": null,
10668            "http": false
10669        }))
10670        .unwrap();
10671        assert!(deserialized.stdio.is_none());
10672        assert!(deserialized.http.is_none());
10673    }
10674
10675    #[cfg(feature = "unstable_mcp_over_acp")]
10676    #[test]
10677    fn test_mcp_capabilities_serialize_acp_support_as_object() {
10678        let caps = McpCapabilities::new().acp(McpAcpCapabilities::new());
10679
10680        assert_eq!(
10681            serde_json::to_value(&caps).unwrap(),
10682            json!({
10683                "acp": {}
10684            })
10685        );
10686    }
10687
10688    #[test]
10689    fn prompt_request_rejects_malformed_content_block() {
10690        use serde_json::json;
10691
10692        assert!(
10693            serde_json::from_value::<PromptRequest>(json!({
10694                "sessionId": "sess-1",
10695                "prompt": [{"type": "text"}]
10696            }))
10697            .is_err()
10698        );
10699    }
10700
10701    #[test]
10702    fn prompt_request_rejects_non_array_prompt() {
10703        use serde_json::json;
10704
10705        assert!(
10706            serde_json::from_value::<PromptRequest>(json!({
10707                "sessionId": "sess-1",
10708                "prompt": "hello"
10709            }))
10710            .is_err()
10711        );
10712    }
10713
10714    fn prompt_request_with_idempotency_key(key: &serde_json::Value) -> serde_json::Value {
10715        serde_json::json!({
10716            "sessionId": "sess-1",
10717            "idempotencyKey": key,
10718            "prompt": [{"type": "text", "text": "hello"}]
10719        })
10720    }
10721
10722    #[test]
10723    fn prompt_request_idempotency_key_round_trips() {
10724        use serde_json::json;
10725
10726        let key = "0b6f3c1e-8d2a-4c57-9a41-5e2f7d90c3ab";
10727        let value = prompt_request_with_idempotency_key(&json!(key));
10728
10729        let request: PromptRequest = serde_json::from_value(value.clone()).unwrap();
10730        assert_eq!(
10731            request.idempotency_key.as_ref().map(IdempotencyKey::as_str),
10732            Some(key)
10733        );
10734        assert_eq!(serde_json::to_value(&request).unwrap(), value);
10735
10736        let built = PromptRequest::new("sess-1", vec![ContentBlock::from("hello")])
10737            .idempotency_key(IdempotencyKey::new(key).unwrap());
10738        assert_eq!(built, request);
10739    }
10740
10741    #[test]
10742    fn prompt_request_omitted_and_null_idempotency_key_mean_no_key() {
10743        use serde_json::json;
10744
10745        let omitted = json!({
10746            "sessionId": "sess-1",
10747            "prompt": [{"type": "text", "text": "hello"}]
10748        });
10749        let request: PromptRequest = serde_json::from_value(omitted.clone()).unwrap();
10750        assert_eq!(request.idempotency_key, None);
10751        // No key is serialized as an omitted field, not as `null`.
10752        assert_eq!(serde_json::to_value(&request).unwrap(), omitted);
10753
10754        let null: PromptRequest =
10755            serde_json::from_value(prompt_request_with_idempotency_key(&json!(null))).unwrap();
10756        assert_eq!(null, request);
10757    }
10758
10759    #[test]
10760    fn prompt_request_rejects_malformed_idempotency_key() {
10761        use serde_json::json;
10762
10763        let too_long = "k".repeat(IdempotencyKey::MAX_LENGTH + 1);
10764        for (name, key) in [
10765            ("an empty string", json!("")),
10766            ("a string over 255 characters", json!(too_long)),
10767            ("a number", json!(7)),
10768            ("a boolean", json!(true)),
10769            ("an object", json!({"key": "k"})),
10770            ("an array", json!(["k"])),
10771        ] {
10772            assert!(
10773                serde_json::from_value::<PromptRequest>(prompt_request_with_idempotency_key(&key))
10774                    .is_err(),
10775                "{name} must fail the request instead of being treated as no key"
10776            );
10777        }
10778    }
10779
10780    #[test]
10781    fn idempotency_key_length_is_counted_in_characters() {
10782        use serde_json::json;
10783
10784        assert_eq!(IdempotencyKey::new(""), Err(InvalidIdempotencyKey::Empty));
10785        assert_eq!(IdempotencyKey::new("k").unwrap().as_str(), "k");
10786
10787        let longest = "k".repeat(IdempotencyKey::MAX_LENGTH);
10788        assert_eq!(
10789            IdempotencyKey::new(longest.as_str()).unwrap().as_str(),
10790            longest
10791        );
10792        assert_eq!(
10793            IdempotencyKey::new(format!("{longest}k")),
10794            Err(InvalidIdempotencyKey::TooLong)
10795        );
10796
10797        // 255 two-byte characters are 510 bytes and still within the limit.
10798        let multibyte = "é".repeat(IdempotencyKey::MAX_LENGTH);
10799        assert!(IdempotencyKey::new(multibyte.as_str()).is_ok());
10800        assert!(
10801            serde_json::from_value::<PromptRequest>(prompt_request_with_idempotency_key(&json!(
10802                multibyte
10803            )))
10804            .is_ok()
10805        );
10806        assert_eq!(
10807            IdempotencyKey::new(format!("{multibyte}é")),
10808            Err(InvalidIdempotencyKey::TooLong)
10809        );
10810
10811        assert_eq!("k".parse::<IdempotencyKey>().unwrap().to_string(), "k");
10812        assert_eq!(
10813            IdempotencyKey::try_from(String::new()),
10814            Err(InvalidIdempotencyKey::Empty)
10815        );
10816        assert_eq!(
10817            InvalidIdempotencyKey::TooLong.to_string(),
10818            "idempotency key must be at most 255 characters"
10819        );
10820    }
10821
10822    #[cfg(feature = "uuid")]
10823    #[test]
10824    fn generated_idempotency_keys_are_distinct_valid_v4_uuids() {
10825        let first = IdempotencyKey::generate();
10826        let second = IdempotencyKey::generate();
10827        assert_ne!(first, second);
10828
10829        for key in [&first, &second] {
10830            let uuid = uuid::Uuid::parse_str(key.as_str()).unwrap();
10831            assert_eq!(uuid.get_version_num(), 4);
10832            // A generated key passes the same validation as any other key.
10833            assert_eq!(IdempotencyKey::new(key.as_str()).as_ref(), Ok(key));
10834            let request = PromptRequest::new("sess-1", vec![ContentBlock::from("hello")])
10835                .idempotency_key(key.clone());
10836            let value = serde_json::to_value(&request).unwrap();
10837            assert_eq!(value["idempotencyKey"], key.as_str());
10838            assert_eq!(
10839                serde_json::from_value::<PromptRequest>(value).unwrap(),
10840                request
10841            );
10842        }
10843
10844        assert_eq!(
10845            IdempotencyKey::from(uuid::Uuid::nil()).as_str(),
10846            "00000000-0000-0000-0000-000000000000"
10847        );
10848    }
10849
10850    #[cfg(feature = "schemars")]
10851    #[test]
10852    fn idempotency_key_schema_is_a_strict_bounded_string() {
10853        use serde_json::json;
10854
10855        let key = serde_json::to_value(schemars::schema_for!(IdempotencyKey)).unwrap();
10856        assert_eq!(key["type"], "string");
10857        assert_eq!(key["minLength"], 1);
10858        assert_eq!(key["maxLength"], json!(IdempotencyKey::MAX_LENGTH));
10859
10860        let request = serde_json::to_value(schemars::schema_for!(PromptRequest)).unwrap();
10861        assert_eq!(request["required"], json!(["sessionId", "prompt"]));
10862        let property = &request["properties"]["idempotencyKey"];
10863        assert_eq!(
10864            property["anyOf"],
10865            json!([{"$ref": "#/$defs/IdempotencyKey"}, {"type": "null"}])
10866        );
10867        // The Agent acts on the key, so the schema must not mark it as tolerant
10868        // of malformed values.
10869        assert!(property.get("x-deserialize-default-on-error").is_none());
10870    }
10871
10872    fn assert_session_setup_lists_are_strict<T>(base: &serde_json::Value)
10873    where
10874        T: serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
10875    {
10876        let name = std::any::type_name::<T>();
10877        let with = |field: &str, value: serde_json::Value| {
10878            let mut request = base.clone();
10879            request[field] = value;
10880            serde_json::from_value::<T>(request)
10881        };
10882
10883        for (field, value) in [
10884            // Dropping the malformed server would start the session without it.
10885            (
10886                "mcpServers",
10887                json!([
10888                    {"type": "stdio", "name": "github", "command": "/usr/bin/gh-mcp", "env": [{"name": "GITHUB_TOKEN", "value": null}]},
10889                    {"type": "stdio", "name": "fs", "command": "/usr/bin/fs-mcp"}
10890                ]),
10891            ),
10892            ("mcpServers", json!({"type": "stdio", "name": "fs"})),
10893            ("additionalDirectories", json!(["/repo/lib", 42])),
10894            ("additionalDirectories", json!("/repo/lib")),
10895        ] {
10896            assert!(
10897                with(field, value.clone()).is_err(),
10898                "{name}.{field}: {value}"
10899            );
10900        }
10901
10902        let empty = serde_json::from_value::<T>(base.clone()).unwrap();
10903        for field in ["mcpServers", "additionalDirectories"] {
10904            assert_eq!(
10905                with(field, serde_json::Value::Null).unwrap(),
10906                empty,
10907                "{name}.{field}"
10908            );
10909        }
10910    }
10911
10912    #[test]
10913    fn session_setup_requests_reject_malformed_mcp_servers_and_directories() {
10914        assert_session_setup_lists_are_strict::<NewSessionRequest>(&json!({"cwd": "/repo"}));
10915        assert_session_setup_lists_are_strict::<ResumeSessionRequest>(&json!({
10916            "sessionId": "sess-1",
10917            "cwd": "/repo"
10918        }));
10919        #[cfg(feature = "unstable_session_fork")]
10920        assert_session_setup_lists_are_strict::<ForkSessionRequest>(&json!({
10921            "sessionId": "sess-1",
10922            "cwd": "/repo"
10923        }));
10924    }
10925
10926    #[test]
10927    fn resume_session_request_rejects_malformed_replay_from() {
10928        let request = |replay_from: serde_json::Value| {
10929            serde_json::from_value::<ResumeSessionRequest>(json!({
10930                "sessionId": "sess-1",
10931                "cwd": "/repo",
10932                "replayFrom": replay_from
10933            }))
10934        };
10935
10936        // Treating this as omitted would reconnect without the requested replay.
10937        assert!(request(json!("start")).is_err());
10938        assert_eq!(request(serde_json::Value::Null).unwrap().replay_from, None);
10939        assert!(matches!(
10940            request(json!({"type": "start"})).unwrap().replay_from,
10941            Some(ReplayFrom::Start(_))
10942        ));
10943    }
10944
10945    #[test]
10946    fn mcp_server_lists_treat_null_as_empty() {
10947        let servers: Vec<McpServer> = serde_json::from_value(json!([
10948            {"type": "stdio", "name": "fs", "command": "/usr/bin/fs-mcp", "args": null, "env": null},
10949            {"type": "http", "name": "api", "url": "https://example.com/mcp", "headers": null}
10950        ]))
10951        .unwrap();
10952
10953        assert_eq!(
10954            servers,
10955            vec![
10956                McpServer::Stdio(McpServerStdio::new("fs", "/usr/bin/fs-mcp")),
10957                McpServer::Http(McpServerHttp::new("api", "https://example.com/mcp")),
10958            ]
10959        );
10960    }
10961
10962    #[test]
10963    fn terminal_auth_methods_reject_malformed_launch_config() {
10964        // The client spawns a process from `args` and `env`, so a malformed
10965        // method is dropped from `authMethods` instead of launched with
10966        // altered arguments or preserved as an unknown method.
10967        let response: InitializeResponse = serde_json::from_value(json!({
10968            "protocolVersion": 2,
10969            "info": {"name": "agent", "version": "1.0.0"},
10970            "authMethods": [
10971                {"type": "terminal", "methodId": "bad-args", "name": "Log in", "args": ["auth", "--port", 8123]},
10972                {"type": "terminal", "methodId": "bad-env", "name": "Log in", "env": [{"name": "DEBUG", "value": 1}]},
10973                {"type": "terminal", "methodId": "null-config", "name": "Log in", "args": null, "env": null},
10974                {"type": "agent", "methodId": "agent", "name": "Agent login"}
10975            ]
10976        }))
10977        .unwrap();
10978
10979        assert_eq!(
10980            response.auth_methods,
10981            vec![
10982                AuthMethod::Terminal(AuthMethodTerminal::new("null-config", "Log in")),
10983                AuthMethod::Agent(AuthMethodAgent::new("agent", "Agent login")),
10984            ]
10985        );
10986    }
10987
10988    #[cfg(feature = "unstable_auth_status")]
10989    #[test]
10990    fn auth_status_response_round_trips() {
10991        let response = AuthStatusResponse::new(AuthState::Authenticated).accounts(vec![
10992            AuthAccount::new("Anthropic API key")
10993                .description("API key helper".to_string())
10994                .active(true),
10995            AuthAccount::new("Claude Max").email("user@example.com".to_string()),
10996        ]);
10997        let json = serde_json::to_value(&response).unwrap();
10998        assert_eq!(
10999            json,
11000            json!({
11001                "state": "authenticated",
11002                "accounts": [
11003                    {
11004                        "label": "Anthropic API key",
11005                        "description": "API key helper",
11006                        "active": true
11007                    },
11008                    {
11009                        "label": "Claude Max",
11010                        "email": "user@example.com"
11011                    }
11012                ]
11013            })
11014        );
11015        assert_eq!(
11016            serde_json::from_value::<AuthStatusResponse>(json).unwrap(),
11017            response
11018        );
11019        assert_eq!(
11020            serde_json::to_value(AuthStatusResponse::new(AuthState::NotRequired)).unwrap(),
11021            json!({"state": "not_required"})
11022        );
11023    }
11024
11025    #[cfg(feature = "unstable_auth_status")]
11026    #[test]
11027    fn auth_status_state_is_strict_and_accounts_are_lenient() {
11028        assert!(serde_json::from_value::<AuthStatusResponse>(json!({})).is_err());
11029        assert!(serde_json::from_value::<AuthStatusResponse>(json!({"state": null})).is_err());
11030        assert!(serde_json::from_value::<AuthStatusResponse>(json!({"state": 1})).is_err());
11031
11032        let response: AuthStatusResponse = serde_json::from_value(json!({
11033            "state": "_vendor_state",
11034            "accounts": [
11035                {"active": true},
11036                {
11037                    "label": "Vertex AI",
11038                    "description": 42,
11039                    "active": "yes",
11040                    "email": ["not", "a", "string"]
11041                }
11042            ]
11043        }))
11044        .unwrap();
11045        assert_eq!(
11046            response,
11047            AuthStatusResponse::new(AuthState::Other("_vendor_state".to_string()))
11048                .accounts(vec![AuthAccount::new("Vertex AI")])
11049        );
11050        assert_eq!(
11051            serde_json::from_value::<AuthStatusResponse>(
11052                json!({"state": "unknown", "accounts": null})
11053            )
11054            .unwrap(),
11055            AuthStatusResponse::new(AuthState::Unknown)
11056        );
11057    }
11058
11059    #[cfg(feature = "unstable_auth_status")]
11060    #[test]
11061    fn auth_status_update_notification_routes() {
11062        use crate::v2::{AgentNotification, CLIENT_METHOD_NAMES};
11063
11064        assert_eq!(AGENT_METHOD_NAMES.auth_status, "auth/status");
11065        assert_eq!(CLIENT_METHOD_NAMES.auth_status_update, "auth/status_update");
11066        let notification = AgentNotification::AuthStatusUpdateNotification(Box::new(
11067            AuthStatusUpdateNotification::new(AuthState::Unauthenticated),
11068        ));
11069        assert_eq!(notification.method(), "auth/status_update");
11070        assert_eq!(
11071            serde_json::to_value(&notification).unwrap(),
11072            json!({"state": "unauthenticated"})
11073        );
11074    }
11075
11076    #[cfg(all(
11077        feature = "unstable_session_fork",
11078        feature = "unstable_session_cursors"
11079    ))]
11080    #[test]
11081    fn fork_session_request_cursor_id_is_optional_and_strict() {
11082        let request = ForkSessionRequest::new("sess_abc123", "/home/user/project")
11083            .cursor_id(CursorId::new("cur_1"));
11084        let wire = json!({
11085            "sessionId": "sess_abc123",
11086            "cursorId": "cur_1",
11087            "cwd": "/home/user/project"
11088        });
11089        assert_eq!(serde_json::to_value(&request).unwrap(), wire);
11090        assert_eq!(
11091            serde_json::from_value::<ForkSessionRequest>(wire).unwrap(),
11092            request
11093        );
11094
11095        // Omitted and `null` both fork the whole session.
11096        for wire in [
11097            json!({ "sessionId": "sess_abc123", "cwd": "/home/user/project" }),
11098            json!({ "sessionId": "sess_abc123", "cwd": "/home/user/project", "cursorId": null }),
11099        ] {
11100            assert_eq!(
11101                serde_json::from_value::<ForkSessionRequest>(wire)
11102                    .unwrap()
11103                    .cursor_id,
11104                None
11105            );
11106        }
11107
11108        // A malformed cursor ID fails the request. It never forks the whole session.
11109        assert!(
11110            serde_json::from_value::<ForkSessionRequest>(json!({
11111                "sessionId": "sess_abc123",
11112                "cwd": "/home/user/project",
11113                "cursorId": 7
11114            }))
11115            .is_err()
11116        );
11117    }
11118}