Skip to main content

agent_client_protocol_schema/v2/
agent.rs

1//! Methods and notifications the Agent handles/receives.
2//!
3//! This module defines the Agent trait and all associated types for implementing
4//! an AI coding agent that follows the Agent Client Protocol (ACP).
5
6use std::{borrow::Cow, sync::Arc};
7
8use derive_more::{Display, From};
9use indexmap::IndexMap;
10#[cfg(feature = "schemars")]
11use schemars::Schema;
12use serde::{Deserialize, Serialize};
13use serde_with::{DefaultOnError, DefaultOnNull, VecSkipError, serde_as, skip_serializing_none};
14
15use super::{
16    AbsolutePath, AvailableCommand, ClientCapabilities, ContentBlock, Error, ExtNotification,
17    ExtRequest, ExtResponse, MessageId, Meta, SessionId, TerminalId, ToolCallId,
18};
19use crate::{IntoOption, ProtocolVersion};
20
21#[cfg(all(
22    feature = "unstable_session_fork",
23    feature = "unstable_session_cursors"
24))]
25use super::CursorId;
26#[cfg(feature = "unstable_session_status")]
27use super::StateUpdate;
28
29#[cfg(all(feature = "unstable_auth_status", feature = "schemars"))]
30use super::AUTH_STATUS_UPDATE_NOTIFICATION;
31#[cfg(feature = "unstable_mcp_over_acp")]
32use super::mcp::{MCP_MESSAGE_METHOD_NAME, MessageMcpNotification};
33
34// Initialize
35
36/// Request parameters for the initialize method.
37///
38/// Sent by the Client to establish connection and negotiate capabilities.
39///
40/// See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/v2/initialization)
41#[serde_as]
42#[skip_serializing_none]
43#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
44#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
45#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = INITIALIZE_METHOD_NAME)))]
46#[serde(rename_all = "camelCase")]
47#[non_exhaustive]
48pub struct InitializeRequest {
49    /// The latest protocol version supported by the Client.
50    pub protocol_version: ProtocolVersion,
51    /// Information about the implementation sending this initialize request.
52    pub info: Implementation,
53    /// Capabilities supported by the Client.
54    #[serde_as(deserialize_as = "DefaultOnError")]
55    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
56    #[serde(default)]
57    pub capabilities: ClientCapabilities,
58    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
59    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
60    /// Implementations MUST NOT assign meaning to keys they do not recognize.
61    ///
62    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
63    #[serde_as(deserialize_as = "DefaultOnError")]
64    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
65    #[serde(default)]
66    #[serde(rename = "_meta")]
67    pub meta: Option<Meta>,
68}
69
70impl InitializeRequest {
71    /// Builds [`InitializeRequest`] with the required request fields set. Optional fields start unset or empty.
72    #[must_use]
73    pub fn new(protocol_version: ProtocolVersion, info: Implementation) -> Self {
74        Self {
75            protocol_version,
76            capabilities: ClientCapabilities::default(),
77            info,
78            meta: None,
79        }
80    }
81
82    /// Capabilities supported by the Client.
83    #[must_use]
84    pub fn capabilities(mut self, capabilities: ClientCapabilities) -> Self {
85        self.capabilities = capabilities;
86        self
87    }
88
89    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
90    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
91    /// do not recognize.
92    ///
93    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
94    #[must_use]
95    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
96        self.meta = meta.into_option();
97        self
98    }
99}
100
101/// Response to the `initialize` method.
102///
103/// Contains the negotiated protocol version and Agent capabilities.
104///
105/// See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/v2/initialization)
106#[serde_as]
107#[skip_serializing_none]
108#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
109#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
110#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = INITIALIZE_METHOD_NAME)))]
111#[serde(rename_all = "camelCase")]
112#[non_exhaustive]
113pub struct InitializeResponse {
114    /// The highest protocol version supported by the Agent that is at or below
115    /// the version requested by the Client. If no such version exists,
116    /// initialization fails with error code -32022.
117    ///
118    /// The Client MUST check that it supports this version and SHOULD disconnect
119    /// if it does not.
120    pub protocol_version: ProtocolVersion,
121    /// Information about the implementation sending this initialize response.
122    pub info: Implementation,
123    /// Capabilities supported by the Agent.
124    #[serde_as(deserialize_as = "DefaultOnError")]
125    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
126    #[serde(default)]
127    pub capabilities: AgentCapabilities,
128    /// Authentication methods supported by the Agent.
129    ///
130    /// Optional. Omitted or empty means the Agent does not advertise the
131    /// `auth/login` and `auth/logout` methods. Supplying one or more methods means
132    /// the Agent MUST support both `auth/login` and `auth/logout`.
133    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
134    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
135    #[serde(default, skip_serializing_if = "Vec::is_empty")]
136    pub auth_methods: Vec<AuthMethod>,
137    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
138    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
139    /// Implementations MUST NOT assign meaning to keys they do not recognize.
140    ///
141    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
142    #[serde_as(deserialize_as = "DefaultOnError")]
143    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
144    #[serde(default)]
145    #[serde(rename = "_meta")]
146    pub meta: Option<Meta>,
147}
148
149impl InitializeResponse {
150    /// Builds [`InitializeResponse`] with the required response fields set. Optional fields start unset or empty.
151    #[must_use]
152    pub fn new(protocol_version: ProtocolVersion, info: Implementation) -> Self {
153        Self {
154            protocol_version,
155            capabilities: AgentCapabilities::default(),
156            auth_methods: vec![],
157            info,
158            meta: None,
159        }
160    }
161
162    /// Capabilities supported by the Agent.
163    #[must_use]
164    pub fn capabilities(mut self, capabilities: AgentCapabilities) -> Self {
165        self.capabilities = capabilities;
166        self
167    }
168
169    /// Authentication methods supported by the Agent.
170    ///
171    /// Supplying one or more methods means the Agent MUST support both
172    /// `auth/login` and `auth/logout`.
173    #[must_use]
174    pub fn auth_methods(mut self, auth_methods: Vec<AuthMethod>) -> Self {
175        self.auth_methods = auth_methods;
176        self
177    }
178
179    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
180    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
181    /// do not recognize.
182    ///
183    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
184    #[must_use]
185    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
186        self.meta = meta.into_option();
187        self
188    }
189}
190
191/// Metadata about the implementation of the Client or Agent.
192/// Describes the name and version of an ACP implementation, with an optional
193/// title for UI representation.
194#[serde_as]
195#[skip_serializing_none]
196#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
197#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
198#[serde(rename_all = "camelCase")]
199#[non_exhaustive]
200pub struct Implementation {
201    /// Intended for programmatic or logical use, but can be used as a display
202    /// name fallback if title isn't present.
203    pub name: String,
204    /// Intended for UI and end-user contexts and optimized to be human-readable
205    /// and easily understood.
206    ///
207    /// If not provided, the name SHOULD be used for display.
208    ///
209    /// Omitted and `null` are equivalent and mean the `name` is used for display.
210    #[serde_as(deserialize_as = "DefaultOnError")]
211    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
212    #[serde(default)]
213    pub title: Option<String>,
214    /// Version of the implementation. Can be displayed to the user or used
215    /// for debugging or metrics purposes. (e.g. "1.0.0").
216    pub version: String,
217    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
218    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
219    /// Implementations MUST NOT assign meaning to keys they do not recognize.
220    ///
221    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
222    #[serde_as(deserialize_as = "DefaultOnError")]
223    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
224    #[serde(default)]
225    #[serde(rename = "_meta")]
226    pub meta: Option<Meta>,
227}
228
229impl Implementation {
230    /// Builds [`Implementation`] with the required fields set. Optional fields start unset or empty.
231    #[must_use]
232    pub fn new(name: impl Into<String>, version: impl Into<String>) -> Self {
233        Self {
234            name: name.into(),
235            title: None,
236            version: version.into(),
237            meta: None,
238        }
239    }
240
241    /// Intended for UI and end-user contexts and optimized to be human-readable
242    /// and easily understood.
243    ///
244    /// If not provided, the name SHOULD be used for display.
245    #[must_use]
246    pub fn title(mut self, title: impl IntoOption<String>) -> Self {
247        self.title = title.into_option();
248        self
249    }
250
251    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
252    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
253    /// do not recognize.
254    ///
255    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
256    #[must_use]
257    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
258        self.meta = meta.into_option();
259        self
260    }
261}
262
263// Authentication
264
265/// Request parameters for the `auth/login` method.
266///
267/// Specifies which authentication method to use.
268///
269/// Agents MUST support this method when their `initialize` response included
270/// a non-empty `authMethods` list. Clients MUST NOT call this method
271/// when `authMethods` was omitted or empty.
272#[serde_as]
273#[skip_serializing_none]
274#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
275#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
276#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGIN_METHOD_NAME)))]
277#[serde(rename_all = "camelCase")]
278#[non_exhaustive]
279pub struct LoginAuthRequest {
280    /// The ID of the authentication method to use.
281    /// Must be one of the methods advertised in the initialize response.
282    pub method_id: AuthMethodId,
283    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
284    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
285    /// Implementations MUST NOT assign meaning to keys they do not recognize.
286    ///
287    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
288    #[serde_as(deserialize_as = "DefaultOnError")]
289    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
290    #[serde(default)]
291    #[serde(rename = "_meta")]
292    pub meta: Option<Meta>,
293}
294
295impl LoginAuthRequest {
296    /// Builds [`LoginAuthRequest`] with the required request fields set. Optional fields start unset or empty.
297    #[must_use]
298    pub fn new(method_id: impl Into<AuthMethodId>) -> Self {
299        Self {
300            method_id: method_id.into(),
301            meta: None,
302        }
303    }
304
305    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
306    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
307    /// do not recognize.
308    ///
309    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
310    #[must_use]
311    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
312        self.meta = meta.into_option();
313        self
314    }
315}
316
317crate::serde_util::default_on_null! {
318    /// Response to the `auth/login` method.
319    #[serde_as]
320    #[skip_serializing_none]
321    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
322    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
323    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGIN_METHOD_NAME)))]
324    #[serde(rename_all = "camelCase")]
325    #[non_exhaustive]
326    pub struct LoginAuthResponse {
327        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
328        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
329        /// Implementations MUST NOT assign meaning to keys they do not recognize.
330        ///
331        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
332        #[serde_as(deserialize_as = "DefaultOnError")]
333        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
334        #[serde(default)]
335        #[serde(rename = "_meta")]
336        pub meta: Option<Meta>,
337    }
338}
339
340impl LoginAuthResponse {
341    /// Builds [`LoginAuthResponse`] with the required response fields set. Optional fields start unset or empty.
342    #[must_use]
343    pub fn new() -> Self {
344        Self::default()
345    }
346
347    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
348    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
349    /// do not recognize.
350    ///
351    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
352    #[must_use]
353    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
354        self.meta = meta.into_option();
355        self
356    }
357}
358
359// Logout
360
361crate::serde_util::default_on_null! {
362    /// Request parameters for the `auth/logout` method.
363    ///
364    /// Terminates the current authenticated session.
365    ///
366    /// Agents MUST support this method when their `initialize` response included
367    /// a non-empty `authMethods` list. Clients MUST NOT call this method
368    /// when `authMethods` was omitted or empty.
369    #[serde_as]
370    #[skip_serializing_none]
371    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
372    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
373    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGOUT_METHOD_NAME)))]
374    #[serde(rename_all = "camelCase")]
375    #[non_exhaustive]
376    pub struct LogoutAuthRequest {
377        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
378        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
379        /// Implementations MUST NOT assign meaning to keys they do not recognize.
380        ///
381        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
382        #[serde_as(deserialize_as = "DefaultOnError")]
383        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
384        #[serde(default)]
385        #[serde(rename = "_meta")]
386        pub meta: Option<Meta>,
387    }
388}
389
390impl LogoutAuthRequest {
391    /// Builds [`LogoutAuthRequest`] with the required request fields set. Optional fields start unset or empty.
392    #[must_use]
393    pub fn new() -> Self {
394        Self::default()
395    }
396
397    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
398    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
399    /// do not recognize.
400    ///
401    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
402    #[must_use]
403    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
404        self.meta = meta.into_option();
405        self
406    }
407}
408
409crate::serde_util::default_on_null! {
410    /// Response to the `auth/logout` method.
411    #[serde_as]
412    #[skip_serializing_none]
413    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
414    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
415    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGOUT_METHOD_NAME)))]
416    #[serde(rename_all = "camelCase")]
417    #[non_exhaustive]
418    pub struct LogoutAuthResponse {
419        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
420        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
421        /// Implementations MUST NOT assign meaning to keys they do not recognize.
422        ///
423        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
424        #[serde_as(deserialize_as = "DefaultOnError")]
425        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
426        #[serde(default)]
427        #[serde(rename = "_meta")]
428        pub meta: Option<Meta>,
429    }
430}
431
432impl LogoutAuthResponse {
433    /// Builds [`LogoutAuthResponse`] with the required response fields set. Optional fields start unset or empty.
434    #[must_use]
435    pub fn new() -> Self {
436        Self::default()
437    }
438
439    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
440    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
441    /// do not recognize.
442    ///
443    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
444    #[must_use]
445    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
446        self.meta = meta.into_option();
447        self
448    }
449}
450
451// Auth status
452
453#[cfg(feature = "unstable_auth_status")]
454crate::serde_util::default_on_null! {
455    /// **UNSTABLE**
456    ///
457    /// This capability is not part of the spec yet, and may be removed or changed at any point.
458    ///
459    /// Request parameters for the `auth/status` method.
460    ///
461    /// Queries the Agent's current authentication state without changing it.
462    ///
463    /// Agents MUST NOT reject it with `-32000` (Authentication required), since Clients call it to learn
464    /// whether authentication is required.
465    #[serde_as]
466    #[skip_serializing_none]
467    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
468    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
469    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_STATUS_METHOD_NAME)))]
470    #[serde(rename_all = "camelCase")]
471    #[non_exhaustive]
472    pub struct AuthStatusRequest {
473        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
474        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
475        /// Implementations MUST NOT assign meaning to keys they do not recognize.
476        ///
477        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
478        #[serde_as(deserialize_as = "DefaultOnError")]
479        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
480        #[serde(default)]
481        #[serde(rename = "_meta")]
482        pub meta: Option<Meta>,
483    }
484}
485
486#[cfg(feature = "unstable_auth_status")]
487impl AuthStatusRequest {
488    /// Builds [`AuthStatusRequest`] with the required request fields set. Optional fields start unset or empty.
489    #[must_use]
490    pub fn new() -> Self {
491        Self::default()
492    }
493
494    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
495    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
496    /// do not recognize.
497    ///
498    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
499    #[must_use]
500    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
501        self.meta = meta.into_option();
502        self
503    }
504}
505
506/// **UNSTABLE**
507///
508/// This capability is not part of the spec yet, and may be removed or changed at any point.
509///
510/// Response to the `auth/status` method.
511#[cfg(feature = "unstable_auth_status")]
512#[serde_as]
513#[skip_serializing_none]
514#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
515#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
516#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_STATUS_METHOD_NAME)))]
517#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"agent": [{"action": "replace", "target": "authStatus"}]})))]
518#[serde(rename_all = "camelCase")]
519#[non_exhaustive]
520pub struct AuthStatusResponse {
521    /// Whether the Agent can start sessions without the user signing in first.
522    ///
523    /// Clients use this field to decide whether sign-in is needed. Clients MUST treat
524    /// values they do not recognize as `unknown`.
525    pub state: AuthState,
526    /// The accounts the Agent has configured, for display.
527    ///
528    /// Optional. Omitted and empty are equivalent and mean no accounts are reported.
529    /// Agents that hold credentials for several providers or accounts SHOULD list each
530    /// of them and mark the ones in effect with `active`.
531    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
532    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
533    #[serde(default, skip_serializing_if = "Vec::is_empty")]
534    pub accounts: Vec<AuthAccount>,
535    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
536    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
537    /// Implementations MUST NOT assign meaning to keys they do not recognize.
538    ///
539    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
540    #[serde_as(deserialize_as = "DefaultOnError")]
541    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
542    #[serde(default)]
543    #[serde(rename = "_meta")]
544    pub meta: Option<Meta>,
545}
546
547#[cfg(feature = "unstable_auth_status")]
548impl AuthStatusResponse {
549    /// Builds [`AuthStatusResponse`] with the required fields set. Optional fields start unset or empty.
550    #[must_use]
551    pub fn new(state: AuthState) -> Self {
552        Self {
553            state,
554            accounts: vec![],
555            meta: None,
556        }
557    }
558
559    /// The accounts the Agent has configured, for display.
560    #[must_use]
561    pub fn accounts(mut self, accounts: Vec<AuthAccount>) -> Self {
562        self.accounts = accounts;
563        self
564    }
565
566    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
567    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
568    /// do not recognize.
569    ///
570    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
571    #[must_use]
572    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
573        self.meta = meta.into_option();
574        self
575    }
576}
577
578/// **UNSTABLE**
579///
580/// This capability is not part of the spec yet, and may be removed or changed at any point.
581///
582/// Notification sent by the Agent when its authentication status changes.
583///
584/// Carries the same fields as the `auth/status` response. Agents that advertise the
585/// `auth.status` capability MAY send it at any time after `initialize`, and SHOULD only
586/// send it when the reported status differs from the last one sent on the connection.
587#[cfg(feature = "unstable_auth_status")]
588#[serde_as]
589#[skip_serializing_none]
590#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
591#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
592#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = AUTH_STATUS_UPDATE_NOTIFICATION)))]
593#[cfg_attr(feature = "schemars", schemars(extend("x-scope" = {})))]
594#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"agent": [{"action": "replace", "target": "authStatus"}]})))]
595#[serde(rename_all = "camelCase")]
596#[non_exhaustive]
597pub struct AuthStatusUpdateNotification {
598    /// Whether the Agent can start sessions without the user signing in first.
599    ///
600    /// Clients use this field to decide whether sign-in is needed. Clients MUST treat
601    /// values they do not recognize as `unknown`.
602    pub state: AuthState,
603    /// The accounts the Agent has configured, for display.
604    ///
605    /// Optional. Omitted and empty are equivalent and mean no accounts are reported.
606    /// Agents that hold credentials for several providers or accounts SHOULD list each
607    /// of them and mark the ones in effect with `active`.
608    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
609    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
610    #[serde(default, skip_serializing_if = "Vec::is_empty")]
611    pub accounts: Vec<AuthAccount>,
612    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
613    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
614    /// Implementations MUST NOT assign meaning to keys they do not recognize.
615    ///
616    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
617    #[serde_as(deserialize_as = "DefaultOnError")]
618    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
619    #[serde(default)]
620    #[serde(rename = "_meta")]
621    pub meta: Option<Meta>,
622}
623
624#[cfg(feature = "unstable_auth_status")]
625impl AuthStatusUpdateNotification {
626    /// Builds [`AuthStatusUpdateNotification`] with the required fields set. Optional fields start unset or empty.
627    #[must_use]
628    pub fn new(state: AuthState) -> Self {
629        Self {
630            state,
631            accounts: vec![],
632            meta: None,
633        }
634    }
635
636    /// The accounts the Agent has configured, for display.
637    #[must_use]
638    pub fn accounts(mut self, accounts: Vec<AuthAccount>) -> Self {
639        self.accounts = accounts;
640        self
641    }
642
643    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
644    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
645    /// do not recognize.
646    ///
647    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
648    #[must_use]
649    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
650        self.meta = meta.into_option();
651        self
652    }
653}
654
655/// **UNSTABLE**
656///
657/// This capability is not part of the spec yet, and may be removed or changed at any point.
658///
659/// The Agent's overall authentication state.
660#[cfg(feature = "unstable_auth_status")]
661#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
662#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
663#[serde(rename_all = "snake_case")]
664#[non_exhaustive]
665pub enum AuthState {
666    /// Credentials are configured. This does not guarantee that they are valid.
667    Authenticated,
668    /// The user needs to sign in. This includes credentials that are missing,
669    /// expired, or known to be invalid.
670    Unauthenticated,
671    /// No authentication is needed, for example because the Agent uses a local model.
672    NotRequired,
673    /// The Agent cannot currently determine the state.
674    Unknown,
675    /// Custom or future authentication state.
676    ///
677    /// Values beginning with `_` are reserved for implementation-specific
678    /// extensions. Unknown values that do not begin with `_` are reserved for
679    /// future ACP variants.
680    #[serde(untagged)]
681    Other(String),
682}
683
684/// **UNSTABLE**
685///
686/// This capability is not part of the spec yet, and may be removed or changed at any point.
687///
688/// An account or credential the Agent has configured, such as a signed-in user
689/// account or an API key.
690///
691/// All fields are display information only. Clients MUST NOT use them as stable
692/// account identifiers, and SHOULD NOT log them or send them elsewhere, such as to
693/// telemetry.
694#[cfg(feature = "unstable_auth_status")]
695#[serde_as]
696#[skip_serializing_none]
697#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
698#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
699#[serde(rename_all = "camelCase")]
700#[non_exhaustive]
701pub struct AuthAccount {
702    /// Human-readable name for the account, suitable for display on its own,
703    /// for example `Claude Max`, `OpenAI API key`, or `Vertex AI`.
704    pub label: String,
705    /// Short text shown with the label, such as the credential source, for example
706    /// `API key helper`. MUST NOT contain credentials.
707    ///
708    /// Optional. Omitted and `null` are equivalent and mean no description is reported.
709    #[serde_as(deserialize_as = "DefaultOnError")]
710    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
711    #[serde(default)]
712    pub description: Option<String>,
713    /// Whether the Agent currently uses this account by default.
714    ///
715    /// Several accounts MAY be active, for example one per provider.
716    ///
717    /// Optional. Omitted and `null` are equivalent and mean the Agent does not indicate whether this account is in effect.
718    #[serde_as(deserialize_as = "DefaultOnError")]
719    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
720    #[serde(default)]
721    pub active: Option<bool>,
722    /// Display name of the user, such as a username or full name.
723    ///
724    /// Optional. Omitted and `null` are equivalent and mean no name is reported.
725    #[serde_as(deserialize_as = "DefaultOnError")]
726    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
727    #[serde(default)]
728    pub name: Option<String>,
729    /// Email address of the user.
730    ///
731    /// Optional. Omitted and `null` are equivalent and mean no email is reported.
732    #[serde_as(deserialize_as = "DefaultOnError")]
733    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
734    #[serde(default)]
735    pub email: Option<String>,
736    /// Display name of the organization, team, or workspace the account is using.
737    ///
738    /// Optional. Omitted and `null` are equivalent and mean no organization is reported.
739    #[serde_as(deserialize_as = "DefaultOnError")]
740    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
741    #[serde(default)]
742    pub organization: Option<String>,
743    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
744    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
745    /// Implementations MUST NOT assign meaning to keys they do not recognize.
746    ///
747    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
748    #[serde_as(deserialize_as = "DefaultOnError")]
749    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
750    #[serde(default)]
751    #[serde(rename = "_meta")]
752    pub meta: Option<Meta>,
753}
754
755#[cfg(feature = "unstable_auth_status")]
756impl AuthAccount {
757    /// Builds [`AuthAccount`] with the required fields set. Optional fields start unset or empty.
758    #[must_use]
759    pub fn new(label: impl Into<String>) -> Self {
760        Self {
761            label: label.into(),
762            description: None,
763            active: None,
764            name: None,
765            email: None,
766            organization: None,
767            meta: None,
768        }
769    }
770
771    /// Short text shown with the label, such as the credential source.
772    #[must_use]
773    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
774        self.description = description.into_option();
775        self
776    }
777
778    /// Whether the Agent currently uses this account by default.
779    #[must_use]
780    pub fn active(mut self, active: impl IntoOption<bool>) -> Self {
781        self.active = active.into_option();
782        self
783    }
784
785    /// Display name of the user, such as a username or full name.
786    #[must_use]
787    pub fn name(mut self, name: impl IntoOption<String>) -> Self {
788        self.name = name.into_option();
789        self
790    }
791
792    /// Email address of the user.
793    #[must_use]
794    pub fn email(mut self, email: impl IntoOption<String>) -> Self {
795        self.email = email.into_option();
796        self
797    }
798
799    /// Display name of the organization, team, or workspace the account is using.
800    #[must_use]
801    pub fn organization(mut self, organization: impl IntoOption<String>) -> Self {
802        self.organization = organization.into_option();
803        self
804    }
805
806    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
807    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
808    /// do not recognize.
809    ///
810    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
811    #[must_use]
812    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
813        self.meta = meta.into_option();
814        self
815    }
816}
817
818/// **UNSTABLE**
819///
820/// This capability is not part of the spec yet, and may be removed or changed at any point.
821///
822/// Auth status capabilities supported by the Agent.
823///
824/// Supplying `{}` means the Agent supports the `auth/status` method.
825#[cfg(feature = "unstable_auth_status")]
826#[serde_as]
827#[skip_serializing_none]
828#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
829#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
830#[non_exhaustive]
831pub struct AuthStatusCapabilities {
832    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
833    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
834    /// Implementations MUST NOT assign meaning to keys they do not recognize.
835    ///
836    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
837    #[serde_as(deserialize_as = "DefaultOnError")]
838    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
839    #[serde(default)]
840    #[serde(rename = "_meta")]
841    pub meta: Option<Meta>,
842}
843
844#[cfg(feature = "unstable_auth_status")]
845impl AuthStatusCapabilities {
846    /// Builds an empty [`AuthStatusCapabilities`]. Use builder methods to advertise supported sub-capabilities.
847    #[must_use]
848    pub fn new() -> Self {
849        Self::default()
850    }
851
852    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
853    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
854    /// do not recognize.
855    ///
856    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
857    #[must_use]
858    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
859        self.meta = meta.into_option();
860        self
861    }
862}
863
864/// Authentication-related extension capabilities supported by the Agent.
865///
866/// This object does not advertise support for `auth/login` or `auth/logout`.
867/// Those methods are advertised by a non-empty `authMethods` list in the
868/// `initialize` response.
869#[serde_as]
870#[skip_serializing_none]
871#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
872#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
873#[serde(rename_all = "camelCase")]
874#[non_exhaustive]
875pub struct AgentAuthCapabilities {
876    /// **UNSTABLE**
877    ///
878    /// This capability is not part of the spec yet, and may be removed or changed at any point.
879    ///
880    /// Whether the Agent supports the `auth/status` method.
881    ///
882    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
883    /// Supplying `{}` means the Agent supports the `auth/status` method.
884    #[cfg(feature = "unstable_auth_status")]
885    #[serde_as(deserialize_as = "DefaultOnError")]
886    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
887    #[serde(default)]
888    pub status: Option<AuthStatusCapabilities>,
889    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
890    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
891    /// Implementations MUST NOT assign meaning to keys they do not recognize.
892    ///
893    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
894    #[serde_as(deserialize_as = "DefaultOnError")]
895    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
896    #[serde(default)]
897    #[serde(rename = "_meta")]
898    pub meta: Option<Meta>,
899}
900
901impl AgentAuthCapabilities {
902    /// Builds an empty [`AgentAuthCapabilities`].
903    #[must_use]
904    pub fn new() -> Self {
905        Self::default()
906    }
907
908    /// **UNSTABLE**
909    ///
910    /// This capability is not part of the spec yet, and may be removed or changed at any point.
911    ///
912    /// Whether the Agent supports the `auth/status` method.
913    #[cfg(feature = "unstable_auth_status")]
914    #[must_use]
915    pub fn status(mut self, status: impl IntoOption<AuthStatusCapabilities>) -> Self {
916        self.status = status.into_option();
917        self
918    }
919
920    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
921    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
922    /// do not recognize.
923    ///
924    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
925    #[must_use]
926    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
927        self.meta = meta.into_option();
928        self
929    }
930}
931
932/// Typed identifier used for auth method values on the wire.
933#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
934#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
935#[serde(transparent)]
936#[from(forward)]
937#[non_exhaustive]
938pub struct AuthMethodId(pub Arc<str>);
939
940impl AuthMethodId {
941    /// Wraps a protocol string as a typed [`AuthMethodId`].
942    #[must_use]
943    pub fn new(id: impl Into<Self>) -> Self {
944        id.into()
945    }
946}
947
948/// Describes an available authentication method.
949///
950/// The `type` field acts as the discriminator in the serialized JSON form.
951#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
952#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
953#[serde(tag = "type", rename_all = "snake_case")]
954#[non_exhaustive]
955pub enum AuthMethod {
956    /// Client runs the configured Agent program as a separate interactive
957    /// process, without passing this method to `auth/login`.
958    Terminal(AuthMethodTerminal),
959    /// Agent handles authentication itself through `auth/login`.
960    ///
961    /// The `type` discriminator value is `agent`.
962    Agent(AuthMethodAgent),
963    /// Custom or future authentication method.
964    ///
965    /// Values beginning with `_` are reserved for implementation-specific
966    /// extensions. Unknown values that do not begin with `_` are reserved for
967    /// future ACP variants.
968    ///
969    /// Clients that do not understand this method type SHOULD preserve the raw
970    /// payload when storing, replaying, proxying, or forwarding initialization
971    /// data, and otherwise ignore the method or display it generically.
972    #[serde(untagged)]
973    Other(OtherAuthMethod),
974}
975
976impl AuthMethod {
977    /// The unique identifier for this authentication method.
978    #[must_use]
979    pub fn method_id(&self) -> &AuthMethodId {
980        match self {
981            Self::Agent(a) => &a.method_id,
982            Self::Other(a) => &a.method_id,
983            Self::Terminal(t) => &t.method_id,
984        }
985    }
986
987    /// The human-readable name of this authentication method.
988    #[must_use]
989    pub fn name(&self) -> &str {
990        match self {
991            Self::Agent(a) => &a.name,
992            Self::Other(a) => &a.name,
993            Self::Terminal(t) => &t.name,
994        }
995    }
996
997    /// Optional human-readable description of this authentication method.
998    #[must_use]
999    pub fn description(&self) -> Option<&str> {
1000        match self {
1001            Self::Agent(a) => a.description.as_deref(),
1002            Self::Other(a) => a
1003                .fields
1004                .get("description")
1005                .and_then(serde_json::Value::as_str),
1006            Self::Terminal(t) => t.description.as_deref(),
1007        }
1008    }
1009
1010    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1011    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1012    /// do not recognize.
1013    ///
1014    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1015    #[must_use]
1016    pub fn meta(&self) -> Option<&Meta> {
1017        match self {
1018            Self::Agent(a) => a.meta.as_ref(),
1019            Self::Other(a) => a.fields.get("_meta").and_then(serde_json::Value::as_object),
1020            Self::Terminal(t) => t.meta.as_ref(),
1021        }
1022    }
1023}
1024
1025/// Custom or future authentication method payload.
1026#[serde_as]
1027#[skip_serializing_none]
1028#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1029#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1030#[cfg_attr(feature = "schemars", schemars(inline))]
1031#[cfg_attr(feature = "schemars", schemars(transform = other_auth_method_schema))]
1032#[serde(rename_all = "camelCase")]
1033#[non_exhaustive]
1034pub struct OtherAuthMethod {
1035    /// Custom or future authentication method type.
1036    ///
1037    /// Values beginning with `_` are reserved for implementation-specific
1038    /// extensions. Unknown values that do not begin with `_` are reserved for
1039    /// future ACP variants.
1040    #[serde(rename = "type")]
1041    pub type_: String,
1042    /// Unique identifier for this authentication method.
1043    pub method_id: AuthMethodId,
1044    /// Human-readable name of the authentication method.
1045    pub name: String,
1046    /// The remaining fields of the unknown authentication method payload, preserved verbatim,
1047    /// including `description` and `_meta`.
1048    #[serde(flatten)]
1049    pub fields: IndexMap<String, serde_json::Value>,
1050}
1051
1052impl OtherAuthMethod {
1053    /// Builds [`OtherAuthMethod`] from an unknown discriminator and preserves the remaining extension fields.
1054    #[must_use]
1055    pub fn new(
1056        type_: impl Into<String>,
1057        method_id: impl Into<AuthMethodId>,
1058        name: impl Into<String>,
1059        mut fields: IndexMap<String, serde_json::Value>,
1060    ) -> Self {
1061        fields.shift_remove("type");
1062        fields.shift_remove("methodId");
1063        fields.shift_remove("name");
1064        Self {
1065            type_: type_.into(),
1066            method_id: method_id.into(),
1067            name: name.into(),
1068            fields,
1069        }
1070    }
1071}
1072
1073impl<'de> Deserialize<'de> for OtherAuthMethod {
1074    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1075    where
1076        D: serde::Deserializer<'de>,
1077    {
1078        #[derive(Deserialize)]
1079        #[serde(rename_all = "camelCase")]
1080        struct RawOtherAuthMethod {
1081            #[serde(rename = "type")]
1082            type_: String,
1083            method_id: AuthMethodId,
1084            name: String,
1085            #[serde(flatten)]
1086            fields: IndexMap<String, serde_json::Value>,
1087        }
1088
1089        let raw = RawOtherAuthMethod::deserialize(deserializer)?;
1090        if is_known_auth_method_type(&raw.type_) {
1091            return Err(serde::de::Error::custom(format!(
1092                "known authentication method `{}` did not match its schema",
1093                raw.type_
1094            )));
1095        }
1096
1097        Ok(Self {
1098            type_: raw.type_,
1099            method_id: raw.method_id,
1100            name: raw.name,
1101            fields: raw.fields,
1102        })
1103    }
1104}
1105
1106fn is_known_auth_method_type(type_: &str) -> bool {
1107    matches!(type_, "agent" | "terminal")
1108}
1109
1110#[cfg(feature = "schemars")]
1111fn other_auth_method_schema(schema: &mut Schema) {
1112    super::schema_util::reject_known_string_discriminators(schema, "type", &["agent", "terminal"]);
1113}
1114
1115/// Agent handles authentication itself through `auth/login`.
1116///
1117/// The `type` discriminator value is `agent`.
1118#[serde_as]
1119#[skip_serializing_none]
1120#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1121#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1122#[serde(rename_all = "camelCase")]
1123#[non_exhaustive]
1124pub struct AuthMethodAgent {
1125    /// Unique identifier for this authentication method.
1126    pub method_id: AuthMethodId,
1127    /// Human-readable name of the authentication method.
1128    pub name: String,
1129    /// Optional human-readable description of this authentication method.
1130    ///
1131    /// Omitted and `null` are equivalent and mean no description is provided.
1132    #[serde_as(deserialize_as = "DefaultOnError")]
1133    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1134    #[serde(default)]
1135    pub description: Option<String>,
1136    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1137    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1138    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1139    ///
1140    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1141    #[serde_as(deserialize_as = "DefaultOnError")]
1142    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1143    #[serde(default)]
1144    #[serde(rename = "_meta")]
1145    pub meta: Option<Meta>,
1146}
1147
1148impl AuthMethodAgent {
1149    /// Builds [`AuthMethodAgent`] with the required fields set. Optional fields start unset or empty.
1150    #[must_use]
1151    pub fn new(method_id: impl Into<AuthMethodId>, name: impl Into<String>) -> Self {
1152        Self {
1153            method_id: method_id.into(),
1154            name: name.into(),
1155            description: None,
1156            meta: None,
1157        }
1158    }
1159
1160    /// Optional human-readable description of this authentication method.
1161    #[must_use]
1162    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
1163        self.description = description.into_option();
1164        self
1165    }
1166
1167    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1168    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1169    /// do not recognize.
1170    ///
1171    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1172    #[must_use]
1173    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1174        self.meta = meta.into_option();
1175        self
1176    }
1177}
1178
1179/// Terminal-based authentication method.
1180///
1181/// The Client runs the configured Agent program as a separate interactive
1182/// process for the user to authenticate via a TUI. Agents MUST advertise this
1183/// method only when the Client enabled its terminal authentication capability.
1184/// A zero exit status signals success. Any other termination signals failure.
1185/// The Client MUST NOT pass this method to `auth/login`.
1186#[serde_as]
1187#[skip_serializing_none]
1188#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1189#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1190#[serde(rename_all = "camelCase")]
1191#[non_exhaustive]
1192pub struct AuthMethodTerminal {
1193    /// Unique identifier for this authentication method.
1194    pub method_id: AuthMethodId,
1195    /// Human-readable name of the authentication method.
1196    pub name: String,
1197    /// Optional human-readable description of this authentication method.
1198    ///
1199    /// Omitted and `null` are equivalent and mean no description is provided.
1200    #[serde_as(deserialize_as = "DefaultOnError")]
1201    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1202    #[serde(default)]
1203    pub description: Option<String>,
1204    /// Additional arguments to append to the configured Agent invocation for terminal auth.
1205    #[serde_as(deserialize_as = "DefaultOnNull")]
1206    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1207    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1208    pub args: Vec<String>,
1209    /// Additional environment variables to set on the configured Agent invocation for terminal auth.
1210    /// Names SHOULD be unique, and otherwise the last entry wins. These values override
1211    /// same-named variables in the base launch configuration.
1212    #[serde_as(deserialize_as = "DefaultOnNull")]
1213    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1214    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1215    pub env: Vec<EnvVariable>,
1216    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1217    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1218    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1219    ///
1220    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1221    #[serde_as(deserialize_as = "DefaultOnError")]
1222    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1223    #[serde(default)]
1224    #[serde(rename = "_meta")]
1225    pub meta: Option<Meta>,
1226}
1227
1228impl AuthMethodTerminal {
1229    /// Builds [`AuthMethodTerminal`] with the required fields set. Optional fields start unset or empty.
1230    #[must_use]
1231    pub fn new(method_id: impl Into<AuthMethodId>, name: impl Into<String>) -> Self {
1232        Self {
1233            method_id: method_id.into(),
1234            name: name.into(),
1235            description: None,
1236            args: Vec::new(),
1237            env: Vec::new(),
1238            meta: None,
1239        }
1240    }
1241
1242    /// Additional arguments to append to the configured Agent invocation for terminal auth.
1243    #[must_use]
1244    pub fn args(mut self, args: Vec<String>) -> Self {
1245        self.args = args;
1246        self
1247    }
1248
1249    /// Additional environment variables to set on the configured Agent invocation for terminal auth.
1250    /// Names SHOULD be unique, and otherwise the last entry wins. These values override
1251    /// same-named variables in the base launch configuration.
1252    #[must_use]
1253    pub fn env(mut self, env: Vec<EnvVariable>) -> Self {
1254        self.env = env;
1255        self
1256    }
1257
1258    /// Optional human-readable description of this authentication method.
1259    #[must_use]
1260    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
1261        self.description = description.into_option();
1262        self
1263    }
1264
1265    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1266    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1267    /// do not recognize.
1268    ///
1269    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1270    #[must_use]
1271    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1272        self.meta = meta.into_option();
1273        self
1274    }
1275}
1276
1277// New session
1278
1279/// Request parameters for creating a new session.
1280///
1281/// See protocol docs: [Creating a Session](https://agentclientprotocol.com/protocol/v2/session-setup#creating-a-session)
1282#[serde_as]
1283#[skip_serializing_none]
1284#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1285#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1286#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_NEW_METHOD_NAME)))]
1287#[serde(rename_all = "camelCase")]
1288#[non_exhaustive]
1289pub struct NewSessionRequest {
1290    /// The working directory for this session. Must be an absolute path.
1291    pub cwd: AbsolutePath,
1292    /// Additional workspace roots for this session. Each path MUST be absolute.
1293    ///
1294    /// These expand the session's workspace scope without changing `cwd`, which
1295    /// remains the base for relative paths. When omitted or empty, no
1296    /// additional roots are activated for the new session.
1297    #[serde_as(deserialize_as = "DefaultOnNull")]
1298    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1299    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1300    pub additional_directories: Vec<AbsolutePath>,
1301    /// List of MCP (Model Context Protocol) servers for the Agent to connect to.
1302    #[serde_as(deserialize_as = "DefaultOnNull")]
1303    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1304    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1305    pub mcp_servers: Vec<McpServer>,
1306    /// System-level instructions for the new session.
1307    ///
1308    /// Optional. Omitted and `null` are equivalent and mean the Agent uses its
1309    /// own default instructions. Clients MUST only send this when the Agent
1310    /// advertises `session.systemPrompt`.
1311    #[serde(default)]
1312    pub system_prompt: Option<SystemPrompt>,
1313    /// **UNSTABLE**
1314    ///
1315    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1316    ///
1317    /// Initial values for the session's config options.
1318    ///
1319    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1320    /// this when the Agent advertises `session.options`.
1321    ///
1322    /// The Agent applies the entries in list order, as if the Client had called
1323    /// `session/set_config_option` for each entry after the session was set up. Malformed
1324    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1325    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1326    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1327    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries,
1328    /// and SHOULD NOT send other `session/update` notifications caused by applying them
1329    /// before it responds.
1330    #[cfg(feature = "unstable_session_options")]
1331    #[serde_as(deserialize_as = "DefaultOnNull")]
1332    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1333    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1334    pub config_options: Vec<InitialSessionConfigOption>,
1335    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1336    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1337    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1338    ///
1339    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1340    #[serde_as(deserialize_as = "DefaultOnError")]
1341    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1342    #[serde(default)]
1343    #[serde(rename = "_meta")]
1344    pub meta: Option<Meta>,
1345}
1346
1347impl NewSessionRequest {
1348    /// Builds [`NewSessionRequest`] with the required request fields set. Optional fields start unset or empty.
1349    #[must_use]
1350    pub fn new(cwd: impl Into<AbsolutePath>) -> Self {
1351        Self {
1352            cwd: cwd.into(),
1353            additional_directories: vec![],
1354            mcp_servers: vec![],
1355            system_prompt: None,
1356            #[cfg(feature = "unstable_session_options")]
1357            config_options: vec![],
1358            meta: None,
1359        }
1360    }
1361
1362    /// Additional workspace roots for this session. Each path MUST be absolute.
1363    #[must_use]
1364    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1365    where
1366        I: IntoIterator<Item = P>,
1367        P: Into<AbsolutePath>,
1368    {
1369        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1370        self
1371    }
1372
1373    /// List of MCP (Model Context Protocol) servers for the Agent to connect to.
1374    #[must_use]
1375    pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1376        self.mcp_servers = mcp_servers;
1377        self
1378    }
1379
1380    /// System-level instructions for the new session.
1381    #[must_use]
1382    pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1383        self.system_prompt = system_prompt.into_option();
1384        self
1385    }
1386
1387    /// **UNSTABLE**
1388    ///
1389    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1390    ///
1391    /// Initial values for the session's config options.
1392    ///
1393    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1394    /// this when the Agent advertises `session.options`.
1395    ///
1396    /// The Agent applies the entries in list order, as if the Client had called
1397    /// `session/set_config_option` for each entry after the session was set up. Malformed
1398    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1399    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1400    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1401    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries,
1402    /// and SHOULD NOT send other `session/update` notifications caused by applying them
1403    /// before it responds.
1404    #[cfg(feature = "unstable_session_options")]
1405    #[must_use]
1406    pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1407        self.config_options = config_options;
1408        self
1409    }
1410
1411    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1412    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1413    /// do not recognize.
1414    ///
1415    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1416    #[must_use]
1417    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1418        self.meta = meta.into_option();
1419        self
1420    }
1421}
1422
1423/// Response from creating a new session.
1424///
1425/// New sessions default to `idle` until a state update reports otherwise.
1426/// Updates may arrive before or after this response. Clients MUST NOT overwrite
1427/// an already-reported state when the response arrives.
1428///
1429/// An Agent whose new session is not `idle` MUST send the session's
1430/// `state_update` after this response.
1431///
1432/// See protocol docs: [Creating a Session](https://agentclientprotocol.com/protocol/v2/session-setup#creating-a-session)
1433#[serde_as]
1434#[skip_serializing_none]
1435#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1436#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1437#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_NEW_METHOD_NAME)))]
1438#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}, {"action": "replace", "target": "availableCommands", "value": "availableCommands"}]})))]
1439#[serde(rename_all = "camelCase")]
1440#[non_exhaustive]
1441pub struct NewSessionResponse {
1442    /// Unique identifier for the created session.
1443    ///
1444    /// Used in all subsequent requests for this conversation.
1445    pub session_id: SessionId,
1446    /// Initial session configuration options.
1447    ///
1448    /// Optional. Omitted or empty means no config options are advertised.
1449    /// Senders MUST use an array, not `null`.
1450    /// Later `config_option_update` notifications replace this list.
1451    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1452    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1453    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1454    pub config_options: Vec<SessionConfigOption>,
1455    /// Initial commands the Agent can execute in this session.
1456    ///
1457    /// Optional. Omitted or empty means no initial commands are advertised.
1458    /// Senders MUST use an array, not `null`.
1459    /// Later `available_commands_update` notifications replace this list.
1460    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1461    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1462    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1463    pub available_commands: Vec<AvailableCommand>,
1464    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1465    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1466    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1467    ///
1468    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1469    #[serde_as(deserialize_as = "DefaultOnError")]
1470    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1471    #[serde(default)]
1472    #[serde(rename = "_meta")]
1473    pub meta: Option<Meta>,
1474}
1475
1476impl NewSessionResponse {
1477    /// Builds [`NewSessionResponse`] with the required response fields set. Optional fields start unset or empty.
1478    #[must_use]
1479    pub fn new(session_id: impl Into<SessionId>) -> Self {
1480        Self {
1481            session_id: session_id.into(),
1482            config_options: Vec::new(),
1483            available_commands: Vec::new(),
1484            meta: None,
1485        }
1486    }
1487
1488    /// Initial session configuration options.
1489    ///
1490    /// Optional. Omitted or empty means no config options are advertised.
1491    /// Senders MUST use an array, not `null`.
1492    /// Later `config_option_update` notifications replace this list.
1493    #[must_use]
1494    pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
1495        self.config_options = config_options;
1496        self
1497    }
1498
1499    /// Initial commands the Agent can execute in this session.
1500    #[must_use]
1501    pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
1502        self.available_commands = available_commands;
1503        self
1504    }
1505
1506    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1507    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1508    /// do not recognize.
1509    ///
1510    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1511    #[must_use]
1512    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1513        self.meta = meta.into_option();
1514        self
1515    }
1516}
1517
1518// Fork session
1519
1520/// **UNSTABLE**
1521///
1522/// This capability is not part of the spec yet, and may be removed or changed at any point.
1523///
1524/// Request parameters for forking an existing session.
1525///
1526/// Creates a new session based on the context of an existing one. The fork can be used
1527/// for operations like generating summaries without affecting the original session's history.
1528///
1529/// Only available if the Agent supports the `session.fork` capability.
1530#[cfg(feature = "unstable_session_fork")]
1531#[serde_as]
1532#[skip_serializing_none]
1533#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1534#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1535#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_FORK_METHOD_NAME)))]
1536#[serde(rename_all = "camelCase")]
1537#[non_exhaustive]
1538pub struct ForkSessionRequest {
1539    /// The ID of the session to fork.
1540    pub session_id: SessionId,
1541    /// **UNSTABLE**
1542    ///
1543    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1544    ///
1545    /// The session cursor to fork at. The new session's history is the source
1546    /// session's history before the cursor.
1547    ///
1548    /// Optional. Omitted and `null` are equivalent and fork the whole session.
1549    /// Clients MUST only send the ID of a cursor that the Agent announced on the
1550    /// source session and that currently advertises `capabilities.fork`. The Agent
1551    /// rejects any other ID with `-32602`. It does not fall back to forking the
1552    /// whole session.
1553    #[cfg(feature = "unstable_session_cursors")]
1554    #[serde(default)]
1555    pub cursor_id: Option<CursorId>,
1556    /// The working directory for this session. Must be an absolute path.
1557    pub cwd: AbsolutePath,
1558    /// Additional workspace roots to activate for this session. Each path MUST be absolute.
1559    ///
1560    /// When omitted or empty, no additional roots are activated. When non-empty,
1561    /// this is the complete resulting additional-root list for the forked
1562    /// session.
1563    #[serde_as(deserialize_as = "DefaultOnNull")]
1564    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1565    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1566    pub additional_directories: Vec<AbsolutePath>,
1567    /// List of MCP servers to connect to for this session.
1568    #[serde_as(deserialize_as = "DefaultOnNull")]
1569    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1570    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1571    pub mcp_servers: Vec<McpServer>,
1572    /// System-level instructions for the forked session.
1573    ///
1574    /// Optional. Omitted and `null` are equivalent. The Agent MAY then keep a
1575    /// system prompt it stored with the source session or use its default
1576    /// instructions. Clients MUST only send this when the Agent advertises
1577    /// `session.systemPrompt`, and SHOULD send the same value they used for the
1578    /// source session.
1579    #[serde(default)]
1580    pub system_prompt: Option<SystemPrompt>,
1581    /// **UNSTABLE**
1582    ///
1583    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1584    ///
1585    /// Initial values for the forked session's config options.
1586    ///
1587    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1588    /// this when the Agent advertises `session.options`.
1589    ///
1590    /// The Agent applies the entries in list order on top of the configuration the fork
1591    /// starts with, as if the Client had called `session/set_config_option` for each entry
1592    /// after the session was set up. Malformed entries and duplicate `configId` values fail
1593    /// the request with `-32602`. The Agent MUST ignore an entry whose `configId` is unknown,
1594    /// whose `type` does not match the option, or whose value is not allowed when it is
1595    /// applied. The `configOptions` in the response contain the values the session actually
1596    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries,
1597    /// and SHOULD NOT send other `session/update` notifications caused by applying them
1598    /// before it responds.
1599    #[cfg(feature = "unstable_session_options")]
1600    #[serde_as(deserialize_as = "DefaultOnNull")]
1601    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1602    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1603    pub config_options: Vec<InitialSessionConfigOption>,
1604    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1605    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1606    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1607    ///
1608    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1609    #[serde_as(deserialize_as = "DefaultOnError")]
1610    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1611    #[serde(default)]
1612    #[serde(rename = "_meta")]
1613    pub meta: Option<Meta>,
1614}
1615
1616#[cfg(feature = "unstable_session_fork")]
1617impl ForkSessionRequest {
1618    /// Builds [`ForkSessionRequest`] with the required request fields set. Optional fields start unset or empty.
1619    #[must_use]
1620    pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
1621        Self {
1622            session_id: session_id.into(),
1623            #[cfg(feature = "unstable_session_cursors")]
1624            cursor_id: None,
1625            cwd: cwd.into(),
1626            additional_directories: vec![],
1627            mcp_servers: vec![],
1628            system_prompt: None,
1629            #[cfg(feature = "unstable_session_options")]
1630            config_options: vec![],
1631            meta: None,
1632        }
1633    }
1634
1635    /// **UNSTABLE**
1636    ///
1637    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1638    ///
1639    /// The session cursor to fork at. Omitting it forks the whole session.
1640    ///
1641    /// Clients MUST only send the ID of a cursor that the Agent announced on the
1642    /// source session and that currently advertises `capabilities.fork`.
1643    #[cfg(feature = "unstable_session_cursors")]
1644    #[must_use]
1645    pub fn cursor_id(mut self, cursor_id: impl IntoOption<CursorId>) -> Self {
1646        self.cursor_id = cursor_id.into_option();
1647        self
1648    }
1649
1650    /// Additional workspace roots to activate for this session. Each path MUST be absolute.
1651    #[must_use]
1652    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1653    where
1654        I: IntoIterator<Item = P>,
1655        P: Into<AbsolutePath>,
1656    {
1657        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1658        self
1659    }
1660
1661    /// List of MCP servers to connect to for this session.
1662    #[must_use]
1663    pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1664        self.mcp_servers = mcp_servers;
1665        self
1666    }
1667
1668    /// System-level instructions for the forked session.
1669    #[must_use]
1670    pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1671        self.system_prompt = system_prompt.into_option();
1672        self
1673    }
1674
1675    /// **UNSTABLE**
1676    ///
1677    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1678    ///
1679    /// Initial values for the forked session's config options.
1680    ///
1681    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1682    /// this when the Agent advertises `session.options`.
1683    ///
1684    /// The Agent applies the entries in list order on top of the configuration the fork
1685    /// starts with, as if the Client had called `session/set_config_option` for each entry
1686    /// after the session was set up. Malformed entries and duplicate `configId` values fail
1687    /// the request with `-32602`. The Agent MUST ignore an entry whose `configId` is unknown,
1688    /// whose `type` does not match the option, or whose value is not allowed when it is
1689    /// applied. The `configOptions` in the response contain the values the session actually
1690    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries,
1691    /// and SHOULD NOT send other `session/update` notifications caused by applying them
1692    /// before it responds.
1693    #[cfg(feature = "unstable_session_options")]
1694    #[must_use]
1695    pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1696        self.config_options = config_options;
1697        self
1698    }
1699
1700    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1701    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1702    /// do not recognize.
1703    ///
1704    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1705    #[must_use]
1706    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1707        self.meta = meta.into_option();
1708        self
1709    }
1710}
1711
1712/// **UNSTABLE**
1713///
1714/// This capability is not part of the spec yet, and may be removed or changed at any point.
1715///
1716/// Response from forking an existing session.
1717#[cfg(feature = "unstable_session_fork")]
1718#[serde_as]
1719#[skip_serializing_none]
1720#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1721#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1722#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_FORK_METHOD_NAME)))]
1723#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}, {"action": "replace", "target": "availableCommands", "value": "availableCommands"}]})))]
1724#[serde(rename_all = "camelCase")]
1725#[non_exhaustive]
1726pub struct ForkSessionResponse {
1727    /// Unique identifier for the newly created forked session.
1728    pub session_id: SessionId,
1729    /// Initial session configuration options.
1730    ///
1731    /// Optional. Omitted or empty means no config options are advertised.
1732    /// Senders MUST use an array, not `null`.
1733    /// Later `config_option_update` notifications replace this list.
1734    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1735    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1736    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1737    pub config_options: Vec<SessionConfigOption>,
1738    /// Initial commands the Agent can execute in this session.
1739    ///
1740    /// Optional. Omitted or empty means no initial commands are advertised.
1741    /// Senders MUST use an array, not `null`.
1742    /// Later `available_commands_update` notifications replace this list.
1743    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1744    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1745    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1746    pub available_commands: Vec<AvailableCommand>,
1747    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1748    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1749    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1750    ///
1751    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1752    #[serde_as(deserialize_as = "DefaultOnError")]
1753    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1754    #[serde(default)]
1755    #[serde(rename = "_meta")]
1756    pub meta: Option<Meta>,
1757}
1758
1759#[cfg(feature = "unstable_session_fork")]
1760impl ForkSessionResponse {
1761    /// Builds [`ForkSessionResponse`] with the required response fields set. Optional fields start unset or empty.
1762    #[must_use]
1763    pub fn new(session_id: impl Into<SessionId>) -> Self {
1764        Self {
1765            session_id: session_id.into(),
1766            config_options: Vec::new(),
1767            available_commands: Vec::new(),
1768            meta: None,
1769        }
1770    }
1771
1772    /// Initial session configuration options.
1773    ///
1774    /// Optional. Omitted or empty means no config options are advertised.
1775    /// Senders MUST use an array, not `null`.
1776    /// Later `config_option_update` notifications replace this list.
1777    #[must_use]
1778    pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
1779        self.config_options = config_options;
1780        self
1781    }
1782
1783    /// Initial commands the Agent can execute in this session.
1784    #[must_use]
1785    pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
1786        self.available_commands = available_commands;
1787        self
1788    }
1789
1790    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1791    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1792    /// do not recognize.
1793    ///
1794    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1795    #[must_use]
1796    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1797        self.meta = meta.into_option();
1798        self
1799    }
1800}
1801
1802// Resume session
1803
1804/// Request parameters for resuming an existing session.
1805///
1806/// Resumes an existing session and optionally replays retained conversation
1807/// history according to `replayFrom`.
1808#[serde_as]
1809#[skip_serializing_none]
1810#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1811#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1812#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_RESUME_METHOD_NAME)))]
1813#[serde(rename_all = "camelCase")]
1814#[non_exhaustive]
1815pub struct ResumeSessionRequest {
1816    /// The ID of the session to resume.
1817    pub session_id: SessionId,
1818    /// The working directory for this session. Must be an absolute path.
1819    ///
1820    /// Clients MUST send the session's working directory. Agents MAY reject a different directory
1821    /// with `-32602`, and MAY normalize paths when comparing.
1822    pub cwd: AbsolutePath,
1823    /// Additional workspace roots to activate for this session. Each path MUST be absolute.
1824    ///
1825    /// When omitted or empty, no additional roots are activated. When non-empty,
1826    /// this is the complete resulting additional-root list for the resumed
1827    /// session. It MAY differ from any previously used or reported list as long as
1828    /// the request `cwd` matches the session's `cwd`.
1829    #[serde_as(deserialize_as = "DefaultOnNull")]
1830    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1831    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1832    pub additional_directories: Vec<AbsolutePath>,
1833    /// List of MCP servers to connect to for this session.
1834    ///
1835    /// The complete set of Client-provided servers. Omitted and `[]` mean none. Agents SHOULD
1836    /// NOT restore servers from earlier requests.
1837    #[serde_as(deserialize_as = "DefaultOnNull")]
1838    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1839    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1840    pub mcp_servers: Vec<McpServer>,
1841    /// Inclusive cursor describing where conversation replay begins.
1842    ///
1843    /// Optional. Omitted and `null` are equivalent, and the Agent MUST NOT replay
1844    /// previous conversation history. Replay cursors are inclusive:
1845    /// replay includes the position identified by the cursor. Supplying
1846    /// `{ "type": "start" }` means the Agent MUST replay all retained
1847    /// conversation history before responding.
1848    ///
1849    /// Agents MUST reject unsupported cursor types or malformed cursor values
1850    /// with `-32602` (Invalid params), rather than substituting another cursor
1851    /// or resuming without replay.
1852    #[serde(default)]
1853    pub replay_from: Option<ReplayFrom>,
1854    /// System-level instructions for the resumed session.
1855    ///
1856    /// Optional. Omitted and `null` are equivalent. The Agent MAY then keep a
1857    /// system prompt it stored with the session or use its default instructions.
1858    /// Clients MUST only send this when the Agent advertises
1859    /// `session.systemPrompt`, and SHOULD send the same value they used when the
1860    /// session was created.
1861    #[serde(default)]
1862    pub system_prompt: Option<SystemPrompt>,
1863    /// **UNSTABLE**
1864    ///
1865    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1866    ///
1867    /// Initial values for the session's config options.
1868    ///
1869    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1870    /// this when the Agent advertises `session.options`.
1871    ///
1872    /// The Agent applies the entries in list order, as if the Client had called
1873    /// `session/set_config_option` for each entry after the session was set up. Malformed
1874    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1875    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1876    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1877    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries
1878    /// on the requesting connection. If the session is active on other connections, the
1879    /// Agent SHOULD send `config_option_update` on those connections.
1880    ///
1881    /// The Agent applies the entries before it replays history for `replayFrom` and before
1882    /// it responds.
1883    #[cfg(feature = "unstable_session_options")]
1884    #[serde_as(deserialize_as = "DefaultOnNull")]
1885    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1886    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1887    pub config_options: Vec<InitialSessionConfigOption>,
1888    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1889    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1890    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1891    ///
1892    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1893    #[serde_as(deserialize_as = "DefaultOnError")]
1894    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1895    #[serde(default)]
1896    #[serde(rename = "_meta")]
1897    pub meta: Option<Meta>,
1898}
1899
1900impl ResumeSessionRequest {
1901    /// Builds [`ResumeSessionRequest`] with the required request fields set. Optional fields start unset or empty.
1902    #[must_use]
1903    pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
1904        Self {
1905            session_id: session_id.into(),
1906            cwd: cwd.into(),
1907            additional_directories: vec![],
1908            mcp_servers: vec![],
1909            replay_from: None,
1910            system_prompt: None,
1911            #[cfg(feature = "unstable_session_options")]
1912            config_options: vec![],
1913            meta: None,
1914        }
1915    }
1916
1917    /// Additional workspace roots to activate for this session. Each path MUST be absolute.
1918    #[must_use]
1919    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1920    where
1921        I: IntoIterator<Item = P>,
1922        P: Into<AbsolutePath>,
1923    {
1924        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1925        self
1926    }
1927
1928    /// List of MCP servers to connect to for this session.
1929    #[must_use]
1930    pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1931        self.mcp_servers = mcp_servers;
1932        self
1933    }
1934
1935    /// Inclusive cursor describing where conversation replay begins.
1936    ///
1937    /// Omitted and `null` are equivalent, and the Agent MUST NOT replay
1938    /// previous conversation history. Replay cursors are inclusive: replay
1939    /// includes the position identified by the cursor. Supplying
1940    /// `{ "type": "start" }` means the Agent MUST replay all retained
1941    /// conversation history before responding.
1942    #[must_use]
1943    pub fn replay_from(mut self, replay_from: impl IntoOption<ReplayFrom>) -> Self {
1944        self.replay_from = replay_from.into_option();
1945        self
1946    }
1947
1948    /// System-level instructions for the resumed session.
1949    #[must_use]
1950    pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1951        self.system_prompt = system_prompt.into_option();
1952        self
1953    }
1954
1955    /// **UNSTABLE**
1956    ///
1957    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1958    ///
1959    /// Initial values for the session's config options.
1960    ///
1961    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1962    /// this when the Agent advertises `session.options`.
1963    ///
1964    /// The Agent applies the entries in list order, as if the Client had called
1965    /// `session/set_config_option` for each entry after the session was set up. Malformed
1966    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1967    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1968    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1969    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries
1970    /// on the requesting connection. If the session is active on other connections, the
1971    /// Agent SHOULD send `config_option_update` on those connections.
1972    #[cfg(feature = "unstable_session_options")]
1973    #[must_use]
1974    pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1975        self.config_options = config_options;
1976        self
1977    }
1978
1979    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1980    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1981    /// do not recognize.
1982    ///
1983    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1984    #[must_use]
1985    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1986        self.meta = meta.into_option();
1987        self
1988    }
1989}
1990
1991/// Inclusive cursor describing where replayed session history begins.
1992///
1993/// Replay includes the position identified by the cursor.
1994#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1995#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1996#[serde(tag = "type", rename_all = "snake_case")]
1997#[non_exhaustive]
1998pub enum ReplayFrom {
1999    /// Replay all retained conversation history from its first replayable entry.
2000    Start(ReplayFromStart),
2001    /// Custom or future replay cursor.
2002    ///
2003    /// Values beginning with `_` are reserved for implementation-specific
2004    /// extensions. Unknown values that do not begin with `_` are reserved for
2005    /// future ACP variants.
2006    ///
2007    /// Intermediaries SHOULD preserve the raw payload when storing, replaying,
2008    /// proxying, or forwarding requests. Agents that do not support this cursor
2009    /// MUST reject the request with `-32602` (Invalid params), rather than
2010    /// substituting another cursor or resuming without replay.
2011    #[serde(untagged)]
2012    Other(OtherReplayFrom),
2013}
2014
2015impl From<ReplayFromStart> for ReplayFrom {
2016    fn from(replay_from: ReplayFromStart) -> Self {
2017        Self::Start(replay_from)
2018    }
2019}
2020
2021/// Inclusive replay cursor requesting replay from the start of retained conversation history.
2022#[serde_as]
2023#[skip_serializing_none]
2024#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2025#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2026#[serde(rename_all = "camelCase")]
2027#[non_exhaustive]
2028pub struct ReplayFromStart {
2029    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2030    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2031    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2032    ///
2033    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2034    #[serde_as(deserialize_as = "DefaultOnError")]
2035    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2036    #[serde(default)]
2037    #[serde(rename = "_meta")]
2038    pub meta: Option<Meta>,
2039}
2040
2041impl ReplayFromStart {
2042    /// Builds [`ReplayFromStart`].
2043    #[must_use]
2044    pub fn new() -> Self {
2045        Self::default()
2046    }
2047
2048    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2049    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2050    /// do not recognize.
2051    ///
2052    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2053    #[must_use]
2054    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2055        self.meta = meta.into_option();
2056        self
2057    }
2058}
2059
2060/// Custom or future replay cursor payload.
2061#[serde_as]
2062#[skip_serializing_none]
2063#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2064#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
2065#[cfg_attr(feature = "schemars", schemars(inline))]
2066#[cfg_attr(feature = "schemars", schemars(transform = other_replay_from_schema))]
2067#[serde(rename_all = "camelCase")]
2068#[non_exhaustive]
2069pub struct OtherReplayFrom {
2070    /// Custom or future replay cursor type.
2071    ///
2072    /// Values beginning with `_` are reserved for implementation-specific
2073    /// extensions. Unknown values that do not begin with `_` are reserved for
2074    /// future ACP variants.
2075    #[serde(rename = "type")]
2076    pub type_: String,
2077    /// The remaining fields of the unknown replay cursor payload, preserved verbatim,
2078    /// including `_meta`.
2079    #[serde(flatten)]
2080    pub fields: IndexMap<String, serde_json::Value>,
2081}
2082
2083impl OtherReplayFrom {
2084    /// Builds [`OtherReplayFrom`] from an unknown discriminator and preserves the remaining extension fields.
2085    #[must_use]
2086    pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
2087        fields.shift_remove("type");
2088        Self {
2089            type_: type_.into(),
2090            fields,
2091        }
2092    }
2093}
2094
2095impl<'de> Deserialize<'de> for OtherReplayFrom {
2096    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2097    where
2098        D: serde::Deserializer<'de>,
2099    {
2100        let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
2101        let type_ = fields
2102            .shift_remove("type")
2103            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
2104        let serde_json::Value::String(type_) = type_ else {
2105            return Err(serde::de::Error::custom("`type` must be a string"));
2106        };
2107
2108        if is_known_replay_from_type(&type_) {
2109            return Err(serde::de::Error::custom(format!(
2110                "known replay cursor `{type_}` did not match its schema"
2111            )));
2112        }
2113
2114        Ok(Self { type_, fields })
2115    }
2116}
2117
2118fn is_known_replay_from_type(type_: &str) -> bool {
2119    matches!(type_, "start")
2120}
2121
2122#[cfg(feature = "schemars")]
2123fn other_replay_from_schema(schema: &mut Schema) {
2124    super::schema_util::reject_known_string_discriminators(schema, "type", &["start"]);
2125}
2126
2127crate::serde_util::default_on_null! {
2128    /// Response from resuming an existing session.
2129    ///
2130    /// The Agent MUST send a current `state_update` after any requested history
2131    /// replay and before this response, even without replay. The update reports
2132    /// foreground state after resuming. The response alone does not imply `idle`.
2133    ///
2134    /// See protocol docs: [Current-State Synchronization](https://agentclientprotocol.com/protocol/v2/session-setup#current-state-synchronization)
2135    #[serde_as]
2136    #[skip_serializing_none]
2137    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2138    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2139    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_RESUME_METHOD_NAME)))]
2140    #[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}, {"action": "replace", "target": "availableCommands", "value": "availableCommands"}]})))]
2141    #[serde(rename_all = "camelCase")]
2142    #[non_exhaustive]
2143    pub struct ResumeSessionResponse {
2144        /// Current session configuration options.
2145        ///
2146        /// Optional. Omitted or empty means no config options are advertised.
2147        /// Senders MUST use an array, not `null`.
2148        /// Later `config_option_update` notifications replace this list.
2149        #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2150        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2151        #[serde(default, skip_serializing_if = "Vec::is_empty")]
2152        pub config_options: Vec<SessionConfigOption>,
2153        /// Current commands the Agent can execute in this session.
2154        ///
2155        /// Optional. Omitted or empty means no initial commands are advertised.
2156        /// Senders MUST use an array, not `null`.
2157        /// Later `available_commands_update` notifications replace this list.
2158        #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2159        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2160        #[serde(default, skip_serializing_if = "Vec::is_empty")]
2161        pub available_commands: Vec<AvailableCommand>,
2162        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2163        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2164        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2165        ///
2166        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2167        #[serde_as(deserialize_as = "DefaultOnError")]
2168        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2169        #[serde(default)]
2170        #[serde(rename = "_meta")]
2171        pub meta: Option<Meta>,
2172    }
2173}
2174
2175impl ResumeSessionResponse {
2176    /// Builds [`ResumeSessionResponse`] with the required response fields set. Optional fields start unset or empty.
2177    #[must_use]
2178    pub fn new() -> Self {
2179        Self::default()
2180    }
2181
2182    /// Current session configuration options.
2183    ///
2184    /// Optional. Omitted or empty means no config options are advertised.
2185    /// Senders MUST use an array, not `null`.
2186    /// Later `config_option_update` notifications replace this list.
2187    #[must_use]
2188    pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
2189        self.config_options = config_options;
2190        self
2191    }
2192
2193    /// Current commands the Agent can execute in this session.
2194    #[must_use]
2195    pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
2196        self.available_commands = available_commands;
2197        self
2198    }
2199
2200    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2201    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2202    /// do not recognize.
2203    ///
2204    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2205    #[must_use]
2206    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2207        self.meta = meta.into_option();
2208        self
2209    }
2210}
2211
2212// Close session
2213
2214/// Request parameters for closing an active session.
2215///
2216/// The Agent MUST cancel any ongoing work related to the session as if `session/cancel`
2217/// was called, then free the resources associated with the session. Unlike `session/cancel`,
2218/// closing also stops the session's background work. After the close response, the Agent
2219/// sends no notifications or requests for the session on that connection. It still
2220/// answers `session/prompt` requests that were pending.
2221///
2222/// Closing a session that does not exist or is not active SHOULD succeed, and Clients SHOULD
2223/// treat a `-32002` response as a successful close.
2224///
2225/// When closing cancels active foreground work, the Agent MUST send the final
2226/// updates for that work and the idle `state_update` with `stopReason: "cancelled"`
2227/// before responding successfully to `session/close`. Closing an idle session
2228/// does not itself require another idle update.
2229///
2230/// Closing also cancels pending `session/prompt` requests whose messages have not
2231/// been inserted, including held prompts. If closing prevents a prompt's user message from being inserted, the
2232/// Agent MUST answer that request with `-32800` (Request cancelled). If the message
2233/// has already been inserted, the Agent MUST respond successfully with its
2234/// `messageId`. Prompt responses need not precede the close response.
2235#[serde_as]
2236#[skip_serializing_none]
2237#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2238#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2239#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CLOSE_METHOD_NAME)))]
2240#[serde(rename_all = "camelCase")]
2241#[non_exhaustive]
2242pub struct CloseSessionRequest {
2243    /// The ID of the session to close.
2244    pub session_id: SessionId,
2245    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2246    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2247    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2248    ///
2249    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2250    #[serde_as(deserialize_as = "DefaultOnError")]
2251    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2252    #[serde(default)]
2253    #[serde(rename = "_meta")]
2254    pub meta: Option<Meta>,
2255}
2256
2257impl CloseSessionRequest {
2258    /// Builds [`CloseSessionRequest`] with the required request fields set. Optional fields start unset or empty.
2259    #[must_use]
2260    pub fn new(session_id: impl Into<SessionId>) -> Self {
2261        Self {
2262            session_id: session_id.into(),
2263            meta: None,
2264        }
2265    }
2266
2267    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2268    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2269    /// do not recognize.
2270    ///
2271    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2272    #[must_use]
2273    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2274        self.meta = meta.into_option();
2275        self
2276    }
2277}
2278
2279crate::serde_util::default_on_null! {
2280    /// Response from closing a session.
2281    #[serde_as]
2282    #[skip_serializing_none]
2283    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2284    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2285    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CLOSE_METHOD_NAME)))]
2286    #[serde(rename_all = "camelCase")]
2287    #[non_exhaustive]
2288    pub struct CloseSessionResponse {
2289        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2290        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2291        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2292        ///
2293        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2294        #[serde_as(deserialize_as = "DefaultOnError")]
2295        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2296        #[serde(default)]
2297        #[serde(rename = "_meta")]
2298        pub meta: Option<Meta>,
2299    }
2300}
2301
2302impl CloseSessionResponse {
2303    /// Builds [`CloseSessionResponse`] with the required response fields set. Optional fields start unset or empty.
2304    #[must_use]
2305    pub fn new() -> Self {
2306        Self::default()
2307    }
2308
2309    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2310    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2311    /// do not recognize.
2312    ///
2313    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2314    #[must_use]
2315    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2316        self.meta = meta.into_option();
2317        self
2318    }
2319}
2320
2321// Session status
2322
2323/// **UNSTABLE**
2324///
2325/// This capability is not part of the spec yet, and may be removed or changed at any point.
2326///
2327/// Request parameters for checking the status of a session.
2328///
2329/// Only available if the Agent supports the `session.status` capability.
2330///
2331/// `session/status` MUST NOT have side effects. The Agent does not resume, create,
2332/// close, or change the session, and does not attach the requesting connection to it.
2333/// A session the Agent does not know gets `-32002` with the requested `sessionId` in `data`.
2334#[cfg(feature = "unstable_session_status")]
2335#[serde_as]
2336#[skip_serializing_none]
2337#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2338#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2339#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_STATUS_METHOD_NAME)))]
2340#[serde(rename_all = "camelCase")]
2341#[non_exhaustive]
2342pub struct SessionStatusRequest {
2343    /// The ID of the session to check.
2344    pub session_id: SessionId,
2345    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2346    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2347    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2348    ///
2349    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2350    #[serde_as(deserialize_as = "DefaultOnError")]
2351    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2352    #[serde(default)]
2353    #[serde(rename = "_meta")]
2354    pub meta: Option<Meta>,
2355}
2356
2357#[cfg(feature = "unstable_session_status")]
2358impl SessionStatusRequest {
2359    /// Builds [`SessionStatusRequest`] with the required request fields set. Optional fields start unset or empty.
2360    #[must_use]
2361    pub fn new(session_id: impl Into<SessionId>) -> Self {
2362        Self {
2363            session_id: session_id.into(),
2364            meta: None,
2365        }
2366    }
2367
2368    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2369    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2370    /// do not recognize.
2371    ///
2372    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2373    #[must_use]
2374    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2375        self.meta = meta.into_option();
2376        self
2377    }
2378}
2379
2380/// **UNSTABLE**
2381///
2382/// This capability is not part of the spec yet, and may be removed or changed at any point.
2383///
2384/// Response from checking the status of a session.
2385///
2386/// The result is a snapshot. A session reported `open` may be closed or evicted before
2387/// the Client's next request.
2388#[cfg(feature = "unstable_session_status")]
2389#[serde_as]
2390#[skip_serializing_none]
2391#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2392#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2393#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_STATUS_METHOD_NAME)))]
2394#[serde(rename_all = "camelCase")]
2395#[non_exhaustive]
2396pub struct SessionStatusResponse {
2397    /// Whether the Agent has the session in memory.
2398    ///
2399    /// Required. Clients MUST treat a value they do not recognize as `saved`.
2400    pub status: SessionStatus,
2401    /// The session's current foreground state, as the same snapshot the Agent sends in
2402    /// `state_update` notifications.
2403    ///
2404    /// Optional. Agents SHOULD include it when `status` is `open`. Omitted and `null`
2405    /// mean the Agent is not reporting foreground state, and Clients
2406    /// MUST NOT read that as `idle`. This is a snapshot, not a new transition. Clients
2407    /// MUST NOT count an `idle` snapshot as a new completion.
2408    #[serde_as(deserialize_as = "DefaultOnError")]
2409    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2410    #[serde(default)]
2411    pub state: Option<StateUpdate>,
2412    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2413    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2414    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2415    ///
2416    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2417    #[serde_as(deserialize_as = "DefaultOnError")]
2418    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2419    #[serde(default)]
2420    #[serde(rename = "_meta")]
2421    pub meta: Option<Meta>,
2422}
2423
2424#[cfg(feature = "unstable_session_status")]
2425impl SessionStatusResponse {
2426    /// Builds [`SessionStatusResponse`] with the required response fields set. Optional fields start unset or empty.
2427    #[must_use]
2428    pub fn new(status: SessionStatus) -> Self {
2429        Self {
2430            status,
2431            state: None,
2432            meta: None,
2433        }
2434    }
2435
2436    /// The session's current foreground state, as the same snapshot the Agent sends in
2437    /// `state_update` notifications.
2438    #[must_use]
2439    pub fn state(mut self, state: impl IntoOption<StateUpdate>) -> Self {
2440        self.state = state.into_option();
2441        self
2442    }
2443
2444    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2445    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2446    /// do not recognize.
2447    ///
2448    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2449    #[must_use]
2450    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2451        self.meta = meta.into_option();
2452        self
2453    }
2454}
2455
2456/// **UNSTABLE**
2457///
2458/// This capability is not part of the spec yet, and may be removed or changed at any point.
2459///
2460/// Whether the Agent has a session in memory, as reported by `session/status`.
2461#[cfg(feature = "unstable_session_status")]
2462#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2463#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2464#[serde(rename_all = "snake_case")]
2465#[non_exhaustive]
2466pub enum SessionStatus {
2467    /// The Agent has the session in memory, for any connection.
2468    ///
2469    /// This does not mean the requesting connection is attached to it. A Client that did
2470    /// not create or resume the session on its own connection MUST still call
2471    /// `session/resume` before sending `session/prompt` or expecting
2472    /// `session/update` notifications.
2473    Open,
2474    /// The Agent knows the session and can resume it, but does not have it in memory.
2475    ///
2476    /// The Client can call `session/resume` to start it.
2477    Saved,
2478    /// Custom or future session status.
2479    ///
2480    /// Values beginning with `_` are reserved for implementation-specific
2481    /// extensions. Unknown values that do not begin with `_` are reserved for
2482    /// future ACP variants. Clients MUST treat a value they do not recognize as
2483    /// `saved`.
2484    #[serde(untagged)]
2485    Other(String),
2486}
2487
2488/// **UNSTABLE**
2489///
2490/// This capability is not part of the spec yet, and may be removed or changed at any point.
2491///
2492/// Request parameters for `session/options`, which returns the config options a session
2493/// would start with, without creating or resuming a session.
2494///
2495/// Only available if the Agent supports the `session.options` capability.
2496///
2497/// `session/options` MUST NOT create or resume a session, send `session/update`
2498/// notifications, add an entry to `session/list`, or change an existing session. Agents
2499/// SHOULD NOT connect to MCP servers to answer it. Agents MAY start their runtime to resolve
2500/// the options. The rules above still hold for it.
2501#[cfg(feature = "unstable_session_options")]
2502#[serde_as]
2503#[skip_serializing_none]
2504#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2505#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2506#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_OPTIONS_METHOD_NAME)))]
2507#[serde(rename_all = "camelCase")]
2508#[non_exhaustive]
2509pub struct SessionOptionsRequest {
2510    /// The working directory to resolve options for. Must be an absolute path.
2511    pub cwd: AbsolutePath,
2512    /// Additional workspace roots to resolve options for. Each path MUST be absolute.
2513    ///
2514    /// Optional. Omitted and `null` are equivalent to an empty list.
2515    #[serde_as(deserialize_as = "DefaultOnNull")]
2516    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
2517    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2518    pub additional_directories: Vec<AbsolutePath>,
2519    /// The session to resolve options for.
2520    ///
2521    /// Optional. Omitted and `null` are equivalent and mean a new session. When present,
2522    /// the Agent returns what `session/resume` with the same `cwd` and
2523    /// `additionalDirectories` would return, with the same `cwd` rules. A session the
2524    /// Agent does not know gets `-32002`.
2525    #[serde(default)]
2526    pub session_id: Option<SessionId>,
2527    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2528    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2529    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2530    ///
2531    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2532    #[serde_as(deserialize_as = "DefaultOnError")]
2533    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2534    #[serde(default)]
2535    #[serde(rename = "_meta")]
2536    pub meta: Option<Meta>,
2537}
2538
2539#[cfg(feature = "unstable_session_options")]
2540impl SessionOptionsRequest {
2541    /// Builds [`SessionOptionsRequest`] with the required request fields set. Optional fields start unset or empty.
2542    #[must_use]
2543    pub fn new(cwd: impl Into<AbsolutePath>) -> Self {
2544        Self {
2545            cwd: cwd.into(),
2546            additional_directories: vec![],
2547            session_id: None,
2548            meta: None,
2549        }
2550    }
2551
2552    /// Additional workspace roots to resolve options for. Each path MUST be absolute.
2553    #[must_use]
2554    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
2555    where
2556        I: IntoIterator<Item = P>,
2557        P: Into<AbsolutePath>,
2558    {
2559        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
2560        self
2561    }
2562
2563    /// The session to resolve options for. Unset means a new session.
2564    #[must_use]
2565    pub fn session_id(mut self, session_id: impl IntoOption<SessionId>) -> Self {
2566        self.session_id = session_id.into_option();
2567        self
2568    }
2569
2570    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2571    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2572    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2573    ///
2574    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2575    #[must_use]
2576    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2577        self.meta = meta.into_option();
2578        self
2579    }
2580}
2581
2582#[cfg(feature = "unstable_session_options")]
2583crate::serde_util::default_on_null! {
2584    /// **UNSTABLE**
2585    ///
2586    /// This capability is not part of the spec yet, and may be removed or changed at any point.
2587    ///
2588    /// Response from `session/options`.
2589    ///
2590    /// The result is a snapshot. The options a session actually starts with are the ones in
2591    /// the session setup response.
2592    #[serde_as]
2593    #[skip_serializing_none]
2594    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2595    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2596    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_OPTIONS_METHOD_NAME)))]
2597    #[serde(rename_all = "camelCase")]
2598    #[non_exhaustive]
2599    pub struct SessionOptionsResponse {
2600        /// The config options the session would start with, with the same rules as on
2601        /// `NewSessionResponse`.
2602        ///
2603        /// Optional. Omitted or empty means no config options are advertised.
2604        /// Senders MUST use an array, not `null`.
2605        #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2606        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2607        #[serde(default, skip_serializing_if = "Vec::is_empty")]
2608        pub config_options: Vec<SessionConfigOption>,
2609        /// Commands the Agent knows the session would have.
2610        ///
2611        /// Optional. Omitted or empty means no commands are advertised.
2612        /// Senders MUST use an array, not `null`.
2613        ///
2614        /// Advisory. Agents MAY return a partial list. Clients MUST use the commands from the
2615        /// `session/new` or `session/resume` response and later `available_commands_update`
2616        /// notifications for the session itself.
2617        #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2618        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2619        #[serde(default, skip_serializing_if = "Vec::is_empty")]
2620        pub available_commands: Vec<AvailableCommand>,
2621        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2622        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2623        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2624        ///
2625        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2626        #[serde_as(deserialize_as = "DefaultOnError")]
2627        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2628        #[serde(default)]
2629        #[serde(rename = "_meta")]
2630        pub meta: Option<Meta>,
2631    }
2632}
2633
2634#[cfg(feature = "unstable_session_options")]
2635impl SessionOptionsResponse {
2636    /// Builds [`SessionOptionsResponse`] with the required response fields set. Optional fields start unset or empty.
2637    #[must_use]
2638    pub fn new() -> Self {
2639        Self::default()
2640    }
2641
2642    /// The config options the session would start with.
2643    #[must_use]
2644    pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
2645        self.config_options = config_options;
2646        self
2647    }
2648
2649    /// Commands the Agent knows the session would have. Advisory.
2650    #[must_use]
2651    pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
2652        self.available_commands = available_commands;
2653        self
2654    }
2655
2656    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2657    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2658    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2659    ///
2660    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2661    #[must_use]
2662    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2663        self.meta = meta.into_option();
2664        self
2665    }
2666}
2667
2668/// **UNSTABLE**
2669///
2670/// This capability is not part of the spec yet, and may be removed or changed at any point.
2671///
2672/// An initial value for a config option, sent on session setup requests.
2673///
2674/// Same shape as `session/set_config_option` without `sessionId`. Unlike
2675/// `session/set_config_option`, an unknown `configId`, a `type` that does not match the
2676/// option, or a value that is not allowed is ignored instead of rejected.
2677#[cfg(feature = "unstable_session_options")]
2678#[serde_as]
2679#[skip_serializing_none]
2680#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2681#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2682#[serde(rename_all = "camelCase")]
2683#[non_exhaustive]
2684pub struct InitialSessionConfigOption {
2685    /// The ID of the configuration option to set.
2686    pub config_id: SessionConfigId,
2687    /// The value to set, including a `type` discriminator and the raw `value`.
2688    ///
2689    /// Payloads MUST send `type: "id"` for id-based options. A value `type` the Agent
2690    /// does not support fails the request with `-32602`.
2691    #[serde(flatten)]
2692    pub value: SessionConfigOptionValue,
2693    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2694    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2695    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2696    ///
2697    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2698    #[serde_as(deserialize_as = "DefaultOnError")]
2699    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2700    #[serde(default)]
2701    #[serde(rename = "_meta")]
2702    pub meta: Option<Meta>,
2703}
2704
2705#[cfg(feature = "unstable_session_options")]
2706impl InitialSessionConfigOption {
2707    /// Builds [`InitialSessionConfigOption`] with the required fields set. Optional fields start unset or empty.
2708    #[must_use]
2709    pub fn new(
2710        config_id: impl Into<SessionConfigId>,
2711        value: impl Into<SessionConfigOptionValue>,
2712    ) -> Self {
2713        Self {
2714            config_id: config_id.into(),
2715            value: value.into(),
2716            meta: None,
2717        }
2718    }
2719
2720    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2721    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2722    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2723    ///
2724    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2725    #[must_use]
2726    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2727        self.meta = meta.into_option();
2728        self
2729    }
2730}
2731
2732// Cancel tool call
2733
2734/// Request parameters for cancelling one tool call.
2735///
2736/// Clients MUST NOT send it unless the tool call currently advertises `capabilities.cancel`.
2737///
2738/// The Agent responds once it has accepted the cancellation. The response does not mean
2739/// the work has stopped. The Agent confirms it with a `tool_call_update` to a final
2740/// status: normally `cancelled`, or `completed` or `failed` if the work finished first.
2741///
2742/// The Agent responds with `-32602` if the tool call is unknown, already final, or not
2743/// cancellable. Cancelling a tool call does not change the foreground state by itself.
2744///
2745/// See protocol docs: [Cancelling Tool Calls](https://agentclientprotocol.com/protocol/v2/tool-calls#cancelling-tool-calls)
2746#[serde_as]
2747#[skip_serializing_none]
2748#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2749#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2750#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TOOL_CALL_CANCEL_METHOD_NAME)))]
2751#[serde(rename_all = "camelCase")]
2752#[non_exhaustive]
2753pub struct CancelToolCallRequest {
2754    /// The ID of the session that owns the tool call.
2755    pub session_id: SessionId,
2756    /// The ID of the tool call to cancel.
2757    pub tool_call_id: ToolCallId,
2758    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2759    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2760    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2761    ///
2762    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2763    #[serde_as(deserialize_as = "DefaultOnError")]
2764    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2765    #[serde(default)]
2766    #[serde(rename = "_meta")]
2767    pub meta: Option<Meta>,
2768}
2769
2770impl CancelToolCallRequest {
2771    /// Builds [`CancelToolCallRequest`] with the required request fields set. Optional fields start unset or empty.
2772    #[must_use]
2773    pub fn new(session_id: impl Into<SessionId>, tool_call_id: impl Into<ToolCallId>) -> Self {
2774        Self {
2775            session_id: session_id.into(),
2776            tool_call_id: tool_call_id.into(),
2777            meta: None,
2778        }
2779    }
2780
2781    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2782    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2783    /// do not recognize.
2784    ///
2785    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2786    #[must_use]
2787    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2788        self.meta = meta.into_option();
2789        self
2790    }
2791}
2792
2793crate::serde_util::default_on_null! {
2794    /// Response from cancelling a tool call.
2795    #[serde_as]
2796    #[skip_serializing_none]
2797    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2798    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2799    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TOOL_CALL_CANCEL_METHOD_NAME)))]
2800    #[serde(rename_all = "camelCase")]
2801    #[non_exhaustive]
2802    pub struct CancelToolCallResponse {
2803        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2804        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2805        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2806        ///
2807        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2808        #[serde_as(deserialize_as = "DefaultOnError")]
2809        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2810        #[serde(default)]
2811        #[serde(rename = "_meta")]
2812        pub meta: Option<Meta>,
2813    }
2814}
2815
2816impl CancelToolCallResponse {
2817    /// Builds [`CancelToolCallResponse`] with the required response fields set. Optional fields start unset or empty.
2818    #[must_use]
2819    pub fn new() -> Self {
2820        Self::default()
2821    }
2822
2823    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2824    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2825    /// do not recognize.
2826    ///
2827    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2828    #[must_use]
2829    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2830        self.meta = meta.into_option();
2831        self
2832    }
2833}
2834
2835// Cancel terminal
2836
2837/// Request parameters for cancelling one terminal.
2838///
2839/// Clients MUST NOT send it unless the terminal currently advertises `capabilities.cancel`.
2840///
2841/// The Agent responds once it has accepted the cancellation. The response does not mean
2842/// the work has stopped. The Agent confirms it with a `terminal_update` that sets
2843/// `exitStatus`. Cancelling stops the process but does not release the terminal, and does
2844/// not change the status of a tool call that references it.
2845///
2846/// The Agent responds with `-32602` if the terminal is unknown, has already exited, or is not
2847/// cancellable. Cancelling a terminal does not change the foreground state by itself.
2848///
2849/// See protocol docs: [Cancelling Terminals](https://agentclientprotocol.com/protocol/v2/tool-calls#cancelling-terminals)
2850#[serde_as]
2851#[skip_serializing_none]
2852#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2853#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2854#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TERMINAL_CANCEL_METHOD_NAME)))]
2855#[serde(rename_all = "camelCase")]
2856#[non_exhaustive]
2857pub struct CancelTerminalRequest {
2858    /// The ID of the session that owns the terminal.
2859    pub session_id: SessionId,
2860    /// The ID of the terminal to cancel.
2861    pub terminal_id: TerminalId,
2862    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2863    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2864    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2865    ///
2866    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2867    #[serde_as(deserialize_as = "DefaultOnError")]
2868    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2869    #[serde(default)]
2870    #[serde(rename = "_meta")]
2871    pub meta: Option<Meta>,
2872}
2873
2874impl CancelTerminalRequest {
2875    /// Builds [`CancelTerminalRequest`] with the required request fields set. Optional fields start unset or empty.
2876    #[must_use]
2877    pub fn new(session_id: impl Into<SessionId>, terminal_id: impl Into<TerminalId>) -> Self {
2878        Self {
2879            session_id: session_id.into(),
2880            terminal_id: terminal_id.into(),
2881            meta: None,
2882        }
2883    }
2884
2885    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2886    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2887    /// do not recognize.
2888    ///
2889    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2890    #[must_use]
2891    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2892        self.meta = meta.into_option();
2893        self
2894    }
2895}
2896
2897crate::serde_util::default_on_null! {
2898    /// Response from cancelling a terminal.
2899    #[serde_as]
2900    #[skip_serializing_none]
2901    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2902    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2903    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TERMINAL_CANCEL_METHOD_NAME)))]
2904    #[serde(rename_all = "camelCase")]
2905    #[non_exhaustive]
2906    pub struct CancelTerminalResponse {
2907        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2908        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2909        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2910        ///
2911        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2912        #[serde_as(deserialize_as = "DefaultOnError")]
2913        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2914        #[serde(default)]
2915        #[serde(rename = "_meta")]
2916        pub meta: Option<Meta>,
2917    }
2918}
2919
2920impl CancelTerminalResponse {
2921    /// Builds [`CancelTerminalResponse`] with the required response fields set. Optional fields start unset or empty.
2922    #[must_use]
2923    pub fn new() -> Self {
2924        Self::default()
2925    }
2926
2927    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
2928    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2929    /// do not recognize.
2930    ///
2931    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2932    #[must_use]
2933    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2934        self.meta = meta.into_option();
2935        self
2936    }
2937}
2938
2939// List sessions
2940
2941/// An opaque cursor used to paginate `session/list` results.
2942#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2943#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
2944#[serde(transparent)]
2945#[from(Arc<str>, String, &str, &mut str, Box<str>, Cow<'_, str>)]
2946#[non_exhaustive]
2947pub struct SessionListCursor(pub Arc<str>);
2948
2949impl SessionListCursor {
2950    /// Wraps a protocol string as a typed [`SessionListCursor`].
2951    #[must_use]
2952    pub fn new(cursor: impl Into<Self>) -> Self {
2953        cursor.into()
2954    }
2955}
2956
2957impl AsRef<str> for SessionListCursor {
2958    fn as_ref(&self) -> &str {
2959        &self.0
2960    }
2961}
2962
2963impl From<&String> for SessionListCursor {
2964    fn from(cursor: &String) -> Self {
2965        Self(cursor.as_str().into())
2966    }
2967}
2968
2969macro_rules! impl_session_list_cursor_option_conversion {
2970    ($source:ty) => {
2971        impl IntoOption<SessionListCursor> for $source {
2972            fn into_option(self) -> Option<SessionListCursor> {
2973                Some(self.into())
2974            }
2975        }
2976    };
2977}
2978
2979impl_session_list_cursor_option_conversion!(Arc<str>);
2980impl_session_list_cursor_option_conversion!(String);
2981impl_session_list_cursor_option_conversion!(&str);
2982impl_session_list_cursor_option_conversion!(&mut str);
2983impl_session_list_cursor_option_conversion!(&String);
2984impl_session_list_cursor_option_conversion!(Box<str>);
2985impl_session_list_cursor_option_conversion!(Cow<'_, str>);
2986
2987crate::serde_util::default_on_null! {
2988    /// Request parameters for listing existing sessions.
2989    #[serde_as]
2990    #[skip_serializing_none]
2991    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2992    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2993    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LIST_METHOD_NAME)))]
2994    #[serde(rename_all = "camelCase")]
2995    #[non_exhaustive]
2996    pub struct ListSessionsRequest {
2997        /// Filter sessions by working directory. Must be an absolute path.
2998        ///
2999        /// Only sessions whose `cwd` is this same directory match. Subdirectories and
3000        /// `additionalDirectories` don't. Agents MAY normalize paths when comparing.
3001        ///
3002        /// Omitted and `null` are equivalent and mean sessions are not filtered by working directory.
3003        /// Clients keep the same value when following `nextCursor`.
3004        #[serde(default)]
3005        pub cwd: Option<AbsolutePath>,
3006        /// Opaque cursor token from a previous response's nextCursor field for cursor-based pagination
3007        ///
3008        /// Omitted and `null` are equivalent and mean the first page is requested.
3009        #[serde(default)]
3010        pub cursor: Option<SessionListCursor>,
3011        /// **UNSTABLE**
3012        ///
3013        /// This capability is not part of the spec yet, and may be removed or changed at any point.
3014        ///
3015        /// Filter sessions by archive state.
3016        ///
3017        /// Optional. Omitted and `null` are equivalent and mean `exclude`. Only send this when
3018        /// the Agent advertises the `session.archive` capability. The filter combines with `cwd` and
3019        /// applies before pagination. Clients keep the same value when following `nextCursor`.
3020        #[cfg(feature = "unstable_session_archive")]
3021        #[serde(default)]
3022        pub archived: Option<SessionArchiveFilter>,
3023        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3024        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3025        /// Implementations MUST NOT assign meaning to keys they do not recognize.
3026        ///
3027        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3028        #[serde_as(deserialize_as = "DefaultOnError")]
3029        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3030        #[serde(default)]
3031        #[serde(rename = "_meta")]
3032        pub meta: Option<Meta>,
3033    }
3034}
3035
3036impl ListSessionsRequest {
3037    /// Builds [`ListSessionsRequest`] with the required request fields set. Optional fields start unset or empty.
3038    #[must_use]
3039    pub fn new() -> Self {
3040        Self::default()
3041    }
3042
3043    /// Filter sessions by working directory. Must be an absolute path.
3044    #[must_use]
3045    pub fn cwd(mut self, cwd: impl IntoOption<AbsolutePath>) -> Self {
3046        self.cwd = cwd.into_option();
3047        self
3048    }
3049
3050    /// Opaque cursor token from a previous response's nextCursor field for cursor-based pagination
3051    #[must_use]
3052    pub fn cursor(mut self, cursor: impl IntoOption<SessionListCursor>) -> Self {
3053        self.cursor = cursor.into_option();
3054        self
3055    }
3056
3057    /// **UNSTABLE**
3058    ///
3059    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3060    ///
3061    /// Filter sessions by archive state.
3062    #[cfg(feature = "unstable_session_archive")]
3063    #[must_use]
3064    pub fn archived(mut self, archived: impl IntoOption<SessionArchiveFilter>) -> Self {
3065        self.archived = archived.into_option();
3066        self
3067    }
3068
3069    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3070    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3071    /// do not recognize.
3072    ///
3073    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3074    #[must_use]
3075    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3076        self.meta = meta.into_option();
3077        self
3078    }
3079}
3080
3081/// Response from listing sessions.
3082#[serde_as]
3083#[skip_serializing_none]
3084#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3085#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3086#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LIST_METHOD_NAME)))]
3087#[serde(rename_all = "camelCase")]
3088#[non_exhaustive]
3089pub struct ListSessionsResponse {
3090    /// Array of session information objects.
3091    ///
3092    /// Agents SHOULD return the sessions with the most recent activity first.
3093    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
3094    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3095    pub sessions: Vec<SessionInfo>,
3096    /// Opaque cursor token. If present, pass this in the next request's cursor parameter
3097    /// to fetch the next page. Omitted and `null` are equivalent and mean there are no more
3098    /// results. An empty string is a valid cursor, not the end of results.
3099    #[serde(default)]
3100    pub next_cursor: Option<SessionListCursor>,
3101    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3102    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3103    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3104    ///
3105    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3106    #[serde_as(deserialize_as = "DefaultOnError")]
3107    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3108    #[serde(default)]
3109    #[serde(rename = "_meta")]
3110    pub meta: Option<Meta>,
3111}
3112
3113impl ListSessionsResponse {
3114    /// Builds [`ListSessionsResponse`] with the required response fields set. Optional fields start unset or empty.
3115    #[must_use]
3116    pub fn new(sessions: Vec<SessionInfo>) -> Self {
3117        Self {
3118            sessions,
3119            next_cursor: None,
3120            meta: None,
3121        }
3122    }
3123
3124    /// Sets or clears the optional `nextCursor` field.
3125    #[must_use]
3126    pub fn next_cursor(mut self, next_cursor: impl IntoOption<SessionListCursor>) -> Self {
3127        self.next_cursor = next_cursor.into_option();
3128        self
3129    }
3130
3131    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3132    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3133    /// do not recognize.
3134    ///
3135    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3136    #[must_use]
3137    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3138        self.meta = meta.into_option();
3139        self
3140    }
3141}
3142
3143// Delete session
3144
3145/// Request parameters for deleting an existing session from `session/list`.
3146///
3147/// Only available if the Agent supports the `session.delete` capability.
3148#[serde_as]
3149#[skip_serializing_none]
3150#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3151#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3152#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_DELETE_METHOD_NAME)))]
3153#[serde(rename_all = "camelCase")]
3154#[non_exhaustive]
3155pub struct DeleteSessionRequest {
3156    /// The ID of the session to delete.
3157    pub session_id: SessionId,
3158    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3159    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3160    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3161    ///
3162    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3163    #[serde_as(deserialize_as = "DefaultOnError")]
3164    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3165    #[serde(default)]
3166    #[serde(rename = "_meta")]
3167    pub meta: Option<Meta>,
3168}
3169
3170impl DeleteSessionRequest {
3171    /// Builds [`DeleteSessionRequest`] with the required request fields set. Optional fields start unset or empty.
3172    #[must_use]
3173    pub fn new(session_id: impl Into<SessionId>) -> Self {
3174        Self {
3175            session_id: session_id.into(),
3176            meta: None,
3177        }
3178    }
3179
3180    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3181    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3182    /// do not recognize.
3183    ///
3184    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3185    #[must_use]
3186    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3187        self.meta = meta.into_option();
3188        self
3189    }
3190}
3191
3192crate::serde_util::default_on_null! {
3193    /// Response from deleting a session.
3194    #[serde_as]
3195    #[skip_serializing_none]
3196    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3197    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3198    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_DELETE_METHOD_NAME)))]
3199    #[serde(rename_all = "camelCase")]
3200    #[non_exhaustive]
3201    pub struct DeleteSessionResponse {
3202        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3203        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3204        /// Implementations MUST NOT assign meaning to keys they do not recognize.
3205        ///
3206        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3207        #[serde_as(deserialize_as = "DefaultOnError")]
3208        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3209        #[serde(default)]
3210        #[serde(rename = "_meta")]
3211        pub meta: Option<Meta>,
3212    }
3213}
3214
3215impl DeleteSessionResponse {
3216    /// Builds [`DeleteSessionResponse`] with the required response fields set. Optional fields start unset or empty.
3217    #[must_use]
3218    pub fn new() -> Self {
3219        Self::default()
3220    }
3221
3222    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3223    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3224    /// do not recognize.
3225    ///
3226    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3227    #[must_use]
3228    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3229        self.meta = meta.into_option();
3230        self
3231    }
3232}
3233
3234// Archive session
3235
3236/// **UNSTABLE**
3237///
3238/// This capability is not part of the spec yet, and may be removed or changed at any point.
3239///
3240/// Request parameters for archiving a session.
3241///
3242/// Only available if the Agent supports the `session.archive` capability.
3243///
3244/// Archiving hides the session from default `session/list` results. It keeps the session ID
3245/// and saved history. If the session is active, the Agent MUST cancel any ongoing work and
3246/// free the session's resources as if `session/close` had been called, then archive it.
3247/// Archiving an archived session succeeds. A session that does not exist gets `-32002`.
3248///
3249#[cfg(feature = "unstable_session_archive")]
3250#[serde_as]
3251#[skip_serializing_none]
3252#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3253#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3254#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_ARCHIVE_METHOD_NAME)))]
3255#[serde(rename_all = "camelCase")]
3256#[non_exhaustive]
3257pub struct ArchiveSessionRequest {
3258    /// The ID of the session to archive.
3259    pub session_id: SessionId,
3260    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3261    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3262    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3263    ///
3264    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3265    #[serde_as(deserialize_as = "DefaultOnError")]
3266    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3267    #[serde(default)]
3268    #[serde(rename = "_meta")]
3269    pub meta: Option<Meta>,
3270}
3271
3272#[cfg(feature = "unstable_session_archive")]
3273impl ArchiveSessionRequest {
3274    /// Builds [`ArchiveSessionRequest`] with the required request fields set. Optional fields start unset or empty.
3275    #[must_use]
3276    pub fn new(session_id: impl Into<SessionId>) -> Self {
3277        Self {
3278            session_id: session_id.into(),
3279            meta: None,
3280        }
3281    }
3282
3283    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3284    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3285    /// do not recognize.
3286    ///
3287    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3288    #[must_use]
3289    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3290        self.meta = meta.into_option();
3291        self
3292    }
3293}
3294
3295#[cfg(feature = "unstable_session_archive")]
3296crate::serde_util::default_on_null! {
3297    /// **UNSTABLE**
3298    ///
3299    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3300    ///
3301    /// Response from archiving a session.
3302    #[serde_as]
3303    #[skip_serializing_none]
3304    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3305    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3306    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_ARCHIVE_METHOD_NAME)))]
3307    #[serde(rename_all = "camelCase")]
3308    #[non_exhaustive]
3309    pub struct ArchiveSessionResponse {
3310        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3311        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3312        /// Implementations MUST NOT assign meaning to keys they do not recognize.
3313        ///
3314        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3315        #[serde_as(deserialize_as = "DefaultOnError")]
3316        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3317        #[serde(default)]
3318        #[serde(rename = "_meta")]
3319        pub meta: Option<Meta>,
3320    }
3321}
3322
3323#[cfg(feature = "unstable_session_archive")]
3324impl ArchiveSessionResponse {
3325    /// Builds [`ArchiveSessionResponse`] with the required response fields set. Optional fields start unset or empty.
3326    #[must_use]
3327    pub fn new() -> Self {
3328        Self::default()
3329    }
3330
3331    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3332    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3333    /// do not recognize.
3334    ///
3335    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3336    #[must_use]
3337    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3338        self.meta = meta.into_option();
3339        self
3340    }
3341}
3342
3343/// **UNSTABLE**
3344///
3345/// This capability is not part of the spec yet, and may be removed or changed at any point.
3346///
3347/// Request parameters for unarchiving a session.
3348///
3349/// Only available if the Agent supports the `session.archive` capability.
3350///
3351/// Unarchiving returns the session to default `session/list` results with the same ID and
3352/// saved history. It never resumes the session. Clients that want to continue an
3353/// archived session SHOULD unarchive it before calling `session/resume`.
3354/// Unarchiving a session that is not archived succeeds. A session that does not exist
3355/// gets `-32002`.
3356///
3357#[cfg(feature = "unstable_session_archive")]
3358#[serde_as]
3359#[skip_serializing_none]
3360#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3361#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3362#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_UNARCHIVE_METHOD_NAME)))]
3363#[serde(rename_all = "camelCase")]
3364#[non_exhaustive]
3365pub struct UnarchiveSessionRequest {
3366    /// The ID of the session to unarchive.
3367    pub session_id: SessionId,
3368    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3369    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3370    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3371    ///
3372    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3373    #[serde_as(deserialize_as = "DefaultOnError")]
3374    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3375    #[serde(default)]
3376    #[serde(rename = "_meta")]
3377    pub meta: Option<Meta>,
3378}
3379
3380#[cfg(feature = "unstable_session_archive")]
3381impl UnarchiveSessionRequest {
3382    /// Builds [`UnarchiveSessionRequest`] with the required request fields set. Optional fields start unset or empty.
3383    #[must_use]
3384    pub fn new(session_id: impl Into<SessionId>) -> Self {
3385        Self {
3386            session_id: session_id.into(),
3387            meta: None,
3388        }
3389    }
3390
3391    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3392    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3393    /// do not recognize.
3394    ///
3395    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3396    #[must_use]
3397    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3398        self.meta = meta.into_option();
3399        self
3400    }
3401}
3402
3403#[cfg(feature = "unstable_session_archive")]
3404crate::serde_util::default_on_null! {
3405    /// **UNSTABLE**
3406    ///
3407    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3408    ///
3409    /// Response from unarchiving a session.
3410    #[serde_as]
3411    #[skip_serializing_none]
3412    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3413    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3414    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_UNARCHIVE_METHOD_NAME)))]
3415    #[serde(rename_all = "camelCase")]
3416    #[non_exhaustive]
3417    pub struct UnarchiveSessionResponse {
3418        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3419        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3420        /// Implementations MUST NOT assign meaning to keys they do not recognize.
3421        ///
3422        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3423        #[serde_as(deserialize_as = "DefaultOnError")]
3424        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3425        #[serde(default)]
3426        #[serde(rename = "_meta")]
3427        pub meta: Option<Meta>,
3428    }
3429}
3430
3431#[cfg(feature = "unstable_session_archive")]
3432impl UnarchiveSessionResponse {
3433    /// Builds [`UnarchiveSessionResponse`] with the required response fields set. Optional fields start unset or empty.
3434    #[must_use]
3435    pub fn new() -> Self {
3436        Self::default()
3437    }
3438
3439    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3440    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3441    /// do not recognize.
3442    ///
3443    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3444    #[must_use]
3445    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3446        self.meta = meta.into_option();
3447        self
3448    }
3449}
3450
3451/// **UNSTABLE**
3452///
3453/// This capability is not part of the spec yet, and may be removed or changed at any point.
3454///
3455/// Which sessions `session/list` returns based on their archive state.
3456///
3457/// Unknown values are preserved so they can be stored, proxied, or forwarded. An Agent MUST
3458/// return `-32602` for a value it does not support rather than treating it as `exclude`.
3459#[cfg(feature = "unstable_session_archive")]
3460#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3461#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
3462#[serde(rename_all = "snake_case")]
3463#[non_exhaustive]
3464pub enum SessionArchiveFilter {
3465    /// Only sessions that are not archived. This is the default.
3466    #[default]
3467    Exclude,
3468    /// Both archived sessions and sessions that are not archived.
3469    Include,
3470    /// Only archived sessions.
3471    Only,
3472    /// Custom or future archive filter.
3473    ///
3474    /// Values beginning with `_` are reserved for implementation-specific
3475    /// extensions. Unknown values that do not begin with `_` are reserved for
3476    /// future ACP variants.
3477    #[serde(untagged)]
3478    Other(String),
3479}
3480
3481/// Information about a session returned by session/list
3482#[serde_as]
3483#[skip_serializing_none]
3484#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3485#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3486#[serde(rename_all = "camelCase")]
3487#[non_exhaustive]
3488pub struct SessionInfo {
3489    /// Unique identifier for the session
3490    pub session_id: SessionId,
3491    /// The working directory for this session. Must be an absolute path.
3492    pub cwd: AbsolutePath,
3493    /// Additional workspace roots reported for this session. Each path MUST be absolute.
3494    ///
3495    /// When present, this is the complete ordered additional-root list reported
3496    /// by the Agent. Omitted and empty values are equivalent: the response
3497    /// reports no additional roots.
3498    #[serde_as(deserialize_as = "DefaultOnNull")]
3499    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
3500    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3501    pub additional_directories: Vec<AbsolutePath>,
3502
3503    /// Human-readable title for the session
3504    ///
3505    /// Omitted and `null` are equivalent and mean no title is provided.
3506    #[serde_as(deserialize_as = "DefaultOnError")]
3507    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3508    #[serde(default)]
3509    pub title: Option<String>,
3510    /// RFC 3339 timestamp of last activity.
3511    ///
3512    /// Omitted and `null` are equivalent and mean the last activity time is not reported.
3513    #[serde_as(deserialize_as = "DefaultOnError")]
3514    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "format" = "date-time")))]
3515    #[serde(default)]
3516    pub updated_at: Option<String>,
3517    /// **UNSTABLE**
3518    ///
3519    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3520    ///
3521    /// Whether the session is archived.
3522    ///
3523    /// Optional. Omitted and `null` are equivalent and mean the archive state is not reported.
3524    /// Agents that advertise the `session.archive` capability MUST include it on every listed session.
3525    #[cfg(feature = "unstable_session_archive")]
3526    #[serde_as(deserialize_as = "DefaultOnError")]
3527    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3528    #[serde(default)]
3529    pub archived: Option<bool>,
3530    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3531    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3532    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3533    ///
3534    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3535    #[serde_as(deserialize_as = "DefaultOnError")]
3536    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3537    #[serde(default)]
3538    #[serde(rename = "_meta")]
3539    pub meta: Option<Meta>,
3540}
3541
3542impl SessionInfo {
3543    /// Builds [`SessionInfo`] with the required fields set. Optional fields start unset or empty.
3544    #[must_use]
3545    pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
3546        Self {
3547            session_id: session_id.into(),
3548            cwd: cwd.into(),
3549            additional_directories: vec![],
3550            title: None,
3551            updated_at: None,
3552            #[cfg(feature = "unstable_session_archive")]
3553            archived: None,
3554            meta: None,
3555        }
3556    }
3557
3558    /// Additional workspace roots reported for this session. Each path MUST be absolute.
3559    #[must_use]
3560    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
3561    where
3562        I: IntoIterator<Item = P>,
3563        P: Into<AbsolutePath>,
3564    {
3565        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
3566        self
3567    }
3568
3569    /// Human-readable title for the session
3570    #[must_use]
3571    pub fn title(mut self, title: impl IntoOption<String>) -> Self {
3572        self.title = title.into_option();
3573        self
3574    }
3575
3576    /// RFC 3339 timestamp of last activity.
3577    #[must_use]
3578    pub fn updated_at(mut self, updated_at: impl IntoOption<String>) -> Self {
3579        self.updated_at = updated_at.into_option();
3580        self
3581    }
3582
3583    /// **UNSTABLE**
3584    ///
3585    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3586    ///
3587    /// Whether the session is archived.
3588    #[cfg(feature = "unstable_session_archive")]
3589    #[must_use]
3590    pub fn archived(mut self, archived: impl IntoOption<bool>) -> Self {
3591        self.archived = archived.into_option();
3592        self
3593    }
3594
3595    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3596    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3597    /// do not recognize.
3598    ///
3599    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3600    #[must_use]
3601    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3602        self.meta = meta.into_option();
3603        self
3604    }
3605}
3606
3607// Set session title
3608
3609/// **UNSTABLE**
3610///
3611/// This capability is not part of the spec yet, and may be removed or changed at any point.
3612///
3613/// Request parameters for setting the title of a session.
3614///
3615/// Only available if the Agent supports the `session.title` capability.
3616///
3617/// The session does not need to be active on the connection. Any session the Agent would
3618/// return from `session/list` can be retitled. A session that does not exist gets `-32002`.
3619///
3620/// The Agent responds only after it has stored the title. After a successful response, the
3621/// Agent SHOULD NOT replace the title with one it generates automatically.
3622#[cfg(feature = "unstable_session_set_title")]
3623#[serde_as]
3624#[skip_serializing_none]
3625#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3626#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3627#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_TITLE_METHOD_NAME)))]
3628#[serde(rename_all = "camelCase")]
3629#[non_exhaustive]
3630pub struct SetSessionTitleRequest {
3631    /// The ID of the session to retitle.
3632    pub session_id: SessionId,
3633    /// The new title for the session.
3634    ///
3635    /// Required and non-null. Omission and explicit `null` are both invalid. The Agent MAY
3636    /// normalize the title before storing it, for example by trimming whitespace or
3637    /// truncating it. The Agent rejects a title that fails its validation, including one
3638    /// that is empty after normalization, with `-32602`.
3639    pub title: String,
3640    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3641    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3642    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3643    ///
3644    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3645    #[serde_as(deserialize_as = "DefaultOnError")]
3646    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3647    #[serde(default)]
3648    #[serde(rename = "_meta")]
3649    pub meta: Option<Meta>,
3650}
3651
3652#[cfg(feature = "unstable_session_set_title")]
3653impl SetSessionTitleRequest {
3654    /// Builds [`SetSessionTitleRequest`] with the required request fields set. Optional fields start unset or empty.
3655    #[must_use]
3656    pub fn new(session_id: impl Into<SessionId>, title: impl Into<String>) -> Self {
3657        Self {
3658            session_id: session_id.into(),
3659            title: title.into(),
3660            meta: None,
3661        }
3662    }
3663
3664    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3665    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3666    /// do not recognize.
3667    ///
3668    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3669    #[must_use]
3670    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3671        self.meta = meta.into_option();
3672        self
3673    }
3674}
3675
3676/// **UNSTABLE**
3677///
3678/// This capability is not part of the spec yet, and may be removed or changed at any point.
3679///
3680/// Response from setting the title of a session.
3681#[cfg(feature = "unstable_session_set_title")]
3682#[serde_as]
3683#[skip_serializing_none]
3684#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3685#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3686#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_TITLE_METHOD_NAME)))]
3687#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "sessionInfo", "field": "title", "value": "title"}]})))]
3688#[serde(rename_all = "camelCase")]
3689#[non_exhaustive]
3690pub struct SetSessionTitleResponse {
3691    /// The title the Agent stored.
3692    ///
3693    /// This differs from the requested title if the Agent normalized it. Clients SHOULD
3694    /// display this value rather than the one they sent.
3695    pub title: String,
3696    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3697    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3698    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3699    ///
3700    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3701    #[serde_as(deserialize_as = "DefaultOnError")]
3702    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3703    #[serde(default)]
3704    #[serde(rename = "_meta")]
3705    pub meta: Option<Meta>,
3706}
3707
3708#[cfg(feature = "unstable_session_set_title")]
3709impl SetSessionTitleResponse {
3710    /// Builds [`SetSessionTitleResponse`] with the required response fields set. Optional fields start unset or empty.
3711    #[must_use]
3712    pub fn new(title: impl Into<String>) -> Self {
3713        Self {
3714            title: title.into(),
3715            meta: None,
3716        }
3717    }
3718
3719    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3720    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3721    /// do not recognize.
3722    ///
3723    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3724    #[must_use]
3725    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3726        self.meta = meta.into_option();
3727        self
3728    }
3729}
3730
3731// Session config options
3732
3733/// Unique identifier for a session configuration option.
3734#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3735#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3736#[serde(transparent)]
3737#[from(forward)]
3738#[non_exhaustive]
3739pub struct SessionConfigId(pub Arc<str>);
3740
3741impl SessionConfigId {
3742    /// Wraps a protocol string as a typed [`SessionConfigId`].
3743    #[must_use]
3744    pub fn new(id: impl Into<Self>) -> Self {
3745        id.into()
3746    }
3747}
3748
3749/// Unique identifier for a session configuration option value.
3750#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3751#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3752#[serde(transparent)]
3753#[from(forward)]
3754#[non_exhaustive]
3755pub struct SessionConfigValueId(pub Arc<str>);
3756
3757impl SessionConfigValueId {
3758    /// Wraps a protocol string as a typed [`SessionConfigValueId`].
3759    #[must_use]
3760    pub fn new(id: impl Into<Self>) -> Self {
3761        id.into()
3762    }
3763}
3764
3765/// Unique identifier for a session configuration option value group.
3766#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3767#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3768#[serde(transparent)]
3769#[from(forward)]
3770#[non_exhaustive]
3771pub struct SessionConfigGroupId(pub Arc<str>);
3772
3773impl SessionConfigGroupId {
3774    /// Wraps a protocol string as a typed [`SessionConfigGroupId`].
3775    #[must_use]
3776    pub fn new(id: impl Into<Self>) -> Self {
3777        id.into()
3778    }
3779}
3780
3781/// A possible value for a session configuration option.
3782#[serde_as]
3783#[skip_serializing_none]
3784#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3785#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3786#[serde(rename_all = "camelCase")]
3787#[non_exhaustive]
3788pub struct SessionConfigSelectOption {
3789    /// Unique identifier for this option value.
3790    pub value: SessionConfigValueId,
3791    /// Human-readable label for this option value.
3792    pub name: String,
3793    /// Optional description for this option value.
3794    ///
3795    /// Omitted and `null` are equivalent and mean no description is provided.
3796    #[serde_as(deserialize_as = "DefaultOnError")]
3797    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3798    #[serde(default)]
3799    pub description: Option<String>,
3800    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3801    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3802    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3803    ///
3804    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3805    #[serde_as(deserialize_as = "DefaultOnError")]
3806    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3807    #[serde(default)]
3808    #[serde(rename = "_meta")]
3809    pub meta: Option<Meta>,
3810}
3811
3812impl SessionConfigSelectOption {
3813    /// Builds [`SessionConfigSelectOption`] with the required fields set. Optional fields start unset or empty.
3814    #[must_use]
3815    pub fn new(value: impl Into<SessionConfigValueId>, name: impl Into<String>) -> Self {
3816        Self {
3817            value: value.into(),
3818            name: name.into(),
3819            description: None,
3820            meta: None,
3821        }
3822    }
3823
3824    /// Sets or clears the optional `description` field.
3825    #[must_use]
3826    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
3827        self.description = description.into_option();
3828        self
3829    }
3830
3831    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3832    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3833    /// do not recognize.
3834    ///
3835    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3836    #[must_use]
3837    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3838        self.meta = meta.into_option();
3839        self
3840    }
3841}
3842
3843/// A group of possible values for a session configuration option.
3844#[serde_as]
3845#[skip_serializing_none]
3846#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3847#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3848#[serde(rename_all = "camelCase")]
3849#[non_exhaustive]
3850pub struct SessionConfigSelectGroup {
3851    /// Identifier for this group. MUST be unique within the option.
3852    pub group_id: SessionConfigGroupId,
3853    /// Human-readable label for this group.
3854    pub name: String,
3855    /// The set of option values in this group. MUST contain at least one value.
3856    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
3857    #[cfg_attr(feature = "schemars", schemars(length(min = 1), extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3858    pub options: Vec<SessionConfigSelectOption>,
3859    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3860    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3861    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3862    ///
3863    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3864    #[serde_as(deserialize_as = "DefaultOnError")]
3865    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3866    #[serde(default)]
3867    #[serde(rename = "_meta")]
3868    pub meta: Option<Meta>,
3869}
3870
3871impl SessionConfigSelectGroup {
3872    /// Builds [`SessionConfigSelectGroup`] with the required fields set. Optional fields start unset or empty.
3873    #[must_use]
3874    pub fn new(
3875        group_id: impl Into<SessionConfigGroupId>,
3876        name: impl Into<String>,
3877        options: Vec<SessionConfigSelectOption>,
3878    ) -> Self {
3879        Self {
3880            group_id: group_id.into(),
3881            name: name.into(),
3882            options,
3883            meta: None,
3884        }
3885    }
3886
3887    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
3888    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3889    /// do not recognize.
3890    ///
3891    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3892    #[must_use]
3893    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3894        self.meta = meta.into_option();
3895        self
3896    }
3897}
3898
3899/// Possible values for a session configuration option.
3900#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3901#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3902#[serde(untagged)]
3903#[non_exhaustive]
3904pub enum SessionConfigSelectOptions {
3905    /// A flat list of options with no grouping.
3906    Ungrouped(
3907        #[cfg_attr(feature = "schemars", schemars(length(min = 1)))] Vec<SessionConfigSelectOption>,
3908    ),
3909    /// A list of options grouped under headers.
3910    Grouped(
3911        #[cfg_attr(feature = "schemars", schemars(length(min = 1)))] Vec<SessionConfigSelectGroup>,
3912    ),
3913}
3914
3915impl From<Vec<SessionConfigSelectOption>> for SessionConfigSelectOptions {
3916    fn from(options: Vec<SessionConfigSelectOption>) -> Self {
3917        SessionConfigSelectOptions::Ungrouped(options)
3918    }
3919}
3920
3921impl From<Vec<SessionConfigSelectGroup>> for SessionConfigSelectOptions {
3922    fn from(groups: Vec<SessionConfigSelectGroup>) -> Self {
3923        SessionConfigSelectOptions::Grouped(groups)
3924    }
3925}
3926
3927/// A single-value selector (dropdown) session configuration option payload.
3928#[skip_serializing_none]
3929#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3930#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3931#[serde(rename_all = "camelCase")]
3932#[non_exhaustive]
3933pub struct SessionConfigSelect {
3934    /// The currently selected value. MUST be one of the `value`s in `options`.
3935    pub current_value: SessionConfigValueId,
3936    /// The set of selectable options. MUST contain at least one value, and each `value` MUST be
3937    /// unique within the option, including across groups.
3938    pub options: SessionConfigSelectOptions,
3939}
3940
3941impl SessionConfigSelect {
3942    /// Builds [`SessionConfigSelect`] with the required fields set. Optional fields start unset or empty.
3943    #[must_use]
3944    pub fn new(
3945        current_value: impl Into<SessionConfigValueId>,
3946        options: impl Into<SessionConfigSelectOptions>,
3947    ) -> Self {
3948        Self {
3949            current_value: current_value.into(),
3950            options: options.into(),
3951        }
3952    }
3953}
3954
3955/// A boolean on/off toggle session configuration option payload.
3956#[skip_serializing_none]
3957#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3958#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3959#[serde(rename_all = "camelCase")]
3960#[non_exhaustive]
3961pub struct SessionConfigBoolean {
3962    /// The current value of the boolean option.
3963    pub current_value: bool,
3964}
3965
3966impl SessionConfigBoolean {
3967    /// Builds [`SessionConfigBoolean`] with the required fields set. Optional fields start unset or empty.
3968    #[must_use]
3969    pub fn new(current_value: bool) -> Self {
3970        Self { current_value }
3971    }
3972}
3973
3974/// Semantic category for a session configuration option.
3975///
3976/// This is intended to help Clients distinguish broadly common selectors (e.g. model selector vs
3977/// session mode selector vs thought/reasoning level) for UX purposes (keyboard shortcuts, icons,
3978/// placement). It MUST NOT be required for correctness. Clients MUST handle missing or unknown
3979/// categories gracefully.
3980///
3981/// Category names beginning with `_` are free for custom use, like other ACP extension methods.
3982/// Category names that do not begin with `_` are reserved for the ACP spec.
3983#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3984#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3985#[serde(rename_all = "snake_case")]
3986#[non_exhaustive]
3987pub enum SessionConfigOptionCategory {
3988    /// Session mode selector.
3989    Mode,
3990    /// Model selector.
3991    Model,
3992    /// Model-related configuration parameter.
3993    ModelConfig,
3994    /// **UNSTABLE**
3995    ///
3996    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3997    ///
3998    /// Response speed selector, such as a fast mode toggle.
3999    #[cfg(feature = "unstable_speed_config_category")]
4000    Speed,
4001    /// Thought/reasoning level selector.
4002    ThoughtLevel,
4003    /// Custom or future category.
4004    ///
4005    /// Values beginning with `_` are reserved for implementation-specific
4006    /// extensions. Unknown values that do not begin with `_` are reserved for
4007    /// future ACP variants.
4008    #[serde(untagged)]
4009    Other(String),
4010}
4011
4012/// Type-specific session configuration option payload.
4013#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4014#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4015#[serde(tag = "type", rename_all = "snake_case")]
4016#[non_exhaustive]
4017pub enum SessionConfigKind {
4018    /// Single-value selector (dropdown).
4019    Select(SessionConfigSelect),
4020    /// Boolean on/off toggle.
4021    Boolean(SessionConfigBoolean),
4022    /// Custom or future session configuration option payload.
4023    ///
4024    /// Values beginning with `_` are reserved for implementation-specific
4025    /// extensions. Unknown values that do not begin with `_` are reserved for
4026    /// future ACP variants.
4027    ///
4028    /// Clients that do not understand this option type SHOULD preserve the raw
4029    /// payload when storing, replaying, proxying, or forwarding configuration
4030    /// data, and otherwise ignore the option. The Agent keeps using its `currentValue`.
4031    #[serde(untagged)]
4032    Other(OtherSessionConfigKind),
4033}
4034
4035/// Custom or future session configuration option payload.
4036#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4037#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4038#[cfg_attr(feature = "schemars", schemars(inline))]
4039#[cfg_attr(feature = "schemars", schemars(transform = other_session_config_kind_schema))]
4040#[serde(rename_all = "camelCase")]
4041#[non_exhaustive]
4042pub struct OtherSessionConfigKind {
4043    /// Custom or future session configuration option type.
4044    ///
4045    /// Values beginning with `_` are reserved for implementation-specific
4046    /// extensions. Unknown values that do not begin with `_` are reserved for
4047    /// future ACP variants.
4048    #[serde(rename = "type")]
4049    pub type_: String,
4050    /// Additional fields from the unknown session configuration option payload.
4051    #[serde(flatten)]
4052    pub fields: IndexMap<String, serde_json::Value>,
4053}
4054
4055impl OtherSessionConfigKind {
4056    /// Builds [`OtherSessionConfigKind`] from an unknown discriminator and preserves the remaining extension fields.
4057    #[must_use]
4058    pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
4059        fields.shift_remove("type");
4060        fields.shift_remove("_meta");
4061        Self {
4062            type_: type_.into(),
4063            fields,
4064        }
4065    }
4066}
4067
4068impl<'de> Deserialize<'de> for OtherSessionConfigKind {
4069    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4070    where
4071        D: serde::Deserializer<'de>,
4072    {
4073        let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4074        let type_ = fields
4075            .shift_remove("type")
4076            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4077        let serde_json::Value::String(type_) = type_ else {
4078            return Err(serde::de::Error::custom("`type` must be a string"));
4079        };
4080
4081        if is_known_session_config_kind_type(&type_) {
4082            return Err(serde::de::Error::custom(format!(
4083                "known session configuration option `{type_}` did not match its schema"
4084            )));
4085        }
4086
4087        Ok(Self { type_, fields })
4088    }
4089}
4090
4091fn is_known_session_config_kind_type(type_: &str) -> bool {
4092    matches!(type_, "select" | "boolean")
4093}
4094
4095#[cfg(feature = "schemars")]
4096fn other_session_config_kind_schema(schema: &mut Schema) {
4097    super::schema_util::reject_known_string_discriminators(schema, "type", &["select", "boolean"]);
4098}
4099
4100/// A session configuration option selector and its current state.
4101#[serde_as]
4102#[skip_serializing_none]
4103#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4104#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4105#[serde(rename_all = "camelCase")]
4106#[non_exhaustive]
4107pub struct SessionConfigOption {
4108    /// Identifier for the configuration option. MUST be unique within `configOptions`.
4109    pub config_id: SessionConfigId,
4110    /// Human-readable label for the option.
4111    pub name: String,
4112    /// Optional description for the Client to display to the user.
4113    ///
4114    /// Omitted and `null` are equivalent and mean no description is provided.
4115    #[serde_as(deserialize_as = "DefaultOnError")]
4116    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4117    #[serde(default)]
4118    pub description: Option<String>,
4119    /// Optional semantic category for this option (UX only).
4120    ///
4121    /// Omitted and `null` are equivalent and mean no category is provided.
4122    #[serde_as(deserialize_as = "DefaultOnError")]
4123    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4124    #[serde(default)]
4125    pub category: Option<SessionConfigOptionCategory>,
4126    /// Type-specific fields for this configuration option.
4127    #[serde(flatten)]
4128    pub kind: SessionConfigKind,
4129    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4130    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4131    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4132    ///
4133    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4134    #[serde_as(deserialize_as = "DefaultOnError")]
4135    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4136    #[serde(default)]
4137    #[serde(rename = "_meta")]
4138    pub meta: Option<Meta>,
4139}
4140
4141impl SessionConfigOption {
4142    /// Builds [`SessionConfigOption`] with the required fields set. Optional fields start unset or empty.
4143    #[must_use]
4144    pub fn new(
4145        config_id: impl Into<SessionConfigId>,
4146        name: impl Into<String>,
4147        kind: SessionConfigKind,
4148    ) -> Self {
4149        Self {
4150            config_id: config_id.into(),
4151            name: name.into(),
4152            description: None,
4153            category: None,
4154            kind,
4155            meta: None,
4156        }
4157    }
4158
4159    /// Builds a select-style session configuration option with its current value and choices.
4160    #[must_use]
4161    pub fn select(
4162        config_id: impl Into<SessionConfigId>,
4163        name: impl Into<String>,
4164        current_value: impl Into<SessionConfigValueId>,
4165        options: impl Into<SessionConfigSelectOptions>,
4166    ) -> Self {
4167        Self::new(
4168            config_id,
4169            name,
4170            SessionConfigKind::Select(SessionConfigSelect::new(current_value, options)),
4171        )
4172    }
4173
4174    /// Builds a boolean-style session configuration option with its current value.
4175    #[must_use]
4176    pub fn boolean(
4177        config_id: impl Into<SessionConfigId>,
4178        name: impl Into<String>,
4179        current_value: bool,
4180    ) -> Self {
4181        Self::new(
4182            config_id,
4183            name,
4184            SessionConfigKind::Boolean(SessionConfigBoolean::new(current_value)),
4185        )
4186    }
4187
4188    /// Sets or clears the optional `description` field.
4189    #[must_use]
4190    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
4191        self.description = description.into_option();
4192        self
4193    }
4194
4195    /// Sets or clears the optional `category` field.
4196    #[must_use]
4197    pub fn category(mut self, category: impl IntoOption<SessionConfigOptionCategory>) -> Self {
4198        self.category = category.into_option();
4199        self
4200    }
4201
4202    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4203    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4204    /// do not recognize.
4205    ///
4206    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4207    #[must_use]
4208    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4209        self.meta = meta.into_option();
4210        self
4211    }
4212}
4213
4214/// The value to set for a session configuration option.
4215///
4216/// The `type` field acts as the discriminator in the serialized JSON form.
4217///
4218/// The `type` discriminator describes the *shape* of the value, not the option
4219/// kind. For example every option kind that picks from a list of ids
4220/// (`select`, `radio`, …) would use [`Id`](Self::Id), while a future freeform
4221/// text option would get its own variant.
4222#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4223#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4224#[serde(tag = "type", rename_all = "snake_case")]
4225#[non_exhaustive]
4226pub enum SessionConfigOptionValue {
4227    /// A `SessionConfigValueId` string value (`type: "id"`).
4228    Id {
4229        /// The value ID.
4230        value: SessionConfigValueId,
4231    },
4232    /// A boolean value (`type: "boolean"`).
4233    Boolean {
4234        /// The boolean value.
4235        value: bool,
4236    },
4237    /// Custom or future session configuration option value payload.
4238    ///
4239    /// Values beginning with `_` are reserved for implementation-specific
4240    /// extensions. Unknown values that do not begin with `_` are reserved for
4241    /// future ACP variants.
4242    ///
4243    /// Agents MUST reject a `session/set_config_option` request with a value type
4244    /// they do not support with `-32602`.
4245    #[serde(untagged)]
4246    Other(OtherSessionConfigOptionValue),
4247}
4248
4249/// Custom or future session configuration option value payload.
4250#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4251#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4252#[cfg_attr(feature = "schemars", schemars(inline))]
4253#[cfg_attr(feature = "schemars", schemars(transform = other_session_config_option_value_schema))]
4254#[serde(rename_all = "camelCase")]
4255#[non_exhaustive]
4256pub struct OtherSessionConfigOptionValue {
4257    /// Custom or future session configuration option value type.
4258    ///
4259    /// Values beginning with `_` are reserved for implementation-specific
4260    /// extensions. Unknown values that do not begin with `_` are reserved for
4261    /// future ACP variants.
4262    #[serde(rename = "type")]
4263    pub type_: String,
4264    /// Raw value payload for the custom or future value type.
4265    pub value: serde_json::Value,
4266    /// Additional fields from the unknown session configuration option value payload.
4267    #[serde(flatten)]
4268    pub fields: IndexMap<String, serde_json::Value>,
4269}
4270
4271impl OtherSessionConfigOptionValue {
4272    /// Builds [`OtherSessionConfigOptionValue`] from an unknown discriminator and preserves the remaining extension fields.
4273    #[must_use]
4274    pub fn new(
4275        type_: impl Into<String>,
4276        value: serde_json::Value,
4277        mut fields: IndexMap<String, serde_json::Value>,
4278    ) -> Self {
4279        fields.shift_remove("type");
4280        fields.shift_remove("value");
4281        fields.shift_remove("_meta");
4282        Self {
4283            type_: type_.into(),
4284            value,
4285            fields,
4286        }
4287    }
4288}
4289
4290impl<'de> Deserialize<'de> for OtherSessionConfigOptionValue {
4291    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4292    where
4293        D: serde::Deserializer<'de>,
4294    {
4295        let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4296        let type_ = fields
4297            .shift_remove("type")
4298            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4299        let serde_json::Value::String(type_) = type_ else {
4300            return Err(serde::de::Error::custom("`type` must be a string"));
4301        };
4302
4303        if is_known_session_config_option_value_type(&type_) {
4304            return Err(serde::de::Error::custom(format!(
4305                "known session configuration option value `{type_}` did not match its schema"
4306            )));
4307        }
4308
4309        let value = fields
4310            .shift_remove("value")
4311            .ok_or_else(|| serde::de::Error::missing_field("value"))?;
4312
4313        Ok(Self {
4314            type_,
4315            value,
4316            fields,
4317        })
4318    }
4319}
4320
4321impl<'de> Deserialize<'de> for SessionConfigOptionValue {
4322    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4323    where
4324        D: serde::Deserializer<'de>,
4325    {
4326        let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4327        let type_ = fields.shift_remove("type");
4328        let value = fields
4329            .shift_remove("value")
4330            .ok_or_else(|| serde::de::Error::missing_field("value"))?;
4331
4332        let type_ = type_.ok_or_else(|| serde::de::Error::missing_field("type"))?;
4333
4334        let serde_json::Value::String(type_) = type_ else {
4335            return Err(serde::de::Error::custom("`type` must be a string"));
4336        };
4337
4338        match type_.as_str() {
4339            "id" => {
4340                let value = serde_json::from_value(value).map_err(|error| {
4341                    serde::de::Error::custom(format!(
4342                        "`value` must be a string for `type: id`: {error}"
4343                    ))
4344                })?;
4345                Ok(Self::Id { value })
4346            }
4347            "boolean" => {
4348                let value = serde_json::from_value(value).map_err(|error| {
4349                    serde::de::Error::custom(format!(
4350                        "`value` must be a boolean for `type: boolean`: {error}"
4351                    ))
4352                })?;
4353                Ok(Self::Boolean { value })
4354            }
4355            _ => Ok(Self::Other(OtherSessionConfigOptionValue {
4356                type_,
4357                value,
4358                fields,
4359            })),
4360        }
4361    }
4362}
4363
4364fn is_known_session_config_option_value_type(type_: &str) -> bool {
4365    matches!(type_, "id" | "boolean")
4366}
4367
4368#[cfg(feature = "schemars")]
4369fn other_session_config_option_value_schema(schema: &mut Schema) {
4370    super::schema_util::reject_known_string_discriminators(schema, "type", &["id", "boolean"]);
4371}
4372
4373impl SessionConfigOptionValue {
4374    /// Create an id option value (used by `select` and other id-based option types).
4375    #[must_use]
4376    pub fn id(id: impl Into<SessionConfigValueId>) -> Self {
4377        Self::Id { value: id.into() }
4378    }
4379
4380    /// Create a boolean option value.
4381    #[must_use]
4382    pub fn boolean(val: bool) -> Self {
4383        Self::Boolean { value: val }
4384    }
4385
4386    /// Return the inner [`SessionConfigValueId`] if this is a
4387    /// [`Id`](Self::Id) value.
4388    #[must_use]
4389    pub fn as_id(&self) -> Option<&SessionConfigValueId> {
4390        match self {
4391            Self::Id { value } => Some(value),
4392            _ => None,
4393        }
4394    }
4395
4396    /// Return the inner [`bool`] if this is a [`Boolean`](Self::Boolean) value.
4397    #[must_use]
4398    pub fn as_bool(&self) -> Option<bool> {
4399        match self {
4400            Self::Boolean { value } => Some(*value),
4401            _ => None,
4402        }
4403    }
4404}
4405
4406impl From<SessionConfigValueId> for SessionConfigOptionValue {
4407    fn from(value: SessionConfigValueId) -> Self {
4408        Self::Id { value }
4409    }
4410}
4411
4412impl From<bool> for SessionConfigOptionValue {
4413    fn from(value: bool) -> Self {
4414        Self::Boolean { value }
4415    }
4416}
4417
4418impl From<&str> for SessionConfigOptionValue {
4419    fn from(value: &str) -> Self {
4420        Self::Id {
4421            value: SessionConfigValueId::new(value),
4422        }
4423    }
4424}
4425
4426/// Request parameters for setting a session configuration option.
4427///
4428/// Agents MUST support this method for any session the Client created or resumed
4429/// where they advertise config options. For a child session, the child's
4430/// capabilities decide whether the Client can send it, and none defined today
4431/// permits it.
4432/// Agents MUST reject an unknown `configId` or invalid value with `-32602` and leave the
4433/// configuration unchanged.
4434///
4435/// See protocol docs: [Session Config Options](https://agentclientprotocol.com/protocol/v2/session-config-options#setting-a-config-option)
4436#[serde_as]
4437#[skip_serializing_none]
4438#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4439#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4440#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_CONFIG_OPTION_METHOD_NAME)))]
4441#[serde(rename_all = "camelCase")]
4442#[non_exhaustive]
4443pub struct SetSessionConfigOptionRequest {
4444    /// The ID of the session to set the configuration option for.
4445    pub session_id: SessionId,
4446    /// The ID of the configuration option to set.
4447    pub config_id: SessionConfigId,
4448    /// The value to set, including a `type` discriminator and the raw `value`.
4449    ///
4450    /// Payloads MUST send `type: "id"` for id-based options.
4451    #[serde(flatten)]
4452    pub value: SessionConfigOptionValue,
4453    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4454    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4455    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4456    ///
4457    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4458    #[serde_as(deserialize_as = "DefaultOnError")]
4459    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4460    #[serde(default)]
4461    #[serde(rename = "_meta")]
4462    pub meta: Option<Meta>,
4463}
4464
4465impl SetSessionConfigOptionRequest {
4466    /// Builds [`SetSessionConfigOptionRequest`] with the required request fields set. Optional fields start unset or empty.
4467    #[must_use]
4468    pub fn new(
4469        session_id: impl Into<SessionId>,
4470        config_id: impl Into<SessionConfigId>,
4471        value: impl Into<SessionConfigOptionValue>,
4472    ) -> Self {
4473        Self {
4474            session_id: session_id.into(),
4475            config_id: config_id.into(),
4476            value: value.into(),
4477            meta: None,
4478        }
4479    }
4480
4481    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4482    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4483    /// do not recognize.
4484    ///
4485    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4486    #[must_use]
4487    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4488        self.meta = meta.into_option();
4489        self
4490    }
4491}
4492
4493/// Response to `session/set_config_option` method.
4494#[serde_as]
4495#[skip_serializing_none]
4496#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4497#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4498#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_CONFIG_OPTION_METHOD_NAME)))]
4499#[cfg_attr(feature = "schemars", schemars(extend("x-state" = {"session": [{"action": "replace", "target": "configOptions", "value": "configOptions"}]})))]
4500#[serde(rename_all = "camelCase")]
4501#[non_exhaustive]
4502pub struct SetSessionConfigOptionResponse {
4503    /// The full set of configuration options and their current values.
4504    #[serde_as(deserialize_as = "VecSkipError<_>")]
4505    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
4506    pub config_options: Vec<SessionConfigOption>,
4507    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4508    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4509    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4510    ///
4511    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4512    #[serde_as(deserialize_as = "DefaultOnError")]
4513    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4514    #[serde(default)]
4515    #[serde(rename = "_meta")]
4516    pub meta: Option<Meta>,
4517}
4518
4519impl SetSessionConfigOptionResponse {
4520    /// Builds [`SetSessionConfigOptionResponse`] with the required response fields set. Optional fields start unset or empty.
4521    #[must_use]
4522    pub fn new(config_options: Vec<SessionConfigOption>) -> Self {
4523        Self {
4524            config_options,
4525            meta: None,
4526        }
4527    }
4528
4529    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4530    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4531    /// do not recognize.
4532    ///
4533    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4534    #[must_use]
4535    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4536        self.meta = meta.into_option();
4537        self
4538    }
4539}
4540
4541// MCP
4542
4543/// Configuration for connecting to an MCP (Model Context Protocol) server.
4544///
4545/// MCP servers provide tools and context that the Agent can use when
4546/// processing prompts.
4547///
4548/// See protocol docs: [MCP Servers](https://agentclientprotocol.com/protocol/v2/session-setup#mcp-servers)
4549#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4550#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4551#[serde(tag = "type", rename_all = "snake_case")]
4552#[non_exhaustive]
4553pub enum McpServer {
4554    /// HTTP transport configuration
4555    ///
4556    /// Only available when the Agent capabilities include `session.mcp.http`.
4557    Http(McpServerHttp),
4558    /// **UNSTABLE**
4559    ///
4560    /// This capability is not part of the spec yet, and may be removed or changed at any point.
4561    ///
4562    /// ACP transport configuration
4563    ///
4564    /// Only available when the Agent capabilities include `session.mcp.acp`.
4565    /// The MCP server is provided by an ACP component and communicates over the ACP channel.
4566    #[cfg(feature = "unstable_mcp_over_acp")]
4567    Acp(McpServerAcp),
4568    /// Stdio transport configuration
4569    ///
4570    /// Only available when the Agent capabilities include `session.mcp.stdio`.
4571    Stdio(McpServerStdio),
4572    /// Custom or future MCP server transport configuration.
4573    ///
4574    /// Values beginning with `_` are reserved for implementation-specific
4575    /// extensions. Unknown values that do not begin with `_` are reserved for
4576    /// future ACP variants.
4577    ///
4578    /// Receivers that do not understand this transport SHOULD preserve the raw
4579    /// payload when storing, replaying, proxying, or forwarding session setup
4580    /// data. Agents MUST reject a request with a transport they do not support
4581    /// with `-32602`.
4582    #[serde(untagged)]
4583    Other(OtherMcpServer),
4584}
4585
4586/// Custom or future MCP server transport payload.
4587#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4588#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4589#[cfg_attr(feature = "schemars", schemars(inline))]
4590#[cfg_attr(feature = "schemars", schemars(transform = other_mcp_server_schema))]
4591#[serde(rename_all = "camelCase")]
4592#[non_exhaustive]
4593pub struct OtherMcpServer {
4594    /// Custom or future MCP server transport type.
4595    ///
4596    /// Values beginning with `_` are reserved for implementation-specific
4597    /// extensions. Unknown values that do not begin with `_` are reserved for
4598    /// future ACP variants.
4599    #[serde(rename = "type")]
4600    pub type_: String,
4601    /// Additional fields from the unknown MCP server transport payload.
4602    #[serde(flatten)]
4603    pub fields: IndexMap<String, serde_json::Value>,
4604}
4605
4606impl OtherMcpServer {
4607    /// Builds [`OtherMcpServer`] from an unknown discriminator and preserves the remaining extension fields.
4608    #[must_use]
4609    pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
4610        fields.shift_remove("type");
4611        Self {
4612            type_: type_.into(),
4613            fields,
4614        }
4615    }
4616}
4617
4618impl<'de> Deserialize<'de> for OtherMcpServer {
4619    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4620    where
4621        D: serde::Deserializer<'de>,
4622    {
4623        let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
4624        let type_ = fields
4625            .shift_remove("type")
4626            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4627        let serde_json::Value::String(type_) = type_ else {
4628            return Err(serde::de::Error::custom("`type` must be a string"));
4629        };
4630
4631        if is_known_mcp_server_type(&type_) {
4632            return Err(serde::de::Error::custom(format!(
4633                "known MCP server transport `{type_}` did not match its schema"
4634            )));
4635        }
4636
4637        Ok(Self { type_, fields })
4638    }
4639}
4640
4641fn is_known_mcp_server_type(type_: &str) -> bool {
4642    match type_ {
4643        "http" | "stdio" => true,
4644        #[cfg(feature = "unstable_mcp_over_acp")]
4645        "acp" => true,
4646        _ => false,
4647    }
4648}
4649
4650#[cfg(feature = "schemars")]
4651fn other_mcp_server_schema(schema: &mut Schema) {
4652    super::schema_util::reject_known_string_discriminators(
4653        schema,
4654        "type",
4655        &[
4656            "http",
4657            "stdio",
4658            #[cfg(feature = "unstable_mcp_over_acp")]
4659            "acp",
4660        ],
4661    );
4662}
4663
4664/// HTTP transport configuration for MCP.
4665#[serde_as]
4666#[skip_serializing_none]
4667#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4668#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4669#[serde(rename_all = "camelCase")]
4670#[non_exhaustive]
4671pub struct McpServerHttp {
4672    /// Human-readable name identifying this MCP server. MUST be unique within `mcpServers`.
4673    ///
4674    /// Agents reject a request with a duplicate `name` with `-32602`.
4675    pub name: String,
4676    /// URL to the MCP server.
4677    #[cfg_attr(feature = "schemars", schemars(url))]
4678    pub url: String,
4679    /// HTTP headers to set when making requests to the MCP server. Headers the MCP transport
4680    /// defines are owned by the transport, and Agents use the transport's values for them.
4681    #[serde_as(deserialize_as = "DefaultOnNull")]
4682    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4683    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4684    pub headers: Vec<HttpHeader>,
4685    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4686    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4687    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4688    ///
4689    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4690    #[serde_as(deserialize_as = "DefaultOnError")]
4691    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4692    #[serde(default)]
4693    #[serde(rename = "_meta")]
4694    pub meta: Option<Meta>,
4695}
4696
4697impl McpServerHttp {
4698    /// Builds [`McpServerHttp`] with the required fields set. Optional fields start unset or empty.
4699    #[must_use]
4700    pub fn new(name: impl Into<String>, url: impl Into<String>) -> Self {
4701        Self {
4702            name: name.into(),
4703            url: url.into(),
4704            headers: Vec::new(),
4705            meta: None,
4706        }
4707    }
4708
4709    /// HTTP headers to set when making requests to the MCP server. Headers the MCP transport
4710    /// defines are owned by the transport, and Agents use the transport's values for them.
4711    #[must_use]
4712    pub fn headers(mut self, headers: Vec<HttpHeader>) -> Self {
4713        self.headers = headers;
4714        self
4715    }
4716
4717    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4718    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4719    /// do not recognize.
4720    ///
4721    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4722    #[must_use]
4723    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4724        self.meta = meta.into_option();
4725        self
4726    }
4727}
4728
4729/// **UNSTABLE**
4730///
4731/// This capability is not part of the spec yet, and may be removed or changed at any point.
4732///
4733/// Unique identifier for an MCP server using the ACP transport.
4734///
4735/// The value is opaque and generated by the ACP component providing the MCP server. It is
4736/// used by `mcp/message` to route requests to the component that declared the server.
4737#[cfg(feature = "unstable_mcp_over_acp")]
4738#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4739#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
4740#[serde(transparent)]
4741#[from(forward)]
4742#[non_exhaustive]
4743pub struct McpServerAcpId(pub Arc<str>);
4744
4745#[cfg(feature = "unstable_mcp_over_acp")]
4746impl McpServerAcpId {
4747    /// Wraps a protocol string as a typed [`McpServerAcpId`].
4748    #[must_use]
4749    pub fn new(id: impl Into<Self>) -> Self {
4750        id.into()
4751    }
4752}
4753
4754/// **UNSTABLE**
4755///
4756/// This capability is not part of the spec yet, and may be removed or changed at any point.
4757///
4758/// ACP transport configuration for MCP.
4759///
4760/// The MCP server is provided by an ACP component and communicates over the ACP channel
4761/// using `mcp/message`.
4762#[serde_as]
4763#[skip_serializing_none]
4764#[cfg(feature = "unstable_mcp_over_acp")]
4765#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4766#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4767#[serde(rename_all = "camelCase")]
4768#[non_exhaustive]
4769pub struct McpServerAcp {
4770    /// Human-readable name identifying this MCP server. MUST be unique within `mcpServers`.
4771    ///
4772    /// Agents reject a request with a duplicate `name` with `-32602`.
4773    pub name: String,
4774    /// Unique identifier for this MCP server, generated by the component providing it.
4775    ///
4776    /// Providers MUST NOT reuse an ID for multiple ACP-transport MCP servers that are visible
4777    /// on the same ACP connection.
4778    pub server_id: McpServerAcpId,
4779    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4780    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4781    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4782    ///
4783    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4784    #[serde_as(deserialize_as = "DefaultOnError")]
4785    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4786    #[serde(default)]
4787    #[serde(rename = "_meta")]
4788    pub meta: Option<Meta>,
4789}
4790
4791#[cfg(feature = "unstable_mcp_over_acp")]
4792impl McpServerAcp {
4793    /// Builds [`McpServerAcp`] with the required fields set. Optional fields start unset or empty.
4794    #[must_use]
4795    pub fn new(name: impl Into<String>, server_id: impl Into<McpServerAcpId>) -> Self {
4796        Self {
4797            name: name.into(),
4798            server_id: server_id.into(),
4799            meta: None,
4800        }
4801    }
4802
4803    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4804    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4805    /// do not recognize.
4806    ///
4807    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4808    #[must_use]
4809    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4810        self.meta = meta.into_option();
4811        self
4812    }
4813}
4814
4815/// Stdio transport configuration for MCP.
4816#[serde_as]
4817#[skip_serializing_none]
4818#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4819#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4820#[serde(rename_all = "camelCase")]
4821#[non_exhaustive]
4822pub struct McpServerStdio {
4823    /// Human-readable name identifying this MCP server. MUST be unique within `mcpServers`.
4824    ///
4825    /// Agents reject a request with a duplicate `name` with `-32602`.
4826    pub name: String,
4827    /// Path to the MCP server executable. Must be an absolute path.
4828    ///
4829    /// Agents reject a request with a relative `command` with `-32602`.
4830    pub command: AbsolutePath,
4831    /// Command-line arguments to pass to the MCP server.
4832    #[serde_as(deserialize_as = "DefaultOnNull")]
4833    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4834    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4835    pub args: Vec<String>,
4836    /// Environment variables to set when launching the MCP server. Names SHOULD be unique.
4837    /// Agents MAY reject duplicates with `-32602`, and otherwise the last entry wins.
4838    #[serde_as(deserialize_as = "DefaultOnNull")]
4839    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4840    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4841    pub env: Vec<EnvVariable>,
4842    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4843    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4844    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4845    ///
4846    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4847    #[serde_as(deserialize_as = "DefaultOnError")]
4848    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4849    #[serde(default)]
4850    #[serde(rename = "_meta")]
4851    pub meta: Option<Meta>,
4852}
4853
4854impl McpServerStdio {
4855    /// Builds [`McpServerStdio`] with the required fields set. Optional fields start unset or empty.
4856    #[must_use]
4857    pub fn new(name: impl Into<String>, command: impl Into<AbsolutePath>) -> Self {
4858        Self {
4859            name: name.into(),
4860            command: command.into(),
4861            args: Vec::new(),
4862            env: Vec::new(),
4863            meta: None,
4864        }
4865    }
4866
4867    /// Command-line arguments to pass to the MCP server.
4868    #[must_use]
4869    pub fn args(mut self, args: Vec<String>) -> Self {
4870        self.args = args;
4871        self
4872    }
4873
4874    /// Environment variables to set when launching the MCP server. Names SHOULD be unique.
4875    /// Agents MAY reject duplicates with `-32602`, and otherwise the last entry wins.
4876    #[must_use]
4877    pub fn env(mut self, env: Vec<EnvVariable>) -> Self {
4878        self.env = env;
4879        self
4880    }
4881
4882    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4883    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4884    /// do not recognize.
4885    ///
4886    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4887    #[must_use]
4888    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4889        self.meta = meta.into_option();
4890        self
4891    }
4892}
4893
4894/// An environment variable to set when launching a process.
4895#[serde_as]
4896#[skip_serializing_none]
4897#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4898#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4899#[serde(rename_all = "camelCase")]
4900#[non_exhaustive]
4901pub struct EnvVariable {
4902    /// The name of the environment variable.
4903    pub name: String,
4904    /// The value to set for the environment variable.
4905    pub value: String,
4906    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4907    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4908    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4909    ///
4910    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4911    #[serde_as(deserialize_as = "DefaultOnError")]
4912    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4913    #[serde(default)]
4914    #[serde(rename = "_meta")]
4915    pub meta: Option<Meta>,
4916}
4917
4918impl EnvVariable {
4919    /// Builds [`EnvVariable`] with the required fields set. Optional fields start unset or empty.
4920    #[must_use]
4921    pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
4922        Self {
4923            name: name.into(),
4924            value: value.into(),
4925            meta: None,
4926        }
4927    }
4928
4929    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4930    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4931    /// do not recognize.
4932    ///
4933    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4934    #[must_use]
4935    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4936        self.meta = meta.into_option();
4937        self
4938    }
4939}
4940
4941/// An HTTP header to set when making requests to the MCP server.
4942#[serde_as]
4943#[skip_serializing_none]
4944#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4945#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4946#[serde(rename_all = "camelCase")]
4947#[non_exhaustive]
4948pub struct HttpHeader {
4949    /// The name of the HTTP header.
4950    pub name: String,
4951    /// The value to set for the HTTP header.
4952    pub value: String,
4953    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4954    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4955    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4956    ///
4957    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4958    #[serde_as(deserialize_as = "DefaultOnError")]
4959    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4960    #[serde(default)]
4961    #[serde(rename = "_meta")]
4962    pub meta: Option<Meta>,
4963}
4964
4965impl HttpHeader {
4966    /// Builds [`HttpHeader`] with the required fields set. Optional fields start unset or empty.
4967    #[must_use]
4968    pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
4969        Self {
4970            name: name.into(),
4971            value: value.into(),
4972            meta: None,
4973        }
4974    }
4975
4976    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
4977    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4978    /// do not recognize.
4979    ///
4980    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4981    #[must_use]
4982    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4983        self.meta = meta.into_option();
4984        self
4985    }
4986}
4987
4988// System prompt
4989
4990/// Client-provided system-level instructions for a session.
4991///
4992/// Clients MUST only send this when the Agent advertises
4993/// `session.systemPrompt`. Agents that cannot apply it, for example because of
4994/// an unadvertised mode or an unsupported content block type, MUST return an
4995/// error instead of creating or resuming the session.
4996#[serde_as]
4997#[skip_serializing_none]
4998#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4999#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5000#[serde(rename_all = "camelCase")]
5001#[non_exhaustive]
5002pub struct SystemPrompt {
5003    /// How the Agent combines `content` with its own instructions.
5004    ///
5005    /// Required. Agents MUST return an error for a mode they do not support rather than
5006    /// treating it as `append` or `override`.
5007    pub mode: SystemPromptMode,
5008    /// The system prompt content.
5009    ///
5010    /// Agents advertising the capability MUST accept `text` content blocks.
5011    /// Clients MUST NOT send other content block types until a future
5012    /// capability allows them, and Agents MUST return an error for content
5013    /// blocks they do not support, including unknown types.
5014    ///
5015    /// Clients MUST NOT send an empty array. Agents MAY reject one with
5016    /// `-32602` without creating or resuming the session.
5017    #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
5018    pub content: Vec<ContentBlock>,
5019    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5020    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5021    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5022    ///
5023    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5024    #[serde_as(deserialize_as = "DefaultOnError")]
5025    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5026    #[serde(default)]
5027    #[serde(rename = "_meta")]
5028    pub meta: Option<Meta>,
5029}
5030
5031impl SystemPrompt {
5032    /// Builds [`SystemPrompt`] with the required fields set. Optional fields start unset or empty.
5033    ///
5034    /// `mode` starts as [`SystemPromptMode::Append`]. Use [`SystemPrompt::mode`]
5035    /// to request another mode.
5036    #[must_use]
5037    pub fn new(content: Vec<ContentBlock>) -> Self {
5038        Self {
5039            mode: SystemPromptMode::default(),
5040            content,
5041            meta: None,
5042        }
5043    }
5044
5045    /// How the Agent combines `content` with its own instructions.
5046    #[must_use]
5047    pub fn mode(mut self, mode: SystemPromptMode) -> Self {
5048        self.mode = mode;
5049        self
5050    }
5051
5052    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5053    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5054    /// do not recognize.
5055    ///
5056    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5057    #[must_use]
5058    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5059        self.meta = meta.into_option();
5060        self
5061    }
5062}
5063
5064/// How the Agent combines a Client-provided system prompt with its own instructions.
5065///
5066/// Unknown modes are preserved so they can be stored,
5067/// proxied, or forwarded. An Agent MUST return an error for a mode it does not
5068/// support rather than treating it as `append` or `override`.
5069#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5070#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
5071#[serde(rename_all = "snake_case")]
5072#[non_exhaustive]
5073pub enum SystemPromptMode {
5074    /// Add the content to the Agent's own instructions rather than replacing them.
5075    ///
5076    /// Every Agent that advertises `session.systemPrompt` supports this mode.
5077    /// Agents SHOULD give the content system-level precedence, for example in the
5078    /// model's system prompt or developer instructions rather than in user-turn
5079    /// content. Where it is placed and how it is formatted is implementation-defined.
5080    #[default]
5081    Append,
5082    /// Replace the Agent's built-in default instructions with the content.
5083    ///
5084    /// This does not change tool availability, MCP servers, permissions, or session
5085    /// configuration. Context the Agent supplies from the workspace or environment
5086    /// MAY still be included. Clients that use this mode take responsibility for any
5087    /// tool guidance or safety instructions the Agent's default instructions
5088    /// provided, and MUST only use it when the Agent advertises
5089    /// `session.systemPrompt.mode.override`.
5090    Override,
5091    /// Custom or future system prompt mode.
5092    ///
5093    /// Values beginning with `_` are reserved for implementation-specific
5094    /// extensions. Unknown values that do not begin with `_` are reserved for
5095    /// future ACP variants.
5096    #[serde(untagged)]
5097    Other(String),
5098}
5099
5100// Prompt
5101
5102/// A key the Client generates to identify one `session/prompt` submission across attempts.
5103///
5104/// The key is an opaque, case-sensitive string of 1 to 255 characters. It is scoped to the
5105/// session named by the request's `sessionId`.
5106///
5107/// See protocol docs: [Retrying a prompt](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#retrying-a-prompt)
5108#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5109#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash, Display)]
5110#[serde(transparent)]
5111pub struct IdempotencyKey(
5112    #[cfg_attr(feature = "schemars", schemars(length(min = 1, max = 255)))] Arc<str>,
5113);
5114
5115impl IdempotencyKey {
5116    /// The maximum length of a key, in characters.
5117    pub const MAX_LENGTH: usize = 255;
5118
5119    /// Wraps a string as a typed [`IdempotencyKey`].
5120    ///
5121    /// # Errors
5122    ///
5123    /// Returns [`InvalidIdempotencyKey`] if the key is empty or longer than
5124    /// [`Self::MAX_LENGTH`] characters.
5125    pub fn new(key: impl Into<Arc<str>>) -> Result<Self, InvalidIdempotencyKey> {
5126        let key = key.into();
5127        if key.is_empty() {
5128            return Err(InvalidIdempotencyKey::Empty);
5129        }
5130        // The limit counts characters, as JSON Schema `maxLength` does, not bytes.
5131        if key.chars().nth(Self::MAX_LENGTH).is_some() {
5132            return Err(InvalidIdempotencyKey::TooLong);
5133        }
5134        Ok(Self(key))
5135    }
5136
5137    /// Generates a key from a random version 4 UUID ([RFC 9562]).
5138    ///
5139    /// Generate one key per submission, when the user submits the input, and store it
5140    /// with the pending input. Every attempt for that submission sends the same key.
5141    ///
5142    /// [RFC 9562]: https://www.rfc-editor.org/rfc/rfc9562
5143    #[cfg(feature = "uuid")]
5144    #[must_use]
5145    pub fn generate() -> Self {
5146        uuid::Uuid::new_v4().into()
5147    }
5148
5149    /// Returns the key as a string slice.
5150    #[must_use]
5151    pub fn as_str(&self) -> &str {
5152        &self.0
5153    }
5154}
5155
5156impl AsRef<str> for IdempotencyKey {
5157    fn as_ref(&self) -> &str {
5158        &self.0
5159    }
5160}
5161
5162#[cfg(feature = "uuid")]
5163impl From<uuid::Uuid> for IdempotencyKey {
5164    /// Uses the UUID's hyphenated lowercase form. It is 36 characters, so it is always a
5165    /// valid key.
5166    fn from(uuid: uuid::Uuid) -> Self {
5167        Self(uuid.to_string().into())
5168    }
5169}
5170
5171impl TryFrom<String> for IdempotencyKey {
5172    type Error = InvalidIdempotencyKey;
5173
5174    fn try_from(key: String) -> Result<Self, Self::Error> {
5175        Self::new(key)
5176    }
5177}
5178
5179impl TryFrom<&str> for IdempotencyKey {
5180    type Error = InvalidIdempotencyKey;
5181
5182    fn try_from(key: &str) -> Result<Self, Self::Error> {
5183        Self::new(key)
5184    }
5185}
5186
5187impl std::str::FromStr for IdempotencyKey {
5188    type Err = InvalidIdempotencyKey;
5189
5190    fn from_str(key: &str) -> Result<Self, Self::Err> {
5191        Self::new(key)
5192    }
5193}
5194
5195// Deserialization validates the key, so a malformed value fails the request
5196// instead of being treated as omitted.
5197impl<'de> Deserialize<'de> for IdempotencyKey {
5198    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
5199    where
5200        D: serde::Deserializer<'de>,
5201    {
5202        let key = Arc::<str>::deserialize(deserializer)?;
5203        Self::new(key).map_err(serde::de::Error::custom)
5204    }
5205}
5206
5207/// Error returned when a string is not a valid [`IdempotencyKey`].
5208#[derive(Debug, Clone, Copy, PartialEq, Eq, Display)]
5209#[non_exhaustive]
5210pub enum InvalidIdempotencyKey {
5211    /// The key is an empty string.
5212    #[display("idempotency key must not be empty")]
5213    Empty,
5214    /// The key is longer than [`IdempotencyKey::MAX_LENGTH`] characters.
5215    #[display(
5216        "idempotency key must be at most {} characters",
5217        IdempotencyKey::MAX_LENGTH
5218    )]
5219    TooLong,
5220}
5221
5222impl std::error::Error for InvalidIdempotencyKey {}
5223
5224/// Request parameters for sending a user prompt to the Agent.
5225///
5226/// Contains the user's message and any additional context.
5227///
5228/// See protocol docs: [User Message](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#1-user-message)
5229#[serde_as]
5230#[skip_serializing_none]
5231#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5232#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5233#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_PROMPT_METHOD_NAME)))]
5234#[serde(rename_all = "camelCase")]
5235#[non_exhaustive]
5236pub struct PromptRequest {
5237    /// The ID of the session to send this user message to
5238    pub session_id: SessionId,
5239    /// The blocks of content that compose the user's message.
5240    ///
5241    /// As a baseline, the Agent MUST support `text` and `resource_link` content blocks,
5242    /// while other variants are optionally enabled via `PromptCapabilities`.
5243    ///
5244    /// The Client MUST adapt its interface according to `PromptCapabilities`.
5245    ///
5246    /// The Client MAY include referenced pieces of context as either
5247    /// `resource` or `resource_link` content blocks.
5248    ///
5249    /// When available, `resource` is preferred
5250    /// as it avoids extra round-trips and allows the message to include
5251    /// pieces of context from sources the Agent might not have access to.
5252    ///
5253    /// Clients MUST NOT send an empty array. Agents MAY reject one with `-32602` without
5254    /// inserting it.
5255    #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
5256    pub prompt: Vec<ContentBlock>,
5257    /// Identifies one prompt submission within this session.
5258    ///
5259    /// Optional. Omitted and `null` are equivalent and mean no key. The Agent then handles
5260    /// the prompt without duplicate detection.
5261    ///
5262    /// The Client generates the key and sends the same key on every attempt for the same
5263    /// submission. Agents that advertise `capabilities.session` MUST support the key.
5264    /// A retry of a recorded insertion returns the original `messageId` without inserting
5265    /// another message.
5266    ///
5267    /// The Agent MUST recognize the key for as long as it retains the message, including
5268    /// across connections and Agent restarts. For a live-only message, it MUST recognize
5269    /// the key while the session stays active on a connection. A retry with a forgotten
5270    /// key is a new submission, even immediately after reconnecting. If a duplicate
5271    /// would matter and the Client cannot rule it out, it SHOULD NOT retry automatically.
5272    ///
5273    /// When present, the value is an opaque, case-sensitive string of 1 to 255 characters.
5274    /// Agents MUST reject any other value with `-32602` (Invalid params) and MUST NOT treat
5275    /// it as omitted.
5276    ///
5277    /// See protocol docs: [Retrying a prompt](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#retrying-a-prompt)
5278    #[serde(default)]
5279    pub idempotency_key: Option<IdempotencyKey>,
5280    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5281    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5282    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5283    ///
5284    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5285    #[serde_as(deserialize_as = "DefaultOnError")]
5286    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5287    #[serde(default)]
5288    #[serde(rename = "_meta")]
5289    pub meta: Option<Meta>,
5290}
5291
5292impl PromptRequest {
5293    /// Builds [`PromptRequest`] with the required request fields set. Optional fields start unset or empty.
5294    #[must_use]
5295    pub fn new(session_id: impl Into<SessionId>, prompt: Vec<ContentBlock>) -> Self {
5296        Self {
5297            session_id: session_id.into(),
5298            prompt,
5299            idempotency_key: None,
5300            meta: None,
5301        }
5302    }
5303
5304    /// Sets the key for this submission. `None` means no key.
5305    ///
5306    /// See protocol docs: [Retrying a prompt](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#retrying-a-prompt)
5307    #[must_use]
5308    pub fn idempotency_key(mut self, idempotency_key: impl IntoOption<IdempotencyKey>) -> Self {
5309        self.idempotency_key = idempotency_key.into_option();
5310        self
5311    }
5312
5313    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5314    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5315    /// do not recognize.
5316    ///
5317    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5318    #[must_use]
5319    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5320        self.meta = meta.into_option();
5321        self
5322    }
5323}
5324
5325/// Response acknowledging that a user prompt was inserted into the ACP conversation.
5326///
5327/// This response does not indicate that the prompt was merely received or held, nor that the
5328/// Agent has finished processing it.
5329/// Processing and completion are reported through `state_update` session updates.
5330///
5331/// Insertion is the logical addition of a user message with a message ID and a position
5332/// relative to other messages in the ACP conversation.
5333///
5334/// See protocol docs: [Prompt Accepted](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#2-prompt-accepted)
5335#[serde_as]
5336#[skip_serializing_none]
5337#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5338#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5339#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_PROMPT_METHOD_NAME)))]
5340#[serde(rename_all = "camelCase")]
5341#[non_exhaustive]
5342pub struct PromptResponse {
5343    /// Identifies the user message inserted into the ACP conversation.
5344    ///
5345    /// Required and non-null. Omission and explicit `null` are both invalid.
5346    ///
5347    /// The corresponding user-message session update carries this same identifier and may arrive
5348    /// before or after this response. Agents MUST echo the message during the live session, but are
5349    /// not required to retain it. If retained and replayed, the message keeps this identifier.
5350    pub message_id: MessageId,
5351    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5352    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5353    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5354    ///
5355    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5356    #[serde_as(deserialize_as = "DefaultOnError")]
5357    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5358    #[serde(default)]
5359    #[serde(rename = "_meta")]
5360    pub meta: Option<Meta>,
5361}
5362
5363impl PromptResponse {
5364    /// Builds [`PromptResponse`] with the required response fields set. Optional fields start unset or empty.
5365    #[must_use]
5366    pub fn new(message_id: impl Into<MessageId>) -> Self {
5367        Self {
5368            message_id: message_id.into(),
5369            meta: None,
5370        }
5371    }
5372
5373    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5374    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5375    /// do not recognize.
5376    ///
5377    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5378    #[must_use]
5379    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5380        self.meta = meta.into_option();
5381        self
5382    }
5383}
5384
5385/// Reasons why an Agent stops active session work.
5386///
5387/// See protocol docs: [Stop Reasons](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#stop-reasons)
5388#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5389#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
5390#[serde(tag = "stopReason", rename_all = "snake_case")]
5391#[non_exhaustive]
5392pub enum StopReason {
5393    /// The active work ended successfully.
5394    /// Includes locally handled commands that required no model call.
5395    EndTurn,
5396    /// The active work ended because the Agent reached the maximum number of tokens.
5397    MaxTokens,
5398    /// The active work ended because the Agent reached the maximum number of
5399    /// model requests for the foreground work.
5400    MaxTurnRequests,
5401    /// The active work ended because the Agent refused to continue.
5402    Refusal,
5403    /// The user or Client chose to stop the work: via `session/cancel`, by
5404    /// closing the session, or through an interaction the Agent offers, such
5405    /// as a permission option that tells the Agent to stop. A child session
5406    /// also reports this reason when its parent cancels its work. Other work
5407    /// the Agent stops for its own reasons uses another reason, such as
5408    /// `error` for an internal timeout.
5409    ///
5410    /// Agents MUST report this stop reason on an idle `state_update` when
5411    /// cancellation ends active foreground work, even if aborting causes
5412    /// exceptions. Agents MUST catch these errors and report `cancelled`, not
5413    /// `error`.
5414    Cancelled,
5415    /// The active work ended because something failed.
5416    ///
5417    /// This includes pre-insertion foreground work. A prompt failure before
5418    /// insertion also requires an error response to `session/prompt`. After
5419    /// insertion, the prompt's response remains successful.
5420    Error(ErrorStopReason),
5421    /// Custom or future stop reason.
5422    ///
5423    /// Values beginning with `_` are reserved for implementation-specific
5424    /// extensions. Unknown values that do not begin with `_` are reserved for
5425    /// future ACP variants.
5426    #[serde(untagged)]
5427    Other(OtherStopReason),
5428}
5429
5430impl From<ErrorStopReason> for StopReason {
5431    fn from(value: ErrorStopReason) -> Self {
5432        Self::Error(value)
5433    }
5434}
5435
5436/// Details of a failure that ended active work.
5437#[serde_as]
5438#[skip_serializing_none]
5439#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5440#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
5441#[serde(rename_all = "camelCase")]
5442#[non_exhaustive]
5443pub struct ErrorStopReason {
5444    /// The failure, as a JSON-RPC error object.
5445    ///
5446    /// Optional. Omitted and `null` are equivalent and mean the Agent is not reporting failure details.
5447    /// Agents SHOULD include it.
5448    #[serde_as(deserialize_as = "DefaultOnError")]
5449    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5450    #[serde(default)]
5451    pub error: Option<Box<Error>>,
5452}
5453
5454impl ErrorStopReason {
5455    /// Builds [`ErrorStopReason`] with the required fields set. Optional fields start unset or empty.
5456    #[must_use]
5457    pub fn new() -> Self {
5458        Self::default()
5459    }
5460
5461    /// The failure, as a JSON-RPC error object.
5462    #[must_use]
5463    pub fn error(mut self, error: impl IntoOption<Error>) -> Self {
5464        self.error = error.into_option().map(Box::new);
5465        self
5466    }
5467}
5468
5469/// Custom or future stop reason payload.
5470#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5471#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
5472#[cfg_attr(feature = "schemars", schemars(inline))]
5473#[cfg_attr(feature = "schemars", schemars(transform = other_stop_reason_schema))]
5474#[serde(rename_all = "camelCase")]
5475#[non_exhaustive]
5476pub struct OtherStopReason {
5477    /// Custom or future stop reason.
5478    ///
5479    /// Values beginning with `_` are reserved for implementation-specific
5480    /// extensions. Unknown values that do not begin with `_` are reserved for
5481    /// future ACP variants.
5482    pub stop_reason: String,
5483    /// Additional fields from the unknown stop reason payload.
5484    #[serde(flatten)]
5485    pub fields: IndexMap<String, serde_json::Value>,
5486}
5487
5488impl OtherStopReason {
5489    /// Builds [`OtherStopReason`] from an unknown discriminator and preserves the remaining extension fields.
5490    #[must_use]
5491    pub fn new(
5492        stop_reason: impl Into<String>,
5493        mut fields: IndexMap<String, serde_json::Value>,
5494    ) -> Self {
5495        remove_idle_state_update_fields(&mut fields);
5496        Self {
5497            stop_reason: stop_reason.into(),
5498            fields,
5499        }
5500    }
5501}
5502
5503impl<'de> Deserialize<'de> for OtherStopReason {
5504    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
5505    where
5506        D: serde::Deserializer<'de>,
5507    {
5508        let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
5509        let stop_reason = fields
5510            .shift_remove("stopReason")
5511            .ok_or_else(|| serde::de::Error::missing_field("stopReason"))?;
5512        let serde_json::Value::String(stop_reason) = stop_reason else {
5513            return Err(serde::de::Error::custom("`stopReason` must be a string"));
5514        };
5515
5516        if KNOWN_STOP_REASONS.contains(&stop_reason.as_str()) {
5517            return Err(serde::de::Error::custom(format!(
5518                "known stop reason `{stop_reason}` did not match its schema"
5519            )));
5520        }
5521        remove_idle_state_update_fields(&mut fields);
5522
5523        Ok(Self {
5524            stop_reason,
5525            fields,
5526        })
5527    }
5528}
5529
5530const KNOWN_STOP_REASONS: &[&str] = &[
5531    "end_turn",
5532    "max_tokens",
5533    "max_turn_requests",
5534    "refusal",
5535    "cancelled",
5536    "error",
5537];
5538
5539/// Keeps the idle update's own fields out of an unknown stop reason's payload.
5540fn remove_idle_state_update_fields(fields: &mut IndexMap<String, serde_json::Value>) {
5541    fields.shift_remove("stopReason");
5542    fields.shift_remove("usage");
5543    fields.shift_remove("_meta");
5544}
5545
5546#[cfg(feature = "schemars")]
5547fn other_stop_reason_schema(schema: &mut Schema) {
5548    super::schema_util::reject_known_string_discriminators(
5549        schema,
5550        "stopReason",
5551        KNOWN_STOP_REASONS,
5552    );
5553}
5554
5555/// **UNSTABLE**
5556///
5557/// This capability is not part of the spec yet, and may be removed or changed at any point.
5558///
5559/// Token usage for the foreground work that just completed, not cumulative for the session.
5560#[cfg(feature = "unstable_end_turn_token_usage")]
5561#[serde_as]
5562#[skip_serializing_none]
5563#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5564#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5565#[serde(rename_all = "camelCase")]
5566#[non_exhaustive]
5567pub struct Usage {
5568    /// Sum of all token types for the completed work.
5569    pub total_tokens: u64,
5570    /// Input tokens for the completed work.
5571    pub input_tokens: u64,
5572    /// Output tokens for the completed work.
5573    pub output_tokens: u64,
5574    /// Thought/reasoning tokens for the completed work.
5575    ///
5576    /// Omitted and `null` are equivalent and mean the count is not reported.
5577    #[serde_as(deserialize_as = "DefaultOnError")]
5578    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5579    #[serde(default)]
5580    pub thought_tokens: Option<u64>,
5581    /// Cache read tokens for the completed work.
5582    ///
5583    /// Omitted and `null` are equivalent and mean the count is not reported.
5584    #[serde_as(deserialize_as = "DefaultOnError")]
5585    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5586    #[serde(default)]
5587    pub cached_read_tokens: Option<u64>,
5588    /// Cache write tokens for the completed work.
5589    ///
5590    /// Omitted and `null` are equivalent and mean the count is not reported.
5591    #[serde_as(deserialize_as = "DefaultOnError")]
5592    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5593    #[serde(default)]
5594    pub cached_write_tokens: Option<u64>,
5595    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5596    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5597    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5598    ///
5599    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5600    #[serde_as(deserialize_as = "DefaultOnError")]
5601    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5602    #[serde(default)]
5603    #[serde(rename = "_meta")]
5604    pub meta: Option<Meta>,
5605}
5606
5607#[cfg(feature = "unstable_end_turn_token_usage")]
5608impl Usage {
5609    /// Builds [`Usage`] with the required fields set. Optional fields start unset or empty.
5610    #[must_use]
5611    pub fn new(total_tokens: u64, input_tokens: u64, output_tokens: u64) -> Self {
5612        Self {
5613            total_tokens,
5614            input_tokens,
5615            output_tokens,
5616            thought_tokens: None,
5617            cached_read_tokens: None,
5618            cached_write_tokens: None,
5619            meta: None,
5620        }
5621    }
5622
5623    /// Thought/reasoning tokens for the completed work.
5624    #[must_use]
5625    pub fn thought_tokens(mut self, thought_tokens: impl IntoOption<u64>) -> Self {
5626        self.thought_tokens = thought_tokens.into_option();
5627        self
5628    }
5629
5630    /// Cache read tokens for the completed work.
5631    #[must_use]
5632    pub fn cached_read_tokens(mut self, cached_read_tokens: impl IntoOption<u64>) -> Self {
5633        self.cached_read_tokens = cached_read_tokens.into_option();
5634        self
5635    }
5636
5637    /// Cache write tokens for the completed work.
5638    #[must_use]
5639    pub fn cached_write_tokens(mut self, cached_write_tokens: impl IntoOption<u64>) -> Self {
5640        self.cached_write_tokens = cached_write_tokens.into_option();
5641        self
5642    }
5643
5644    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5645    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5646    /// do not recognize.
5647    ///
5648    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5649    #[must_use]
5650    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5651        self.meta = meta.into_option();
5652        self
5653    }
5654}
5655
5656// Providers
5657
5658/// **UNSTABLE**
5659///
5660/// This capability is not part of the spec yet, and may be removed or changed at any point.
5661///
5662/// Well-known API protocol identifiers for LLM providers.
5663///
5664/// Agents and Clients MUST handle unknown protocol identifiers gracefully.
5665///
5666/// Protocol names beginning with `_` are free for custom use, like other ACP extension methods.
5667/// Protocol names that do not begin with `_` are reserved for the ACP spec.
5668#[cfg(feature = "unstable_llm_providers")]
5669#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5670#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5671#[serde(rename_all = "snake_case")]
5672#[non_exhaustive]
5673#[expect(clippy::doc_markdown)]
5674pub enum LlmProtocol {
5675    /// Anthropic API protocol.
5676    Anthropic,
5677    /// OpenAI API protocol.
5678    #[serde(rename = "openai")]
5679    OpenAi,
5680    /// Azure OpenAI API protocol.
5681    Azure,
5682    /// Google Vertex AI API protocol.
5683    Vertex,
5684    /// AWS Bedrock API protocol.
5685    Bedrock,
5686    /// Custom or future protocol.
5687    ///
5688    /// Values beginning with `_` are reserved for implementation-specific
5689    /// extensions. Unknown values that do not begin with `_` are reserved for
5690    /// future ACP variants.
5691    #[serde(untagged)]
5692    Other(String),
5693}
5694
5695/// **UNSTABLE**
5696///
5697/// This capability is not part of the spec yet, and may be removed or changed at any point.
5698///
5699/// Current effective non-secret routing configuration for a provider.
5700#[cfg(feature = "unstable_llm_providers")]
5701#[serde_as]
5702#[skip_serializing_none]
5703#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5704#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5705#[serde(rename_all = "camelCase")]
5706#[non_exhaustive]
5707pub struct ProviderCurrentConfig {
5708    /// Protocol currently used by this provider.
5709    pub api_type: LlmProtocol,
5710    /// Base URL currently used by this provider.
5711    #[cfg_attr(feature = "schemars", schemars(url))]
5712    pub base_url: String,
5713    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5714    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5715    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5716    ///
5717    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5718    #[serde_as(deserialize_as = "DefaultOnError")]
5719    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5720    #[serde(default)]
5721    #[serde(rename = "_meta")]
5722    pub meta: Option<Meta>,
5723}
5724
5725#[cfg(feature = "unstable_llm_providers")]
5726impl ProviderCurrentConfig {
5727    /// Builds [`ProviderCurrentConfig`] with the required fields set. Optional fields start unset or empty.
5728    #[must_use]
5729    pub fn new(api_type: LlmProtocol, base_url: impl Into<String>) -> Self {
5730        Self {
5731            api_type,
5732            base_url: base_url.into(),
5733            meta: None,
5734        }
5735    }
5736
5737    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5738    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5739    /// do not recognize.
5740    ///
5741    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5742    #[must_use]
5743    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5744        self.meta = meta.into_option();
5745        self
5746    }
5747}
5748
5749/// **UNSTABLE**
5750///
5751/// This capability is not part of the spec yet, and may be removed or changed at any point.
5752///
5753/// Unique identifier for a configurable LLM provider.
5754#[cfg(feature = "unstable_llm_providers")]
5755#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5756#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
5757#[serde(transparent)]
5758#[from(forward)]
5759#[non_exhaustive]
5760pub struct ProviderId(pub Arc<str>);
5761
5762#[cfg(feature = "unstable_llm_providers")]
5763impl ProviderId {
5764    /// Wraps a protocol string as a typed [`ProviderId`].
5765    #[must_use]
5766    pub fn new(id: impl Into<Self>) -> Self {
5767        id.into()
5768    }
5769}
5770
5771/// **UNSTABLE**
5772///
5773/// This capability is not part of the spec yet, and may be removed or changed at any point.
5774///
5775/// Information about a configurable LLM provider.
5776#[cfg(feature = "unstable_llm_providers")]
5777#[serde_as]
5778#[skip_serializing_none]
5779#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5780#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5781#[serde(rename_all = "camelCase")]
5782#[non_exhaustive]
5783pub struct ProviderInfo {
5784    /// Provider identifier, for example "main" or "openai".
5785    pub provider_id: ProviderId,
5786    /// Supported protocol types for this provider.
5787    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
5788    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
5789    pub supported: Vec<LlmProtocol>,
5790    /// Whether this provider is mandatory and cannot be disabled via `providers/disable`.
5791    /// If true, Clients MUST NOT call `providers/disable` for this provider ID.
5792    pub required: bool,
5793    /// Current effective non-secret routing config.
5794    /// Null or omitted means provider is disabled.
5795    #[serde(default)]
5796    pub current: Option<ProviderCurrentConfig>,
5797    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5798    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5799    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5800    ///
5801    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5802    #[serde_as(deserialize_as = "DefaultOnError")]
5803    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5804    #[serde(default)]
5805    #[serde(rename = "_meta")]
5806    pub meta: Option<Meta>,
5807}
5808
5809#[cfg(feature = "unstable_llm_providers")]
5810impl ProviderInfo {
5811    /// Builds [`ProviderInfo`] with the required fields set. Optional fields start unset or empty.
5812    #[must_use]
5813    pub fn new(
5814        provider_id: impl Into<ProviderId>,
5815        supported: Vec<LlmProtocol>,
5816        required: bool,
5817        current: impl IntoOption<ProviderCurrentConfig>,
5818    ) -> Self {
5819        Self {
5820            provider_id: provider_id.into(),
5821            supported,
5822            required,
5823            current: current.into_option(),
5824            meta: None,
5825        }
5826    }
5827
5828    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5829    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5830    /// do not recognize.
5831    ///
5832    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5833    #[must_use]
5834    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5835        self.meta = meta.into_option();
5836        self
5837    }
5838}
5839
5840#[cfg(feature = "unstable_llm_providers")]
5841crate::serde_util::default_on_null! {
5842    /// **UNSTABLE**
5843    ///
5844    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5845    ///
5846    /// Request parameters for `providers/list`.
5847    #[serde_as]
5848    #[skip_serializing_none]
5849    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5850    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
5851    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_LIST_METHOD_NAME)))]
5852    #[serde(rename_all = "camelCase")]
5853    #[non_exhaustive]
5854    pub struct ListProvidersRequest {
5855        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5856        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5857        /// Implementations MUST NOT assign meaning to keys they do not recognize.
5858        ///
5859        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5860        #[serde_as(deserialize_as = "DefaultOnError")]
5861        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5862        #[serde(default)]
5863        #[serde(rename = "_meta")]
5864        pub meta: Option<Meta>,
5865    }
5866}
5867
5868#[cfg(feature = "unstable_llm_providers")]
5869impl ListProvidersRequest {
5870    /// Builds [`ListProvidersRequest`] with the required request fields set. Optional fields start unset or empty.
5871    #[must_use]
5872    pub fn new() -> Self {
5873        Self::default()
5874    }
5875
5876    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5877    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5878    /// do not recognize.
5879    ///
5880    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5881    #[must_use]
5882    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5883        self.meta = meta.into_option();
5884        self
5885    }
5886}
5887
5888/// **UNSTABLE**
5889///
5890/// This capability is not part of the spec yet, and may be removed or changed at any point.
5891///
5892/// Response to `providers/list`.
5893#[cfg(feature = "unstable_llm_providers")]
5894#[serde_as]
5895#[skip_serializing_none]
5896#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5897#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5898#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_LIST_METHOD_NAME)))]
5899#[serde(rename_all = "camelCase")]
5900#[non_exhaustive]
5901pub struct ListProvidersResponse {
5902    /// Configurable providers with current routing info suitable for UI display.
5903    pub providers: Vec<ProviderInfo>,
5904    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5905    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5906    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5907    ///
5908    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5909    #[serde_as(deserialize_as = "DefaultOnError")]
5910    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5911    #[serde(default)]
5912    #[serde(rename = "_meta")]
5913    pub meta: Option<Meta>,
5914}
5915
5916#[cfg(feature = "unstable_llm_providers")]
5917impl ListProvidersResponse {
5918    /// Builds [`ListProvidersResponse`] with the required response fields set. Optional fields start unset or empty.
5919    #[must_use]
5920    pub fn new(providers: Vec<ProviderInfo>) -> Self {
5921        Self {
5922            providers,
5923            meta: None,
5924        }
5925    }
5926
5927    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5928    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5929    /// do not recognize.
5930    ///
5931    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5932    #[must_use]
5933    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5934        self.meta = meta.into_option();
5935        self
5936    }
5937}
5938
5939/// **UNSTABLE**
5940///
5941/// This capability is not part of the spec yet, and may be removed or changed at any point.
5942///
5943/// Request parameters for `providers/set`.
5944///
5945/// Replaces the full configuration for one provider ID.
5946#[cfg(feature = "unstable_llm_providers")]
5947#[serde_as]
5948#[skip_serializing_none]
5949#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5950#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
5951#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_SET_METHOD_NAME)))]
5952#[serde(rename_all = "camelCase")]
5953#[non_exhaustive]
5954pub struct SetProviderRequest {
5955    /// Provider ID to configure.
5956    pub provider_id: ProviderId,
5957    /// Protocol type for this provider.
5958    pub api_type: LlmProtocol,
5959    /// Base URL for requests sent through this provider.
5960    #[cfg_attr(feature = "schemars", schemars(url))]
5961    pub base_url: String,
5962    /// Full headers map for this provider.
5963    /// May include authorization, routing, or other integration-specific headers.
5964    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
5965    pub headers: IndexMap<String, String>,
5966    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
5967    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5968    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5969    ///
5970    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5971    #[serde_as(deserialize_as = "DefaultOnError")]
5972    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5973    #[serde(default)]
5974    #[serde(rename = "_meta")]
5975    pub meta: Option<Meta>,
5976}
5977
5978#[cfg(feature = "unstable_llm_providers")]
5979impl SetProviderRequest {
5980    /// Builds [`SetProviderRequest`] with the required request fields set. Optional fields start unset or empty.
5981    #[must_use]
5982    pub fn new(
5983        provider_id: impl Into<ProviderId>,
5984        api_type: LlmProtocol,
5985        base_url: impl Into<String>,
5986    ) -> Self {
5987        Self {
5988            provider_id: provider_id.into(),
5989            api_type,
5990            base_url: base_url.into(),
5991            headers: IndexMap::new(),
5992            meta: None,
5993        }
5994    }
5995
5996    /// Full headers map for this provider.
5997    /// May include authorization, routing, or other integration-specific headers.
5998    #[must_use]
5999    pub fn headers(mut self, headers: IndexMap<String, String>) -> Self {
6000        self.headers = headers;
6001        self
6002    }
6003
6004    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6005    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6006    /// do not recognize.
6007    ///
6008    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6009    #[must_use]
6010    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6011        self.meta = meta.into_option();
6012        self
6013    }
6014}
6015
6016#[cfg(feature = "unstable_llm_providers")]
6017crate::serde_util::default_on_null! {
6018    /// **UNSTABLE**
6019    ///
6020    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6021    ///
6022    /// Response to `providers/set`.
6023    #[serde_as]
6024    #[skip_serializing_none]
6025    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6026    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
6027    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_SET_METHOD_NAME)))]
6028    #[serde(rename_all = "camelCase")]
6029    #[non_exhaustive]
6030    pub struct SetProviderResponse {
6031        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6032        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6033        /// Implementations MUST NOT assign meaning to keys they do not recognize.
6034        ///
6035        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6036        #[serde_as(deserialize_as = "DefaultOnError")]
6037        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6038        #[serde(default)]
6039        #[serde(rename = "_meta")]
6040        pub meta: Option<Meta>,
6041    }
6042}
6043
6044#[cfg(feature = "unstable_llm_providers")]
6045impl SetProviderResponse {
6046    /// Builds [`SetProviderResponse`] with the required response fields set. Optional fields start unset or empty.
6047    #[must_use]
6048    pub fn new() -> Self {
6049        Self::default()
6050    }
6051
6052    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6053    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6054    /// do not recognize.
6055    ///
6056    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6057    #[must_use]
6058    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6059        self.meta = meta.into_option();
6060        self
6061    }
6062}
6063
6064/// **UNSTABLE**
6065///
6066/// This capability is not part of the spec yet, and may be removed or changed at any point.
6067///
6068/// Request parameters for `providers/disable`.
6069#[cfg(feature = "unstable_llm_providers")]
6070#[serde_as]
6071#[skip_serializing_none]
6072#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6073#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6074#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_DISABLE_METHOD_NAME)))]
6075#[serde(rename_all = "camelCase")]
6076#[non_exhaustive]
6077pub struct DisableProviderRequest {
6078    /// Provider ID to disable.
6079    pub provider_id: ProviderId,
6080    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6081    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6082    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6083    ///
6084    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6085    #[serde_as(deserialize_as = "DefaultOnError")]
6086    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6087    #[serde(default)]
6088    #[serde(rename = "_meta")]
6089    pub meta: Option<Meta>,
6090}
6091
6092#[cfg(feature = "unstable_llm_providers")]
6093impl DisableProviderRequest {
6094    /// Builds [`DisableProviderRequest`] with the required request fields set. Optional fields start unset or empty.
6095    #[must_use]
6096    pub fn new(provider_id: impl Into<ProviderId>) -> Self {
6097        Self {
6098            provider_id: provider_id.into(),
6099            meta: None,
6100        }
6101    }
6102
6103    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6104    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6105    /// do not recognize.
6106    ///
6107    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6108    #[must_use]
6109    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6110        self.meta = meta.into_option();
6111        self
6112    }
6113}
6114
6115#[cfg(feature = "unstable_llm_providers")]
6116crate::serde_util::default_on_null! {
6117    /// **UNSTABLE**
6118    ///
6119    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6120    ///
6121    /// Response to `providers/disable`.
6122    #[serde_as]
6123    #[skip_serializing_none]
6124    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6125    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
6126    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_DISABLE_METHOD_NAME)))]
6127    #[serde(rename_all = "camelCase")]
6128    #[non_exhaustive]
6129    pub struct DisableProviderResponse {
6130        /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6131        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6132        /// Implementations MUST NOT assign meaning to keys they do not recognize.
6133        ///
6134        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6135        #[serde_as(deserialize_as = "DefaultOnError")]
6136        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6137        #[serde(default)]
6138        #[serde(rename = "_meta")]
6139        pub meta: Option<Meta>,
6140    }
6141}
6142
6143#[cfg(feature = "unstable_llm_providers")]
6144impl DisableProviderResponse {
6145    /// Builds [`DisableProviderResponse`] with the required response fields set. Optional fields start unset or empty.
6146    #[must_use]
6147    pub fn new() -> Self {
6148        Self::default()
6149    }
6150
6151    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6152    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6153    /// do not recognize.
6154    ///
6155    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6156    #[must_use]
6157    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6158        self.meta = meta.into_option();
6159        self
6160    }
6161}
6162
6163// Capabilities
6164
6165/// Capabilities supported by the Agent.
6166///
6167/// Advertised during initialization to inform the Client about
6168/// available features and content types.
6169///
6170/// See protocol docs: [Agent Capabilities](https://agentclientprotocol.com/protocol/v2/initialization#agent-capabilities)
6171#[serde_as]
6172#[skip_serializing_none]
6173#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6174#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6175#[serde(rename_all = "camelCase")]
6176#[non_exhaustive]
6177pub struct AgentCapabilities {
6178    /// Session capabilities supported by the Agent.
6179    ///
6180    /// Optional. Omitted and `null` are equivalent and mean the Agent does not support the
6181    /// `session/*` methods. Supplying `{}` means the Agent supports the
6182    /// baseline session methods: `session/new`, `session/list`,
6183    /// `session/resume`, `session/close`, `session/prompt`, `session/cancel`,
6184    /// and `session/update`.
6185    #[serde_as(deserialize_as = "DefaultOnError")]
6186    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6187    #[serde(default)]
6188    pub session: Option<SessionCapabilities>,
6189    /// Authentication-related extension capabilities supported by the Agent.
6190    ///
6191    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise any
6192    /// authentication-related extensions. This field does not advertise support
6193    /// for `auth/login` or `auth/logout`. Those methods are advertised by a
6194    /// non-empty `authMethods` list in the `initialize` response.
6195    #[serde_as(deserialize_as = "DefaultOnError")]
6196    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6197    #[serde(default)]
6198    pub auth: Option<AgentAuthCapabilities>,
6199    /// **UNSTABLE**
6200    ///
6201    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6202    ///
6203    /// Provider configuration capabilities supported by the Agent.
6204    ///
6205    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6206    /// Supplying `{}` means the Agent supports provider configuration methods.
6207    #[cfg(feature = "unstable_llm_providers")]
6208    #[serde_as(deserialize_as = "DefaultOnError")]
6209    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6210    #[serde(default)]
6211    pub providers: Option<ProvidersCapabilities>,
6212    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6213    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6214    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6215    ///
6216    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6217    #[serde_as(deserialize_as = "DefaultOnError")]
6218    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6219    #[serde(default)]
6220    #[serde(rename = "_meta")]
6221    pub meta: Option<Meta>,
6222}
6223
6224impl AgentCapabilities {
6225    /// Builds an empty [`AgentCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6226    #[must_use]
6227    pub fn new() -> Self {
6228        Self::default()
6229    }
6230
6231    /// Session capabilities supported by the Agent.
6232    ///
6233    /// Omitted and `null` are equivalent and mean the Agent does not support the `session/*`
6234    /// methods. Supplying `{}` means the Agent supports the baseline
6235    /// session methods: `session/new`, `session/list`, `session/resume`,
6236    /// `session/close`, `session/prompt`, `session/cancel`, and
6237    /// `session/update`.
6238    #[must_use]
6239    pub fn session(mut self, session: impl IntoOption<SessionCapabilities>) -> Self {
6240        self.session = session.into_option();
6241        self
6242    }
6243
6244    /// Authentication-related extension capabilities supported by the Agent.
6245    ///
6246    /// This field does not advertise support for `auth/login` or `auth/logout`.
6247    #[must_use]
6248    pub fn auth(mut self, auth: impl IntoOption<AgentAuthCapabilities>) -> Self {
6249        self.auth = auth.into_option();
6250        self
6251    }
6252
6253    /// **UNSTABLE**
6254    ///
6255    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6256    ///
6257    /// Provider configuration capabilities supported by the Agent.
6258    #[cfg(feature = "unstable_llm_providers")]
6259    #[must_use]
6260    pub fn providers(mut self, providers: impl IntoOption<ProvidersCapabilities>) -> Self {
6261        self.providers = providers.into_option();
6262        self
6263    }
6264
6265    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6266    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6267    /// do not recognize.
6268    ///
6269    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6270    #[must_use]
6271    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6272        self.meta = meta.into_option();
6273        self
6274    }
6275}
6276
6277/// **UNSTABLE**
6278///
6279/// This capability is not part of the spec yet, and may be removed or changed at any point.
6280///
6281/// Provider configuration capabilities supported by the Agent.
6282///
6283/// Supplying `{}` means the Agent supports provider configuration methods.
6284#[cfg(feature = "unstable_llm_providers")]
6285#[serde_as]
6286#[skip_serializing_none]
6287#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6288#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6289#[non_exhaustive]
6290pub struct ProvidersCapabilities {
6291    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6292    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6293    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6294    ///
6295    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6296    #[serde_as(deserialize_as = "DefaultOnError")]
6297    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6298    #[serde(default)]
6299    #[serde(rename = "_meta")]
6300    pub meta: Option<Meta>,
6301}
6302
6303#[cfg(feature = "unstable_llm_providers")]
6304impl ProvidersCapabilities {
6305    /// Builds an empty [`ProvidersCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6306    #[must_use]
6307    pub fn new() -> Self {
6308        Self::default()
6309    }
6310
6311    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6312    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6313    /// do not recognize.
6314    ///
6315    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6316    #[must_use]
6317    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6318        self.meta = meta.into_option();
6319        self
6320    }
6321}
6322
6323/// Session capabilities supported by the Agent.
6324///
6325/// Supplying `{}` means the Agent supports the baseline session methods:
6326/// `session/new`, `session/list`, `session/resume`, `session/close`,
6327/// `session/prompt`, `session/cancel`, and `session/update`.
6328///
6329/// Agents that support sessions MAY support additional session methods,
6330/// prompt content types, and MCP transports by specifying additional
6331/// capabilities.
6332///
6333/// See protocol docs: [Session Capabilities](https://agentclientprotocol.com/protocol/v2/initialization#session-capabilities)
6334#[serde_as]
6335#[skip_serializing_none]
6336#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6337#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6338#[serde(rename_all = "camelCase")]
6339#[non_exhaustive]
6340pub struct SessionCapabilities {
6341    /// Prompt capabilities supported by the Agent in `session/prompt` requests.
6342    ///
6343    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise any
6344    /// prompt extensions beyond the baseline text and resource-link content
6345    /// required by `session/prompt`.
6346    #[serde_as(deserialize_as = "DefaultOnError")]
6347    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6348    #[serde(default)]
6349    pub prompt: Option<PromptCapabilities>,
6350    /// MCP capabilities supported by the Agent for session lifecycle requests.
6351    ///
6352    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise MCP
6353    /// server transport support for sessions.
6354    #[serde_as(deserialize_as = "DefaultOnError")]
6355    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6356    #[serde(default)]
6357    pub mcp: Option<McpCapabilities>,
6358    /// Whether the Agent supports `session/delete`.
6359    ///
6360    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6361    /// Supplying `{}` means the Agent supports deleting sessions from `session/list`.
6362    #[serde_as(deserialize_as = "DefaultOnError")]
6363    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6364    #[serde(default)]
6365    pub delete: Option<SessionDeleteCapabilities>,
6366    /// Whether the Agent supports `additionalDirectories` on supported session lifecycle requests.
6367    ///
6368    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6369    /// Supplying `{}` means the Agent supports `additionalDirectories` on
6370    /// supported session lifecycle requests.
6371    ///
6372    /// Agents MAY return `SessionInfo.additionalDirectories` to report the
6373    /// complete ordered additional-root list associated with a listed session.
6374    #[serde_as(deserialize_as = "DefaultOnError")]
6375    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6376    #[serde(default)]
6377    pub additional_directories: Option<SessionAdditionalDirectoriesCapabilities>,
6378    /// Whether the Agent supports `systemPrompt` on session lifecycle requests.
6379    ///
6380    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6381    /// Supplying `{}` means the Agent supports `systemPrompt` in `append` mode.
6382    #[serde_as(deserialize_as = "DefaultOnError")]
6383    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6384    #[serde(default)]
6385    pub system_prompt: Option<SessionSystemPromptCapabilities>,
6386    /// **UNSTABLE**
6387    ///
6388    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6389    ///
6390    /// Whether the Agent supports `session/fork`.
6391    ///
6392    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6393    /// Supplying `{}` means the Agent supports forking sessions.
6394    #[cfg(feature = "unstable_session_fork")]
6395    #[serde_as(deserialize_as = "DefaultOnError")]
6396    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6397    #[serde(default)]
6398    pub fork: Option<SessionForkCapabilities>,
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/archive` and `session/unarchive`.
6404    ///
6405    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6406    /// Supplying `{}` means the Agent supports both methods, the `archived` filter on
6407    /// `session/list`, and `SessionInfo.archived`.
6408    #[cfg(feature = "unstable_session_archive")]
6409    #[serde_as(deserialize_as = "DefaultOnError")]
6410    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6411    #[serde(default)]
6412    pub archive: Option<SessionArchiveCapabilities>,
6413    /// **UNSTABLE**
6414    ///
6415    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6416    ///
6417    /// Whether the Agent supports `session/status`.
6418    ///
6419    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6420    /// Supplying `{}` means the Agent supports checking session status.
6421    #[cfg(feature = "unstable_session_status")]
6422    #[serde_as(deserialize_as = "DefaultOnError")]
6423    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6424    #[serde(default)]
6425    pub status: Option<SessionStatusCapabilities>,
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/options`.
6431    ///
6432    /// Optional. Omitted or `null` both mean the Agent does not advertise support.
6433    /// Supplying `{}` means the Agent supports `session/options` and accepts initial
6434    /// config option values on session setup requests.
6435    #[cfg(feature = "unstable_session_options")]
6436    #[serde_as(deserialize_as = "DefaultOnError")]
6437    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6438    #[serde(default)]
6439    pub options: Option<SessionOptionsCapabilities>,
6440    /// **UNSTABLE**
6441    ///
6442    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6443    ///
6444    /// Whether the Agent supports `session/set_title`.
6445    ///
6446    /// Agents report titles through `session/list` and `session_info_update` without this
6447    /// capability. It only advertises that Clients can set titles.
6448    ///
6449    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6450    /// Supplying `{}` means the Agent supports setting session titles.
6451    #[cfg(feature = "unstable_session_set_title")]
6452    #[serde_as(deserialize_as = "DefaultOnError")]
6453    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6454    #[serde(default)]
6455    pub title: Option<SessionTitleCapabilities>,
6456    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6457    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6458    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6459    ///
6460    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6461    #[serde_as(deserialize_as = "DefaultOnError")]
6462    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6463    #[serde(default)]
6464    #[serde(rename = "_meta")]
6465    pub meta: Option<Meta>,
6466}
6467
6468impl SessionCapabilities {
6469    /// Builds an empty [`SessionCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6470    #[must_use]
6471    pub fn new() -> Self {
6472        Self::default()
6473    }
6474
6475    /// Prompt capabilities supported by the Agent in `session/prompt` requests.
6476    ///
6477    /// Omitted and `null` are equivalent and mean the Agent does not advertise any prompt
6478    /// extensions beyond the baseline text and resource-link content required by
6479    /// `session/prompt`.
6480    #[must_use]
6481    pub fn prompt(mut self, prompt: impl IntoOption<PromptCapabilities>) -> Self {
6482        self.prompt = prompt.into_option();
6483        self
6484    }
6485
6486    /// MCP capabilities supported by the Agent for session lifecycle requests.
6487    ///
6488    /// Omitted and `null` are equivalent and mean the Agent does not advertise MCP server
6489    /// transport support for sessions.
6490    #[must_use]
6491    pub fn mcp(mut self, mcp: impl IntoOption<McpCapabilities>) -> Self {
6492        self.mcp = mcp.into_option();
6493        self
6494    }
6495
6496    /// Whether the Agent supports `session/delete`.
6497    ///
6498    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
6499    /// Supplying `{}` means the Agent supports deleting sessions from `session/list`.
6500    #[must_use]
6501    pub fn delete(mut self, delete: impl IntoOption<SessionDeleteCapabilities>) -> Self {
6502        self.delete = delete.into_option();
6503        self
6504    }
6505
6506    /// Whether the Agent supports `additionalDirectories` on supported session lifecycle requests.
6507    ///
6508    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
6509    /// Supplying `{}` means the Agent supports `additionalDirectories` on
6510    /// supported session lifecycle requests.
6511    ///
6512    /// Agents MAY return `SessionInfo.additionalDirectories` to report the
6513    /// complete ordered additional-root list associated with a listed session.
6514    #[must_use]
6515    pub fn additional_directories(
6516        mut self,
6517        additional_directories: impl IntoOption<SessionAdditionalDirectoriesCapabilities>,
6518    ) -> Self {
6519        self.additional_directories = additional_directories.into_option();
6520        self
6521    }
6522
6523    /// Whether the Agent supports `systemPrompt` on session lifecycle requests.
6524    ///
6525    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
6526    /// Supplying `{}` means the Agent supports `systemPrompt` in `append` mode.
6527    #[must_use]
6528    pub fn system_prompt(
6529        mut self,
6530        system_prompt: impl IntoOption<SessionSystemPromptCapabilities>,
6531    ) -> Self {
6532        self.system_prompt = system_prompt.into_option();
6533        self
6534    }
6535
6536    #[cfg(feature = "unstable_session_fork")]
6537    /// Whether the Agent supports `session/fork`.
6538    ///
6539    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
6540    /// Supplying `{}` means the Agent supports forking sessions.
6541    #[must_use]
6542    pub fn fork(mut self, fork: impl IntoOption<SessionForkCapabilities>) -> Self {
6543        self.fork = fork.into_option();
6544        self
6545    }
6546
6547    /// **UNSTABLE**
6548    ///
6549    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6550    ///
6551    /// Whether the Agent supports `session/archive` and `session/unarchive`.
6552    ///
6553    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
6554    /// Supplying `{}` means the Agent supports both methods, the `archived` filter on
6555    /// `session/list`, and `SessionInfo.archived`.
6556    #[cfg(feature = "unstable_session_archive")]
6557    #[must_use]
6558    pub fn archive(mut self, archive: impl IntoOption<SessionArchiveCapabilities>) -> Self {
6559        self.archive = archive.into_option();
6560        self
6561    }
6562
6563    /// **UNSTABLE**
6564    ///
6565    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6566    ///
6567    /// Whether the Agent supports `session/status`.
6568    ///
6569    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
6570    /// Supplying `{}` means the Agent supports checking session status.
6571    #[cfg(feature = "unstable_session_status")]
6572    #[must_use]
6573    pub fn status(mut self, status: impl IntoOption<SessionStatusCapabilities>) -> Self {
6574        self.status = status.into_option();
6575        self
6576    }
6577
6578    /// **UNSTABLE**
6579    ///
6580    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6581    ///
6582    /// Whether the Agent supports `session/options`.
6583    ///
6584    /// Omitted or `null` both mean the Agent does not advertise support.
6585    /// Supplying `{}` means the Agent supports `session/options` and accepts initial
6586    /// config option values on session setup requests.
6587    #[cfg(feature = "unstable_session_options")]
6588    #[must_use]
6589    pub fn options(mut self, options: impl IntoOption<SessionOptionsCapabilities>) -> Self {
6590        self.options = options.into_option();
6591        self
6592    }
6593
6594    /// **UNSTABLE**
6595    ///
6596    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6597    ///
6598    /// Whether the Agent supports `session/set_title`.
6599    ///
6600    /// Agents report titles through `session/list` and `session_info_update` without this
6601    /// capability. It only advertises that Clients can set titles.
6602    ///
6603    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
6604    /// Supplying `{}` means the Agent supports setting session titles.
6605    #[cfg(feature = "unstable_session_set_title")]
6606    #[must_use]
6607    pub fn title(mut self, title: impl IntoOption<SessionTitleCapabilities>) -> Self {
6608        self.title = title.into_option();
6609        self
6610    }
6611
6612    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6613    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6614    /// do not recognize.
6615    ///
6616    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6617    #[must_use]
6618    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6619        self.meta = meta.into_option();
6620        self
6621    }
6622}
6623
6624/// Capabilities for the `session/delete` method.
6625///
6626/// Supplying `{}` means the Agent supports deleting sessions from `session/list`.
6627#[serde_as]
6628#[skip_serializing_none]
6629#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6630#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6631#[non_exhaustive]
6632pub struct SessionDeleteCapabilities {
6633    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6634    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6635    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6636    ///
6637    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6638    #[serde_as(deserialize_as = "DefaultOnError")]
6639    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6640    #[serde(default)]
6641    #[serde(rename = "_meta")]
6642    pub meta: Option<Meta>,
6643}
6644
6645impl SessionDeleteCapabilities {
6646    /// Builds an empty [`SessionDeleteCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6647    #[must_use]
6648    pub fn new() -> Self {
6649        Self::default()
6650    }
6651
6652    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6653    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6654    /// do not recognize.
6655    ///
6656    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6657    #[must_use]
6658    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6659        self.meta = meta.into_option();
6660        self
6661    }
6662}
6663
6664/// Capabilities for additional session directories support.
6665///
6666/// Supplying `{}` means the Agent supports the `additionalDirectories` field on
6667/// supported session lifecycle requests. Agents MAY return
6668/// `SessionInfo.additionalDirectories` in `session/list` to report the
6669/// complete ordered additional-root list associated with a listed session.
6670#[serde_as]
6671#[skip_serializing_none]
6672#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6673#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6674#[non_exhaustive]
6675pub struct SessionAdditionalDirectoriesCapabilities {
6676    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6677    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6678    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6679    ///
6680    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6681    #[serde_as(deserialize_as = "DefaultOnError")]
6682    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6683    #[serde(default)]
6684    #[serde(rename = "_meta")]
6685    pub meta: Option<Meta>,
6686}
6687
6688impl SessionAdditionalDirectoriesCapabilities {
6689    /// Builds an empty [`SessionAdditionalDirectoriesCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6690    #[must_use]
6691    pub fn new() -> Self {
6692        Self::default()
6693    }
6694
6695    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6696    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6697    /// do not recognize.
6698    ///
6699    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6700    #[must_use]
6701    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6702        self.meta = meta.into_option();
6703        self
6704    }
6705}
6706
6707/// Capabilities for Client-provided system prompts.
6708///
6709/// Supplying `{}` means the Agent supports `systemPrompt` on session lifecycle
6710/// requests in `append` mode.
6711#[serde_as]
6712#[skip_serializing_none]
6713#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6714#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6715#[serde(rename_all = "camelCase")]
6716#[non_exhaustive]
6717pub struct SessionSystemPromptCapabilities {
6718    /// Delivery modes the Agent supports in addition to `append`.
6719    ///
6720    /// Optional. Omitted and `null` are equivalent and mean the Agent supports only `append`.
6721    #[serde_as(deserialize_as = "DefaultOnError")]
6722    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6723    #[serde(default)]
6724    pub mode: Option<SessionSystemPromptModeCapabilities>,
6725    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6726    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6727    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6728    ///
6729    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6730    #[serde_as(deserialize_as = "DefaultOnError")]
6731    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6732    #[serde(default)]
6733    #[serde(rename = "_meta")]
6734    pub meta: Option<Meta>,
6735}
6736
6737impl SessionSystemPromptCapabilities {
6738    /// Builds an empty [`SessionSystemPromptCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6739    #[must_use]
6740    pub fn new() -> Self {
6741        Self::default()
6742    }
6743
6744    /// Delivery modes the Agent supports in addition to `append`.
6745    ///
6746    /// Omitted and `null` are equivalent and mean the Agent supports only `append`.
6747    #[must_use]
6748    pub fn mode(mut self, mode: impl IntoOption<SessionSystemPromptModeCapabilities>) -> Self {
6749        self.mode = mode.into_option();
6750        self
6751    }
6752
6753    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6754    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6755    /// do not recognize.
6756    ///
6757    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6758    #[must_use]
6759    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6760        self.meta = meta.into_option();
6761        self
6762    }
6763}
6764
6765/// System prompt delivery modes the Agent supports in addition to `append`.
6766///
6767/// `append` has no entry because every Agent advertising `session.systemPrompt`
6768/// supports it.
6769#[serde_as]
6770#[skip_serializing_none]
6771#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6772#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6773#[serde(rename_all = "camelCase")]
6774#[non_exhaustive]
6775pub struct SessionSystemPromptModeCapabilities {
6776    /// Whether the Agent supports `override` mode.
6777    ///
6778    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
6779    /// Supplying `{}` means the Agent supports replacing its built-in default
6780    /// instructions with the Client-provided system prompt.
6781    #[serde_as(deserialize_as = "DefaultOnError")]
6782    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6783    #[serde(default, rename = "override")]
6784    pub override_: Option<SessionSystemPromptOverrideCapabilities>,
6785    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6786    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6787    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6788    ///
6789    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6790    #[serde_as(deserialize_as = "DefaultOnError")]
6791    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6792    #[serde(default)]
6793    #[serde(rename = "_meta")]
6794    pub meta: Option<Meta>,
6795}
6796
6797impl SessionSystemPromptModeCapabilities {
6798    /// Builds an empty [`SessionSystemPromptModeCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6799    #[must_use]
6800    pub fn new() -> Self {
6801        Self::default()
6802    }
6803
6804    /// Whether the Agent supports `override` mode.
6805    ///
6806    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
6807    /// Supplying `{}` means the Agent supports replacing its built-in default
6808    /// instructions with the Client-provided system prompt.
6809    #[must_use]
6810    pub fn override_(
6811        mut self,
6812        override_: impl IntoOption<SessionSystemPromptOverrideCapabilities>,
6813    ) -> Self {
6814        self.override_ = override_.into_option();
6815        self
6816    }
6817
6818    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6819    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6820    /// do not recognize.
6821    ///
6822    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6823    #[must_use]
6824    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6825        self.meta = meta.into_option();
6826        self
6827    }
6828}
6829
6830/// Capabilities for the `override` system prompt mode.
6831///
6832/// Supplying `{}` means the Agent supports replacing its built-in default
6833/// instructions with the Client-provided system prompt.
6834#[serde_as]
6835#[skip_serializing_none]
6836#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6837#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6838#[non_exhaustive]
6839pub struct SessionSystemPromptOverrideCapabilities {
6840    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6841    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6842    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6843    ///
6844    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6845    #[serde_as(deserialize_as = "DefaultOnError")]
6846    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6847    #[serde(default)]
6848    #[serde(rename = "_meta")]
6849    pub meta: Option<Meta>,
6850}
6851
6852impl SessionSystemPromptOverrideCapabilities {
6853    /// Builds an empty [`SessionSystemPromptOverrideCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6854    #[must_use]
6855    pub fn new() -> Self {
6856        Self::default()
6857    }
6858
6859    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6860    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6861    /// do not recognize.
6862    ///
6863    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6864    #[must_use]
6865    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6866        self.meta = meta.into_option();
6867        self
6868    }
6869}
6870
6871/// **UNSTABLE**
6872///
6873/// This capability is not part of the spec yet, and may be removed or changed at any point.
6874///
6875/// Capabilities for the `session/fork` method.
6876///
6877/// Supplying `{}` means the Agent supports forking sessions.
6878#[cfg(feature = "unstable_session_fork")]
6879#[serde_as]
6880#[skip_serializing_none]
6881#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6882#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6883#[non_exhaustive]
6884pub struct SessionForkCapabilities {
6885    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6886    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6887    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6888    ///
6889    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6890    #[serde_as(deserialize_as = "DefaultOnError")]
6891    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6892    #[serde(default)]
6893    #[serde(rename = "_meta")]
6894    pub meta: Option<Meta>,
6895}
6896
6897#[cfg(feature = "unstable_session_fork")]
6898impl SessionForkCapabilities {
6899    /// Builds an empty [`SessionForkCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6900    #[must_use]
6901    pub fn new() -> Self {
6902        Self::default()
6903    }
6904
6905    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6906    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6907    /// do not recognize.
6908    ///
6909    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6910    #[must_use]
6911    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6912        self.meta = meta.into_option();
6913        self
6914    }
6915}
6916
6917/// **UNSTABLE**
6918///
6919/// This capability is not part of the spec yet, and may be removed or changed at any point.
6920///
6921/// Capabilities for `session/archive` and `session/unarchive`.
6922///
6923/// Supplying `{}` means the Agent supports both methods, the `archived` filter on
6924/// `session/list`, and `SessionInfo.archived`.
6925#[cfg(feature = "unstable_session_archive")]
6926#[serde_as]
6927#[skip_serializing_none]
6928#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6929#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6930#[non_exhaustive]
6931pub struct SessionArchiveCapabilities {
6932    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6933    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6934    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6935    ///
6936    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6937    #[serde_as(deserialize_as = "DefaultOnError")]
6938    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6939    #[serde(default)]
6940    #[serde(rename = "_meta")]
6941    pub meta: Option<Meta>,
6942}
6943
6944#[cfg(feature = "unstable_session_archive")]
6945impl SessionArchiveCapabilities {
6946    /// Builds an empty [`SessionArchiveCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6947    #[must_use]
6948    pub fn new() -> Self {
6949        Self::default()
6950    }
6951
6952    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6953    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6954    /// do not recognize.
6955    ///
6956    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6957    #[must_use]
6958    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6959        self.meta = meta.into_option();
6960        self
6961    }
6962}
6963
6964/// **UNSTABLE**
6965///
6966/// This capability is not part of the spec yet, and may be removed or changed at any point.
6967///
6968/// Capabilities for the `session/status` method.
6969///
6970/// Supplying `{}` means the Agent supports checking session status.
6971#[cfg(feature = "unstable_session_status")]
6972#[serde_as]
6973#[skip_serializing_none]
6974#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6975#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6976#[non_exhaustive]
6977pub struct SessionStatusCapabilities {
6978    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6979    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6980    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6981    ///
6982    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6983    #[serde_as(deserialize_as = "DefaultOnError")]
6984    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6985    #[serde(default)]
6986    #[serde(rename = "_meta")]
6987    pub meta: Option<Meta>,
6988}
6989
6990#[cfg(feature = "unstable_session_status")]
6991impl SessionStatusCapabilities {
6992    /// Builds an empty [`SessionStatusCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6993    #[must_use]
6994    pub fn new() -> Self {
6995        Self::default()
6996    }
6997
6998    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
6999    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7000    /// do not recognize.
7001    ///
7002    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7003    #[must_use]
7004    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7005        self.meta = meta.into_option();
7006        self
7007    }
7008}
7009
7010/// **UNSTABLE**
7011///
7012/// This capability is not part of the spec yet, and may be removed or changed at any point.
7013///
7014/// Capabilities for the `session/options` method.
7015///
7016/// Supplying `{}` means the Agent supports `session/options` and accepts initial config
7017/// option values on session setup requests.
7018#[cfg(feature = "unstable_session_options")]
7019#[serde_as]
7020#[skip_serializing_none]
7021#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7022#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7023#[non_exhaustive]
7024pub struct SessionOptionsCapabilities {
7025    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7026    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7027    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7028    ///
7029    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7030    #[serde_as(deserialize_as = "DefaultOnError")]
7031    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7032    #[serde(default)]
7033    #[serde(rename = "_meta")]
7034    pub meta: Option<Meta>,
7035}
7036
7037#[cfg(feature = "unstable_session_options")]
7038impl SessionOptionsCapabilities {
7039    /// Builds an empty [`SessionOptionsCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7040    #[must_use]
7041    pub fn new() -> Self {
7042        Self::default()
7043    }
7044
7045    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7046    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7047    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7048    ///
7049    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7050    #[must_use]
7051    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7052        self.meta = meta.into_option();
7053        self
7054    }
7055}
7056
7057/// **UNSTABLE**
7058///
7059/// This capability is not part of the spec yet, and may be removed or changed at any point.
7060///
7061/// Capabilities for Client-set session titles.
7062///
7063/// Supplying `{}` means the Agent supports `session/set_title`. Agents report titles
7064/// through `session/list` and `session_info_update` without this capability.
7065#[cfg(feature = "unstable_session_set_title")]
7066#[serde_as]
7067#[skip_serializing_none]
7068#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7069#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7070#[non_exhaustive]
7071pub struct SessionTitleCapabilities {
7072    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7073    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7074    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7075    ///
7076    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7077    #[serde_as(deserialize_as = "DefaultOnError")]
7078    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7079    #[serde(default)]
7080    #[serde(rename = "_meta")]
7081    pub meta: Option<Meta>,
7082}
7083
7084#[cfg(feature = "unstable_session_set_title")]
7085impl SessionTitleCapabilities {
7086    /// Builds an empty [`SessionTitleCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7087    #[must_use]
7088    pub fn new() -> Self {
7089        Self::default()
7090    }
7091
7092    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7093    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7094    /// do not recognize.
7095    ///
7096    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7097    #[must_use]
7098    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7099        self.meta = meta.into_option();
7100        self
7101    }
7102}
7103
7104/// Prompt capabilities supported by the Agent in `session/prompt` requests.
7105///
7106/// Baseline Agent functionality requires support for `text`
7107/// and `resource_link` content blocks in prompt requests.
7108///
7109/// Other content types need one of these capabilities.
7110/// Capabilities for different types of content in prompt requests.
7111///
7112/// Indicates which content types beyond the baseline (text and resource links)
7113/// the Agent can process.
7114///
7115/// See protocol docs: [Session Prompt Capabilities](https://agentclientprotocol.com/protocol/v2/initialization#session-prompt-capabilities)
7116#[serde_as]
7117#[skip_serializing_none]
7118#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7119#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7120#[serde(rename_all = "camelCase")]
7121#[non_exhaustive]
7122pub struct PromptCapabilities {
7123    /// Agent supports `image` content blocks.
7124    ///
7125    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
7126    /// Supplying `{}` means the Agent supports image content in prompts.
7127    #[serde_as(deserialize_as = "DefaultOnError")]
7128    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7129    #[serde(default)]
7130    pub image: Option<PromptImageCapabilities>,
7131    /// Agent supports `audio` content blocks.
7132    ///
7133    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
7134    /// Supplying `{}` means the Agent supports audio content in prompts.
7135    #[serde_as(deserialize_as = "DefaultOnError")]
7136    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7137    #[serde(default)]
7138    pub audio: Option<PromptAudioCapabilities>,
7139    /// Agent supports embedded context in `session/prompt` requests.
7140    ///
7141    /// When enabled, the Client is allowed to include `resource` content blocks
7142    /// in prompt requests for pieces of context that are referenced in the message.
7143    ///
7144    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
7145    /// Supplying `{}` means the Agent supports embedded context in prompts.
7146    #[serde_as(deserialize_as = "DefaultOnError")]
7147    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7148    #[serde(default)]
7149    pub embedded_context: Option<PromptEmbeddedContextCapabilities>,
7150    /// **UNSTABLE**
7151    ///
7152    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7153    ///
7154    /// Agent supports `skill` content blocks.
7155    ///
7156    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
7157    /// Supplying `{}` means a prompt may contain one `skill` content block, as its first block.
7158    /// An Agent that sends `skill` entries in `availableCommands` MUST advertise this capability.
7159    #[cfg(feature = "unstable_agent_skills")]
7160    #[serde_as(deserialize_as = "DefaultOnError")]
7161    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7162    #[serde(default)]
7163    pub skill: Option<PromptSkillCapabilities>,
7164    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7165    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7166    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7167    ///
7168    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7169    #[serde_as(deserialize_as = "DefaultOnError")]
7170    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7171    #[serde(default)]
7172    #[serde(rename = "_meta")]
7173    pub meta: Option<Meta>,
7174}
7175
7176impl PromptCapabilities {
7177    /// Builds an empty [`PromptCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7178    #[must_use]
7179    pub fn new() -> Self {
7180        Self::default()
7181    }
7182
7183    /// Agent supports `image` content blocks.
7184    ///
7185    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
7186    /// Supplying `{}` means the Agent supports image content in prompts.
7187    #[must_use]
7188    pub fn image(mut self, image: impl IntoOption<PromptImageCapabilities>) -> Self {
7189        self.image = image.into_option();
7190        self
7191    }
7192
7193    /// Agent supports `audio` content blocks.
7194    ///
7195    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
7196    /// Supplying `{}` means the Agent supports audio content in prompts.
7197    #[must_use]
7198    pub fn audio(mut self, audio: impl IntoOption<PromptAudioCapabilities>) -> Self {
7199        self.audio = audio.into_option();
7200        self
7201    }
7202
7203    /// Agent supports embedded context in `session/prompt` requests.
7204    ///
7205    /// When enabled, the Client is allowed to include `resource` content blocks
7206    /// in prompt requests for pieces of context that are referenced in the message.
7207    ///
7208    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
7209    /// Supplying `{}` means the Agent supports embedded context in prompts.
7210    #[must_use]
7211    pub fn embedded_context(
7212        mut self,
7213        embedded_context: impl IntoOption<PromptEmbeddedContextCapabilities>,
7214    ) -> Self {
7215        self.embedded_context = embedded_context.into_option();
7216        self
7217    }
7218
7219    /// **UNSTABLE**
7220    ///
7221    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7222    ///
7223    /// Agent supports `skill` content blocks.
7224    ///
7225    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
7226    /// Supplying `{}` means a prompt may contain one `skill` content block, as its first block.
7227    #[cfg(feature = "unstable_agent_skills")]
7228    #[must_use]
7229    pub fn skill(mut self, skill: impl IntoOption<PromptSkillCapabilities>) -> Self {
7230        self.skill = skill.into_option();
7231        self
7232    }
7233
7234    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7235    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7236    /// do not recognize.
7237    ///
7238    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7239    #[must_use]
7240    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7241        self.meta = meta.into_option();
7242        self
7243    }
7244}
7245
7246/// Capabilities for image content in prompt requests.
7247///
7248/// Supplying `{}` means the Agent supports image content in prompts.
7249#[serde_as]
7250#[skip_serializing_none]
7251#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7252#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7253#[non_exhaustive]
7254pub struct PromptImageCapabilities {
7255    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7256    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7257    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7258    ///
7259    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7260    #[serde_as(deserialize_as = "DefaultOnError")]
7261    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7262    #[serde(default)]
7263    #[serde(rename = "_meta")]
7264    pub meta: Option<Meta>,
7265}
7266
7267impl PromptImageCapabilities {
7268    /// Builds an empty [`PromptImageCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7269    #[must_use]
7270    pub fn new() -> Self {
7271        Self::default()
7272    }
7273
7274    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7275    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7276    /// do not recognize.
7277    ///
7278    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7279    #[must_use]
7280    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7281        self.meta = meta.into_option();
7282        self
7283    }
7284}
7285
7286/// Capabilities for audio content in prompt requests.
7287///
7288/// Supplying `{}` means the Agent supports audio content in prompts.
7289#[serde_as]
7290#[skip_serializing_none]
7291#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7292#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7293#[non_exhaustive]
7294pub struct PromptAudioCapabilities {
7295    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7296    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7297    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7298    ///
7299    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7300    #[serde_as(deserialize_as = "DefaultOnError")]
7301    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7302    #[serde(default)]
7303    #[serde(rename = "_meta")]
7304    pub meta: Option<Meta>,
7305}
7306
7307impl PromptAudioCapabilities {
7308    /// Builds an empty [`PromptAudioCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7309    #[must_use]
7310    pub fn new() -> Self {
7311        Self::default()
7312    }
7313
7314    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7315    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7316    /// do not recognize.
7317    ///
7318    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7319    #[must_use]
7320    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7321        self.meta = meta.into_option();
7322        self
7323    }
7324}
7325
7326/// Capabilities for embedded context in prompt requests.
7327///
7328/// Supplying `{}` means the Agent supports embedded context in prompts.
7329#[serde_as]
7330#[skip_serializing_none]
7331#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7332#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7333#[non_exhaustive]
7334pub struct PromptEmbeddedContextCapabilities {
7335    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7336    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7337    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7338    ///
7339    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7340    #[serde_as(deserialize_as = "DefaultOnError")]
7341    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7342    #[serde(default)]
7343    #[serde(rename = "_meta")]
7344    pub meta: Option<Meta>,
7345}
7346
7347impl PromptEmbeddedContextCapabilities {
7348    /// Builds an empty [`PromptEmbeddedContextCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7349    #[must_use]
7350    pub fn new() -> Self {
7351        Self::default()
7352    }
7353
7354    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7355    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7356    /// do not recognize.
7357    ///
7358    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7359    #[must_use]
7360    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7361        self.meta = meta.into_option();
7362        self
7363    }
7364}
7365
7366/// **UNSTABLE**
7367///
7368/// This capability is not part of the spec yet, and may be removed or changed at any point.
7369///
7370/// Capabilities for `skill` content blocks in prompt requests.
7371///
7372/// Supplying `{}` means a prompt may contain one `skill` content block, as
7373/// its first block. The Agent opts in to more with the `inline` field.
7374#[cfg(feature = "unstable_agent_skills")]
7375#[serde_as]
7376#[skip_serializing_none]
7377#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7378#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7379#[serde(rename_all = "camelCase")]
7380#[non_exhaustive]
7381pub struct PromptSkillCapabilities {
7382    /// Agent supports `skill` content blocks at any position in a prompt.
7383    ///
7384    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
7385    /// Supplying `{}` means a prompt may contain any number of `skill` content blocks, at any
7386    /// position.
7387    #[serde_as(deserialize_as = "DefaultOnError")]
7388    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7389    #[serde(default)]
7390    pub inline: Option<PromptSkillInlineCapabilities>,
7391    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7392    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7393    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7394    ///
7395    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7396    #[serde_as(deserialize_as = "DefaultOnError")]
7397    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7398    #[serde(default)]
7399    #[serde(rename = "_meta")]
7400    pub meta: Option<Meta>,
7401}
7402
7403#[cfg(feature = "unstable_agent_skills")]
7404impl PromptSkillCapabilities {
7405    /// Builds an empty [`PromptSkillCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7406    #[must_use]
7407    pub fn new() -> Self {
7408        Self::default()
7409    }
7410
7411    /// Agent supports `skill` content blocks at any position in a prompt.
7412    ///
7413    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
7414    /// Supplying `{}` means a prompt may contain any number of `skill` content blocks, at any
7415    /// position.
7416    #[must_use]
7417    pub fn inline(mut self, inline: impl IntoOption<PromptSkillInlineCapabilities>) -> Self {
7418        self.inline = inline.into_option();
7419        self
7420    }
7421
7422    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7423    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7424    /// do not recognize.
7425    ///
7426    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7427    #[must_use]
7428    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7429        self.meta = meta.into_option();
7430        self
7431    }
7432}
7433
7434/// **UNSTABLE**
7435///
7436/// This capability is not part of the spec yet, and may be removed or changed at any point.
7437///
7438/// Capabilities for `skill` content blocks at any position in a prompt.
7439///
7440/// Supplying `{}` means a prompt may contain any number of `skill` content
7441/// blocks, at any position.
7442#[cfg(feature = "unstable_agent_skills")]
7443#[serde_as]
7444#[skip_serializing_none]
7445#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7446#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7447#[non_exhaustive]
7448pub struct PromptSkillInlineCapabilities {
7449    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7450    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7451    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7452    ///
7453    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7454    #[serde_as(deserialize_as = "DefaultOnError")]
7455    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7456    #[serde(default)]
7457    #[serde(rename = "_meta")]
7458    pub meta: Option<Meta>,
7459}
7460
7461#[cfg(feature = "unstable_agent_skills")]
7462impl PromptSkillInlineCapabilities {
7463    /// Builds an empty [`PromptSkillInlineCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7464    #[must_use]
7465    pub fn new() -> Self {
7466        Self::default()
7467    }
7468
7469    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7470    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7471    /// do not recognize.
7472    ///
7473    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7474    #[must_use]
7475    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7476        self.meta = meta.into_option();
7477        self
7478    }
7479}
7480
7481/// MCP capabilities supported by the Agent for session lifecycle requests.
7482#[serde_as]
7483#[skip_serializing_none]
7484#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7485#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7486#[serde(rename_all = "camelCase")]
7487#[non_exhaustive]
7488pub struct McpCapabilities {
7489    /// Agent supports `stdio` MCP servers.
7490    ///
7491    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
7492    /// Supplying `{}` means the Agent supports stdio MCP server transports.
7493    #[serde_as(deserialize_as = "DefaultOnError")]
7494    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7495    #[serde(default)]
7496    pub stdio: Option<McpStdioCapabilities>,
7497    /// Agent supports `http` MCP servers.
7498    ///
7499    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
7500    /// Supplying `{}` means the Agent supports HTTP MCP server transports.
7501    #[serde_as(deserialize_as = "DefaultOnError")]
7502    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7503    #[serde(default)]
7504    pub http: Option<McpHttpCapabilities>,
7505    /// **UNSTABLE**
7506    ///
7507    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7508    ///
7509    /// Agent supports `acp` MCP servers.
7510    ///
7511    /// Optional. Omitted and `null` are equivalent and mean the Agent does not advertise support.
7512    /// Supplying `{}` means the Agent supports ACP MCP server transports.
7513    #[cfg(feature = "unstable_mcp_over_acp")]
7514    #[serde_as(deserialize_as = "DefaultOnError")]
7515    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7516    #[serde(default)]
7517    pub acp: Option<McpAcpCapabilities>,
7518    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7519    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7520    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7521    ///
7522    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7523    #[serde_as(deserialize_as = "DefaultOnError")]
7524    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7525    #[serde(default)]
7526    #[serde(rename = "_meta")]
7527    pub meta: Option<Meta>,
7528}
7529
7530impl McpCapabilities {
7531    /// Builds an empty [`McpCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7532    #[must_use]
7533    pub fn new() -> Self {
7534        Self::default()
7535    }
7536
7537    /// Agent supports `stdio` MCP servers.
7538    ///
7539    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
7540    /// Supplying `{}` means the Agent supports stdio MCP server transports.
7541    #[must_use]
7542    pub fn stdio(mut self, stdio: impl IntoOption<McpStdioCapabilities>) -> Self {
7543        self.stdio = stdio.into_option();
7544        self
7545    }
7546
7547    /// Agent supports `http` MCP servers.
7548    ///
7549    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
7550    /// Supplying `{}` means the Agent supports HTTP MCP server transports.
7551    #[must_use]
7552    pub fn http(mut self, http: impl IntoOption<McpHttpCapabilities>) -> Self {
7553        self.http = http.into_option();
7554        self
7555    }
7556
7557    /// **UNSTABLE**
7558    ///
7559    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7560    ///
7561    /// Agent supports `acp` MCP servers.
7562    #[cfg(feature = "unstable_mcp_over_acp")]
7563    ///
7564    /// Omitted and `null` are equivalent and mean the Agent does not advertise support.
7565    /// Supplying `{}` means the Agent supports ACP MCP server transports.
7566    #[must_use]
7567    pub fn acp(mut self, acp: impl IntoOption<McpAcpCapabilities>) -> Self {
7568        self.acp = acp.into_option();
7569        self
7570    }
7571
7572    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7573    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7574    /// do not recognize.
7575    ///
7576    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7577    #[must_use]
7578    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7579        self.meta = meta.into_option();
7580        self
7581    }
7582}
7583
7584/// Capabilities for stdio MCP server transports.
7585///
7586/// Supplying `{}` means the Agent supports stdio MCP server transports.
7587#[serde_as]
7588#[skip_serializing_none]
7589#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7590#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7591#[non_exhaustive]
7592pub struct McpStdioCapabilities {
7593    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7594    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7595    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7596    ///
7597    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7598    #[serde_as(deserialize_as = "DefaultOnError")]
7599    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7600    #[serde(default)]
7601    #[serde(rename = "_meta")]
7602    pub meta: Option<Meta>,
7603}
7604
7605impl McpStdioCapabilities {
7606    /// Builds an empty [`McpStdioCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7607    #[must_use]
7608    pub fn new() -> Self {
7609        Self::default()
7610    }
7611
7612    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7613    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7614    /// do not recognize.
7615    ///
7616    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7617    #[must_use]
7618    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7619        self.meta = meta.into_option();
7620        self
7621    }
7622}
7623
7624/// Capabilities for HTTP MCP server transports.
7625///
7626/// Supplying `{}` means the Agent supports HTTP MCP server transports.
7627#[serde_as]
7628#[skip_serializing_none]
7629#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7630#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7631#[non_exhaustive]
7632pub struct McpHttpCapabilities {
7633    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7634    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7635    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7636    ///
7637    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7638    #[serde_as(deserialize_as = "DefaultOnError")]
7639    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7640    #[serde(default)]
7641    #[serde(rename = "_meta")]
7642    pub meta: Option<Meta>,
7643}
7644
7645impl McpHttpCapabilities {
7646    /// Builds an empty [`McpHttpCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7647    #[must_use]
7648    pub fn new() -> Self {
7649        Self::default()
7650    }
7651
7652    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7653    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7654    /// do not recognize.
7655    ///
7656    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7657    #[must_use]
7658    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7659        self.meta = meta.into_option();
7660        self
7661    }
7662}
7663
7664/// **UNSTABLE**
7665///
7666/// This capability is not part of the spec yet, and may be removed or changed at any point.
7667///
7668/// Capabilities for ACP MCP server transports.
7669///
7670/// Supplying `{}` means the Agent supports ACP MCP server transports.
7671#[cfg(feature = "unstable_mcp_over_acp")]
7672#[serde_as]
7673#[skip_serializing_none]
7674#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7675#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7676#[non_exhaustive]
7677pub struct McpAcpCapabilities {
7678    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7679    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7680    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7681    ///
7682    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7683    #[serde_as(deserialize_as = "DefaultOnError")]
7684    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7685    #[serde(default)]
7686    #[serde(rename = "_meta")]
7687    pub meta: Option<Meta>,
7688}
7689
7690#[cfg(feature = "unstable_mcp_over_acp")]
7691impl McpAcpCapabilities {
7692    /// Builds an empty [`McpAcpCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7693    #[must_use]
7694    pub fn new() -> Self {
7695        Self::default()
7696    }
7697
7698    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7699    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7700    /// do not recognize.
7701    ///
7702    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7703    #[must_use]
7704    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7705        self.meta = meta.into_option();
7706        self
7707    }
7708}
7709
7710/// Cancels the named session's active foreground work and earlier prompts not yet inserted.
7711/// It does not cancel later submissions or work in the session's latest `background` list.
7712///
7713/// See protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#cancellation)
7714#[serde_as]
7715#[skip_serializing_none]
7716#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7717#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7718#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CANCEL_METHOD_NAME)))]
7719#[serde(rename_all = "camelCase")]
7720#[non_exhaustive]
7721pub struct CancelSessionNotification {
7722    /// The ID of the session whose foreground work to cancel.
7723    pub session_id: SessionId,
7724    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7725    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7726    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7727    ///
7728    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7729    #[serde_as(deserialize_as = "DefaultOnError")]
7730    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7731    #[serde(default)]
7732    #[serde(rename = "_meta")]
7733    pub meta: Option<Meta>,
7734}
7735
7736impl CancelSessionNotification {
7737    /// Builds [`CancelSessionNotification`] with the required notification fields set. Optional fields start unset or empty.
7738    #[must_use]
7739    pub fn new(session_id: impl Into<SessionId>) -> Self {
7740        Self {
7741            session_id: session_id.into(),
7742            meta: None,
7743        }
7744    }
7745
7746    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
7747    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7748    /// do not recognize.
7749    ///
7750    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7751    #[must_use]
7752    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7753        self.meta = meta.into_option();
7754        self
7755    }
7756}
7757
7758// Method schema
7759
7760/// Names of all methods that Agents handle.
7761///
7762/// Provides a centralized definition of method names used in the protocol.
7763#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7764#[non_exhaustive]
7765pub struct AgentMethodNames {
7766    /// Method for initializing the connection.
7767    pub initialize: &'static str,
7768    /// Method for authenticating with the Agent.
7769    pub auth_login: &'static str,
7770    /// Method for listing configurable providers.
7771    #[cfg(feature = "unstable_llm_providers")]
7772    pub providers_list: &'static str,
7773    /// Method for setting provider configuration.
7774    #[cfg(feature = "unstable_llm_providers")]
7775    pub providers_set: &'static str,
7776    /// Method for disabling a provider.
7777    #[cfg(feature = "unstable_llm_providers")]
7778    pub providers_disable: &'static str,
7779    /// Method for creating a new session.
7780    pub session_new: &'static str,
7781    /// Method for setting a configuration option for a session.
7782    pub session_set_config_option: &'static str,
7783    /// Method for sending a prompt to the Agent.
7784    pub session_prompt: &'static str,
7785    /// Notification for cancelling operations.
7786    pub session_cancel: &'static str,
7787    /// Method for exchanging MCP-over-ACP messages.
7788    #[cfg(feature = "unstable_mcp_over_acp")]
7789    pub mcp_message: &'static str,
7790    /// Method for listing existing sessions.
7791    pub session_list: &'static str,
7792    /// Method for deleting an existing session.
7793    pub session_delete: &'static str,
7794    /// Method for forking an existing session.
7795    #[cfg(feature = "unstable_session_fork")]
7796    pub session_fork: &'static str,
7797    /// Method for archiving a session.
7798    #[cfg(feature = "unstable_session_archive")]
7799    pub session_archive: &'static str,
7800    /// Method for unarchiving a session.
7801    #[cfg(feature = "unstable_session_archive")]
7802    pub session_unarchive: &'static str,
7803    /// Method for checking the status of a session.
7804    #[cfg(feature = "unstable_session_status")]
7805    pub session_status: &'static str,
7806    /// Method for querying the config options a session would start with.
7807    #[cfg(feature = "unstable_session_options")]
7808    pub session_options: &'static str,
7809    /// Method for setting the title of a session.
7810    #[cfg(feature = "unstable_session_set_title")]
7811    pub session_set_title: &'static str,
7812    /// Method for resuming an existing session.
7813    pub session_resume: &'static str,
7814    /// Method for closing an active session.
7815    pub session_close: &'static str,
7816    /// Method for cancelling one tool call.
7817    pub tool_call_cancel: &'static str,
7818    /// Method for cancelling one terminal's process.
7819    pub terminal_cancel: &'static str,
7820    /// Method for logging out of an authenticated session.
7821    pub auth_logout: &'static str,
7822    /// Method for querying the Agent's authentication state.
7823    #[cfg(feature = "unstable_auth_status")]
7824    pub auth_status: &'static str,
7825}
7826
7827/// Constant containing all Agent method names.
7828pub const AGENT_METHOD_NAMES: AgentMethodNames = AgentMethodNames {
7829    initialize: INITIALIZE_METHOD_NAME,
7830    auth_login: AUTH_LOGIN_METHOD_NAME,
7831    #[cfg(feature = "unstable_llm_providers")]
7832    providers_list: PROVIDERS_LIST_METHOD_NAME,
7833    #[cfg(feature = "unstable_llm_providers")]
7834    providers_set: PROVIDERS_SET_METHOD_NAME,
7835    #[cfg(feature = "unstable_llm_providers")]
7836    providers_disable: PROVIDERS_DISABLE_METHOD_NAME,
7837    session_new: SESSION_NEW_METHOD_NAME,
7838    session_set_config_option: SESSION_SET_CONFIG_OPTION_METHOD_NAME,
7839    session_prompt: SESSION_PROMPT_METHOD_NAME,
7840    session_cancel: SESSION_CANCEL_METHOD_NAME,
7841    #[cfg(feature = "unstable_mcp_over_acp")]
7842    mcp_message: MCP_MESSAGE_METHOD_NAME,
7843    session_list: SESSION_LIST_METHOD_NAME,
7844    session_delete: SESSION_DELETE_METHOD_NAME,
7845    #[cfg(feature = "unstable_session_fork")]
7846    session_fork: SESSION_FORK_METHOD_NAME,
7847    #[cfg(feature = "unstable_session_archive")]
7848    session_archive: SESSION_ARCHIVE_METHOD_NAME,
7849    #[cfg(feature = "unstable_session_archive")]
7850    session_unarchive: SESSION_UNARCHIVE_METHOD_NAME,
7851    #[cfg(feature = "unstable_session_status")]
7852    session_status: SESSION_STATUS_METHOD_NAME,
7853    #[cfg(feature = "unstable_session_options")]
7854    session_options: SESSION_OPTIONS_METHOD_NAME,
7855    #[cfg(feature = "unstable_session_set_title")]
7856    session_set_title: SESSION_SET_TITLE_METHOD_NAME,
7857    session_resume: SESSION_RESUME_METHOD_NAME,
7858    session_close: SESSION_CLOSE_METHOD_NAME,
7859    tool_call_cancel: TOOL_CALL_CANCEL_METHOD_NAME,
7860    terminal_cancel: TERMINAL_CANCEL_METHOD_NAME,
7861    auth_logout: AUTH_LOGOUT_METHOD_NAME,
7862    #[cfg(feature = "unstable_auth_status")]
7863    auth_status: AUTH_STATUS_METHOD_NAME,
7864};
7865
7866/// Method name for the initialize request.
7867pub(crate) const INITIALIZE_METHOD_NAME: &str = "initialize";
7868/// Method name for the `auth/login` request.
7869pub(crate) const AUTH_LOGIN_METHOD_NAME: &str = "auth/login";
7870/// Method name for listing configurable providers.
7871#[cfg(feature = "unstable_llm_providers")]
7872pub(crate) const PROVIDERS_LIST_METHOD_NAME: &str = "providers/list";
7873/// Method name for setting provider configuration.
7874#[cfg(feature = "unstable_llm_providers")]
7875pub(crate) const PROVIDERS_SET_METHOD_NAME: &str = "providers/set";
7876/// Method name for disabling a provider.
7877#[cfg(feature = "unstable_llm_providers")]
7878pub(crate) const PROVIDERS_DISABLE_METHOD_NAME: &str = "providers/disable";
7879/// Method name for creating a new session.
7880pub(crate) const SESSION_NEW_METHOD_NAME: &str = "session/new";
7881/// Method name for setting a configuration option for a session.
7882pub(crate) const SESSION_SET_CONFIG_OPTION_METHOD_NAME: &str = "session/set_config_option";
7883/// Method name for sending a prompt.
7884pub(crate) const SESSION_PROMPT_METHOD_NAME: &str = "session/prompt";
7885/// Method name for the cancel notification.
7886pub(crate) const SESSION_CANCEL_METHOD_NAME: &str = "session/cancel";
7887/// Method name for listing existing sessions.
7888pub(crate) const SESSION_LIST_METHOD_NAME: &str = "session/list";
7889/// Method name for deleting an existing session.
7890pub(crate) const SESSION_DELETE_METHOD_NAME: &str = "session/delete";
7891/// Method name for forking an existing session.
7892#[cfg(feature = "unstable_session_fork")]
7893pub(crate) const SESSION_FORK_METHOD_NAME: &str = "session/fork";
7894/// Method name for archiving a session.
7895#[cfg(feature = "unstable_session_archive")]
7896pub(crate) const SESSION_ARCHIVE_METHOD_NAME: &str = "session/archive";
7897/// Method name for unarchiving a session.
7898#[cfg(feature = "unstable_session_archive")]
7899pub(crate) const SESSION_UNARCHIVE_METHOD_NAME: &str = "session/unarchive";
7900/// Method name for checking the status of a session.
7901#[cfg(feature = "unstable_session_status")]
7902pub(crate) const SESSION_STATUS_METHOD_NAME: &str = "session/status";
7903/// Method name for querying the config options a session would start with.
7904#[cfg(feature = "unstable_session_options")]
7905pub(crate) const SESSION_OPTIONS_METHOD_NAME: &str = "session/options";
7906/// Method name for setting the title of a session.
7907#[cfg(feature = "unstable_session_set_title")]
7908pub(crate) const SESSION_SET_TITLE_METHOD_NAME: &str = "session/set_title";
7909/// Method name for resuming an existing session.
7910pub(crate) const SESSION_RESUME_METHOD_NAME: &str = "session/resume";
7911/// Method name for closing an active session.
7912pub(crate) const SESSION_CLOSE_METHOD_NAME: &str = "session/close";
7913/// Method name for cancelling one tool call.
7914pub(crate) const TOOL_CALL_CANCEL_METHOD_NAME: &str = "tool_call/cancel";
7915/// Method name for cancelling one terminal's process.
7916pub(crate) const TERMINAL_CANCEL_METHOD_NAME: &str = "terminal/cancel";
7917/// Method name for the `auth/logout` request.
7918pub(crate) const AUTH_LOGOUT_METHOD_NAME: &str = "auth/logout";
7919/// Method name for the `auth/status` request.
7920#[cfg(feature = "unstable_auth_status")]
7921pub(crate) const AUTH_STATUS_METHOD_NAME: &str = "auth/status";
7922
7923/// All possible requests that a Client can send to an Agent.
7924///
7925/// This enum is used internally for routing RPC requests. You typically won't need
7926/// to use this directly.
7927///
7928/// This enum encompasses all method calls from Client to Agent.
7929#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7930#[derive(Clone, Debug, Serialize, Deserialize)]
7931#[serde(untagged)]
7932#[cfg_attr(feature = "schemars", schemars(inline))]
7933#[non_exhaustive]
7934pub enum ClientRequest {
7935    /// Establishes the connection with a Client and negotiates protocol capabilities.
7936    ///
7937    /// This method is called at the beginning of the connection, before any other request, to:
7938    /// - Negotiate the protocol version to use
7939    /// - Exchange capability information between Client and Agent
7940    /// - Determine available authentication methods
7941    ///
7942    /// The Client MAY repeat it before its first other request. The latest successful
7943    /// `initialize` is authoritative.
7944    ///
7945    /// The Agent responds with its supported protocol version and capabilities.
7946    ///
7947    /// See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/v2/initialization)
7948    InitializeRequest(Box<InitializeRequest>),
7949    /// Authenticates the Client using the specified authentication method.
7950    ///
7951    /// Agents MUST support this method when their `initialize` response included
7952    /// a non-empty `authMethods` list. Clients MUST call this method only
7953    /// with a method whose type defines a protocol-driven login flow, and MUST NOT
7954    /// call it when `authMethods` was omitted or empty.
7955    ///
7956    /// Called when the Agent requires authentication before allowing session creation.
7957    /// The Client provides the authentication method ID that was advertised during initialization.
7958    ///
7959    /// After successful authentication, the Client can proceed to create sessions with
7960    /// `session/new` without receiving a `-32000` (Authentication required) error.
7961    ///
7962    /// See protocol docs: [Authentication](https://agentclientprotocol.com/protocol/v2/authentication)
7963    LoginAuthRequest(Box<LoginAuthRequest>),
7964    /// **UNSTABLE**
7965    ///
7966    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7967    ///
7968    /// Lists providers that can be configured by the Client.
7969    #[cfg(feature = "unstable_llm_providers")]
7970    ListProvidersRequest(Box<ListProvidersRequest>),
7971    /// **UNSTABLE**
7972    ///
7973    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7974    ///
7975    /// Replaces the configuration for a provider.
7976    #[cfg(feature = "unstable_llm_providers")]
7977    SetProviderRequest(Box<SetProviderRequest>),
7978    /// **UNSTABLE**
7979    ///
7980    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7981    ///
7982    /// Disables a provider.
7983    #[cfg(feature = "unstable_llm_providers")]
7984    DisableProviderRequest(Box<DisableProviderRequest>),
7985    /// Logs out of the current authenticated state.
7986    ///
7987    /// Agents MUST support this method when their `initialize` response included
7988    /// a non-empty `authMethods` list. Clients MUST NOT call this method
7989    /// when `authMethods` was omitted or empty.
7990    ///
7991    /// After a successful logout, authentication-gated requests require the
7992    /// Client to complete an advertised authentication flow again. There is no
7993    /// guarantee about the behavior of already running sessions.
7994    LogoutAuthRequest(Box<LogoutAuthRequest>),
7995    /// **UNSTABLE**
7996    ///
7997    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7998    ///
7999    /// Queries the Agent's current authentication state.
8000    ///
8001    /// This method is only available if the Agent advertises the `auth.status` capability.
8002    /// It MUST NOT change any Agent state, and Agents MUST NOT reject it with `-32000` (Authentication required).
8003    #[cfg(feature = "unstable_auth_status")]
8004    AuthStatusRequest(Box<AuthStatusRequest>),
8005    /// Creates a new conversation session with the Agent.
8006    ///
8007    /// Sessions represent independent conversation contexts with their own history and state.
8008    ///
8009    /// The Agent:
8010    /// - Creates a new session context
8011    /// - Connects to the specified MCP servers
8012    /// - Returns a unique session ID for future requests
8013    ///
8014    /// Fails with `-32000` (Authentication required) if the Agent requires authentication.
8015    ///
8016    /// See protocol docs: [Session Setup](https://agentclientprotocol.com/protocol/v2/session-setup)
8017    NewSessionRequest(Box<NewSessionRequest>),
8018    /// Lists existing sessions known to the Agent.
8019    ///
8020    /// The Agent returns metadata about sessions, with optional filtering and pagination.
8021    ListSessionsRequest(Box<ListSessionsRequest>),
8022    /// Deletes an existing session from `session/list`.
8023    ///
8024    /// This method is only available if the Agent advertises the `session.delete` capability.
8025    DeleteSessionRequest(Box<DeleteSessionRequest>),
8026    #[cfg(feature = "unstable_session_fork")]
8027    /// **UNSTABLE**
8028    ///
8029    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8030    ///
8031    /// Forks an existing session to create a new independent session.
8032    ///
8033    /// This method is only available if the Agent advertises the `session.fork` capability.
8034    ///
8035    /// The Agent creates a new session with the same conversation context as the
8036    /// original. The fork can be used for operations like generating summaries without
8037    /// affecting the original session's history.
8038    ///
8039    /// As with `session/new`, the forked session is active once the Agent responds,
8040    /// set up with the request's `cwd`, `additionalDirectories`, and `mcpServers`.
8041    /// The Client can prompt it without calling `session/resume` first.
8042    ForkSessionRequest(Box<ForkSessionRequest>),
8043    #[cfg(feature = "unstable_session_archive")]
8044    /// **UNSTABLE**
8045    ///
8046    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8047    ///
8048    /// Archives a session, hiding it from default `session/list` results.
8049    ///
8050    /// This method is only available if the Agent advertises the `session.archive` capability.
8051    ArchiveSessionRequest(Box<ArchiveSessionRequest>),
8052    #[cfg(feature = "unstable_session_archive")]
8053    /// **UNSTABLE**
8054    ///
8055    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8056    ///
8057    /// Unarchives a session, returning it to default `session/list` results.
8058    ///
8059    /// This method is only available if the Agent advertises the `session.archive` capability.
8060    UnarchiveSessionRequest(Box<UnarchiveSessionRequest>),
8061    #[cfg(feature = "unstable_session_status")]
8062    /// **UNSTABLE**
8063    ///
8064    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8065    ///
8066    /// Checks whether the Agent has a session in memory, without changing it.
8067    ///
8068    /// This method is only available if the Agent advertises the `session.status` capability.
8069    SessionStatusRequest(Box<SessionStatusRequest>),
8070    #[cfg(feature = "unstable_session_options")]
8071    /// **UNSTABLE**
8072    ///
8073    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8074    ///
8075    /// Returns the config options a session would start with, without creating or resuming a session.
8076    ///
8077    /// This method is only available if the Agent advertises the `session.options` capability.
8078    SessionOptionsRequest(Box<SessionOptionsRequest>),
8079    #[cfg(feature = "unstable_session_set_title")]
8080    /// **UNSTABLE**
8081    ///
8082    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8083    ///
8084    /// Sets the title of a session.
8085    ///
8086    /// This method is only available if the Agent advertises the `session.title` capability.
8087    ///
8088    /// The session does not need to be active on the connection. The Agent stores the
8089    /// title and returns the stored title, which may be normalized.
8090    SetSessionTitleRequest(Box<SetSessionTitleRequest>),
8091    /// Resumes an existing session.
8092    ///
8093    /// The Agent resumes the session context so that the conversation
8094    /// can continue. If `replayFrom` is set, the Agent replays
8095    /// retained conversation history before responding.
8096    ResumeSessionRequest(Box<ResumeSessionRequest>),
8097    /// Closes an active session and frees up any resources associated with it.
8098    ///
8099    /// The Agent MUST cancel any ongoing work as if `session/cancel` was called, stop the
8100    /// session's background work, and then free the resources associated with the session.
8101    CloseSessionRequest(Box<CloseSessionRequest>),
8102    /// Cancels one tool call without cancelling the rest of the session's work.
8103    ///
8104    /// This method is only available while the tool call advertises `capabilities.cancel`.
8105    /// The response means the Agent accepted the cancellation. A final `tool_call_update`
8106    /// confirms it.
8107    CancelToolCallRequest(Box<CancelToolCallRequest>),
8108    /// Stops one terminal's process without cancelling the rest of the session's work.
8109    ///
8110    /// This method is only available while the terminal advertises `capabilities.cancel`.
8111    /// The response means the Agent accepted the cancellation. A `terminal_update` with
8112    /// `exitStatus` confirms it.
8113    CancelTerminalRequest(Box<CancelTerminalRequest>),
8114    /// Sets the current value for a session configuration option.
8115    SetSessionConfigOptionRequest(Box<SetSessionConfigOptionRequest>),
8116    /// Processes a user prompt within a session.
8117    ///
8118    /// Acceptance means adding a logical user message with an ID and a position
8119    /// relative to other messages in the ACP conversation, not receipt or queueing.
8120    /// The Agent MUST return the inserted message's ID without waiting for
8121    /// processing to finish.
8122    ///
8123    /// The Agent reports the user message with the same ID through `session/update`.
8124    /// This notification can arrive before or after the response, and MUST NOT
8125    /// precede insertion. Processing state, output, tool calls, and completion are
8126    /// also reported through session updates.
8127    ///
8128    /// An error response means the user message was not inserted. Once it is
8129    /// inserted, the Agent MUST NOT answer with an error, even if the work fails
8130    /// before the response is sent. It ends that work with the `error` stop reason.
8131    ///
8132    /// A rejected submission produces no user-message updates. Foreground state
8133    /// follows its normal lifecycle independently of the request outcome:
8134    /// `running` may precede insertion, and rejection alone does not imply `idle`.
8135    ///
8136    /// See protocol docs: [Prompt Lifecycle](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle)
8137    PromptRequest(Box<PromptRequest>),
8138    /// Handles extension method requests from the Client.
8139    ///
8140    /// Extension methods are custom methods that are not part of the ACP spec.
8141    ///
8142    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
8143    ExtMethodRequest(Box<ExtRequest>),
8144}
8145
8146impl_request_dispatch! {
8147    ClientRequest => AgentResponse {
8148        InitializeRequest => InitializeResponse: AGENT_METHOD_NAMES.initialize,
8149        LoginAuthRequest => LoginAuthResponse: AGENT_METHOD_NAMES.auth_login,
8150        #[cfg(feature = "unstable_llm_providers")]
8151        ListProvidersRequest => ListProvidersResponse: AGENT_METHOD_NAMES.providers_list,
8152        #[cfg(feature = "unstable_llm_providers")]
8153        SetProviderRequest => SetProviderResponse: AGENT_METHOD_NAMES.providers_set,
8154        #[cfg(feature = "unstable_llm_providers")]
8155        DisableProviderRequest => DisableProviderResponse: AGENT_METHOD_NAMES.providers_disable,
8156        LogoutAuthRequest => LogoutAuthResponse: AGENT_METHOD_NAMES.auth_logout,
8157        #[cfg(feature = "unstable_auth_status")]
8158        AuthStatusRequest => AuthStatusResponse: AGENT_METHOD_NAMES.auth_status,
8159        NewSessionRequest => NewSessionResponse: AGENT_METHOD_NAMES.session_new,
8160        ListSessionsRequest => ListSessionsResponse: AGENT_METHOD_NAMES.session_list,
8161        DeleteSessionRequest => DeleteSessionResponse: AGENT_METHOD_NAMES.session_delete,
8162        #[cfg(feature = "unstable_session_fork")]
8163        ForkSessionRequest => ForkSessionResponse: AGENT_METHOD_NAMES.session_fork,
8164        #[cfg(feature = "unstable_session_archive")]
8165        ArchiveSessionRequest => ArchiveSessionResponse: AGENT_METHOD_NAMES.session_archive,
8166        #[cfg(feature = "unstable_session_archive")]
8167        UnarchiveSessionRequest => UnarchiveSessionResponse: AGENT_METHOD_NAMES.session_unarchive,
8168        #[cfg(feature = "unstable_session_status")]
8169        SessionStatusRequest => SessionStatusResponse: AGENT_METHOD_NAMES.session_status,
8170        #[cfg(feature = "unstable_session_options")]
8171        SessionOptionsRequest => SessionOptionsResponse: AGENT_METHOD_NAMES.session_options,
8172        #[cfg(feature = "unstable_session_set_title")]
8173        SetSessionTitleRequest => SetSessionTitleResponse: AGENT_METHOD_NAMES.session_set_title,
8174        ResumeSessionRequest => ResumeSessionResponse: AGENT_METHOD_NAMES.session_resume,
8175        CloseSessionRequest => CloseSessionResponse: AGENT_METHOD_NAMES.session_close,
8176        CancelToolCallRequest => CancelToolCallResponse: AGENT_METHOD_NAMES.tool_call_cancel,
8177        CancelTerminalRequest => CancelTerminalResponse: AGENT_METHOD_NAMES.terminal_cancel,
8178        SetSessionConfigOptionRequest => SetSessionConfigOptionResponse: AGENT_METHOD_NAMES.session_set_config_option,
8179        PromptRequest => PromptResponse: AGENT_METHOD_NAMES.session_prompt,
8180    }
8181    extension ExtMethodRequest(Box<ExtRequest>) => ExtMethodResponse;
8182}
8183
8184/// All possible responses that an Agent can send to a Client.
8185///
8186/// This enum is used internally for routing RPC responses. You typically won't need
8187/// to use this directly. The connection handles the responses automatically.
8188///
8189/// These are responses to the corresponding `ClientRequest` variants.
8190#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
8191#[derive(Clone, Debug, Serialize, Deserialize)]
8192#[serde(untagged)]
8193#[cfg_attr(feature = "schemars", schemars(inline))]
8194#[non_exhaustive]
8195pub enum AgentResponse {
8196    /// Successful result returned for a `initialize` request.
8197    InitializeResponse(Box<InitializeResponse>),
8198    /// Successful result returned for an `auth/login` request.
8199    LoginAuthResponse(#[serde(default)] Box<LoginAuthResponse>),
8200    /// Successful result returned for a `providers/list` request.
8201    #[cfg(feature = "unstable_llm_providers")]
8202    ListProvidersResponse(Box<ListProvidersResponse>),
8203    /// Successful result returned for a `providers/set` request.
8204    #[cfg(feature = "unstable_llm_providers")]
8205    SetProviderResponse(#[serde(default)] Box<SetProviderResponse>),
8206    /// Successful result returned for a `providers/disable` request.
8207    #[cfg(feature = "unstable_llm_providers")]
8208    DisableProviderResponse(#[serde(default)] Box<DisableProviderResponse>),
8209    /// Successful result returned for an `auth/logout` request.
8210    LogoutAuthResponse(#[serde(default)] Box<LogoutAuthResponse>),
8211    /// Successful result returned for an `auth/status` request.
8212    #[cfg(feature = "unstable_auth_status")]
8213    AuthStatusResponse(Box<AuthStatusResponse>),
8214    /// Successful result returned for a `session/new` request.
8215    NewSessionResponse(Box<NewSessionResponse>),
8216    /// Successful result returned for a `session/list` request.
8217    ListSessionsResponse(Box<ListSessionsResponse>),
8218    /// Successful result returned for a `session/delete` request.
8219    DeleteSessionResponse(#[serde(default)] Box<DeleteSessionResponse>),
8220    /// Successful result returned for a `session/fork` request.
8221    #[cfg(feature = "unstable_session_fork")]
8222    ForkSessionResponse(Box<ForkSessionResponse>),
8223    /// Successful result returned for a `session/archive` request.
8224    #[cfg(feature = "unstable_session_archive")]
8225    ArchiveSessionResponse(#[serde(default)] Box<ArchiveSessionResponse>),
8226    /// Successful result returned for a `session/unarchive` request.
8227    #[cfg(feature = "unstable_session_archive")]
8228    UnarchiveSessionResponse(#[serde(default)] Box<UnarchiveSessionResponse>),
8229    /// Successful result returned for a `session/status` request.
8230    #[cfg(feature = "unstable_session_status")]
8231    SessionStatusResponse(Box<SessionStatusResponse>),
8232    /// Successful result returned for a `session/options` request.
8233    #[cfg(feature = "unstable_session_options")]
8234    SessionOptionsResponse(#[serde(default)] Box<SessionOptionsResponse>),
8235    /// Successful result returned for a `session/set_title` request.
8236    #[cfg(feature = "unstable_session_set_title")]
8237    SetSessionTitleResponse(Box<SetSessionTitleResponse>),
8238    /// Successful result returned for a `session/resume` request.
8239    ResumeSessionResponse(#[serde(default)] Box<ResumeSessionResponse>),
8240    /// Successful result returned for a `session/close` request.
8241    CloseSessionResponse(#[serde(default)] Box<CloseSessionResponse>),
8242    /// Successful result returned for a `tool_call/cancel` request.
8243    CancelToolCallResponse(#[serde(default)] Box<CancelToolCallResponse>),
8244    /// Successful result returned for a `terminal/cancel` request.
8245    CancelTerminalResponse(#[serde(default)] Box<CancelTerminalResponse>),
8246    /// Successful result returned for a `session/set_config_option` request.
8247    SetSessionConfigOptionResponse(Box<SetSessionConfigOptionResponse>),
8248    /// Successful result returned for a `session/prompt` request.
8249    PromptResponse(Box<PromptResponse>),
8250    /// Successful result returned by an extension method outside the core ACP method set.
8251    ExtMethodResponse(Box<ExtResponse>),
8252}
8253
8254/// All possible notifications that a Client can send to an Agent.
8255///
8256/// This enum is used internally for routing RPC notifications. You typically won't need
8257/// to use this directly.
8258///
8259/// Notifications do not expect a response.
8260#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
8261#[derive(Clone, Debug, Serialize, Deserialize)]
8262#[serde(untagged)]
8263#[cfg_attr(feature = "schemars", schemars(inline))]
8264#[non_exhaustive]
8265pub enum ClientNotification {
8266    /// Cancels the named session's active foreground work and earlier prompts not yet inserted.
8267    /// The Agent MUST answer those uninserted prompts with `-32800`. Inserted prompts still
8268    /// succeed with their `messageId`. This cancellation does not cover later submissions.
8269    ///
8270    /// Work in the latest `background` list is not covered and keeps running. The
8271    /// Agent MAY stop background activity it does not list.
8272    ///
8273    /// Upon receiving this notification, the Agent SHOULD stop all language model
8274    /// requests and all tool call invocations of the cancelled foreground work as soon
8275    /// as possible.
8276    ///
8277    /// The Agent MUST stop waiting for pending `session/request_permission` requests of
8278    /// the cancelled work and treat them as not approved. It MUST cancel each of them
8279    /// with `$/cancel_request`.
8280    ///
8281    /// When cancellation stops active foreground work, the Agent MUST send that work's
8282    /// pending updates, then an idle `state_update` with `stopReason: "cancelled"`,
8283    /// before starting new foreground work in the same session. A later prompt can be
8284    /// inserted and acknowledged before that idle update, or held with its response
8285    /// pending. Listed background work can report updates before or after it.
8286    /// No additional idle update is required if no foreground work was active.
8287    ///
8288    /// After cancellation completes, the Agent SHOULD ignore late answers rather
8289    /// than use them to resume the cancelled work.
8290    ///
8291    /// Agents MUST catch errors caused by aborting cancelled work and report the
8292    /// `cancelled` stop reason, not `error`.
8293    ///
8294    /// See protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#cancellation)
8295    CancelSessionNotification(Box<CancelSessionNotification>),
8296    /// **UNSTABLE**
8297    ///
8298    /// This capability is not part of the spec yet, and may be removed or changed at any point.
8299    ///
8300    /// Sends an MCP-over-ACP notification.
8301    #[cfg(feature = "unstable_mcp_over_acp")]
8302    MessageMcpNotification(Box<MessageMcpNotification>),
8303    /// Handles extension notifications from the Client.
8304    ///
8305    /// Extension notifications are custom one-way messages that are not part of the ACP spec.
8306    ///
8307    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
8308    ExtNotification(Box<ExtNotification>),
8309}
8310
8311impl_message_dispatch! {
8312    ClientNotification {
8313        CancelSessionNotification => AGENT_METHOD_NAMES.session_cancel,
8314        #[cfg(feature = "unstable_mcp_over_acp")]
8315        MessageMcpNotification => AGENT_METHOD_NAMES.mcp_message,
8316    }
8317    extension ExtNotification(Box<ExtNotification>);
8318}
8319
8320#[cfg(test)]
8321mod test_serialization {
8322    use std::path::PathBuf;
8323
8324    use super::*;
8325    use serde_json::json;
8326
8327    fn test_meta() -> Meta {
8328        json!({ "source": "test" }).as_object().unwrap().clone()
8329    }
8330
8331    #[test]
8332    fn list_sessions_cursor_and_session_directories_are_strict() {
8333        for cursor in [json!(null), json!("next")] {
8334            let response = json!({ "sessions": [], "nextCursor": cursor });
8335            serde_json::from_value::<ListSessionsResponse>(response).unwrap();
8336        }
8337        let malformed = json!({ "sessions": [], "nextCursor": 42 });
8338        assert!(serde_json::from_value::<ListSessionsResponse>(malformed).is_err());
8339
8340        let session = |dirs: serde_json::Value| json!({ "sessionId": "s", "cwd": "/w", "additionalDirectories": dirs });
8341        let info: SessionInfo = serde_json::from_value(session(json!(null))).unwrap();
8342        assert_eq!(info.additional_directories, Vec::<AbsolutePath>::new());
8343        for bad in [json!(["/a", 42]), json!("/a")] {
8344            assert!(serde_json::from_value::<SessionInfo>(session(bad)).is_err());
8345        }
8346        // A session with malformed directories is skipped, not truncated.
8347        let response = json!({ "sessions": [session(json!(["/a", 42]))] });
8348        let response: ListSessionsResponse = serde_json::from_value(response).unwrap();
8349        assert_eq!(response.sessions, Vec::<SessionInfo>::new());
8350    }
8351
8352    #[test]
8353    fn other_fallbacks_preserve_optional_fields_verbatim() {
8354        let valid = json!({ "type": "_custom", "methodId": "m", "name": "M",
8355            "description": "d", "_meta": { "k": 1 } });
8356        let method: AuthMethod = serde_json::from_value(valid.clone()).unwrap();
8357        assert_eq!(method.description(), Some("d"));
8358        assert_eq!(
8359            method.meta(),
8360            Some(&json!({ "k": 1 }).as_object().unwrap().clone())
8361        );
8362        assert_eq!(serde_json::to_value(&method).unwrap(), valid);
8363
8364        // Malformed optional fields are kept as sent and read as absent.
8365        let malformed = json!({ "type": "_custom", "methodId": "m", "name": "M",
8366            "description": 42, "_meta": "bad", "extra": true });
8367        let method: AuthMethod = serde_json::from_value(malformed.clone()).unwrap();
8368        assert_eq!(method.description(), None);
8369        assert_eq!(method.meta(), None);
8370        assert_eq!(serde_json::to_value(&method).unwrap(), malformed);
8371
8372        let replay = json!({ "type": "_custom", "_meta": "bad", "cursor": 3 });
8373        let decoded: ReplayFrom = serde_json::from_value(replay.clone()).unwrap();
8374        assert_eq!(serde_json::to_value(&decoded).unwrap(), replay);
8375    }
8376
8377    fn serialized_meta_key_count(value: &impl serde::Serialize) -> usize {
8378        serde_json::to_string(value)
8379            .unwrap()
8380            .matches("\"_meta\"")
8381            .count()
8382    }
8383
8384    #[test]
8385    fn prompt_response_without_metadata_round_trips() {
8386        let response = PromptResponse::new(MessageId::new("message-1"));
8387        let serialized = serde_json::to_value(&response).unwrap();
8388        assert_eq!(serialized, json!({ "messageId": "message-1" }));
8389        assert_eq!(
8390            serde_json::from_value::<PromptResponse>(serialized).unwrap(),
8391            response
8392        );
8393        assert_eq!(
8394            serde_json::from_value::<PromptResponse>(json!({
8395                "messageId": "message-1",
8396                "_meta": null
8397            }))
8398            .unwrap(),
8399            response
8400        );
8401    }
8402
8403    #[test]
8404    fn prompt_response_requires_message_id_and_preserves_metadata_tolerance() {
8405        let response = PromptResponse::new("message-1").meta(test_meta());
8406        let serialized = serde_json::to_value(&response).unwrap();
8407        assert_eq!(
8408            serialized,
8409            json!({
8410                "messageId": "message-1",
8411                "_meta": { "source": "test" }
8412            })
8413        );
8414
8415        let deserialized: PromptResponse = serde_json::from_value(serialized).unwrap();
8416        assert_eq!(deserialized.message_id, MessageId::new("message-1"));
8417        assert_eq!(deserialized.meta, Some(test_meta()));
8418
8419        let malformed_meta: PromptResponse = serde_json::from_value(json!({
8420            "messageId": "message-2",
8421            "_meta": false
8422        }))
8423        .unwrap();
8424        assert_eq!(malformed_meta.message_id, MessageId::new("message-2"));
8425        assert_eq!(malformed_meta.meta, None);
8426
8427        for invalid in [
8428            json!({}),
8429            json!({ "messageId": null }),
8430            json!({ "messageId": 1 }),
8431            json!({ "messageId": false }),
8432            json!({ "messageId": {} }),
8433            json!({ "messageId": [] }),
8434        ] {
8435            assert!(
8436                serde_json::from_value::<PromptResponse>(invalid).is_err(),
8437                "missing, null, and non-string message IDs must be rejected"
8438            );
8439        }
8440    }
8441
8442    #[cfg(feature = "schemars")]
8443    #[test]
8444    fn prompt_response_schema_requires_non_null_string_message_id_reference() {
8445        let schema = serde_json::to_value(schemars::schema_for!(PromptResponse)).unwrap();
8446
8447        assert_eq!(schema["required"], json!(["messageId"]));
8448        assert_eq!(
8449            schema["properties"]["messageId"]["$ref"],
8450            "#/$defs/MessageId"
8451        );
8452        assert_eq!(schema["$defs"]["MessageId"]["type"], "string");
8453    }
8454
8455    #[test]
8456    fn test_initialize_capabilities_default_on_malformed_values() {
8457        let request: InitializeRequest = serde_json::from_value(json!({
8458            "protocolVersion": 2,
8459            "capabilities": false,
8460            "info": {
8461                "name": "client",
8462                "version": "1.0.0"
8463            }
8464        }))
8465        .unwrap();
8466        assert_eq!(request.capabilities, ClientCapabilities::default());
8467
8468        let response: InitializeResponse = serde_json::from_value(json!({
8469            "protocolVersion": 2,
8470            "capabilities": false,
8471            "info": {
8472                "name": "agent",
8473                "version": "1.0.0"
8474            }
8475        }))
8476        .unwrap();
8477        assert_eq!(response.capabilities, AgentCapabilities::default());
8478    }
8479
8480    #[test]
8481    fn test_agent_capabilities_default_on_malformed_values() {
8482        let capabilities: AgentCapabilities = serde_json::from_value(json!({
8483            "session": false,
8484            "auth": false
8485        }))
8486        .unwrap();
8487
8488        assert!(capabilities.session.is_none());
8489        assert_eq!(capabilities.auth, None);
8490    }
8491
8492    #[test]
8493    fn test_mcp_server_stdio_serialization() {
8494        let server = McpServer::Stdio(
8495            McpServerStdio::new("test-server", "/usr/bin/server")
8496                .args(vec!["--port".to_string(), "3000".to_string()])
8497                .env(vec![EnvVariable::new("API_KEY", "secret123")]),
8498        );
8499
8500        let json = serde_json::to_value(&server).unwrap();
8501        assert_eq!(
8502            json,
8503            json!({
8504                "type": "stdio",
8505                "name": "test-server",
8506                "command": "/usr/bin/server",
8507                "args": ["--port", "3000"],
8508                "env": [
8509                    {
8510                        "name": "API_KEY",
8511                        "value": "secret123"
8512                    }
8513                ]
8514            })
8515        );
8516
8517        let deserialized: McpServer = serde_json::from_value(json).unwrap();
8518        match deserialized {
8519            McpServer::Stdio(McpServerStdio {
8520                name,
8521                command,
8522                args,
8523                env,
8524                meta: _,
8525            }) => {
8526                assert_eq!(name, "test-server");
8527                assert_eq!(command, AbsolutePath::new("/usr/bin/server"));
8528                assert_eq!(args, vec!["--port", "3000"]);
8529                assert_eq!(env.len(), 1);
8530                assert_eq!(env[0].name, "API_KEY");
8531                assert_eq!(env[0].value, "secret123");
8532            }
8533            _ => panic!("Expected Stdio variant"),
8534        }
8535    }
8536
8537    #[test]
8538    fn test_mcp_server_empty_arrays_are_optional() {
8539        let stdio = McpServer::Stdio(McpServerStdio::new("test-server", "/usr/bin/server"));
8540        assert_eq!(
8541            serde_json::to_value(&stdio).unwrap(),
8542            json!({
8543                "type": "stdio",
8544                "name": "test-server",
8545                "command": "/usr/bin/server"
8546            })
8547        );
8548
8549        let McpServer::Stdio(McpServerStdio { args, env, .. }) =
8550            serde_json::from_value::<McpServer>(json!({
8551                "type": "stdio",
8552                "name": "test-server",
8553                "command": "/usr/bin/server"
8554            }))
8555            .unwrap()
8556        else {
8557            panic!("Expected Stdio variant");
8558        };
8559        assert_eq!(args, Vec::<String>::new());
8560        assert_eq!(env, []);
8561
8562        let http = McpServer::Http(McpServerHttp::new("http-server", "https://api.example.com"));
8563        assert_eq!(
8564            serde_json::to_value(&http).unwrap(),
8565            json!({
8566                "type": "http",
8567                "name": "http-server",
8568                "url": "https://api.example.com"
8569            })
8570        );
8571
8572        let McpServer::Http(McpServerHttp { headers, .. }) =
8573            serde_json::from_value::<McpServer>(json!({
8574                "type": "http",
8575                "name": "http-server",
8576                "url": "https://api.example.com"
8577            }))
8578            .unwrap()
8579        else {
8580            panic!("Expected Http variant");
8581        };
8582        assert_eq!(headers, []);
8583    }
8584
8585    #[test]
8586    fn test_mcp_server_unknown_transport_serialization() {
8587        let json = json!({
8588            "type": "websocket",
8589            "name": "future-server",
8590            "url": "wss://example.com/mcp",
8591            "protocolVersion": "2026-01-01"
8592        });
8593
8594        let deserialized: McpServer = serde_json::from_value(json.clone()).unwrap();
8595        let McpServer::Other(OtherMcpServer { type_, fields }) = &deserialized else {
8596            panic!("Expected Other variant");
8597        };
8598
8599        assert_eq!(type_, "websocket");
8600        assert_eq!(fields["name"], "future-server");
8601        assert_eq!(fields["url"], "wss://example.com/mcp");
8602        assert_eq!(fields["protocolVersion"], "2026-01-01");
8603        assert_eq!(serde_json::to_value(&deserialized).unwrap(), json);
8604    }
8605
8606    #[test]
8607    fn test_mcp_server_stdio_requires_type() {
8608        let result = serde_json::from_value::<McpServer>(json!({
8609            "name": "test-server",
8610            "command": "/usr/bin/server",
8611            "args": [],
8612            "env": []
8613        }));
8614
8615        assert!(result.is_err());
8616    }
8617
8618    #[test]
8619    fn test_mcp_server_unknown_does_not_hide_malformed_known_transport() {
8620        let result = serde_json::from_value::<McpServer>(json!({
8621            "type": "stdio",
8622            "name": "test-server",
8623            "args": [],
8624            "env": []
8625        }));
8626
8627        assert!(result.is_err());
8628    }
8629
8630    #[test]
8631    fn test_mcp_server_http_serialization() {
8632        let server = McpServer::Http(
8633            McpServerHttp::new("http-server", "https://api.example.com").headers(vec![
8634                HttpHeader::new("Authorization", "Bearer token123"),
8635                HttpHeader::new("Content-Type", "application/json"),
8636            ]),
8637        );
8638
8639        let json = serde_json::to_value(&server).unwrap();
8640        assert_eq!(
8641            json,
8642            json!({
8643                "type": "http",
8644                "name": "http-server",
8645                "url": "https://api.example.com",
8646                "headers": [
8647                    {
8648                        "name": "Authorization",
8649                        "value": "Bearer token123"
8650                    },
8651                    {
8652                        "name": "Content-Type",
8653                        "value": "application/json"
8654                    }
8655                ]
8656            })
8657        );
8658
8659        let deserialized: McpServer = serde_json::from_value(json).unwrap();
8660        match deserialized {
8661            McpServer::Http(McpServerHttp {
8662                name,
8663                url,
8664                headers,
8665                meta: _,
8666            }) => {
8667                assert_eq!(name, "http-server");
8668                assert_eq!(url, "https://api.example.com");
8669                assert_eq!(headers.len(), 2);
8670                assert_eq!(headers[0].name, "Authorization");
8671                assert_eq!(headers[0].value, "Bearer token123");
8672                assert_eq!(headers[1].name, "Content-Type");
8673                assert_eq!(headers[1].value, "application/json");
8674            }
8675            _ => panic!("Expected Http variant"),
8676        }
8677    }
8678
8679    #[cfg(feature = "schemars")]
8680    #[test]
8681    fn mcp_server_http_schema_marks_url_as_uri() {
8682        let schema = serde_json::to_value(schemars::schema_for!(McpServerHttp)).unwrap();
8683
8684        assert_eq!(schema["properties"]["url"]["format"], "uri");
8685    }
8686
8687    #[cfg(feature = "unstable_mcp_over_acp")]
8688    #[test]
8689    fn test_client_mcp_message_method_names() {
8690        use serde_json::json;
8691
8692        assert_eq!(AGENT_METHOD_NAMES.mcp_message, "mcp/message");
8693
8694        let notification =
8695            MessageMcpNotification::new("server-1", "req-1", "notifications/progress");
8696        assert_eq!(
8697            ClientNotification::MessageMcpNotification(Box::new(notification.clone())).method(),
8698            "mcp/message"
8699        );
8700        assert_eq!(
8701            serde_json::to_value(notification).unwrap(),
8702            json!({
8703                "serverId": "server-1",
8704                "requestId": "req-1",
8705                "method": "notifications/progress"
8706            })
8707        );
8708        let notification: MessageMcpNotification = serde_json::from_value(json!({
8709            "serverId": "server-1", "requestId": "req-1", "method": "notifications/progress",
8710            "params": null, "_meta": null
8711        }))
8712        .unwrap();
8713        assert_eq!(notification.params, None);
8714        assert_eq!(notification.meta, None);
8715        for key in ["serverId", "requestId", "method"] {
8716            let mut value = json!({"serverId":"server-1", "requestId":"req-1", "method":"notifications/progress"});
8717            value.as_object_mut().unwrap().remove(key);
8718            assert!(serde_json::from_value::<MessageMcpNotification>(value).is_err());
8719        }
8720    }
8721
8722    #[test]
8723    fn test_auth_method_names() {
8724        assert_eq!(AGENT_METHOD_NAMES.auth_login, "auth/login");
8725        assert_eq!(AGENT_METHOD_NAMES.auth_logout, "auth/logout");
8726
8727        assert_eq!(
8728            ClientRequest::LoginAuthRequest(Box::new(LoginAuthRequest::new("agent-login")))
8729                .method(),
8730            "auth/login"
8731        );
8732        assert_eq!(
8733            ClientRequest::LogoutAuthRequest(Box::new(LogoutAuthRequest::new())).method(),
8734            "auth/logout"
8735        );
8736    }
8737
8738    #[test]
8739    fn test_session_config_option_category_known_variants() {
8740        // Test serialization of known variants
8741        assert_eq!(
8742            serde_json::to_value(&SessionConfigOptionCategory::Mode).unwrap(),
8743            json!("mode")
8744        );
8745        assert_eq!(
8746            serde_json::to_value(&SessionConfigOptionCategory::Model).unwrap(),
8747            json!("model")
8748        );
8749        assert_eq!(
8750            serde_json::to_value(&SessionConfigOptionCategory::ModelConfig).unwrap(),
8751            json!("model_config")
8752        );
8753        #[cfg(feature = "unstable_speed_config_category")]
8754        assert_eq!(
8755            serde_json::to_value(&SessionConfigOptionCategory::Speed).unwrap(),
8756            json!("speed")
8757        );
8758        assert_eq!(
8759            serde_json::to_value(&SessionConfigOptionCategory::ThoughtLevel).unwrap(),
8760            json!("thought_level")
8761        );
8762
8763        // Test deserialization of known variants
8764        assert_eq!(
8765            serde_json::from_str::<SessionConfigOptionCategory>("\"mode\"").unwrap(),
8766            SessionConfigOptionCategory::Mode
8767        );
8768        assert_eq!(
8769            serde_json::from_str::<SessionConfigOptionCategory>("\"model\"").unwrap(),
8770            SessionConfigOptionCategory::Model
8771        );
8772        assert_eq!(
8773            serde_json::from_str::<SessionConfigOptionCategory>("\"model_config\"").unwrap(),
8774            SessionConfigOptionCategory::ModelConfig
8775        );
8776        #[cfg(feature = "unstable_speed_config_category")]
8777        assert_eq!(
8778            serde_json::from_str::<SessionConfigOptionCategory>("\"speed\"").unwrap(),
8779            SessionConfigOptionCategory::Speed
8780        );
8781        assert_eq!(
8782            serde_json::from_str::<SessionConfigOptionCategory>("\"thought_level\"").unwrap(),
8783            SessionConfigOptionCategory::ThoughtLevel
8784        );
8785    }
8786
8787    #[test]
8788    fn test_session_config_option_category_unknown_variants() {
8789        // Test that unknown strings are captured in Other variant
8790        let unknown: SessionConfigOptionCategory =
8791            serde_json::from_str("\"some_future_category\"").unwrap();
8792        assert_eq!(
8793            unknown,
8794            SessionConfigOptionCategory::Other("some_future_category".to_string())
8795        );
8796
8797        // Test round-trip of unknown category
8798        let json = serde_json::to_value(&unknown).unwrap();
8799        assert_eq!(json, json!("some_future_category"));
8800    }
8801
8802    #[cfg(not(feature = "unstable_speed_config_category"))]
8803    #[test]
8804    fn test_session_config_option_speed_is_unknown_without_feature() {
8805        let unknown: SessionConfigOptionCategory = serde_json::from_str("\"speed\"").unwrap();
8806        assert_eq!(
8807            unknown,
8808            SessionConfigOptionCategory::Other("speed".to_string())
8809        );
8810    }
8811
8812    #[test]
8813    fn test_session_config_option_category_custom_categories() {
8814        // Category names beginning with `_` are free for custom use
8815        let custom: SessionConfigOptionCategory =
8816            serde_json::from_str("\"_my_custom_category\"").unwrap();
8817        assert_eq!(
8818            custom,
8819            SessionConfigOptionCategory::Other("_my_custom_category".to_string())
8820        );
8821
8822        // Test round-trip preserves the custom category name
8823        let json = serde_json::to_value(&custom).unwrap();
8824        assert_eq!(json, json!("_my_custom_category"));
8825
8826        // Deserialize back and verify
8827        let deserialized: SessionConfigOptionCategory = serde_json::from_value(json).unwrap();
8828        assert_eq!(
8829            deserialized,
8830            SessionConfigOptionCategory::Other("_my_custom_category".to_string()),
8831        );
8832    }
8833
8834    fn test_config_option() -> SessionConfigOption {
8835        SessionConfigOption::select(
8836            "mode",
8837            "Mode",
8838            "ask",
8839            vec![SessionConfigSelectOption::new("ask", "Ask")],
8840        )
8841    }
8842
8843    #[test]
8844    fn test_session_response_initial_state_default_empty_and_skip_serializing() {
8845        assert_eq!(
8846            serde_json::to_value(NewSessionResponse::new("sess")).unwrap(),
8847            json!({ "sessionId": "sess" })
8848        );
8849        assert_eq!(
8850            serde_json::to_value(ResumeSessionResponse::new()).unwrap(),
8851            json!({})
8852        );
8853        #[cfg(feature = "unstable_session_fork")]
8854        assert_eq!(
8855            serde_json::to_value(ForkSessionResponse::new("fork")).unwrap(),
8856            json!({ "sessionId": "fork" })
8857        );
8858
8859        let json = serde_json::to_value(
8860            NewSessionResponse::new("sess").config_options(vec![test_config_option()]),
8861        )
8862        .unwrap();
8863        assert_eq!(json["configOptions"].as_array().unwrap().len(), 1);
8864    }
8865
8866    #[test]
8867    fn test_session_response_config_options_deserialize_missing_null_and_invalid() {
8868        let missing: NewSessionResponse =
8869            serde_json::from_value(json!({ "sessionId": "sess" })).unwrap();
8870        assert_eq!(missing.config_options, []);
8871
8872        let null: NewSessionResponse = serde_json::from_value(json!({
8873            "sessionId": "sess",
8874            "configOptions": null
8875        }))
8876        .unwrap();
8877        assert_eq!(null.config_options, []);
8878
8879        let wrong_shape: NewSessionResponse = serde_json::from_value(json!({
8880            "sessionId": "sess",
8881            "configOptions": "oops"
8882        }))
8883        .unwrap();
8884        assert_eq!(wrong_shape.config_options, []);
8885
8886        let valid_option = serde_json::to_value(test_config_option()).unwrap();
8887        let mixed: NewSessionResponse = serde_json::from_value(json!({
8888            "sessionId": "sess",
8889            "configOptions": ["oops", valid_option]
8890        }))
8891        .unwrap();
8892        assert_eq!(mixed.config_options.len(), 1);
8893
8894        let resume: ResumeSessionResponse = serde_json::from_value(json!({})).unwrap();
8895        assert_eq!(resume.config_options, []);
8896        #[cfg(feature = "unstable_session_fork")]
8897        {
8898            let fork: ForkSessionResponse =
8899                serde_json::from_value(json!({ "sessionId": "fork" })).unwrap();
8900            assert_eq!(fork.config_options, []);
8901        }
8902    }
8903
8904    #[test]
8905    fn test_session_response_available_commands_roundtrip_with_config_options() {
8906        use super::super::{AvailableCommandInput, Command, TextCommandInput};
8907
8908        let commands = vec![
8909            AvailableCommand::Command(
8910                Command::new("web", "Search the web")
8911                    .input(AvailableCommandInput::Text(TextCommandInput::new("Query"))),
8912            ),
8913            AvailableCommand::Command(Command::new("test", "Run project tests")),
8914        ];
8915        let mut expected = json!({
8916            "sessionId": "sess",
8917            "configOptions": [test_config_option()],
8918            "availableCommands": [
8919                {
8920                    "type": "command",
8921                    "name": "web",
8922                    "description": "Search the web",
8923                    "input": { "type": "text", "hint": "Query" }
8924                },
8925                { "type": "command", "name": "test", "description": "Run project tests" }
8926            ]
8927        });
8928
8929        let new = NewSessionResponse::new("sess")
8930            .config_options(vec![test_config_option()])
8931            .available_commands(commands.clone());
8932        assert_eq!(serde_json::to_value(&new).unwrap(), expected);
8933        assert_eq!(
8934            serde_json::from_value::<NewSessionResponse>(expected.clone()).unwrap(),
8935            new
8936        );
8937
8938        expected.as_object_mut().unwrap().remove("sessionId");
8939        let resume = ResumeSessionResponse::new()
8940            .config_options(vec![test_config_option()])
8941            .available_commands(commands.clone());
8942        assert_eq!(serde_json::to_value(&resume).unwrap(), expected);
8943        assert_eq!(
8944            serde_json::from_value::<ResumeSessionResponse>(expected.clone()).unwrap(),
8945            resume
8946        );
8947
8948        #[cfg(feature = "unstable_session_fork")]
8949        {
8950            expected["sessionId"] = json!("fork");
8951            let fork = ForkSessionResponse::new("fork")
8952                .config_options(vec![test_config_option()])
8953                .available_commands(commands);
8954            assert_eq!(serde_json::to_value(&fork).unwrap(), expected);
8955            assert_eq!(
8956                serde_json::from_value::<ForkSessionResponse>(expected).unwrap(),
8957                fork
8958            );
8959        }
8960    }
8961
8962    #[test]
8963    fn test_session_response_available_commands_deserialize_missing_null_and_invalid() {
8964        let command =
8965            AvailableCommand::Command(super::super::Command::new("test", "Run project tests"));
8966        let config_options = vec![test_config_option()];
8967
8968        for (commands, expected) in [
8969            (None, vec![]),
8970            (Some(json!(null)), vec![]),
8971            (Some(json!([])), vec![]),
8972            (Some(json!("oops")), vec![]),
8973            (Some(json!({})), vec![]),
8974            (Some(json!([null, {}, { "name": "invalid" }])), vec![]),
8975            (
8976                Some(json!([{ "name": "test", "description": "Run project tests" }])),
8977                vec![],
8978            ),
8979            (
8980                Some(json!([null, command, { "name": "invalid" }])),
8981                vec![command.clone()],
8982            ),
8983        ] {
8984            let mut value = json!({
8985                "sessionId": "sess",
8986                "configOptions": config_options
8987            });
8988            if let Some(commands) = commands {
8989                value["availableCommands"] = commands;
8990            }
8991
8992            let new: NewSessionResponse = serde_json::from_value(value.clone()).unwrap();
8993            assert_eq!(new.available_commands, expected);
8994            assert_eq!(new.config_options, config_options);
8995
8996            #[cfg(feature = "unstable_session_fork")]
8997            {
8998                let fork: ForkSessionResponse = serde_json::from_value(value.clone()).unwrap();
8999                assert_eq!(fork.available_commands, expected);
9000                assert_eq!(fork.config_options, config_options);
9001            }
9002
9003            value.as_object_mut().unwrap().remove("sessionId");
9004            let resume: ResumeSessionResponse = serde_json::from_value(value).unwrap();
9005            assert_eq!(resume.available_commands, expected);
9006            assert_eq!(resume.config_options, config_options);
9007        }
9008
9009        let resume: ResumeSessionResponse = serde_json::from_value(json!(null)).unwrap();
9010        assert_eq!(resume.available_commands, []);
9011    }
9012
9013    #[test]
9014    fn test_resume_session_replay_from_serialization() {
9015        assert_eq!(
9016            serde_json::to_value(ResumeSessionRequest::new(
9017                "sess_abc123",
9018                "/home/user/project"
9019            ))
9020            .unwrap(),
9021            json!({
9022                "sessionId": "sess_abc123",
9023                "cwd": "/home/user/project"
9024            })
9025        );
9026        assert_eq!(
9027            serde_json::to_value(
9028                ResumeSessionRequest::new("sess_abc123", "/home/user/project")
9029                    .replay_from(ReplayFrom::from(ReplayFromStart::new()))
9030            )
9031            .unwrap(),
9032            json!({
9033                "sessionId": "sess_abc123",
9034                "cwd": "/home/user/project",
9035                "replayFrom": {
9036                    "type": "start"
9037                }
9038            })
9039        );
9040
9041        let replay: ResumeSessionRequest = serde_json::from_value(json!({
9042            "sessionId": "sess_abc123",
9043            "cwd": "/home/user/project",
9044            "replayFrom": {
9045                "type": "start"
9046            }
9047        }))
9048        .unwrap();
9049        assert!(matches!(replay.replay_from, Some(ReplayFrom::Start(_))));
9050
9051        let none: ResumeSessionRequest = serde_json::from_value(json!({
9052            "sessionId": "sess_abc123",
9053            "cwd": "/home/user/project",
9054            "replayFrom": null
9055        }))
9056        .unwrap();
9057        assert!(none.replay_from.is_none());
9058    }
9059
9060    #[test]
9061    fn test_auth_method_agent_serialization() {
9062        let method = AuthMethod::Agent(AuthMethodAgent::new("default-auth", "Default Auth"));
9063
9064        let json = serde_json::to_value(&method).unwrap();
9065        assert_eq!(
9066            json,
9067            json!({
9068                "methodId": "default-auth",
9069                "name": "Default Auth",
9070                "type": "agent"
9071            })
9072        );
9073        // description should be omitted when None
9074        assert!(!json.as_object().unwrap().contains_key("description"));
9075
9076        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9077        match deserialized {
9078            AuthMethod::Agent(AuthMethodAgent {
9079                method_id, name, ..
9080            }) => {
9081                assert_eq!(method_id.0.as_ref(), "default-auth");
9082                assert_eq!(name, "Default Auth");
9083            }
9084            _ => panic!("Expected Agent variant"),
9085        }
9086    }
9087
9088    #[test]
9089    fn test_auth_method_agent_deserialization() {
9090        let json = json!({
9091            "methodId": "agent-auth",
9092            "name": "Agent Auth",
9093            "type": "agent"
9094        });
9095
9096        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9097        assert!(matches!(deserialized, AuthMethod::Agent(_)));
9098    }
9099
9100    #[test]
9101    fn test_auth_method_agent_requires_type() {
9102        assert!(
9103            serde_json::from_value::<AuthMethod>(json!({
9104                "methodId": "agent-auth",
9105                "name": "Agent Auth"
9106            }))
9107            .is_err()
9108        );
9109    }
9110
9111    #[test]
9112    fn test_auth_method_agent_rejects_null_type() {
9113        assert!(
9114            serde_json::from_value::<AuthMethod>(json!({
9115                "methodId": "agent-auth",
9116                "name": "Agent Auth",
9117                "type": null
9118            }))
9119            .is_err()
9120        );
9121    }
9122
9123    #[test]
9124    fn test_auth_method_unknown_does_not_hide_malformed_agent() {
9125        assert!(
9126            serde_json::from_value::<AuthMethod>(json!({
9127                "methodId": "agent-auth",
9128                "type": "agent"
9129            }))
9130            .is_err()
9131        );
9132        assert!(
9133            serde_json::from_value::<AuthMethod>(json!({
9134                "methodId": "api-key",
9135                "type": "env_var",
9136                "vars": [{"name": "API_KEY"}]
9137            }))
9138            .is_err()
9139        );
9140    }
9141
9142    #[test]
9143    fn test_auth_method_unknown_variant_roundtrip() {
9144        let method: AuthMethod = serde_json::from_value(json!({
9145            "methodId": "oauth",
9146            "name": "OAuth",
9147            "type": "_oauth",
9148            "authorizationUrl": "https://example.com/auth"
9149        }))
9150        .unwrap();
9151
9152        assert_eq!(method.method_id().0.as_ref(), "oauth");
9153        assert_eq!(method.name(), "OAuth");
9154        let AuthMethod::Other(unknown) = method else {
9155            panic!("expected unknown auth method");
9156        };
9157        assert_eq!(unknown.type_, "_oauth");
9158        assert_eq!(
9159            unknown.fields.get("authorizationUrl"),
9160            Some(&json!("https://example.com/auth"))
9161        );
9162
9163        assert_eq!(
9164            serde_json::to_value(AuthMethod::Other(unknown)).unwrap(),
9165            json!({
9166                "methodId": "oauth",
9167                "name": "OAuth",
9168                "type": "_oauth",
9169                "authorizationUrl": "https://example.com/auth"
9170            })
9171        );
9172    }
9173
9174    #[test]
9175    fn test_auth_method_unknown_does_not_hide_malformed_known_variant() {
9176        assert!(
9177            serde_json::from_value::<AuthMethod>(json!({
9178                "methodId": "terminal-auth",
9179                "type": "terminal"
9180            }))
9181            .is_err()
9182        );
9183    }
9184
9185    #[test]
9186    fn test_tool_call_and_terminal_cancel_serialization() {
9187        assert_eq!(AGENT_METHOD_NAMES.tool_call_cancel, "tool_call/cancel");
9188        assert_eq!(AGENT_METHOD_NAMES.terminal_cancel, "terminal/cancel");
9189        assert_eq!(
9190            ClientRequest::CancelToolCallRequest(Box::new(CancelToolCallRequest::new(
9191                "sess_abc123",
9192                "call_012"
9193            )))
9194            .method(),
9195            "tool_call/cancel"
9196        );
9197        assert_eq!(
9198            ClientRequest::CancelTerminalRequest(Box::new(CancelTerminalRequest::new(
9199                "sess_abc123",
9200                "term_003"
9201            )))
9202            .method(),
9203            "terminal/cancel"
9204        );
9205        assert_eq!(
9206            serde_json::to_value(CancelToolCallRequest::new("sess_abc123", "call_012")).unwrap(),
9207            json!({"sessionId": "sess_abc123", "toolCallId": "call_012"})
9208        );
9209        assert_eq!(
9210            serde_json::to_value(CancelTerminalRequest::new("sess_abc123", "term_003")).unwrap(),
9211            json!({"sessionId": "sess_abc123", "terminalId": "term_003"})
9212        );
9213        assert!(
9214            serde_json::from_value::<CancelToolCallRequest>(json!({"sessionId": "sess_abc123"}))
9215                .is_err()
9216        );
9217        assert_eq!(
9218            serde_json::to_value(CancelTerminalResponse::new()).unwrap(),
9219            json!({})
9220        );
9221    }
9222
9223    #[test]
9224    fn test_session_delete_serialization() {
9225        assert_eq!(AGENT_METHOD_NAMES.session_delete, "session/delete");
9226        assert_eq!(
9227            ClientRequest::DeleteSessionRequest(Box::new(DeleteSessionRequest::new("sess_abc123")))
9228                .method(),
9229            "session/delete"
9230        );
9231        assert_eq!(
9232            serde_json::to_value(DeleteSessionRequest::new("sess_abc123")).unwrap(),
9233            json!({
9234                "sessionId": "sess_abc123"
9235            })
9236        );
9237        assert_eq!(
9238            serde_json::to_value(DeleteSessionResponse::new()).unwrap(),
9239            json!({})
9240        );
9241        assert_eq!(
9242            serde_json::to_value(
9243                SessionCapabilities::new().delete(SessionDeleteCapabilities::new())
9244            )
9245            .unwrap(),
9246            json!({
9247                "delete": {}
9248            })
9249        );
9250    }
9251    #[cfg(feature = "unstable_session_set_title")]
9252    #[test]
9253    fn test_session_set_title_serialization() {
9254        assert_eq!(AGENT_METHOD_NAMES.session_set_title, "session/set_title");
9255        assert_eq!(
9256            ClientRequest::SetSessionTitleRequest(Box::new(SetSessionTitleRequest::new(
9257                "sess_abc123",
9258                "Investigate OAuth timeout"
9259            )))
9260            .method(),
9261            "session/set_title"
9262        );
9263        assert_eq!(
9264            serde_json::to_value(SetSessionTitleRequest::new(
9265                "sess_abc123",
9266                "Investigate OAuth timeout"
9267            ))
9268            .unwrap(),
9269            json!({
9270                "sessionId": "sess_abc123",
9271                "title": "Investigate OAuth timeout"
9272            })
9273        );
9274        assert_eq!(
9275            serde_json::to_value(SetSessionTitleResponse::new("Investigate OAuth timeout"))
9276                .unwrap(),
9277            json!({
9278                "title": "Investigate OAuth timeout"
9279            })
9280        );
9281        assert_eq!(
9282            serde_json::to_value(SessionCapabilities::new().title(SessionTitleCapabilities::new()))
9283                .unwrap(),
9284            json!({
9285                "title": {}
9286            })
9287        );
9288    }
9289
9290    #[cfg(feature = "unstable_session_set_title")]
9291    #[test]
9292    fn test_session_set_title_requires_title() {
9293        for params in [
9294            json!({"sessionId": "sess_abc123"}),
9295            json!({"sessionId": "sess_abc123", "title": null}),
9296            json!({"sessionId": "sess_abc123", "title": 42}),
9297        ] {
9298            assert!(serde_json::from_value::<SetSessionTitleRequest>(params).is_err());
9299        }
9300        for result in [json!({}), json!({"title": null})] {
9301            assert!(serde_json::from_value::<SetSessionTitleResponse>(result).is_err());
9302        }
9303    }
9304
9305    #[cfg(feature = "unstable_session_options")]
9306    #[test]
9307    fn test_session_options_serialization() {
9308        assert_eq!(AGENT_METHOD_NAMES.session_options, "session/options");
9309        assert_eq!(
9310            ClientRequest::SessionOptionsRequest(Box::new(SessionOptionsRequest::new(
9311                "/home/user/project"
9312            )))
9313            .method(),
9314            "session/options"
9315        );
9316        assert_eq!(
9317            serde_json::to_value(
9318                SessionOptionsRequest::new("/home/user/project")
9319                    .session_id(SessionId::new("sess_abc123"))
9320            )
9321            .unwrap(),
9322            json!({"cwd": "/home/user/project", "sessionId": "sess_abc123"})
9323        );
9324        assert_eq!(
9325            serde_json::from_value::<SessionOptionsRequest>(
9326                json!({"cwd": "/home/user/project", "additionalDirectories": null, "sessionId": null})
9327            )
9328            .unwrap(),
9329            SessionOptionsRequest::new("/home/user/project")
9330        );
9331        let request = NewSessionRequest::new("/home/user/project").config_options(vec![
9332            InitialSessionConfigOption::new("model", SessionConfigOptionValue::id("model-2")),
9333            InitialSessionConfigOption::new("fast", SessionConfigOptionValue::boolean(true)),
9334        ]);
9335        let value = serde_json::to_value(&request).unwrap();
9336        assert_eq!(
9337            value["configOptions"],
9338            json!([
9339                {"configId": "model", "type": "id", "value": "model-2"},
9340                {"configId": "fast", "type": "boolean", "value": true}
9341            ])
9342        );
9343        assert_eq!(
9344            serde_json::from_value::<NewSessionRequest>(value).unwrap(),
9345            request
9346        );
9347        assert!(
9348            serde_json::from_value::<NewSessionRequest>(json!({
9349                "cwd": "/home/user/project",
9350                "mcpServers": [],
9351                "configOptions": [{"type": "boolean", "value": true}]
9352            }))
9353            .is_err()
9354        );
9355        assert_eq!(
9356            serde_json::to_value(SessionOptionsResponse::new()).unwrap(),
9357            json!({})
9358        );
9359        #[cfg(feature = "unstable_session_fork")]
9360        {
9361            let fork =
9362                ForkSessionRequest::new("sess_abc123", "/home/user/project").config_options(vec![
9363                    InitialSessionConfigOption::new(
9364                        "model",
9365                        SessionConfigOptionValue::id("model-2"),
9366                    ),
9367                ]);
9368            let value = serde_json::to_value(&fork).unwrap();
9369            assert_eq!(
9370                value["configOptions"],
9371                json!([{"configId": "model", "type": "id", "value": "model-2"}])
9372            );
9373            assert_eq!(
9374                serde_json::from_value::<ForkSessionRequest>(value).unwrap(),
9375                fork
9376            );
9377            // `null` is an empty list, and a malformed entry fails the request.
9378            assert_eq!(
9379                serde_json::from_value::<ForkSessionRequest>(json!({
9380                    "sessionId": "sess_abc123",
9381                    "cwd": "/home/user/project",
9382                    "configOptions": null
9383                }))
9384                .unwrap(),
9385                ForkSessionRequest::new("sess_abc123", "/home/user/project")
9386            );
9387            assert!(
9388                serde_json::from_value::<ForkSessionRequest>(json!({
9389                    "sessionId": "sess_abc123",
9390                    "cwd": "/home/user/project",
9391                    "configOptions": [{"type": "boolean", "value": true}]
9392                }))
9393                .is_err()
9394            );
9395        }
9396        assert_eq!(
9397            serde_json::to_value(
9398                SessionCapabilities::new().options(SessionOptionsCapabilities::new())
9399            )
9400            .unwrap(),
9401            json!({"options": {}})
9402        );
9403    }
9404
9405    #[cfg(feature = "unstable_session_status")]
9406    #[test]
9407    fn test_session_status_serialization() {
9408        assert_eq!(AGENT_METHOD_NAMES.session_status, "session/status");
9409        assert_eq!(
9410            ClientRequest::SessionStatusRequest(Box::new(SessionStatusRequest::new("sess_abc123")))
9411                .method(),
9412            "session/status"
9413        );
9414        assert_eq!(
9415            serde_json::to_value(SessionStatusRequest::new("sess_abc123")).unwrap(),
9416            json!({"sessionId": "sess_abc123"})
9417        );
9418        assert_eq!(
9419            serde_json::to_value(SessionStatusResponse::new(SessionStatus::Saved)).unwrap(),
9420            json!({"status": "saved"})
9421        );
9422        assert_eq!(
9423            serde_json::to_value(
9424                SessionCapabilities::new().status(SessionStatusCapabilities::new())
9425            )
9426            .unwrap(),
9427            json!({"status": {}})
9428        );
9429        assert_eq!(
9430            serde_json::to_value(SessionStatusResponse::new(SessionStatus::Open).state(
9431                StateUpdate::RequiresAction(crate::v2::RequiresActionStateUpdate::new())
9432            ))
9433            .unwrap(),
9434            json!({
9435                "status": "open",
9436                "state": {"state": "requires_action"}
9437            })
9438        );
9439        for state in [json!(null), json!("running"), json!({"state": 7})] {
9440            let response = serde_json::from_value::<SessionStatusResponse>(
9441                json!({"status": "open", "state": state}),
9442            )
9443            .unwrap();
9444            assert_eq!(response.state, None);
9445        }
9446    }
9447
9448    #[cfg(feature = "unstable_session_status")]
9449    #[test]
9450    fn test_session_status_is_strict_and_open() {
9451        let custom =
9452            serde_json::from_value::<SessionStatusResponse>(json!({"status": "_suspended"}))
9453                .unwrap();
9454        assert_eq!(
9455            custom.status,
9456            SessionStatus::Other("_suspended".to_string())
9457        );
9458        assert_eq!(
9459            serde_json::to_value(&custom).unwrap(),
9460            json!({"status": "_suspended"})
9461        );
9462        for result in [json!({}), json!({"status": null}), json!({"status": 1})] {
9463            assert!(serde_json::from_value::<SessionStatusResponse>(result).is_err());
9464        }
9465        for params in [json!({}), json!({"sessionId": null})] {
9466            assert!(serde_json::from_value::<SessionStatusRequest>(params).is_err());
9467        }
9468    }
9469
9470    #[cfg(feature = "unstable_session_archive")]
9471    #[test]
9472    fn test_session_archive_serialization() {
9473        assert_eq!(AGENT_METHOD_NAMES.session_archive, "session/archive");
9474        assert_eq!(AGENT_METHOD_NAMES.session_unarchive, "session/unarchive");
9475        assert_eq!(
9476            ClientRequest::ArchiveSessionRequest(Box::new(ArchiveSessionRequest::new(
9477                "sess_abc123"
9478            )))
9479            .method(),
9480            "session/archive"
9481        );
9482        assert_eq!(
9483            ClientRequest::UnarchiveSessionRequest(Box::new(UnarchiveSessionRequest::new(
9484                "sess_abc123"
9485            )))
9486            .method(),
9487            "session/unarchive"
9488        );
9489        assert_eq!(
9490            serde_json::to_value(ArchiveSessionRequest::new("sess_abc123")).unwrap(),
9491            json!({"sessionId": "sess_abc123"})
9492        );
9493        assert_eq!(
9494            serde_json::to_value(UnarchiveSessionResponse::new()).unwrap(),
9495            json!({})
9496        );
9497        assert_eq!(
9498            serde_json::to_value(
9499                SessionCapabilities::new().archive(SessionArchiveCapabilities::new())
9500            )
9501            .unwrap(),
9502            json!({"archive": {}})
9503        );
9504        assert_eq!(
9505            serde_json::to_value(
9506                ListSessionsRequest::new()
9507                    .cwd("/home/user/project")
9508                    .archived(SessionArchiveFilter::Only)
9509            )
9510            .unwrap(),
9511            json!({"cwd": "/home/user/project", "archived": "only"})
9512        );
9513        assert_eq!(
9514            serde_json::to_value(
9515                SessionInfo::new("sess_abc123", "/home/user/project").archived(true)
9516            )
9517            .unwrap(),
9518            json!({"sessionId": "sess_abc123", "cwd": "/home/user/project", "archived": true})
9519        );
9520    }
9521
9522    #[cfg(feature = "unstable_session_archive")]
9523    #[test]
9524    fn test_session_archive_filter_is_strict_and_open() {
9525        for (value, expected) in [
9526            (json!(null), None),
9527            (json!("include"), Some(SessionArchiveFilter::Include)),
9528            (
9529                json!("_recent"),
9530                Some(SessionArchiveFilter::Other("_recent".to_string())),
9531            ),
9532        ] {
9533            let request =
9534                serde_json::from_value::<ListSessionsRequest>(json!({"archived": value})).unwrap();
9535            assert_eq!(request.archived, expected);
9536        }
9537        for value in [json!(true), json!(1), json!({})] {
9538            assert!(
9539                serde_json::from_value::<ListSessionsRequest>(json!({"archived": value})).is_err()
9540            );
9541        }
9542        let info = serde_json::from_value::<SessionInfo>(
9543            json!({"sessionId": "sess_abc123", "cwd": "/home/user/project", "archived": "yes"}),
9544        )
9545        .unwrap();
9546        assert_eq!(info.archived, None);
9547    }
9548
9549    #[test]
9550    fn test_session_additional_directories_serialization() {
9551        assert_eq!(
9552            serde_json::to_value(NewSessionRequest::new("/home/user/project")).unwrap(),
9553            json!({
9554                "cwd": "/home/user/project",
9555            })
9556        );
9557        assert_eq!(
9558            serde_json::to_value(
9559                NewSessionRequest::new("/home/user/project").additional_directories(vec![
9560                    PathBuf::from("/home/user/shared-lib"),
9561                    PathBuf::from("/home/user/product-docs"),
9562                ])
9563            )
9564            .unwrap(),
9565            json!({
9566                "cwd": "/home/user/project",
9567                "additionalDirectories": [
9568                    "/home/user/shared-lib",
9569                    "/home/user/product-docs"
9570                ],
9571            })
9572        );
9573        assert_eq!(
9574            serde_json::to_value(ResumeSessionRequest::new(
9575                "sess_abc123",
9576                "/home/user/project"
9577            ))
9578            .unwrap(),
9579            json!({
9580                "sessionId": "sess_abc123",
9581                "cwd": "/home/user/project",
9582            })
9583        );
9584        assert_eq!(
9585            serde_json::from_value::<ResumeSessionRequest>(json!({
9586                "sessionId": "sess_abc123",
9587                "cwd": "/home/user/project"
9588            }))
9589            .unwrap()
9590            .mcp_servers,
9591            Vec::<McpServer>::new()
9592        );
9593        assert_eq!(
9594            serde_json::from_value::<ResumeSessionRequest>(json!({
9595                "sessionId": "sess_abc123",
9596                "cwd": "/home/user/project",
9597                "mcpServers": null
9598            }))
9599            .unwrap()
9600            .mcp_servers,
9601            Vec::<McpServer>::new()
9602        );
9603        assert_eq!(
9604            serde_json::to_value(SessionInfo::new("sess_abc123", "/home/user/project")).unwrap(),
9605            json!({
9606                "sessionId": "sess_abc123",
9607                "cwd": "/home/user/project"
9608            })
9609        );
9610        assert_eq!(
9611            serde_json::to_value(
9612                SessionInfo::new("sess_abc123", "/home/user/project").additional_directories(vec![
9613                    PathBuf::from("/home/user/shared-lib"),
9614                    PathBuf::from("/home/user/product-docs"),
9615                ])
9616            )
9617            .unwrap(),
9618            json!({
9619                "sessionId": "sess_abc123",
9620                "cwd": "/home/user/project",
9621                "additionalDirectories": [
9622                    "/home/user/shared-lib",
9623                    "/home/user/product-docs"
9624                ]
9625            })
9626        );
9627        assert_eq!(
9628            serde_json::from_value::<SessionInfo>(json!({
9629                "sessionId": "sess_abc123",
9630                "cwd": "/home/user/project"
9631            }))
9632            .unwrap()
9633            .additional_directories,
9634            Vec::<AbsolutePath>::new()
9635        );
9636    }
9637    #[test]
9638    fn test_session_additional_directories_capabilities_serialization() {
9639        assert_eq!(
9640            serde_json::to_value(
9641                SessionCapabilities::new()
9642                    .additional_directories(SessionAdditionalDirectoriesCapabilities::new())
9643            )
9644            .unwrap(),
9645            json!({
9646                "additionalDirectories": {}
9647            })
9648        );
9649    }
9650
9651    #[test]
9652    fn test_session_system_prompt_capabilities_serialization() {
9653        assert_eq!(
9654            serde_json::to_value(
9655                SessionCapabilities::new().system_prompt(SessionSystemPromptCapabilities::new())
9656            )
9657            .unwrap(),
9658            json!({ "systemPrompt": {} })
9659        );
9660        assert_eq!(
9661            serde_json::to_value(
9662                SessionCapabilities::new().system_prompt(
9663                    SessionSystemPromptCapabilities::new().mode(
9664                        SessionSystemPromptModeCapabilities::new()
9665                            .override_(SessionSystemPromptOverrideCapabilities::new())
9666                    )
9667                )
9668            )
9669            .unwrap(),
9670            json!({ "systemPrompt": { "mode": { "override": {} } } })
9671        );
9672        assert_eq!(
9673            serde_json::from_value::<SessionCapabilities>(
9674                json!({ "systemPrompt": { "mode": { "override": {} } } })
9675            )
9676            .unwrap()
9677            .system_prompt
9678            .and_then(|capabilities| capabilities.mode)
9679            .and_then(|mode| mode.override_),
9680            Some(SessionSystemPromptOverrideCapabilities::new())
9681        );
9682
9683        // Capabilities fall back to "not advertised" when malformed.
9684        assert_eq!(
9685            serde_json::from_value::<SessionCapabilities>(json!({ "systemPrompt": "yes" }))
9686                .unwrap()
9687                .system_prompt,
9688            None
9689        );
9690        assert_eq!(
9691            serde_json::from_value::<SessionCapabilities>(
9692                json!({ "systemPrompt": { "mode": { "override": true } } })
9693            )
9694            .unwrap()
9695            .system_prompt,
9696            Some(
9697                SessionSystemPromptCapabilities::new()
9698                    .mode(SessionSystemPromptModeCapabilities::new())
9699            )
9700        );
9701        assert_eq!(
9702            serde_json::from_value::<SessionCapabilities>(
9703                json!({ "systemPrompt": { "mode": "override" } })
9704            )
9705            .unwrap()
9706            .system_prompt,
9707            Some(SessionSystemPromptCapabilities::new())
9708        );
9709    }
9710
9711    #[test]
9712    fn test_system_prompt_lifecycle_request_serialization() {
9713        let system_prompt = SystemPrompt::new(vec![ContentBlock::from(
9714            "You are a code review specialist.",
9715        )]);
9716        let system_prompt_json = json!({
9717            "mode": "append",
9718            "content": [{ "type": "text", "text": "You are a code review specialist." }]
9719        });
9720
9721        let request =
9722            NewSessionRequest::new("/home/user/project").system_prompt(system_prompt.clone());
9723        let request_json = json!({
9724            "cwd": "/home/user/project",
9725            "systemPrompt": system_prompt_json
9726        });
9727        assert_eq!(serde_json::to_value(&request).unwrap(), request_json);
9728        assert_eq!(
9729            serde_json::from_value::<NewSessionRequest>(request_json).unwrap(),
9730            request
9731        );
9732
9733        assert_eq!(
9734            serde_json::to_value(
9735                ResumeSessionRequest::new("sess_abc123", "/home/user/project")
9736                    .system_prompt(system_prompt.clone())
9737            )
9738            .unwrap()["systemPrompt"],
9739            system_prompt_json
9740        );
9741        #[cfg(feature = "unstable_session_fork")]
9742        assert_eq!(
9743            serde_json::to_value(
9744                ForkSessionRequest::new("sess_abc123", "/home/user/project")
9745                    .system_prompt(system_prompt.clone())
9746            )
9747            .unwrap()["systemPrompt"],
9748            system_prompt_json
9749        );
9750
9751        let override_prompt =
9752            SystemPrompt::new(vec![ContentBlock::from("...")]).mode(SystemPromptMode::Override);
9753        let override_json = json!({
9754            "mode": "override",
9755            "content": [{ "type": "text", "text": "..." }]
9756        });
9757        assert_eq!(
9758            serde_json::to_value(&override_prompt).unwrap(),
9759            override_json
9760        );
9761        assert_eq!(
9762            serde_json::from_value::<SystemPrompt>(override_json).unwrap(),
9763            override_prompt
9764        );
9765    }
9766
9767    /// `SystemPrompt::new` defaults to `append` in Rust, but `mode` is required on
9768    /// the wire, so it is always serialized.
9769    #[test]
9770    fn test_system_prompt_new_defaults_to_append() {
9771        let system_prompt = SystemPrompt::new(vec![ContentBlock::from("...")]);
9772        assert_eq!(system_prompt.mode, SystemPromptMode::Append);
9773        assert_eq!(
9774            serde_json::to_value(&system_prompt).unwrap(),
9775            json!({ "mode": "append", "content": [{ "type": "text", "text": "..." }] })
9776        );
9777    }
9778
9779    /// Unknown modes follow the enum variant extension rule: they parse as
9780    /// `SystemPromptMode::Other` so they are not dropped, and an Agent that does
9781    /// not support them must reject the request.
9782    #[test]
9783    fn test_system_prompt_preserves_unknown_modes() {
9784        for mode in ["_vendor_mode", "prepend"] {
9785            let system_prompt_json =
9786                json!({ "mode": mode, "content": [{ "type": "text", "text": "..." }] });
9787            let system_prompt: SystemPrompt =
9788                serde_json::from_value(system_prompt_json.clone()).unwrap();
9789            assert_eq!(
9790                system_prompt.mode,
9791                SystemPromptMode::Other(mode.to_string())
9792            );
9793            assert_eq!(
9794                serde_json::to_value(&system_prompt).unwrap(),
9795                system_prompt_json
9796            );
9797        }
9798    }
9799
9800    /// The receiver acts on `systemPrompt`, so malformed values fail the request
9801    /// (`-32602`) instead of creating a session without the prompt, and `null`
9802    /// is equivalent to omitting the field.
9803    fn assert_system_prompt_is_strict<T>(base: &serde_json::Value)
9804    where
9805        T: serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
9806    {
9807        let name = std::any::type_name::<T>();
9808        let with = |system_prompt: serde_json::Value| {
9809            let mut request = base.clone();
9810            request["systemPrompt"] = system_prompt;
9811            serde_json::from_value::<T>(request)
9812        };
9813
9814        for system_prompt in [
9815            json!("You are a code review specialist."),
9816            json!({ "content": [{ "type": "text", "text": "..." }] }),
9817            json!({ "mode": null, "content": [{ "type": "text", "text": "..." }] }),
9818            json!({ "mode": 1, "content": [{ "type": "text", "text": "..." }] }),
9819            json!({ "mode": "append" }),
9820            json!({ "mode": "append", "content": "..." }),
9821            json!({ "mode": "append", "content": [{ "type": "text" }] }),
9822        ] {
9823            assert!(
9824                with(system_prompt.clone()).is_err(),
9825                "{name}.systemPrompt: {system_prompt}"
9826            );
9827        }
9828
9829        assert_eq!(
9830            with(serde_json::Value::Null).unwrap(),
9831            serde_json::from_value::<T>(base.clone()).unwrap(),
9832            "{name}.systemPrompt"
9833        );
9834    }
9835
9836    #[test]
9837    fn test_session_setup_requests_reject_malformed_system_prompts() {
9838        assert!(
9839            serde_json::to_value(NewSessionRequest::new("/repo"))
9840                .unwrap()
9841                .get("systemPrompt")
9842                .is_none()
9843        );
9844        assert_system_prompt_is_strict::<NewSessionRequest>(&json!({ "cwd": "/repo" }));
9845        assert_system_prompt_is_strict::<ResumeSessionRequest>(&json!({
9846            "sessionId": "sess-1",
9847            "cwd": "/repo"
9848        }));
9849        #[cfg(feature = "unstable_session_fork")]
9850        assert_system_prompt_is_strict::<ForkSessionRequest>(&json!({
9851            "sessionId": "sess-1",
9852            "cwd": "/repo"
9853        }));
9854    }
9855
9856    /// Unknown content block types parse as `ContentBlock::Other` so they are not
9857    /// dropped. An Agent that does not support them must reject the request.
9858    #[test]
9859    fn test_system_prompt_preserves_unknown_content_blocks() {
9860        let request: NewSessionRequest = serde_json::from_value(json!({
9861            "cwd": "/home/user/project",
9862            "systemPrompt": {
9863                "mode": "append",
9864                "content": [{ "type": "_vendor_video", "uri": "https://example.com/intro.mp4" }]
9865            }
9866        }))
9867        .unwrap();
9868        let content = request.system_prompt.unwrap().content;
9869        assert_eq!(content.len(), 1);
9870        assert!(matches!(content[0], ContentBlock::Other(_)));
9871    }
9872
9873    #[test]
9874    fn test_auth_method_terminal_serialization() {
9875        let method = AuthMethod::Terminal(AuthMethodTerminal::new("tui-auth", "Terminal Auth"));
9876
9877        let json = serde_json::to_value(&method).unwrap();
9878        assert_eq!(
9879            json,
9880            json!({
9881                "methodId": "tui-auth",
9882                "name": "Terminal Auth",
9883                "type": "terminal"
9884            })
9885        );
9886        // args and env should be omitted when empty
9887        assert!(!json.as_object().unwrap().contains_key("args"));
9888        assert!(!json.as_object().unwrap().contains_key("env"));
9889
9890        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9891        match deserialized {
9892            AuthMethod::Terminal(AuthMethodTerminal { args, env, .. }) => {
9893                assert_eq!(args, Vec::<String>::new());
9894                assert_eq!(env, []);
9895            }
9896            _ => panic!("Expected Terminal variant"),
9897        }
9898    }
9899
9900    #[test]
9901    fn test_auth_method_terminal_with_args_and_env_serialization() {
9902        let method = AuthMethod::Terminal(
9903            AuthMethodTerminal::new("tui-auth", "Terminal Auth")
9904                .args(vec!["--interactive".to_string(), "--color".to_string()])
9905                .env(vec![EnvVariable::new("TERM", "xterm-256color")]),
9906        );
9907
9908        let json = serde_json::to_value(&method).unwrap();
9909        assert_eq!(
9910            json,
9911            json!({
9912                "methodId": "tui-auth",
9913                "name": "Terminal Auth",
9914                "type": "terminal",
9915                "args": ["--interactive", "--color"],
9916                "env": [
9917                    {
9918                        "name": "TERM",
9919                        "value": "xterm-256color"
9920                    }
9921                ]
9922            })
9923        );
9924
9925        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9926        match deserialized {
9927            AuthMethod::Terminal(AuthMethodTerminal { args, env, .. }) => {
9928                assert_eq!(args, vec!["--interactive", "--color"]);
9929                assert_eq!(env.len(), 1);
9930                assert_eq!(env[0].name, "TERM");
9931                assert_eq!(env[0].value, "xterm-256color");
9932            }
9933            _ => panic!("Expected Terminal variant"),
9934        }
9935    }
9936
9937    #[test]
9938    fn test_session_config_option_id_serialize() {
9939        let val = SessionConfigOptionValue::id("model-1");
9940        let json = serde_json::to_value(&val).unwrap();
9941        assert_eq!(json, json!({ "type": "id", "value": "model-1" }));
9942    }
9943
9944    #[test]
9945    fn test_session_config_option_value_boolean_serialize() {
9946        let val = SessionConfigOptionValue::boolean(true);
9947        let json = serde_json::to_value(&val).unwrap();
9948        assert_eq!(json, json!({ "type": "boolean", "value": true }));
9949    }
9950
9951    #[test]
9952    fn test_session_config_option_value_deserialize_id() {
9953        let json = json!({ "type": "id", "value": "model-1" });
9954        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9955        assert_eq!(val, SessionConfigOptionValue::id("model-1"));
9956        assert_eq!(val.as_id().unwrap().to_string(), "model-1");
9957    }
9958
9959    #[test]
9960    fn test_session_config_option_value_deserialize_requires_type() {
9961        let json = json!({ "value": "model-1" });
9962        let result = serde_json::from_value::<SessionConfigOptionValue>(json);
9963        assert!(result.is_err());
9964    }
9965
9966    #[test]
9967    fn test_session_config_option_value_deserialize_boolean() {
9968        let json = json!({ "type": "boolean", "value": true });
9969        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9970        assert_eq!(val, SessionConfigOptionValue::boolean(true));
9971        assert_eq!(val.as_bool(), Some(true));
9972    }
9973
9974    #[test]
9975    fn test_session_config_option_value_deserialize_boolean_false() {
9976        let json = json!({ "type": "boolean", "value": false });
9977        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9978        assert_eq!(val, SessionConfigOptionValue::boolean(false));
9979        assert_eq!(val.as_bool(), Some(false));
9980    }
9981
9982    #[test]
9983    fn test_session_config_option_value_deserialize_unknown_type_with_string_value() {
9984        let json = json!({
9985            "type": "text",
9986            "value": "freeform input",
9987            "maxLength": 200
9988        });
9989        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9990        let SessionConfigOptionValue::Other(unknown) = val else {
9991            panic!("Expected Other variant");
9992        };
9993        assert_eq!(unknown.type_, "text");
9994        assert_eq!(unknown.value, json!("freeform input"));
9995        assert_eq!(unknown.fields["maxLength"], json!(200));
9996    }
9997
9998    #[test]
9999    fn test_session_config_option_value_deserialize_unknown_type_with_object_value() {
10000        let json = json!({
10001            "type": "range",
10002            "value": { "min": 1, "max": 5 }
10003        });
10004        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10005        let SessionConfigOptionValue::Other(unknown) = val else {
10006            panic!("Expected Other variant");
10007        };
10008        assert_eq!(unknown.type_, "range");
10009        assert_eq!(unknown.value, json!({ "min": 1, "max": 5 }));
10010    }
10011
10012    #[test]
10013    fn test_session_config_option_value_roundtrip_id() {
10014        let original = SessionConfigOptionValue::id("option-a");
10015        let json = serde_json::to_value(&original).unwrap();
10016        let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10017        assert_eq!(original, roundtripped);
10018    }
10019
10020    #[test]
10021    fn test_session_config_option_value_roundtrip_boolean() {
10022        let original = SessionConfigOptionValue::boolean(false);
10023        let json = serde_json::to_value(&original).unwrap();
10024        let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10025        assert_eq!(original, roundtripped);
10026    }
10027
10028    #[test]
10029    fn test_session_config_option_value_roundtrip_other() {
10030        let mut fields = IndexMap::new();
10031        fields.insert("maxLength".to_string(), json!(200));
10032        let original = SessionConfigOptionValue::Other(OtherSessionConfigOptionValue::new(
10033            "text",
10034            json!("freeform input"),
10035            fields,
10036        ));
10037        let json = serde_json::to_value(&original).unwrap();
10038        let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
10039        assert_eq!(original, roundtripped);
10040    }
10041
10042    #[test]
10043    fn test_session_config_option_value_type_mismatch_boolean_with_string() {
10044        let json = json!({ "type": "boolean", "value": "not a bool" });
10045        let result = serde_json::from_value::<SessionConfigOptionValue>(json);
10046        assert!(result.is_err());
10047    }
10048
10049    #[test]
10050    fn test_session_config_option_value_from_impls() {
10051        let from_str: SessionConfigOptionValue = "model-1".into();
10052        assert_eq!(from_str.as_id().unwrap().to_string(), "model-1");
10053
10054        let from_id: SessionConfigOptionValue = SessionConfigValueId::new("model-2").into();
10055        assert_eq!(from_id.as_id().unwrap().to_string(), "model-2");
10056
10057        let from_bool: SessionConfigOptionValue = true.into();
10058        assert_eq!(from_bool.as_bool(), Some(true));
10059    }
10060
10061    #[test]
10062    fn test_set_session_config_option_request_id() {
10063        let req = SetSessionConfigOptionRequest::new("sess_1", "model", "model-1");
10064        let json = serde_json::to_value(&req).unwrap();
10065        assert_eq!(
10066            json,
10067            json!({
10068                "sessionId": "sess_1",
10069                "configId": "model",
10070                "type": "id",
10071                "value": "model-1"
10072            })
10073        );
10074    }
10075
10076    #[test]
10077    fn test_set_session_config_option_request_boolean() {
10078        let req = SetSessionConfigOptionRequest::new("sess_1", "brave_mode", true);
10079        let json = serde_json::to_value(&req).unwrap();
10080        assert_eq!(
10081            json,
10082            json!({
10083                "sessionId": "sess_1",
10084                "configId": "brave_mode",
10085                "type": "boolean",
10086                "value": true
10087            })
10088        );
10089    }
10090
10091    #[test]
10092    fn test_set_session_config_option_request_deserialize_requires_type() {
10093        let json = json!({
10094            "sessionId": "sess_1",
10095            "configId": "model",
10096            "value": "model-1"
10097        });
10098        let result = serde_json::from_value::<SetSessionConfigOptionRequest>(json);
10099        assert!(result.is_err());
10100    }
10101
10102    #[test]
10103    fn test_set_session_config_option_request_deserialize_boolean() {
10104        let json = json!({
10105            "sessionId": "sess_1",
10106            "configId": "brave_mode",
10107            "type": "boolean",
10108            "value": true
10109        });
10110        let req: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
10111        assert_eq!(req.value.as_bool(), Some(true));
10112    }
10113
10114    #[test]
10115    fn test_set_session_config_option_request_roundtrip_id() {
10116        let original = SetSessionConfigOptionRequest::new("s", "c", "v");
10117        let json = serde_json::to_value(&original).unwrap();
10118        let roundtripped: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
10119        assert_eq!(original, roundtripped);
10120    }
10121
10122    #[test]
10123    fn test_set_session_config_option_request_roundtrip_boolean() {
10124        let original = SetSessionConfigOptionRequest::new("s", "c", false);
10125        let json = serde_json::to_value(&original).unwrap();
10126        let roundtripped: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
10127        assert_eq!(original, roundtripped);
10128    }
10129
10130    #[test]
10131    fn test_session_config_boolean_serialization() {
10132        let cfg = SessionConfigBoolean::new(true);
10133        let json = serde_json::to_value(&cfg).unwrap();
10134        assert_eq!(json, json!({ "currentValue": true }));
10135
10136        let deserialized: SessionConfigBoolean = serde_json::from_value(json).unwrap();
10137        assert!(deserialized.current_value);
10138    }
10139
10140    #[test]
10141    fn test_session_config_option_boolean_variant() {
10142        let opt = SessionConfigOption::boolean("brave_mode", "Brave Mode", false)
10143            .description("Skip confirmation prompts")
10144            .meta(test_meta());
10145        assert_eq!(serialized_meta_key_count(&opt), 1);
10146
10147        let json = serde_json::to_value(&opt).unwrap();
10148        assert_eq!(
10149            json,
10150            json!({
10151                "configId": "brave_mode",
10152                "name": "Brave Mode",
10153                "description": "Skip confirmation prompts",
10154                "type": "boolean",
10155                "currentValue": false,
10156                "_meta": {
10157                    "source": "test"
10158                }
10159            })
10160        );
10161
10162        let deserialized: SessionConfigOption = serde_json::from_value(json).unwrap();
10163        assert_eq!(deserialized.config_id.to_string(), "brave_mode");
10164        assert_eq!(deserialized.name, "Brave Mode");
10165        match deserialized.kind {
10166            SessionConfigKind::Boolean(ref b) => assert!(!b.current_value),
10167            _ => panic!("Expected Boolean kind"),
10168        }
10169    }
10170
10171    #[test]
10172    fn test_session_config_option_select_still_works() {
10173        // Make sure existing select options are unaffected
10174        let opt = SessionConfigOption::select(
10175            "model",
10176            "Model",
10177            "model-1",
10178            vec![
10179                SessionConfigSelectOption::new("model-1", "Model 1"),
10180                SessionConfigSelectOption::new("model-2", "Model 2"),
10181            ],
10182        )
10183        .meta(test_meta());
10184        assert_eq!(serialized_meta_key_count(&opt), 1);
10185
10186        let json = serde_json::to_value(&opt).unwrap();
10187        assert_eq!(json["type"], "select");
10188        assert_eq!(json["currentValue"], "model-1");
10189        assert_eq!(json["options"].as_array().unwrap().len(), 2);
10190        assert_eq!(json["_meta"]["source"], "test");
10191
10192        let deserialized: SessionConfigOption = serde_json::from_value(json).unwrap();
10193        match deserialized.kind {
10194            SessionConfigKind::Select(ref s) => {
10195                assert_eq!(s.current_value.to_string(), "model-1");
10196            }
10197            _ => panic!("Expected Select kind"),
10198        }
10199    }
10200
10201    #[test]
10202    fn test_session_config_option_unknown_kind_roundtrip() {
10203        let option: SessionConfigOption = serde_json::from_value(json!({
10204            "configId": "verbosity",
10205            "name": "Verbosity",
10206            "type": "_slider",
10207            "currentValue": 3,
10208            "min": 0,
10209            "max": 5,
10210            "_meta": {
10211                "source": "test"
10212            }
10213        }))
10214        .unwrap();
10215
10216        assert_eq!(option.config_id.to_string(), "verbosity");
10217        assert_eq!(option.meta.as_ref().unwrap()["source"], "test");
10218        let SessionConfigKind::Other(unknown) = &option.kind else {
10219            panic!("expected unknown config kind");
10220        };
10221        assert_eq!(unknown.type_, "_slider");
10222        assert_eq!(unknown.fields.get("currentValue"), Some(&json!(3)));
10223        assert!(!unknown.fields.contains_key("_meta"));
10224        assert_eq!(serialized_meta_key_count(&option), 1);
10225
10226        let json = serde_json::to_value(&option).unwrap();
10227        assert_eq!(json["type"], "_slider");
10228        assert_eq!(json["currentValue"], 3);
10229        assert_eq!(json["min"], 0);
10230        assert_eq!(json["max"], 5);
10231        assert_eq!(json["_meta"]["source"], "test");
10232    }
10233
10234    #[test]
10235    fn test_session_config_option_unknown_kind_does_not_duplicate_flattened_meta() {
10236        let mut fields = IndexMap::new();
10237        fields.insert("currentValue".to_string(), json!(3));
10238        fields.insert("_meta".to_string(), json!({ "inner": "ignored" }));
10239
10240        let option = SessionConfigOption::new(
10241            "verbosity",
10242            "Verbosity",
10243            SessionConfigKind::Other(OtherSessionConfigKind::new("_slider", fields)),
10244        )
10245        .meta(test_meta());
10246
10247        let SessionConfigKind::Other(unknown) = &option.kind else {
10248            panic!("expected unknown config kind");
10249        };
10250        assert!(!unknown.fields.contains_key("_meta"));
10251        assert_eq!(serialized_meta_key_count(&option), 1);
10252
10253        let json = serde_json::to_value(&option).unwrap();
10254        assert_eq!(json["type"], "_slider");
10255        assert_eq!(json["currentValue"], 3);
10256        assert_eq!(json["_meta"]["source"], "test");
10257    }
10258
10259    #[test]
10260    fn test_session_config_option_unknown_does_not_hide_malformed_known_kind() {
10261        assert!(
10262            serde_json::from_value::<SessionConfigOption>(json!({
10263                "configId": "model",
10264                "name": "Model",
10265                "type": "select"
10266            }))
10267            .is_err()
10268        );
10269    }
10270
10271    #[cfg(feature = "unstable_llm_providers")]
10272    #[test]
10273    fn test_llm_protocol_known_variants() {
10274        assert_eq!(
10275            serde_json::to_value(&LlmProtocol::Anthropic).unwrap(),
10276            json!("anthropic")
10277        );
10278        assert_eq!(
10279            serde_json::to_value(&LlmProtocol::OpenAi).unwrap(),
10280            json!("openai")
10281        );
10282        assert_eq!(
10283            serde_json::to_value(&LlmProtocol::Azure).unwrap(),
10284            json!("azure")
10285        );
10286        assert_eq!(
10287            serde_json::to_value(&LlmProtocol::Vertex).unwrap(),
10288            json!("vertex")
10289        );
10290        assert_eq!(
10291            serde_json::to_value(&LlmProtocol::Bedrock).unwrap(),
10292            json!("bedrock")
10293        );
10294
10295        assert_eq!(
10296            serde_json::from_str::<LlmProtocol>("\"anthropic\"").unwrap(),
10297            LlmProtocol::Anthropic
10298        );
10299        assert_eq!(
10300            serde_json::from_str::<LlmProtocol>("\"openai\"").unwrap(),
10301            LlmProtocol::OpenAi
10302        );
10303        assert_eq!(
10304            serde_json::from_str::<LlmProtocol>("\"azure\"").unwrap(),
10305            LlmProtocol::Azure
10306        );
10307        assert_eq!(
10308            serde_json::from_str::<LlmProtocol>("\"vertex\"").unwrap(),
10309            LlmProtocol::Vertex
10310        );
10311        assert_eq!(
10312            serde_json::from_str::<LlmProtocol>("\"bedrock\"").unwrap(),
10313            LlmProtocol::Bedrock
10314        );
10315    }
10316
10317    #[cfg(feature = "unstable_llm_providers")]
10318    #[test]
10319    fn test_llm_protocol_unknown_variant() {
10320        let unknown: LlmProtocol = serde_json::from_str("\"cohere\"").unwrap();
10321        assert_eq!(unknown, LlmProtocol::Other("cohere".to_string()));
10322
10323        let json = serde_json::to_value(&unknown).unwrap();
10324        assert_eq!(json, json!("cohere"));
10325    }
10326
10327    #[cfg(feature = "unstable_llm_providers")]
10328    #[test]
10329    fn test_provider_current_config_serialization() {
10330        let config =
10331            ProviderCurrentConfig::new(LlmProtocol::Anthropic, "https://api.anthropic.com");
10332
10333        let json = serde_json::to_value(&config).unwrap();
10334        assert_eq!(
10335            json,
10336            json!({
10337                "apiType": "anthropic",
10338                "baseUrl": "https://api.anthropic.com"
10339            })
10340        );
10341
10342        let deserialized: ProviderCurrentConfig = serde_json::from_value(json).unwrap();
10343        assert_eq!(deserialized.api_type, LlmProtocol::Anthropic);
10344        assert_eq!(deserialized.base_url, "https://api.anthropic.com");
10345    }
10346
10347    #[cfg(feature = "unstable_llm_providers")]
10348    #[test]
10349    fn test_provider_info_with_current_config() {
10350        let info = ProviderInfo::new(
10351            "main",
10352            vec![LlmProtocol::Anthropic, LlmProtocol::OpenAi],
10353            true,
10354            Some(ProviderCurrentConfig::new(
10355                LlmProtocol::Anthropic,
10356                "https://api.anthropic.com",
10357            )),
10358        );
10359
10360        let json = serde_json::to_value(&info).unwrap();
10361        assert_eq!(
10362            json,
10363            json!({
10364                "providerId": "main",
10365                "supported": ["anthropic", "openai"],
10366                "required": true,
10367                "current": {
10368                    "apiType": "anthropic",
10369                    "baseUrl": "https://api.anthropic.com"
10370                }
10371            })
10372        );
10373
10374        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10375        assert_eq!(deserialized.provider_id.to_string(), "main");
10376        assert_eq!(deserialized.supported.len(), 2);
10377        assert!(deserialized.required);
10378        assert!(deserialized.current.is_some());
10379        assert_eq!(
10380            deserialized.current.as_ref().unwrap().api_type,
10381            LlmProtocol::Anthropic
10382        );
10383    }
10384
10385    #[cfg(feature = "unstable_llm_providers")]
10386    #[test]
10387    fn test_provider_info_disabled() {
10388        let info = ProviderInfo::new(
10389            "secondary",
10390            vec![LlmProtocol::OpenAi],
10391            false,
10392            None::<ProviderCurrentConfig>,
10393        );
10394
10395        let json = serde_json::to_value(&info).unwrap();
10396        assert_eq!(
10397            json,
10398            json!({
10399                "providerId": "secondary",
10400                "supported": ["openai"],
10401                "required": false
10402            })
10403        );
10404
10405        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10406        assert_eq!(deserialized.provider_id.to_string(), "secondary");
10407        assert!(!deserialized.required);
10408        assert!(deserialized.current.is_none());
10409    }
10410
10411    #[cfg(feature = "unstable_llm_providers")]
10412    #[test]
10413    fn test_provider_info_missing_current_defaults_to_none() {
10414        // current is optional; omitting it should decode as None
10415        let json = json!({
10416            "providerId": "main",
10417            "supported": ["anthropic"],
10418            "required": true
10419        });
10420        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10421        assert!(deserialized.current.is_none());
10422    }
10423
10424    #[cfg(feature = "unstable_llm_providers")]
10425    #[test]
10426    fn test_provider_info_explicit_null_current_decodes_to_none() {
10427        // current: null and an omitted current are equivalent on the wire;
10428        // both must deserialize into None so the disabled state is preserved
10429        // regardless of which form the peer chose to send.
10430        let json = json!({
10431            "providerId": "main",
10432            "supported": ["anthropic"],
10433            "required": true,
10434            "current": null
10435        });
10436        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
10437        assert!(deserialized.current.is_none());
10438    }
10439
10440    #[cfg(feature = "unstable_llm_providers")]
10441    #[test]
10442    fn test_list_providers_response_serialization() {
10443        let response = ListProvidersResponse::new(vec![ProviderInfo::new(
10444            "main",
10445            vec![LlmProtocol::Anthropic],
10446            true,
10447            Some(ProviderCurrentConfig::new(
10448                LlmProtocol::Anthropic,
10449                "https://api.anthropic.com",
10450            )),
10451        )]);
10452
10453        let json = serde_json::to_value(&response).unwrap();
10454        assert_eq!(json["providers"].as_array().unwrap().len(), 1);
10455        assert_eq!(json["providers"][0]["providerId"], "main");
10456
10457        let deserialized: ListProvidersResponse = serde_json::from_value(json).unwrap();
10458        assert_eq!(deserialized.providers.len(), 1);
10459    }
10460
10461    #[cfg(feature = "unstable_llm_providers")]
10462    #[test]
10463    fn test_set_provider_request_serialization() {
10464        let mut headers = IndexMap::new();
10465        headers.insert("Authorization".to_string(), "Bearer sk-test".to_string());
10466
10467        let request =
10468            SetProviderRequest::new("main", LlmProtocol::OpenAi, "https://api.openai.com/v1")
10469                .headers(headers);
10470
10471        let json = serde_json::to_value(&request).unwrap();
10472        assert_eq!(
10473            json,
10474            json!({
10475                "providerId": "main",
10476                "apiType": "openai",
10477                "baseUrl": "https://api.openai.com/v1",
10478                "headers": {
10479                    "Authorization": "Bearer sk-test"
10480                }
10481            })
10482        );
10483
10484        let deserialized: SetProviderRequest = serde_json::from_value(json).unwrap();
10485        assert_eq!(deserialized.provider_id.to_string(), "main");
10486        assert_eq!(deserialized.api_type, LlmProtocol::OpenAi);
10487        assert_eq!(deserialized.base_url, "https://api.openai.com/v1");
10488        assert_eq!(deserialized.headers.len(), 1);
10489        assert_eq!(
10490            deserialized.headers.get("Authorization").unwrap(),
10491            "Bearer sk-test"
10492        );
10493    }
10494
10495    #[cfg(feature = "unstable_llm_providers")]
10496    #[test]
10497    fn test_set_provider_request_omits_empty_headers() {
10498        let request =
10499            SetProviderRequest::new("main", LlmProtocol::Anthropic, "https://api.anthropic.com");
10500
10501        let json = serde_json::to_value(&request).unwrap();
10502        // headers should be omitted when empty
10503        assert!(!json.as_object().unwrap().contains_key("headers"));
10504    }
10505
10506    #[cfg(feature = "unstable_llm_providers")]
10507    #[test]
10508    fn test_disable_provider_request_serialization() {
10509        let request = DisableProviderRequest::new("secondary");
10510
10511        let json = serde_json::to_value(&request).unwrap();
10512        assert_eq!(json, json!({ "providerId": "secondary" }));
10513
10514        let deserialized: DisableProviderRequest = serde_json::from_value(json).unwrap();
10515        assert_eq!(deserialized.provider_id.to_string(), "secondary");
10516    }
10517
10518    #[cfg(feature = "unstable_llm_providers")]
10519    #[test]
10520    fn test_providers_capabilities_serialization() {
10521        let caps = ProvidersCapabilities::new();
10522
10523        let json = serde_json::to_value(&caps).unwrap();
10524        assert_eq!(json, json!({}));
10525
10526        let deserialized: ProvidersCapabilities = serde_json::from_value(json).unwrap();
10527        assert!(deserialized.meta.is_none());
10528    }
10529
10530    #[cfg(feature = "unstable_llm_providers")]
10531    #[test]
10532    fn test_agent_capabilities_with_providers() {
10533        let caps = AgentCapabilities::new().providers(ProvidersCapabilities::new());
10534
10535        let json = serde_json::to_value(&caps).unwrap();
10536        assert_eq!(json["providers"], json!({}));
10537
10538        let deserialized: AgentCapabilities = serde_json::from_value(json).unwrap();
10539        assert!(deserialized.providers.is_some());
10540    }
10541
10542    #[test]
10543    fn test_agent_capabilities_session_is_explicit() {
10544        let json = serde_json::to_value(AgentCapabilities::new()).unwrap();
10545        assert!(json.get("session").is_none());
10546
10547        let caps = AgentCapabilities::new().session(
10548            SessionCapabilities::new()
10549                .prompt(PromptCapabilities::new().image(PromptImageCapabilities::new()))
10550                .mcp(McpCapabilities::new().stdio(McpStdioCapabilities::new())),
10551        );
10552
10553        assert_eq!(
10554            serde_json::to_value(&caps).unwrap(),
10555            json!({
10556                "session": {
10557                    "prompt": {
10558                        "image": {}
10559                    },
10560                    "mcp": {
10561                        "stdio": {}
10562                    }
10563                }
10564            })
10565        );
10566
10567        let deserialized: AgentCapabilities = serde_json::from_value(json!({
10568            "session": false
10569        }))
10570        .unwrap();
10571        assert!(deserialized.session.is_none());
10572    }
10573
10574    #[test]
10575    fn test_prompt_capabilities_serialize_supported_content_as_objects() {
10576        let caps = PromptCapabilities::new()
10577            .image(PromptImageCapabilities::new())
10578            .audio(PromptAudioCapabilities::new())
10579            .embedded_context(PromptEmbeddedContextCapabilities::new());
10580
10581        assert_eq!(
10582            serde_json::to_value(&caps).unwrap(),
10583            json!({
10584                "image": {},
10585                "audio": {},
10586                "embeddedContext": {}
10587            })
10588        );
10589
10590        let deserialized: PromptCapabilities = serde_json::from_value(json!({
10591            "image": null,
10592            "audio": false,
10593            "embeddedContext": {}
10594        }))
10595        .unwrap();
10596        assert!(deserialized.image.is_none());
10597        assert!(deserialized.audio.is_none());
10598        assert!(deserialized.embedded_context.is_some());
10599    }
10600
10601    #[cfg(feature = "unstable_agent_skills")]
10602    #[test]
10603    fn prompt_skill_capability_has_two_levels() {
10604        // `{}` allows one leading skill block. `inline` allows them anywhere.
10605        let leading = PromptCapabilities::new().skill(PromptSkillCapabilities::new());
10606        assert_eq!(
10607            serde_json::to_value(&leading).unwrap(),
10608            json!({ "skill": {} })
10609        );
10610
10611        let inline = PromptCapabilities::new()
10612            .skill(PromptSkillCapabilities::new().inline(PromptSkillInlineCapabilities::new()));
10613        let wire = json!({ "skill": { "inline": {} } });
10614        assert_eq!(serde_json::to_value(&inline).unwrap(), wire);
10615        assert_eq!(
10616            serde_json::from_value::<PromptCapabilities>(wire).unwrap(),
10617            inline
10618        );
10619
10620        for unsupported in [
10621            json!({}),
10622            json!({ "skill": null }),
10623            json!({ "skill": false }),
10624            json!({ "skill": true }),
10625        ] {
10626            let caps: PromptCapabilities = serde_json::from_value(unsupported).unwrap();
10627            assert!(caps.skill.is_none());
10628        }
10629
10630        // A malformed `inline` does not withdraw the first level.
10631        for leading_only in [
10632            json!({ "skill": { "inline": null } }),
10633            json!({ "skill": { "inline": true } }),
10634        ] {
10635            assert_eq!(
10636                serde_json::from_value::<PromptCapabilities>(leading_only).unwrap(),
10637                leading
10638            );
10639        }
10640    }
10641
10642    #[test]
10643    fn test_mcp_capabilities_serialize_supported_transports_as_objects() {
10644        let caps = McpCapabilities::new()
10645            .stdio(McpStdioCapabilities::new())
10646            .http(McpHttpCapabilities::new());
10647
10648        assert_eq!(
10649            serde_json::to_value(&caps).unwrap(),
10650            json!({
10651                "stdio": {},
10652                "http": {}
10653            })
10654        );
10655
10656        let deserialized: McpCapabilities = serde_json::from_value(json!({
10657            "stdio": null,
10658            "http": false
10659        }))
10660        .unwrap();
10661        assert!(deserialized.stdio.is_none());
10662        assert!(deserialized.http.is_none());
10663    }
10664
10665    #[cfg(feature = "unstable_mcp_over_acp")]
10666    #[test]
10667    fn test_mcp_capabilities_serialize_acp_support_as_object() {
10668        let caps = McpCapabilities::new().acp(McpAcpCapabilities::new());
10669
10670        assert_eq!(
10671            serde_json::to_value(&caps).unwrap(),
10672            json!({
10673                "acp": {}
10674            })
10675        );
10676    }
10677
10678    #[test]
10679    fn prompt_request_rejects_malformed_content_block() {
10680        use serde_json::json;
10681
10682        assert!(
10683            serde_json::from_value::<PromptRequest>(json!({
10684                "sessionId": "sess-1",
10685                "prompt": [{"type": "text"}]
10686            }))
10687            .is_err()
10688        );
10689    }
10690
10691    #[test]
10692    fn prompt_request_rejects_non_array_prompt() {
10693        use serde_json::json;
10694
10695        assert!(
10696            serde_json::from_value::<PromptRequest>(json!({
10697                "sessionId": "sess-1",
10698                "prompt": "hello"
10699            }))
10700            .is_err()
10701        );
10702    }
10703
10704    fn prompt_request_with_idempotency_key(key: &serde_json::Value) -> serde_json::Value {
10705        serde_json::json!({
10706            "sessionId": "sess-1",
10707            "idempotencyKey": key,
10708            "prompt": [{"type": "text", "text": "hello"}]
10709        })
10710    }
10711
10712    #[test]
10713    fn prompt_request_idempotency_key_round_trips() {
10714        use serde_json::json;
10715
10716        let key = "0b6f3c1e-8d2a-4c57-9a41-5e2f7d90c3ab";
10717        let value = prompt_request_with_idempotency_key(&json!(key));
10718
10719        let request: PromptRequest = serde_json::from_value(value.clone()).unwrap();
10720        assert_eq!(
10721            request.idempotency_key.as_ref().map(IdempotencyKey::as_str),
10722            Some(key)
10723        );
10724        assert_eq!(serde_json::to_value(&request).unwrap(), value);
10725
10726        let built = PromptRequest::new("sess-1", vec![ContentBlock::from("hello")])
10727            .idempotency_key(IdempotencyKey::new(key).unwrap());
10728        assert_eq!(built, request);
10729    }
10730
10731    #[test]
10732    fn prompt_request_omitted_and_null_idempotency_key_mean_no_key() {
10733        use serde_json::json;
10734
10735        let omitted = json!({
10736            "sessionId": "sess-1",
10737            "prompt": [{"type": "text", "text": "hello"}]
10738        });
10739        let request: PromptRequest = serde_json::from_value(omitted.clone()).unwrap();
10740        assert_eq!(request.idempotency_key, None);
10741        // No key is serialized as an omitted field, not as `null`.
10742        assert_eq!(serde_json::to_value(&request).unwrap(), omitted);
10743
10744        let null: PromptRequest =
10745            serde_json::from_value(prompt_request_with_idempotency_key(&json!(null))).unwrap();
10746        assert_eq!(null, request);
10747    }
10748
10749    #[test]
10750    fn prompt_request_rejects_malformed_idempotency_key() {
10751        use serde_json::json;
10752
10753        let too_long = "k".repeat(IdempotencyKey::MAX_LENGTH + 1);
10754        for (name, key) in [
10755            ("an empty string", json!("")),
10756            ("a string over 255 characters", json!(too_long)),
10757            ("a number", json!(7)),
10758            ("a boolean", json!(true)),
10759            ("an object", json!({"key": "k"})),
10760            ("an array", json!(["k"])),
10761        ] {
10762            assert!(
10763                serde_json::from_value::<PromptRequest>(prompt_request_with_idempotency_key(&key))
10764                    .is_err(),
10765                "{name} must fail the request instead of being treated as no key"
10766            );
10767        }
10768    }
10769
10770    #[test]
10771    fn idempotency_key_length_is_counted_in_characters() {
10772        use serde_json::json;
10773
10774        assert_eq!(IdempotencyKey::new(""), Err(InvalidIdempotencyKey::Empty));
10775        assert_eq!(IdempotencyKey::new("k").unwrap().as_str(), "k");
10776
10777        let longest = "k".repeat(IdempotencyKey::MAX_LENGTH);
10778        assert_eq!(
10779            IdempotencyKey::new(longest.as_str()).unwrap().as_str(),
10780            longest
10781        );
10782        assert_eq!(
10783            IdempotencyKey::new(format!("{longest}k")),
10784            Err(InvalidIdempotencyKey::TooLong)
10785        );
10786
10787        // 255 two-byte characters are 510 bytes and still within the limit.
10788        let multibyte = "é".repeat(IdempotencyKey::MAX_LENGTH);
10789        assert!(IdempotencyKey::new(multibyte.as_str()).is_ok());
10790        assert!(
10791            serde_json::from_value::<PromptRequest>(prompt_request_with_idempotency_key(&json!(
10792                multibyte
10793            )))
10794            .is_ok()
10795        );
10796        assert_eq!(
10797            IdempotencyKey::new(format!("{multibyte}é")),
10798            Err(InvalidIdempotencyKey::TooLong)
10799        );
10800
10801        assert_eq!("k".parse::<IdempotencyKey>().unwrap().to_string(), "k");
10802        assert_eq!(
10803            IdempotencyKey::try_from(String::new()),
10804            Err(InvalidIdempotencyKey::Empty)
10805        );
10806        assert_eq!(
10807            InvalidIdempotencyKey::TooLong.to_string(),
10808            "idempotency key must be at most 255 characters"
10809        );
10810    }
10811
10812    #[cfg(feature = "uuid")]
10813    #[test]
10814    fn generated_idempotency_keys_are_distinct_valid_v4_uuids() {
10815        let first = IdempotencyKey::generate();
10816        let second = IdempotencyKey::generate();
10817        assert_ne!(first, second);
10818
10819        for key in [&first, &second] {
10820            let uuid = uuid::Uuid::parse_str(key.as_str()).unwrap();
10821            assert_eq!(uuid.get_version_num(), 4);
10822            // A generated key passes the same validation as any other key.
10823            assert_eq!(IdempotencyKey::new(key.as_str()).as_ref(), Ok(key));
10824            let request = PromptRequest::new("sess-1", vec![ContentBlock::from("hello")])
10825                .idempotency_key(key.clone());
10826            let value = serde_json::to_value(&request).unwrap();
10827            assert_eq!(value["idempotencyKey"], key.as_str());
10828            assert_eq!(
10829                serde_json::from_value::<PromptRequest>(value).unwrap(),
10830                request
10831            );
10832        }
10833
10834        assert_eq!(
10835            IdempotencyKey::from(uuid::Uuid::nil()).as_str(),
10836            "00000000-0000-0000-0000-000000000000"
10837        );
10838    }
10839
10840    #[cfg(feature = "schemars")]
10841    #[test]
10842    fn idempotency_key_schema_is_a_strict_bounded_string() {
10843        use serde_json::json;
10844
10845        let key = serde_json::to_value(schemars::schema_for!(IdempotencyKey)).unwrap();
10846        assert_eq!(key["type"], "string");
10847        assert_eq!(key["minLength"], 1);
10848        assert_eq!(key["maxLength"], json!(IdempotencyKey::MAX_LENGTH));
10849
10850        let request = serde_json::to_value(schemars::schema_for!(PromptRequest)).unwrap();
10851        assert_eq!(request["required"], json!(["sessionId", "prompt"]));
10852        let property = &request["properties"]["idempotencyKey"];
10853        assert_eq!(
10854            property["anyOf"],
10855            json!([{"$ref": "#/$defs/IdempotencyKey"}, {"type": "null"}])
10856        );
10857        // The Agent acts on the key, so the schema must not mark it as tolerant
10858        // of malformed values.
10859        assert!(property.get("x-deserialize-default-on-error").is_none());
10860    }
10861
10862    fn assert_session_setup_lists_are_strict<T>(base: &serde_json::Value)
10863    where
10864        T: serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
10865    {
10866        let name = std::any::type_name::<T>();
10867        let with = |field: &str, value: serde_json::Value| {
10868            let mut request = base.clone();
10869            request[field] = value;
10870            serde_json::from_value::<T>(request)
10871        };
10872
10873        for (field, value) in [
10874            // Dropping the malformed server would start the session without it.
10875            (
10876                "mcpServers",
10877                json!([
10878                    {"type": "stdio", "name": "github", "command": "/usr/bin/gh-mcp", "env": [{"name": "GITHUB_TOKEN", "value": null}]},
10879                    {"type": "stdio", "name": "fs", "command": "/usr/bin/fs-mcp"}
10880                ]),
10881            ),
10882            ("mcpServers", json!({"type": "stdio", "name": "fs"})),
10883            ("additionalDirectories", json!(["/repo/lib", 42])),
10884            ("additionalDirectories", json!("/repo/lib")),
10885        ] {
10886            assert!(
10887                with(field, value.clone()).is_err(),
10888                "{name}.{field}: {value}"
10889            );
10890        }
10891
10892        let empty = serde_json::from_value::<T>(base.clone()).unwrap();
10893        for field in ["mcpServers", "additionalDirectories"] {
10894            assert_eq!(
10895                with(field, serde_json::Value::Null).unwrap(),
10896                empty,
10897                "{name}.{field}"
10898            );
10899        }
10900    }
10901
10902    #[test]
10903    fn session_setup_requests_reject_malformed_mcp_servers_and_directories() {
10904        assert_session_setup_lists_are_strict::<NewSessionRequest>(&json!({"cwd": "/repo"}));
10905        assert_session_setup_lists_are_strict::<ResumeSessionRequest>(&json!({
10906            "sessionId": "sess-1",
10907            "cwd": "/repo"
10908        }));
10909        #[cfg(feature = "unstable_session_fork")]
10910        assert_session_setup_lists_are_strict::<ForkSessionRequest>(&json!({
10911            "sessionId": "sess-1",
10912            "cwd": "/repo"
10913        }));
10914    }
10915
10916    #[test]
10917    fn resume_session_request_rejects_malformed_replay_from() {
10918        let request = |replay_from: serde_json::Value| {
10919            serde_json::from_value::<ResumeSessionRequest>(json!({
10920                "sessionId": "sess-1",
10921                "cwd": "/repo",
10922                "replayFrom": replay_from
10923            }))
10924        };
10925
10926        // Treating this as omitted would reconnect without the requested replay.
10927        assert!(request(json!("start")).is_err());
10928        assert_eq!(request(serde_json::Value::Null).unwrap().replay_from, None);
10929        assert!(matches!(
10930            request(json!({"type": "start"})).unwrap().replay_from,
10931            Some(ReplayFrom::Start(_))
10932        ));
10933    }
10934
10935    #[test]
10936    fn mcp_server_lists_treat_null_as_empty() {
10937        let servers: Vec<McpServer> = serde_json::from_value(json!([
10938            {"type": "stdio", "name": "fs", "command": "/usr/bin/fs-mcp", "args": null, "env": null},
10939            {"type": "http", "name": "api", "url": "https://example.com/mcp", "headers": null}
10940        ]))
10941        .unwrap();
10942
10943        assert_eq!(
10944            servers,
10945            vec![
10946                McpServer::Stdio(McpServerStdio::new("fs", "/usr/bin/fs-mcp")),
10947                McpServer::Http(McpServerHttp::new("api", "https://example.com/mcp")),
10948            ]
10949        );
10950    }
10951
10952    #[test]
10953    fn terminal_auth_methods_reject_malformed_launch_config() {
10954        // The client spawns a process from `args` and `env`, so a malformed
10955        // method is dropped from `authMethods` instead of launched with
10956        // altered arguments or preserved as an unknown method.
10957        let response: InitializeResponse = serde_json::from_value(json!({
10958            "protocolVersion": 2,
10959            "info": {"name": "agent", "version": "1.0.0"},
10960            "authMethods": [
10961                {"type": "terminal", "methodId": "bad-args", "name": "Log in", "args": ["auth", "--port", 8123]},
10962                {"type": "terminal", "methodId": "bad-env", "name": "Log in", "env": [{"name": "DEBUG", "value": 1}]},
10963                {"type": "terminal", "methodId": "null-config", "name": "Log in", "args": null, "env": null},
10964                {"type": "agent", "methodId": "agent", "name": "Agent login"}
10965            ]
10966        }))
10967        .unwrap();
10968
10969        assert_eq!(
10970            response.auth_methods,
10971            vec![
10972                AuthMethod::Terminal(AuthMethodTerminal::new("null-config", "Log in")),
10973                AuthMethod::Agent(AuthMethodAgent::new("agent", "Agent login")),
10974            ]
10975        );
10976    }
10977
10978    #[cfg(feature = "unstable_auth_status")]
10979    #[test]
10980    fn auth_status_response_round_trips() {
10981        let response = AuthStatusResponse::new(AuthState::Authenticated).accounts(vec![
10982            AuthAccount::new("Anthropic API key")
10983                .description("API key helper".to_string())
10984                .active(true),
10985            AuthAccount::new("Claude Max").email("user@example.com".to_string()),
10986        ]);
10987        let json = serde_json::to_value(&response).unwrap();
10988        assert_eq!(
10989            json,
10990            json!({
10991                "state": "authenticated",
10992                "accounts": [
10993                    {
10994                        "label": "Anthropic API key",
10995                        "description": "API key helper",
10996                        "active": true
10997                    },
10998                    {
10999                        "label": "Claude Max",
11000                        "email": "user@example.com"
11001                    }
11002                ]
11003            })
11004        );
11005        assert_eq!(
11006            serde_json::from_value::<AuthStatusResponse>(json).unwrap(),
11007            response
11008        );
11009        assert_eq!(
11010            serde_json::to_value(AuthStatusResponse::new(AuthState::NotRequired)).unwrap(),
11011            json!({"state": "not_required"})
11012        );
11013    }
11014
11015    #[cfg(feature = "unstable_auth_status")]
11016    #[test]
11017    fn auth_status_state_is_strict_and_accounts_are_lenient() {
11018        assert!(serde_json::from_value::<AuthStatusResponse>(json!({})).is_err());
11019        assert!(serde_json::from_value::<AuthStatusResponse>(json!({"state": null})).is_err());
11020        assert!(serde_json::from_value::<AuthStatusResponse>(json!({"state": 1})).is_err());
11021
11022        let response: AuthStatusResponse = serde_json::from_value(json!({
11023            "state": "_vendor_state",
11024            "accounts": [
11025                {"active": true},
11026                {
11027                    "label": "Vertex AI",
11028                    "description": 42,
11029                    "active": "yes",
11030                    "email": ["not", "a", "string"]
11031                }
11032            ]
11033        }))
11034        .unwrap();
11035        assert_eq!(
11036            response,
11037            AuthStatusResponse::new(AuthState::Other("_vendor_state".to_string()))
11038                .accounts(vec![AuthAccount::new("Vertex AI")])
11039        );
11040        assert_eq!(
11041            serde_json::from_value::<AuthStatusResponse>(
11042                json!({"state": "unknown", "accounts": null})
11043            )
11044            .unwrap(),
11045            AuthStatusResponse::new(AuthState::Unknown)
11046        );
11047    }
11048
11049    #[cfg(feature = "unstable_auth_status")]
11050    #[test]
11051    fn auth_status_update_notification_routes() {
11052        use crate::v2::{AgentNotification, CLIENT_METHOD_NAMES};
11053
11054        assert_eq!(AGENT_METHOD_NAMES.auth_status, "auth/status");
11055        assert_eq!(CLIENT_METHOD_NAMES.auth_status_update, "auth/status_update");
11056        let notification = AgentNotification::AuthStatusUpdateNotification(Box::new(
11057            AuthStatusUpdateNotification::new(AuthState::Unauthenticated),
11058        ));
11059        assert_eq!(notification.method(), "auth/status_update");
11060        assert_eq!(
11061            serde_json::to_value(&notification).unwrap(),
11062            json!({"state": "unauthenticated"})
11063        );
11064    }
11065
11066    #[cfg(all(
11067        feature = "unstable_session_fork",
11068        feature = "unstable_session_cursors"
11069    ))]
11070    #[test]
11071    fn fork_session_request_cursor_id_is_optional_and_strict() {
11072        let request = ForkSessionRequest::new("sess_abc123", "/home/user/project")
11073            .cursor_id(CursorId::new("cur_1"));
11074        let wire = json!({
11075            "sessionId": "sess_abc123",
11076            "cursorId": "cur_1",
11077            "cwd": "/home/user/project"
11078        });
11079        assert_eq!(serde_json::to_value(&request).unwrap(), wire);
11080        assert_eq!(
11081            serde_json::from_value::<ForkSessionRequest>(wire).unwrap(),
11082            request
11083        );
11084
11085        // Omitted and `null` both fork the whole session.
11086        for wire in [
11087            json!({ "sessionId": "sess_abc123", "cwd": "/home/user/project" }),
11088            json!({ "sessionId": "sess_abc123", "cwd": "/home/user/project", "cursorId": null }),
11089        ] {
11090            assert_eq!(
11091                serde_json::from_value::<ForkSessionRequest>(wire)
11092                    .unwrap()
11093                    .cursor_id,
11094                None
11095            );
11096        }
11097
11098        // A malformed cursor ID fails the request. It never forks the whole session.
11099        assert!(
11100            serde_json::from_value::<ForkSessionRequest>(json!({
11101                "sessionId": "sess_abc123",
11102                "cwd": "/home/user/project",
11103                "cursorId": 7
11104            }))
11105            .is_err()
11106        );
11107    }
11108}