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    /// May contain Markdown.
999    #[must_use]
1000    pub fn description(&self) -> Option<&str> {
1001        match self {
1002            Self::Agent(a) => a.description.as_deref(),
1003            Self::Other(a) => a
1004                .fields
1005                .get("description")
1006                .and_then(serde_json::Value::as_str),
1007            Self::Terminal(t) => t.description.as_deref(),
1008        }
1009    }
1010
1011    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1012    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1013    /// do not recognize.
1014    ///
1015    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1016    #[must_use]
1017    pub fn meta(&self) -> Option<&Meta> {
1018        match self {
1019            Self::Agent(a) => a.meta.as_ref(),
1020            Self::Other(a) => a.fields.get("_meta").and_then(serde_json::Value::as_object),
1021            Self::Terminal(t) => t.meta.as_ref(),
1022        }
1023    }
1024}
1025
1026/// Custom or future authentication method payload.
1027#[serde_as]
1028#[skip_serializing_none]
1029#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1030#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1031#[cfg_attr(feature = "schemars", schemars(inline))]
1032#[cfg_attr(feature = "schemars", schemars(transform = other_auth_method_schema))]
1033#[serde(rename_all = "camelCase")]
1034#[non_exhaustive]
1035pub struct OtherAuthMethod {
1036    /// Custom or future authentication method type.
1037    ///
1038    /// Values beginning with `_` are reserved for implementation-specific
1039    /// extensions. Unknown values that do not begin with `_` are reserved for
1040    /// future ACP variants.
1041    #[serde(rename = "type")]
1042    pub type_: String,
1043    /// Unique identifier for this authentication method.
1044    pub method_id: AuthMethodId,
1045    /// Human-readable name of the authentication method.
1046    pub name: String,
1047    /// The remaining fields of the unknown authentication method payload, preserved verbatim,
1048    /// including `description` and `_meta`.
1049    #[serde(flatten)]
1050    pub fields: IndexMap<String, serde_json::Value>,
1051}
1052
1053impl OtherAuthMethod {
1054    /// Builds [`OtherAuthMethod`] from an unknown discriminator and preserves the remaining extension fields.
1055    #[must_use]
1056    pub fn new(
1057        type_: impl Into<String>,
1058        method_id: impl Into<AuthMethodId>,
1059        name: impl Into<String>,
1060        mut fields: IndexMap<String, serde_json::Value>,
1061    ) -> Self {
1062        fields.shift_remove("type");
1063        fields.shift_remove("methodId");
1064        fields.shift_remove("name");
1065        Self {
1066            type_: type_.into(),
1067            method_id: method_id.into(),
1068            name: name.into(),
1069            fields,
1070        }
1071    }
1072}
1073
1074impl<'de> Deserialize<'de> for OtherAuthMethod {
1075    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1076    where
1077        D: serde::Deserializer<'de>,
1078    {
1079        #[derive(Deserialize)]
1080        #[serde(rename_all = "camelCase")]
1081        struct RawOtherAuthMethod {
1082            #[serde(rename = "type")]
1083            type_: String,
1084            method_id: AuthMethodId,
1085            name: String,
1086            #[serde(flatten)]
1087            fields: IndexMap<String, serde_json::Value>,
1088        }
1089
1090        let raw = RawOtherAuthMethod::deserialize(deserializer)?;
1091        if is_known_auth_method_type(&raw.type_) {
1092            return Err(serde::de::Error::custom(format!(
1093                "known authentication method `{}` did not match its schema",
1094                raw.type_
1095            )));
1096        }
1097
1098        Ok(Self {
1099            type_: raw.type_,
1100            method_id: raw.method_id,
1101            name: raw.name,
1102            fields: raw.fields,
1103        })
1104    }
1105}
1106
1107fn is_known_auth_method_type(type_: &str) -> bool {
1108    matches!(type_, "agent" | "terminal")
1109}
1110
1111#[cfg(feature = "schemars")]
1112fn other_auth_method_schema(schema: &mut Schema) {
1113    super::schema_util::reject_known_string_discriminators(schema, "type", &["agent", "terminal"]);
1114}
1115
1116/// Agent handles authentication itself through `auth/login`.
1117///
1118/// The `type` discriminator value is `agent`.
1119#[serde_as]
1120#[skip_serializing_none]
1121#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1122#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1123#[serde(rename_all = "camelCase")]
1124#[non_exhaustive]
1125pub struct AuthMethodAgent {
1126    /// Unique identifier for this authentication method.
1127    pub method_id: AuthMethodId,
1128    /// Human-readable name of the authentication method.
1129    pub name: String,
1130    /// Optional human-readable description of this authentication method.
1131    /// May contain Markdown.
1132    ///
1133    /// Omitted and `null` are equivalent and mean no description is provided.
1134    #[serde_as(deserialize_as = "DefaultOnError")]
1135    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1136    #[serde(default)]
1137    pub description: Option<String>,
1138    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1139    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1140    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1141    ///
1142    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1143    #[serde_as(deserialize_as = "DefaultOnError")]
1144    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1145    #[serde(default)]
1146    #[serde(rename = "_meta")]
1147    pub meta: Option<Meta>,
1148}
1149
1150impl AuthMethodAgent {
1151    /// Builds [`AuthMethodAgent`] with the required fields set. Optional fields start unset or empty.
1152    #[must_use]
1153    pub fn new(method_id: impl Into<AuthMethodId>, name: impl Into<String>) -> Self {
1154        Self {
1155            method_id: method_id.into(),
1156            name: name.into(),
1157            description: None,
1158            meta: None,
1159        }
1160    }
1161
1162    /// Optional human-readable description of this authentication method.
1163    /// May contain Markdown.
1164    #[must_use]
1165    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
1166        self.description = description.into_option();
1167        self
1168    }
1169
1170    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1171    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1172    /// do not recognize.
1173    ///
1174    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1175    #[must_use]
1176    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1177        self.meta = meta.into_option();
1178        self
1179    }
1180}
1181
1182/// Terminal-based authentication method.
1183///
1184/// The Client runs the configured Agent program as a separate interactive
1185/// process for the user to authenticate via a TUI. Agents MUST advertise this
1186/// method only when the Client enabled its terminal authentication capability.
1187/// A zero exit status signals success. Any other termination signals failure.
1188/// The Client MUST NOT pass this method to `auth/login`.
1189#[serde_as]
1190#[skip_serializing_none]
1191#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1192#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1193#[serde(rename_all = "camelCase")]
1194#[non_exhaustive]
1195pub struct AuthMethodTerminal {
1196    /// Unique identifier for this authentication method.
1197    pub method_id: AuthMethodId,
1198    /// Human-readable name of the authentication method.
1199    pub name: String,
1200    /// Optional human-readable description of this authentication method.
1201    /// May contain Markdown.
1202    ///
1203    /// Omitted and `null` are equivalent and mean no description is provided.
1204    #[serde_as(deserialize_as = "DefaultOnError")]
1205    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1206    #[serde(default)]
1207    pub description: Option<String>,
1208    /// Additional arguments to append to the configured Agent invocation for terminal auth.
1209    #[serde_as(deserialize_as = "DefaultOnNull")]
1210    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1211    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1212    pub args: Vec<String>,
1213    /// Additional environment variables to set on the configured Agent invocation for terminal auth.
1214    /// Names SHOULD be unique, and otherwise the last entry wins. These values override
1215    /// same-named variables in the base launch configuration.
1216    #[serde_as(deserialize_as = "DefaultOnNull")]
1217    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1218    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1219    pub env: Vec<EnvVariable>,
1220    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1221    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1222    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1223    ///
1224    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1225    #[serde_as(deserialize_as = "DefaultOnError")]
1226    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1227    #[serde(default)]
1228    #[serde(rename = "_meta")]
1229    pub meta: Option<Meta>,
1230}
1231
1232impl AuthMethodTerminal {
1233    /// Builds [`AuthMethodTerminal`] with the required fields set. Optional fields start unset or empty.
1234    #[must_use]
1235    pub fn new(method_id: impl Into<AuthMethodId>, name: impl Into<String>) -> Self {
1236        Self {
1237            method_id: method_id.into(),
1238            name: name.into(),
1239            description: None,
1240            args: Vec::new(),
1241            env: Vec::new(),
1242            meta: None,
1243        }
1244    }
1245
1246    /// Additional arguments to append to the configured Agent invocation for terminal auth.
1247    #[must_use]
1248    pub fn args(mut self, args: Vec<String>) -> Self {
1249        self.args = args;
1250        self
1251    }
1252
1253    /// Additional environment variables to set on the configured Agent invocation for terminal auth.
1254    /// Names SHOULD be unique, and otherwise the last entry wins. These values override
1255    /// same-named variables in the base launch configuration.
1256    #[must_use]
1257    pub fn env(mut self, env: Vec<EnvVariable>) -> Self {
1258        self.env = env;
1259        self
1260    }
1261
1262    /// Optional human-readable description of this authentication method.
1263    /// May contain Markdown.
1264    #[must_use]
1265    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
1266        self.description = description.into_option();
1267        self
1268    }
1269
1270    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1271    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1272    /// do not recognize.
1273    ///
1274    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1275    #[must_use]
1276    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1277        self.meta = meta.into_option();
1278        self
1279    }
1280}
1281
1282// New session
1283
1284/// Request parameters for creating a new session.
1285///
1286/// See protocol docs: [Creating a Session](https://agentclientprotocol.com/protocol/v2/session-setup#creating-a-session)
1287#[serde_as]
1288#[skip_serializing_none]
1289#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1290#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1291#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_NEW_METHOD_NAME)))]
1292#[serde(rename_all = "camelCase")]
1293#[non_exhaustive]
1294pub struct NewSessionRequest {
1295    /// The working directory for this session. Must be an absolute path.
1296    pub cwd: AbsolutePath,
1297    /// Additional workspace roots for this session. Each path MUST be absolute.
1298    ///
1299    /// These expand the session's workspace scope without changing `cwd`, which
1300    /// remains the base for relative paths. When omitted or empty, no
1301    /// additional roots are activated for the new session.
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 additional_directories: Vec<AbsolutePath>,
1306    /// List of MCP (Model Context Protocol) servers for the Agent to connect to.
1307    #[serde_as(deserialize_as = "DefaultOnNull")]
1308    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1309    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1310    pub mcp_servers: Vec<McpServer>,
1311    /// System-level instructions for the new session.
1312    ///
1313    /// Optional. Omitted and `null` are equivalent and mean the Agent uses its
1314    /// own default instructions. Clients MUST only send this when the Agent
1315    /// advertises `session.systemPrompt`.
1316    #[serde(default)]
1317    pub system_prompt: Option<SystemPrompt>,
1318    /// **UNSTABLE**
1319    ///
1320    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1321    ///
1322    /// Initial values for the session's config options.
1323    ///
1324    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1325    /// this when the Agent advertises `session.options`.
1326    ///
1327    /// The Agent applies the entries in list order, as if the Client had called
1328    /// `session/set_config_option` for each entry after the session was set up. Malformed
1329    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1330    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1331    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1332    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries,
1333    /// and SHOULD NOT send other `session/update` notifications caused by applying them
1334    /// before it responds.
1335    #[cfg(feature = "unstable_session_options")]
1336    #[serde_as(deserialize_as = "DefaultOnNull")]
1337    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1338    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1339    pub config_options: Vec<InitialSessionConfigOption>,
1340    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1341    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1342    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1343    ///
1344    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1345    #[serde_as(deserialize_as = "DefaultOnError")]
1346    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1347    #[serde(default)]
1348    #[serde(rename = "_meta")]
1349    pub meta: Option<Meta>,
1350}
1351
1352impl NewSessionRequest {
1353    /// Builds [`NewSessionRequest`] with the required request fields set. Optional fields start unset or empty.
1354    #[must_use]
1355    pub fn new(cwd: impl Into<AbsolutePath>) -> Self {
1356        Self {
1357            cwd: cwd.into(),
1358            additional_directories: vec![],
1359            mcp_servers: vec![],
1360            system_prompt: None,
1361            #[cfg(feature = "unstable_session_options")]
1362            config_options: vec![],
1363            meta: None,
1364        }
1365    }
1366
1367    /// Additional workspace roots for this session. Each path MUST be absolute.
1368    #[must_use]
1369    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1370    where
1371        I: IntoIterator<Item = P>,
1372        P: Into<AbsolutePath>,
1373    {
1374        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1375        self
1376    }
1377
1378    /// List of MCP (Model Context Protocol) servers for the Agent to connect to.
1379    #[must_use]
1380    pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1381        self.mcp_servers = mcp_servers;
1382        self
1383    }
1384
1385    /// System-level instructions for the new session.
1386    #[must_use]
1387    pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1388        self.system_prompt = system_prompt.into_option();
1389        self
1390    }
1391
1392    /// **UNSTABLE**
1393    ///
1394    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1395    ///
1396    /// Initial values for the session's config options.
1397    ///
1398    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1399    /// this when the Agent advertises `session.options`.
1400    ///
1401    /// The Agent applies the entries in list order, as if the Client had called
1402    /// `session/set_config_option` for each entry after the session was set up. Malformed
1403    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1404    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1405    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1406    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries,
1407    /// and SHOULD NOT send other `session/update` notifications caused by applying them
1408    /// before it responds.
1409    #[cfg(feature = "unstable_session_options")]
1410    #[must_use]
1411    pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1412        self.config_options = config_options;
1413        self
1414    }
1415
1416    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1417    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1418    /// do not recognize.
1419    ///
1420    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1421    #[must_use]
1422    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1423        self.meta = meta.into_option();
1424        self
1425    }
1426}
1427
1428/// Response from creating a new session.
1429///
1430/// New sessions default to `idle` until a state update reports otherwise.
1431/// Updates may arrive before or after this response. Clients MUST NOT overwrite
1432/// an already-reported state when the response arrives.
1433///
1434/// An Agent whose new session is not `idle` MUST send the session's
1435/// `state_update` after this response.
1436///
1437/// See protocol docs: [Creating a Session](https://agentclientprotocol.com/protocol/v2/session-setup#creating-a-session)
1438#[serde_as]
1439#[skip_serializing_none]
1440#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1441#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1442#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_NEW_METHOD_NAME)))]
1443#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}, {"action": "replace", "target": "availableCommands", "value": "availableCommands"}]})))]
1444#[serde(rename_all = "camelCase")]
1445#[non_exhaustive]
1446pub struct NewSessionResponse {
1447    /// Unique identifier for the created session.
1448    ///
1449    /// Used in all subsequent requests for this conversation.
1450    pub session_id: SessionId,
1451    /// Initial session configuration options.
1452    ///
1453    /// Optional. Omitted or empty means no config options are advertised.
1454    /// Senders MUST use an array, not `null`.
1455    /// Later `config_option_update` notifications replace this list.
1456    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1457    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1458    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1459    pub config_options: Vec<SessionConfigOption>,
1460    /// Initial commands the Agent can execute in this session.
1461    ///
1462    /// Optional. Omitted or empty means no initial commands are advertised.
1463    /// Senders MUST use an array, not `null`.
1464    /// Later `available_commands_update` notifications replace this list.
1465    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1466    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1467    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1468    pub available_commands: Vec<AvailableCommand>,
1469    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1470    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1471    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1472    ///
1473    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1474    #[serde_as(deserialize_as = "DefaultOnError")]
1475    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1476    #[serde(default)]
1477    #[serde(rename = "_meta")]
1478    pub meta: Option<Meta>,
1479}
1480
1481impl NewSessionResponse {
1482    /// Builds [`NewSessionResponse`] with the required response fields set. Optional fields start unset or empty.
1483    #[must_use]
1484    pub fn new(session_id: impl Into<SessionId>) -> Self {
1485        Self {
1486            session_id: session_id.into(),
1487            config_options: Vec::new(),
1488            available_commands: Vec::new(),
1489            meta: None,
1490        }
1491    }
1492
1493    /// Initial session configuration options.
1494    ///
1495    /// Optional. Omitted or empty means no config options are advertised.
1496    /// Senders MUST use an array, not `null`.
1497    /// Later `config_option_update` notifications replace this list.
1498    #[must_use]
1499    pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
1500        self.config_options = config_options;
1501        self
1502    }
1503
1504    /// Initial commands the Agent can execute in this session.
1505    #[must_use]
1506    pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
1507        self.available_commands = available_commands;
1508        self
1509    }
1510
1511    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1512    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1513    /// do not recognize.
1514    ///
1515    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1516    #[must_use]
1517    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1518        self.meta = meta.into_option();
1519        self
1520    }
1521}
1522
1523// Fork session
1524
1525/// **UNSTABLE**
1526///
1527/// This capability is not part of the spec yet, and may be removed or changed at any point.
1528///
1529/// Request parameters for forking an existing session.
1530///
1531/// Creates a new session based on the context of an existing one. The fork can be used
1532/// for operations like generating summaries without affecting the original session's history.
1533///
1534/// Only available if the Agent supports the `session.fork` capability.
1535#[cfg(feature = "unstable_session_fork")]
1536#[serde_as]
1537#[skip_serializing_none]
1538#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1539#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1540#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_FORK_METHOD_NAME)))]
1541#[serde(rename_all = "camelCase")]
1542#[non_exhaustive]
1543pub struct ForkSessionRequest {
1544    /// The ID of the session to fork.
1545    pub session_id: SessionId,
1546    /// **UNSTABLE**
1547    ///
1548    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1549    ///
1550    /// The session cursor to fork at. The new session's history is the source
1551    /// session's history before the cursor.
1552    ///
1553    /// Optional. Omitted and `null` are equivalent and fork the whole session.
1554    /// Clients MUST only send the ID of a cursor that the Agent announced on the
1555    /// source session and that currently advertises `capabilities.fork`. The Agent
1556    /// rejects any other ID with `-32602`. It does not fall back to forking the
1557    /// whole session.
1558    #[cfg(feature = "unstable_session_cursors")]
1559    #[serde(default)]
1560    pub cursor_id: Option<CursorId>,
1561    /// The working directory for this session. Must be an absolute path.
1562    pub cwd: AbsolutePath,
1563    /// Additional workspace roots to activate for this session. Each path MUST be absolute.
1564    ///
1565    /// When omitted or empty, no additional roots are activated. When non-empty,
1566    /// this is the complete resulting additional-root list for the forked
1567    /// 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 additional_directories: Vec<AbsolutePath>,
1572    /// List of MCP servers to connect to for this session.
1573    #[serde_as(deserialize_as = "DefaultOnNull")]
1574    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1575    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1576    pub mcp_servers: Vec<McpServer>,
1577    /// System-level instructions for the forked session.
1578    ///
1579    /// Optional. Omitted and `null` are equivalent. The Agent MAY then keep a
1580    /// system prompt it stored with the source session or use its default
1581    /// instructions. Clients MUST only send this when the Agent advertises
1582    /// `session.systemPrompt`, and SHOULD send the same value they used for the
1583    /// source session.
1584    #[serde(default)]
1585    pub system_prompt: Option<SystemPrompt>,
1586    /// **UNSTABLE**
1587    ///
1588    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1589    ///
1590    /// Initial values for the forked session's config options.
1591    ///
1592    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1593    /// this when the Agent advertises `session.options`.
1594    ///
1595    /// The Agent applies the entries in list order on top of the configuration the fork
1596    /// starts with, as if the Client had called `session/set_config_option` for each entry
1597    /// after the session was set up. Malformed entries and duplicate `configId` values fail
1598    /// the request with `-32602`. The Agent MUST ignore an entry whose `configId` is unknown,
1599    /// whose `type` does not match the option, or whose value is not allowed when it is
1600    /// applied. The `configOptions` in the response contain the values the session actually
1601    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries,
1602    /// and SHOULD NOT send other `session/update` notifications caused by applying them
1603    /// before it responds.
1604    #[cfg(feature = "unstable_session_options")]
1605    #[serde_as(deserialize_as = "DefaultOnNull")]
1606    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1607    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1608    pub config_options: Vec<InitialSessionConfigOption>,
1609    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1610    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1611    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1612    ///
1613    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1614    #[serde_as(deserialize_as = "DefaultOnError")]
1615    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1616    #[serde(default)]
1617    #[serde(rename = "_meta")]
1618    pub meta: Option<Meta>,
1619}
1620
1621#[cfg(feature = "unstable_session_fork")]
1622impl ForkSessionRequest {
1623    /// Builds [`ForkSessionRequest`] with the required request fields set. Optional fields start unset or empty.
1624    #[must_use]
1625    pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
1626        Self {
1627            session_id: session_id.into(),
1628            #[cfg(feature = "unstable_session_cursors")]
1629            cursor_id: None,
1630            cwd: cwd.into(),
1631            additional_directories: vec![],
1632            mcp_servers: vec![],
1633            system_prompt: None,
1634            #[cfg(feature = "unstable_session_options")]
1635            config_options: vec![],
1636            meta: None,
1637        }
1638    }
1639
1640    /// **UNSTABLE**
1641    ///
1642    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1643    ///
1644    /// The session cursor to fork at. Omitting it forks the whole session.
1645    ///
1646    /// Clients MUST only send the ID of a cursor that the Agent announced on the
1647    /// source session and that currently advertises `capabilities.fork`.
1648    #[cfg(feature = "unstable_session_cursors")]
1649    #[must_use]
1650    pub fn cursor_id(mut self, cursor_id: impl IntoOption<CursorId>) -> Self {
1651        self.cursor_id = cursor_id.into_option();
1652        self
1653    }
1654
1655    /// Additional workspace roots to activate for this session. Each path MUST be absolute.
1656    #[must_use]
1657    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1658    where
1659        I: IntoIterator<Item = P>,
1660        P: Into<AbsolutePath>,
1661    {
1662        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1663        self
1664    }
1665
1666    /// List of MCP servers to connect to for this session.
1667    #[must_use]
1668    pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1669        self.mcp_servers = mcp_servers;
1670        self
1671    }
1672
1673    /// System-level instructions for the forked session.
1674    #[must_use]
1675    pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1676        self.system_prompt = system_prompt.into_option();
1677        self
1678    }
1679
1680    /// **UNSTABLE**
1681    ///
1682    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1683    ///
1684    /// Initial values for the forked session's config options.
1685    ///
1686    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1687    /// this when the Agent advertises `session.options`.
1688    ///
1689    /// The Agent applies the entries in list order on top of the configuration the fork
1690    /// starts with, as if the Client had called `session/set_config_option` for each entry
1691    /// after the session was set up. Malformed entries and duplicate `configId` values fail
1692    /// the request with `-32602`. The Agent MUST ignore an entry whose `configId` is unknown,
1693    /// whose `type` does not match the option, or whose value is not allowed when it is
1694    /// applied. The `configOptions` in the response contain the values the session actually
1695    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries,
1696    /// and SHOULD NOT send other `session/update` notifications caused by applying them
1697    /// before it responds.
1698    #[cfg(feature = "unstable_session_options")]
1699    #[must_use]
1700    pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1701        self.config_options = config_options;
1702        self
1703    }
1704
1705    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1706    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1707    /// do not recognize.
1708    ///
1709    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1710    #[must_use]
1711    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1712        self.meta = meta.into_option();
1713        self
1714    }
1715}
1716
1717/// **UNSTABLE**
1718///
1719/// This capability is not part of the spec yet, and may be removed or changed at any point.
1720///
1721/// Response from forking an existing session.
1722#[cfg(feature = "unstable_session_fork")]
1723#[serde_as]
1724#[skip_serializing_none]
1725#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1726#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1727#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_FORK_METHOD_NAME)))]
1728#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}, {"action": "replace", "target": "availableCommands", "value": "availableCommands"}]})))]
1729#[serde(rename_all = "camelCase")]
1730#[non_exhaustive]
1731pub struct ForkSessionResponse {
1732    /// Unique identifier for the newly created forked session.
1733    pub session_id: SessionId,
1734    /// Initial session configuration options.
1735    ///
1736    /// Optional. Omitted or empty means no config options are advertised.
1737    /// Senders MUST use an array, not `null`.
1738    /// Later `config_option_update` notifications replace this list.
1739    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1740    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1741    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1742    pub config_options: Vec<SessionConfigOption>,
1743    /// Initial commands the Agent can execute in this session.
1744    ///
1745    /// Optional. Omitted or empty means no initial commands are advertised.
1746    /// Senders MUST use an array, not `null`.
1747    /// Later `available_commands_update` notifications replace this list.
1748    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1749    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1750    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1751    pub available_commands: Vec<AvailableCommand>,
1752    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1753    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1754    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1755    ///
1756    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1757    #[serde_as(deserialize_as = "DefaultOnError")]
1758    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1759    #[serde(default)]
1760    #[serde(rename = "_meta")]
1761    pub meta: Option<Meta>,
1762}
1763
1764#[cfg(feature = "unstable_session_fork")]
1765impl ForkSessionResponse {
1766    /// Builds [`ForkSessionResponse`] with the required response fields set. Optional fields start unset or empty.
1767    #[must_use]
1768    pub fn new(session_id: impl Into<SessionId>) -> Self {
1769        Self {
1770            session_id: session_id.into(),
1771            config_options: Vec::new(),
1772            available_commands: Vec::new(),
1773            meta: None,
1774        }
1775    }
1776
1777    /// Initial session configuration options.
1778    ///
1779    /// Optional. Omitted or empty means no config options are advertised.
1780    /// Senders MUST use an array, not `null`.
1781    /// Later `config_option_update` notifications replace this list.
1782    #[must_use]
1783    pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
1784        self.config_options = config_options;
1785        self
1786    }
1787
1788    /// Initial commands the Agent can execute in this session.
1789    #[must_use]
1790    pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
1791        self.available_commands = available_commands;
1792        self
1793    }
1794
1795    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1796    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1797    /// do not recognize.
1798    ///
1799    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1800    #[must_use]
1801    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1802        self.meta = meta.into_option();
1803        self
1804    }
1805}
1806
1807// Resume session
1808
1809/// Request parameters for resuming an existing session.
1810///
1811/// Resumes an existing session and optionally replays retained conversation
1812/// history according to `replayFrom`.
1813#[serde_as]
1814#[skip_serializing_none]
1815#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1816#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1817#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_RESUME_METHOD_NAME)))]
1818#[serde(rename_all = "camelCase")]
1819#[non_exhaustive]
1820pub struct ResumeSessionRequest {
1821    /// The ID of the session to resume.
1822    pub session_id: SessionId,
1823    /// The working directory for this session. Must be an absolute path.
1824    ///
1825    /// Clients MUST send the session's working directory. Agents MAY reject a different directory
1826    /// with `-32602`, and MAY normalize paths when comparing.
1827    pub cwd: AbsolutePath,
1828    /// Additional workspace roots to activate for this session. Each path MUST be absolute.
1829    ///
1830    /// When omitted or empty, no additional roots are activated. When non-empty,
1831    /// this is the complete resulting additional-root list for the resumed
1832    /// session. It MAY differ from any previously used or reported list as long as
1833    /// the request `cwd` matches the session's `cwd`.
1834    #[serde_as(deserialize_as = "DefaultOnNull")]
1835    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1836    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1837    pub additional_directories: Vec<AbsolutePath>,
1838    /// List of MCP servers to connect to for this session.
1839    ///
1840    /// The complete set of Client-provided servers. Omitted and `[]` mean none. Agents SHOULD
1841    /// NOT restore servers from earlier requests.
1842    #[serde_as(deserialize_as = "DefaultOnNull")]
1843    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1844    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1845    pub mcp_servers: Vec<McpServer>,
1846    /// Inclusive cursor describing where conversation replay begins.
1847    ///
1848    /// Optional. Omitted and `null` are equivalent, and the Agent MUST NOT replay
1849    /// previous conversation history. Replay cursors are inclusive:
1850    /// replay includes the position identified by the cursor. Supplying
1851    /// `{ "type": "start" }` means the Agent MUST replay all retained
1852    /// conversation history before responding.
1853    ///
1854    /// Agents MUST reject unsupported cursor types or malformed cursor values
1855    /// with `-32602` (Invalid params), rather than substituting another cursor
1856    /// or resuming without replay.
1857    #[serde(default)]
1858    pub replay_from: Option<ReplayFrom>,
1859    /// System-level instructions for the resumed session.
1860    ///
1861    /// Optional. Omitted and `null` are equivalent. The Agent MAY then keep a
1862    /// system prompt it stored with the session or use its default instructions.
1863    /// Clients MUST only send this when the Agent advertises
1864    /// `session.systemPrompt`, and SHOULD send the same value they used when the
1865    /// session was created.
1866    #[serde(default)]
1867    pub system_prompt: Option<SystemPrompt>,
1868    /// **UNSTABLE**
1869    ///
1870    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1871    ///
1872    /// Initial values for the session's config options.
1873    ///
1874    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1875    /// this when the Agent advertises `session.options`.
1876    ///
1877    /// The Agent applies the entries in list order, as if the Client had called
1878    /// `session/set_config_option` for each entry after the session was set up. Malformed
1879    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1880    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1881    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1882    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries
1883    /// on the requesting connection. If the session is active on other connections, the
1884    /// Agent SHOULD send `config_option_update` on those connections.
1885    ///
1886    /// The Agent applies the entries before it replays history for `replayFrom` and before
1887    /// it responds.
1888    #[cfg(feature = "unstable_session_options")]
1889    #[serde_as(deserialize_as = "DefaultOnNull")]
1890    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1891    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1892    pub config_options: Vec<InitialSessionConfigOption>,
1893    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1894    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1895    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1896    ///
1897    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1898    #[serde_as(deserialize_as = "DefaultOnError")]
1899    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1900    #[serde(default)]
1901    #[serde(rename = "_meta")]
1902    pub meta: Option<Meta>,
1903}
1904
1905impl ResumeSessionRequest {
1906    /// Builds [`ResumeSessionRequest`] with the required request fields set. Optional fields start unset or empty.
1907    #[must_use]
1908    pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
1909        Self {
1910            session_id: session_id.into(),
1911            cwd: cwd.into(),
1912            additional_directories: vec![],
1913            mcp_servers: vec![],
1914            replay_from: None,
1915            system_prompt: None,
1916            #[cfg(feature = "unstable_session_options")]
1917            config_options: vec![],
1918            meta: None,
1919        }
1920    }
1921
1922    /// Additional workspace roots to activate for this session. Each path MUST be absolute.
1923    #[must_use]
1924    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1925    where
1926        I: IntoIterator<Item = P>,
1927        P: Into<AbsolutePath>,
1928    {
1929        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1930        self
1931    }
1932
1933    /// List of MCP servers to connect to for this session.
1934    #[must_use]
1935    pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1936        self.mcp_servers = mcp_servers;
1937        self
1938    }
1939
1940    /// Inclusive cursor describing where conversation replay begins.
1941    ///
1942    /// Omitted and `null` are equivalent, and the Agent MUST NOT replay
1943    /// previous conversation history. Replay cursors are inclusive: replay
1944    /// includes the position identified by the cursor. Supplying
1945    /// `{ "type": "start" }` means the Agent MUST replay all retained
1946    /// conversation history before responding.
1947    #[must_use]
1948    pub fn replay_from(mut self, replay_from: impl IntoOption<ReplayFrom>) -> Self {
1949        self.replay_from = replay_from.into_option();
1950        self
1951    }
1952
1953    /// System-level instructions for the resumed session.
1954    #[must_use]
1955    pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1956        self.system_prompt = system_prompt.into_option();
1957        self
1958    }
1959
1960    /// **UNSTABLE**
1961    ///
1962    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1963    ///
1964    /// Initial values for the session's config options.
1965    ///
1966    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1967    /// this when the Agent advertises `session.options`.
1968    ///
1969    /// The Agent applies the entries in list order, as if the Client had called
1970    /// `session/set_config_option` for each entry after the session was set up. Malformed
1971    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1972    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1973    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1974    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries
1975    /// on the requesting connection. If the session is active on other connections, the
1976    /// Agent SHOULD send `config_option_update` on those connections.
1977    #[cfg(feature = "unstable_session_options")]
1978    #[must_use]
1979    pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1980        self.config_options = config_options;
1981        self
1982    }
1983
1984    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1985    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1986    /// do not recognize.
1987    ///
1988    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1989    #[must_use]
1990    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1991        self.meta = meta.into_option();
1992        self
1993    }
1994}
1995
1996/// Inclusive cursor describing where replayed session history begins.
1997///
1998/// Replay includes the position identified by the cursor.
1999#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2000#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2001#[serde(tag = "type", rename_all = "snake_case")]
2002#[non_exhaustive]
2003pub enum ReplayFrom {
2004    /// Replay all retained conversation history from its first replayable entry.
2005    Start(ReplayFromStart),
2006    /// Custom or future replay cursor.
2007    ///
2008    /// Values beginning with `_` are reserved for implementation-specific
2009    /// extensions. Unknown values that do not begin with `_` are reserved for
2010    /// future ACP variants.
2011    ///
2012    /// Intermediaries SHOULD preserve the raw payload when storing, replaying,
2013    /// proxying, or forwarding requests. Agents that do not support this cursor
2014    /// MUST reject the request with `-32602` (Invalid params), rather than
2015    /// substituting another cursor or resuming without replay.
2016    #[serde(untagged)]
2017    Other(OtherReplayFrom),
2018}
2019
2020impl From<ReplayFromStart> for ReplayFrom {
2021    fn from(replay_from: ReplayFromStart) -> Self {
2022        Self::Start(replay_from)
2023    }
2024}
2025
2026/// Inclusive replay cursor requesting replay from the start of retained conversation history.
2027#[serde_as]
2028#[skip_serializing_none]
2029#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2030#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2031#[serde(rename_all = "camelCase")]
2032#[non_exhaustive]
2033pub struct ReplayFromStart {
2034    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2035    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2036    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2037    ///
2038    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2039    #[serde_as(deserialize_as = "DefaultOnError")]
2040    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2041    #[serde(default)]
2042    #[serde(rename = "_meta")]
2043    pub meta: Option<Meta>,
2044}
2045
2046impl ReplayFromStart {
2047    /// Builds [`ReplayFromStart`].
2048    #[must_use]
2049    pub fn new() -> Self {
2050        Self::default()
2051    }
2052
2053    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2054    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2055    /// do not recognize.
2056    ///
2057    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2058    #[must_use]
2059    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2060        self.meta = meta.into_option();
2061        self
2062    }
2063}
2064
2065/// Custom or future replay cursor payload.
2066#[serde_as]
2067#[skip_serializing_none]
2068#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2069#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
2070#[cfg_attr(feature = "schemars", schemars(inline))]
2071#[cfg_attr(feature = "schemars", schemars(transform = other_replay_from_schema))]
2072#[serde(rename_all = "camelCase")]
2073#[non_exhaustive]
2074pub struct OtherReplayFrom {
2075    /// Custom or future replay cursor type.
2076    ///
2077    /// Values beginning with `_` are reserved for implementation-specific
2078    /// extensions. Unknown values that do not begin with `_` are reserved for
2079    /// future ACP variants.
2080    #[serde(rename = "type")]
2081    pub type_: String,
2082    /// The remaining fields of the unknown replay cursor payload, preserved verbatim,
2083    /// including `_meta`.
2084    #[serde(flatten)]
2085    pub fields: IndexMap<String, serde_json::Value>,
2086}
2087
2088impl OtherReplayFrom {
2089    /// Builds [`OtherReplayFrom`] from an unknown discriminator and preserves the remaining extension fields.
2090    #[must_use]
2091    pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
2092        fields.shift_remove("type");
2093        Self {
2094            type_: type_.into(),
2095            fields,
2096        }
2097    }
2098}
2099
2100impl<'de> Deserialize<'de> for OtherReplayFrom {
2101    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2102    where
2103        D: serde::Deserializer<'de>,
2104    {
2105        let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
2106        let type_ = fields
2107            .shift_remove("type")
2108            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
2109        let serde_json::Value::String(type_) = type_ else {
2110            return Err(serde::de::Error::custom("`type` must be a string"));
2111        };
2112
2113        if is_known_replay_from_type(&type_) {
2114            return Err(serde::de::Error::custom(format!(
2115                "known replay cursor `{type_}` did not match its schema"
2116            )));
2117        }
2118
2119        Ok(Self { type_, fields })
2120    }
2121}
2122
2123fn is_known_replay_from_type(type_: &str) -> bool {
2124    matches!(type_, "start")
2125}
2126
2127#[cfg(feature = "schemars")]
2128fn other_replay_from_schema(schema: &mut Schema) {
2129    super::schema_util::reject_known_string_discriminators(schema, "type", &["start"]);
2130}
2131
2132crate::serde_util::default_on_null! {
2133    /// Response from resuming an existing session.
2134    ///
2135    /// The Agent MUST send a current `state_update` after any requested history
2136    /// replay and before this response, even without replay. The update reports
2137    /// foreground state after resuming. The response alone does not imply `idle`.
2138    ///
2139    /// See protocol docs: [Current-State Synchronization](https://agentclientprotocol.com/protocol/v2/session-setup#current-state-synchronization)
2140    #[serde_as]
2141    #[skip_serializing_none]
2142    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2143    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2144    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_RESUME_METHOD_NAME)))]
2145    #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}, {"action": "replace", "target": "availableCommands", "value": "availableCommands"}]})))]
2146    #[serde(rename_all = "camelCase")]
2147    #[non_exhaustive]
2148    pub struct ResumeSessionResponse {
2149        /// Current session configuration options.
2150        ///
2151        /// Optional. Omitted or empty means no config options are advertised.
2152        /// Senders MUST use an array, not `null`.
2153        /// Later `config_option_update` notifications replace this list.
2154        #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2155        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2156        #[serde(default, skip_serializing_if = "Vec::is_empty")]
2157        pub config_options: Vec<SessionConfigOption>,
2158        /// Current commands the Agent can execute in this session.
2159        ///
2160        /// Optional. Omitted or empty means no initial commands are advertised.
2161        /// Senders MUST use an array, not `null`.
2162        /// Later `available_commands_update` notifications replace this list.
2163        #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2164        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2165        #[serde(default, skip_serializing_if = "Vec::is_empty")]
2166        pub available_commands: Vec<AvailableCommand>,
2167        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2168        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2169        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2170        ///
2171        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2172        #[serde_as(deserialize_as = "DefaultOnError")]
2173        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2174        #[serde(default)]
2175        #[serde(rename = "_meta")]
2176        pub meta: Option<Meta>,
2177    }
2178}
2179
2180impl ResumeSessionResponse {
2181    /// Builds [`ResumeSessionResponse`] with the required response fields set. Optional fields start unset or empty.
2182    #[must_use]
2183    pub fn new() -> Self {
2184        Self::default()
2185    }
2186
2187    /// Current session configuration options.
2188    ///
2189    /// Optional. Omitted or empty means no config options are advertised.
2190    /// Senders MUST use an array, not `null`.
2191    /// Later `config_option_update` notifications replace this list.
2192    #[must_use]
2193    pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
2194        self.config_options = config_options;
2195        self
2196    }
2197
2198    /// Current commands the Agent can execute in this session.
2199    #[must_use]
2200    pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
2201        self.available_commands = available_commands;
2202        self
2203    }
2204
2205    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2206    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2207    /// do not recognize.
2208    ///
2209    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2210    #[must_use]
2211    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2212        self.meta = meta.into_option();
2213        self
2214    }
2215}
2216
2217// Close session
2218
2219/// Request parameters for closing an active session.
2220///
2221/// The Agent MUST cancel any ongoing work related to the session as if `session/cancel`
2222/// was called, then free the resources associated with the session. Unlike `session/cancel`,
2223/// closing also stops the session's background work. After the close response, the Agent
2224/// sends no notifications or requests for the session on that connection. It still
2225/// answers `session/prompt` requests that were pending.
2226///
2227/// Closing a session that does not exist or is not active SHOULD succeed, and Clients SHOULD
2228/// treat a `-32002` response as a successful close.
2229///
2230/// When closing cancels active foreground work, the Agent MUST send the final
2231/// updates for that work and the idle `state_update` with `stopReason: "cancelled"`
2232/// before responding successfully to `session/close`. Closing an idle session
2233/// does not itself require another idle update.
2234///
2235/// Closing also cancels pending `session/prompt` requests whose messages have not
2236/// been inserted, including held prompts. If closing prevents a prompt's user message from being inserted, the
2237/// Agent MUST answer that request with `-32800` (Request cancelled). If the message
2238/// has already been inserted, the Agent MUST respond successfully with its
2239/// `messageId`. Prompt responses need not precede the close response.
2240#[serde_as]
2241#[skip_serializing_none]
2242#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2243#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2244#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CLOSE_METHOD_NAME)))]
2245#[serde(rename_all = "camelCase")]
2246#[non_exhaustive]
2247pub struct CloseSessionRequest {
2248    /// The ID of the session to close.
2249    pub session_id: SessionId,
2250    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2251    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2252    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2253    ///
2254    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2255    #[serde_as(deserialize_as = "DefaultOnError")]
2256    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2257    #[serde(default)]
2258    #[serde(rename = "_meta")]
2259    pub meta: Option<Meta>,
2260}
2261
2262impl CloseSessionRequest {
2263    /// Builds [`CloseSessionRequest`] with the required request fields set. Optional fields start unset or empty.
2264    #[must_use]
2265    pub fn new(session_id: impl Into<SessionId>) -> Self {
2266        Self {
2267            session_id: session_id.into(),
2268            meta: None,
2269        }
2270    }
2271
2272    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2273    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2274    /// do not recognize.
2275    ///
2276    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2277    #[must_use]
2278    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2279        self.meta = meta.into_option();
2280        self
2281    }
2282}
2283
2284crate::serde_util::default_on_null! {
2285    /// Response from closing a session.
2286    #[serde_as]
2287    #[skip_serializing_none]
2288    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2289    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2290    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CLOSE_METHOD_NAME)))]
2291    #[serde(rename_all = "camelCase")]
2292    #[non_exhaustive]
2293    pub struct CloseSessionResponse {
2294        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2295        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2296        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2297        ///
2298        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2299        #[serde_as(deserialize_as = "DefaultOnError")]
2300        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2301        #[serde(default)]
2302        #[serde(rename = "_meta")]
2303        pub meta: Option<Meta>,
2304    }
2305}
2306
2307impl CloseSessionResponse {
2308    /// Builds [`CloseSessionResponse`] with the required response fields set. Optional fields start unset or empty.
2309    #[must_use]
2310    pub fn new() -> Self {
2311        Self::default()
2312    }
2313
2314    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2315    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2316    /// do not recognize.
2317    ///
2318    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2319    #[must_use]
2320    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2321        self.meta = meta.into_option();
2322        self
2323    }
2324}
2325
2326// Session status
2327
2328/// **UNSTABLE**
2329///
2330/// This capability is not part of the spec yet, and may be removed or changed at any point.
2331///
2332/// Request parameters for checking the status of a session.
2333///
2334/// Only available if the Agent supports the `session.status` capability.
2335///
2336/// `session/status` MUST NOT have side effects. The Agent does not resume, create,
2337/// close, or change the session, and does not attach the requesting connection to it.
2338/// A session the Agent does not know gets `-32002` with the requested `sessionId` in `data`.
2339#[cfg(feature = "unstable_session_status")]
2340#[serde_as]
2341#[skip_serializing_none]
2342#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2343#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2344#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_STATUS_METHOD_NAME)))]
2345#[serde(rename_all = "camelCase")]
2346#[non_exhaustive]
2347pub struct SessionStatusRequest {
2348    /// The ID of the session to check.
2349    pub session_id: SessionId,
2350    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2351    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2352    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2353    ///
2354    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2355    #[serde_as(deserialize_as = "DefaultOnError")]
2356    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2357    #[serde(default)]
2358    #[serde(rename = "_meta")]
2359    pub meta: Option<Meta>,
2360}
2361
2362#[cfg(feature = "unstable_session_status")]
2363impl SessionStatusRequest {
2364    /// Builds [`SessionStatusRequest`] with the required request fields set. Optional fields start unset or empty.
2365    #[must_use]
2366    pub fn new(session_id: impl Into<SessionId>) -> Self {
2367        Self {
2368            session_id: session_id.into(),
2369            meta: None,
2370        }
2371    }
2372
2373    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2374    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2375    /// do not recognize.
2376    ///
2377    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2378    #[must_use]
2379    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2380        self.meta = meta.into_option();
2381        self
2382    }
2383}
2384
2385/// **UNSTABLE**
2386///
2387/// This capability is not part of the spec yet, and may be removed or changed at any point.
2388///
2389/// Response from checking the status of a session.
2390///
2391/// The result is a snapshot. A session reported `open` may be closed or evicted before
2392/// the Client's next request.
2393#[cfg(feature = "unstable_session_status")]
2394#[serde_as]
2395#[skip_serializing_none]
2396#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2397#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2398#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_STATUS_METHOD_NAME)))]
2399#[serde(rename_all = "camelCase")]
2400#[non_exhaustive]
2401pub struct SessionStatusResponse {
2402    /// Whether the Agent has the session in memory.
2403    ///
2404    /// Required. Clients MUST treat a value they do not recognize as `saved`.
2405    pub status: SessionStatus,
2406    /// The session's current foreground state, as the same snapshot the Agent sends in
2407    /// `state_update` notifications.
2408    ///
2409    /// Optional. Agents SHOULD include it when `status` is `open`. Omitted and `null`
2410    /// mean the Agent is not reporting foreground state, and Clients
2411    /// MUST NOT read that as `idle`. This is a snapshot, not a new transition. Clients
2412    /// MUST NOT count an `idle` snapshot as a new completion.
2413    #[serde_as(deserialize_as = "DefaultOnError")]
2414    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2415    #[serde(default)]
2416    pub state: Option<StateUpdate>,
2417    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2418    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2419    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2420    ///
2421    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2422    #[serde_as(deserialize_as = "DefaultOnError")]
2423    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2424    #[serde(default)]
2425    #[serde(rename = "_meta")]
2426    pub meta: Option<Meta>,
2427}
2428
2429#[cfg(feature = "unstable_session_status")]
2430impl SessionStatusResponse {
2431    /// Builds [`SessionStatusResponse`] with the required response fields set. Optional fields start unset or empty.
2432    #[must_use]
2433    pub fn new(status: SessionStatus) -> Self {
2434        Self {
2435            status,
2436            state: None,
2437            meta: None,
2438        }
2439    }
2440
2441    /// The session's current foreground state, as the same snapshot the Agent sends in
2442    /// `state_update` notifications.
2443    #[must_use]
2444    pub fn state(mut self, state: impl IntoOption<StateUpdate>) -> Self {
2445        self.state = state.into_option();
2446        self
2447    }
2448
2449    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2450    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2451    /// do not recognize.
2452    ///
2453    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2454    #[must_use]
2455    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2456        self.meta = meta.into_option();
2457        self
2458    }
2459}
2460
2461/// **UNSTABLE**
2462///
2463/// This capability is not part of the spec yet, and may be removed or changed at any point.
2464///
2465/// Whether the Agent has a session in memory, as reported by `session/status`.
2466#[cfg(feature = "unstable_session_status")]
2467#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2468#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2469#[serde(rename_all = "snake_case")]
2470#[non_exhaustive]
2471pub enum SessionStatus {
2472    /// The Agent has the session in memory, for any connection.
2473    ///
2474    /// This does not mean the requesting connection is attached to it. A Client that did
2475    /// not create or resume the session on its own connection MUST still call
2476    /// `session/resume` before sending `session/prompt` or expecting
2477    /// `session/update` notifications.
2478    Open,
2479    /// The Agent knows the session and can resume it, but does not have it in memory.
2480    ///
2481    /// The Client can call `session/resume` to start it.
2482    Saved,
2483    /// Custom or future session status.
2484    ///
2485    /// Values beginning with `_` are reserved for implementation-specific
2486    /// extensions. Unknown values that do not begin with `_` are reserved for
2487    /// future ACP variants. Clients MUST treat a value they do not recognize as
2488    /// `saved`.
2489    #[serde(untagged)]
2490    Other(String),
2491}
2492
2493/// **UNSTABLE**
2494///
2495/// This capability is not part of the spec yet, and may be removed or changed at any point.
2496///
2497/// Request parameters for `session/options`, which returns the config options a session
2498/// would start with, without creating or resuming a session.
2499///
2500/// Only available if the Agent supports the `session.options` capability.
2501///
2502/// `session/options` MUST NOT create or resume a session, send `session/update`
2503/// notifications, add an entry to `session/list`, or change an existing session. Agents
2504/// SHOULD NOT connect to MCP servers to answer it. Agents MAY start their runtime to resolve
2505/// the options. The rules above still hold for it.
2506#[cfg(feature = "unstable_session_options")]
2507#[serde_as]
2508#[skip_serializing_none]
2509#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2510#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2511#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_OPTIONS_METHOD_NAME)))]
2512#[serde(rename_all = "camelCase")]
2513#[non_exhaustive]
2514pub struct SessionOptionsRequest {
2515    /// The working directory to resolve options for. Must be an absolute path.
2516    pub cwd: AbsolutePath,
2517    /// Additional workspace roots to resolve options for. Each path MUST be absolute.
2518    ///
2519    /// Optional. Omitted and `null` are equivalent to an empty list.
2520    #[serde_as(deserialize_as = "DefaultOnNull")]
2521    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
2522    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2523    pub additional_directories: Vec<AbsolutePath>,
2524    /// The session to resolve options for.
2525    ///
2526    /// Optional. Omitted and `null` are equivalent and mean a new session. When present,
2527    /// the Agent returns what `session/resume` with the same `cwd` and
2528    /// `additionalDirectories` would return, with the same `cwd` rules. A session the
2529    /// Agent does not know gets `-32002`.
2530    #[serde(default)]
2531    pub session_id: Option<SessionId>,
2532    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2533    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2534    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2535    ///
2536    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2537    #[serde_as(deserialize_as = "DefaultOnError")]
2538    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2539    #[serde(default)]
2540    #[serde(rename = "_meta")]
2541    pub meta: Option<Meta>,
2542}
2543
2544#[cfg(feature = "unstable_session_options")]
2545impl SessionOptionsRequest {
2546    /// Builds [`SessionOptionsRequest`] with the required request fields set. Optional fields start unset or empty.
2547    #[must_use]
2548    pub fn new(cwd: impl Into<AbsolutePath>) -> Self {
2549        Self {
2550            cwd: cwd.into(),
2551            additional_directories: vec![],
2552            session_id: None,
2553            meta: None,
2554        }
2555    }
2556
2557    /// Additional workspace roots to resolve options for. Each path MUST be absolute.
2558    #[must_use]
2559    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
2560    where
2561        I: IntoIterator<Item = P>,
2562        P: Into<AbsolutePath>,
2563    {
2564        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
2565        self
2566    }
2567
2568    /// The session to resolve options for. Unset means a new session.
2569    #[must_use]
2570    pub fn session_id(mut self, session_id: impl IntoOption<SessionId>) -> Self {
2571        self.session_id = session_id.into_option();
2572        self
2573    }
2574
2575    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2576    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2577    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2578    ///
2579    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2580    #[must_use]
2581    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2582        self.meta = meta.into_option();
2583        self
2584    }
2585}
2586
2587#[cfg(feature = "unstable_session_options")]
2588crate::serde_util::default_on_null! {
2589    /// **UNSTABLE**
2590    ///
2591    /// This capability is not part of the spec yet, and may be removed or changed at any point.
2592    ///
2593    /// Response from `session/options`.
2594    ///
2595    /// The result is a snapshot. The options a session actually starts with are the ones in
2596    /// the session setup response.
2597    #[serde_as]
2598    #[skip_serializing_none]
2599    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2600    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2601    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_OPTIONS_METHOD_NAME)))]
2602    #[serde(rename_all = "camelCase")]
2603    #[non_exhaustive]
2604    pub struct SessionOptionsResponse {
2605        /// The config options the session would start with, with the same rules as on
2606        /// `NewSessionResponse`.
2607        ///
2608        /// Optional. Omitted or empty means no config options are advertised.
2609        /// Senders MUST use an array, not `null`.
2610        #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2611        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2612        #[serde(default, skip_serializing_if = "Vec::is_empty")]
2613        pub config_options: Vec<SessionConfigOption>,
2614        /// Commands the Agent knows the session would have.
2615        ///
2616        /// Optional. Omitted or empty means no commands are advertised.
2617        /// Senders MUST use an array, not `null`.
2618        ///
2619        /// Advisory. Agents MAY return a partial list. Clients MUST use the commands from the
2620        /// `session/new` or `session/resume` response and later `available_commands_update`
2621        /// notifications for the session itself.
2622        #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2623        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2624        #[serde(default, skip_serializing_if = "Vec::is_empty")]
2625        pub available_commands: Vec<AvailableCommand>,
2626        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2627        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2628        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2629        ///
2630        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2631        #[serde_as(deserialize_as = "DefaultOnError")]
2632        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2633        #[serde(default)]
2634        #[serde(rename = "_meta")]
2635        pub meta: Option<Meta>,
2636    }
2637}
2638
2639#[cfg(feature = "unstable_session_options")]
2640impl SessionOptionsResponse {
2641    /// Builds [`SessionOptionsResponse`] with the required response fields set. Optional fields start unset or empty.
2642    #[must_use]
2643    pub fn new() -> Self {
2644        Self::default()
2645    }
2646
2647    /// The config options the session would start with.
2648    #[must_use]
2649    pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
2650        self.config_options = config_options;
2651        self
2652    }
2653
2654    /// Commands the Agent knows the session would have. Advisory.
2655    #[must_use]
2656    pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
2657        self.available_commands = available_commands;
2658        self
2659    }
2660
2661    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2662    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2663    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2664    ///
2665    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2666    #[must_use]
2667    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2668        self.meta = meta.into_option();
2669        self
2670    }
2671}
2672
2673/// **UNSTABLE**
2674///
2675/// This capability is not part of the spec yet, and may be removed or changed at any point.
2676///
2677/// An initial value for a config option, sent on session setup requests.
2678///
2679/// Same shape as `session/set_config_option` without `sessionId`. Unlike
2680/// `session/set_config_option`, an unknown `configId`, a `type` that does not match the
2681/// option, or a value that is not allowed is ignored instead of rejected.
2682#[cfg(feature = "unstable_session_options")]
2683#[serde_as]
2684#[skip_serializing_none]
2685#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2686#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2687#[serde(rename_all = "camelCase")]
2688#[non_exhaustive]
2689pub struct InitialSessionConfigOption {
2690    /// The ID of the configuration option to set.
2691    pub config_id: SessionConfigId,
2692    /// The value to set, including a `type` discriminator and the raw `value`.
2693    ///
2694    /// Payloads MUST send `type: "id"` for id-based options. A value `type` the Agent
2695    /// does not support fails the request with `-32602`.
2696    #[serde(flatten)]
2697    pub value: SessionConfigOptionValue,
2698    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2699    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2700    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2701    ///
2702    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2703    #[serde_as(deserialize_as = "DefaultOnError")]
2704    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2705    #[serde(default)]
2706    #[serde(rename = "_meta")]
2707    pub meta: Option<Meta>,
2708}
2709
2710#[cfg(feature = "unstable_session_options")]
2711impl InitialSessionConfigOption {
2712    /// Builds [`InitialSessionConfigOption`] with the required fields set. Optional fields start unset or empty.
2713    #[must_use]
2714    pub fn new(
2715        config_id: impl Into<SessionConfigId>,
2716        value: impl Into<SessionConfigOptionValue>,
2717    ) -> Self {
2718        Self {
2719            config_id: config_id.into(),
2720            value: value.into(),
2721            meta: None,
2722        }
2723    }
2724
2725    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2726    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2727    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2728    ///
2729    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2730    #[must_use]
2731    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2732        self.meta = meta.into_option();
2733        self
2734    }
2735}
2736
2737// Cancel tool call
2738
2739/// Request parameters for cancelling one tool call.
2740///
2741/// Clients MUST NOT send it unless the tool call currently advertises `capabilities.cancel`.
2742///
2743/// The Agent responds once it has accepted the cancellation. The response does not mean
2744/// the work has stopped. The Agent confirms it with a `tool_call_update` to a final
2745/// status: normally `cancelled`, or `completed` or `failed` if the work finished first.
2746///
2747/// The Agent responds with `-32602` if the tool call is unknown, already final, or not
2748/// cancellable. Cancelling a tool call does not change the foreground state by itself.
2749///
2750/// See protocol docs: [Cancelling Tool Calls](https://agentclientprotocol.com/protocol/v2/tool-calls#cancelling-tool-calls)
2751#[serde_as]
2752#[skip_serializing_none]
2753#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2754#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2755#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TOOL_CALL_CANCEL_METHOD_NAME)))]
2756#[serde(rename_all = "camelCase")]
2757#[non_exhaustive]
2758pub struct CancelToolCallRequest {
2759    /// The ID of the session that owns the tool call.
2760    pub session_id: SessionId,
2761    /// The ID of the tool call to cancel.
2762    pub tool_call_id: ToolCallId,
2763    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2764    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2765    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2766    ///
2767    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2768    #[serde_as(deserialize_as = "DefaultOnError")]
2769    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2770    #[serde(default)]
2771    #[serde(rename = "_meta")]
2772    pub meta: Option<Meta>,
2773}
2774
2775impl CancelToolCallRequest {
2776    /// Builds [`CancelToolCallRequest`] with the required request fields set. Optional fields start unset or empty.
2777    #[must_use]
2778    pub fn new(session_id: impl Into<SessionId>, tool_call_id: impl Into<ToolCallId>) -> Self {
2779        Self {
2780            session_id: session_id.into(),
2781            tool_call_id: tool_call_id.into(),
2782            meta: None,
2783        }
2784    }
2785
2786    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2787    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2788    /// do not recognize.
2789    ///
2790    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2791    #[must_use]
2792    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2793        self.meta = meta.into_option();
2794        self
2795    }
2796}
2797
2798crate::serde_util::default_on_null! {
2799    /// Response from cancelling a tool call.
2800    #[serde_as]
2801    #[skip_serializing_none]
2802    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2803    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2804    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TOOL_CALL_CANCEL_METHOD_NAME)))]
2805    #[serde(rename_all = "camelCase")]
2806    #[non_exhaustive]
2807    pub struct CancelToolCallResponse {
2808        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2809        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2810        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2811        ///
2812        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2813        #[serde_as(deserialize_as = "DefaultOnError")]
2814        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2815        #[serde(default)]
2816        #[serde(rename = "_meta")]
2817        pub meta: Option<Meta>,
2818    }
2819}
2820
2821impl CancelToolCallResponse {
2822    /// Builds [`CancelToolCallResponse`] with the required response fields set. Optional fields start unset or empty.
2823    #[must_use]
2824    pub fn new() -> Self {
2825        Self::default()
2826    }
2827
2828    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2829    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2830    /// do not recognize.
2831    ///
2832    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2833    #[must_use]
2834    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2835        self.meta = meta.into_option();
2836        self
2837    }
2838}
2839
2840// Cancel terminal
2841
2842/// Request parameters for cancelling one terminal.
2843///
2844/// Clients MUST NOT send it unless the terminal currently advertises `capabilities.cancel`.
2845///
2846/// The Agent responds once it has accepted the cancellation. The response does not mean
2847/// the work has stopped. The Agent confirms it with a `terminal_update` that sets
2848/// `exitStatus`. Cancelling stops the process but does not release the terminal, and does
2849/// not change the status of a tool call that references it.
2850///
2851/// The Agent responds with `-32602` if the terminal is unknown, has already exited, or is not
2852/// cancellable. Cancelling a terminal does not change the foreground state by itself.
2853///
2854/// See protocol docs: [Cancelling Terminals](https://agentclientprotocol.com/protocol/v2/tool-calls#cancelling-terminals)
2855#[serde_as]
2856#[skip_serializing_none]
2857#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2858#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2859#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TERMINAL_CANCEL_METHOD_NAME)))]
2860#[serde(rename_all = "camelCase")]
2861#[non_exhaustive]
2862pub struct CancelTerminalRequest {
2863    /// The ID of the session that owns the terminal.
2864    pub session_id: SessionId,
2865    /// The ID of the terminal to cancel.
2866    pub terminal_id: TerminalId,
2867    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2868    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2869    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2870    ///
2871    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2872    #[serde_as(deserialize_as = "DefaultOnError")]
2873    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2874    #[serde(default)]
2875    #[serde(rename = "_meta")]
2876    pub meta: Option<Meta>,
2877}
2878
2879impl CancelTerminalRequest {
2880    /// Builds [`CancelTerminalRequest`] with the required request fields set. Optional fields start unset or empty.
2881    #[must_use]
2882    pub fn new(session_id: impl Into<SessionId>, terminal_id: impl Into<TerminalId>) -> Self {
2883        Self {
2884            session_id: session_id.into(),
2885            terminal_id: terminal_id.into(),
2886            meta: None,
2887        }
2888    }
2889
2890    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2891    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2892    /// do not recognize.
2893    ///
2894    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2895    #[must_use]
2896    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2897        self.meta = meta.into_option();
2898        self
2899    }
2900}
2901
2902crate::serde_util::default_on_null! {
2903    /// Response from cancelling a terminal.
2904    #[serde_as]
2905    #[skip_serializing_none]
2906    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2907    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2908    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TERMINAL_CANCEL_METHOD_NAME)))]
2909    #[serde(rename_all = "camelCase")]
2910    #[non_exhaustive]
2911    pub struct CancelTerminalResponse {
2912        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2913        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2914        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2915        ///
2916        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2917        #[serde_as(deserialize_as = "DefaultOnError")]
2918        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2919        #[serde(default)]
2920        #[serde(rename = "_meta")]
2921        pub meta: Option<Meta>,
2922    }
2923}
2924
2925impl CancelTerminalResponse {
2926    /// Builds [`CancelTerminalResponse`] with the required response fields set. Optional fields start unset or empty.
2927    #[must_use]
2928    pub fn new() -> Self {
2929        Self::default()
2930    }
2931
2932    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2933    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2934    /// do not recognize.
2935    ///
2936    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2937    #[must_use]
2938    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2939        self.meta = meta.into_option();
2940        self
2941    }
2942}
2943
2944// List sessions
2945
2946/// An opaque cursor used to paginate `session/list` results.
2947#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2948#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
2949#[serde(transparent)]
2950#[from(Arc<str>, String, &str, &mut str, Box<str>, Cow<'_, str>)]
2951#[non_exhaustive]
2952pub struct SessionListCursor(pub Arc<str>);
2953
2954impl SessionListCursor {
2955    /// Wraps a protocol string as a typed [`SessionListCursor`].
2956    #[must_use]
2957    pub fn new(cursor: impl Into<Self>) -> Self {
2958        cursor.into()
2959    }
2960}
2961
2962impl AsRef<str> for SessionListCursor {
2963    fn as_ref(&self) -> &str {
2964        &self.0
2965    }
2966}
2967
2968impl From<&String> for SessionListCursor {
2969    fn from(cursor: &String) -> Self {
2970        Self(cursor.as_str().into())
2971    }
2972}
2973
2974macro_rules! impl_session_list_cursor_option_conversion {
2975    ($source:ty) => {
2976        impl IntoOption<SessionListCursor> for $source {
2977            fn into_option(self) -> Option<SessionListCursor> {
2978                Some(self.into())
2979            }
2980        }
2981    };
2982}
2983
2984impl_session_list_cursor_option_conversion!(Arc<str>);
2985impl_session_list_cursor_option_conversion!(String);
2986impl_session_list_cursor_option_conversion!(&str);
2987impl_session_list_cursor_option_conversion!(&mut str);
2988impl_session_list_cursor_option_conversion!(&String);
2989impl_session_list_cursor_option_conversion!(Box<str>);
2990impl_session_list_cursor_option_conversion!(Cow<'_, str>);
2991
2992crate::serde_util::default_on_null! {
2993    /// Request parameters for listing existing sessions.
2994    #[serde_as]
2995    #[skip_serializing_none]
2996    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2997    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2998    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LIST_METHOD_NAME)))]
2999    #[serde(rename_all = "camelCase")]
3000    #[non_exhaustive]
3001    pub struct ListSessionsRequest {
3002        /// Filter sessions by working directory. Must be an absolute path.
3003        ///
3004        /// Only sessions whose `cwd` is this same directory match. Subdirectories and
3005        /// `additionalDirectories` don't. Agents MAY normalize paths when comparing.
3006        ///
3007        /// Omitted and `null` are equivalent and mean sessions are not filtered by working directory.
3008        /// Clients keep the same value when following `nextCursor`.
3009        #[serde(default)]
3010        pub cwd: Option<AbsolutePath>,
3011        /// Opaque cursor token from a previous response's nextCursor field for cursor-based pagination
3012        ///
3013        /// Omitted and `null` are equivalent and mean the first page is requested.
3014        #[serde(default)]
3015        pub cursor: Option<SessionListCursor>,
3016        /// **UNSTABLE**
3017        ///
3018        /// This capability is not part of the spec yet, and may be removed or changed at any point.
3019        ///
3020        /// Filter sessions by archive state.
3021        ///
3022        /// Optional. Omitted and `null` are equivalent and mean `exclude`. Only send this when
3023        /// the Agent advertises the `session.archive` capability. The filter combines with `cwd` and
3024        /// applies before pagination. Clients keep the same value when following `nextCursor`.
3025        #[cfg(feature = "unstable_session_archive")]
3026        #[serde(default)]
3027        pub archived: Option<SessionArchiveFilter>,
3028        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3029        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3030        /// Implementations MUST NOT assign meaning to keys they do not recognize.
3031        ///
3032        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3033        #[serde_as(deserialize_as = "DefaultOnError")]
3034        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3035        #[serde(default)]
3036        #[serde(rename = "_meta")]
3037        pub meta: Option<Meta>,
3038    }
3039}
3040
3041impl ListSessionsRequest {
3042    /// Builds [`ListSessionsRequest`] with the required request fields set. Optional fields start unset or empty.
3043    #[must_use]
3044    pub fn new() -> Self {
3045        Self::default()
3046    }
3047
3048    /// Filter sessions by working directory. Must be an absolute path.
3049    #[must_use]
3050    pub fn cwd(mut self, cwd: impl IntoOption<AbsolutePath>) -> Self {
3051        self.cwd = cwd.into_option();
3052        self
3053    }
3054
3055    /// Opaque cursor token from a previous response's nextCursor field for cursor-based pagination
3056    #[must_use]
3057    pub fn cursor(mut self, cursor: impl IntoOption<SessionListCursor>) -> Self {
3058        self.cursor = cursor.into_option();
3059        self
3060    }
3061
3062    /// **UNSTABLE**
3063    ///
3064    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3065    ///
3066    /// Filter sessions by archive state.
3067    #[cfg(feature = "unstable_session_archive")]
3068    #[must_use]
3069    pub fn archived(mut self, archived: impl IntoOption<SessionArchiveFilter>) -> Self {
3070        self.archived = archived.into_option();
3071        self
3072    }
3073
3074    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3075    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3076    /// do not recognize.
3077    ///
3078    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3079    #[must_use]
3080    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3081        self.meta = meta.into_option();
3082        self
3083    }
3084}
3085
3086/// Response from listing sessions.
3087#[serde_as]
3088#[skip_serializing_none]
3089#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3090#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3091#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LIST_METHOD_NAME)))]
3092#[serde(rename_all = "camelCase")]
3093#[non_exhaustive]
3094pub struct ListSessionsResponse {
3095    /// Array of session information objects.
3096    ///
3097    /// Agents SHOULD return the sessions with the most recent activity first.
3098    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
3099    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3100    pub sessions: Vec<SessionInfo>,
3101    /// Opaque cursor token. If present, pass this in the next request's cursor parameter
3102    /// to fetch the next page. Omitted and `null` are equivalent and mean there are no more
3103    /// results. An empty string is a valid cursor, not the end of results.
3104    #[serde(default)]
3105    pub next_cursor: Option<SessionListCursor>,
3106    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3107    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3108    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3109    ///
3110    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3111    #[serde_as(deserialize_as = "DefaultOnError")]
3112    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3113    #[serde(default)]
3114    #[serde(rename = "_meta")]
3115    pub meta: Option<Meta>,
3116}
3117
3118impl ListSessionsResponse {
3119    /// Builds [`ListSessionsResponse`] with the required response fields set. Optional fields start unset or empty.
3120    #[must_use]
3121    pub fn new(sessions: Vec<SessionInfo>) -> Self {
3122        Self {
3123            sessions,
3124            next_cursor: None,
3125            meta: None,
3126        }
3127    }
3128
3129    /// Sets or clears the optional `nextCursor` field.
3130    #[must_use]
3131    pub fn next_cursor(mut self, next_cursor: impl IntoOption<SessionListCursor>) -> Self {
3132        self.next_cursor = next_cursor.into_option();
3133        self
3134    }
3135
3136    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3137    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3138    /// do not recognize.
3139    ///
3140    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3141    #[must_use]
3142    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3143        self.meta = meta.into_option();
3144        self
3145    }
3146}
3147
3148// Delete session
3149
3150/// Request parameters for deleting an existing session from `session/list`.
3151///
3152/// Only available if the Agent supports the `session.delete` capability.
3153#[serde_as]
3154#[skip_serializing_none]
3155#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3156#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3157#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_DELETE_METHOD_NAME)))]
3158#[serde(rename_all = "camelCase")]
3159#[non_exhaustive]
3160pub struct DeleteSessionRequest {
3161    /// The ID of the session to delete.
3162    pub session_id: SessionId,
3163    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3164    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3165    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3166    ///
3167    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3168    #[serde_as(deserialize_as = "DefaultOnError")]
3169    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3170    #[serde(default)]
3171    #[serde(rename = "_meta")]
3172    pub meta: Option<Meta>,
3173}
3174
3175impl DeleteSessionRequest {
3176    /// Builds [`DeleteSessionRequest`] with the required request fields set. Optional fields start unset or empty.
3177    #[must_use]
3178    pub fn new(session_id: impl Into<SessionId>) -> Self {
3179        Self {
3180            session_id: session_id.into(),
3181            meta: None,
3182        }
3183    }
3184
3185    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3186    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3187    /// do not recognize.
3188    ///
3189    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3190    #[must_use]
3191    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3192        self.meta = meta.into_option();
3193        self
3194    }
3195}
3196
3197crate::serde_util::default_on_null! {
3198    /// Response from deleting a session.
3199    #[serde_as]
3200    #[skip_serializing_none]
3201    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3202    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3203    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_DELETE_METHOD_NAME)))]
3204    #[serde(rename_all = "camelCase")]
3205    #[non_exhaustive]
3206    pub struct DeleteSessionResponse {
3207        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3208        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3209        /// Implementations MUST NOT assign meaning to keys they do not recognize.
3210        ///
3211        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3212        #[serde_as(deserialize_as = "DefaultOnError")]
3213        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3214        #[serde(default)]
3215        #[serde(rename = "_meta")]
3216        pub meta: Option<Meta>,
3217    }
3218}
3219
3220impl DeleteSessionResponse {
3221    /// Builds [`DeleteSessionResponse`] with the required response fields set. Optional fields start unset or empty.
3222    #[must_use]
3223    pub fn new() -> Self {
3224        Self::default()
3225    }
3226
3227    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3228    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3229    /// do not recognize.
3230    ///
3231    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3232    #[must_use]
3233    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3234        self.meta = meta.into_option();
3235        self
3236    }
3237}
3238
3239// Archive session
3240
3241/// **UNSTABLE**
3242///
3243/// This capability is not part of the spec yet, and may be removed or changed at any point.
3244///
3245/// Request parameters for archiving a session.
3246///
3247/// Only available if the Agent supports the `session.archive` capability.
3248///
3249/// Archiving hides the session from default `session/list` results. It keeps the session ID
3250/// and saved history. If the session is active, the Agent MUST cancel any ongoing work and
3251/// free the session's resources as if `session/close` had been called, then archive it.
3252/// Archiving an archived session succeeds. A session that does not exist gets `-32002`.
3253///
3254#[cfg(feature = "unstable_session_archive")]
3255#[serde_as]
3256#[skip_serializing_none]
3257#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3258#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3259#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_ARCHIVE_METHOD_NAME)))]
3260#[serde(rename_all = "camelCase")]
3261#[non_exhaustive]
3262pub struct ArchiveSessionRequest {
3263    /// The ID of the session to archive.
3264    pub session_id: SessionId,
3265    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3266    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3267    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3268    ///
3269    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3270    #[serde_as(deserialize_as = "DefaultOnError")]
3271    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3272    #[serde(default)]
3273    #[serde(rename = "_meta")]
3274    pub meta: Option<Meta>,
3275}
3276
3277#[cfg(feature = "unstable_session_archive")]
3278impl ArchiveSessionRequest {
3279    /// Builds [`ArchiveSessionRequest`] with the required request fields set. Optional fields start unset or empty.
3280    #[must_use]
3281    pub fn new(session_id: impl Into<SessionId>) -> Self {
3282        Self {
3283            session_id: session_id.into(),
3284            meta: None,
3285        }
3286    }
3287
3288    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3289    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3290    /// do not recognize.
3291    ///
3292    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3293    #[must_use]
3294    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3295        self.meta = meta.into_option();
3296        self
3297    }
3298}
3299
3300#[cfg(feature = "unstable_session_archive")]
3301crate::serde_util::default_on_null! {
3302    /// **UNSTABLE**
3303    ///
3304    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3305    ///
3306    /// Response from archiving a session.
3307    #[serde_as]
3308    #[skip_serializing_none]
3309    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3310    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3311    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_ARCHIVE_METHOD_NAME)))]
3312    #[serde(rename_all = "camelCase")]
3313    #[non_exhaustive]
3314    pub struct ArchiveSessionResponse {
3315        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3316        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3317        /// Implementations MUST NOT assign meaning to keys they do not recognize.
3318        ///
3319        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3320        #[serde_as(deserialize_as = "DefaultOnError")]
3321        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3322        #[serde(default)]
3323        #[serde(rename = "_meta")]
3324        pub meta: Option<Meta>,
3325    }
3326}
3327
3328#[cfg(feature = "unstable_session_archive")]
3329impl ArchiveSessionResponse {
3330    /// Builds [`ArchiveSessionResponse`] with the required response fields set. Optional fields start unset or empty.
3331    #[must_use]
3332    pub fn new() -> Self {
3333        Self::default()
3334    }
3335
3336    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3337    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3338    /// do not recognize.
3339    ///
3340    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3341    #[must_use]
3342    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3343        self.meta = meta.into_option();
3344        self
3345    }
3346}
3347
3348/// **UNSTABLE**
3349///
3350/// This capability is not part of the spec yet, and may be removed or changed at any point.
3351///
3352/// Request parameters for unarchiving a session.
3353///
3354/// Only available if the Agent supports the `session.archive` capability.
3355///
3356/// Unarchiving returns the session to default `session/list` results with the same ID and
3357/// saved history. It never resumes the session. Clients that want to continue an
3358/// archived session SHOULD unarchive it before calling `session/resume`.
3359/// Unarchiving a session that is not archived succeeds. A session that does not exist
3360/// gets `-32002`.
3361///
3362#[cfg(feature = "unstable_session_archive")]
3363#[serde_as]
3364#[skip_serializing_none]
3365#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3366#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3367#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_UNARCHIVE_METHOD_NAME)))]
3368#[serde(rename_all = "camelCase")]
3369#[non_exhaustive]
3370pub struct UnarchiveSessionRequest {
3371    /// The ID of the session to unarchive.
3372    pub session_id: SessionId,
3373    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3374    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3375    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3376    ///
3377    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3378    #[serde_as(deserialize_as = "DefaultOnError")]
3379    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3380    #[serde(default)]
3381    #[serde(rename = "_meta")]
3382    pub meta: Option<Meta>,
3383}
3384
3385#[cfg(feature = "unstable_session_archive")]
3386impl UnarchiveSessionRequest {
3387    /// Builds [`UnarchiveSessionRequest`] with the required request fields set. Optional fields start unset or empty.
3388    #[must_use]
3389    pub fn new(session_id: impl Into<SessionId>) -> Self {
3390        Self {
3391            session_id: session_id.into(),
3392            meta: None,
3393        }
3394    }
3395
3396    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3397    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3398    /// do not recognize.
3399    ///
3400    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3401    #[must_use]
3402    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3403        self.meta = meta.into_option();
3404        self
3405    }
3406}
3407
3408#[cfg(feature = "unstable_session_archive")]
3409crate::serde_util::default_on_null! {
3410    /// **UNSTABLE**
3411    ///
3412    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3413    ///
3414    /// Response from unarchiving a session.
3415    #[serde_as]
3416    #[skip_serializing_none]
3417    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3418    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3419    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_UNARCHIVE_METHOD_NAME)))]
3420    #[serde(rename_all = "camelCase")]
3421    #[non_exhaustive]
3422    pub struct UnarchiveSessionResponse {
3423        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3424        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3425        /// Implementations MUST NOT assign meaning to keys they do not recognize.
3426        ///
3427        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3428        #[serde_as(deserialize_as = "DefaultOnError")]
3429        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3430        #[serde(default)]
3431        #[serde(rename = "_meta")]
3432        pub meta: Option<Meta>,
3433    }
3434}
3435
3436#[cfg(feature = "unstable_session_archive")]
3437impl UnarchiveSessionResponse {
3438    /// Builds [`UnarchiveSessionResponse`] with the required response fields set. Optional fields start unset or empty.
3439    #[must_use]
3440    pub fn new() -> Self {
3441        Self::default()
3442    }
3443
3444    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3445    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3446    /// do not recognize.
3447    ///
3448    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3449    #[must_use]
3450    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3451        self.meta = meta.into_option();
3452        self
3453    }
3454}
3455
3456/// **UNSTABLE**
3457///
3458/// This capability is not part of the spec yet, and may be removed or changed at any point.
3459///
3460/// Which sessions `session/list` returns based on their archive state.
3461///
3462/// Unknown values are preserved so they can be stored, proxied, or forwarded. An Agent MUST
3463/// return `-32602` for a value it does not support rather than treating it as `exclude`.
3464#[cfg(feature = "unstable_session_archive")]
3465#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3466#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
3467#[serde(rename_all = "snake_case")]
3468#[non_exhaustive]
3469pub enum SessionArchiveFilter {
3470    /// Only sessions that are not archived. This is the default.
3471    #[default]
3472    Exclude,
3473    /// Both archived sessions and sessions that are not archived.
3474    Include,
3475    /// Only archived sessions.
3476    Only,
3477    /// Custom or future archive filter.
3478    ///
3479    /// Values beginning with `_` are reserved for implementation-specific
3480    /// extensions. Unknown values that do not begin with `_` are reserved for
3481    /// future ACP variants.
3482    #[serde(untagged)]
3483    Other(String),
3484}
3485
3486/// Information about a session returned by session/list
3487#[serde_as]
3488#[skip_serializing_none]
3489#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3490#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3491#[serde(rename_all = "camelCase")]
3492#[non_exhaustive]
3493pub struct SessionInfo {
3494    /// Unique identifier for the session
3495    pub session_id: SessionId,
3496    /// The working directory for this session. Must be an absolute path.
3497    pub cwd: AbsolutePath,
3498    /// Additional workspace roots reported for this session. Each path MUST be absolute.
3499    ///
3500    /// When present, this is the complete ordered additional-root list reported
3501    /// by the Agent. Omitted and empty values are equivalent: the response
3502    /// reports no additional roots.
3503    #[serde_as(deserialize_as = "DefaultOnNull")]
3504    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
3505    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3506    pub additional_directories: Vec<AbsolutePath>,
3507
3508    /// Human-readable title for the session
3509    ///
3510    /// Omitted and `null` are equivalent and mean no title is provided.
3511    #[serde_as(deserialize_as = "DefaultOnError")]
3512    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3513    #[serde(default)]
3514    pub title: Option<String>,
3515    /// RFC 3339 timestamp of last activity.
3516    ///
3517    /// Omitted and `null` are equivalent and mean the last activity time is not reported.
3518    #[serde_as(deserialize_as = "DefaultOnError")]
3519    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "format" = "date-time")))]
3520    #[serde(default)]
3521    pub updated_at: Option<String>,
3522    /// **UNSTABLE**
3523    ///
3524    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3525    ///
3526    /// Whether the session is archived.
3527    ///
3528    /// Optional. Omitted and `null` are equivalent and mean the archive state is not reported.
3529    /// Agents that advertise the `session.archive` capability MUST include it on every listed session.
3530    #[cfg(feature = "unstable_session_archive")]
3531    #[serde_as(deserialize_as = "DefaultOnError")]
3532    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3533    #[serde(default)]
3534    pub archived: Option<bool>,
3535    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3536    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3537    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3538    ///
3539    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3540    #[serde_as(deserialize_as = "DefaultOnError")]
3541    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3542    #[serde(default)]
3543    #[serde(rename = "_meta")]
3544    pub meta: Option<Meta>,
3545}
3546
3547impl SessionInfo {
3548    /// Builds [`SessionInfo`] with the required fields set. Optional fields start unset or empty.
3549    #[must_use]
3550    pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
3551        Self {
3552            session_id: session_id.into(),
3553            cwd: cwd.into(),
3554            additional_directories: vec![],
3555            title: None,
3556            updated_at: None,
3557            #[cfg(feature = "unstable_session_archive")]
3558            archived: None,
3559            meta: None,
3560        }
3561    }
3562
3563    /// Additional workspace roots reported for this session. Each path MUST be absolute.
3564    #[must_use]
3565    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
3566    where
3567        I: IntoIterator<Item = P>,
3568        P: Into<AbsolutePath>,
3569    {
3570        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
3571        self
3572    }
3573
3574    /// Human-readable title for the session
3575    #[must_use]
3576    pub fn title(mut self, title: impl IntoOption<String>) -> Self {
3577        self.title = title.into_option();
3578        self
3579    }
3580
3581    /// RFC 3339 timestamp of last activity.
3582    #[must_use]
3583    pub fn updated_at(mut self, updated_at: impl IntoOption<String>) -> Self {
3584        self.updated_at = updated_at.into_option();
3585        self
3586    }
3587
3588    /// **UNSTABLE**
3589    ///
3590    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3591    ///
3592    /// Whether the session is archived.
3593    #[cfg(feature = "unstable_session_archive")]
3594    #[must_use]
3595    pub fn archived(mut self, archived: impl IntoOption<bool>) -> Self {
3596        self.archived = archived.into_option();
3597        self
3598    }
3599
3600    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3601    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3602    /// do not recognize.
3603    ///
3604    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3605    #[must_use]
3606    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3607        self.meta = meta.into_option();
3608        self
3609    }
3610}
3611
3612// Set session title
3613
3614/// **UNSTABLE**
3615///
3616/// This capability is not part of the spec yet, and may be removed or changed at any point.
3617///
3618/// Request parameters for setting the title of a session.
3619///
3620/// Only available if the Agent supports the `session.title` capability.
3621///
3622/// The session does not need to be active on the connection. Any session the Agent would
3623/// return from `session/list` can be retitled. A session that does not exist gets `-32002`.
3624///
3625/// The Agent responds only after it has stored the title. After a successful response, the
3626/// Agent SHOULD NOT replace the title with one it generates automatically.
3627#[cfg(feature = "unstable_session_set_title")]
3628#[serde_as]
3629#[skip_serializing_none]
3630#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3631#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3632#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_TITLE_METHOD_NAME)))]
3633#[serde(rename_all = "camelCase")]
3634#[non_exhaustive]
3635pub struct SetSessionTitleRequest {
3636    /// The ID of the session to retitle.
3637    pub session_id: SessionId,
3638    /// The new title for the session.
3639    ///
3640    /// Required and non-null. Omission and explicit `null` are both invalid. The Agent MAY
3641    /// normalize the title before storing it, for example by trimming whitespace or
3642    /// truncating it. The Agent rejects a title that fails its validation, including one
3643    /// that is empty after normalization, with `-32602`.
3644    pub title: String,
3645    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3646    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3647    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3648    ///
3649    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3650    #[serde_as(deserialize_as = "DefaultOnError")]
3651    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3652    #[serde(default)]
3653    #[serde(rename = "_meta")]
3654    pub meta: Option<Meta>,
3655}
3656
3657#[cfg(feature = "unstable_session_set_title")]
3658impl SetSessionTitleRequest {
3659    /// Builds [`SetSessionTitleRequest`] with the required request fields set. Optional fields start unset or empty.
3660    #[must_use]
3661    pub fn new(session_id: impl Into<SessionId>, title: impl Into<String>) -> Self {
3662        Self {
3663            session_id: session_id.into(),
3664            title: title.into(),
3665            meta: None,
3666        }
3667    }
3668
3669    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3670    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3671    /// do not recognize.
3672    ///
3673    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3674    #[must_use]
3675    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3676        self.meta = meta.into_option();
3677        self
3678    }
3679}
3680
3681/// **UNSTABLE**
3682///
3683/// This capability is not part of the spec yet, and may be removed or changed at any point.
3684///
3685/// Response from setting the title of a session.
3686#[cfg(feature = "unstable_session_set_title")]
3687#[serde_as]
3688#[skip_serializing_none]
3689#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3690#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3691#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_TITLE_METHOD_NAME)))]
3692#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "sessionInfo", "field": "title", "value": "title"}]})))]
3693#[serde(rename_all = "camelCase")]
3694#[non_exhaustive]
3695pub struct SetSessionTitleResponse {
3696    /// The title the Agent stored.
3697    ///
3698    /// This differs from the requested title if the Agent normalized it. Clients SHOULD
3699    /// display this value rather than the one they sent.
3700    pub title: String,
3701    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3702    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3703    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3704    ///
3705    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3706    #[serde_as(deserialize_as = "DefaultOnError")]
3707    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3708    #[serde(default)]
3709    #[serde(rename = "_meta")]
3710    pub meta: Option<Meta>,
3711}
3712
3713#[cfg(feature = "unstable_session_set_title")]
3714impl SetSessionTitleResponse {
3715    /// Builds [`SetSessionTitleResponse`] with the required response fields set. Optional fields start unset or empty.
3716    #[must_use]
3717    pub fn new(title: impl Into<String>) -> Self {
3718        Self {
3719            title: title.into(),
3720            meta: None,
3721        }
3722    }
3723
3724    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3725    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3726    /// do not recognize.
3727    ///
3728    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3729    #[must_use]
3730    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3731        self.meta = meta.into_option();
3732        self
3733    }
3734}
3735
3736// Session config options
3737
3738/// Unique identifier for a session configuration option.
3739#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3740#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3741#[serde(transparent)]
3742#[from(forward)]
3743#[non_exhaustive]
3744pub struct SessionConfigId(pub Arc<str>);
3745
3746impl SessionConfigId {
3747    /// Wraps a protocol string as a typed [`SessionConfigId`].
3748    #[must_use]
3749    pub fn new(id: impl Into<Self>) -> Self {
3750        id.into()
3751    }
3752}
3753
3754/// Unique identifier for a session configuration option value.
3755#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3756#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3757#[serde(transparent)]
3758#[from(forward)]
3759#[non_exhaustive]
3760pub struct SessionConfigValueId(pub Arc<str>);
3761
3762impl SessionConfigValueId {
3763    /// Wraps a protocol string as a typed [`SessionConfigValueId`].
3764    #[must_use]
3765    pub fn new(id: impl Into<Self>) -> Self {
3766        id.into()
3767    }
3768}
3769
3770/// Unique identifier for a session configuration option value group.
3771#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3772#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3773#[serde(transparent)]
3774#[from(forward)]
3775#[non_exhaustive]
3776pub struct SessionConfigGroupId(pub Arc<str>);
3777
3778impl SessionConfigGroupId {
3779    /// Wraps a protocol string as a typed [`SessionConfigGroupId`].
3780    #[must_use]
3781    pub fn new(id: impl Into<Self>) -> Self {
3782        id.into()
3783    }
3784}
3785
3786/// A possible value for a session configuration option.
3787#[serde_as]
3788#[skip_serializing_none]
3789#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3790#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3791#[serde(rename_all = "camelCase")]
3792#[non_exhaustive]
3793pub struct SessionConfigSelectOption {
3794    /// Unique identifier for this option value.
3795    pub value: SessionConfigValueId,
3796    /// Human-readable label for this option value.
3797    pub name: String,
3798    /// Optional description for this option value.
3799    /// May contain Markdown.
3800    ///
3801    /// Omitted and `null` are equivalent and mean no description is provided.
3802    #[serde_as(deserialize_as = "DefaultOnError")]
3803    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3804    #[serde(default)]
3805    pub description: Option<String>,
3806    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3807    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3808    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3809    ///
3810    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3811    #[serde_as(deserialize_as = "DefaultOnError")]
3812    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3813    #[serde(default)]
3814    #[serde(rename = "_meta")]
3815    pub meta: Option<Meta>,
3816}
3817
3818impl SessionConfigSelectOption {
3819    /// Builds [`SessionConfigSelectOption`] with the required fields set. Optional fields start unset or empty.
3820    #[must_use]
3821    pub fn new(value: impl Into<SessionConfigValueId>, name: impl Into<String>) -> Self {
3822        Self {
3823            value: value.into(),
3824            name: name.into(),
3825            description: None,
3826            meta: None,
3827        }
3828    }
3829
3830    /// Sets or clears the optional `description` field.
3831    #[must_use]
3832    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
3833        self.description = description.into_option();
3834        self
3835    }
3836
3837    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3838    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3839    /// do not recognize.
3840    ///
3841    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3842    #[must_use]
3843    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3844        self.meta = meta.into_option();
3845        self
3846    }
3847}
3848
3849/// A group of possible values for a session configuration option.
3850#[serde_as]
3851#[skip_serializing_none]
3852#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3853#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3854#[serde(rename_all = "camelCase")]
3855#[non_exhaustive]
3856pub struct SessionConfigSelectGroup {
3857    /// Identifier for this group. MUST be unique within the option.
3858    pub group_id: SessionConfigGroupId,
3859    /// Human-readable label for this group.
3860    pub name: String,
3861    /// The set of option values in this group. MUST contain at least one value.
3862    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
3863    #[cfg_attr(feature = "schemars", schemars(length(min = 1), extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3864    pub options: Vec<SessionConfigSelectOption>,
3865    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3866    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3867    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3868    ///
3869    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3870    #[serde_as(deserialize_as = "DefaultOnError")]
3871    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3872    #[serde(default)]
3873    #[serde(rename = "_meta")]
3874    pub meta: Option<Meta>,
3875}
3876
3877impl SessionConfigSelectGroup {
3878    /// Builds [`SessionConfigSelectGroup`] with the required fields set. Optional fields start unset or empty.
3879    #[must_use]
3880    pub fn new(
3881        group_id: impl Into<SessionConfigGroupId>,
3882        name: impl Into<String>,
3883        options: Vec<SessionConfigSelectOption>,
3884    ) -> Self {
3885        Self {
3886            group_id: group_id.into(),
3887            name: name.into(),
3888            options,
3889            meta: None,
3890        }
3891    }
3892
3893    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3894    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3895    /// do not recognize.
3896    ///
3897    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3898    #[must_use]
3899    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3900        self.meta = meta.into_option();
3901        self
3902    }
3903}
3904
3905/// Possible values for a session configuration option.
3906#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3907#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3908#[serde(untagged)]
3909#[non_exhaustive]
3910pub enum SessionConfigSelectOptions {
3911    /// A flat list of options with no grouping.
3912    Ungrouped(
3913        #[cfg_attr(feature = "schemars", schemars(length(min = 1)))] Vec<SessionConfigSelectOption>,
3914    ),
3915    /// A list of options grouped under headers.
3916    Grouped(
3917        #[cfg_attr(feature = "schemars", schemars(length(min = 1)))] Vec<SessionConfigSelectGroup>,
3918    ),
3919}
3920
3921impl From<Vec<SessionConfigSelectOption>> for SessionConfigSelectOptions {
3922    fn from(options: Vec<SessionConfigSelectOption>) -> Self {
3923        SessionConfigSelectOptions::Ungrouped(options)
3924    }
3925}
3926
3927impl From<Vec<SessionConfigSelectGroup>> for SessionConfigSelectOptions {
3928    fn from(groups: Vec<SessionConfigSelectGroup>) -> Self {
3929        SessionConfigSelectOptions::Grouped(groups)
3930    }
3931}
3932
3933/// A single-value selector (dropdown) session configuration option payload.
3934#[skip_serializing_none]
3935#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3936#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3937#[serde(rename_all = "camelCase")]
3938#[non_exhaustive]
3939pub struct SessionConfigSelect {
3940    /// The currently selected value. MUST be one of the `value`s in `options`.
3941    pub current_value: SessionConfigValueId,
3942    /// The set of selectable options. MUST contain at least one value, and each `value` MUST be
3943    /// unique within the option, including across groups.
3944    pub options: SessionConfigSelectOptions,
3945}
3946
3947impl SessionConfigSelect {
3948    /// Builds [`SessionConfigSelect`] with the required fields set. Optional fields start unset or empty.
3949    #[must_use]
3950    pub fn new(
3951        current_value: impl Into<SessionConfigValueId>,
3952        options: impl Into<SessionConfigSelectOptions>,
3953    ) -> Self {
3954        Self {
3955            current_value: current_value.into(),
3956            options: options.into(),
3957        }
3958    }
3959}
3960
3961/// A boolean on/off toggle session configuration option payload.
3962#[skip_serializing_none]
3963#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3964#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3965#[serde(rename_all = "camelCase")]
3966#[non_exhaustive]
3967pub struct SessionConfigBoolean {
3968    /// The current value of the boolean option.
3969    pub current_value: bool,
3970}
3971
3972impl SessionConfigBoolean {
3973    /// Builds [`SessionConfigBoolean`] with the required fields set. Optional fields start unset or empty.
3974    #[must_use]
3975    pub fn new(current_value: bool) -> Self {
3976        Self { current_value }
3977    }
3978}
3979
3980/// Semantic category for a session configuration option.
3981///
3982/// This is intended to help Clients distinguish broadly common selectors (e.g. model selector vs
3983/// session mode selector vs thought/reasoning level) for UX purposes (keyboard shortcuts, icons,
3984/// placement). It MUST NOT be required for correctness. Clients MUST handle missing or unknown
3985/// categories gracefully.
3986///
3987/// Category names beginning with `_` are free for custom use, like other ACP extension methods.
3988/// Category names that do not begin with `_` are reserved for the ACP spec.
3989#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3990#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3991#[serde(rename_all = "snake_case")]
3992#[non_exhaustive]
3993pub enum SessionConfigOptionCategory {
3994    /// Session mode selector.
3995    Mode,
3996    /// Model selector.
3997    Model,
3998    /// Model-related configuration parameter.
3999    ModelConfig,
4000    /// **UNSTABLE**
4001    ///
4002    /// This capability is not part of the spec yet, and may be removed or changed at any point.
4003    ///
4004    /// Response speed selector, such as a fast mode toggle.
4005    #[cfg(feature = "unstable_speed_config_category")]
4006    Speed,
4007    /// Thought/reasoning level selector.
4008    ThoughtLevel,
4009    /// Custom or future category.
4010    ///
4011    /// Values beginning with `_` are reserved for implementation-specific
4012    /// extensions. Unknown values that do not begin with `_` are reserved for
4013    /// future ACP variants.
4014    #[serde(untagged)]
4015    Other(String),
4016}
4017
4018/// Type-specific session configuration option payload.
4019#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4020#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4021#[serde(tag = "type", rename_all = "snake_case")]
4022#[non_exhaustive]
4023pub enum SessionConfigKind {
4024    /// Single-value selector (dropdown).
4025    Select(SessionConfigSelect),
4026    /// Boolean on/off toggle.
4027    Boolean(SessionConfigBoolean),
4028    /// Custom or future session configuration option payload.
4029    ///
4030    /// Values beginning with `_` are reserved for implementation-specific
4031    /// extensions. Unknown values that do not begin with `_` are reserved for
4032    /// future ACP variants.
4033    ///
4034    /// Clients that do not understand this option type SHOULD preserve the raw
4035    /// payload when storing, replaying, proxying, or forwarding configuration
4036    /// data, and otherwise ignore the option. The Agent keeps using its `currentValue`.
4037    #[serde(untagged)]
4038    Other(OtherSessionConfigKind),
4039}
4040
4041/// Custom or future session configuration option payload.
4042#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4043#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4044#[cfg_attr(feature = "schemars", schemars(inline))]
4045#[cfg_attr(feature = "schemars", schemars(transform = other_session_config_kind_schema))]
4046#[serde(rename_all = "camelCase")]
4047#[non_exhaustive]
4048pub struct OtherSessionConfigKind {
4049    /// Custom or future session configuration option type.
4050    ///
4051    /// Values beginning with `_` are reserved for implementation-specific
4052    /// extensions. Unknown values that do not begin with `_` are reserved for
4053    /// future ACP variants.
4054    #[serde(rename = "type")]
4055    pub type_: String,
4056    /// Additional fields from the unknown session configuration option payload.
4057    #[serde(flatten)]
4058    pub fields: IndexMap<String, serde_json::Value>,
4059}
4060
4061impl OtherSessionConfigKind {
4062    /// Builds [`OtherSessionConfigKind`] from an unknown discriminator and preserves the remaining extension fields.
4063    #[must_use]
4064    pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
4065        fields.shift_remove("type");
4066        fields.shift_remove("_meta");
4067        Self {
4068            type_: type_.into(),
4069            fields,
4070        }
4071    }
4072}
4073
4074impl<'de> Deserialize<'de> for OtherSessionConfigKind {
4075    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4076    where
4077        D: serde::Deserializer<'de>,
4078    {
4079        let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4080        let type_ = fields
4081            .shift_remove("type")
4082            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4083        let serde_json::Value::String(type_) = type_ else {
4084            return Err(serde::de::Error::custom("`type` must be a string"));
4085        };
4086
4087        if is_known_session_config_kind_type(&type_) {
4088            return Err(serde::de::Error::custom(format!(
4089                "known session configuration option `{type_}` did not match its schema"
4090            )));
4091        }
4092
4093        Ok(Self { type_, fields })
4094    }
4095}
4096
4097fn is_known_session_config_kind_type(type_: &str) -> bool {
4098    matches!(type_, "select" | "boolean")
4099}
4100
4101#[cfg(feature = "schemars")]
4102fn other_session_config_kind_schema(schema: &mut Schema) {
4103    super::schema_util::reject_known_string_discriminators(schema, "type", &["select", "boolean"]);
4104}
4105
4106/// A session configuration option selector and its current state.
4107#[serde_as]
4108#[skip_serializing_none]
4109#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4110#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4111#[serde(rename_all = "camelCase")]
4112#[non_exhaustive]
4113pub struct SessionConfigOption {
4114    /// Identifier for the configuration option. MUST be unique within `configOptions`.
4115    pub config_id: SessionConfigId,
4116    /// Human-readable label for the option.
4117    pub name: String,
4118    /// Optional description for the Client to display to the user.
4119    /// May contain Markdown.
4120    ///
4121    /// Omitted and `null` are equivalent and mean no description is provided.
4122    #[serde_as(deserialize_as = "DefaultOnError")]
4123    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4124    #[serde(default)]
4125    pub description: Option<String>,
4126    /// Optional semantic category for this option (UX only).
4127    ///
4128    /// Omitted and `null` are equivalent and mean no category is provided.
4129    #[serde_as(deserialize_as = "DefaultOnError")]
4130    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4131    #[serde(default)]
4132    pub category: Option<SessionConfigOptionCategory>,
4133    /// Type-specific fields for this configuration option.
4134    #[serde(flatten)]
4135    pub kind: SessionConfigKind,
4136    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4137    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4138    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4139    ///
4140    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4141    #[serde_as(deserialize_as = "DefaultOnError")]
4142    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4143    #[serde(default)]
4144    #[serde(rename = "_meta")]
4145    pub meta: Option<Meta>,
4146}
4147
4148impl SessionConfigOption {
4149    /// Builds [`SessionConfigOption`] with the required fields set. Optional fields start unset or empty.
4150    #[must_use]
4151    pub fn new(
4152        config_id: impl Into<SessionConfigId>,
4153        name: impl Into<String>,
4154        kind: SessionConfigKind,
4155    ) -> Self {
4156        Self {
4157            config_id: config_id.into(),
4158            name: name.into(),
4159            description: None,
4160            category: None,
4161            kind,
4162            meta: None,
4163        }
4164    }
4165
4166    /// Builds a select-style session configuration option with its current value and choices.
4167    #[must_use]
4168    pub fn select(
4169        config_id: impl Into<SessionConfigId>,
4170        name: impl Into<String>,
4171        current_value: impl Into<SessionConfigValueId>,
4172        options: impl Into<SessionConfigSelectOptions>,
4173    ) -> Self {
4174        Self::new(
4175            config_id,
4176            name,
4177            SessionConfigKind::Select(SessionConfigSelect::new(current_value, options)),
4178        )
4179    }
4180
4181    /// Builds a boolean-style session configuration option with its current value.
4182    #[must_use]
4183    pub fn boolean(
4184        config_id: impl Into<SessionConfigId>,
4185        name: impl Into<String>,
4186        current_value: bool,
4187    ) -> Self {
4188        Self::new(
4189            config_id,
4190            name,
4191            SessionConfigKind::Boolean(SessionConfigBoolean::new(current_value)),
4192        )
4193    }
4194
4195    /// Sets or clears the optional `description` field.
4196    #[must_use]
4197    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
4198        self.description = description.into_option();
4199        self
4200    }
4201
4202    /// Sets or clears the optional `category` field.
4203    #[must_use]
4204    pub fn category(mut self, category: impl IntoOption<SessionConfigOptionCategory>) -> Self {
4205        self.category = category.into_option();
4206        self
4207    }
4208
4209    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4210    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4211    /// do not recognize.
4212    ///
4213    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4214    #[must_use]
4215    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4216        self.meta = meta.into_option();
4217        self
4218    }
4219}
4220
4221/// The value to set for a session configuration option.
4222///
4223/// The `type` field acts as the discriminator in the serialized JSON form.
4224///
4225/// The `type` discriminator describes the *shape* of the value, not the option
4226/// kind. For example every option kind that picks from a list of ids
4227/// (`select`, `radio`, …) would use [`Id`](Self::Id), while a future freeform
4228/// text option would get its own variant.
4229#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4230#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4231#[serde(tag = "type", rename_all = "snake_case")]
4232#[non_exhaustive]
4233pub enum SessionConfigOptionValue {
4234    /// A `SessionConfigValueId` string value (`type: "id"`).
4235    Id {
4236        /// The value ID.
4237        value: SessionConfigValueId,
4238    },
4239    /// A boolean value (`type: "boolean"`).
4240    Boolean {
4241        /// The boolean value.
4242        value: bool,
4243    },
4244    /// Custom or future session configuration option value payload.
4245    ///
4246    /// Values beginning with `_` are reserved for implementation-specific
4247    /// extensions. Unknown values that do not begin with `_` are reserved for
4248    /// future ACP variants.
4249    ///
4250    /// Agents MUST reject a `session/set_config_option` request with a value type
4251    /// they do not support with `-32602`.
4252    #[serde(untagged)]
4253    Other(Box<OtherSessionConfigOptionValue>),
4254}
4255
4256/// Custom or future session configuration option value payload.
4257#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4258#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4259#[cfg_attr(feature = "schemars", schemars(inline))]
4260#[cfg_attr(feature = "schemars", schemars(transform = other_session_config_option_value_schema))]
4261#[serde(rename_all = "camelCase")]
4262#[non_exhaustive]
4263pub struct OtherSessionConfigOptionValue {
4264    /// Custom or future session configuration option value type.
4265    ///
4266    /// Values beginning with `_` are reserved for implementation-specific
4267    /// extensions. Unknown values that do not begin with `_` are reserved for
4268    /// future ACP variants.
4269    #[serde(rename = "type")]
4270    pub type_: String,
4271    /// Raw value payload for the custom or future value type.
4272    pub value: serde_json::Value,
4273    /// Additional fields from the unknown session configuration option value payload.
4274    #[serde(flatten)]
4275    pub fields: IndexMap<String, serde_json::Value>,
4276}
4277
4278impl OtherSessionConfigOptionValue {
4279    /// Builds [`OtherSessionConfigOptionValue`] from an unknown discriminator and preserves the remaining extension fields.
4280    #[must_use]
4281    pub fn new(
4282        type_: impl Into<String>,
4283        value: serde_json::Value,
4284        mut fields: IndexMap<String, serde_json::Value>,
4285    ) -> Self {
4286        fields.shift_remove("type");
4287        fields.shift_remove("value");
4288        fields.shift_remove("_meta");
4289        Self {
4290            type_: type_.into(),
4291            value,
4292            fields,
4293        }
4294    }
4295}
4296
4297impl<'de> Deserialize<'de> for OtherSessionConfigOptionValue {
4298    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4299    where
4300        D: serde::Deserializer<'de>,
4301    {
4302        let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4303        let type_ = fields
4304            .shift_remove("type")
4305            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4306        let serde_json::Value::String(type_) = type_ else {
4307            return Err(serde::de::Error::custom("`type` must be a string"));
4308        };
4309
4310        if is_known_session_config_option_value_type(&type_) {
4311            return Err(serde::de::Error::custom(format!(
4312                "known session configuration option value `{type_}` did not match its schema"
4313            )));
4314        }
4315
4316        let value = fields
4317            .shift_remove("value")
4318            .ok_or_else(|| serde::de::Error::missing_field("value"))?;
4319
4320        Ok(Self {
4321            type_,
4322            value,
4323            fields,
4324        })
4325    }
4326}
4327
4328impl<'de> Deserialize<'de> for SessionConfigOptionValue {
4329    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4330    where
4331        D: serde::Deserializer<'de>,
4332    {
4333        let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4334        let type_ = fields.shift_remove("type");
4335        let value = fields
4336            .shift_remove("value")
4337            .ok_or_else(|| serde::de::Error::missing_field("value"))?;
4338
4339        let type_ = type_.ok_or_else(|| serde::de::Error::missing_field("type"))?;
4340
4341        let serde_json::Value::String(type_) = type_ else {
4342            return Err(serde::de::Error::custom("`type` must be a string"));
4343        };
4344
4345        match type_.as_str() {
4346            "id" => {
4347                let value = serde_json::from_value(value).map_err(|error| {
4348                    serde::de::Error::custom(format!(
4349                        "`value` must be a string for `type: id`: {error}"
4350                    ))
4351                })?;
4352                Ok(Self::Id { value })
4353            }
4354            "boolean" => {
4355                let value = serde_json::from_value(value).map_err(|error| {
4356                    serde::de::Error::custom(format!(
4357                        "`value` must be a boolean for `type: boolean`: {error}"
4358                    ))
4359                })?;
4360                Ok(Self::Boolean { value })
4361            }
4362            _ => Ok(OtherSessionConfigOptionValue {
4363                type_,
4364                value,
4365                fields,
4366            }
4367            .into()),
4368        }
4369    }
4370}
4371
4372fn is_known_session_config_option_value_type(type_: &str) -> bool {
4373    matches!(type_, "id" | "boolean")
4374}
4375
4376#[cfg(feature = "schemars")]
4377fn other_session_config_option_value_schema(schema: &mut Schema) {
4378    super::schema_util::reject_known_string_discriminators(schema, "type", &["id", "boolean"]);
4379}
4380
4381impl SessionConfigOptionValue {
4382    /// Create an id option value (used by `select` and other id-based option types).
4383    #[must_use]
4384    pub fn id(id: impl Into<SessionConfigValueId>) -> Self {
4385        Self::Id { value: id.into() }
4386    }
4387
4388    /// Create a boolean option value.
4389    #[must_use]
4390    pub fn boolean(val: bool) -> Self {
4391        Self::Boolean { value: val }
4392    }
4393
4394    /// Return the inner [`SessionConfigValueId`] if this is a
4395    /// [`Id`](Self::Id) value.
4396    #[must_use]
4397    pub fn as_id(&self) -> Option<&SessionConfigValueId> {
4398        match self {
4399            Self::Id { value } => Some(value),
4400            _ => None,
4401        }
4402    }
4403
4404    /// Return the inner [`bool`] if this is a [`Boolean`](Self::Boolean) value.
4405    #[must_use]
4406    pub fn as_bool(&self) -> Option<bool> {
4407        match self {
4408            Self::Boolean { value } => Some(*value),
4409            _ => None,
4410        }
4411    }
4412}
4413
4414impl From<SessionConfigValueId> for SessionConfigOptionValue {
4415    fn from(value: SessionConfigValueId) -> Self {
4416        Self::Id { value }
4417    }
4418}
4419
4420impl From<bool> for SessionConfigOptionValue {
4421    fn from(value: bool) -> Self {
4422        Self::Boolean { value }
4423    }
4424}
4425
4426impl From<OtherSessionConfigOptionValue> for SessionConfigOptionValue {
4427    fn from(value: OtherSessionConfigOptionValue) -> Self {
4428        Self::Other(Box::new(value))
4429    }
4430}
4431
4432impl From<&str> for SessionConfigOptionValue {
4433    fn from(value: &str) -> Self {
4434        Self::Id {
4435            value: SessionConfigValueId::new(value),
4436        }
4437    }
4438}
4439
4440/// Request parameters for setting a session configuration option.
4441///
4442/// Agents MUST support this method for any session the Client created or resumed
4443/// where they advertise config options. For a child session, the child's
4444/// capabilities decide whether the Client can send it, and none defined today
4445/// permits it.
4446/// Agents MUST reject an unknown `configId` or invalid value with `-32602` and leave the
4447/// configuration unchanged.
4448///
4449/// See protocol docs: [Session Config Options](https://agentclientprotocol.com/protocol/v2/session-config-options#setting-a-config-option)
4450#[serde_as]
4451#[skip_serializing_none]
4452#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4453#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4454#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_CONFIG_OPTION_METHOD_NAME)))]
4455#[serde(rename_all = "camelCase")]
4456#[non_exhaustive]
4457pub struct SetSessionConfigOptionRequest {
4458    /// The ID of the session to set the configuration option for.
4459    pub session_id: SessionId,
4460    /// The ID of the configuration option to set.
4461    pub config_id: SessionConfigId,
4462    /// The value to set, including a `type` discriminator and the raw `value`.
4463    ///
4464    /// Payloads MUST send `type: "id"` for id-based options.
4465    #[serde(flatten)]
4466    pub value: SessionConfigOptionValue,
4467    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4468    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4469    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4470    ///
4471    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4472    #[serde_as(deserialize_as = "DefaultOnError")]
4473    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4474    #[serde(default)]
4475    #[serde(rename = "_meta")]
4476    pub meta: Option<Meta>,
4477}
4478
4479impl SetSessionConfigOptionRequest {
4480    /// Builds [`SetSessionConfigOptionRequest`] with the required request fields set. Optional fields start unset or empty.
4481    #[must_use]
4482    pub fn new(
4483        session_id: impl Into<SessionId>,
4484        config_id: impl Into<SessionConfigId>,
4485        value: impl Into<SessionConfigOptionValue>,
4486    ) -> Self {
4487        Self {
4488            session_id: session_id.into(),
4489            config_id: config_id.into(),
4490            value: value.into(),
4491            meta: None,
4492        }
4493    }
4494
4495    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4496    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4497    /// do not recognize.
4498    ///
4499    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4500    #[must_use]
4501    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4502        self.meta = meta.into_option();
4503        self
4504    }
4505}
4506
4507/// Response to `session/set_config_option` method.
4508#[serde_as]
4509#[skip_serializing_none]
4510#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4511#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4512#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_CONFIG_OPTION_METHOD_NAME)))]
4513#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}]})))]
4514#[serde(rename_all = "camelCase")]
4515#[non_exhaustive]
4516pub struct SetSessionConfigOptionResponse {
4517    /// The full set of configuration options and their current values.
4518    #[serde_as(deserialize_as = "VecSkipError<_>")]
4519    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
4520    pub config_options: Vec<SessionConfigOption>,
4521    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4522    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4523    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4524    ///
4525    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4526    #[serde_as(deserialize_as = "DefaultOnError")]
4527    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4528    #[serde(default)]
4529    #[serde(rename = "_meta")]
4530    pub meta: Option<Meta>,
4531}
4532
4533impl SetSessionConfigOptionResponse {
4534    /// Builds [`SetSessionConfigOptionResponse`] with the required response fields set. Optional fields start unset or empty.
4535    #[must_use]
4536    pub fn new(config_options: Vec<SessionConfigOption>) -> Self {
4537        Self {
4538            config_options,
4539            meta: None,
4540        }
4541    }
4542
4543    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4544    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4545    /// do not recognize.
4546    ///
4547    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4548    #[must_use]
4549    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4550        self.meta = meta.into_option();
4551        self
4552    }
4553}
4554
4555// MCP
4556
4557/// Configuration for connecting to an MCP (Model Context Protocol) server.
4558///
4559/// MCP servers provide tools and context that the Agent can use when
4560/// processing prompts.
4561///
4562/// See protocol docs: [MCP Servers](https://agentclientprotocol.com/protocol/v2/session-setup#mcp-servers)
4563#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4564#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4565#[serde(tag = "type", rename_all = "snake_case")]
4566#[non_exhaustive]
4567pub enum McpServer {
4568    /// HTTP transport configuration
4569    ///
4570    /// Only available when the Agent capabilities include `session.mcp.http`.
4571    Http(McpServerHttp),
4572    /// **UNSTABLE**
4573    ///
4574    /// This capability is not part of the spec yet, and may be removed or changed at any point.
4575    ///
4576    /// ACP transport configuration
4577    ///
4578    /// Only available when the Agent capabilities include `session.mcp.acp`.
4579    /// The MCP server is provided by an ACP component and communicates over the ACP channel.
4580    #[cfg(feature = "unstable_mcp_over_acp")]
4581    Acp(McpServerAcp),
4582    /// Stdio transport configuration
4583    ///
4584    /// Only available when the Agent capabilities include `session.mcp.stdio`.
4585    Stdio(McpServerStdio),
4586    /// Custom or future MCP server transport configuration.
4587    ///
4588    /// Values beginning with `_` are reserved for implementation-specific
4589    /// extensions. Unknown values that do not begin with `_` are reserved for
4590    /// future ACP variants.
4591    ///
4592    /// Receivers that do not understand this transport SHOULD preserve the raw
4593    /// payload when storing, replaying, proxying, or forwarding session setup
4594    /// data. Agents MUST reject a request with a transport they do not support
4595    /// with `-32602`.
4596    #[serde(untagged)]
4597    Other(OtherMcpServer),
4598}
4599
4600/// Custom or future MCP server transport payload.
4601#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4602#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4603#[cfg_attr(feature = "schemars", schemars(inline))]
4604#[cfg_attr(feature = "schemars", schemars(transform = other_mcp_server_schema))]
4605#[serde(rename_all = "camelCase")]
4606#[non_exhaustive]
4607pub struct OtherMcpServer {
4608    /// Custom or future MCP server transport type.
4609    ///
4610    /// Values beginning with `_` are reserved for implementation-specific
4611    /// extensions. Unknown values that do not begin with `_` are reserved for
4612    /// future ACP variants.
4613    #[serde(rename = "type")]
4614    pub type_: String,
4615    /// Additional fields from the unknown MCP server transport payload.
4616    #[serde(flatten)]
4617    pub fields: IndexMap<String, serde_json::Value>,
4618}
4619
4620impl OtherMcpServer {
4621    /// Builds [`OtherMcpServer`] from an unknown discriminator and preserves the remaining extension fields.
4622    #[must_use]
4623    pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
4624        fields.shift_remove("type");
4625        Self {
4626            type_: type_.into(),
4627            fields,
4628        }
4629    }
4630}
4631
4632impl<'de> Deserialize<'de> for OtherMcpServer {
4633    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4634    where
4635        D: serde::Deserializer<'de>,
4636    {
4637        let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4638        let type_ = fields
4639            .shift_remove("type")
4640            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4641        let serde_json::Value::String(type_) = type_ else {
4642            return Err(serde::de::Error::custom("`type` must be a string"));
4643        };
4644
4645        if is_known_mcp_server_type(&type_) {
4646            return Err(serde::de::Error::custom(format!(
4647                "known MCP server transport `{type_}` did not match its schema"
4648            )));
4649        }
4650
4651        Ok(Self { type_, fields })
4652    }
4653}
4654
4655fn is_known_mcp_server_type(type_: &str) -> bool {
4656    match type_ {
4657        "http" | "stdio" => true,
4658        #[cfg(feature = "unstable_mcp_over_acp")]
4659        "acp" => true,
4660        _ => false,
4661    }
4662}
4663
4664#[cfg(feature = "schemars")]
4665fn other_mcp_server_schema(schema: &mut Schema) {
4666    super::schema_util::reject_known_string_discriminators(
4667        schema,
4668        "type",
4669        &[
4670            "http",
4671            "stdio",
4672            #[cfg(feature = "unstable_mcp_over_acp")]
4673            "acp",
4674        ],
4675    );
4676}
4677
4678/// HTTP transport configuration for MCP.
4679#[serde_as]
4680#[skip_serializing_none]
4681#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4682#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4683#[serde(rename_all = "camelCase")]
4684#[non_exhaustive]
4685pub struct McpServerHttp {
4686    /// Human-readable name identifying this MCP server. MUST be unique within `mcpServers`.
4687    ///
4688    /// Agents reject a request with a duplicate `name` with `-32602`.
4689    pub name: String,
4690    /// URL to the MCP server.
4691    #[cfg_attr(feature = "schemars", schemars(url))]
4692    pub url: String,
4693    /// HTTP headers to set when making requests to the MCP server. Headers the MCP transport
4694    /// defines are owned by the transport, and Agents use the transport's values for them.
4695    #[serde_as(deserialize_as = "DefaultOnNull")]
4696    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4697    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4698    pub headers: Vec<HttpHeader>,
4699    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4700    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4701    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4702    ///
4703    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4704    #[serde_as(deserialize_as = "DefaultOnError")]
4705    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4706    #[serde(default)]
4707    #[serde(rename = "_meta")]
4708    pub meta: Option<Meta>,
4709}
4710
4711impl McpServerHttp {
4712    /// Builds [`McpServerHttp`] with the required fields set. Optional fields start unset or empty.
4713    #[must_use]
4714    pub fn new(name: impl Into<String>, url: impl Into<String>) -> Self {
4715        Self {
4716            name: name.into(),
4717            url: url.into(),
4718            headers: Vec::new(),
4719            meta: None,
4720        }
4721    }
4722
4723    /// HTTP headers to set when making requests to the MCP server. Headers the MCP transport
4724    /// defines are owned by the transport, and Agents use the transport's values for them.
4725    #[must_use]
4726    pub fn headers(mut self, headers: Vec<HttpHeader>) -> Self {
4727        self.headers = headers;
4728        self
4729    }
4730
4731    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4732    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4733    /// do not recognize.
4734    ///
4735    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4736    #[must_use]
4737    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4738        self.meta = meta.into_option();
4739        self
4740    }
4741}
4742
4743/// **UNSTABLE**
4744///
4745/// This capability is not part of the spec yet, and may be removed or changed at any point.
4746///
4747/// Unique identifier for an MCP server using the ACP transport.
4748///
4749/// The value is opaque and generated by the ACP component providing the MCP server. It is
4750/// used by `mcp/message` to route requests to the component that declared the server.
4751#[cfg(feature = "unstable_mcp_over_acp")]
4752#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4753#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
4754#[serde(transparent)]
4755#[from(forward)]
4756#[non_exhaustive]
4757pub struct McpServerAcpId(pub Arc<str>);
4758
4759#[cfg(feature = "unstable_mcp_over_acp")]
4760impl McpServerAcpId {
4761    /// Wraps a protocol string as a typed [`McpServerAcpId`].
4762    #[must_use]
4763    pub fn new(id: impl Into<Self>) -> Self {
4764        id.into()
4765    }
4766}
4767
4768/// **UNSTABLE**
4769///
4770/// This capability is not part of the spec yet, and may be removed or changed at any point.
4771///
4772/// ACP transport configuration for MCP.
4773///
4774/// The MCP server is provided by an ACP component and communicates over the ACP channel
4775/// using `mcp/message`.
4776#[serde_as]
4777#[skip_serializing_none]
4778#[cfg(feature = "unstable_mcp_over_acp")]
4779#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4780#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4781#[serde(rename_all = "camelCase")]
4782#[non_exhaustive]
4783pub struct McpServerAcp {
4784    /// Human-readable name identifying this MCP server. MUST be unique within `mcpServers`.
4785    ///
4786    /// Agents reject a request with a duplicate `name` with `-32602`.
4787    pub name: String,
4788    /// Unique identifier for this MCP server, generated by the component providing it.
4789    ///
4790    /// Providers MUST NOT reuse an ID for multiple ACP-transport MCP servers that are visible
4791    /// on the same ACP connection.
4792    pub server_id: McpServerAcpId,
4793    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4794    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4795    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4796    ///
4797    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4798    #[serde_as(deserialize_as = "DefaultOnError")]
4799    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4800    #[serde(default)]
4801    #[serde(rename = "_meta")]
4802    pub meta: Option<Meta>,
4803}
4804
4805#[cfg(feature = "unstable_mcp_over_acp")]
4806impl McpServerAcp {
4807    /// Builds [`McpServerAcp`] with the required fields set. Optional fields start unset or empty.
4808    #[must_use]
4809    pub fn new(name: impl Into<String>, server_id: impl Into<McpServerAcpId>) -> Self {
4810        Self {
4811            name: name.into(),
4812            server_id: server_id.into(),
4813            meta: None,
4814        }
4815    }
4816
4817    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4818    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4819    /// do not recognize.
4820    ///
4821    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4822    #[must_use]
4823    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4824        self.meta = meta.into_option();
4825        self
4826    }
4827}
4828
4829/// Stdio transport configuration for MCP.
4830#[serde_as]
4831#[skip_serializing_none]
4832#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4833#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4834#[serde(rename_all = "camelCase")]
4835#[non_exhaustive]
4836pub struct McpServerStdio {
4837    /// Human-readable name identifying this MCP server. MUST be unique within `mcpServers`.
4838    ///
4839    /// Agents reject a request with a duplicate `name` with `-32602`.
4840    pub name: String,
4841    /// Path to the MCP server executable. Must be an absolute path.
4842    ///
4843    /// Agents reject a request with a relative `command` with `-32602`.
4844    pub command: AbsolutePath,
4845    /// Command-line arguments to pass to the MCP server.
4846    #[serde_as(deserialize_as = "DefaultOnNull")]
4847    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4848    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4849    pub args: Vec<String>,
4850    /// Environment variables to set when launching the MCP server. Names SHOULD be unique.
4851    /// Agents MAY reject duplicates with `-32602`, and otherwise the last entry wins.
4852    #[serde_as(deserialize_as = "DefaultOnNull")]
4853    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4854    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4855    pub env: Vec<EnvVariable>,
4856    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4857    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4858    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4859    ///
4860    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4861    #[serde_as(deserialize_as = "DefaultOnError")]
4862    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4863    #[serde(default)]
4864    #[serde(rename = "_meta")]
4865    pub meta: Option<Meta>,
4866}
4867
4868impl McpServerStdio {
4869    /// Builds [`McpServerStdio`] with the required fields set. Optional fields start unset or empty.
4870    #[must_use]
4871    pub fn new(name: impl Into<String>, command: impl Into<AbsolutePath>) -> Self {
4872        Self {
4873            name: name.into(),
4874            command: command.into(),
4875            args: Vec::new(),
4876            env: Vec::new(),
4877            meta: None,
4878        }
4879    }
4880
4881    /// Command-line arguments to pass to the MCP server.
4882    #[must_use]
4883    pub fn args(mut self, args: Vec<String>) -> Self {
4884        self.args = args;
4885        self
4886    }
4887
4888    /// Environment variables to set when launching the MCP server. Names SHOULD be unique.
4889    /// Agents MAY reject duplicates with `-32602`, and otherwise the last entry wins.
4890    #[must_use]
4891    pub fn env(mut self, env: Vec<EnvVariable>) -> Self {
4892        self.env = env;
4893        self
4894    }
4895
4896    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4897    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4898    /// do not recognize.
4899    ///
4900    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4901    #[must_use]
4902    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4903        self.meta = meta.into_option();
4904        self
4905    }
4906}
4907
4908/// An environment variable to set when launching a process.
4909#[serde_as]
4910#[skip_serializing_none]
4911#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4912#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4913#[serde(rename_all = "camelCase")]
4914#[non_exhaustive]
4915pub struct EnvVariable {
4916    /// The name of the environment variable.
4917    pub name: String,
4918    /// The value to set for the environment variable.
4919    pub value: String,
4920    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4921    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4922    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4923    ///
4924    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4925    #[serde_as(deserialize_as = "DefaultOnError")]
4926    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4927    #[serde(default)]
4928    #[serde(rename = "_meta")]
4929    pub meta: Option<Meta>,
4930}
4931
4932impl EnvVariable {
4933    /// Builds [`EnvVariable`] with the required fields set. Optional fields start unset or empty.
4934    #[must_use]
4935    pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
4936        Self {
4937            name: name.into(),
4938            value: value.into(),
4939            meta: None,
4940        }
4941    }
4942
4943    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4944    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4945    /// do not recognize.
4946    ///
4947    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4948    #[must_use]
4949    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4950        self.meta = meta.into_option();
4951        self
4952    }
4953}
4954
4955/// An HTTP header to set when making requests to the MCP server.
4956#[serde_as]
4957#[skip_serializing_none]
4958#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4959#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4960#[serde(rename_all = "camelCase")]
4961#[non_exhaustive]
4962pub struct HttpHeader {
4963    /// The name of the HTTP header.
4964    pub name: String,
4965    /// The value to set for the HTTP header.
4966    pub value: String,
4967    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4968    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4969    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4970    ///
4971    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4972    #[serde_as(deserialize_as = "DefaultOnError")]
4973    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4974    #[serde(default)]
4975    #[serde(rename = "_meta")]
4976    pub meta: Option<Meta>,
4977}
4978
4979impl HttpHeader {
4980    /// Builds [`HttpHeader`] with the required fields set. Optional fields start unset or empty.
4981    #[must_use]
4982    pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
4983        Self {
4984            name: name.into(),
4985            value: value.into(),
4986            meta: None,
4987        }
4988    }
4989
4990    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4991    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4992    /// do not recognize.
4993    ///
4994    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4995    #[must_use]
4996    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4997        self.meta = meta.into_option();
4998        self
4999    }
5000}
5001
5002// System prompt
5003
5004/// Client-provided system-level instructions for a session.
5005///
5006/// Clients MUST only send this when the Agent advertises
5007/// `session.systemPrompt`. Agents that cannot apply it, for example because of
5008/// an unadvertised mode or an unsupported content block type, MUST return an
5009/// error instead of creating or resuming the session.
5010#[serde_as]
5011#[skip_serializing_none]
5012#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5013#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5014#[serde(rename_all = "camelCase")]
5015#[non_exhaustive]
5016pub struct SystemPrompt {
5017    /// How the Agent combines `content` with its own instructions.
5018    ///
5019    /// Required. Agents MUST return an error for a mode they do not support rather than
5020    /// treating it as `append` or `override`.
5021    pub mode: SystemPromptMode,
5022    /// The system prompt content.
5023    ///
5024    /// Agents advertising the capability MUST accept `text` content blocks.
5025    /// Clients MUST NOT send other content block types until a future
5026    /// capability allows them, and Agents MUST return an error for content
5027    /// blocks they do not support, including unknown types.
5028    ///
5029    /// Clients MUST NOT send an empty array. Agents MAY reject one with
5030    /// `-32602` without creating or resuming the session.
5031    #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
5032    pub content: Vec<ContentBlock>,
5033    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5034    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5035    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5036    ///
5037    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5038    #[serde_as(deserialize_as = "DefaultOnError")]
5039    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5040    #[serde(default)]
5041    #[serde(rename = "_meta")]
5042    pub meta: Option<Meta>,
5043}
5044
5045impl SystemPrompt {
5046    /// Builds [`SystemPrompt`] with the required fields set. Optional fields start unset or empty.
5047    ///
5048    /// `mode` starts as [`SystemPromptMode::Append`]. Use [`SystemPrompt::mode`]
5049    /// to request another mode.
5050    #[must_use]
5051    pub fn new(content: Vec<ContentBlock>) -> Self {
5052        Self {
5053            mode: SystemPromptMode::default(),
5054            content,
5055            meta: None,
5056        }
5057    }
5058
5059    /// How the Agent combines `content` with its own instructions.
5060    #[must_use]
5061    pub fn mode(mut self, mode: SystemPromptMode) -> Self {
5062        self.mode = mode;
5063        self
5064    }
5065
5066    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5067    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5068    /// do not recognize.
5069    ///
5070    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5071    #[must_use]
5072    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5073        self.meta = meta.into_option();
5074        self
5075    }
5076}
5077
5078/// How the Agent combines a Client-provided system prompt with its own instructions.
5079///
5080/// Unknown modes are preserved so they can be stored,
5081/// proxied, or forwarded. An Agent MUST return an error for a mode it does not
5082/// support rather than treating it as `append` or `override`.
5083#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5084#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
5085#[serde(rename_all = "snake_case")]
5086#[non_exhaustive]
5087pub enum SystemPromptMode {
5088    /// Add the content to the Agent's own instructions rather than replacing them.
5089    ///
5090    /// Every Agent that advertises `session.systemPrompt` supports this mode.
5091    /// Agents SHOULD give the content system-level precedence, for example in the
5092    /// model's system prompt or developer instructions rather than in user-turn
5093    /// content. Where it is placed and how it is formatted is implementation-defined.
5094    #[default]
5095    Append,
5096    /// Replace the Agent's built-in default instructions with the content.
5097    ///
5098    /// This does not change tool availability, MCP servers, permissions, or session
5099    /// configuration. Context the Agent supplies from the workspace or environment
5100    /// MAY still be included. Clients that use this mode take responsibility for any
5101    /// tool guidance or safety instructions the Agent's default instructions
5102    /// provided, and MUST only use it when the Agent advertises
5103    /// `session.systemPrompt.mode.override`.
5104    Override,
5105    /// Custom or future system prompt mode.
5106    ///
5107    /// Values beginning with `_` are reserved for implementation-specific
5108    /// extensions. Unknown values that do not begin with `_` are reserved for
5109    /// future ACP variants.
5110    #[serde(untagged)]
5111    Other(String),
5112}
5113
5114// Prompt
5115
5116/// A key the Client generates to identify one `session/prompt` submission across attempts.
5117///
5118/// The key is an opaque, case-sensitive string of 1 to 255 characters. It is scoped to the
5119/// session named by the request's `sessionId`.
5120///
5121/// See protocol docs: [Retrying a prompt](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#retrying-a-prompt)
5122#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5123#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash, Display)]
5124#[serde(transparent)]
5125pub struct IdempotencyKey(
5126    #[cfg_attr(feature = "schemars", schemars(length(min = 1, max = 255)))] Arc<str>,
5127);
5128
5129impl IdempotencyKey {
5130    /// The maximum length of a key, in characters.
5131    pub const MAX_LENGTH: usize = 255;
5132
5133    /// Wraps a string as a typed [`IdempotencyKey`].
5134    ///
5135    /// # Errors
5136    ///
5137    /// Returns [`InvalidIdempotencyKey`] if the key is empty or longer than
5138    /// [`Self::MAX_LENGTH`] characters.
5139    pub fn new(key: impl Into<Arc<str>>) -> Result<Self, InvalidIdempotencyKey> {
5140        let key = key.into();
5141        if key.is_empty() {
5142            return Err(InvalidIdempotencyKey::Empty);
5143        }
5144        // The limit counts characters, as JSON Schema `maxLength` does, not bytes.
5145        if key.chars().nth(Self::MAX_LENGTH).is_some() {
5146            return Err(InvalidIdempotencyKey::TooLong);
5147        }
5148        Ok(Self(key))
5149    }
5150
5151    /// Generates a key from a random version 4 UUID ([RFC 9562]).
5152    ///
5153    /// Generate one key per submission, when the user submits the input, and store it
5154    /// with the pending input. Every attempt for that submission sends the same key.
5155    ///
5156    /// [RFC 9562]: https://www.rfc-editor.org/rfc/rfc9562
5157    #[cfg(feature = "uuid")]
5158    #[must_use]
5159    pub fn generate() -> Self {
5160        uuid::Uuid::new_v4().into()
5161    }
5162
5163    /// Returns the key as a string slice.
5164    #[must_use]
5165    pub fn as_str(&self) -> &str {
5166        &self.0
5167    }
5168}
5169
5170impl AsRef<str> for IdempotencyKey {
5171    fn as_ref(&self) -> &str {
5172        &self.0
5173    }
5174}
5175
5176#[cfg(feature = "uuid")]
5177impl From<uuid::Uuid> for IdempotencyKey {
5178    /// Uses the UUID's hyphenated lowercase form. It is 36 characters, so it is always a
5179    /// valid key.
5180    fn from(uuid: uuid::Uuid) -> Self {
5181        Self(uuid.to_string().into())
5182    }
5183}
5184
5185impl TryFrom<String> for IdempotencyKey {
5186    type Error = InvalidIdempotencyKey;
5187
5188    fn try_from(key: String) -> Result<Self, Self::Error> {
5189        Self::new(key)
5190    }
5191}
5192
5193impl TryFrom<&str> for IdempotencyKey {
5194    type Error = InvalidIdempotencyKey;
5195
5196    fn try_from(key: &str) -> Result<Self, Self::Error> {
5197        Self::new(key)
5198    }
5199}
5200
5201impl std::str::FromStr for IdempotencyKey {
5202    type Err = InvalidIdempotencyKey;
5203
5204    fn from_str(key: &str) -> Result<Self, Self::Err> {
5205        Self::new(key)
5206    }
5207}
5208
5209// Deserialization validates the key, so a malformed value fails the request
5210// instead of being treated as omitted.
5211impl<'de> Deserialize<'de> for IdempotencyKey {
5212    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
5213    where
5214        D: serde::Deserializer<'de>,
5215    {
5216        let key = Arc::<str>::deserialize(deserializer)?;
5217        Self::new(key).map_err(serde::de::Error::custom)
5218    }
5219}
5220
5221/// Error returned when a string is not a valid [`IdempotencyKey`].
5222#[derive(Debug, Clone, Copy, PartialEq, Eq, Display)]
5223#[non_exhaustive]
5224pub enum InvalidIdempotencyKey {
5225    /// The key is an empty string.
5226    #[display("idempotency key must not be empty")]
5227    Empty,
5228    /// The key is longer than [`IdempotencyKey::MAX_LENGTH`] characters.
5229    #[display(
5230        "idempotency key must be at most {} characters",
5231        IdempotencyKey::MAX_LENGTH
5232    )]
5233    TooLong,
5234}
5235
5236impl std::error::Error for InvalidIdempotencyKey {}
5237
5238/// Request parameters for sending a user prompt to the Agent.
5239///
5240/// Contains the user's message and any additional context.
5241///
5242/// See protocol docs: [User Message](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#1-user-message)
5243#[serde_as]
5244#[skip_serializing_none]
5245#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5246#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5247#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_PROMPT_METHOD_NAME)))]
5248#[serde(rename_all = "camelCase")]
5249#[non_exhaustive]
5250pub struct PromptRequest {
5251    /// The ID of the session to send this user message to
5252    pub session_id: SessionId,
5253    /// The blocks of content that compose the user's message.
5254    ///
5255    /// As a baseline, the Agent MUST support `text` and `resource_link` content blocks,
5256    /// while other variants are optionally enabled via `PromptCapabilities`.
5257    ///
5258    /// The Client MUST adapt its interface according to `PromptCapabilities`.
5259    ///
5260    /// The Client MAY include referenced pieces of context as either
5261    /// `resource` or `resource_link` content blocks.
5262    ///
5263    /// When available, `resource` is preferred
5264    /// as it avoids extra round-trips and allows the message to include
5265    /// pieces of context from sources the Agent might not have access to.
5266    ///
5267    /// Clients MUST NOT send an empty array. Agents MAY reject one with `-32602` without
5268    /// inserting it.
5269    #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
5270    pub prompt: Vec<ContentBlock>,
5271    /// Identifies one prompt submission within this session.
5272    ///
5273    /// Optional. Omitted and `null` are equivalent and mean no key. The Agent then handles
5274    /// the prompt without duplicate detection.
5275    ///
5276    /// The Client generates the key and sends the same key on every attempt for the same
5277    /// submission. Agents that advertise `capabilities.session` MUST support the key.
5278    /// A retry of a recorded insertion returns the original `messageId` without inserting
5279    /// another message.
5280    ///
5281    /// The Agent MUST recognize the key for as long as it retains the message, including
5282    /// across connections and Agent restarts. For a live-only message, it MUST recognize
5283    /// the key while the session stays active on a connection. A retry with a forgotten
5284    /// key is a new submission, even immediately after reconnecting. If a duplicate
5285    /// would matter and the Client cannot rule it out, it SHOULD NOT retry automatically.
5286    ///
5287    /// When present, the value is an opaque, case-sensitive string of 1 to 255 characters.
5288    /// Agents MUST reject any other value with `-32602` (Invalid params) and MUST NOT treat
5289    /// it as omitted.
5290    ///
5291    /// See protocol docs: [Retrying a prompt](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#retrying-a-prompt)
5292    #[serde(default)]
5293    pub idempotency_key: Option<IdempotencyKey>,
5294    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5295    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5296    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5297    ///
5298    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5299    #[serde_as(deserialize_as = "DefaultOnError")]
5300    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5301    #[serde(default)]
5302    #[serde(rename = "_meta")]
5303    pub meta: Option<Meta>,
5304}
5305
5306impl PromptRequest {
5307    /// Builds [`PromptRequest`] with the required request fields set. Optional fields start unset or empty.
5308    #[must_use]
5309    pub fn new(session_id: impl Into<SessionId>, prompt: Vec<ContentBlock>) -> Self {
5310        Self {
5311            session_id: session_id.into(),
5312            prompt,
5313            idempotency_key: None,
5314            meta: None,
5315        }
5316    }
5317
5318    /// Sets the key for this submission. `None` means no key.
5319    ///
5320    /// See protocol docs: [Retrying a prompt](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#retrying-a-prompt)
5321    #[must_use]
5322    pub fn idempotency_key(mut self, idempotency_key: impl IntoOption<IdempotencyKey>) -> Self {
5323        self.idempotency_key = idempotency_key.into_option();
5324        self
5325    }
5326
5327    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5328    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5329    /// do not recognize.
5330    ///
5331    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5332    #[must_use]
5333    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5334        self.meta = meta.into_option();
5335        self
5336    }
5337}
5338
5339/// Response acknowledging that a user prompt was inserted into the ACP conversation.
5340///
5341/// This response does not indicate that the prompt was merely received or held, nor that the
5342/// Agent has finished processing it.
5343/// Processing and completion are reported through `state_update` session updates.
5344///
5345/// Insertion is the logical addition of a user message with a message ID and a position
5346/// relative to other messages in the ACP conversation.
5347///
5348/// See protocol docs: [Prompt Accepted](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#2-prompt-accepted)
5349#[serde_as]
5350#[skip_serializing_none]
5351#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5352#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5353#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_PROMPT_METHOD_NAME)))]
5354#[serde(rename_all = "camelCase")]
5355#[non_exhaustive]
5356pub struct PromptResponse {
5357    /// Identifies the user message inserted into the ACP conversation.
5358    ///
5359    /// Required and non-null. Omission and explicit `null` are both invalid.
5360    ///
5361    /// The corresponding user-message session update carries this same identifier and may arrive
5362    /// before or after this response. Agents MUST echo the message during the live session, but are
5363    /// not required to retain it. If retained and replayed, the message keeps this identifier.
5364    pub message_id: MessageId,
5365    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5366    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5367    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5368    ///
5369    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5370    #[serde_as(deserialize_as = "DefaultOnError")]
5371    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5372    #[serde(default)]
5373    #[serde(rename = "_meta")]
5374    pub meta: Option<Meta>,
5375}
5376
5377impl PromptResponse {
5378    /// Builds [`PromptResponse`] with the required response fields set. Optional fields start unset or empty.
5379    #[must_use]
5380    pub fn new(message_id: impl Into<MessageId>) -> Self {
5381        Self {
5382            message_id: message_id.into(),
5383            meta: None,
5384        }
5385    }
5386
5387    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5388    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5389    /// do not recognize.
5390    ///
5391    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5392    #[must_use]
5393    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5394        self.meta = meta.into_option();
5395        self
5396    }
5397}
5398
5399/// Reasons why an Agent stops active session work.
5400///
5401/// See protocol docs: [Stop Reasons](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#stop-reasons)
5402#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5403#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
5404#[serde(tag = "stopReason", rename_all = "snake_case")]
5405#[non_exhaustive]
5406pub enum StopReason {
5407    /// The active work ended successfully.
5408    /// Includes locally handled commands that required no model call.
5409    EndTurn,
5410    /// The active work ended because the Agent reached the maximum number of tokens.
5411    MaxTokens,
5412    /// The active work ended because the Agent reached the maximum number of
5413    /// model requests for the foreground work.
5414    MaxTurnRequests,
5415    /// The active work ended because the Agent refused to continue.
5416    Refusal,
5417    /// The user or Client chose to stop the work: via `session/cancel`, by
5418    /// closing the session, or through an interaction the Agent offers, such
5419    /// as a permission option that tells the Agent to stop. A child session
5420    /// also reports this reason when its parent cancels its work. Other work
5421    /// the Agent stops for its own reasons uses another reason, such as
5422    /// `error` for an internal timeout.
5423    ///
5424    /// Agents MUST report this stop reason on an idle `state_update` when
5425    /// cancellation ends active foreground work, even if aborting causes
5426    /// exceptions. Agents MUST catch these errors and report `cancelled`, not
5427    /// `error`.
5428    Cancelled,
5429    /// The active work ended because something failed.
5430    ///
5431    /// This includes pre-insertion foreground work. A prompt failure before
5432    /// insertion also requires an error response to `session/prompt`. After
5433    /// insertion, the prompt's response remains successful.
5434    Error(ErrorStopReason),
5435    /// Custom or future stop reason.
5436    ///
5437    /// Values beginning with `_` are reserved for implementation-specific
5438    /// extensions. Unknown values that do not begin with `_` are reserved for
5439    /// future ACP variants.
5440    #[serde(untagged)]
5441    Other(OtherStopReason),
5442}
5443
5444impl From<ErrorStopReason> for StopReason {
5445    fn from(value: ErrorStopReason) -> Self {
5446        Self::Error(value)
5447    }
5448}
5449
5450/// Details of a failure that ended active work.
5451#[serde_as]
5452#[skip_serializing_none]
5453#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5454#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
5455#[serde(rename_all = "camelCase")]
5456#[non_exhaustive]
5457pub struct ErrorStopReason {
5458    /// The failure, as a JSON-RPC error object.
5459    ///
5460    /// Optional. Omitted and `null` are equivalent and mean the Agent is not reporting failure details.
5461    /// Agents SHOULD include it.
5462    #[serde_as(deserialize_as = "DefaultOnError")]
5463    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5464    #[serde(default)]
5465    pub error: Option<Box<Error>>,
5466}
5467
5468impl ErrorStopReason {
5469    /// Builds [`ErrorStopReason`] with the required fields set. Optional fields start unset or empty.
5470    #[must_use]
5471    pub fn new() -> Self {
5472        Self::default()
5473    }
5474
5475    /// The failure, as a JSON-RPC error object.
5476    #[must_use]
5477    pub fn error(mut self, error: impl IntoOption<Error>) -> Self {
5478        self.error = error.into_option().map(Box::new);
5479        self
5480    }
5481}
5482
5483/// Custom or future stop reason payload.
5484#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5485#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
5486#[cfg_attr(feature = "schemars", schemars(inline))]
5487#[cfg_attr(feature = "schemars", schemars(transform = other_stop_reason_schema))]
5488#[serde(rename_all = "camelCase")]
5489#[non_exhaustive]
5490pub struct OtherStopReason {
5491    /// Custom or future stop reason.
5492    ///
5493    /// Values beginning with `_` are reserved for implementation-specific
5494    /// extensions. Unknown values that do not begin with `_` are reserved for
5495    /// future ACP variants.
5496    pub stop_reason: String,
5497    /// Additional fields from the unknown stop reason payload.
5498    #[serde(flatten)]
5499    pub fields: IndexMap<String, serde_json::Value>,
5500}
5501
5502impl OtherStopReason {
5503    /// Builds [`OtherStopReason`] from an unknown discriminator and preserves the remaining extension fields.
5504    #[must_use]
5505    pub fn new(
5506        stop_reason: impl Into<String>,
5507        mut fields: IndexMap<String, serde_json::Value>,
5508    ) -> Self {
5509        remove_idle_state_update_fields(&mut fields);
5510        Self {
5511            stop_reason: stop_reason.into(),
5512            fields,
5513        }
5514    }
5515}
5516
5517impl<'de> Deserialize<'de> for OtherStopReason {
5518    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
5519    where
5520        D: serde::Deserializer<'de>,
5521    {
5522        let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
5523        let stop_reason = fields
5524            .shift_remove("stopReason")
5525            .ok_or_else(|| serde::de::Error::missing_field("stopReason"))?;
5526        let serde_json::Value::String(stop_reason) = stop_reason else {
5527            return Err(serde::de::Error::custom("`stopReason` must be a string"));
5528        };
5529
5530        if KNOWN_STOP_REASONS.contains(&stop_reason.as_str()) {
5531            return Err(serde::de::Error::custom(format!(
5532                "known stop reason `{stop_reason}` did not match its schema"
5533            )));
5534        }
5535        remove_idle_state_update_fields(&mut fields);
5536
5537        Ok(Self {
5538            stop_reason,
5539            fields,
5540        })
5541    }
5542}
5543
5544const KNOWN_STOP_REASONS: &[&str] = &[
5545    "end_turn",
5546    "max_tokens",
5547    "max_turn_requests",
5548    "refusal",
5549    "cancelled",
5550    "error",
5551];
5552
5553/// Keeps the idle update's own fields out of an unknown stop reason's payload.
5554fn remove_idle_state_update_fields(fields: &mut IndexMap<String, serde_json::Value>) {
5555    fields.shift_remove("stopReason");
5556    fields.shift_remove("usage");
5557    fields.shift_remove("_meta");
5558}
5559
5560#[cfg(feature = "schemars")]
5561fn other_stop_reason_schema(schema: &mut Schema) {
5562    super::schema_util::reject_known_string_discriminators(
5563        schema,
5564        "stopReason",
5565        KNOWN_STOP_REASONS,
5566    );
5567}
5568
5569/// **UNSTABLE**
5570///
5571/// This capability is not part of the spec yet, and may be removed or changed at any point.
5572///
5573/// Token usage for the foreground work that just completed, not cumulative for the session.
5574#[cfg(feature = "unstable_end_turn_token_usage")]
5575#[serde_as]
5576#[skip_serializing_none]
5577#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5578#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5579#[serde(rename_all = "camelCase")]
5580#[non_exhaustive]
5581pub struct Usage {
5582    /// Sum of all token types for the completed work.
5583    pub total_tokens: u64,
5584    /// Input tokens for the completed work.
5585    pub input_tokens: u64,
5586    /// Output tokens for the completed work.
5587    pub output_tokens: u64,
5588    /// Thought/reasoning 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 thought_tokens: Option<u64>,
5595    /// Cache read 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_read_tokens: Option<u64>,
5602    /// Cache write tokens for the completed work.
5603    ///
5604    /// Omitted and `null` are equivalent and mean the count is not reported.
5605    #[serde_as(deserialize_as = "DefaultOnError")]
5606    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5607    #[serde(default)]
5608    pub cached_write_tokens: Option<u64>,
5609    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5610    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5611    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5612    ///
5613    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5614    #[serde_as(deserialize_as = "DefaultOnError")]
5615    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5616    #[serde(default)]
5617    #[serde(rename = "_meta")]
5618    pub meta: Option<Meta>,
5619}
5620
5621#[cfg(feature = "unstable_end_turn_token_usage")]
5622impl Usage {
5623    /// Builds [`Usage`] with the required fields set. Optional fields start unset or empty.
5624    #[must_use]
5625    pub fn new(total_tokens: u64, input_tokens: u64, output_tokens: u64) -> Self {
5626        Self {
5627            total_tokens,
5628            input_tokens,
5629            output_tokens,
5630            thought_tokens: None,
5631            cached_read_tokens: None,
5632            cached_write_tokens: None,
5633            meta: None,
5634        }
5635    }
5636
5637    /// Thought/reasoning tokens for the completed work.
5638    #[must_use]
5639    pub fn thought_tokens(mut self, thought_tokens: impl IntoOption<u64>) -> Self {
5640        self.thought_tokens = thought_tokens.into_option();
5641        self
5642    }
5643
5644    /// Cache read tokens for the completed work.
5645    #[must_use]
5646    pub fn cached_read_tokens(mut self, cached_read_tokens: impl IntoOption<u64>) -> Self {
5647        self.cached_read_tokens = cached_read_tokens.into_option();
5648        self
5649    }
5650
5651    /// Cache write tokens for the completed work.
5652    #[must_use]
5653    pub fn cached_write_tokens(mut self, cached_write_tokens: impl IntoOption<u64>) -> Self {
5654        self.cached_write_tokens = cached_write_tokens.into_option();
5655        self
5656    }
5657
5658    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5659    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5660    /// do not recognize.
5661    ///
5662    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5663    #[must_use]
5664    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5665        self.meta = meta.into_option();
5666        self
5667    }
5668}
5669
5670// Providers
5671
5672/// **UNSTABLE**
5673///
5674/// This capability is not part of the spec yet, and may be removed or changed at any point.
5675///
5676/// Well-known API protocol identifiers for LLM providers.
5677///
5678/// Agents and Clients MUST handle unknown protocol identifiers gracefully.
5679///
5680/// Protocol names beginning with `_` are free for custom use, like other ACP extension methods.
5681/// Protocol names that do not begin with `_` are reserved for the ACP spec.
5682#[cfg(feature = "unstable_llm_providers")]
5683#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5684#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5685#[serde(rename_all = "snake_case")]
5686#[non_exhaustive]
5687pub enum LlmProtocol {
5688    /// Anthropic API protocol.
5689    Anthropic,
5690    /// OpenAI API protocol.
5691    #[serde(rename = "openai")]
5692    OpenAi,
5693    /// Azure OpenAI API protocol.
5694    Azure,
5695    /// Google Vertex AI API protocol.
5696    Vertex,
5697    /// AWS Bedrock API protocol.
5698    Bedrock,
5699    /// Custom or future protocol.
5700    ///
5701    /// Values beginning with `_` are reserved for implementation-specific
5702    /// extensions. Unknown values that do not begin with `_` are reserved for
5703    /// future ACP variants.
5704    #[serde(untagged)]
5705    Other(String),
5706}
5707
5708/// **UNSTABLE**
5709///
5710/// This capability is not part of the spec yet, and may be removed or changed at any point.
5711///
5712/// Current effective non-secret routing configuration for a provider.
5713#[cfg(feature = "unstable_llm_providers")]
5714#[serde_as]
5715#[skip_serializing_none]
5716#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5717#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5718#[serde(rename_all = "camelCase")]
5719#[non_exhaustive]
5720pub struct ProviderCurrentConfig {
5721    /// Protocol currently used by this provider.
5722    pub api_type: LlmProtocol,
5723    /// Base URL currently used by this provider.
5724    #[cfg_attr(feature = "schemars", schemars(url))]
5725    pub base_url: String,
5726    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5727    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5728    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5729    ///
5730    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5731    #[serde_as(deserialize_as = "DefaultOnError")]
5732    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5733    #[serde(default)]
5734    #[serde(rename = "_meta")]
5735    pub meta: Option<Meta>,
5736}
5737
5738#[cfg(feature = "unstable_llm_providers")]
5739impl ProviderCurrentConfig {
5740    /// Builds [`ProviderCurrentConfig`] with the required fields set. Optional fields start unset or empty.
5741    #[must_use]
5742    pub fn new(api_type: LlmProtocol, base_url: impl Into<String>) -> Self {
5743        Self {
5744            api_type,
5745            base_url: base_url.into(),
5746            meta: None,
5747        }
5748    }
5749
5750    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5751    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5752    /// do not recognize.
5753    ///
5754    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5755    #[must_use]
5756    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5757        self.meta = meta.into_option();
5758        self
5759    }
5760}
5761
5762/// **UNSTABLE**
5763///
5764/// This capability is not part of the spec yet, and may be removed or changed at any point.
5765///
5766/// Unique identifier for a configurable LLM provider.
5767#[cfg(feature = "unstable_llm_providers")]
5768#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5769#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
5770#[serde(transparent)]
5771#[from(forward)]
5772#[non_exhaustive]
5773pub struct ProviderId(pub Arc<str>);
5774
5775#[cfg(feature = "unstable_llm_providers")]
5776impl ProviderId {
5777    /// Wraps a protocol string as a typed [`ProviderId`].
5778    #[must_use]
5779    pub fn new(id: impl Into<Self>) -> Self {
5780        id.into()
5781    }
5782}
5783
5784/// **UNSTABLE**
5785///
5786/// This capability is not part of the spec yet, and may be removed or changed at any point.
5787///
5788/// Information about a configurable LLM provider.
5789#[cfg(feature = "unstable_llm_providers")]
5790#[serde_as]
5791#[skip_serializing_none]
5792#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5793#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5794#[serde(rename_all = "camelCase")]
5795#[non_exhaustive]
5796pub struct ProviderInfo {
5797    /// Provider identifier, for example "main" or "openai".
5798    pub provider_id: ProviderId,
5799    /// Supported protocol types for this provider.
5800    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
5801    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
5802    pub supported: Vec<LlmProtocol>,
5803    /// Whether this provider is mandatory and cannot be disabled via `providers/disable`.
5804    /// If true, Clients MUST NOT call `providers/disable` for this provider ID.
5805    pub required: bool,
5806    /// Current effective non-secret routing config.
5807    /// Null or omitted means provider is disabled.
5808    #[serde(default)]
5809    pub current: Option<ProviderCurrentConfig>,
5810    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5811    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5812    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5813    ///
5814    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5815    #[serde_as(deserialize_as = "DefaultOnError")]
5816    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5817    #[serde(default)]
5818    #[serde(rename = "_meta")]
5819    pub meta: Option<Meta>,
5820}
5821
5822#[cfg(feature = "unstable_llm_providers")]
5823impl ProviderInfo {
5824    /// Builds [`ProviderInfo`] with the required fields set. Optional fields start unset or empty.
5825    #[must_use]
5826    pub fn new(
5827        provider_id: impl Into<ProviderId>,
5828        supported: Vec<LlmProtocol>,
5829        required: bool,
5830        current: impl IntoOption<ProviderCurrentConfig>,
5831    ) -> Self {
5832        Self {
5833            provider_id: provider_id.into(),
5834            supported,
5835            required,
5836            current: current.into_option(),
5837            meta: None,
5838        }
5839    }
5840
5841    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5842    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5843    /// do not recognize.
5844    ///
5845    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5846    #[must_use]
5847    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5848        self.meta = meta.into_option();
5849        self
5850    }
5851}
5852
5853#[cfg(feature = "unstable_llm_providers")]
5854crate::serde_util::default_on_null! {
5855    /// **UNSTABLE**
5856    ///
5857    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5858    ///
5859    /// Request parameters for `providers/list`.
5860    #[serde_as]
5861    #[skip_serializing_none]
5862    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5863    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
5864    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_LIST_METHOD_NAME)))]
5865    #[serde(rename_all = "camelCase")]
5866    #[non_exhaustive]
5867    pub struct ListProvidersRequest {
5868        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5869        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5870        /// Implementations MUST NOT assign meaning to keys they do not recognize.
5871        ///
5872        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5873        #[serde_as(deserialize_as = "DefaultOnError")]
5874        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5875        #[serde(default)]
5876        #[serde(rename = "_meta")]
5877        pub meta: Option<Meta>,
5878    }
5879}
5880
5881#[cfg(feature = "unstable_llm_providers")]
5882impl ListProvidersRequest {
5883    /// Builds [`ListProvidersRequest`] with the required request fields set. Optional fields start unset or empty.
5884    #[must_use]
5885    pub fn new() -> Self {
5886        Self::default()
5887    }
5888
5889    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5890    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5891    /// do not recognize.
5892    ///
5893    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5894    #[must_use]
5895    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5896        self.meta = meta.into_option();
5897        self
5898    }
5899}
5900
5901/// **UNSTABLE**
5902///
5903/// This capability is not part of the spec yet, and may be removed or changed at any point.
5904///
5905/// Response to `providers/list`.
5906#[cfg(feature = "unstable_llm_providers")]
5907#[serde_as]
5908#[skip_serializing_none]
5909#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5910#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5911#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_LIST_METHOD_NAME)))]
5912#[serde(rename_all = "camelCase")]
5913#[non_exhaustive]
5914pub struct ListProvidersResponse {
5915    /// Configurable providers with current routing info suitable for UI display.
5916    pub providers: Vec<ProviderInfo>,
5917    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5918    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5919    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5920    ///
5921    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5922    #[serde_as(deserialize_as = "DefaultOnError")]
5923    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5924    #[serde(default)]
5925    #[serde(rename = "_meta")]
5926    pub meta: Option<Meta>,
5927}
5928
5929#[cfg(feature = "unstable_llm_providers")]
5930impl ListProvidersResponse {
5931    /// Builds [`ListProvidersResponse`] with the required response fields set. Optional fields start unset or empty.
5932    #[must_use]
5933    pub fn new(providers: Vec<ProviderInfo>) -> Self {
5934        Self {
5935            providers,
5936            meta: None,
5937        }
5938    }
5939
5940    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5941    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5942    /// do not recognize.
5943    ///
5944    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5945    #[must_use]
5946    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5947        self.meta = meta.into_option();
5948        self
5949    }
5950}
5951
5952/// **UNSTABLE**
5953///
5954/// This capability is not part of the spec yet, and may be removed or changed at any point.
5955///
5956/// Request parameters for `providers/set`.
5957///
5958/// Replaces the full configuration for one provider ID.
5959#[cfg(feature = "unstable_llm_providers")]
5960#[serde_as]
5961#[skip_serializing_none]
5962#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5963#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
5964#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_SET_METHOD_NAME)))]
5965#[serde(rename_all = "camelCase")]
5966#[non_exhaustive]
5967pub struct SetProviderRequest {
5968    /// Provider ID to configure.
5969    pub provider_id: ProviderId,
5970    /// Protocol type for this provider.
5971    pub api_type: LlmProtocol,
5972    /// Base URL for requests sent through this provider.
5973    #[cfg_attr(feature = "schemars", schemars(url))]
5974    pub base_url: String,
5975    /// Full headers map for this provider.
5976    /// May include authorization, routing, or other integration-specific headers.
5977    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
5978    pub headers: IndexMap<String, String>,
5979    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5980    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5981    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5982    ///
5983    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5984    #[serde_as(deserialize_as = "DefaultOnError")]
5985    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5986    #[serde(default)]
5987    #[serde(rename = "_meta")]
5988    pub meta: Option<Meta>,
5989}
5990
5991#[cfg(feature = "unstable_llm_providers")]
5992impl SetProviderRequest {
5993    /// Builds [`SetProviderRequest`] with the required request fields set. Optional fields start unset or empty.
5994    #[must_use]
5995    pub fn new(
5996        provider_id: impl Into<ProviderId>,
5997        api_type: LlmProtocol,
5998        base_url: impl Into<String>,
5999    ) -> Self {
6000        Self {
6001            provider_id: provider_id.into(),
6002            api_type,
6003            base_url: base_url.into(),
6004            headers: IndexMap::new(),
6005            meta: None,
6006        }
6007    }
6008
6009    /// Full headers map for this provider.
6010    /// May include authorization, routing, or other integration-specific headers.
6011    #[must_use]
6012    pub fn headers(mut self, headers: IndexMap<String, String>) -> Self {
6013        self.headers = headers;
6014        self
6015    }
6016
6017    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6018    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6019    /// do not recognize.
6020    ///
6021    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6022    #[must_use]
6023    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6024        self.meta = meta.into_option();
6025        self
6026    }
6027}
6028
6029#[cfg(feature = "unstable_llm_providers")]
6030crate::serde_util::default_on_null! {
6031    /// **UNSTABLE**
6032    ///
6033    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6034    ///
6035    /// Response to `providers/set`.
6036    #[serde_as]
6037    #[skip_serializing_none]
6038    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6039    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
6040    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_SET_METHOD_NAME)))]
6041    #[serde(rename_all = "camelCase")]
6042    #[non_exhaustive]
6043    pub struct SetProviderResponse {
6044        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6045        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6046        /// Implementations MUST NOT assign meaning to keys they do not recognize.
6047        ///
6048        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6049        #[serde_as(deserialize_as = "DefaultOnError")]
6050        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6051        #[serde(default)]
6052        #[serde(rename = "_meta")]
6053        pub meta: Option<Meta>,
6054    }
6055}
6056
6057#[cfg(feature = "unstable_llm_providers")]
6058impl SetProviderResponse {
6059    /// Builds [`SetProviderResponse`] with the required response fields set. Optional fields start unset or empty.
6060    #[must_use]
6061    pub fn new() -> Self {
6062        Self::default()
6063    }
6064
6065    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6066    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6067    /// do not recognize.
6068    ///
6069    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6070    #[must_use]
6071    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6072        self.meta = meta.into_option();
6073        self
6074    }
6075}
6076
6077/// **UNSTABLE**
6078///
6079/// This capability is not part of the spec yet, and may be removed or changed at any point.
6080///
6081/// Request parameters for `providers/disable`.
6082#[cfg(feature = "unstable_llm_providers")]
6083#[serde_as]
6084#[skip_serializing_none]
6085#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6086#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6087#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_DISABLE_METHOD_NAME)))]
6088#[serde(rename_all = "camelCase")]
6089#[non_exhaustive]
6090pub struct DisableProviderRequest {
6091    /// Provider ID to disable.
6092    pub provider_id: ProviderId,
6093    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6094    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6095    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6096    ///
6097    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6098    #[serde_as(deserialize_as = "DefaultOnError")]
6099    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6100    #[serde(default)]
6101    #[serde(rename = "_meta")]
6102    pub meta: Option<Meta>,
6103}
6104
6105#[cfg(feature = "unstable_llm_providers")]
6106impl DisableProviderRequest {
6107    /// Builds [`DisableProviderRequest`] with the required request fields set. Optional fields start unset or empty.
6108    #[must_use]
6109    pub fn new(provider_id: impl Into<ProviderId>) -> Self {
6110        Self {
6111            provider_id: provider_id.into(),
6112            meta: None,
6113        }
6114    }
6115
6116    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6117    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6118    /// do not recognize.
6119    ///
6120    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6121    #[must_use]
6122    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6123        self.meta = meta.into_option();
6124        self
6125    }
6126}
6127
6128#[cfg(feature = "unstable_llm_providers")]
6129crate::serde_util::default_on_null! {
6130    /// **UNSTABLE**
6131    ///
6132    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6133    ///
6134    /// Response to `providers/disable`.
6135    #[serde_as]
6136    #[skip_serializing_none]
6137    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6138    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
6139    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_DISABLE_METHOD_NAME)))]
6140    #[serde(rename_all = "camelCase")]
6141    #[non_exhaustive]
6142    pub struct DisableProviderResponse {
6143        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6144        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6145        /// Implementations MUST NOT assign meaning to keys they do not recognize.
6146        ///
6147        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6148        #[serde_as(deserialize_as = "DefaultOnError")]
6149        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6150        #[serde(default)]
6151        #[serde(rename = "_meta")]
6152        pub meta: Option<Meta>,
6153    }
6154}
6155
6156#[cfg(feature = "unstable_llm_providers")]
6157impl DisableProviderResponse {
6158    /// Builds [`DisableProviderResponse`] with the required response fields set. Optional fields start unset or empty.
6159    #[must_use]
6160    pub fn new() -> Self {
6161        Self::default()
6162    }
6163
6164    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6165    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6166    /// do not recognize.
6167    ///
6168    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6169    #[must_use]
6170    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6171        self.meta = meta.into_option();
6172        self
6173    }
6174}
6175
6176// Capabilities
6177
6178/// Capabilities supported by the Agent.
6179///
6180/// Advertised during initialization to inform the Client about
6181/// available features and content types.
6182///
6183/// See protocol docs: [Agent Capabilities](https://agentclientprotocol.com/protocol/v2/initialization#agent-capabilities)
6184#[serde_as]
6185#[skip_serializing_none]
6186#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6187#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6188#[serde(rename_all = "camelCase")]
6189#[non_exhaustive]
6190pub struct AgentCapabilities {
6191    /// Session capabilities supported by the Agent.
6192    ///
6193    /// Optional. Omitted and `null` are equivalent and mean the Agent does not support the
6194    /// `session/*` methods. Supplying `{}` means the Agent supports the
6195    /// baseline session methods: `session/new`, `session/list`,
6196    /// `session/resume`, `session/close`, `session/prompt`, `session/cancel`,
6197    /// and `session/update`.
6198    #[serde_as(deserialize_as = "DefaultOnError")]
6199    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6200    #[serde(default)]
6201    pub session: Option<SessionCapabilities>,
6202    /// Authentication-related extension capabilities supported by the Agent.
6203    ///
6204    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise any
6205    /// authentication-related extensions. This field does not advertise support
6206    /// for `auth/login` or `auth/logout`. Those methods are advertised by a
6207    /// non-empty `authMethods` list in the `initialize` response.
6208    #[serde_as(deserialize_as = "DefaultOnError")]
6209    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6210    #[serde(default)]
6211    pub auth: Option<AgentAuthCapabilities>,
6212    /// **UNSTABLE**
6213    ///
6214    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6215    ///
6216    /// Provider configuration capabilities supported by the Agent.
6217    ///
6218    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6219    /// Supplying `{}` means the Agent supports provider configuration methods.
6220    #[cfg(feature = "unstable_llm_providers")]
6221    #[serde_as(deserialize_as = "DefaultOnError")]
6222    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6223    #[serde(default)]
6224    pub providers: Option<ProvidersCapabilities>,
6225    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6226    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6227    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6228    ///
6229    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6230    #[serde_as(deserialize_as = "DefaultOnError")]
6231    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6232    #[serde(default)]
6233    #[serde(rename = "_meta")]
6234    pub meta: Option<Meta>,
6235}
6236
6237impl AgentCapabilities {
6238    /// Builds an empty [`AgentCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6239    #[must_use]
6240    pub fn new() -> Self {
6241        Self::default()
6242    }
6243
6244    /// Session capabilities supported by the Agent.
6245    ///
6246    /// Omitted and `null` are equivalent and mean the Agent does not support the `session/*`
6247    /// methods. Supplying `{}` means the Agent supports the baseline
6248    /// session methods: `session/new`, `session/list`, `session/resume`,
6249    /// `session/close`, `session/prompt`, `session/cancel`, and
6250    /// `session/update`.
6251    #[must_use]
6252    pub fn session(mut self, session: impl IntoOption<SessionCapabilities>) -> Self {
6253        self.session = session.into_option();
6254        self
6255    }
6256
6257    /// Authentication-related extension capabilities supported by the Agent.
6258    ///
6259    /// This field does not advertise support for `auth/login` or `auth/logout`.
6260    #[must_use]
6261    pub fn auth(mut self, auth: impl IntoOption<AgentAuthCapabilities>) -> Self {
6262        self.auth = auth.into_option();
6263        self
6264    }
6265
6266    /// **UNSTABLE**
6267    ///
6268    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6269    ///
6270    /// Provider configuration capabilities supported by the Agent.
6271    #[cfg(feature = "unstable_llm_providers")]
6272    #[must_use]
6273    pub fn providers(mut self, providers: impl IntoOption<ProvidersCapabilities>) -> Self {
6274        self.providers = providers.into_option();
6275        self
6276    }
6277
6278    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6279    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6280    /// do not recognize.
6281    ///
6282    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6283    #[must_use]
6284    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6285        self.meta = meta.into_option();
6286        self
6287    }
6288}
6289
6290/// **UNSTABLE**
6291///
6292/// This capability is not part of the spec yet, and may be removed or changed at any point.
6293///
6294/// Provider configuration capabilities supported by the Agent.
6295///
6296/// Supplying `{}` means the Agent supports provider configuration methods.
6297#[cfg(feature = "unstable_llm_providers")]
6298#[serde_as]
6299#[skip_serializing_none]
6300#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6301#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6302#[non_exhaustive]
6303pub struct ProvidersCapabilities {
6304    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6305    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6306    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6307    ///
6308    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6309    #[serde_as(deserialize_as = "DefaultOnError")]
6310    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6311    #[serde(default)]
6312    #[serde(rename = "_meta")]
6313    pub meta: Option<Meta>,
6314}
6315
6316#[cfg(feature = "unstable_llm_providers")]
6317impl ProvidersCapabilities {
6318    /// Builds an empty [`ProvidersCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6319    #[must_use]
6320    pub fn new() -> Self {
6321        Self::default()
6322    }
6323
6324    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6325    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6326    /// do not recognize.
6327    ///
6328    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6329    #[must_use]
6330    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6331        self.meta = meta.into_option();
6332        self
6333    }
6334}
6335
6336/// Session capabilities supported by the Agent.
6337///
6338/// Supplying `{}` means the Agent supports the baseline session methods:
6339/// `session/new`, `session/list`, `session/resume`, `session/close`,
6340/// `session/prompt`, `session/cancel`, and `session/update`.
6341///
6342/// Agents that support sessions MAY support additional session methods,
6343/// prompt content types, and MCP transports by specifying additional
6344/// capabilities.
6345///
6346/// See protocol docs: [Session Capabilities](https://agentclientprotocol.com/protocol/v2/initialization#session-capabilities)
6347#[serde_as]
6348#[skip_serializing_none]
6349#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6350#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6351#[serde(rename_all = "camelCase")]
6352#[non_exhaustive]
6353pub struct SessionCapabilities {
6354    /// Prompt capabilities supported by the Agent in `session/prompt` requests.
6355    ///
6356    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise any
6357    /// prompt extensions beyond the baseline text and resource-link content
6358    /// required by `session/prompt`.
6359    #[serde_as(deserialize_as = "DefaultOnError")]
6360    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6361    #[serde(default)]
6362    pub prompt: Option<PromptCapabilities>,
6363    /// MCP capabilities supported by the Agent for session lifecycle requests.
6364    ///
6365    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise MCP
6366    /// server transport support for sessions.
6367    #[serde_as(deserialize_as = "DefaultOnError")]
6368    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6369    #[serde(default)]
6370    pub mcp: Option<McpCapabilities>,
6371    /// Whether the Agent supports `session/delete`.
6372    ///
6373    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6374    /// Supplying `{}` means the Agent supports deleting sessions from `session/list`.
6375    #[serde_as(deserialize_as = "DefaultOnError")]
6376    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6377    #[serde(default)]
6378    pub delete: Option<SessionDeleteCapabilities>,
6379    /// Whether the Agent supports `additionalDirectories` on supported session lifecycle requests.
6380    ///
6381    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6382    /// Supplying `{}` means the Agent supports `additionalDirectories` on
6383    /// supported session lifecycle requests.
6384    ///
6385    /// Agents MAY return `SessionInfo.additionalDirectories` to report the
6386    /// complete ordered additional-root list associated with a listed session.
6387    #[serde_as(deserialize_as = "DefaultOnError")]
6388    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6389    #[serde(default)]
6390    pub additional_directories: Option<SessionAdditionalDirectoriesCapabilities>,
6391    /// Whether the Agent supports `systemPrompt` on session lifecycle requests.
6392    ///
6393    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6394    /// Supplying `{}` means the Agent supports `systemPrompt` in `append` mode.
6395    #[serde_as(deserialize_as = "DefaultOnError")]
6396    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6397    #[serde(default)]
6398    pub system_prompt: Option<SessionSystemPromptCapabilities>,
6399    /// **UNSTABLE**
6400    ///
6401    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6402    ///
6403    /// Whether the Agent supports `session/fork`.
6404    ///
6405    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6406    /// Supplying `{}` means the Agent supports forking sessions.
6407    #[cfg(feature = "unstable_session_fork")]
6408    #[serde_as(deserialize_as = "DefaultOnError")]
6409    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6410    #[serde(default)]
6411    pub fork: Option<SessionForkCapabilities>,
6412    /// **UNSTABLE**
6413    ///
6414    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6415    ///
6416    /// Whether the Agent supports `session/archive` and `session/unarchive`.
6417    ///
6418    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6419    /// Supplying `{}` means the Agent supports both methods, the `archived` filter on
6420    /// `session/list`, and `SessionInfo.archived`.
6421    #[cfg(feature = "unstable_session_archive")]
6422    #[serde_as(deserialize_as = "DefaultOnError")]
6423    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6424    #[serde(default)]
6425    pub archive: Option<SessionArchiveCapabilities>,
6426    /// **UNSTABLE**
6427    ///
6428    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6429    ///
6430    /// Whether the Agent supports `session/status`.
6431    ///
6432    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6433    /// Supplying `{}` means the Agent supports checking session status.
6434    #[cfg(feature = "unstable_session_status")]
6435    #[serde_as(deserialize_as = "DefaultOnError")]
6436    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6437    #[serde(default)]
6438    pub status: Option<SessionStatusCapabilities>,
6439    /// **UNSTABLE**
6440    ///
6441    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6442    ///
6443    /// Whether the Agent supports `session/options`.
6444    ///
6445    /// Optional. Omitted or `null` both mean the Agent does not advertise support.
6446    /// Supplying `{}` means the Agent supports `session/options` and accepts initial
6447    /// config option values on session setup requests.
6448    #[cfg(feature = "unstable_session_options")]
6449    #[serde_as(deserialize_as = "DefaultOnError")]
6450    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6451    #[serde(default)]
6452    pub options: Option<SessionOptionsCapabilities>,
6453    /// **UNSTABLE**
6454    ///
6455    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6456    ///
6457    /// Whether the Agent supports `session/set_title`.
6458    ///
6459    /// Agents report titles through `session/list` and `session_info_update` without this
6460    /// capability. It only advertises that Clients can set titles.
6461    ///
6462    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6463    /// Supplying `{}` means the Agent supports setting session titles.
6464    #[cfg(feature = "unstable_session_set_title")]
6465    #[serde_as(deserialize_as = "DefaultOnError")]
6466    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6467    #[serde(default)]
6468    pub title: Option<SessionTitleCapabilities>,
6469    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6470    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6471    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6472    ///
6473    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6474    #[serde_as(deserialize_as = "DefaultOnError")]
6475    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6476    #[serde(default)]
6477    #[serde(rename = "_meta")]
6478    pub meta: Option<Meta>,
6479}
6480
6481impl SessionCapabilities {
6482    /// Builds an empty [`SessionCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6483    #[must_use]
6484    pub fn new() -> Self {
6485        Self::default()
6486    }
6487
6488    /// Prompt capabilities supported by the Agent in `session/prompt` requests.
6489    ///
6490    /// Omitted and `null` are equivalent and mean the Agent does not advertise any prompt
6491    /// extensions beyond the baseline text and resource-link content required by
6492    /// `session/prompt`.
6493    #[must_use]
6494    pub fn prompt(mut self, prompt: impl IntoOption<PromptCapabilities>) -> Self {
6495        self.prompt = prompt.into_option();
6496        self
6497    }
6498
6499    /// MCP capabilities supported by the Agent for session lifecycle requests.
6500    ///
6501    /// Omitted and `null` are equivalent and mean the Agent does not advertise MCP server
6502    /// transport support for sessions.
6503    #[must_use]
6504    pub fn mcp(mut self, mcp: impl IntoOption<McpCapabilities>) -> Self {
6505        self.mcp = mcp.into_option();
6506        self
6507    }
6508
6509    /// Whether the Agent supports `session/delete`.
6510    ///
6511    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
6512    /// Supplying `{}` means the Agent supports deleting sessions from `session/list`.
6513    #[must_use]
6514    pub fn delete(mut self, delete: impl IntoOption<SessionDeleteCapabilities>) -> Self {
6515        self.delete = delete.into_option();
6516        self
6517    }
6518
6519    /// Whether the Agent supports `additionalDirectories` on supported session lifecycle requests.
6520    ///
6521    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
6522    /// Supplying `{}` means the Agent supports `additionalDirectories` on
6523    /// supported session lifecycle requests.
6524    ///
6525    /// Agents MAY return `SessionInfo.additionalDirectories` to report the
6526    /// complete ordered additional-root list associated with a listed session.
6527    #[must_use]
6528    pub fn additional_directories(
6529        mut self,
6530        additional_directories: impl IntoOption<SessionAdditionalDirectoriesCapabilities>,
6531    ) -> Self {
6532        self.additional_directories = additional_directories.into_option();
6533        self
6534    }
6535
6536    /// Whether the Agent supports `systemPrompt` on session lifecycle requests.
6537    ///
6538    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
6539    /// Supplying `{}` means the Agent supports `systemPrompt` in `append` mode.
6540    #[must_use]
6541    pub fn system_prompt(
6542        mut self,
6543        system_prompt: impl IntoOption<SessionSystemPromptCapabilities>,
6544    ) -> Self {
6545        self.system_prompt = system_prompt.into_option();
6546        self
6547    }
6548
6549    #[cfg(feature = "unstable_session_fork")]
6550    /// Whether the Agent supports `session/fork`.
6551    ///
6552    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
6553    /// Supplying `{}` means the Agent supports forking sessions.
6554    #[must_use]
6555    pub fn fork(mut self, fork: impl IntoOption<SessionForkCapabilities>) -> Self {
6556        self.fork = fork.into_option();
6557        self
6558    }
6559
6560    /// **UNSTABLE**
6561    ///
6562    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6563    ///
6564    /// Whether the Agent supports `session/archive` and `session/unarchive`.
6565    ///
6566    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
6567    /// Supplying `{}` means the Agent supports both methods, the `archived` filter on
6568    /// `session/list`, and `SessionInfo.archived`.
6569    #[cfg(feature = "unstable_session_archive")]
6570    #[must_use]
6571    pub fn archive(mut self, archive: impl IntoOption<SessionArchiveCapabilities>) -> Self {
6572        self.archive = archive.into_option();
6573        self
6574    }
6575
6576    /// **UNSTABLE**
6577    ///
6578    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6579    ///
6580    /// Whether the Agent supports `session/status`.
6581    ///
6582    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
6583    /// Supplying `{}` means the Agent supports checking session status.
6584    #[cfg(feature = "unstable_session_status")]
6585    #[must_use]
6586    pub fn status(mut self, status: impl IntoOption<SessionStatusCapabilities>) -> Self {
6587        self.status = status.into_option();
6588        self
6589    }
6590
6591    /// **UNSTABLE**
6592    ///
6593    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6594    ///
6595    /// Whether the Agent supports `session/options`.
6596    ///
6597    /// Omitted or `null` both mean the Agent does not advertise support.
6598    /// Supplying `{}` means the Agent supports `session/options` and accepts initial
6599    /// config option values on session setup requests.
6600    #[cfg(feature = "unstable_session_options")]
6601    #[must_use]
6602    pub fn options(mut self, options: impl IntoOption<SessionOptionsCapabilities>) -> Self {
6603        self.options = options.into_option();
6604        self
6605    }
6606
6607    /// **UNSTABLE**
6608    ///
6609    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6610    ///
6611    /// Whether the Agent supports `session/set_title`.
6612    ///
6613    /// Agents report titles through `session/list` and `session_info_update` without this
6614    /// capability. It only advertises that Clients can set titles.
6615    ///
6616    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
6617    /// Supplying `{}` means the Agent supports setting session titles.
6618    #[cfg(feature = "unstable_session_set_title")]
6619    #[must_use]
6620    pub fn title(mut self, title: impl IntoOption<SessionTitleCapabilities>) -> Self {
6621        self.title = title.into_option();
6622        self
6623    }
6624
6625    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6626    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6627    /// do not recognize.
6628    ///
6629    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6630    #[must_use]
6631    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6632        self.meta = meta.into_option();
6633        self
6634    }
6635}
6636
6637/// Capabilities for the `session/delete` method.
6638///
6639/// Supplying `{}` means the Agent supports deleting sessions from `session/list`.
6640#[serde_as]
6641#[skip_serializing_none]
6642#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6643#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6644#[non_exhaustive]
6645pub struct SessionDeleteCapabilities {
6646    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6647    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6648    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6649    ///
6650    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6651    #[serde_as(deserialize_as = "DefaultOnError")]
6652    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6653    #[serde(default)]
6654    #[serde(rename = "_meta")]
6655    pub meta: Option<Meta>,
6656}
6657
6658impl SessionDeleteCapabilities {
6659    /// Builds an empty [`SessionDeleteCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6660    #[must_use]
6661    pub fn new() -> Self {
6662        Self::default()
6663    }
6664
6665    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6666    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6667    /// do not recognize.
6668    ///
6669    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6670    #[must_use]
6671    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6672        self.meta = meta.into_option();
6673        self
6674    }
6675}
6676
6677/// Capabilities for additional session directories support.
6678///
6679/// Supplying `{}` means the Agent supports the `additionalDirectories` field on
6680/// supported session lifecycle requests. Agents MAY return
6681/// `SessionInfo.additionalDirectories` in `session/list` to report the
6682/// complete ordered additional-root list associated with a listed session.
6683#[serde_as]
6684#[skip_serializing_none]
6685#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6686#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6687#[non_exhaustive]
6688pub struct SessionAdditionalDirectoriesCapabilities {
6689    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6690    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6691    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6692    ///
6693    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6694    #[serde_as(deserialize_as = "DefaultOnError")]
6695    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6696    #[serde(default)]
6697    #[serde(rename = "_meta")]
6698    pub meta: Option<Meta>,
6699}
6700
6701impl SessionAdditionalDirectoriesCapabilities {
6702    /// Builds an empty [`SessionAdditionalDirectoriesCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6703    #[must_use]
6704    pub fn new() -> Self {
6705        Self::default()
6706    }
6707
6708    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6709    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6710    /// do not recognize.
6711    ///
6712    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6713    #[must_use]
6714    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6715        self.meta = meta.into_option();
6716        self
6717    }
6718}
6719
6720/// Capabilities for Client-provided system prompts.
6721///
6722/// Supplying `{}` means the Agent supports `systemPrompt` on session lifecycle
6723/// requests in `append` mode.
6724#[serde_as]
6725#[skip_serializing_none]
6726#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6727#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6728#[serde(rename_all = "camelCase")]
6729#[non_exhaustive]
6730pub struct SessionSystemPromptCapabilities {
6731    /// Delivery modes the Agent supports in addition to `append`.
6732    ///
6733    /// Optional. Omitted and `null` are equivalent and mean the Agent supports only `append`.
6734    #[serde_as(deserialize_as = "DefaultOnError")]
6735    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6736    #[serde(default)]
6737    pub mode: Option<SessionSystemPromptModeCapabilities>,
6738    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6739    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6740    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6741    ///
6742    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6743    #[serde_as(deserialize_as = "DefaultOnError")]
6744    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6745    #[serde(default)]
6746    #[serde(rename = "_meta")]
6747    pub meta: Option<Meta>,
6748}
6749
6750impl SessionSystemPromptCapabilities {
6751    /// Builds an empty [`SessionSystemPromptCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6752    #[must_use]
6753    pub fn new() -> Self {
6754        Self::default()
6755    }
6756
6757    /// Delivery modes the Agent supports in addition to `append`.
6758    ///
6759    /// Omitted and `null` are equivalent and mean the Agent supports only `append`.
6760    #[must_use]
6761    pub fn mode(mut self, mode: impl IntoOption<SessionSystemPromptModeCapabilities>) -> Self {
6762        self.mode = mode.into_option();
6763        self
6764    }
6765
6766    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6767    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6768    /// do not recognize.
6769    ///
6770    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6771    #[must_use]
6772    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6773        self.meta = meta.into_option();
6774        self
6775    }
6776}
6777
6778/// System prompt delivery modes the Agent supports in addition to `append`.
6779///
6780/// `append` has no entry because every Agent advertising `session.systemPrompt`
6781/// supports it.
6782#[serde_as]
6783#[skip_serializing_none]
6784#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6785#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6786#[serde(rename_all = "camelCase")]
6787#[non_exhaustive]
6788pub struct SessionSystemPromptModeCapabilities {
6789    /// Whether the Agent supports `override` mode.
6790    ///
6791    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6792    /// Supplying `{}` means the Agent supports replacing its built-in default
6793    /// instructions with the Client-provided system prompt.
6794    #[serde_as(deserialize_as = "DefaultOnError")]
6795    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6796    #[serde(default, rename = "override")]
6797    pub override_: Option<SessionSystemPromptOverrideCapabilities>,
6798    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6799    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6800    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6801    ///
6802    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6803    #[serde_as(deserialize_as = "DefaultOnError")]
6804    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6805    #[serde(default)]
6806    #[serde(rename = "_meta")]
6807    pub meta: Option<Meta>,
6808}
6809
6810impl SessionSystemPromptModeCapabilities {
6811    /// Builds an empty [`SessionSystemPromptModeCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6812    #[must_use]
6813    pub fn new() -> Self {
6814        Self::default()
6815    }
6816
6817    /// Whether the Agent supports `override` mode.
6818    ///
6819    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
6820    /// Supplying `{}` means the Agent supports replacing its built-in default
6821    /// instructions with the Client-provided system prompt.
6822    #[must_use]
6823    pub fn override_(
6824        mut self,
6825        override_: impl IntoOption<SessionSystemPromptOverrideCapabilities>,
6826    ) -> Self {
6827        self.override_ = override_.into_option();
6828        self
6829    }
6830
6831    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6832    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6833    /// do not recognize.
6834    ///
6835    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6836    #[must_use]
6837    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6838        self.meta = meta.into_option();
6839        self
6840    }
6841}
6842
6843/// Capabilities for the `override` system prompt mode.
6844///
6845/// Supplying `{}` means the Agent supports replacing its built-in default
6846/// instructions with the Client-provided system prompt.
6847#[serde_as]
6848#[skip_serializing_none]
6849#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6850#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6851#[non_exhaustive]
6852pub struct SessionSystemPromptOverrideCapabilities {
6853    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6854    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6855    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6856    ///
6857    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6858    #[serde_as(deserialize_as = "DefaultOnError")]
6859    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6860    #[serde(default)]
6861    #[serde(rename = "_meta")]
6862    pub meta: Option<Meta>,
6863}
6864
6865impl SessionSystemPromptOverrideCapabilities {
6866    /// Builds an empty [`SessionSystemPromptOverrideCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6867    #[must_use]
6868    pub fn new() -> Self {
6869        Self::default()
6870    }
6871
6872    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6873    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6874    /// do not recognize.
6875    ///
6876    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6877    #[must_use]
6878    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6879        self.meta = meta.into_option();
6880        self
6881    }
6882}
6883
6884/// **UNSTABLE**
6885///
6886/// This capability is not part of the spec yet, and may be removed or changed at any point.
6887///
6888/// Capabilities for the `session/fork` method.
6889///
6890/// Supplying `{}` means the Agent supports forking sessions.
6891#[cfg(feature = "unstable_session_fork")]
6892#[serde_as]
6893#[skip_serializing_none]
6894#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6895#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6896#[non_exhaustive]
6897pub struct SessionForkCapabilities {
6898    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6899    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6900    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6901    ///
6902    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6903    #[serde_as(deserialize_as = "DefaultOnError")]
6904    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6905    #[serde(default)]
6906    #[serde(rename = "_meta")]
6907    pub meta: Option<Meta>,
6908}
6909
6910#[cfg(feature = "unstable_session_fork")]
6911impl SessionForkCapabilities {
6912    /// Builds an empty [`SessionForkCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6913    #[must_use]
6914    pub fn new() -> Self {
6915        Self::default()
6916    }
6917
6918    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6919    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6920    /// do not recognize.
6921    ///
6922    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6923    #[must_use]
6924    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6925        self.meta = meta.into_option();
6926        self
6927    }
6928}
6929
6930/// **UNSTABLE**
6931///
6932/// This capability is not part of the spec yet, and may be removed or changed at any point.
6933///
6934/// Capabilities for `session/archive` and `session/unarchive`.
6935///
6936/// Supplying `{}` means the Agent supports both methods, the `archived` filter on
6937/// `session/list`, and `SessionInfo.archived`.
6938#[cfg(feature = "unstable_session_archive")]
6939#[serde_as]
6940#[skip_serializing_none]
6941#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6942#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6943#[non_exhaustive]
6944pub struct SessionArchiveCapabilities {
6945    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6946    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6947    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6948    ///
6949    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6950    #[serde_as(deserialize_as = "DefaultOnError")]
6951    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6952    #[serde(default)]
6953    #[serde(rename = "_meta")]
6954    pub meta: Option<Meta>,
6955}
6956
6957#[cfg(feature = "unstable_session_archive")]
6958impl SessionArchiveCapabilities {
6959    /// Builds an empty [`SessionArchiveCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6960    #[must_use]
6961    pub fn new() -> Self {
6962        Self::default()
6963    }
6964
6965    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6966    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6967    /// do not recognize.
6968    ///
6969    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6970    #[must_use]
6971    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6972        self.meta = meta.into_option();
6973        self
6974    }
6975}
6976
6977/// **UNSTABLE**
6978///
6979/// This capability is not part of the spec yet, and may be removed or changed at any point.
6980///
6981/// Capabilities for the `session/status` method.
6982///
6983/// Supplying `{}` means the Agent supports checking session status.
6984#[cfg(feature = "unstable_session_status")]
6985#[serde_as]
6986#[skip_serializing_none]
6987#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6988#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6989#[non_exhaustive]
6990pub struct SessionStatusCapabilities {
6991    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6992    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6993    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6994    ///
6995    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6996    #[serde_as(deserialize_as = "DefaultOnError")]
6997    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6998    #[serde(default)]
6999    #[serde(rename = "_meta")]
7000    pub meta: Option<Meta>,
7001}
7002
7003#[cfg(feature = "unstable_session_status")]
7004impl SessionStatusCapabilities {
7005    /// Builds an empty [`SessionStatusCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7006    #[must_use]
7007    pub fn new() -> Self {
7008        Self::default()
7009    }
7010
7011    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7012    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7013    /// do not recognize.
7014    ///
7015    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7016    #[must_use]
7017    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7018        self.meta = meta.into_option();
7019        self
7020    }
7021}
7022
7023/// **UNSTABLE**
7024///
7025/// This capability is not part of the spec yet, and may be removed or changed at any point.
7026///
7027/// Capabilities for the `session/options` method.
7028///
7029/// Supplying `{}` means the Agent supports `session/options` and accepts initial config
7030/// option values on session setup requests.
7031#[cfg(feature = "unstable_session_options")]
7032#[serde_as]
7033#[skip_serializing_none]
7034#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7035#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7036#[non_exhaustive]
7037pub struct SessionOptionsCapabilities {
7038    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7039    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7040    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7041    ///
7042    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7043    #[serde_as(deserialize_as = "DefaultOnError")]
7044    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7045    #[serde(default)]
7046    #[serde(rename = "_meta")]
7047    pub meta: Option<Meta>,
7048}
7049
7050#[cfg(feature = "unstable_session_options")]
7051impl SessionOptionsCapabilities {
7052    /// Builds an empty [`SessionOptionsCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7053    #[must_use]
7054    pub fn new() -> Self {
7055        Self::default()
7056    }
7057
7058    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7059    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7060    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7061    ///
7062    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7063    #[must_use]
7064    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7065        self.meta = meta.into_option();
7066        self
7067    }
7068}
7069
7070/// **UNSTABLE**
7071///
7072/// This capability is not part of the spec yet, and may be removed or changed at any point.
7073///
7074/// Capabilities for Client-set session titles.
7075///
7076/// Supplying `{}` means the Agent supports `session/set_title`. Agents report titles
7077/// through `session/list` and `session_info_update` without this capability.
7078#[cfg(feature = "unstable_session_set_title")]
7079#[serde_as]
7080#[skip_serializing_none]
7081#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7082#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7083#[non_exhaustive]
7084pub struct SessionTitleCapabilities {
7085    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7086    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7087    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7088    ///
7089    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7090    #[serde_as(deserialize_as = "DefaultOnError")]
7091    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7092    #[serde(default)]
7093    #[serde(rename = "_meta")]
7094    pub meta: Option<Meta>,
7095}
7096
7097#[cfg(feature = "unstable_session_set_title")]
7098impl SessionTitleCapabilities {
7099    /// Builds an empty [`SessionTitleCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7100    #[must_use]
7101    pub fn new() -> Self {
7102        Self::default()
7103    }
7104
7105    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7106    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7107    /// do not recognize.
7108    ///
7109    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7110    #[must_use]
7111    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7112        self.meta = meta.into_option();
7113        self
7114    }
7115}
7116
7117/// Prompt capabilities supported by the Agent in `session/prompt` requests.
7118///
7119/// Baseline Agent functionality requires support for `text`
7120/// and `resource_link` content blocks in prompt requests.
7121///
7122/// Other content types need one of these capabilities.
7123/// Capabilities for different types of content in prompt requests.
7124///
7125/// Indicates which content types beyond the baseline (text and resource links)
7126/// the Agent can process.
7127///
7128/// See protocol docs: [Session Prompt Capabilities](https://agentclientprotocol.com/protocol/v2/initialization#session-prompt-capabilities)
7129#[serde_as]
7130#[skip_serializing_none]
7131#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7132#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7133#[serde(rename_all = "camelCase")]
7134#[non_exhaustive]
7135pub struct PromptCapabilities {
7136    /// Agent supports `image` content blocks.
7137    ///
7138    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
7139    /// Supplying `{}` means the Agent supports image content in prompts.
7140    #[serde_as(deserialize_as = "DefaultOnError")]
7141    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7142    #[serde(default)]
7143    pub image: Option<PromptImageCapabilities>,
7144    /// Agent supports `audio` content blocks.
7145    ///
7146    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
7147    /// Supplying `{}` means the Agent supports audio content in prompts.
7148    #[serde_as(deserialize_as = "DefaultOnError")]
7149    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7150    #[serde(default)]
7151    pub audio: Option<PromptAudioCapabilities>,
7152    /// Agent supports embedded context in `session/prompt` requests.
7153    ///
7154    /// When enabled, the Client is allowed to include `resource` content blocks
7155    /// in prompt requests for pieces of context that are referenced in the message.
7156    ///
7157    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
7158    /// Supplying `{}` means the Agent supports embedded context in prompts.
7159    #[serde_as(deserialize_as = "DefaultOnError")]
7160    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7161    #[serde(default)]
7162    pub embedded_context: Option<PromptEmbeddedContextCapabilities>,
7163    /// **UNSTABLE**
7164    ///
7165    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7166    ///
7167    /// Agent supports `skill` content blocks.
7168    ///
7169    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
7170    /// Supplying `{}` means a prompt may contain one `skill` content block, as its first block.
7171    /// An Agent that sends `skill` entries in `availableCommands` MUST advertise this capability.
7172    #[cfg(feature = "unstable_agent_skills")]
7173    #[serde_as(deserialize_as = "DefaultOnError")]
7174    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7175    #[serde(default)]
7176    pub skill: Option<PromptSkillCapabilities>,
7177    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7178    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7179    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7180    ///
7181    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7182    #[serde_as(deserialize_as = "DefaultOnError")]
7183    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7184    #[serde(default)]
7185    #[serde(rename = "_meta")]
7186    pub meta: Option<Meta>,
7187}
7188
7189impl PromptCapabilities {
7190    /// Builds an empty [`PromptCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7191    #[must_use]
7192    pub fn new() -> Self {
7193        Self::default()
7194    }
7195
7196    /// Agent supports `image` content blocks.
7197    ///
7198    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
7199    /// Supplying `{}` means the Agent supports image content in prompts.
7200    #[must_use]
7201    pub fn image(mut self, image: impl IntoOption<PromptImageCapabilities>) -> Self {
7202        self.image = image.into_option();
7203        self
7204    }
7205
7206    /// Agent supports `audio` content blocks.
7207    ///
7208    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
7209    /// Supplying `{}` means the Agent supports audio content in prompts.
7210    #[must_use]
7211    pub fn audio(mut self, audio: impl IntoOption<PromptAudioCapabilities>) -> Self {
7212        self.audio = audio.into_option();
7213        self
7214    }
7215
7216    /// Agent supports embedded context in `session/prompt` requests.
7217    ///
7218    /// When enabled, the Client is allowed to include `resource` content blocks
7219    /// in prompt requests for pieces of context that are referenced in the message.
7220    ///
7221    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
7222    /// Supplying `{}` means the Agent supports embedded context in prompts.
7223    #[must_use]
7224    pub fn embedded_context(
7225        mut self,
7226        embedded_context: impl IntoOption<PromptEmbeddedContextCapabilities>,
7227    ) -> Self {
7228        self.embedded_context = embedded_context.into_option();
7229        self
7230    }
7231
7232    /// **UNSTABLE**
7233    ///
7234    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7235    ///
7236    /// Agent supports `skill` content blocks.
7237    ///
7238    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
7239    /// Supplying `{}` means a prompt may contain one `skill` content block, as its first block.
7240    #[cfg(feature = "unstable_agent_skills")]
7241    #[must_use]
7242    pub fn skill(mut self, skill: impl IntoOption<PromptSkillCapabilities>) -> Self {
7243        self.skill = skill.into_option();
7244        self
7245    }
7246
7247    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7248    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7249    /// do not recognize.
7250    ///
7251    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7252    #[must_use]
7253    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7254        self.meta = meta.into_option();
7255        self
7256    }
7257}
7258
7259/// Capabilities for image content in prompt requests.
7260///
7261/// Supplying `{}` means the Agent supports image content in prompts.
7262#[serde_as]
7263#[skip_serializing_none]
7264#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7265#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7266#[non_exhaustive]
7267pub struct PromptImageCapabilities {
7268    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7269    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7270    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7271    ///
7272    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7273    #[serde_as(deserialize_as = "DefaultOnError")]
7274    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7275    #[serde(default)]
7276    #[serde(rename = "_meta")]
7277    pub meta: Option<Meta>,
7278}
7279
7280impl PromptImageCapabilities {
7281    /// Builds an empty [`PromptImageCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7282    #[must_use]
7283    pub fn new() -> Self {
7284        Self::default()
7285    }
7286
7287    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7288    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7289    /// do not recognize.
7290    ///
7291    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7292    #[must_use]
7293    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7294        self.meta = meta.into_option();
7295        self
7296    }
7297}
7298
7299/// Capabilities for audio content in prompt requests.
7300///
7301/// Supplying `{}` means the Agent supports audio content in prompts.
7302#[serde_as]
7303#[skip_serializing_none]
7304#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7305#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7306#[non_exhaustive]
7307pub struct PromptAudioCapabilities {
7308    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7309    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7310    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7311    ///
7312    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7313    #[serde_as(deserialize_as = "DefaultOnError")]
7314    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7315    #[serde(default)]
7316    #[serde(rename = "_meta")]
7317    pub meta: Option<Meta>,
7318}
7319
7320impl PromptAudioCapabilities {
7321    /// Builds an empty [`PromptAudioCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7322    #[must_use]
7323    pub fn new() -> Self {
7324        Self::default()
7325    }
7326
7327    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7328    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7329    /// do not recognize.
7330    ///
7331    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7332    #[must_use]
7333    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7334        self.meta = meta.into_option();
7335        self
7336    }
7337}
7338
7339/// Capabilities for embedded context in prompt requests.
7340///
7341/// Supplying `{}` means the Agent supports embedded context in prompts.
7342#[serde_as]
7343#[skip_serializing_none]
7344#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7345#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7346#[non_exhaustive]
7347pub struct PromptEmbeddedContextCapabilities {
7348    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7349    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7350    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7351    ///
7352    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7353    #[serde_as(deserialize_as = "DefaultOnError")]
7354    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7355    #[serde(default)]
7356    #[serde(rename = "_meta")]
7357    pub meta: Option<Meta>,
7358}
7359
7360impl PromptEmbeddedContextCapabilities {
7361    /// Builds an empty [`PromptEmbeddedContextCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7362    #[must_use]
7363    pub fn new() -> Self {
7364        Self::default()
7365    }
7366
7367    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7368    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7369    /// do not recognize.
7370    ///
7371    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7372    #[must_use]
7373    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7374        self.meta = meta.into_option();
7375        self
7376    }
7377}
7378
7379/// **UNSTABLE**
7380///
7381/// This capability is not part of the spec yet, and may be removed or changed at any point.
7382///
7383/// Capabilities for `skill` content blocks in prompt requests.
7384///
7385/// Supplying `{}` means a prompt may contain one `skill` content block, as
7386/// its first block. The Agent opts in to more with the `inline` field.
7387#[cfg(feature = "unstable_agent_skills")]
7388#[serde_as]
7389#[skip_serializing_none]
7390#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7391#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7392#[serde(rename_all = "camelCase")]
7393#[non_exhaustive]
7394pub struct PromptSkillCapabilities {
7395    /// Agent supports `skill` content blocks at any position in a prompt.
7396    ///
7397    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
7398    /// Supplying `{}` means a prompt may contain any number of `skill` content blocks, at any
7399    /// position.
7400    #[serde_as(deserialize_as = "DefaultOnError")]
7401    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7402    #[serde(default)]
7403    pub inline: Option<PromptSkillInlineCapabilities>,
7404    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7405    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7406    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7407    ///
7408    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7409    #[serde_as(deserialize_as = "DefaultOnError")]
7410    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7411    #[serde(default)]
7412    #[serde(rename = "_meta")]
7413    pub meta: Option<Meta>,
7414}
7415
7416#[cfg(feature = "unstable_agent_skills")]
7417impl PromptSkillCapabilities {
7418    /// Builds an empty [`PromptSkillCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7419    #[must_use]
7420    pub fn new() -> Self {
7421        Self::default()
7422    }
7423
7424    /// Agent supports `skill` content blocks at any position in a prompt.
7425    ///
7426    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
7427    /// Supplying `{}` means a prompt may contain any number of `skill` content blocks, at any
7428    /// position.
7429    #[must_use]
7430    pub fn inline(mut self, inline: impl IntoOption<PromptSkillInlineCapabilities>) -> Self {
7431        self.inline = inline.into_option();
7432        self
7433    }
7434
7435    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7436    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7437    /// do not recognize.
7438    ///
7439    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7440    #[must_use]
7441    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7442        self.meta = meta.into_option();
7443        self
7444    }
7445}
7446
7447/// **UNSTABLE**
7448///
7449/// This capability is not part of the spec yet, and may be removed or changed at any point.
7450///
7451/// Capabilities for `skill` content blocks at any position in a prompt.
7452///
7453/// Supplying `{}` means a prompt may contain any number of `skill` content
7454/// blocks, at any position.
7455#[cfg(feature = "unstable_agent_skills")]
7456#[serde_as]
7457#[skip_serializing_none]
7458#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7459#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7460#[non_exhaustive]
7461pub struct PromptSkillInlineCapabilities {
7462    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7463    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7464    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7465    ///
7466    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7467    #[serde_as(deserialize_as = "DefaultOnError")]
7468    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7469    #[serde(default)]
7470    #[serde(rename = "_meta")]
7471    pub meta: Option<Meta>,
7472}
7473
7474#[cfg(feature = "unstable_agent_skills")]
7475impl PromptSkillInlineCapabilities {
7476    /// Builds an empty [`PromptSkillInlineCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7477    #[must_use]
7478    pub fn new() -> Self {
7479        Self::default()
7480    }
7481
7482    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7483    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7484    /// do not recognize.
7485    ///
7486    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7487    #[must_use]
7488    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7489        self.meta = meta.into_option();
7490        self
7491    }
7492}
7493
7494/// MCP capabilities supported by the Agent for session lifecycle requests.
7495#[serde_as]
7496#[skip_serializing_none]
7497#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7498#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7499#[serde(rename_all = "camelCase")]
7500#[non_exhaustive]
7501pub struct McpCapabilities {
7502    /// Agent supports `stdio` MCP servers.
7503    ///
7504    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
7505    /// Supplying `{}` means the Agent supports stdio MCP server transports.
7506    #[serde_as(deserialize_as = "DefaultOnError")]
7507    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7508    #[serde(default)]
7509    pub stdio: Option<McpStdioCapabilities>,
7510    /// Agent supports `http` MCP servers.
7511    ///
7512    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
7513    /// Supplying `{}` means the Agent supports HTTP MCP server transports.
7514    #[serde_as(deserialize_as = "DefaultOnError")]
7515    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7516    #[serde(default)]
7517    pub http: Option<McpHttpCapabilities>,
7518    /// **UNSTABLE**
7519    ///
7520    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7521    ///
7522    /// Agent supports `acp` MCP servers.
7523    ///
7524    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
7525    /// Supplying `{}` means the Agent supports ACP MCP server transports.
7526    #[cfg(feature = "unstable_mcp_over_acp")]
7527    #[serde_as(deserialize_as = "DefaultOnError")]
7528    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7529    #[serde(default)]
7530    pub acp: Option<McpAcpCapabilities>,
7531    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7532    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7533    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7534    ///
7535    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7536    #[serde_as(deserialize_as = "DefaultOnError")]
7537    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7538    #[serde(default)]
7539    #[serde(rename = "_meta")]
7540    pub meta: Option<Meta>,
7541}
7542
7543impl McpCapabilities {
7544    /// Builds an empty [`McpCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7545    #[must_use]
7546    pub fn new() -> Self {
7547        Self::default()
7548    }
7549
7550    /// Agent supports `stdio` MCP servers.
7551    ///
7552    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
7553    /// Supplying `{}` means the Agent supports stdio MCP server transports.
7554    #[must_use]
7555    pub fn stdio(mut self, stdio: impl IntoOption<McpStdioCapabilities>) -> Self {
7556        self.stdio = stdio.into_option();
7557        self
7558    }
7559
7560    /// Agent supports `http` MCP servers.
7561    ///
7562    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
7563    /// Supplying `{}` means the Agent supports HTTP MCP server transports.
7564    #[must_use]
7565    pub fn http(mut self, http: impl IntoOption<McpHttpCapabilities>) -> Self {
7566        self.http = http.into_option();
7567        self
7568    }
7569
7570    /// **UNSTABLE**
7571    ///
7572    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7573    ///
7574    /// Agent supports `acp` MCP servers.
7575    #[cfg(feature = "unstable_mcp_over_acp")]
7576    ///
7577    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
7578    /// Supplying `{}` means the Agent supports ACP MCP server transports.
7579    #[must_use]
7580    pub fn acp(mut self, acp: impl IntoOption<McpAcpCapabilities>) -> Self {
7581        self.acp = acp.into_option();
7582        self
7583    }
7584
7585    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7586    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7587    /// do not recognize.
7588    ///
7589    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7590    #[must_use]
7591    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7592        self.meta = meta.into_option();
7593        self
7594    }
7595}
7596
7597/// Capabilities for stdio MCP server transports.
7598///
7599/// Supplying `{}` means the Agent supports stdio MCP server transports.
7600#[serde_as]
7601#[skip_serializing_none]
7602#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7603#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7604#[non_exhaustive]
7605pub struct McpStdioCapabilities {
7606    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7607    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7608    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7609    ///
7610    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7611    #[serde_as(deserialize_as = "DefaultOnError")]
7612    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7613    #[serde(default)]
7614    #[serde(rename = "_meta")]
7615    pub meta: Option<Meta>,
7616}
7617
7618impl McpStdioCapabilities {
7619    /// Builds an empty [`McpStdioCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7620    #[must_use]
7621    pub fn new() -> Self {
7622        Self::default()
7623    }
7624
7625    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7626    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7627    /// do not recognize.
7628    ///
7629    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7630    #[must_use]
7631    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7632        self.meta = meta.into_option();
7633        self
7634    }
7635}
7636
7637/// Capabilities for HTTP MCP server transports.
7638///
7639/// Supplying `{}` means the Agent supports HTTP MCP server transports.
7640#[serde_as]
7641#[skip_serializing_none]
7642#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7643#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7644#[non_exhaustive]
7645pub struct McpHttpCapabilities {
7646    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7647    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7648    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7649    ///
7650    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7651    #[serde_as(deserialize_as = "DefaultOnError")]
7652    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7653    #[serde(default)]
7654    #[serde(rename = "_meta")]
7655    pub meta: Option<Meta>,
7656}
7657
7658impl McpHttpCapabilities {
7659    /// Builds an empty [`McpHttpCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7660    #[must_use]
7661    pub fn new() -> Self {
7662        Self::default()
7663    }
7664
7665    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7666    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7667    /// do not recognize.
7668    ///
7669    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7670    #[must_use]
7671    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7672        self.meta = meta.into_option();
7673        self
7674    }
7675}
7676
7677/// **UNSTABLE**
7678///
7679/// This capability is not part of the spec yet, and may be removed or changed at any point.
7680///
7681/// Capabilities for ACP MCP server transports.
7682///
7683/// Supplying `{}` means the Agent supports ACP MCP server transports.
7684#[cfg(feature = "unstable_mcp_over_acp")]
7685#[serde_as]
7686#[skip_serializing_none]
7687#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7688#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7689#[non_exhaustive]
7690pub struct McpAcpCapabilities {
7691    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7692    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7693    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7694    ///
7695    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7696    #[serde_as(deserialize_as = "DefaultOnError")]
7697    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7698    #[serde(default)]
7699    #[serde(rename = "_meta")]
7700    pub meta: Option<Meta>,
7701}
7702
7703#[cfg(feature = "unstable_mcp_over_acp")]
7704impl McpAcpCapabilities {
7705    /// Builds an empty [`McpAcpCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7706    #[must_use]
7707    pub fn new() -> Self {
7708        Self::default()
7709    }
7710
7711    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7712    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7713    /// do not recognize.
7714    ///
7715    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7716    #[must_use]
7717    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7718        self.meta = meta.into_option();
7719        self
7720    }
7721}
7722
7723/// Cancels the named session's active foreground work and earlier prompts not yet inserted.
7724/// It does not cancel later submissions or work in the session's latest `background` list.
7725///
7726/// See protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#cancellation)
7727#[serde_as]
7728#[skip_serializing_none]
7729#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7730#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7731#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CANCEL_METHOD_NAME)))]
7732#[serde(rename_all = "camelCase")]
7733#[non_exhaustive]
7734pub struct CancelSessionNotification {
7735    /// The ID of the session whose foreground work to cancel.
7736    pub session_id: SessionId,
7737    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7738    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7739    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7740    ///
7741    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7742    #[serde_as(deserialize_as = "DefaultOnError")]
7743    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7744    #[serde(default)]
7745    #[serde(rename = "_meta")]
7746    pub meta: Option<Meta>,
7747}
7748
7749impl CancelSessionNotification {
7750    /// Builds [`CancelSessionNotification`] with the required notification fields set. Optional fields start unset or empty.
7751    #[must_use]
7752    pub fn new(session_id: impl Into<SessionId>) -> Self {
7753        Self {
7754            session_id: session_id.into(),
7755            meta: None,
7756        }
7757    }
7758
7759    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7760    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7761    /// do not recognize.
7762    ///
7763    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7764    #[must_use]
7765    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7766        self.meta = meta.into_option();
7767        self
7768    }
7769}
7770
7771// Method schema
7772
7773/// Names of all methods that Agents handle.
7774///
7775/// Provides a centralized definition of method names used in the protocol.
7776#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7777#[non_exhaustive]
7778pub struct AgentMethodNames {
7779    /// Method for initializing the connection.
7780    pub initialize: &'static str,
7781    /// Method for authenticating with the Agent.
7782    pub auth_login: &'static str,
7783    /// Method for listing configurable providers.
7784    #[cfg(feature = "unstable_llm_providers")]
7785    pub providers_list: &'static str,
7786    /// Method for setting provider configuration.
7787    #[cfg(feature = "unstable_llm_providers")]
7788    pub providers_set: &'static str,
7789    /// Method for disabling a provider.
7790    #[cfg(feature = "unstable_llm_providers")]
7791    pub providers_disable: &'static str,
7792    /// Method for creating a new session.
7793    pub session_new: &'static str,
7794    /// Method for setting a configuration option for a session.
7795    pub session_set_config_option: &'static str,
7796    /// Method for sending a prompt to the Agent.
7797    pub session_prompt: &'static str,
7798    /// Notification for cancelling operations.
7799    pub session_cancel: &'static str,
7800    /// Method for exchanging MCP-over-ACP messages.
7801    #[cfg(feature = "unstable_mcp_over_acp")]
7802    pub mcp_message: &'static str,
7803    /// Method for listing existing sessions.
7804    pub session_list: &'static str,
7805    /// Method for deleting an existing session.
7806    pub session_delete: &'static str,
7807    /// Method for forking an existing session.
7808    #[cfg(feature = "unstable_session_fork")]
7809    pub session_fork: &'static str,
7810    /// Method for archiving a session.
7811    #[cfg(feature = "unstable_session_archive")]
7812    pub session_archive: &'static str,
7813    /// Method for unarchiving a session.
7814    #[cfg(feature = "unstable_session_archive")]
7815    pub session_unarchive: &'static str,
7816    /// Method for checking the status of a session.
7817    #[cfg(feature = "unstable_session_status")]
7818    pub session_status: &'static str,
7819    /// Method for querying the config options a session would start with.
7820    #[cfg(feature = "unstable_session_options")]
7821    pub session_options: &'static str,
7822    /// Method for setting the title of a session.
7823    #[cfg(feature = "unstable_session_set_title")]
7824    pub session_set_title: &'static str,
7825    /// Method for resuming an existing session.
7826    pub session_resume: &'static str,
7827    /// Method for closing an active session.
7828    pub session_close: &'static str,
7829    /// Method for cancelling one tool call.
7830    pub tool_call_cancel: &'static str,
7831    /// Method for cancelling one terminal's process.
7832    pub terminal_cancel: &'static str,
7833    /// Method for logging out of an authenticated session.
7834    pub auth_logout: &'static str,
7835    /// Method for querying the Agent's authentication state.
7836    #[cfg(feature = "unstable_auth_status")]
7837    pub auth_status: &'static str,
7838}
7839
7840/// Constant containing all Agent method names.
7841pub const AGENT_METHOD_NAMES: AgentMethodNames = AgentMethodNames {
7842    initialize: INITIALIZE_METHOD_NAME,
7843    auth_login: AUTH_LOGIN_METHOD_NAME,
7844    #[cfg(feature = "unstable_llm_providers")]
7845    providers_list: PROVIDERS_LIST_METHOD_NAME,
7846    #[cfg(feature = "unstable_llm_providers")]
7847    providers_set: PROVIDERS_SET_METHOD_NAME,
7848    #[cfg(feature = "unstable_llm_providers")]
7849    providers_disable: PROVIDERS_DISABLE_METHOD_NAME,
7850    session_new: SESSION_NEW_METHOD_NAME,
7851    session_set_config_option: SESSION_SET_CONFIG_OPTION_METHOD_NAME,
7852    session_prompt: SESSION_PROMPT_METHOD_NAME,
7853    session_cancel: SESSION_CANCEL_METHOD_NAME,
7854    #[cfg(feature = "unstable_mcp_over_acp")]
7855    mcp_message: MCP_MESSAGE_METHOD_NAME,
7856    session_list: SESSION_LIST_METHOD_NAME,
7857    session_delete: SESSION_DELETE_METHOD_NAME,
7858    #[cfg(feature = "unstable_session_fork")]
7859    session_fork: SESSION_FORK_METHOD_NAME,
7860    #[cfg(feature = "unstable_session_archive")]
7861    session_archive: SESSION_ARCHIVE_METHOD_NAME,
7862    #[cfg(feature = "unstable_session_archive")]
7863    session_unarchive: SESSION_UNARCHIVE_METHOD_NAME,
7864    #[cfg(feature = "unstable_session_status")]
7865    session_status: SESSION_STATUS_METHOD_NAME,
7866    #[cfg(feature = "unstable_session_options")]
7867    session_options: SESSION_OPTIONS_METHOD_NAME,
7868    #[cfg(feature = "unstable_session_set_title")]
7869    session_set_title: SESSION_SET_TITLE_METHOD_NAME,
7870    session_resume: SESSION_RESUME_METHOD_NAME,
7871    session_close: SESSION_CLOSE_METHOD_NAME,
7872    tool_call_cancel: TOOL_CALL_CANCEL_METHOD_NAME,
7873    terminal_cancel: TERMINAL_CANCEL_METHOD_NAME,
7874    auth_logout: AUTH_LOGOUT_METHOD_NAME,
7875    #[cfg(feature = "unstable_auth_status")]
7876    auth_status: AUTH_STATUS_METHOD_NAME,
7877};
7878
7879/// Method name for the initialize request.
7880pub(crate) const INITIALIZE_METHOD_NAME: &str = "initialize";
7881/// Method name for the `auth/login` request.
7882pub(crate) const AUTH_LOGIN_METHOD_NAME: &str = "auth/login";
7883/// Method name for listing configurable providers.
7884#[cfg(feature = "unstable_llm_providers")]
7885pub(crate) const PROVIDERS_LIST_METHOD_NAME: &str = "providers/list";
7886/// Method name for setting provider configuration.
7887#[cfg(feature = "unstable_llm_providers")]
7888pub(crate) const PROVIDERS_SET_METHOD_NAME: &str = "providers/set";
7889/// Method name for disabling a provider.
7890#[cfg(feature = "unstable_llm_providers")]
7891pub(crate) const PROVIDERS_DISABLE_METHOD_NAME: &str = "providers/disable";
7892/// Method name for creating a new session.
7893pub(crate) const SESSION_NEW_METHOD_NAME: &str = "session/new";
7894/// Method name for setting a configuration option for a session.
7895pub(crate) const SESSION_SET_CONFIG_OPTION_METHOD_NAME: &str = "session/set_config_option";
7896/// Method name for sending a prompt.
7897pub(crate) const SESSION_PROMPT_METHOD_NAME: &str = "session/prompt";
7898/// Method name for the cancel notification.
7899pub(crate) const SESSION_CANCEL_METHOD_NAME: &str = "session/cancel";
7900/// Method name for listing existing sessions.
7901pub(crate) const SESSION_LIST_METHOD_NAME: &str = "session/list";
7902/// Method name for deleting an existing session.
7903pub(crate) const SESSION_DELETE_METHOD_NAME: &str = "session/delete";
7904/// Method name for forking an existing session.
7905#[cfg(feature = "unstable_session_fork")]
7906pub(crate) const SESSION_FORK_METHOD_NAME: &str = "session/fork";
7907/// Method name for archiving a session.
7908#[cfg(feature = "unstable_session_archive")]
7909pub(crate) const SESSION_ARCHIVE_METHOD_NAME: &str = "session/archive";
7910/// Method name for unarchiving a session.
7911#[cfg(feature = "unstable_session_archive")]
7912pub(crate) const SESSION_UNARCHIVE_METHOD_NAME: &str = "session/unarchive";
7913/// Method name for checking the status of a session.
7914#[cfg(feature = "unstable_session_status")]
7915pub(crate) const SESSION_STATUS_METHOD_NAME: &str = "session/status";
7916/// Method name for querying the config options a session would start with.
7917#[cfg(feature = "unstable_session_options")]
7918pub(crate) const SESSION_OPTIONS_METHOD_NAME: &str = "session/options";
7919/// Method name for setting the title of a session.
7920#[cfg(feature = "unstable_session_set_title")]
7921pub(crate) const SESSION_SET_TITLE_METHOD_NAME: &str = "session/set_title";
7922/// Method name for resuming an existing session.
7923pub(crate) const SESSION_RESUME_METHOD_NAME: &str = "session/resume";
7924/// Method name for closing an active session.
7925pub(crate) const SESSION_CLOSE_METHOD_NAME: &str = "session/close";
7926/// Method name for cancelling one tool call.
7927pub(crate) const TOOL_CALL_CANCEL_METHOD_NAME: &str = "tool_call/cancel";
7928/// Method name for cancelling one terminal's process.
7929pub(crate) const TERMINAL_CANCEL_METHOD_NAME: &str = "terminal/cancel";
7930/// Method name for the `auth/logout` request.
7931pub(crate) const AUTH_LOGOUT_METHOD_NAME: &str = "auth/logout";
7932/// Method name for the `auth/status` request.
7933#[cfg(feature = "unstable_auth_status")]
7934pub(crate) const AUTH_STATUS_METHOD_NAME: &str = "auth/status";
7935
7936/// All possible requests that a Client can send to an Agent.
7937///
7938/// This enum is used internally for routing RPC requests. You typically won't need
7939/// to use this directly.
7940///
7941/// This enum encompasses all method calls from Client to Agent.
7942#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7943#[derive(Clone, Debug, Serialize, Deserialize)]
7944#[serde(untagged)]
7945#[cfg_attr(feature = "schemars", schemars(inline))]
7946#[non_exhaustive]
7947pub enum ClientRequest {
7948    /// Establishes the connection with a Client and negotiates protocol capabilities.
7949    ///
7950    /// This method is called at the beginning of the connection, before any other request, to:
7951    /// - Negotiate the protocol version to use
7952    /// - Exchange capability information between Client and Agent
7953    /// - Determine available authentication methods
7954    ///
7955    /// The Client MAY repeat it before its first other request. The latest successful
7956    /// `initialize` is authoritative.
7957    ///
7958    /// The Agent responds with its supported protocol version and capabilities.
7959    ///
7960    /// See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/v2/initialization)
7961    InitializeRequest(Box<InitializeRequest>),
7962    /// Authenticates the Client using the specified authentication method.
7963    ///
7964    /// Agents MUST support this method when their `initialize` response included
7965    /// a non-empty `authMethods` list. Clients MUST call this method only
7966    /// with a method whose type defines a protocol-driven login flow, and MUST NOT
7967    /// call it when `authMethods` was omitted or empty.
7968    ///
7969    /// Called when the Agent requires authentication before allowing session creation.
7970    /// The Client provides the authentication method ID that was advertised during initialization.
7971    ///
7972    /// After successful authentication, the Client can proceed to create sessions with
7973    /// `session/new` without receiving a `-32000` (Authentication required) error.
7974    ///
7975    /// See protocol docs: [Authentication](https://agentclientprotocol.com/protocol/v2/authentication)
7976    LoginAuthRequest(Box<LoginAuthRequest>),
7977    /// **UNSTABLE**
7978    ///
7979    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7980    ///
7981    /// Lists providers that can be configured by the Client.
7982    #[cfg(feature = "unstable_llm_providers")]
7983    ListProvidersRequest(Box<ListProvidersRequest>),
7984    /// **UNSTABLE**
7985    ///
7986    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7987    ///
7988    /// Replaces the configuration for a provider.
7989    #[cfg(feature = "unstable_llm_providers")]
7990    SetProviderRequest(Box<SetProviderRequest>),
7991    /// **UNSTABLE**
7992    ///
7993    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7994    ///
7995    /// Disables a provider.
7996    #[cfg(feature = "unstable_llm_providers")]
7997    DisableProviderRequest(Box<DisableProviderRequest>),
7998    /// Logs out of the current authenticated state.
7999    ///
8000    /// Agents MUST support this method when their `initialize` response included
8001    /// a non-empty `authMethods` list. Clients MUST NOT call this method
8002    /// when `authMethods` was omitted or empty.
8003    ///
8004    /// After a successful logout, authentication-gated requests require the
8005    /// Client to complete an advertised authentication flow again. There is no
8006    /// guarantee about the behavior of already running sessions.
8007    LogoutAuthRequest(Box<LogoutAuthRequest>),
8008    /// **UNSTABLE**
8009    ///
8010    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8011    ///
8012    /// Queries the Agent's current authentication state.
8013    ///
8014    /// This method is only available if the Agent advertises the `auth.status` capability.
8015    /// It MUST NOT change any Agent state, and Agents MUST NOT reject it with `-32000` (Authentication required).
8016    #[cfg(feature = "unstable_auth_status")]
8017    AuthStatusRequest(Box<AuthStatusRequest>),
8018    /// Creates a new conversation session with the Agent.
8019    ///
8020    /// Sessions represent independent conversation contexts with their own history and state.
8021    ///
8022    /// The Agent:
8023    /// - Creates a new session context
8024    /// - Connects to the specified MCP servers
8025    /// - Returns a unique session ID for future requests
8026    ///
8027    /// Fails with `-32000` (Authentication required) if the Agent requires authentication.
8028    ///
8029    /// See protocol docs: [Session Setup](https://agentclientprotocol.com/protocol/v2/session-setup)
8030    NewSessionRequest(Box<NewSessionRequest>),
8031    /// Lists existing sessions known to the Agent.
8032    ///
8033    /// The Agent returns metadata about sessions, with optional filtering and pagination.
8034    ListSessionsRequest(Box<ListSessionsRequest>),
8035    /// Deletes an existing session from `session/list`.
8036    ///
8037    /// This method is only available if the Agent advertises the `session.delete` capability.
8038    DeleteSessionRequest(Box<DeleteSessionRequest>),
8039    #[cfg(feature = "unstable_session_fork")]
8040    /// **UNSTABLE**
8041    ///
8042    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8043    ///
8044    /// Forks an existing session to create a new independent session.
8045    ///
8046    /// This method is only available if the Agent advertises the `session.fork` capability.
8047    ///
8048    /// The Agent creates a new session with the same conversation context as the
8049    /// original. The fork can be used for operations like generating summaries without
8050    /// affecting the original session's history.
8051    ///
8052    /// As with `session/new`, the forked session is active once the Agent responds,
8053    /// set up with the request's `cwd`, `additionalDirectories`, and `mcpServers`.
8054    /// The Client can prompt it without calling `session/resume` first.
8055    ForkSessionRequest(Box<ForkSessionRequest>),
8056    #[cfg(feature = "unstable_session_archive")]
8057    /// **UNSTABLE**
8058    ///
8059    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8060    ///
8061    /// Archives a session, hiding it from default `session/list` results.
8062    ///
8063    /// This method is only available if the Agent advertises the `session.archive` capability.
8064    ArchiveSessionRequest(Box<ArchiveSessionRequest>),
8065    #[cfg(feature = "unstable_session_archive")]
8066    /// **UNSTABLE**
8067    ///
8068    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8069    ///
8070    /// Unarchives a session, returning it to default `session/list` results.
8071    ///
8072    /// This method is only available if the Agent advertises the `session.archive` capability.
8073    UnarchiveSessionRequest(Box<UnarchiveSessionRequest>),
8074    #[cfg(feature = "unstable_session_status")]
8075    /// **UNSTABLE**
8076    ///
8077    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8078    ///
8079    /// Checks whether the Agent has a session in memory, without changing it.
8080    ///
8081    /// This method is only available if the Agent advertises the `session.status` capability.
8082    SessionStatusRequest(Box<SessionStatusRequest>),
8083    #[cfg(feature = "unstable_session_options")]
8084    /// **UNSTABLE**
8085    ///
8086    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8087    ///
8088    /// Returns the config options a session would start with, without creating or resuming a session.
8089    ///
8090    /// This method is only available if the Agent advertises the `session.options` capability.
8091    SessionOptionsRequest(Box<SessionOptionsRequest>),
8092    #[cfg(feature = "unstable_session_set_title")]
8093    /// **UNSTABLE**
8094    ///
8095    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8096    ///
8097    /// Sets the title of a session.
8098    ///
8099    /// This method is only available if the Agent advertises the `session.title` capability.
8100    ///
8101    /// The session does not need to be active on the connection. The Agent stores the
8102    /// title and returns the stored title, which may be normalized.
8103    SetSessionTitleRequest(Box<SetSessionTitleRequest>),
8104    /// Resumes an existing session.
8105    ///
8106    /// The Agent resumes the session context so that the conversation
8107    /// can continue. If `replayFrom` is set, the Agent replays
8108    /// retained conversation history before responding.
8109    ResumeSessionRequest(Box<ResumeSessionRequest>),
8110    /// Closes an active session and frees up any resources associated with it.
8111    ///
8112    /// The Agent MUST cancel any ongoing work as if `session/cancel` was called, stop the
8113    /// session's background work, and then free the resources associated with the session.
8114    CloseSessionRequest(Box<CloseSessionRequest>),
8115    /// Cancels one tool call without cancelling the rest of the session's work.
8116    ///
8117    /// This method is only available while the tool call advertises `capabilities.cancel`.
8118    /// The response means the Agent accepted the cancellation. A final `tool_call_update`
8119    /// confirms it.
8120    CancelToolCallRequest(Box<CancelToolCallRequest>),
8121    /// Stops one terminal's process without cancelling the rest of the session's work.
8122    ///
8123    /// This method is only available while the terminal advertises `capabilities.cancel`.
8124    /// The response means the Agent accepted the cancellation. A `terminal_update` with
8125    /// `exitStatus` confirms it.
8126    CancelTerminalRequest(Box<CancelTerminalRequest>),
8127    /// Sets the current value for a session configuration option.
8128    SetSessionConfigOptionRequest(Box<SetSessionConfigOptionRequest>),
8129    /// Processes a user prompt within a session.
8130    ///
8131    /// Acceptance means adding a logical user message with an ID and a position
8132    /// relative to other messages in the ACP conversation, not receipt or queueing.
8133    /// The Agent MUST return the inserted message's ID without waiting for
8134    /// processing to finish.
8135    ///
8136    /// The Agent reports the user message with the same ID through `session/update`.
8137    /// This notification can arrive before or after the response, and MUST NOT
8138    /// precede insertion. Processing state, output, tool calls, and completion are
8139    /// also reported through session updates.
8140    ///
8141    /// An error response means the user message was not inserted. Once it is
8142    /// inserted, the Agent MUST NOT answer with an error, even if the work fails
8143    /// before the response is sent. It ends that work with the `error` stop reason.
8144    ///
8145    /// A rejected submission produces no user-message updates. Foreground state
8146    /// follows its normal lifecycle independently of the request outcome:
8147    /// `running` may precede insertion, and rejection alone does not imply `idle`.
8148    ///
8149    /// See protocol docs: [Prompt Lifecycle](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle)
8150    PromptRequest(Box<PromptRequest>),
8151    /// Handles extension method requests from the Client.
8152    ///
8153    /// Extension methods are custom methods that are not part of the ACP spec.
8154    ///
8155    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
8156    ExtMethodRequest(Box<ExtRequest>),
8157}
8158
8159impl_request_dispatch! {
8160    ClientRequest => AgentResponse {
8161        InitializeRequest => InitializeResponse: AGENT_METHOD_NAMES.initialize,
8162        LoginAuthRequest => LoginAuthResponse: AGENT_METHOD_NAMES.auth_login,
8163        #[cfg(feature = "unstable_llm_providers")]
8164        ListProvidersRequest => ListProvidersResponse: AGENT_METHOD_NAMES.providers_list,
8165        #[cfg(feature = "unstable_llm_providers")]
8166        SetProviderRequest => SetProviderResponse: AGENT_METHOD_NAMES.providers_set,
8167        #[cfg(feature = "unstable_llm_providers")]
8168        DisableProviderRequest => DisableProviderResponse: AGENT_METHOD_NAMES.providers_disable,
8169        LogoutAuthRequest => LogoutAuthResponse: AGENT_METHOD_NAMES.auth_logout,
8170        #[cfg(feature = "unstable_auth_status")]
8171        AuthStatusRequest => AuthStatusResponse: AGENT_METHOD_NAMES.auth_status,
8172        NewSessionRequest => NewSessionResponse: AGENT_METHOD_NAMES.session_new,
8173        ListSessionsRequest => ListSessionsResponse: AGENT_METHOD_NAMES.session_list,
8174        DeleteSessionRequest => DeleteSessionResponse: AGENT_METHOD_NAMES.session_delete,
8175        #[cfg(feature = "unstable_session_fork")]
8176        ForkSessionRequest => ForkSessionResponse: AGENT_METHOD_NAMES.session_fork,
8177        #[cfg(feature = "unstable_session_archive")]
8178        ArchiveSessionRequest => ArchiveSessionResponse: AGENT_METHOD_NAMES.session_archive,
8179        #[cfg(feature = "unstable_session_archive")]
8180        UnarchiveSessionRequest => UnarchiveSessionResponse: AGENT_METHOD_NAMES.session_unarchive,
8181        #[cfg(feature = "unstable_session_status")]
8182        SessionStatusRequest => SessionStatusResponse: AGENT_METHOD_NAMES.session_status,
8183        #[cfg(feature = "unstable_session_options")]
8184        SessionOptionsRequest => SessionOptionsResponse: AGENT_METHOD_NAMES.session_options,
8185        #[cfg(feature = "unstable_session_set_title")]
8186        SetSessionTitleRequest => SetSessionTitleResponse: AGENT_METHOD_NAMES.session_set_title,
8187        ResumeSessionRequest => ResumeSessionResponse: AGENT_METHOD_NAMES.session_resume,
8188        CloseSessionRequest => CloseSessionResponse: AGENT_METHOD_NAMES.session_close,
8189        CancelToolCallRequest => CancelToolCallResponse: AGENT_METHOD_NAMES.tool_call_cancel,
8190        CancelTerminalRequest => CancelTerminalResponse: AGENT_METHOD_NAMES.terminal_cancel,
8191        SetSessionConfigOptionRequest => SetSessionConfigOptionResponse: AGENT_METHOD_NAMES.session_set_config_option,
8192        PromptRequest => PromptResponse: AGENT_METHOD_NAMES.session_prompt,
8193    }
8194    extension ExtMethodRequest(Box<ExtRequest>) => ExtMethodResponse;
8195}
8196
8197/// All possible responses that an Agent can send to a Client.
8198///
8199/// This enum is used internally for routing RPC responses. You typically won't need
8200/// to use this directly. The connection handles the responses automatically.
8201///
8202/// These are responses to the corresponding `ClientRequest` variants.
8203#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
8204#[derive(Clone, Debug, Serialize, Deserialize)]
8205#[serde(untagged)]
8206#[cfg_attr(feature = "schemars", schemars(inline))]
8207#[non_exhaustive]
8208pub enum AgentResponse {
8209    /// Successful result returned for a `initialize` request.
8210    InitializeResponse(Box<InitializeResponse>),
8211    /// Successful result returned for an `auth/login` request.
8212    LoginAuthResponse(#[serde(default)] Box<LoginAuthResponse>),
8213    /// Successful result returned for a `providers/list` request.
8214    #[cfg(feature = "unstable_llm_providers")]
8215    ListProvidersResponse(Box<ListProvidersResponse>),
8216    /// Successful result returned for a `providers/set` request.
8217    #[cfg(feature = "unstable_llm_providers")]
8218    SetProviderResponse(#[serde(default)] Box<SetProviderResponse>),
8219    /// Successful result returned for a `providers/disable` request.
8220    #[cfg(feature = "unstable_llm_providers")]
8221    DisableProviderResponse(#[serde(default)] Box<DisableProviderResponse>),
8222    /// Successful result returned for an `auth/logout` request.
8223    LogoutAuthResponse(#[serde(default)] Box<LogoutAuthResponse>),
8224    /// Successful result returned for an `auth/status` request.
8225    #[cfg(feature = "unstable_auth_status")]
8226    AuthStatusResponse(Box<AuthStatusResponse>),
8227    /// Successful result returned for a `session/new` request.
8228    NewSessionResponse(Box<NewSessionResponse>),
8229    /// Successful result returned for a `session/list` request.
8230    ListSessionsResponse(Box<ListSessionsResponse>),
8231    /// Successful result returned for a `session/delete` request.
8232    DeleteSessionResponse(#[serde(default)] Box<DeleteSessionResponse>),
8233    /// Successful result returned for a `session/fork` request.
8234    #[cfg(feature = "unstable_session_fork")]
8235    ForkSessionResponse(Box<ForkSessionResponse>),
8236    /// Successful result returned for a `session/archive` request.
8237    #[cfg(feature = "unstable_session_archive")]
8238    ArchiveSessionResponse(#[serde(default)] Box<ArchiveSessionResponse>),
8239    /// Successful result returned for a `session/unarchive` request.
8240    #[cfg(feature = "unstable_session_archive")]
8241    UnarchiveSessionResponse(#[serde(default)] Box<UnarchiveSessionResponse>),
8242    /// Successful result returned for a `session/status` request.
8243    #[cfg(feature = "unstable_session_status")]
8244    SessionStatusResponse(Box<SessionStatusResponse>),
8245    /// Successful result returned for a `session/options` request.
8246    #[cfg(feature = "unstable_session_options")]
8247    SessionOptionsResponse(#[serde(default)] Box<SessionOptionsResponse>),
8248    /// Successful result returned for a `session/set_title` request.
8249    #[cfg(feature = "unstable_session_set_title")]
8250    SetSessionTitleResponse(Box<SetSessionTitleResponse>),
8251    /// Successful result returned for a `session/resume` request.
8252    ResumeSessionResponse(#[serde(default)] Box<ResumeSessionResponse>),
8253    /// Successful result returned for a `session/close` request.
8254    CloseSessionResponse(#[serde(default)] Box<CloseSessionResponse>),
8255    /// Successful result returned for a `tool_call/cancel` request.
8256    CancelToolCallResponse(#[serde(default)] Box<CancelToolCallResponse>),
8257    /// Successful result returned for a `terminal/cancel` request.
8258    CancelTerminalResponse(#[serde(default)] Box<CancelTerminalResponse>),
8259    /// Successful result returned for a `session/set_config_option` request.
8260    SetSessionConfigOptionResponse(Box<SetSessionConfigOptionResponse>),
8261    /// Successful result returned for a `session/prompt` request.
8262    PromptResponse(Box<PromptResponse>),
8263    /// Successful result returned by an extension method outside the core ACP method set.
8264    ExtMethodResponse(Box<ExtResponse>),
8265}
8266
8267/// All possible notifications that a Client can send to an Agent.
8268///
8269/// This enum is used internally for routing RPC notifications. You typically won't need
8270/// to use this directly.
8271///
8272/// Notifications do not expect a response.
8273#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
8274#[derive(Clone, Debug, Serialize, Deserialize)]
8275#[serde(untagged)]
8276#[cfg_attr(feature = "schemars", schemars(inline))]
8277#[non_exhaustive]
8278pub enum ClientNotification {
8279    /// Cancels the named session's active foreground work and earlier prompts not yet inserted.
8280    /// The Agent MUST answer those uninserted prompts with `-32800`. Inserted prompts still
8281    /// succeed with their `messageId`. This cancellation does not cover later submissions.
8282    ///
8283    /// Work in the latest `background` list is not covered and keeps running. The
8284    /// Agent MAY stop background activity it does not list.
8285    ///
8286    /// Upon receiving this notification, the Agent SHOULD stop all language model
8287    /// requests and all tool call invocations of the cancelled foreground work as soon
8288    /// as possible.
8289    ///
8290    /// The Agent MUST stop waiting for pending `session/request_permission` requests of
8291    /// the cancelled work and treat them as not approved. It MUST cancel each of them
8292    /// with `$/cancel_request`.
8293    ///
8294    /// When cancellation stops active foreground work, the Agent MUST send that work's
8295    /// pending updates, then an idle `state_update` with `stopReason: "cancelled"`,
8296    /// before starting new foreground work in the same session. A later prompt can be
8297    /// inserted and acknowledged before that idle update, or held with its response
8298    /// pending. Listed background work can report updates before or after it.
8299    /// No additional idle update is required if no foreground work was active.
8300    ///
8301    /// After cancellation completes, the Agent SHOULD ignore late answers rather
8302    /// than use them to resume the cancelled work.
8303    ///
8304    /// Agents MUST catch errors caused by aborting cancelled work and report the
8305    /// `cancelled` stop reason, not `error`.
8306    ///
8307    /// See protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#cancellation)
8308    CancelSessionNotification(Box<CancelSessionNotification>),
8309    /// **UNSTABLE**
8310    ///
8311    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8312    ///
8313    /// Sends an MCP-over-ACP notification.
8314    #[cfg(feature = "unstable_mcp_over_acp")]
8315    MessageMcpNotification(Box<MessageMcpNotification>),
8316    /// Handles extension notifications from the Client.
8317    ///
8318    /// Extension notifications are custom one-way messages that are not part of the ACP spec.
8319    ///
8320    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
8321    ExtNotification(Box<ExtNotification>),
8322}
8323
8324impl_message_dispatch! {
8325    ClientNotification {
8326        CancelSessionNotification => AGENT_METHOD_NAMES.session_cancel,
8327        #[cfg(feature = "unstable_mcp_over_acp")]
8328        MessageMcpNotification => AGENT_METHOD_NAMES.mcp_message,
8329    }
8330    extension ExtNotification(Box<ExtNotification>);
8331}
8332
8333#[cfg(test)]
8334mod test_serialization {
8335    use std::path::PathBuf;
8336
8337    use super::*;
8338    use serde_json::json;
8339
8340    fn test_meta() -> Meta {
8341        json!({ "source": "test" }).as_object().unwrap().clone()
8342    }
8343
8344    #[test]
8345    fn list_sessions_cursor_and_session_directories_are_strict() {
8346        for cursor in [json!(null), json!("next")] {
8347            let response = json!({ "sessions": [], "nextCursor": cursor });
8348            serde_json::from_value::<ListSessionsResponse>(response).unwrap();
8349        }
8350        let malformed = json!({ "sessions": [], "nextCursor": 42 });
8351        assert!(serde_json::from_value::<ListSessionsResponse>(malformed).is_err());
8352
8353        let session = |dirs: serde_json::Value| json!({ "sessionId": "s", "cwd": "/w", "additionalDirectories": dirs });
8354        let info: SessionInfo = serde_json::from_value(session(json!(null))).unwrap();
8355        assert_eq!(info.additional_directories, Vec::<AbsolutePath>::new());
8356        for bad in [json!(["/a", 42]), json!("/a")] {
8357            assert!(serde_json::from_value::<SessionInfo>(session(bad)).is_err());
8358        }
8359        // A session with malformed directories is skipped, not truncated.
8360        let response = json!({ "sessions": [session(json!(["/a", 42]))] });
8361        let response: ListSessionsResponse = serde_json::from_value(response).unwrap();
8362        assert_eq!(response.sessions, Vec::<SessionInfo>::new());
8363    }
8364
8365    #[test]
8366    fn other_fallbacks_preserve_optional_fields_verbatim() {
8367        let valid = json!({ "type": "_custom", "methodId": "m", "name": "M",
8368            "description": "d", "_meta": { "k": 1 } });
8369        let method: AuthMethod = serde_json::from_value(valid.clone()).unwrap();
8370        assert_eq!(method.description(), Some("d"));
8371        assert_eq!(
8372            method.meta(),
8373            Some(&json!({ "k": 1 }).as_object().unwrap().clone())
8374        );
8375        assert_eq!(serde_json::to_value(&method).unwrap(), valid);
8376
8377        // Malformed optional fields are kept as sent and read as absent.
8378        let malformed = json!({ "type": "_custom", "methodId": "m", "name": "M",
8379            "description": 42, "_meta": "bad", "extra": true });
8380        let method: AuthMethod = serde_json::from_value(malformed.clone()).unwrap();
8381        assert_eq!(method.description(), None);
8382        assert_eq!(method.meta(), None);
8383        assert_eq!(serde_json::to_value(&method).unwrap(), malformed);
8384
8385        let replay = json!({ "type": "_custom", "_meta": "bad", "cursor": 3 });
8386        let decoded: ReplayFrom = serde_json::from_value(replay.clone()).unwrap();
8387        assert_eq!(serde_json::to_value(&decoded).unwrap(), replay);
8388    }
8389
8390    fn serialized_meta_key_count(value: &impl serde::Serialize) -> usize {
8391        serde_json::to_string(value)
8392            .unwrap()
8393            .matches("\"_meta\"")
8394            .count()
8395    }
8396
8397    #[test]
8398    fn prompt_response_without_metadata_round_trips() {
8399        let response = PromptResponse::new(MessageId::new("message-1"));
8400        let serialized = serde_json::to_value(&response).unwrap();
8401        assert_eq!(serialized, json!({ "messageId": "message-1" }));
8402        assert_eq!(
8403            serde_json::from_value::<PromptResponse>(serialized).unwrap(),
8404            response
8405        );
8406        assert_eq!(
8407            serde_json::from_value::<PromptResponse>(json!({
8408                "messageId": "message-1",
8409                "_meta": null
8410            }))
8411            .unwrap(),
8412            response
8413        );
8414    }
8415
8416    #[test]
8417    fn prompt_response_requires_message_id_and_preserves_metadata_tolerance() {
8418        let response = PromptResponse::new("message-1").meta(test_meta());
8419        let serialized = serde_json::to_value(&response).unwrap();
8420        assert_eq!(
8421            serialized,
8422            json!({
8423                "messageId": "message-1",
8424                "_meta": { "source": "test" }
8425            })
8426        );
8427
8428        let deserialized: PromptResponse = serde_json::from_value(serialized).unwrap();
8429        assert_eq!(deserialized.message_id, MessageId::new("message-1"));
8430        assert_eq!(deserialized.meta, Some(test_meta()));
8431
8432        let malformed_meta: PromptResponse = serde_json::from_value(json!({
8433            "messageId": "message-2",
8434            "_meta": false
8435        }))
8436        .unwrap();
8437        assert_eq!(malformed_meta.message_id, MessageId::new("message-2"));
8438        assert_eq!(malformed_meta.meta, None);
8439
8440        for invalid in [
8441            json!({}),
8442            json!({ "messageId": null }),
8443            json!({ "messageId": 1 }),
8444            json!({ "messageId": false }),
8445            json!({ "messageId": {} }),
8446            json!({ "messageId": [] }),
8447        ] {
8448            assert!(
8449                serde_json::from_value::<PromptResponse>(invalid).is_err(),
8450                "missing, null, and non-string message IDs must be rejected"
8451            );
8452        }
8453    }
8454
8455    #[cfg(feature = "schemars")]
8456    #[test]
8457    fn prompt_response_schema_requires_non_null_string_message_id_reference() {
8458        let schema = serde_json::to_value(schemars::schema_for!(PromptResponse)).unwrap();
8459
8460        assert_eq!(schema["required"], json!(["messageId"]));
8461        assert_eq!(
8462            schema["properties"]["messageId"]["$ref"],
8463            "#/$defs/MessageId"
8464        );
8465        assert_eq!(schema["$defs"]["MessageId"]["type"], "string");
8466    }
8467
8468    #[test]
8469    fn test_initialize_capabilities_default_on_malformed_values() {
8470        let request: InitializeRequest = serde_json::from_value(json!({
8471            "protocolVersion": 2,
8472            "capabilities": false,
8473            "info": {
8474                "name": "client",
8475                "version": "1.0.0"
8476            }
8477        }))
8478        .unwrap();
8479        assert_eq!(request.capabilities, ClientCapabilities::default());
8480
8481        let response: InitializeResponse = serde_json::from_value(json!({
8482            "protocolVersion": 2,
8483            "capabilities": false,
8484            "info": {
8485                "name": "agent",
8486                "version": "1.0.0"
8487            }
8488        }))
8489        .unwrap();
8490        assert_eq!(response.capabilities, AgentCapabilities::default());
8491    }
8492
8493    #[test]
8494    fn test_agent_capabilities_default_on_malformed_values() {
8495        let capabilities: AgentCapabilities = serde_json::from_value(json!({
8496            "session": false,
8497            "auth": false
8498        }))
8499        .unwrap();
8500
8501        assert!(capabilities.session.is_none());
8502        assert_eq!(capabilities.auth, None);
8503    }
8504
8505    #[test]
8506    fn test_mcp_server_stdio_serialization() {
8507        let server = McpServer::Stdio(
8508            McpServerStdio::new("test-server", "/usr/bin/server")
8509                .args(vec!["--port".to_string(), "3000".to_string()])
8510                .env(vec![EnvVariable::new("API_KEY", "secret123")]),
8511        );
8512
8513        let json = serde_json::to_value(&server).unwrap();
8514        assert_eq!(
8515            json,
8516            json!({
8517                "type": "stdio",
8518                "name": "test-server",
8519                "command": "/usr/bin/server",
8520                "args": ["--port", "3000"],
8521                "env": [
8522                    {
8523                        "name": "API_KEY",
8524                        "value": "secret123"
8525                    }
8526                ]
8527            })
8528        );
8529
8530        let deserialized: McpServer = serde_json::from_value(json).unwrap();
8531        match deserialized {
8532            McpServer::Stdio(McpServerStdio {
8533                name,
8534                command,
8535                args,
8536                env,
8537                meta: _,
8538            }) => {
8539                assert_eq!(name, "test-server");
8540                assert_eq!(command, AbsolutePath::new("/usr/bin/server"));
8541                assert_eq!(args, vec!["--port", "3000"]);
8542                assert_eq!(env.len(), 1);
8543                assert_eq!(env[0].name, "API_KEY");
8544                assert_eq!(env[0].value, "secret123");
8545            }
8546            _ => panic!("Expected Stdio variant"),
8547        }
8548    }
8549
8550    #[test]
8551    fn test_mcp_server_empty_arrays_are_optional() {
8552        let stdio = McpServer::Stdio(McpServerStdio::new("test-server", "/usr/bin/server"));
8553        assert_eq!(
8554            serde_json::to_value(&stdio).unwrap(),
8555            json!({
8556                "type": "stdio",
8557                "name": "test-server",
8558                "command": "/usr/bin/server"
8559            })
8560        );
8561
8562        let McpServer::Stdio(McpServerStdio { args, env, .. }) =
8563            serde_json::from_value::<McpServer>(json!({
8564                "type": "stdio",
8565                "name": "test-server",
8566                "command": "/usr/bin/server"
8567            }))
8568            .unwrap()
8569        else {
8570            panic!("Expected Stdio variant");
8571        };
8572        assert_eq!(args, Vec::<String>::new());
8573        assert_eq!(env, []);
8574
8575        let http = McpServer::Http(McpServerHttp::new("http-server", "https://api.example.com"));
8576        assert_eq!(
8577            serde_json::to_value(&http).unwrap(),
8578            json!({
8579                "type": "http",
8580                "name": "http-server",
8581                "url": "https://api.example.com"
8582            })
8583        );
8584
8585        let McpServer::Http(McpServerHttp { headers, .. }) =
8586            serde_json::from_value::<McpServer>(json!({
8587                "type": "http",
8588                "name": "http-server",
8589                "url": "https://api.example.com"
8590            }))
8591            .unwrap()
8592        else {
8593            panic!("Expected Http variant");
8594        };
8595        assert_eq!(headers, []);
8596    }
8597
8598    #[test]
8599    fn test_mcp_server_unknown_transport_serialization() {
8600        let json = json!({
8601            "type": "websocket",
8602            "name": "future-server",
8603            "url": "wss://example.com/mcp",
8604            "protocolVersion": "2026-01-01"
8605        });
8606
8607        let deserialized: McpServer = serde_json::from_value(json.clone()).unwrap();
8608        let McpServer::Other(OtherMcpServer { type_, fields }) = &deserialized else {
8609            panic!("Expected Other variant");
8610        };
8611
8612        assert_eq!(type_, "websocket");
8613        assert_eq!(fields["name"], "future-server");
8614        assert_eq!(fields["url"], "wss://example.com/mcp");
8615        assert_eq!(fields["protocolVersion"], "2026-01-01");
8616        assert_eq!(serde_json::to_value(&deserialized).unwrap(), json);
8617    }
8618
8619    #[test]
8620    fn test_mcp_server_stdio_requires_type() {
8621        let result = serde_json::from_value::<McpServer>(json!({
8622            "name": "test-server",
8623            "command": "/usr/bin/server",
8624            "args": [],
8625            "env": []
8626        }));
8627
8628        assert!(result.is_err());
8629    }
8630
8631    #[test]
8632    fn test_mcp_server_unknown_does_not_hide_malformed_known_transport() {
8633        let result = serde_json::from_value::<McpServer>(json!({
8634            "type": "stdio",
8635            "name": "test-server",
8636            "args": [],
8637            "env": []
8638        }));
8639
8640        assert!(result.is_err());
8641    }
8642
8643    #[test]
8644    fn test_mcp_server_http_serialization() {
8645        let server = McpServer::Http(
8646            McpServerHttp::new("http-server", "https://api.example.com").headers(vec![
8647                HttpHeader::new("Authorization", "Bearer token123"),
8648                HttpHeader::new("Content-Type", "application/json"),
8649            ]),
8650        );
8651
8652        let json = serde_json::to_value(&server).unwrap();
8653        assert_eq!(
8654            json,
8655            json!({
8656                "type": "http",
8657                "name": "http-server",
8658                "url": "https://api.example.com",
8659                "headers": [
8660                    {
8661                        "name": "Authorization",
8662                        "value": "Bearer token123"
8663                    },
8664                    {
8665                        "name": "Content-Type",
8666                        "value": "application/json"
8667                    }
8668                ]
8669            })
8670        );
8671
8672        let deserialized: McpServer = serde_json::from_value(json).unwrap();
8673        match deserialized {
8674            McpServer::Http(McpServerHttp {
8675                name,
8676                url,
8677                headers,
8678                meta: _,
8679            }) => {
8680                assert_eq!(name, "http-server");
8681                assert_eq!(url, "https://api.example.com");
8682                assert_eq!(headers.len(), 2);
8683                assert_eq!(headers[0].name, "Authorization");
8684                assert_eq!(headers[0].value, "Bearer token123");
8685                assert_eq!(headers[1].name, "Content-Type");
8686                assert_eq!(headers[1].value, "application/json");
8687            }
8688            _ => panic!("Expected Http variant"),
8689        }
8690    }
8691
8692    #[cfg(feature = "schemars")]
8693    #[test]
8694    fn mcp_server_http_schema_marks_url_as_uri() {
8695        let schema = serde_json::to_value(schemars::schema_for!(McpServerHttp)).unwrap();
8696
8697        assert_eq!(schema["properties"]["url"]["format"], "uri");
8698    }
8699
8700    #[cfg(feature = "unstable_mcp_over_acp")]
8701    #[test]
8702    fn test_client_mcp_message_method_names() {
8703        use serde_json::json;
8704
8705        assert_eq!(AGENT_METHOD_NAMES.mcp_message, "mcp/message");
8706
8707        let notification =
8708            MessageMcpNotification::new("server-1", "req-1", "notifications/progress");
8709        assert_eq!(
8710            ClientNotification::MessageMcpNotification(Box::new(notification.clone())).method(),
8711            "mcp/message"
8712        );
8713        assert_eq!(
8714            serde_json::to_value(notification).unwrap(),
8715            json!({
8716                "serverId": "server-1",
8717                "requestId": "req-1",
8718                "method": "notifications/progress"
8719            })
8720        );
8721        let notification: MessageMcpNotification = serde_json::from_value(json!({
8722            "serverId": "server-1", "requestId": "req-1", "method": "notifications/progress",
8723            "params": null, "_meta": null
8724        }))
8725        .unwrap();
8726        assert_eq!(notification.params, None);
8727        assert_eq!(notification.meta, None);
8728        for key in ["serverId", "requestId", "method"] {
8729            let mut value = json!({"serverId":"server-1", "requestId":"req-1", "method":"notifications/progress"});
8730            value.as_object_mut().unwrap().remove(key);
8731            assert!(serde_json::from_value::<MessageMcpNotification>(value).is_err());
8732        }
8733    }
8734
8735    #[test]
8736    fn test_auth_method_names() {
8737        assert_eq!(AGENT_METHOD_NAMES.auth_login, "auth/login");
8738        assert_eq!(AGENT_METHOD_NAMES.auth_logout, "auth/logout");
8739
8740        assert_eq!(
8741            ClientRequest::LoginAuthRequest(Box::new(LoginAuthRequest::new("agent-login")))
8742                .method(),
8743            "auth/login"
8744        );
8745        assert_eq!(
8746            ClientRequest::LogoutAuthRequest(Box::new(LogoutAuthRequest::new())).method(),
8747            "auth/logout"
8748        );
8749    }
8750
8751    #[test]
8752    fn test_session_config_option_category_known_variants() {
8753        // Test serialization of known variants
8754        assert_eq!(
8755            serde_json::to_value(&SessionConfigOptionCategory::Mode).unwrap(),
8756            json!("mode")
8757        );
8758        assert_eq!(
8759            serde_json::to_value(&SessionConfigOptionCategory::Model).unwrap(),
8760            json!("model")
8761        );
8762        assert_eq!(
8763            serde_json::to_value(&SessionConfigOptionCategory::ModelConfig).unwrap(),
8764            json!("model_config")
8765        );
8766        #[cfg(feature = "unstable_speed_config_category")]
8767        assert_eq!(
8768            serde_json::to_value(&SessionConfigOptionCategory::Speed).unwrap(),
8769            json!("speed")
8770        );
8771        assert_eq!(
8772            serde_json::to_value(&SessionConfigOptionCategory::ThoughtLevel).unwrap(),
8773            json!("thought_level")
8774        );
8775
8776        // Test deserialization of known variants
8777        assert_eq!(
8778            serde_json::from_str::<SessionConfigOptionCategory>("\"mode\"").unwrap(),
8779            SessionConfigOptionCategory::Mode
8780        );
8781        assert_eq!(
8782            serde_json::from_str::<SessionConfigOptionCategory>("\"model\"").unwrap(),
8783            SessionConfigOptionCategory::Model
8784        );
8785        assert_eq!(
8786            serde_json::from_str::<SessionConfigOptionCategory>("\"model_config\"").unwrap(),
8787            SessionConfigOptionCategory::ModelConfig
8788        );
8789        #[cfg(feature = "unstable_speed_config_category")]
8790        assert_eq!(
8791            serde_json::from_str::<SessionConfigOptionCategory>("\"speed\"").unwrap(),
8792            SessionConfigOptionCategory::Speed
8793        );
8794        assert_eq!(
8795            serde_json::from_str::<SessionConfigOptionCategory>("\"thought_level\"").unwrap(),
8796            SessionConfigOptionCategory::ThoughtLevel
8797        );
8798    }
8799
8800    #[test]
8801    fn test_session_config_option_category_unknown_variants() {
8802        // Test that unknown strings are captured in Other variant
8803        let unknown: SessionConfigOptionCategory =
8804            serde_json::from_str("\"some_future_category\"").unwrap();
8805        assert_eq!(
8806            unknown,
8807            SessionConfigOptionCategory::Other("some_future_category".to_string())
8808        );
8809
8810        // Test round-trip of unknown category
8811        let json = serde_json::to_value(&unknown).unwrap();
8812        assert_eq!(json, json!("some_future_category"));
8813    }
8814
8815    #[cfg(not(feature = "unstable_speed_config_category"))]
8816    #[test]
8817    fn test_session_config_option_speed_is_unknown_without_feature() {
8818        let unknown: SessionConfigOptionCategory = serde_json::from_str("\"speed\"").unwrap();
8819        assert_eq!(
8820            unknown,
8821            SessionConfigOptionCategory::Other("speed".to_string())
8822        );
8823    }
8824
8825    #[test]
8826    fn test_session_config_option_category_custom_categories() {
8827        // Category names beginning with `_` are free for custom use
8828        let custom: SessionConfigOptionCategory =
8829            serde_json::from_str("\"_my_custom_category\"").unwrap();
8830        assert_eq!(
8831            custom,
8832            SessionConfigOptionCategory::Other("_my_custom_category".to_string())
8833        );
8834
8835        // Test round-trip preserves the custom category name
8836        let json = serde_json::to_value(&custom).unwrap();
8837        assert_eq!(json, json!("_my_custom_category"));
8838
8839        // Deserialize back and verify
8840        let deserialized: SessionConfigOptionCategory = serde_json::from_value(json).unwrap();
8841        assert_eq!(
8842            deserialized,
8843            SessionConfigOptionCategory::Other("_my_custom_category".to_string()),
8844        );
8845    }
8846
8847    fn test_config_option() -> SessionConfigOption {
8848        SessionConfigOption::select(
8849            "mode",
8850            "Mode",
8851            "ask",
8852            vec![SessionConfigSelectOption::new("ask", "Ask")],
8853        )
8854    }
8855
8856    #[test]
8857    fn test_session_response_initial_state_default_empty_and_skip_serializing() {
8858        assert_eq!(
8859            serde_json::to_value(NewSessionResponse::new("sess")).unwrap(),
8860            json!({ "sessionId": "sess" })
8861        );
8862        assert_eq!(
8863            serde_json::to_value(ResumeSessionResponse::new()).unwrap(),
8864            json!({})
8865        );
8866        #[cfg(feature = "unstable_session_fork")]
8867        assert_eq!(
8868            serde_json::to_value(ForkSessionResponse::new("fork")).unwrap(),
8869            json!({ "sessionId": "fork" })
8870        );
8871
8872        let json = serde_json::to_value(
8873            NewSessionResponse::new("sess").config_options(vec![test_config_option()]),
8874        )
8875        .unwrap();
8876        assert_eq!(json["configOptions"].as_array().unwrap().len(), 1);
8877    }
8878
8879    #[test]
8880    fn test_session_response_config_options_deserialize_missing_null_and_invalid() {
8881        let missing: NewSessionResponse =
8882            serde_json::from_value(json!({ "sessionId": "sess" })).unwrap();
8883        assert_eq!(missing.config_options, []);
8884
8885        let null: NewSessionResponse = serde_json::from_value(json!({
8886            "sessionId": "sess",
8887            "configOptions": null
8888        }))
8889        .unwrap();
8890        assert_eq!(null.config_options, []);
8891
8892        let wrong_shape: NewSessionResponse = serde_json::from_value(json!({
8893            "sessionId": "sess",
8894            "configOptions": "oops"
8895        }))
8896        .unwrap();
8897        assert_eq!(wrong_shape.config_options, []);
8898
8899        let valid_option = serde_json::to_value(test_config_option()).unwrap();
8900        let mixed: NewSessionResponse = serde_json::from_value(json!({
8901            "sessionId": "sess",
8902            "configOptions": ["oops", valid_option]
8903        }))
8904        .unwrap();
8905        assert_eq!(mixed.config_options.len(), 1);
8906
8907        let resume: ResumeSessionResponse = serde_json::from_value(json!({})).unwrap();
8908        assert_eq!(resume.config_options, []);
8909        #[cfg(feature = "unstable_session_fork")]
8910        {
8911            let fork: ForkSessionResponse =
8912                serde_json::from_value(json!({ "sessionId": "fork" })).unwrap();
8913            assert_eq!(fork.config_options, []);
8914        }
8915    }
8916
8917    #[test]
8918    fn test_session_response_available_commands_roundtrip_with_config_options() {
8919        use super::super::{AvailableCommandInput, Command, TextCommandInput};
8920
8921        let commands = vec![
8922            AvailableCommand::Command(
8923                Command::new("web", "Search the web")
8924                    .input(AvailableCommandInput::Text(TextCommandInput::new("Query"))),
8925            ),
8926            AvailableCommand::Command(Command::new("test", "Run project tests")),
8927        ];
8928        let mut expected = json!({
8929            "sessionId": "sess",
8930            "configOptions": [test_config_option()],
8931            "availableCommands": [
8932                {
8933                    "type": "command",
8934                    "name": "web",
8935                    "description": "Search the web",
8936                    "input": { "type": "text", "hint": "Query" }
8937                },
8938                { "type": "command", "name": "test", "description": "Run project tests" }
8939            ]
8940        });
8941
8942        let new = NewSessionResponse::new("sess")
8943            .config_options(vec![test_config_option()])
8944            .available_commands(commands.clone());
8945        assert_eq!(serde_json::to_value(&new).unwrap(), expected);
8946        assert_eq!(
8947            serde_json::from_value::<NewSessionResponse>(expected.clone()).unwrap(),
8948            new
8949        );
8950
8951        expected.as_object_mut().unwrap().remove("sessionId");
8952        let resume = ResumeSessionResponse::new()
8953            .config_options(vec![test_config_option()])
8954            .available_commands(commands.clone());
8955        assert_eq!(serde_json::to_value(&resume).unwrap(), expected);
8956        assert_eq!(
8957            serde_json::from_value::<ResumeSessionResponse>(expected.clone()).unwrap(),
8958            resume
8959        );
8960
8961        #[cfg(feature = "unstable_session_fork")]
8962        {
8963            expected["sessionId"] = json!("fork");
8964            let fork = ForkSessionResponse::new("fork")
8965                .config_options(vec![test_config_option()])
8966                .available_commands(commands);
8967            assert_eq!(serde_json::to_value(&fork).unwrap(), expected);
8968            assert_eq!(
8969                serde_json::from_value::<ForkSessionResponse>(expected).unwrap(),
8970                fork
8971            );
8972        }
8973    }
8974
8975    #[test]
8976    fn test_session_response_available_commands_deserialize_missing_null_and_invalid() {
8977        let command =
8978            AvailableCommand::Command(super::super::Command::new("test", "Run project tests"));
8979        let config_options = vec![test_config_option()];
8980
8981        for (commands, expected) in [
8982            (None, vec![]),
8983            (Some(json!(null)), vec![]),
8984            (Some(json!([])), vec![]),
8985            (Some(json!("oops")), vec![]),
8986            (Some(json!({})), vec![]),
8987            (Some(json!([null, {}, { "name": "invalid" }])), vec![]),
8988            (
8989                Some(json!([{ "name": "test", "description": "Run project tests" }])),
8990                vec![],
8991            ),
8992            (
8993                Some(json!([null, command, { "name": "invalid" }])),
8994                vec![command.clone()],
8995            ),
8996        ] {
8997            let mut value = json!({
8998                "sessionId": "sess",
8999                "configOptions": config_options
9000            });
9001            if let Some(commands) = commands {
9002                value["availableCommands"] = commands;
9003            }
9004
9005            let new: NewSessionResponse = serde_json::from_value(value.clone()).unwrap();
9006            assert_eq!(new.available_commands, expected);
9007            assert_eq!(new.config_options, config_options);
9008
9009            #[cfg(feature = "unstable_session_fork")]
9010            {
9011                let fork: ForkSessionResponse = serde_json::from_value(value.clone()).unwrap();
9012                assert_eq!(fork.available_commands, expected);
9013                assert_eq!(fork.config_options, config_options);
9014            }
9015
9016            value.as_object_mut().unwrap().remove("sessionId");
9017            let resume: ResumeSessionResponse = serde_json::from_value(value).unwrap();
9018            assert_eq!(resume.available_commands, expected);
9019            assert_eq!(resume.config_options, config_options);
9020        }
9021
9022        let resume: ResumeSessionResponse = serde_json::from_value(json!(null)).unwrap();
9023        assert_eq!(resume.available_commands, []);
9024    }
9025
9026    #[test]
9027    fn test_resume_session_replay_from_serialization() {
9028        assert_eq!(
9029            serde_json::to_value(ResumeSessionRequest::new(
9030                "sess_abc123",
9031                "/home/user/project"
9032            ))
9033            .unwrap(),
9034            json!({
9035                "sessionId": "sess_abc123",
9036                "cwd": "/home/user/project"
9037            })
9038        );
9039        assert_eq!(
9040            serde_json::to_value(
9041                ResumeSessionRequest::new("sess_abc123", "/home/user/project")
9042                    .replay_from(ReplayFrom::from(ReplayFromStart::new()))
9043            )
9044            .unwrap(),
9045            json!({
9046                "sessionId": "sess_abc123",
9047                "cwd": "/home/user/project",
9048                "replayFrom": {
9049                    "type": "start"
9050                }
9051            })
9052        );
9053
9054        let replay: ResumeSessionRequest = serde_json::from_value(json!({
9055            "sessionId": "sess_abc123",
9056            "cwd": "/home/user/project",
9057            "replayFrom": {
9058                "type": "start"
9059            }
9060        }))
9061        .unwrap();
9062        assert!(matches!(replay.replay_from, Some(ReplayFrom::Start(_))));
9063
9064        let none: ResumeSessionRequest = serde_json::from_value(json!({
9065            "sessionId": "sess_abc123",
9066            "cwd": "/home/user/project",
9067            "replayFrom": null
9068        }))
9069        .unwrap();
9070        assert!(none.replay_from.is_none());
9071    }
9072
9073    #[test]
9074    fn test_auth_method_agent_serialization() {
9075        let method = AuthMethod::Agent(AuthMethodAgent::new("default-auth", "Default Auth"));
9076
9077        let json = serde_json::to_value(&method).unwrap();
9078        assert_eq!(
9079            json,
9080            json!({
9081                "methodId": "default-auth",
9082                "name": "Default Auth",
9083                "type": "agent"
9084            })
9085        );
9086        // description should be omitted when None
9087        assert!(!json.as_object().unwrap().contains_key("description"));
9088
9089        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9090        match deserialized {
9091            AuthMethod::Agent(AuthMethodAgent {
9092                method_id, name, ..
9093            }) => {
9094                assert_eq!(method_id.0.as_ref(), "default-auth");
9095                assert_eq!(name, "Default Auth");
9096            }
9097            _ => panic!("Expected Agent variant"),
9098        }
9099    }
9100
9101    #[test]
9102    fn test_auth_method_agent_deserialization() {
9103        let json = json!({
9104            "methodId": "agent-auth",
9105            "name": "Agent Auth",
9106            "type": "agent"
9107        });
9108
9109        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9110        assert!(matches!(deserialized, AuthMethod::Agent(_)));
9111    }
9112
9113    #[test]
9114    fn test_auth_method_agent_requires_type() {
9115        assert!(
9116            serde_json::from_value::<AuthMethod>(json!({
9117                "methodId": "agent-auth",
9118                "name": "Agent Auth"
9119            }))
9120            .is_err()
9121        );
9122    }
9123
9124    #[test]
9125    fn test_auth_method_agent_rejects_null_type() {
9126        assert!(
9127            serde_json::from_value::<AuthMethod>(json!({
9128                "methodId": "agent-auth",
9129                "name": "Agent Auth",
9130                "type": null
9131            }))
9132            .is_err()
9133        );
9134    }
9135
9136    #[test]
9137    fn test_auth_method_unknown_does_not_hide_malformed_agent() {
9138        assert!(
9139            serde_json::from_value::<AuthMethod>(json!({
9140                "methodId": "agent-auth",
9141                "type": "agent"
9142            }))
9143            .is_err()
9144        );
9145        assert!(
9146            serde_json::from_value::<AuthMethod>(json!({
9147                "methodId": "api-key",
9148                "type": "env_var",
9149                "vars": [{"name": "API_KEY"}]
9150            }))
9151            .is_err()
9152        );
9153    }
9154
9155    #[test]
9156    fn test_auth_method_unknown_variant_roundtrip() {
9157        let method: AuthMethod = serde_json::from_value(json!({
9158            "methodId": "oauth",
9159            "name": "OAuth",
9160            "type": "_oauth",
9161            "authorizationUrl": "https://example.com/auth"
9162        }))
9163        .unwrap();
9164
9165        assert_eq!(method.method_id().0.as_ref(), "oauth");
9166        assert_eq!(method.name(), "OAuth");
9167        let AuthMethod::Other(unknown) = method else {
9168            panic!("expected unknown auth method");
9169        };
9170        assert_eq!(unknown.type_, "_oauth");
9171        assert_eq!(
9172            unknown.fields.get("authorizationUrl"),
9173            Some(&json!("https://example.com/auth"))
9174        );
9175
9176        assert_eq!(
9177            serde_json::to_value(AuthMethod::Other(unknown)).unwrap(),
9178            json!({
9179                "methodId": "oauth",
9180                "name": "OAuth",
9181                "type": "_oauth",
9182                "authorizationUrl": "https://example.com/auth"
9183            })
9184        );
9185    }
9186
9187    #[test]
9188    fn test_auth_method_unknown_does_not_hide_malformed_known_variant() {
9189        assert!(
9190            serde_json::from_value::<AuthMethod>(json!({
9191                "methodId": "terminal-auth",
9192                "type": "terminal"
9193            }))
9194            .is_err()
9195        );
9196    }
9197
9198    #[test]
9199    fn test_tool_call_and_terminal_cancel_serialization() {
9200        assert_eq!(AGENT_METHOD_NAMES.tool_call_cancel, "tool_call/cancel");
9201        assert_eq!(AGENT_METHOD_NAMES.terminal_cancel, "terminal/cancel");
9202        assert_eq!(
9203            ClientRequest::CancelToolCallRequest(Box::new(CancelToolCallRequest::new(
9204                "sess_abc123",
9205                "call_012"
9206            )))
9207            .method(),
9208            "tool_call/cancel"
9209        );
9210        assert_eq!(
9211            ClientRequest::CancelTerminalRequest(Box::new(CancelTerminalRequest::new(
9212                "sess_abc123",
9213                "term_003"
9214            )))
9215            .method(),
9216            "terminal/cancel"
9217        );
9218        assert_eq!(
9219            serde_json::to_value(CancelToolCallRequest::new("sess_abc123", "call_012")).unwrap(),
9220            json!({"sessionId": "sess_abc123", "toolCallId": "call_012"})
9221        );
9222        assert_eq!(
9223            serde_json::to_value(CancelTerminalRequest::new("sess_abc123", "term_003")).unwrap(),
9224            json!({"sessionId": "sess_abc123", "terminalId": "term_003"})
9225        );
9226        assert!(
9227            serde_json::from_value::<CancelToolCallRequest>(json!({"sessionId": "sess_abc123"}))
9228                .is_err()
9229        );
9230        assert_eq!(
9231            serde_json::to_value(CancelTerminalResponse::new()).unwrap(),
9232            json!({})
9233        );
9234    }
9235
9236    #[test]
9237    fn test_session_delete_serialization() {
9238        assert_eq!(AGENT_METHOD_NAMES.session_delete, "session/delete");
9239        assert_eq!(
9240            ClientRequest::DeleteSessionRequest(Box::new(DeleteSessionRequest::new("sess_abc123")))
9241                .method(),
9242            "session/delete"
9243        );
9244        assert_eq!(
9245            serde_json::to_value(DeleteSessionRequest::new("sess_abc123")).unwrap(),
9246            json!({
9247                "sessionId": "sess_abc123"
9248            })
9249        );
9250        assert_eq!(
9251            serde_json::to_value(DeleteSessionResponse::new()).unwrap(),
9252            json!({})
9253        );
9254        assert_eq!(
9255            serde_json::to_value(
9256                SessionCapabilities::new().delete(SessionDeleteCapabilities::new())
9257            )
9258            .unwrap(),
9259            json!({
9260                "delete": {}
9261            })
9262        );
9263    }
9264    #[cfg(feature = "unstable_session_set_title")]
9265    #[test]
9266    fn test_session_set_title_serialization() {
9267        assert_eq!(AGENT_METHOD_NAMES.session_set_title, "session/set_title");
9268        assert_eq!(
9269            ClientRequest::SetSessionTitleRequest(Box::new(SetSessionTitleRequest::new(
9270                "sess_abc123",
9271                "Investigate OAuth timeout"
9272            )))
9273            .method(),
9274            "session/set_title"
9275        );
9276        assert_eq!(
9277            serde_json::to_value(SetSessionTitleRequest::new(
9278                "sess_abc123",
9279                "Investigate OAuth timeout"
9280            ))
9281            .unwrap(),
9282            json!({
9283                "sessionId": "sess_abc123",
9284                "title": "Investigate OAuth timeout"
9285            })
9286        );
9287        assert_eq!(
9288            serde_json::to_value(SetSessionTitleResponse::new("Investigate OAuth timeout"))
9289                .unwrap(),
9290            json!({
9291                "title": "Investigate OAuth timeout"
9292            })
9293        );
9294        assert_eq!(
9295            serde_json::to_value(SessionCapabilities::new().title(SessionTitleCapabilities::new()))
9296                .unwrap(),
9297            json!({
9298                "title": {}
9299            })
9300        );
9301    }
9302
9303    #[cfg(feature = "unstable_session_set_title")]
9304    #[test]
9305    fn test_session_set_title_requires_title() {
9306        for params in [
9307            json!({"sessionId": "sess_abc123"}),
9308            json!({"sessionId": "sess_abc123", "title": null}),
9309            json!({"sessionId": "sess_abc123", "title": 42}),
9310        ] {
9311            assert!(serde_json::from_value::<SetSessionTitleRequest>(params).is_err());
9312        }
9313        for result in [json!({}), json!({"title": null})] {
9314            assert!(serde_json::from_value::<SetSessionTitleResponse>(result).is_err());
9315        }
9316    }
9317
9318    #[cfg(feature = "unstable_session_options")]
9319    #[test]
9320    fn test_session_options_serialization() {
9321        assert_eq!(AGENT_METHOD_NAMES.session_options, "session/options");
9322        assert_eq!(
9323            ClientRequest::SessionOptionsRequest(Box::new(SessionOptionsRequest::new(
9324                "/home/user/project"
9325            )))
9326            .method(),
9327            "session/options"
9328        );
9329        assert_eq!(
9330            serde_json::to_value(
9331                SessionOptionsRequest::new("/home/user/project")
9332                    .session_id(SessionId::new("sess_abc123"))
9333            )
9334            .unwrap(),
9335            json!({"cwd": "/home/user/project", "sessionId": "sess_abc123"})
9336        );
9337        assert_eq!(
9338            serde_json::from_value::<SessionOptionsRequest>(
9339                json!({"cwd": "/home/user/project", "additionalDirectories": null, "sessionId": null})
9340            )
9341            .unwrap(),
9342            SessionOptionsRequest::new("/home/user/project")
9343        );
9344        let request = NewSessionRequest::new("/home/user/project").config_options(vec![
9345            InitialSessionConfigOption::new("model", SessionConfigOptionValue::id("model-2")),
9346            InitialSessionConfigOption::new("fast", SessionConfigOptionValue::boolean(true)),
9347        ]);
9348        let value = serde_json::to_value(&request).unwrap();
9349        assert_eq!(
9350            value["configOptions"],
9351            json!([
9352                {"configId": "model", "type": "id", "value": "model-2"},
9353                {"configId": "fast", "type": "boolean", "value": true}
9354            ])
9355        );
9356        assert_eq!(
9357            serde_json::from_value::<NewSessionRequest>(value).unwrap(),
9358            request
9359        );
9360        assert!(
9361            serde_json::from_value::<NewSessionRequest>(json!({
9362                "cwd": "/home/user/project",
9363                "mcpServers": [],
9364                "configOptions": [{"type": "boolean", "value": true}]
9365            }))
9366            .is_err()
9367        );
9368        assert_eq!(
9369            serde_json::to_value(SessionOptionsResponse::new()).unwrap(),
9370            json!({})
9371        );
9372        #[cfg(feature = "unstable_session_fork")]
9373        {
9374            let fork =
9375                ForkSessionRequest::new("sess_abc123", "/home/user/project").config_options(vec![
9376                    InitialSessionConfigOption::new(
9377                        "model",
9378                        SessionConfigOptionValue::id("model-2"),
9379                    ),
9380                ]);
9381            let value = serde_json::to_value(&fork).unwrap();
9382            assert_eq!(
9383                value["configOptions"],
9384                json!([{"configId": "model", "type": "id", "value": "model-2"}])
9385            );
9386            assert_eq!(
9387                serde_json::from_value::<ForkSessionRequest>(value).unwrap(),
9388                fork
9389            );
9390            // `null` is an empty list, and a malformed entry fails the request.
9391            assert_eq!(
9392                serde_json::from_value::<ForkSessionRequest>(json!({
9393                    "sessionId": "sess_abc123",
9394                    "cwd": "/home/user/project",
9395                    "configOptions": null
9396                }))
9397                .unwrap(),
9398                ForkSessionRequest::new("sess_abc123", "/home/user/project")
9399            );
9400            assert!(
9401                serde_json::from_value::<ForkSessionRequest>(json!({
9402                    "sessionId": "sess_abc123",
9403                    "cwd": "/home/user/project",
9404                    "configOptions": [{"type": "boolean", "value": true}]
9405                }))
9406                .is_err()
9407            );
9408        }
9409        assert_eq!(
9410            serde_json::to_value(
9411                SessionCapabilities::new().options(SessionOptionsCapabilities::new())
9412            )
9413            .unwrap(),
9414            json!({"options": {}})
9415        );
9416    }
9417
9418    #[cfg(feature = "unstable_session_status")]
9419    #[test]
9420    fn test_session_status_serialization() {
9421        assert_eq!(AGENT_METHOD_NAMES.session_status, "session/status");
9422        assert_eq!(
9423            ClientRequest::SessionStatusRequest(Box::new(SessionStatusRequest::new("sess_abc123")))
9424                .method(),
9425            "session/status"
9426        );
9427        assert_eq!(
9428            serde_json::to_value(SessionStatusRequest::new("sess_abc123")).unwrap(),
9429            json!({"sessionId": "sess_abc123"})
9430        );
9431        assert_eq!(
9432            serde_json::to_value(SessionStatusResponse::new(SessionStatus::Saved)).unwrap(),
9433            json!({"status": "saved"})
9434        );
9435        assert_eq!(
9436            serde_json::to_value(
9437                SessionCapabilities::new().status(SessionStatusCapabilities::new())
9438            )
9439            .unwrap(),
9440            json!({"status": {}})
9441        );
9442        assert_eq!(
9443            serde_json::to_value(SessionStatusResponse::new(SessionStatus::Open).state(
9444                StateUpdate::RequiresAction(crate::v2::RequiresActionStateUpdate::new())
9445            ))
9446            .unwrap(),
9447            json!({
9448                "status": "open",
9449                "state": {"state": "requires_action"}
9450            })
9451        );
9452        for state in [json!(null), json!("running"), json!({"state": 7})] {
9453            let response = serde_json::from_value::<SessionStatusResponse>(
9454                json!({"status": "open", "state": state}),
9455            )
9456            .unwrap();
9457            assert_eq!(response.state, None);
9458        }
9459    }
9460
9461    #[cfg(feature = "unstable_session_status")]
9462    #[test]
9463    fn test_session_status_is_strict_and_open() {
9464        let custom =
9465            serde_json::from_value::<SessionStatusResponse>(json!({"status": "_suspended"}))
9466                .unwrap();
9467        assert_eq!(
9468            custom.status,
9469            SessionStatus::Other("_suspended".to_string())
9470        );
9471        assert_eq!(
9472            serde_json::to_value(&custom).unwrap(),
9473            json!({"status": "_suspended"})
9474        );
9475        for result in [json!({}), json!({"status": null}), json!({"status": 1})] {
9476            assert!(serde_json::from_value::<SessionStatusResponse>(result).is_err());
9477        }
9478        for params in [json!({}), json!({"sessionId": null})] {
9479            assert!(serde_json::from_value::<SessionStatusRequest>(params).is_err());
9480        }
9481    }
9482
9483    #[cfg(feature = "unstable_session_archive")]
9484    #[test]
9485    fn test_session_archive_serialization() {
9486        assert_eq!(AGENT_METHOD_NAMES.session_archive, "session/archive");
9487        assert_eq!(AGENT_METHOD_NAMES.session_unarchive, "session/unarchive");
9488        assert_eq!(
9489            ClientRequest::ArchiveSessionRequest(Box::new(ArchiveSessionRequest::new(
9490                "sess_abc123"
9491            )))
9492            .method(),
9493            "session/archive"
9494        );
9495        assert_eq!(
9496            ClientRequest::UnarchiveSessionRequest(Box::new(UnarchiveSessionRequest::new(
9497                "sess_abc123"
9498            )))
9499            .method(),
9500            "session/unarchive"
9501        );
9502        assert_eq!(
9503            serde_json::to_value(ArchiveSessionRequest::new("sess_abc123")).unwrap(),
9504            json!({"sessionId": "sess_abc123"})
9505        );
9506        assert_eq!(
9507            serde_json::to_value(UnarchiveSessionResponse::new()).unwrap(),
9508            json!({})
9509        );
9510        assert_eq!(
9511            serde_json::to_value(
9512                SessionCapabilities::new().archive(SessionArchiveCapabilities::new())
9513            )
9514            .unwrap(),
9515            json!({"archive": {}})
9516        );
9517        assert_eq!(
9518            serde_json::to_value(
9519                ListSessionsRequest::new()
9520                    .cwd("/home/user/project")
9521                    .archived(SessionArchiveFilter::Only)
9522            )
9523            .unwrap(),
9524            json!({"cwd": "/home/user/project", "archived": "only"})
9525        );
9526        assert_eq!(
9527            serde_json::to_value(
9528                SessionInfo::new("sess_abc123", "/home/user/project").archived(true)
9529            )
9530            .unwrap(),
9531            json!({"sessionId": "sess_abc123", "cwd": "/home/user/project", "archived": true})
9532        );
9533    }
9534
9535    #[cfg(feature = "unstable_session_archive")]
9536    #[test]
9537    fn test_session_archive_filter_is_strict_and_open() {
9538        for (value, expected) in [
9539            (json!(null), None),
9540            (json!("include"), Some(SessionArchiveFilter::Include)),
9541            (
9542                json!("_recent"),
9543                Some(SessionArchiveFilter::Other("_recent".to_string())),
9544            ),
9545        ] {
9546            let request =
9547                serde_json::from_value::<ListSessionsRequest>(json!({"archived": value})).unwrap();
9548            assert_eq!(request.archived, expected);
9549        }
9550        for value in [json!(true), json!(1), json!({})] {
9551            assert!(
9552                serde_json::from_value::<ListSessionsRequest>(json!({"archived": value})).is_err()
9553            );
9554        }
9555        let info = serde_json::from_value::<SessionInfo>(
9556            json!({"sessionId": "sess_abc123", "cwd": "/home/user/project", "archived": "yes"}),
9557        )
9558        .unwrap();
9559        assert_eq!(info.archived, None);
9560    }
9561
9562    #[test]
9563    fn test_session_additional_directories_serialization() {
9564        assert_eq!(
9565            serde_json::to_value(NewSessionRequest::new("/home/user/project")).unwrap(),
9566            json!({
9567                "cwd": "/home/user/project",
9568            })
9569        );
9570        assert_eq!(
9571            serde_json::to_value(
9572                NewSessionRequest::new("/home/user/project").additional_directories(vec![
9573                    PathBuf::from("/home/user/shared-lib"),
9574                    PathBuf::from("/home/user/product-docs"),
9575                ])
9576            )
9577            .unwrap(),
9578            json!({
9579                "cwd": "/home/user/project",
9580                "additionalDirectories": [
9581                    "/home/user/shared-lib",
9582                    "/home/user/product-docs"
9583                ],
9584            })
9585        );
9586        assert_eq!(
9587            serde_json::to_value(ResumeSessionRequest::new(
9588                "sess_abc123",
9589                "/home/user/project"
9590            ))
9591            .unwrap(),
9592            json!({
9593                "sessionId": "sess_abc123",
9594                "cwd": "/home/user/project",
9595            })
9596        );
9597        assert_eq!(
9598            serde_json::from_value::<ResumeSessionRequest>(json!({
9599                "sessionId": "sess_abc123",
9600                "cwd": "/home/user/project"
9601            }))
9602            .unwrap()
9603            .mcp_servers,
9604            Vec::<McpServer>::new()
9605        );
9606        assert_eq!(
9607            serde_json::from_value::<ResumeSessionRequest>(json!({
9608                "sessionId": "sess_abc123",
9609                "cwd": "/home/user/project",
9610                "mcpServers": null
9611            }))
9612            .unwrap()
9613            .mcp_servers,
9614            Vec::<McpServer>::new()
9615        );
9616        assert_eq!(
9617            serde_json::to_value(SessionInfo::new("sess_abc123", "/home/user/project")).unwrap(),
9618            json!({
9619                "sessionId": "sess_abc123",
9620                "cwd": "/home/user/project"
9621            })
9622        );
9623        assert_eq!(
9624            serde_json::to_value(
9625                SessionInfo::new("sess_abc123", "/home/user/project").additional_directories(vec![
9626                    PathBuf::from("/home/user/shared-lib"),
9627                    PathBuf::from("/home/user/product-docs"),
9628                ])
9629            )
9630            .unwrap(),
9631            json!({
9632                "sessionId": "sess_abc123",
9633                "cwd": "/home/user/project",
9634                "additionalDirectories": [
9635                    "/home/user/shared-lib",
9636                    "/home/user/product-docs"
9637                ]
9638            })
9639        );
9640        assert_eq!(
9641            serde_json::from_value::<SessionInfo>(json!({
9642                "sessionId": "sess_abc123",
9643                "cwd": "/home/user/project"
9644            }))
9645            .unwrap()
9646            .additional_directories,
9647            Vec::<AbsolutePath>::new()
9648        );
9649    }
9650    #[test]
9651    fn test_session_additional_directories_capabilities_serialization() {
9652        assert_eq!(
9653            serde_json::to_value(
9654                SessionCapabilities::new()
9655                    .additional_directories(SessionAdditionalDirectoriesCapabilities::new())
9656            )
9657            .unwrap(),
9658            json!({
9659                "additionalDirectories": {}
9660            })
9661        );
9662    }
9663
9664    #[test]
9665    fn test_session_system_prompt_capabilities_serialization() {
9666        assert_eq!(
9667            serde_json::to_value(
9668                SessionCapabilities::new().system_prompt(SessionSystemPromptCapabilities::new())
9669            )
9670            .unwrap(),
9671            json!({ "systemPrompt": {} })
9672        );
9673        assert_eq!(
9674            serde_json::to_value(
9675                SessionCapabilities::new().system_prompt(
9676                    SessionSystemPromptCapabilities::new().mode(
9677                        SessionSystemPromptModeCapabilities::new()
9678                            .override_(SessionSystemPromptOverrideCapabilities::new())
9679                    )
9680                )
9681            )
9682            .unwrap(),
9683            json!({ "systemPrompt": { "mode": { "override": {} } } })
9684        );
9685        assert_eq!(
9686            serde_json::from_value::<SessionCapabilities>(
9687                json!({ "systemPrompt": { "mode": { "override": {} } } })
9688            )
9689            .unwrap()
9690            .system_prompt
9691            .and_then(|capabilities| capabilities.mode)
9692            .and_then(|mode| mode.override_),
9693            Some(SessionSystemPromptOverrideCapabilities::new())
9694        );
9695
9696        // Capabilities fall back to "not advertised" when malformed.
9697        assert_eq!(
9698            serde_json::from_value::<SessionCapabilities>(json!({ "systemPrompt": "yes" }))
9699                .unwrap()
9700                .system_prompt,
9701            None
9702        );
9703        assert_eq!(
9704            serde_json::from_value::<SessionCapabilities>(
9705                json!({ "systemPrompt": { "mode": { "override": true } } })
9706            )
9707            .unwrap()
9708            .system_prompt,
9709            Some(
9710                SessionSystemPromptCapabilities::new()
9711                    .mode(SessionSystemPromptModeCapabilities::new())
9712            )
9713        );
9714        assert_eq!(
9715            serde_json::from_value::<SessionCapabilities>(
9716                json!({ "systemPrompt": { "mode": "override" } })
9717            )
9718            .unwrap()
9719            .system_prompt,
9720            Some(SessionSystemPromptCapabilities::new())
9721        );
9722    }
9723
9724    #[test]
9725    fn test_system_prompt_lifecycle_request_serialization() {
9726        let system_prompt = SystemPrompt::new(vec![ContentBlock::from(
9727            "You are a code review specialist.",
9728        )]);
9729        let system_prompt_json = json!({
9730            "mode": "append",
9731            "content": [{ "type": "text", "text": "You are a code review specialist." }]
9732        });
9733
9734        let request =
9735            NewSessionRequest::new("/home/user/project").system_prompt(system_prompt.clone());
9736        let request_json = json!({
9737            "cwd": "/home/user/project",
9738            "systemPrompt": system_prompt_json
9739        });
9740        assert_eq!(serde_json::to_value(&request).unwrap(), request_json);
9741        assert_eq!(
9742            serde_json::from_value::<NewSessionRequest>(request_json).unwrap(),
9743            request
9744        );
9745
9746        assert_eq!(
9747            serde_json::to_value(
9748                ResumeSessionRequest::new("sess_abc123", "/home/user/project")
9749                    .system_prompt(system_prompt.clone())
9750            )
9751            .unwrap()["systemPrompt"],
9752            system_prompt_json
9753        );
9754        #[cfg(feature = "unstable_session_fork")]
9755        assert_eq!(
9756            serde_json::to_value(
9757                ForkSessionRequest::new("sess_abc123", "/home/user/project")
9758                    .system_prompt(system_prompt.clone())
9759            )
9760            .unwrap()["systemPrompt"],
9761            system_prompt_json
9762        );
9763
9764        let override_prompt =
9765            SystemPrompt::new(vec![ContentBlock::from("...")]).mode(SystemPromptMode::Override);
9766        let override_json = json!({
9767            "mode": "override",
9768            "content": [{ "type": "text", "text": "..." }]
9769        });
9770        assert_eq!(
9771            serde_json::to_value(&override_prompt).unwrap(),
9772            override_json
9773        );
9774        assert_eq!(
9775            serde_json::from_value::<SystemPrompt>(override_json).unwrap(),
9776            override_prompt
9777        );
9778    }
9779
9780    /// `SystemPrompt::new` defaults to `append` in Rust, but `mode` is required on
9781    /// the wire, so it is always serialized.
9782    #[test]
9783    fn test_system_prompt_new_defaults_to_append() {
9784        let system_prompt = SystemPrompt::new(vec![ContentBlock::from("...")]);
9785        assert_eq!(system_prompt.mode, SystemPromptMode::Append);
9786        assert_eq!(
9787            serde_json::to_value(&system_prompt).unwrap(),
9788            json!({ "mode": "append", "content": [{ "type": "text", "text": "..." }] })
9789        );
9790    }
9791
9792    /// Unknown modes follow the enum variant extension rule: they parse as
9793    /// `SystemPromptMode::Other` so they are not dropped, and an Agent that does
9794    /// not support them must reject the request.
9795    #[test]
9796    fn test_system_prompt_preserves_unknown_modes() {
9797        for mode in ["_vendor_mode", "prepend"] {
9798            let system_prompt_json =
9799                json!({ "mode": mode, "content": [{ "type": "text", "text": "..." }] });
9800            let system_prompt: SystemPrompt =
9801                serde_json::from_value(system_prompt_json.clone()).unwrap();
9802            assert_eq!(
9803                system_prompt.mode,
9804                SystemPromptMode::Other(mode.to_string())
9805            );
9806            assert_eq!(
9807                serde_json::to_value(&system_prompt).unwrap(),
9808                system_prompt_json
9809            );
9810        }
9811    }
9812
9813    /// The receiver acts on `systemPrompt`, so malformed values fail the request
9814    /// (`-32602`) instead of creating a session without the prompt, and `null`
9815    /// is equivalent to omitting the field.
9816    fn assert_system_prompt_is_strict<T>(base: &serde_json::Value)
9817    where
9818        T: serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
9819    {
9820        let name = std::any::type_name::<T>();
9821        let with = |system_prompt: serde_json::Value| {
9822            let mut request = base.clone();
9823            request["systemPrompt"] = system_prompt;
9824            serde_json::from_value::<T>(request)
9825        };
9826
9827        for system_prompt in [
9828            json!("You are a code review specialist."),
9829            json!({ "content": [{ "type": "text", "text": "..." }] }),
9830            json!({ "mode": null, "content": [{ "type": "text", "text": "..." }] }),
9831            json!({ "mode": 1, "content": [{ "type": "text", "text": "..." }] }),
9832            json!({ "mode": "append" }),
9833            json!({ "mode": "append", "content": "..." }),
9834            json!({ "mode": "append", "content": [{ "type": "text" }] }),
9835        ] {
9836            assert!(
9837                with(system_prompt.clone()).is_err(),
9838                "{name}.systemPrompt: {system_prompt}"
9839            );
9840        }
9841
9842        assert_eq!(
9843            with(serde_json::Value::Null).unwrap(),
9844            serde_json::from_value::<T>(base.clone()).unwrap(),
9845            "{name}.systemPrompt"
9846        );
9847    }
9848
9849    #[test]
9850    fn test_session_setup_requests_reject_malformed_system_prompts() {
9851        assert!(
9852            serde_json::to_value(NewSessionRequest::new("/repo"))
9853                .unwrap()
9854                .get("systemPrompt")
9855                .is_none()
9856        );
9857        assert_system_prompt_is_strict::<NewSessionRequest>(&json!({ "cwd": "/repo" }));
9858        assert_system_prompt_is_strict::<ResumeSessionRequest>(&json!({
9859            "sessionId": "sess-1",
9860            "cwd": "/repo"
9861        }));
9862        #[cfg(feature = "unstable_session_fork")]
9863        assert_system_prompt_is_strict::<ForkSessionRequest>(&json!({
9864            "sessionId": "sess-1",
9865            "cwd": "/repo"
9866        }));
9867    }
9868
9869    /// Unknown content block types parse as `ContentBlock::Other` so they are not
9870    /// dropped. An Agent that does not support them must reject the request.
9871    #[test]
9872    fn test_system_prompt_preserves_unknown_content_blocks() {
9873        let request: NewSessionRequest = serde_json::from_value(json!({
9874            "cwd": "/home/user/project",
9875            "systemPrompt": {
9876                "mode": "append",
9877                "content": [{ "type": "_vendor_video", "uri": "https://example.com/intro.mp4" }]
9878            }
9879        }))
9880        .unwrap();
9881        let content = request.system_prompt.unwrap().content;
9882        assert_eq!(content.len(), 1);
9883        assert!(matches!(content[0], ContentBlock::Other(_)));
9884    }
9885
9886    #[test]
9887    fn test_auth_method_terminal_serialization() {
9888        let method = AuthMethod::Terminal(AuthMethodTerminal::new("tui-auth", "Terminal Auth"));
9889
9890        let json = serde_json::to_value(&method).unwrap();
9891        assert_eq!(
9892            json,
9893            json!({
9894                "methodId": "tui-auth",
9895                "name": "Terminal Auth",
9896                "type": "terminal"
9897            })
9898        );
9899        // args and env should be omitted when empty
9900        assert!(!json.as_object().unwrap().contains_key("args"));
9901        assert!(!json.as_object().unwrap().contains_key("env"));
9902
9903        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9904        match deserialized {
9905            AuthMethod::Terminal(AuthMethodTerminal { args, env, .. }) => {
9906                assert_eq!(args, Vec::<String>::new());
9907                assert_eq!(env, []);
9908            }
9909            _ => panic!("Expected Terminal variant"),
9910        }
9911    }
9912
9913    #[test]
9914    fn test_auth_method_terminal_with_args_and_env_serialization() {
9915        let method = AuthMethod::Terminal(
9916            AuthMethodTerminal::new("tui-auth", "Terminal Auth")
9917                .args(vec!["--interactive".to_string(), "--color".to_string()])
9918                .env(vec![EnvVariable::new("TERM", "xterm-256color")]),
9919        );
9920
9921        let json = serde_json::to_value(&method).unwrap();
9922        assert_eq!(
9923            json,
9924            json!({
9925                "methodId": "tui-auth",
9926                "name": "Terminal Auth",
9927                "type": "terminal",
9928                "args": ["--interactive", "--color"],
9929                "env": [
9930                    {
9931                        "name": "TERM",
9932                        "value": "xterm-256color"
9933                    }
9934                ]
9935            })
9936        );
9937
9938        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9939        match deserialized {
9940            AuthMethod::Terminal(AuthMethodTerminal { args, env, .. }) => {
9941                assert_eq!(args, vec!["--interactive", "--color"]);
9942                assert_eq!(env.len(), 1);
9943                assert_eq!(env[0].name, "TERM");
9944                assert_eq!(env[0].value, "xterm-256color");
9945            }
9946            _ => panic!("Expected Terminal variant"),
9947        }
9948    }
9949
9950    #[test]
9951    fn test_session_config_option_id_serialize() {
9952        let val = SessionConfigOptionValue::id("model-1");
9953        let json = serde_json::to_value(&val).unwrap();
9954        assert_eq!(json, json!({ "type": "id", "value": "model-1" }));
9955    }
9956
9957    #[test]
9958    fn test_session_config_option_value_boolean_serialize() {
9959        let val = SessionConfigOptionValue::boolean(true);
9960        let json = serde_json::to_value(&val).unwrap();
9961        assert_eq!(json, json!({ "type": "boolean", "value": true }));
9962    }
9963
9964    #[test]
9965    fn test_session_config_option_value_deserialize_id() {
9966        let json = json!({ "type": "id", "value": "model-1" });
9967        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9968        assert_eq!(val, SessionConfigOptionValue::id("model-1"));
9969        assert_eq!(val.as_id().unwrap().to_string(), "model-1");
9970    }
9971
9972    #[test]
9973    fn test_session_config_option_value_deserialize_requires_type() {
9974        let json = json!({ "value": "model-1" });
9975        let result = serde_json::from_value::<SessionConfigOptionValue>(json);
9976        assert!(result.is_err());
9977    }
9978
9979    #[test]
9980    fn test_session_config_option_value_deserialize_boolean() {
9981        let json = json!({ "type": "boolean", "value": true });
9982        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9983        assert_eq!(val, SessionConfigOptionValue::boolean(true));
9984        assert_eq!(val.as_bool(), Some(true));
9985    }
9986
9987    #[test]
9988    fn test_session_config_option_value_deserialize_boolean_false() {
9989        let json = json!({ "type": "boolean", "value": false });
9990        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9991        assert_eq!(val, SessionConfigOptionValue::boolean(false));
9992        assert_eq!(val.as_bool(), Some(false));
9993    }
9994
9995    #[test]
9996    fn test_session_config_option_value_deserialize_unknown_type_with_string_value() {
9997        let json = json!({
9998            "type": "text",
9999            "value": "freeform input",
10000            "maxLength": 200
10001        });
10002        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10003        let SessionConfigOptionValue::Other(unknown) = val else {
10004            panic!("Expected Other variant");
10005        };
10006        assert_eq!(unknown.type_, "text");
10007        assert_eq!(unknown.value, json!("freeform input"));
10008        assert_eq!(unknown.fields["maxLength"], json!(200));
10009    }
10010
10011    #[test]
10012    fn test_session_config_option_value_deserialize_unknown_type_with_object_value() {
10013        let json = json!({
10014            "type": "range",
10015            "value": { "min": 1, "max": 5 }
10016        });
10017        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10018        let SessionConfigOptionValue::Other(unknown) = val else {
10019            panic!("Expected Other variant");
10020        };
10021        assert_eq!(unknown.type_, "range");
10022        assert_eq!(unknown.value, json!({ "min": 1, "max": 5 }));
10023    }
10024
10025    #[test]
10026    fn test_session_config_option_value_roundtrip_id() {
10027        let original = SessionConfigOptionValue::id("option-a");
10028        let json = serde_json::to_value(&original).unwrap();
10029        let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10030        assert_eq!(original, roundtripped);
10031    }
10032
10033    #[test]
10034    fn test_session_config_option_value_roundtrip_boolean() {
10035        let original = SessionConfigOptionValue::boolean(false);
10036        let json = serde_json::to_value(&original).unwrap();
10037        let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10038        assert_eq!(original, roundtripped);
10039    }
10040
10041    #[test]
10042    fn test_session_config_option_value_roundtrip_other() {
10043        let mut fields = IndexMap::new();
10044        fields.insert("maxLength".to_string(), json!(200));
10045        let original = SessionConfigOptionValue::from(OtherSessionConfigOptionValue::new(
10046            "text",
10047            json!("freeform input"),
10048            fields,
10049        ));
10050        let json = serde_json::to_value(&original).unwrap();
10051        assert_eq!(
10052            json,
10053            json!({"type": "text", "value": "freeform input", "maxLength": 200})
10054        );
10055        let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10056        assert_eq!(original, roundtripped);
10057    }
10058
10059    #[test]
10060    fn test_session_config_option_value_type_mismatch_boolean_with_string() {
10061        let json = json!({ "type": "boolean", "value": "not a bool" });
10062        let result = serde_json::from_value::<SessionConfigOptionValue>(json);
10063        assert!(result.is_err());
10064    }
10065
10066    #[test]
10067    fn test_session_config_option_value_from_impls() {
10068        let from_str: SessionConfigOptionValue = "model-1".into();
10069        assert_eq!(from_str.as_id().unwrap().to_string(), "model-1");
10070
10071        let from_id: SessionConfigOptionValue = SessionConfigValueId::new("model-2").into();
10072        assert_eq!(from_id.as_id().unwrap().to_string(), "model-2");
10073
10074        let from_bool: SessionConfigOptionValue = true.into();
10075        assert_eq!(from_bool.as_bool(), Some(true));
10076    }
10077
10078    #[test]
10079    fn test_set_session_config_option_request_id() {
10080        let req = SetSessionConfigOptionRequest::new("sess_1", "model", "model-1");
10081        let json = serde_json::to_value(&req).unwrap();
10082        assert_eq!(
10083            json,
10084            json!({
10085                "sessionId": "sess_1",
10086                "configId": "model",
10087                "type": "id",
10088                "value": "model-1"
10089            })
10090        );
10091    }
10092
10093    #[test]
10094    fn test_set_session_config_option_request_boolean() {
10095        let req = SetSessionConfigOptionRequest::new("sess_1", "brave_mode", true);
10096        let json = serde_json::to_value(&req).unwrap();
10097        assert_eq!(
10098            json,
10099            json!({
10100                "sessionId": "sess_1",
10101                "configId": "brave_mode",
10102                "type": "boolean",
10103                "value": true
10104            })
10105        );
10106    }
10107
10108    #[test]
10109    fn test_set_session_config_option_request_deserialize_requires_type() {
10110        let json = json!({
10111            "sessionId": "sess_1",
10112            "configId": "model",
10113            "value": "model-1"
10114        });
10115        let result = serde_json::from_value::<SetSessionConfigOptionRequest>(json);
10116        assert!(result.is_err());
10117    }
10118
10119    #[test]
10120    fn test_set_session_config_option_request_deserialize_boolean() {
10121        let json = json!({
10122            "sessionId": "sess_1",
10123            "configId": "brave_mode",
10124            "type": "boolean",
10125            "value": true
10126        });
10127        let req: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
10128        assert_eq!(req.value.as_bool(), Some(true));
10129    }
10130
10131    #[test]
10132    fn test_set_session_config_option_request_roundtrip_id() {
10133        let original = SetSessionConfigOptionRequest::new("s", "c", "v");
10134        let json = serde_json::to_value(&original).unwrap();
10135        let roundtripped: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
10136        assert_eq!(original, roundtripped);
10137    }
10138
10139    #[test]
10140    fn test_set_session_config_option_request_roundtrip_boolean() {
10141        let original = SetSessionConfigOptionRequest::new("s", "c", false);
10142        let json = serde_json::to_value(&original).unwrap();
10143        let roundtripped: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
10144        assert_eq!(original, roundtripped);
10145    }
10146
10147    #[test]
10148    fn test_session_config_boolean_serialization() {
10149        let cfg = SessionConfigBoolean::new(true);
10150        let json = serde_json::to_value(&cfg).unwrap();
10151        assert_eq!(json, json!({ "currentValue": true }));
10152
10153        let deserialized: SessionConfigBoolean = serde_json::from_value(json).unwrap();
10154        assert!(deserialized.current_value);
10155    }
10156
10157    #[test]
10158    fn test_session_config_option_boolean_variant() {
10159        let opt = SessionConfigOption::boolean("brave_mode", "Brave Mode", false)
10160            .description("Skip confirmation prompts")
10161            .meta(test_meta());
10162        assert_eq!(serialized_meta_key_count(&opt), 1);
10163
10164        let json = serde_json::to_value(&opt).unwrap();
10165        assert_eq!(
10166            json,
10167            json!({
10168                "configId": "brave_mode",
10169                "name": "Brave Mode",
10170                "description": "Skip confirmation prompts",
10171                "type": "boolean",
10172                "currentValue": false,
10173                "_meta": {
10174                    "source": "test"
10175                }
10176            })
10177        );
10178
10179        let deserialized: SessionConfigOption = serde_json::from_value(json).unwrap();
10180        assert_eq!(deserialized.config_id.to_string(), "brave_mode");
10181        assert_eq!(deserialized.name, "Brave Mode");
10182        match deserialized.kind {
10183            SessionConfigKind::Boolean(ref b) => assert!(!b.current_value),
10184            _ => panic!("Expected Boolean kind"),
10185        }
10186    }
10187
10188    #[test]
10189    fn test_session_config_option_select_still_works() {
10190        // Make sure existing select options are unaffected
10191        let opt = SessionConfigOption::select(
10192            "model",
10193            "Model",
10194            "model-1",
10195            vec![
10196                SessionConfigSelectOption::new("model-1", "Model 1"),
10197                SessionConfigSelectOption::new("model-2", "Model 2"),
10198            ],
10199        )
10200        .meta(test_meta());
10201        assert_eq!(serialized_meta_key_count(&opt), 1);
10202
10203        let json = serde_json::to_value(&opt).unwrap();
10204        assert_eq!(json["type"], "select");
10205        assert_eq!(json["currentValue"], "model-1");
10206        assert_eq!(json["options"].as_array().unwrap().len(), 2);
10207        assert_eq!(json["_meta"]["source"], "test");
10208
10209        let deserialized: SessionConfigOption = serde_json::from_value(json).unwrap();
10210        match deserialized.kind {
10211            SessionConfigKind::Select(ref s) => {
10212                assert_eq!(s.current_value.to_string(), "model-1");
10213            }
10214            _ => panic!("Expected Select kind"),
10215        }
10216    }
10217
10218    #[test]
10219    fn test_session_config_option_unknown_kind_roundtrip() {
10220        let option: SessionConfigOption = serde_json::from_value(json!({
10221            "configId": "verbosity",
10222            "name": "Verbosity",
10223            "type": "_slider",
10224            "currentValue": 3,
10225            "min": 0,
10226            "max": 5,
10227            "_meta": {
10228                "source": "test"
10229            }
10230        }))
10231        .unwrap();
10232
10233        assert_eq!(option.config_id.to_string(), "verbosity");
10234        assert_eq!(option.meta.as_ref().unwrap()["source"], "test");
10235        let SessionConfigKind::Other(unknown) = &option.kind else {
10236            panic!("expected unknown config kind");
10237        };
10238        assert_eq!(unknown.type_, "_slider");
10239        assert_eq!(unknown.fields.get("currentValue"), Some(&json!(3)));
10240        assert!(!unknown.fields.contains_key("_meta"));
10241        assert_eq!(serialized_meta_key_count(&option), 1);
10242
10243        let json = serde_json::to_value(&option).unwrap();
10244        assert_eq!(json["type"], "_slider");
10245        assert_eq!(json["currentValue"], 3);
10246        assert_eq!(json["min"], 0);
10247        assert_eq!(json["max"], 5);
10248        assert_eq!(json["_meta"]["source"], "test");
10249    }
10250
10251    #[test]
10252    fn test_session_config_option_unknown_kind_does_not_duplicate_flattened_meta() {
10253        let mut fields = IndexMap::new();
10254        fields.insert("currentValue".to_string(), json!(3));
10255        fields.insert("_meta".to_string(), json!({ "inner": "ignored" }));
10256
10257        let option = SessionConfigOption::new(
10258            "verbosity",
10259            "Verbosity",
10260            SessionConfigKind::Other(OtherSessionConfigKind::new("_slider", fields)),
10261        )
10262        .meta(test_meta());
10263
10264        let SessionConfigKind::Other(unknown) = &option.kind else {
10265            panic!("expected unknown config kind");
10266        };
10267        assert!(!unknown.fields.contains_key("_meta"));
10268        assert_eq!(serialized_meta_key_count(&option), 1);
10269
10270        let json = serde_json::to_value(&option).unwrap();
10271        assert_eq!(json["type"], "_slider");
10272        assert_eq!(json["currentValue"], 3);
10273        assert_eq!(json["_meta"]["source"], "test");
10274    }
10275
10276    #[test]
10277    fn test_session_config_option_unknown_does_not_hide_malformed_known_kind() {
10278        assert!(
10279            serde_json::from_value::<SessionConfigOption>(json!({
10280                "configId": "model",
10281                "name": "Model",
10282                "type": "select"
10283            }))
10284            .is_err()
10285        );
10286    }
10287
10288    #[cfg(feature = "unstable_llm_providers")]
10289    #[test]
10290    fn test_llm_protocol_known_variants() {
10291        assert_eq!(
10292            serde_json::to_value(&LlmProtocol::Anthropic).unwrap(),
10293            json!("anthropic")
10294        );
10295        assert_eq!(
10296            serde_json::to_value(&LlmProtocol::OpenAi).unwrap(),
10297            json!("openai")
10298        );
10299        assert_eq!(
10300            serde_json::to_value(&LlmProtocol::Azure).unwrap(),
10301            json!("azure")
10302        );
10303        assert_eq!(
10304            serde_json::to_value(&LlmProtocol::Vertex).unwrap(),
10305            json!("vertex")
10306        );
10307        assert_eq!(
10308            serde_json::to_value(&LlmProtocol::Bedrock).unwrap(),
10309            json!("bedrock")
10310        );
10311
10312        assert_eq!(
10313            serde_json::from_str::<LlmProtocol>("\"anthropic\"").unwrap(),
10314            LlmProtocol::Anthropic
10315        );
10316        assert_eq!(
10317            serde_json::from_str::<LlmProtocol>("\"openai\"").unwrap(),
10318            LlmProtocol::OpenAi
10319        );
10320        assert_eq!(
10321            serde_json::from_str::<LlmProtocol>("\"azure\"").unwrap(),
10322            LlmProtocol::Azure
10323        );
10324        assert_eq!(
10325            serde_json::from_str::<LlmProtocol>("\"vertex\"").unwrap(),
10326            LlmProtocol::Vertex
10327        );
10328        assert_eq!(
10329            serde_json::from_str::<LlmProtocol>("\"bedrock\"").unwrap(),
10330            LlmProtocol::Bedrock
10331        );
10332    }
10333
10334    #[cfg(feature = "unstable_llm_providers")]
10335    #[test]
10336    fn test_llm_protocol_unknown_variant() {
10337        let unknown: LlmProtocol = serde_json::from_str("\"cohere\"").unwrap();
10338        assert_eq!(unknown, LlmProtocol::Other("cohere".to_string()));
10339
10340        let json = serde_json::to_value(&unknown).unwrap();
10341        assert_eq!(json, json!("cohere"));
10342    }
10343
10344    #[cfg(feature = "unstable_llm_providers")]
10345    #[test]
10346    fn test_provider_current_config_serialization() {
10347        let config =
10348            ProviderCurrentConfig::new(LlmProtocol::Anthropic, "https://api.anthropic.com");
10349
10350        let json = serde_json::to_value(&config).unwrap();
10351        assert_eq!(
10352            json,
10353            json!({
10354                "apiType": "anthropic",
10355                "baseUrl": "https://api.anthropic.com"
10356            })
10357        );
10358
10359        let deserialized: ProviderCurrentConfig = serde_json::from_value(json).unwrap();
10360        assert_eq!(deserialized.api_type, LlmProtocol::Anthropic);
10361        assert_eq!(deserialized.base_url, "https://api.anthropic.com");
10362    }
10363
10364    #[cfg(feature = "unstable_llm_providers")]
10365    #[test]
10366    fn test_provider_info_with_current_config() {
10367        let info = ProviderInfo::new(
10368            "main",
10369            vec![LlmProtocol::Anthropic, LlmProtocol::OpenAi],
10370            true,
10371            Some(ProviderCurrentConfig::new(
10372                LlmProtocol::Anthropic,
10373                "https://api.anthropic.com",
10374            )),
10375        );
10376
10377        let json = serde_json::to_value(&info).unwrap();
10378        assert_eq!(
10379            json,
10380            json!({
10381                "providerId": "main",
10382                "supported": ["anthropic", "openai"],
10383                "required": true,
10384                "current": {
10385                    "apiType": "anthropic",
10386                    "baseUrl": "https://api.anthropic.com"
10387                }
10388            })
10389        );
10390
10391        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10392        assert_eq!(deserialized.provider_id.to_string(), "main");
10393        assert_eq!(deserialized.supported.len(), 2);
10394        assert!(deserialized.required);
10395        assert!(deserialized.current.is_some());
10396        assert_eq!(
10397            deserialized.current.as_ref().unwrap().api_type,
10398            LlmProtocol::Anthropic
10399        );
10400    }
10401
10402    #[cfg(feature = "unstable_llm_providers")]
10403    #[test]
10404    fn test_provider_info_disabled() {
10405        let info = ProviderInfo::new(
10406            "secondary",
10407            vec![LlmProtocol::OpenAi],
10408            false,
10409            None::<ProviderCurrentConfig>,
10410        );
10411
10412        let json = serde_json::to_value(&info).unwrap();
10413        assert_eq!(
10414            json,
10415            json!({
10416                "providerId": "secondary",
10417                "supported": ["openai"],
10418                "required": false
10419            })
10420        );
10421
10422        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10423        assert_eq!(deserialized.provider_id.to_string(), "secondary");
10424        assert!(!deserialized.required);
10425        assert!(deserialized.current.is_none());
10426    }
10427
10428    #[cfg(feature = "unstable_llm_providers")]
10429    #[test]
10430    fn test_provider_info_missing_current_defaults_to_none() {
10431        // current is optional; omitting it should decode as None
10432        let json = json!({
10433            "providerId": "main",
10434            "supported": ["anthropic"],
10435            "required": true
10436        });
10437        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10438        assert!(deserialized.current.is_none());
10439    }
10440
10441    #[cfg(feature = "unstable_llm_providers")]
10442    #[test]
10443    fn test_provider_info_explicit_null_current_decodes_to_none() {
10444        // current: null and an omitted current are equivalent on the wire;
10445        // both must deserialize into None so the disabled state is preserved
10446        // regardless of which form the peer chose to send.
10447        let json = json!({
10448            "providerId": "main",
10449            "supported": ["anthropic"],
10450            "required": true,
10451            "current": null
10452        });
10453        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10454        assert!(deserialized.current.is_none());
10455    }
10456
10457    #[cfg(feature = "unstable_llm_providers")]
10458    #[test]
10459    fn test_list_providers_response_serialization() {
10460        let response = ListProvidersResponse::new(vec![ProviderInfo::new(
10461            "main",
10462            vec![LlmProtocol::Anthropic],
10463            true,
10464            Some(ProviderCurrentConfig::new(
10465                LlmProtocol::Anthropic,
10466                "https://api.anthropic.com",
10467            )),
10468        )]);
10469
10470        let json = serde_json::to_value(&response).unwrap();
10471        assert_eq!(json["providers"].as_array().unwrap().len(), 1);
10472        assert_eq!(json["providers"][0]["providerId"], "main");
10473
10474        let deserialized: ListProvidersResponse = serde_json::from_value(json).unwrap();
10475        assert_eq!(deserialized.providers.len(), 1);
10476    }
10477
10478    #[cfg(feature = "unstable_llm_providers")]
10479    #[test]
10480    fn test_set_provider_request_serialization() {
10481        let mut headers = IndexMap::new();
10482        headers.insert("Authorization".to_string(), "Bearer sk-test".to_string());
10483
10484        let request =
10485            SetProviderRequest::new("main", LlmProtocol::OpenAi, "https://api.openai.com/v1")
10486                .headers(headers);
10487
10488        let json = serde_json::to_value(&request).unwrap();
10489        assert_eq!(
10490            json,
10491            json!({
10492                "providerId": "main",
10493                "apiType": "openai",
10494                "baseUrl": "https://api.openai.com/v1",
10495                "headers": {
10496                    "Authorization": "Bearer sk-test"
10497                }
10498            })
10499        );
10500
10501        let deserialized: SetProviderRequest = serde_json::from_value(json).unwrap();
10502        assert_eq!(deserialized.provider_id.to_string(), "main");
10503        assert_eq!(deserialized.api_type, LlmProtocol::OpenAi);
10504        assert_eq!(deserialized.base_url, "https://api.openai.com/v1");
10505        assert_eq!(deserialized.headers.len(), 1);
10506        assert_eq!(
10507            deserialized.headers.get("Authorization").unwrap(),
10508            "Bearer sk-test"
10509        );
10510    }
10511
10512    #[cfg(feature = "unstable_llm_providers")]
10513    #[test]
10514    fn test_set_provider_request_omits_empty_headers() {
10515        let request =
10516            SetProviderRequest::new("main", LlmProtocol::Anthropic, "https://api.anthropic.com");
10517
10518        let json = serde_json::to_value(&request).unwrap();
10519        // headers should be omitted when empty
10520        assert!(!json.as_object().unwrap().contains_key("headers"));
10521    }
10522
10523    #[cfg(feature = "unstable_llm_providers")]
10524    #[test]
10525    fn test_disable_provider_request_serialization() {
10526        let request = DisableProviderRequest::new("secondary");
10527
10528        let json = serde_json::to_value(&request).unwrap();
10529        assert_eq!(json, json!({ "providerId": "secondary" }));
10530
10531        let deserialized: DisableProviderRequest = serde_json::from_value(json).unwrap();
10532        assert_eq!(deserialized.provider_id.to_string(), "secondary");
10533    }
10534
10535    #[cfg(feature = "unstable_llm_providers")]
10536    #[test]
10537    fn test_providers_capabilities_serialization() {
10538        let caps = ProvidersCapabilities::new();
10539
10540        let json = serde_json::to_value(&caps).unwrap();
10541        assert_eq!(json, json!({}));
10542
10543        let deserialized: ProvidersCapabilities = serde_json::from_value(json).unwrap();
10544        assert!(deserialized.meta.is_none());
10545    }
10546
10547    #[cfg(feature = "unstable_llm_providers")]
10548    #[test]
10549    fn test_agent_capabilities_with_providers() {
10550        let caps = AgentCapabilities::new().providers(ProvidersCapabilities::new());
10551
10552        let json = serde_json::to_value(&caps).unwrap();
10553        assert_eq!(json["providers"], json!({}));
10554
10555        let deserialized: AgentCapabilities = serde_json::from_value(json).unwrap();
10556        assert!(deserialized.providers.is_some());
10557    }
10558
10559    #[test]
10560    fn test_agent_capabilities_session_is_explicit() {
10561        let json = serde_json::to_value(AgentCapabilities::new()).unwrap();
10562        assert!(json.get("session").is_none());
10563
10564        let caps = AgentCapabilities::new().session(
10565            SessionCapabilities::new()
10566                .prompt(PromptCapabilities::new().image(PromptImageCapabilities::new()))
10567                .mcp(McpCapabilities::new().stdio(McpStdioCapabilities::new())),
10568        );
10569
10570        assert_eq!(
10571            serde_json::to_value(&caps).unwrap(),
10572            json!({
10573                "session": {
10574                    "prompt": {
10575                        "image": {}
10576                    },
10577                    "mcp": {
10578                        "stdio": {}
10579                    }
10580                }
10581            })
10582        );
10583
10584        let deserialized: AgentCapabilities = serde_json::from_value(json!({
10585            "session": false
10586        }))
10587        .unwrap();
10588        assert!(deserialized.session.is_none());
10589    }
10590
10591    #[test]
10592    fn test_prompt_capabilities_serialize_supported_content_as_objects() {
10593        let caps = PromptCapabilities::new()
10594            .image(PromptImageCapabilities::new())
10595            .audio(PromptAudioCapabilities::new())
10596            .embedded_context(PromptEmbeddedContextCapabilities::new());
10597
10598        assert_eq!(
10599            serde_json::to_value(&caps).unwrap(),
10600            json!({
10601                "image": {},
10602                "audio": {},
10603                "embeddedContext": {}
10604            })
10605        );
10606
10607        let deserialized: PromptCapabilities = serde_json::from_value(json!({
10608            "image": null,
10609            "audio": false,
10610            "embeddedContext": {}
10611        }))
10612        .unwrap();
10613        assert!(deserialized.image.is_none());
10614        assert!(deserialized.audio.is_none());
10615        assert!(deserialized.embedded_context.is_some());
10616    }
10617
10618    #[cfg(feature = "unstable_agent_skills")]
10619    #[test]
10620    fn prompt_skill_capability_has_two_levels() {
10621        // `{}` allows one leading skill block. `inline` allows them anywhere.
10622        let leading = PromptCapabilities::new().skill(PromptSkillCapabilities::new());
10623        assert_eq!(
10624            serde_json::to_value(&leading).unwrap(),
10625            json!({ "skill": {} })
10626        );
10627
10628        let inline = PromptCapabilities::new()
10629            .skill(PromptSkillCapabilities::new().inline(PromptSkillInlineCapabilities::new()));
10630        let wire = json!({ "skill": { "inline": {} } });
10631        assert_eq!(serde_json::to_value(&inline).unwrap(), wire);
10632        assert_eq!(
10633            serde_json::from_value::<PromptCapabilities>(wire).unwrap(),
10634            inline
10635        );
10636
10637        for unsupported in [
10638            json!({}),
10639            json!({ "skill": null }),
10640            json!({ "skill": false }),
10641            json!({ "skill": true }),
10642        ] {
10643            let caps: PromptCapabilities = serde_json::from_value(unsupported).unwrap();
10644            assert!(caps.skill.is_none());
10645        }
10646
10647        // A malformed `inline` does not withdraw the first level.
10648        for leading_only in [
10649            json!({ "skill": { "inline": null } }),
10650            json!({ "skill": { "inline": true } }),
10651        ] {
10652            assert_eq!(
10653                serde_json::from_value::<PromptCapabilities>(leading_only).unwrap(),
10654                leading
10655            );
10656        }
10657    }
10658
10659    #[test]
10660    fn test_mcp_capabilities_serialize_supported_transports_as_objects() {
10661        let caps = McpCapabilities::new()
10662            .stdio(McpStdioCapabilities::new())
10663            .http(McpHttpCapabilities::new());
10664
10665        assert_eq!(
10666            serde_json::to_value(&caps).unwrap(),
10667            json!({
10668                "stdio": {},
10669                "http": {}
10670            })
10671        );
10672
10673        let deserialized: McpCapabilities = serde_json::from_value(json!({
10674            "stdio": null,
10675            "http": false
10676        }))
10677        .unwrap();
10678        assert!(deserialized.stdio.is_none());
10679        assert!(deserialized.http.is_none());
10680    }
10681
10682    #[cfg(feature = "unstable_mcp_over_acp")]
10683    #[test]
10684    fn test_mcp_capabilities_serialize_acp_support_as_object() {
10685        let caps = McpCapabilities::new().acp(McpAcpCapabilities::new());
10686
10687        assert_eq!(
10688            serde_json::to_value(&caps).unwrap(),
10689            json!({
10690                "acp": {}
10691            })
10692        );
10693    }
10694
10695    #[test]
10696    fn prompt_request_rejects_malformed_content_block() {
10697        use serde_json::json;
10698
10699        assert!(
10700            serde_json::from_value::<PromptRequest>(json!({
10701                "sessionId": "sess-1",
10702                "prompt": [{"type": "text"}]
10703            }))
10704            .is_err()
10705        );
10706    }
10707
10708    #[test]
10709    fn prompt_request_rejects_non_array_prompt() {
10710        use serde_json::json;
10711
10712        assert!(
10713            serde_json::from_value::<PromptRequest>(json!({
10714                "sessionId": "sess-1",
10715                "prompt": "hello"
10716            }))
10717            .is_err()
10718        );
10719    }
10720
10721    fn prompt_request_with_idempotency_key(key: &serde_json::Value) -> serde_json::Value {
10722        serde_json::json!({
10723            "sessionId": "sess-1",
10724            "idempotencyKey": key,
10725            "prompt": [{"type": "text", "text": "hello"}]
10726        })
10727    }
10728
10729    #[test]
10730    fn prompt_request_idempotency_key_round_trips() {
10731        use serde_json::json;
10732
10733        let key = "0b6f3c1e-8d2a-4c57-9a41-5e2f7d90c3ab";
10734        let value = prompt_request_with_idempotency_key(&json!(key));
10735
10736        let request: PromptRequest = serde_json::from_value(value.clone()).unwrap();
10737        assert_eq!(
10738            request.idempotency_key.as_ref().map(IdempotencyKey::as_str),
10739            Some(key)
10740        );
10741        assert_eq!(serde_json::to_value(&request).unwrap(), value);
10742
10743        let built = PromptRequest::new("sess-1", vec![ContentBlock::from("hello")])
10744            .idempotency_key(IdempotencyKey::new(key).unwrap());
10745        assert_eq!(built, request);
10746    }
10747
10748    #[test]
10749    fn prompt_request_omitted_and_null_idempotency_key_mean_no_key() {
10750        use serde_json::json;
10751
10752        let omitted = json!({
10753            "sessionId": "sess-1",
10754            "prompt": [{"type": "text", "text": "hello"}]
10755        });
10756        let request: PromptRequest = serde_json::from_value(omitted.clone()).unwrap();
10757        assert_eq!(request.idempotency_key, None);
10758        // No key is serialized as an omitted field, not as `null`.
10759        assert_eq!(serde_json::to_value(&request).unwrap(), omitted);
10760
10761        let null: PromptRequest =
10762            serde_json::from_value(prompt_request_with_idempotency_key(&json!(null))).unwrap();
10763        assert_eq!(null, request);
10764    }
10765
10766    #[test]
10767    fn prompt_request_rejects_malformed_idempotency_key() {
10768        use serde_json::json;
10769
10770        let too_long = "k".repeat(IdempotencyKey::MAX_LENGTH + 1);
10771        for (name, key) in [
10772            ("an empty string", json!("")),
10773            ("a string over 255 characters", json!(too_long)),
10774            ("a number", json!(7)),
10775            ("a boolean", json!(true)),
10776            ("an object", json!({"key": "k"})),
10777            ("an array", json!(["k"])),
10778        ] {
10779            assert!(
10780                serde_json::from_value::<PromptRequest>(prompt_request_with_idempotency_key(&key))
10781                    .is_err(),
10782                "{name} must fail the request instead of being treated as no key"
10783            );
10784        }
10785    }
10786
10787    #[test]
10788    fn idempotency_key_length_is_counted_in_characters() {
10789        use serde_json::json;
10790
10791        assert_eq!(IdempotencyKey::new(""), Err(InvalidIdempotencyKey::Empty));
10792        assert_eq!(IdempotencyKey::new("k").unwrap().as_str(), "k");
10793
10794        let longest = "k".repeat(IdempotencyKey::MAX_LENGTH);
10795        assert_eq!(
10796            IdempotencyKey::new(longest.as_str()).unwrap().as_str(),
10797            longest
10798        );
10799        assert_eq!(
10800            IdempotencyKey::new(format!("{longest}k")),
10801            Err(InvalidIdempotencyKey::TooLong)
10802        );
10803
10804        // 255 two-byte characters are 510 bytes and still within the limit.
10805        let multibyte = "é".repeat(IdempotencyKey::MAX_LENGTH);
10806        assert!(IdempotencyKey::new(multibyte.as_str()).is_ok());
10807        assert!(
10808            serde_json::from_value::<PromptRequest>(prompt_request_with_idempotency_key(&json!(
10809                multibyte
10810            )))
10811            .is_ok()
10812        );
10813        assert_eq!(
10814            IdempotencyKey::new(format!("{multibyte}é")),
10815            Err(InvalidIdempotencyKey::TooLong)
10816        );
10817
10818        assert_eq!("k".parse::<IdempotencyKey>().unwrap().to_string(), "k");
10819        assert_eq!(
10820            IdempotencyKey::try_from(String::new()),
10821            Err(InvalidIdempotencyKey::Empty)
10822        );
10823        assert_eq!(
10824            InvalidIdempotencyKey::TooLong.to_string(),
10825            "idempotency key must be at most 255 characters"
10826        );
10827    }
10828
10829    #[cfg(feature = "uuid")]
10830    #[test]
10831    fn generated_idempotency_keys_are_distinct_valid_v4_uuids() {
10832        let first = IdempotencyKey::generate();
10833        let second = IdempotencyKey::generate();
10834        assert_ne!(first, second);
10835
10836        for key in [&first, &second] {
10837            let uuid = uuid::Uuid::parse_str(key.as_str()).unwrap();
10838            assert_eq!(uuid.get_version_num(), 4);
10839            // A generated key passes the same validation as any other key.
10840            assert_eq!(IdempotencyKey::new(key.as_str()).as_ref(), Ok(key));
10841            let request = PromptRequest::new("sess-1", vec![ContentBlock::from("hello")])
10842                .idempotency_key(key.clone());
10843            let value = serde_json::to_value(&request).unwrap();
10844            assert_eq!(value["idempotencyKey"], key.as_str());
10845            assert_eq!(
10846                serde_json::from_value::<PromptRequest>(value).unwrap(),
10847                request
10848            );
10849        }
10850
10851        assert_eq!(
10852            IdempotencyKey::from(uuid::Uuid::nil()).as_str(),
10853            "00000000-0000-0000-0000-000000000000"
10854        );
10855    }
10856
10857    #[cfg(feature = "schemars")]
10858    #[test]
10859    fn idempotency_key_schema_is_a_strict_bounded_string() {
10860        use serde_json::json;
10861
10862        let key = serde_json::to_value(schemars::schema_for!(IdempotencyKey)).unwrap();
10863        assert_eq!(key["type"], "string");
10864        assert_eq!(key["minLength"], 1);
10865        assert_eq!(key["maxLength"], json!(IdempotencyKey::MAX_LENGTH));
10866
10867        let request = serde_json::to_value(schemars::schema_for!(PromptRequest)).unwrap();
10868        assert_eq!(request["required"], json!(["sessionId", "prompt"]));
10869        let property = &request["properties"]["idempotencyKey"];
10870        assert_eq!(
10871            property["anyOf"],
10872            json!([{"$ref": "#/$defs/IdempotencyKey"}, {"type": "null"}])
10873        );
10874        // The Agent acts on the key, so the schema must not mark it as tolerant
10875        // of malformed values.
10876        assert!(property.get("x-deserialize-default-on-error").is_none());
10877    }
10878
10879    fn assert_session_setup_lists_are_strict<T>(base: &serde_json::Value)
10880    where
10881        T: serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
10882    {
10883        let name = std::any::type_name::<T>();
10884        let with = |field: &str, value: serde_json::Value| {
10885            let mut request = base.clone();
10886            request[field] = value;
10887            serde_json::from_value::<T>(request)
10888        };
10889
10890        for (field, value) in [
10891            // Dropping the malformed server would start the session without it.
10892            (
10893                "mcpServers",
10894                json!([
10895                    {"type": "stdio", "name": "github", "command": "/usr/bin/gh-mcp", "env": [{"name": "GITHUB_TOKEN", "value": null}]},
10896                    {"type": "stdio", "name": "fs", "command": "/usr/bin/fs-mcp"}
10897                ]),
10898            ),
10899            ("mcpServers", json!({"type": "stdio", "name": "fs"})),
10900            ("additionalDirectories", json!(["/repo/lib", 42])),
10901            ("additionalDirectories", json!("/repo/lib")),
10902        ] {
10903            assert!(
10904                with(field, value.clone()).is_err(),
10905                "{name}.{field}: {value}"
10906            );
10907        }
10908
10909        let empty = serde_json::from_value::<T>(base.clone()).unwrap();
10910        for field in ["mcpServers", "additionalDirectories"] {
10911            assert_eq!(
10912                with(field, serde_json::Value::Null).unwrap(),
10913                empty,
10914                "{name}.{field}"
10915            );
10916        }
10917    }
10918
10919    #[test]
10920    fn session_setup_requests_reject_malformed_mcp_servers_and_directories() {
10921        assert_session_setup_lists_are_strict::<NewSessionRequest>(&json!({"cwd": "/repo"}));
10922        assert_session_setup_lists_are_strict::<ResumeSessionRequest>(&json!({
10923            "sessionId": "sess-1",
10924            "cwd": "/repo"
10925        }));
10926        #[cfg(feature = "unstable_session_fork")]
10927        assert_session_setup_lists_are_strict::<ForkSessionRequest>(&json!({
10928            "sessionId": "sess-1",
10929            "cwd": "/repo"
10930        }));
10931    }
10932
10933    #[test]
10934    fn resume_session_request_rejects_malformed_replay_from() {
10935        let request = |replay_from: serde_json::Value| {
10936            serde_json::from_value::<ResumeSessionRequest>(json!({
10937                "sessionId": "sess-1",
10938                "cwd": "/repo",
10939                "replayFrom": replay_from
10940            }))
10941        };
10942
10943        // Treating this as omitted would reconnect without the requested replay.
10944        assert!(request(json!("start")).is_err());
10945        assert_eq!(request(serde_json::Value::Null).unwrap().replay_from, None);
10946        assert!(matches!(
10947            request(json!({"type": "start"})).unwrap().replay_from,
10948            Some(ReplayFrom::Start(_))
10949        ));
10950    }
10951
10952    #[test]
10953    fn mcp_server_lists_treat_null_as_empty() {
10954        let servers: Vec<McpServer> = serde_json::from_value(json!([
10955            {"type": "stdio", "name": "fs", "command": "/usr/bin/fs-mcp", "args": null, "env": null},
10956            {"type": "http", "name": "api", "url": "https://example.com/mcp", "headers": null}
10957        ]))
10958        .unwrap();
10959
10960        assert_eq!(
10961            servers,
10962            vec![
10963                McpServer::Stdio(McpServerStdio::new("fs", "/usr/bin/fs-mcp")),
10964                McpServer::Http(McpServerHttp::new("api", "https://example.com/mcp")),
10965            ]
10966        );
10967    }
10968
10969    #[test]
10970    fn terminal_auth_methods_reject_malformed_launch_config() {
10971        // The client spawns a process from `args` and `env`, so a malformed
10972        // method is dropped from `authMethods` instead of launched with
10973        // altered arguments or preserved as an unknown method.
10974        let response: InitializeResponse = serde_json::from_value(json!({
10975            "protocolVersion": 2,
10976            "info": {"name": "agent", "version": "1.0.0"},
10977            "authMethods": [
10978                {"type": "terminal", "methodId": "bad-args", "name": "Log in", "args": ["auth", "--port", 8123]},
10979                {"type": "terminal", "methodId": "bad-env", "name": "Log in", "env": [{"name": "DEBUG", "value": 1}]},
10980                {"type": "terminal", "methodId": "null-config", "name": "Log in", "args": null, "env": null},
10981                {"type": "agent", "methodId": "agent", "name": "Agent login"}
10982            ]
10983        }))
10984        .unwrap();
10985
10986        assert_eq!(
10987            response.auth_methods,
10988            vec![
10989                AuthMethod::Terminal(AuthMethodTerminal::new("null-config", "Log in")),
10990                AuthMethod::Agent(AuthMethodAgent::new("agent", "Agent login")),
10991            ]
10992        );
10993    }
10994
10995    #[cfg(feature = "unstable_auth_status")]
10996    #[test]
10997    fn auth_status_response_round_trips() {
10998        let response = AuthStatusResponse::new(AuthState::Authenticated).accounts(vec![
10999            AuthAccount::new("Anthropic API key")
11000                .description("API key helper".to_string())
11001                .active(true),
11002            AuthAccount::new("Claude Max").email("user@example.com".to_string()),
11003        ]);
11004        let json = serde_json::to_value(&response).unwrap();
11005        assert_eq!(
11006            json,
11007            json!({
11008                "state": "authenticated",
11009                "accounts": [
11010                    {
11011                        "label": "Anthropic API key",
11012                        "description": "API key helper",
11013                        "active": true
11014                    },
11015                    {
11016                        "label": "Claude Max",
11017                        "email": "user@example.com"
11018                    }
11019                ]
11020            })
11021        );
11022        assert_eq!(
11023            serde_json::from_value::<AuthStatusResponse>(json).unwrap(),
11024            response
11025        );
11026        assert_eq!(
11027            serde_json::to_value(AuthStatusResponse::new(AuthState::NotRequired)).unwrap(),
11028            json!({"state": "not_required"})
11029        );
11030    }
11031
11032    #[cfg(feature = "unstable_auth_status")]
11033    #[test]
11034    fn auth_status_state_is_strict_and_accounts_are_lenient() {
11035        assert!(serde_json::from_value::<AuthStatusResponse>(json!({})).is_err());
11036        assert!(serde_json::from_value::<AuthStatusResponse>(json!({"state": null})).is_err());
11037        assert!(serde_json::from_value::<AuthStatusResponse>(json!({"state": 1})).is_err());
11038
11039        let response: AuthStatusResponse = serde_json::from_value(json!({
11040            "state": "_vendor_state",
11041            "accounts": [
11042                {"active": true},
11043                {
11044                    "label": "Vertex AI",
11045                    "description": 42,
11046                    "active": "yes",
11047                    "email": ["not", "a", "string"]
11048                }
11049            ]
11050        }))
11051        .unwrap();
11052        assert_eq!(
11053            response,
11054            AuthStatusResponse::new(AuthState::Other("_vendor_state".to_string()))
11055                .accounts(vec![AuthAccount::new("Vertex AI")])
11056        );
11057        assert_eq!(
11058            serde_json::from_value::<AuthStatusResponse>(
11059                json!({"state": "unknown", "accounts": null})
11060            )
11061            .unwrap(),
11062            AuthStatusResponse::new(AuthState::Unknown)
11063        );
11064    }
11065
11066    #[cfg(feature = "unstable_auth_status")]
11067    #[test]
11068    fn auth_status_update_notification_routes() {
11069        use crate::v2::{AgentNotification, CLIENT_METHOD_NAMES};
11070
11071        assert_eq!(AGENT_METHOD_NAMES.auth_status, "auth/status");
11072        assert_eq!(CLIENT_METHOD_NAMES.auth_status_update, "auth/status_update");
11073        let notification = AgentNotification::AuthStatusUpdateNotification(Box::new(
11074            AuthStatusUpdateNotification::new(AuthState::Unauthenticated),
11075        ));
11076        assert_eq!(notification.method(), "auth/status_update");
11077        assert_eq!(
11078            serde_json::to_value(&notification).unwrap(),
11079            json!({"state": "unauthenticated"})
11080        );
11081    }
11082
11083    #[cfg(all(
11084        feature = "unstable_session_fork",
11085        feature = "unstable_session_cursors"
11086    ))]
11087    #[test]
11088    fn fork_session_request_cursor_id_is_optional_and_strict() {
11089        let request = ForkSessionRequest::new("sess_abc123", "/home/user/project")
11090            .cursor_id(CursorId::new("cur_1"));
11091        let wire = json!({
11092            "sessionId": "sess_abc123",
11093            "cursorId": "cur_1",
11094            "cwd": "/home/user/project"
11095        });
11096        assert_eq!(serde_json::to_value(&request).unwrap(), wire);
11097        assert_eq!(
11098            serde_json::from_value::<ForkSessionRequest>(wire).unwrap(),
11099            request
11100        );
11101
11102        // Omitted and `null` both fork the whole session.
11103        for wire in [
11104            json!({ "sessionId": "sess_abc123", "cwd": "/home/user/project" }),
11105            json!({ "sessionId": "sess_abc123", "cwd": "/home/user/project", "cursorId": null }),
11106        ] {
11107            assert_eq!(
11108                serde_json::from_value::<ForkSessionRequest>(wire)
11109                    .unwrap()
11110                    .cursor_id,
11111                None
11112            );
11113        }
11114
11115        // A malformed cursor ID fails the request. It never forks the whole session.
11116        assert!(
11117            serde_json::from_value::<ForkSessionRequest>(json!({
11118                "sessionId": "sess_abc123",
11119                "cwd": "/home/user/project",
11120                "cursorId": 7
11121            }))
11122            .is_err()
11123        );
11124    }
11125}