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, collections::BTreeMap, sync::Arc};
7
8#[cfg(feature = "unstable_llm_providers")]
9use std::collections::HashMap;
10
11use derive_more::{Display, From};
12#[cfg(feature = "schemars")]
13use schemars::Schema;
14use serde::{Deserialize, Serialize};
15use serde_with::{DefaultOnError, DefaultOnNull, VecSkipError, serde_as, skip_serializing_none};
16
17use super::{
18    AbsolutePath, AvailableCommand, ClientCapabilities, ContentBlock, Error, ExtNotification,
19    ExtRequest, ExtResponse, MessageId, Meta, SessionId, TerminalId, ToolCallId,
20};
21use crate::{IntoOption, ProtocolVersion};
22
23#[cfg(feature = "unstable_session_status")]
24use super::StateUpdate;
25
26#[cfg(all(feature = "unstable_auth_status", feature = "schemars"))]
27use super::AUTH_STATUS_UPDATE_NOTIFICATION;
28#[cfg(feature = "unstable_mcp_over_acp")]
29use super::mcp::{MCP_MESSAGE_METHOD_NAME, MessageMcpNotification};
30
31// Initialize
32
33/// Request parameters for the initialize method.
34///
35/// Sent by the client to establish connection and negotiate capabilities.
36///
37/// See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/v2/initialization)
38#[serde_as]
39#[skip_serializing_none]
40#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
41#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
42#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = INITIALIZE_METHOD_NAME)))]
43#[serde(rename_all = "camelCase")]
44#[non_exhaustive]
45pub struct InitializeRequest {
46    /// The latest protocol version supported by the client.
47    pub protocol_version: ProtocolVersion,
48    /// Information about the implementation sending this initialize request.
49    pub info: Implementation,
50    /// Capabilities supported by the client.
51    #[serde_as(deserialize_as = "DefaultOnError")]
52    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
53    #[serde(default)]
54    pub capabilities: ClientCapabilities,
55    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
56    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
57    /// Implementations MUST NOT assign meaning to keys they do not recognize.
58    ///
59    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
60    #[serde_as(deserialize_as = "DefaultOnError")]
61    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
62    #[serde(default)]
63    #[serde(rename = "_meta")]
64    pub meta: Option<Meta>,
65}
66
67impl InitializeRequest {
68    /// Builds [`InitializeRequest`] with the required request fields set. Optional fields start unset or empty.
69    #[must_use]
70    pub fn new(protocol_version: ProtocolVersion, info: Implementation) -> Self {
71        Self {
72            protocol_version,
73            capabilities: ClientCapabilities::default(),
74            info,
75            meta: None,
76        }
77    }
78
79    /// Capabilities supported by the client.
80    #[must_use]
81    pub fn capabilities(mut self, capabilities: ClientCapabilities) -> Self {
82        self.capabilities = capabilities;
83        self
84    }
85
86    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
87    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
88    /// do not recognize.
89    ///
90    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
91    #[must_use]
92    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
93        self.meta = meta.into_option();
94        self
95    }
96}
97
98/// Response to the `initialize` method.
99///
100/// Contains the negotiated protocol version and agent capabilities.
101///
102/// See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/v2/initialization)
103#[serde_as]
104#[skip_serializing_none]
105#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
106#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
107#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = INITIALIZE_METHOD_NAME)))]
108#[serde(rename_all = "camelCase")]
109#[non_exhaustive]
110pub struct InitializeResponse {
111    /// The highest protocol version supported by the agent that is at or below
112    /// the version requested by the client. If no such version exists,
113    /// initialization fails with error code -32022.
114    ///
115    /// The client must check that it supports this version and should disconnect
116    /// if it does not.
117    pub protocol_version: ProtocolVersion,
118    /// Information about the implementation sending this initialize response.
119    pub info: Implementation,
120    /// Capabilities supported by the agent.
121    #[serde_as(deserialize_as = "DefaultOnError")]
122    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
123    #[serde(default)]
124    pub capabilities: AgentCapabilities,
125    /// Authentication methods supported by the agent.
126    ///
127    /// Optional. Omitted or empty means the agent does not advertise the
128    /// `auth/login` and `auth/logout` methods. Supplying one or more methods means
129    /// the agent MUST support both `auth/login` and `auth/logout`.
130    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
131    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
132    #[serde(default, skip_serializing_if = "Vec::is_empty")]
133    pub auth_methods: Vec<AuthMethod>,
134    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
135    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
136    /// Implementations MUST NOT assign meaning to keys they do not recognize.
137    ///
138    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
139    #[serde_as(deserialize_as = "DefaultOnError")]
140    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
141    #[serde(default)]
142    #[serde(rename = "_meta")]
143    pub meta: Option<Meta>,
144}
145
146impl InitializeResponse {
147    /// Builds [`InitializeResponse`] with the required response fields set. Optional fields start unset or empty.
148    #[must_use]
149    pub fn new(protocol_version: ProtocolVersion, info: Implementation) -> Self {
150        Self {
151            protocol_version,
152            capabilities: AgentCapabilities::default(),
153            auth_methods: vec![],
154            info,
155            meta: None,
156        }
157    }
158
159    /// Capabilities supported by the agent.
160    #[must_use]
161    pub fn capabilities(mut self, capabilities: AgentCapabilities) -> Self {
162        self.capabilities = capabilities;
163        self
164    }
165
166    /// Authentication methods supported by the agent.
167    ///
168    /// Supplying one or more methods means the agent MUST support both
169    /// `auth/login` and `auth/logout`.
170    #[must_use]
171    pub fn auth_methods(mut self, auth_methods: Vec<AuthMethod>) -> Self {
172        self.auth_methods = auth_methods;
173        self
174    }
175
176    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
177    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
178    /// do not recognize.
179    ///
180    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
181    #[must_use]
182    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
183        self.meta = meta.into_option();
184        self
185    }
186}
187
188/// Metadata about the implementation of the client or agent.
189/// Describes the name and version of an ACP implementation, with an optional
190/// title for UI representation.
191#[serde_as]
192#[skip_serializing_none]
193#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
194#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
195#[serde(rename_all = "camelCase")]
196#[non_exhaustive]
197pub struct Implementation {
198    /// Intended for programmatic or logical use, but can be used as a display
199    /// name fallback if title isn't present.
200    pub name: String,
201    /// Intended for UI and end-user contexts and optimized to be human-readable
202    /// and easily understood.
203    ///
204    /// If not provided, the name should be used for display.
205    ///
206    /// Omitted and `null` are equivalent and mean the `name` is used for display.
207    #[serde_as(deserialize_as = "DefaultOnError")]
208    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
209    #[serde(default)]
210    pub title: Option<String>,
211    /// Version of the implementation. Can be displayed to the user or used
212    /// for debugging or metrics purposes. (e.g. "1.0.0").
213    pub version: String,
214    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
215    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
216    /// Implementations MUST NOT assign meaning to keys they do not recognize.
217    ///
218    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
219    #[serde_as(deserialize_as = "DefaultOnError")]
220    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
221    #[serde(default)]
222    #[serde(rename = "_meta")]
223    pub meta: Option<Meta>,
224}
225
226impl Implementation {
227    /// Builds [`Implementation`] with the required fields set. Optional fields start unset or empty.
228    #[must_use]
229    pub fn new(name: impl Into<String>, version: impl Into<String>) -> Self {
230        Self {
231            name: name.into(),
232            title: None,
233            version: version.into(),
234            meta: None,
235        }
236    }
237
238    /// Intended for UI and end-user contexts and optimized to be human-readable
239    /// and easily understood.
240    ///
241    /// If not provided, the name should be used for display.
242    #[must_use]
243    pub fn title(mut self, title: impl IntoOption<String>) -> Self {
244        self.title = title.into_option();
245        self
246    }
247
248    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
249    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
250    /// do not recognize.
251    ///
252    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
253    #[must_use]
254    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
255        self.meta = meta.into_option();
256        self
257    }
258}
259
260// Authentication
261
262/// Request parameters for the `auth/login` method.
263///
264/// Specifies which authentication method to use.
265///
266/// Agents MUST support this method when their `initialize` response included
267/// a non-empty `authMethods` list. Clients MUST NOT call this method
268/// when `authMethods` was omitted or empty.
269#[serde_as]
270#[skip_serializing_none]
271#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
272#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
273#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGIN_METHOD_NAME)))]
274#[serde(rename_all = "camelCase")]
275#[non_exhaustive]
276pub struct LoginAuthRequest {
277    /// The ID of the authentication method to use.
278    /// Must be one of the methods advertised in the initialize response.
279    pub method_id: AuthMethodId,
280    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
281    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
282    /// Implementations MUST NOT assign meaning to keys they do not recognize.
283    ///
284    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
285    #[serde_as(deserialize_as = "DefaultOnError")]
286    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
287    #[serde(default)]
288    #[serde(rename = "_meta")]
289    pub meta: Option<Meta>,
290}
291
292impl LoginAuthRequest {
293    /// Builds [`LoginAuthRequest`] with the required request fields set. Optional fields start unset or empty.
294    #[must_use]
295    pub fn new(method_id: impl Into<AuthMethodId>) -> Self {
296        Self {
297            method_id: method_id.into(),
298            meta: None,
299        }
300    }
301
302    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
303    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
304    /// do not recognize.
305    ///
306    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
307    #[must_use]
308    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
309        self.meta = meta.into_option();
310        self
311    }
312}
313
314crate::serde_util::default_on_null! {
315    /// Response to the `auth/login` method.
316    #[serde_as]
317    #[skip_serializing_none]
318    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
319    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
320    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGIN_METHOD_NAME)))]
321    #[serde(rename_all = "camelCase")]
322    #[non_exhaustive]
323    pub struct LoginAuthResponse {
324        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
325        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
326        /// Implementations MUST NOT assign meaning to keys they do not recognize.
327        ///
328        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
329        #[serde_as(deserialize_as = "DefaultOnError")]
330        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
331        #[serde(default)]
332        #[serde(rename = "_meta")]
333        pub meta: Option<Meta>,
334    }
335}
336
337impl LoginAuthResponse {
338    /// Builds [`LoginAuthResponse`] with the required response fields set. Optional fields start unset or empty.
339    #[must_use]
340    pub fn new() -> Self {
341        Self::default()
342    }
343
344    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
345    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
346    /// do not recognize.
347    ///
348    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
349    #[must_use]
350    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
351        self.meta = meta.into_option();
352        self
353    }
354}
355
356// Logout
357
358crate::serde_util::default_on_null! {
359    /// Request parameters for the `auth/logout` method.
360    ///
361    /// Terminates the current authenticated session.
362    ///
363    /// Agents MUST support this method when their `initialize` response included
364    /// a non-empty `authMethods` list. Clients MUST NOT call this method
365    /// when `authMethods` was omitted or empty.
366    #[serde_as]
367    #[skip_serializing_none]
368    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
369    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
370    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGOUT_METHOD_NAME)))]
371    #[serde(rename_all = "camelCase")]
372    #[non_exhaustive]
373    pub struct LogoutAuthRequest {
374        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
375        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
376        /// Implementations MUST NOT assign meaning to keys they do not recognize.
377        ///
378        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
379        #[serde_as(deserialize_as = "DefaultOnError")]
380        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
381        #[serde(default)]
382        #[serde(rename = "_meta")]
383        pub meta: Option<Meta>,
384    }
385}
386
387impl LogoutAuthRequest {
388    /// Builds [`LogoutAuthRequest`] with the required request fields set. Optional fields start unset or empty.
389    #[must_use]
390    pub fn new() -> Self {
391        Self::default()
392    }
393
394    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
395    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
396    /// do not recognize.
397    ///
398    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
399    #[must_use]
400    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
401        self.meta = meta.into_option();
402        self
403    }
404}
405
406crate::serde_util::default_on_null! {
407    /// Response to the `auth/logout` method.
408    #[serde_as]
409    #[skip_serializing_none]
410    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
411    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
412    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_LOGOUT_METHOD_NAME)))]
413    #[serde(rename_all = "camelCase")]
414    #[non_exhaustive]
415    pub struct LogoutAuthResponse {
416        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
417        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
418        /// Implementations MUST NOT assign meaning to keys they do not recognize.
419        ///
420        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
421        #[serde_as(deserialize_as = "DefaultOnError")]
422        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
423        #[serde(default)]
424        #[serde(rename = "_meta")]
425        pub meta: Option<Meta>,
426    }
427}
428
429impl LogoutAuthResponse {
430    /// Builds [`LogoutAuthResponse`] with the required response fields set. Optional fields start unset or empty.
431    #[must_use]
432    pub fn new() -> Self {
433        Self::default()
434    }
435
436    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
437    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
438    /// do not recognize.
439    ///
440    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
441    #[must_use]
442    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
443        self.meta = meta.into_option();
444        self
445    }
446}
447
448// Auth status
449
450#[cfg(feature = "unstable_auth_status")]
451crate::serde_util::default_on_null! {
452    /// **UNSTABLE**
453    ///
454    /// This capability is not part of the spec yet, and may be removed or changed at any point.
455    ///
456    /// Request parameters for the `auth/status` method.
457    ///
458    /// Queries the agent's current authentication state without changing it.
459    ///
460    /// Agents MUST NOT reject it with `auth_required` (`-32000`), since Clients call it to learn
461    /// whether authentication is required.
462    #[serde_as]
463    #[skip_serializing_none]
464    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
465    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
466    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_STATUS_METHOD_NAME)))]
467    #[serde(rename_all = "camelCase")]
468    #[non_exhaustive]
469    pub struct AuthStatusRequest {
470        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
471        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
472        /// Implementations MUST NOT assign meaning to keys they do not recognize.
473        ///
474        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
475        #[serde_as(deserialize_as = "DefaultOnError")]
476        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
477        #[serde(default)]
478        #[serde(rename = "_meta")]
479        pub meta: Option<Meta>,
480    }
481}
482
483#[cfg(feature = "unstable_auth_status")]
484impl AuthStatusRequest {
485    /// Builds [`AuthStatusRequest`] with the required request fields set. Optional fields start unset or empty.
486    #[must_use]
487    pub fn new() -> Self {
488        Self::default()
489    }
490
491    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
492    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
493    /// do not recognize.
494    ///
495    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
496    #[must_use]
497    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
498        self.meta = meta.into_option();
499        self
500    }
501}
502
503/// **UNSTABLE**
504///
505/// This capability is not part of the spec yet, and may be removed or changed at any point.
506///
507/// Response to the `auth/status` method.
508#[cfg(feature = "unstable_auth_status")]
509#[serde_as]
510#[skip_serializing_none]
511#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
512#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
513#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_STATUS_METHOD_NAME)))]
514#[serde(rename_all = "camelCase")]
515#[non_exhaustive]
516pub struct AuthStatusResponse {
517    /// Whether the agent can start sessions without the user signing in first.
518    ///
519    /// Clients use this field to decide whether sign-in is needed. Clients MUST treat
520    /// values they do not recognize as `unknown`.
521    pub state: AuthState,
522    /// The accounts the agent has configured, for display.
523    ///
524    /// Optional. Omitted and empty are equivalent and mean no accounts are reported.
525    /// Agents that hold credentials for several providers or accounts SHOULD list each
526    /// of them and mark the ones in effect with `active`.
527    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
528    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
529    #[serde(default, skip_serializing_if = "Vec::is_empty")]
530    pub accounts: Vec<AuthAccount>,
531    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
532    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
533    /// Implementations MUST NOT assign meaning to keys they do not recognize.
534    ///
535    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
536    #[serde_as(deserialize_as = "DefaultOnError")]
537    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
538    #[serde(default)]
539    #[serde(rename = "_meta")]
540    pub meta: Option<Meta>,
541}
542
543#[cfg(feature = "unstable_auth_status")]
544impl AuthStatusResponse {
545    /// Builds [`AuthStatusResponse`] with the required fields set. Optional fields start unset or empty.
546    #[must_use]
547    pub fn new(state: AuthState) -> Self {
548        Self {
549            state,
550            accounts: vec![],
551            meta: None,
552        }
553    }
554
555    /// The accounts the agent has configured, for display.
556    #[must_use]
557    pub fn accounts(mut self, accounts: Vec<AuthAccount>) -> Self {
558        self.accounts = accounts;
559        self
560    }
561
562    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
563    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
564    /// do not recognize.
565    ///
566    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
567    #[must_use]
568    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
569        self.meta = meta.into_option();
570        self
571    }
572}
573
574/// **UNSTABLE**
575///
576/// This capability is not part of the spec yet, and may be removed or changed at any point.
577///
578/// Notification sent by the agent when its authentication status changes.
579///
580/// Carries the same fields as the `auth/status` response. Agents that advertise the
581/// `auth.status` capability MAY send it at any time after `initialize`, and SHOULD only
582/// send it when the reported status differs from the last one sent on the connection.
583#[cfg(feature = "unstable_auth_status")]
584#[serde_as]
585#[skip_serializing_none]
586#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
587#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
588#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = AUTH_STATUS_UPDATE_NOTIFICATION)))]
589#[serde(rename_all = "camelCase")]
590#[non_exhaustive]
591pub struct AuthStatusUpdateNotification {
592    /// Whether the agent can start sessions without the user signing in first.
593    ///
594    /// Clients use this field to decide whether sign-in is needed. Clients MUST treat
595    /// values they do not recognize as `unknown`.
596    pub state: AuthState,
597    /// The accounts the agent has configured, for display.
598    ///
599    /// Optional. Omitted and empty are equivalent and mean no accounts are reported.
600    /// Agents that hold credentials for several providers or accounts SHOULD list each
601    /// of them and mark the ones in effect with `active`.
602    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
603    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
604    #[serde(default, skip_serializing_if = "Vec::is_empty")]
605    pub accounts: Vec<AuthAccount>,
606    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
607    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
608    /// Implementations MUST NOT assign meaning to keys they do not recognize.
609    ///
610    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
611    #[serde_as(deserialize_as = "DefaultOnError")]
612    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
613    #[serde(default)]
614    #[serde(rename = "_meta")]
615    pub meta: Option<Meta>,
616}
617
618#[cfg(feature = "unstable_auth_status")]
619impl AuthStatusUpdateNotification {
620    /// Builds [`AuthStatusUpdateNotification`] with the required fields set. Optional fields start unset or empty.
621    #[must_use]
622    pub fn new(state: AuthState) -> Self {
623        Self {
624            state,
625            accounts: vec![],
626            meta: None,
627        }
628    }
629
630    /// The accounts the agent has configured, for display.
631    #[must_use]
632    pub fn accounts(mut self, accounts: Vec<AuthAccount>) -> Self {
633        self.accounts = accounts;
634        self
635    }
636
637    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
638    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
639    /// do not recognize.
640    ///
641    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
642    #[must_use]
643    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
644        self.meta = meta.into_option();
645        self
646    }
647}
648
649/// **UNSTABLE**
650///
651/// This capability is not part of the spec yet, and may be removed or changed at any point.
652///
653/// The agent's overall authentication state.
654#[cfg(feature = "unstable_auth_status")]
655#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
656#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
657#[serde(rename_all = "snake_case")]
658#[non_exhaustive]
659pub enum AuthState {
660    /// Credentials are configured. This does not guarantee that they are valid.
661    Authenticated,
662    /// The user needs to sign in. This includes credentials that are missing,
663    /// expired, or known to be invalid.
664    Unauthenticated,
665    /// No authentication is needed, for example because the agent uses a local model.
666    NotRequired,
667    /// The agent cannot currently determine the state.
668    Unknown,
669    /// Custom or future authentication state.
670    ///
671    /// Values beginning with `_` are reserved for implementation-specific
672    /// extensions. Unknown values that do not begin with `_` are reserved for
673    /// future ACP variants.
674    #[serde(untagged)]
675    Other(String),
676}
677
678/// **UNSTABLE**
679///
680/// This capability is not part of the spec yet, and may be removed or changed at any point.
681///
682/// An account or credential the agent has configured, such as a signed-in user
683/// account or an API key.
684///
685/// All fields are display information only. Clients MUST NOT use them as stable
686/// account identifiers, and SHOULD NOT log them or send them elsewhere, such as to
687/// telemetry.
688#[cfg(feature = "unstable_auth_status")]
689#[serde_as]
690#[skip_serializing_none]
691#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
692#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
693#[serde(rename_all = "camelCase")]
694#[non_exhaustive]
695pub struct AuthAccount {
696    /// Human-readable name for the account, suitable for display on its own,
697    /// for example `Claude Max`, `OpenAI API key`, or `Vertex AI`.
698    pub label: String,
699    /// Short text shown with the label, such as the credential source, for example
700    /// `API key helper`. MUST NOT contain credentials.
701    ///
702    /// Optional. Omitted and `null` are equivalent and mean no description is reported.
703    #[serde_as(deserialize_as = "DefaultOnError")]
704    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
705    #[serde(default)]
706    pub description: Option<String>,
707    /// Whether the agent currently uses this account by default.
708    ///
709    /// Several accounts MAY be active, for example one per provider.
710    ///
711    /// Optional. Omitted and `null` are equivalent and mean the agent does not indicate whether this account is in effect.
712    #[serde_as(deserialize_as = "DefaultOnError")]
713    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
714    #[serde(default)]
715    pub active: Option<bool>,
716    /// Display name of the user, such as a username or full name.
717    ///
718    /// Optional. Omitted and `null` are equivalent and mean no name is reported.
719    #[serde_as(deserialize_as = "DefaultOnError")]
720    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
721    #[serde(default)]
722    pub name: Option<String>,
723    /// Email address of the user.
724    ///
725    /// Optional. Omitted and `null` are equivalent and mean no email is reported.
726    #[serde_as(deserialize_as = "DefaultOnError")]
727    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
728    #[serde(default)]
729    pub email: Option<String>,
730    /// Display name of the organization, team, or workspace the account is using.
731    ///
732    /// Optional. Omitted and `null` are equivalent and mean no organization is reported.
733    #[serde_as(deserialize_as = "DefaultOnError")]
734    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
735    #[serde(default)]
736    pub organization: Option<String>,
737    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
738    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
739    /// Implementations MUST NOT assign meaning to keys they do not recognize.
740    ///
741    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
742    #[serde_as(deserialize_as = "DefaultOnError")]
743    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
744    #[serde(default)]
745    #[serde(rename = "_meta")]
746    pub meta: Option<Meta>,
747}
748
749#[cfg(feature = "unstable_auth_status")]
750impl AuthAccount {
751    /// Builds [`AuthAccount`] with the required fields set. Optional fields start unset or empty.
752    #[must_use]
753    pub fn new(label: impl Into<String>) -> Self {
754        Self {
755            label: label.into(),
756            description: None,
757            active: None,
758            name: None,
759            email: None,
760            organization: None,
761            meta: None,
762        }
763    }
764
765    /// Short text shown with the label, such as the credential source.
766    #[must_use]
767    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
768        self.description = description.into_option();
769        self
770    }
771
772    /// Whether the agent currently uses this account by default.
773    #[must_use]
774    pub fn active(mut self, active: impl IntoOption<bool>) -> Self {
775        self.active = active.into_option();
776        self
777    }
778
779    /// Display name of the user, such as a username or full name.
780    #[must_use]
781    pub fn name(mut self, name: impl IntoOption<String>) -> Self {
782        self.name = name.into_option();
783        self
784    }
785
786    /// Email address of the user.
787    #[must_use]
788    pub fn email(mut self, email: impl IntoOption<String>) -> Self {
789        self.email = email.into_option();
790        self
791    }
792
793    /// Display name of the organization, team, or workspace the account is using.
794    #[must_use]
795    pub fn organization(mut self, organization: impl IntoOption<String>) -> Self {
796        self.organization = organization.into_option();
797        self
798    }
799
800    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
801    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
802    /// do not recognize.
803    ///
804    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
805    #[must_use]
806    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
807        self.meta = meta.into_option();
808        self
809    }
810}
811
812/// **UNSTABLE**
813///
814/// This capability is not part of the spec yet, and may be removed or changed at any point.
815///
816/// Auth status capabilities supported by the agent.
817///
818/// Supplying `{}` means the agent supports the `auth/status` method.
819#[cfg(feature = "unstable_auth_status")]
820#[serde_as]
821#[skip_serializing_none]
822#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
823#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
824#[non_exhaustive]
825pub struct AuthStatusCapabilities {
826    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
827    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
828    /// Implementations MUST NOT assign meaning to keys they do not recognize.
829    ///
830    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
831    #[serde_as(deserialize_as = "DefaultOnError")]
832    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
833    #[serde(default)]
834    #[serde(rename = "_meta")]
835    pub meta: Option<Meta>,
836}
837
838#[cfg(feature = "unstable_auth_status")]
839impl AuthStatusCapabilities {
840    /// Builds an empty [`AuthStatusCapabilities`]. Use builder methods to advertise supported sub-capabilities.
841    #[must_use]
842    pub fn new() -> Self {
843        Self::default()
844    }
845
846    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
847    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
848    /// do not recognize.
849    ///
850    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
851    #[must_use]
852    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
853        self.meta = meta.into_option();
854        self
855    }
856}
857
858/// Authentication-related extension capabilities supported by the agent.
859///
860/// This object does not advertise support for `auth/login` or `auth/logout`.
861/// Those methods are advertised by a non-empty `authMethods` list in the
862/// `initialize` response.
863#[serde_as]
864#[skip_serializing_none]
865#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
866#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
867#[serde(rename_all = "camelCase")]
868#[non_exhaustive]
869pub struct AgentAuthCapabilities {
870    /// **UNSTABLE**
871    ///
872    /// This capability is not part of the spec yet, and may be removed or changed at any point.
873    ///
874    /// Whether the agent supports the `auth/status` method.
875    ///
876    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
877    /// Supplying `{}` means the agent supports the `auth/status` method.
878    #[cfg(feature = "unstable_auth_status")]
879    #[serde_as(deserialize_as = "DefaultOnError")]
880    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
881    #[serde(default)]
882    pub status: Option<AuthStatusCapabilities>,
883    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
884    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
885    /// Implementations MUST NOT assign meaning to keys they do not recognize.
886    ///
887    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
888    #[serde_as(deserialize_as = "DefaultOnError")]
889    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
890    #[serde(default)]
891    #[serde(rename = "_meta")]
892    pub meta: Option<Meta>,
893}
894
895impl AgentAuthCapabilities {
896    /// Builds an empty [`AgentAuthCapabilities`].
897    #[must_use]
898    pub fn new() -> Self {
899        Self::default()
900    }
901
902    /// **UNSTABLE**
903    ///
904    /// This capability is not part of the spec yet, and may be removed or changed at any point.
905    ///
906    /// Whether the agent supports the `auth/status` method.
907    #[cfg(feature = "unstable_auth_status")]
908    #[must_use]
909    pub fn status(mut self, status: impl IntoOption<AuthStatusCapabilities>) -> Self {
910        self.status = status.into_option();
911        self
912    }
913
914    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
915    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
916    /// do not recognize.
917    ///
918    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
919    #[must_use]
920    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
921        self.meta = meta.into_option();
922        self
923    }
924}
925
926/// Typed identifier used for auth method values on the wire.
927#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
928#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
929#[serde(transparent)]
930#[from(forward)]
931#[non_exhaustive]
932pub struct AuthMethodId(pub Arc<str>);
933
934impl AuthMethodId {
935    /// Wraps a protocol string as a typed [`AuthMethodId`].
936    #[must_use]
937    pub fn new(id: impl Into<Self>) -> Self {
938        id.into()
939    }
940}
941
942/// Describes an available authentication method.
943///
944/// The `type` field acts as the discriminator in the serialized JSON form.
945#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
946#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
947#[serde(tag = "type", rename_all = "snake_case")]
948#[non_exhaustive]
949pub enum AuthMethod {
950    /// Client runs the configured agent program as a separate interactive
951    /// process, without passing this method to `auth/login`.
952    Terminal(AuthMethodTerminal),
953    /// Agent handles authentication itself through `auth/login`.
954    ///
955    /// The `type` discriminator value is `agent`.
956    Agent(AuthMethodAgent),
957    /// Custom or future authentication method.
958    ///
959    /// Values beginning with `_` are reserved for implementation-specific
960    /// extensions. Unknown values that do not begin with `_` are reserved for
961    /// future ACP variants.
962    ///
963    /// Clients that do not understand this method type should preserve the raw
964    /// payload when storing, replaying, proxying, or forwarding initialization
965    /// data, and otherwise ignore the method or display it generically.
966    #[serde(untagged)]
967    Other(OtherAuthMethod),
968}
969
970impl AuthMethod {
971    /// The unique identifier for this authentication method.
972    #[must_use]
973    pub fn method_id(&self) -> &AuthMethodId {
974        match self {
975            Self::Agent(a) => &a.method_id,
976            Self::Other(a) => &a.method_id,
977            Self::Terminal(t) => &t.method_id,
978        }
979    }
980
981    /// The human-readable name of this authentication method.
982    #[must_use]
983    pub fn name(&self) -> &str {
984        match self {
985            Self::Agent(a) => &a.name,
986            Self::Other(a) => &a.name,
987            Self::Terminal(t) => &t.name,
988        }
989    }
990
991    /// Optional human-readable description of this authentication method.
992    #[must_use]
993    pub fn description(&self) -> Option<&str> {
994        match self {
995            Self::Agent(a) => a.description.as_deref(),
996            Self::Other(a) => a
997                .fields
998                .get("description")
999                .and_then(serde_json::Value::as_str),
1000            Self::Terminal(t) => t.description.as_deref(),
1001        }
1002    }
1003
1004    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1005    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1006    /// do not recognize.
1007    ///
1008    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1009    #[must_use]
1010    pub fn meta(&self) -> Option<&Meta> {
1011        match self {
1012            Self::Agent(a) => a.meta.as_ref(),
1013            Self::Other(a) => a.fields.get("_meta").and_then(serde_json::Value::as_object),
1014            Self::Terminal(t) => t.meta.as_ref(),
1015        }
1016    }
1017}
1018
1019/// Custom or future authentication method payload.
1020#[serde_as]
1021#[skip_serializing_none]
1022#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1023#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1024#[cfg_attr(feature = "schemars", schemars(inline))]
1025#[cfg_attr(feature = "schemars", schemars(transform = other_auth_method_schema))]
1026#[serde(rename_all = "camelCase")]
1027#[non_exhaustive]
1028pub struct OtherAuthMethod {
1029    /// Custom or future authentication method type.
1030    ///
1031    /// Values beginning with `_` are reserved for implementation-specific
1032    /// extensions. Unknown values that do not begin with `_` are reserved for
1033    /// future ACP variants.
1034    #[serde(rename = "type")]
1035    pub type_: String,
1036    /// Unique identifier for this authentication method.
1037    pub method_id: AuthMethodId,
1038    /// Human-readable name of the authentication method.
1039    pub name: String,
1040    /// The remaining fields of the unknown authentication method payload, preserved verbatim,
1041    /// including `description` and `_meta`.
1042    #[serde(flatten)]
1043    pub fields: BTreeMap<String, serde_json::Value>,
1044}
1045
1046impl OtherAuthMethod {
1047    /// Builds [`OtherAuthMethod`] from an unknown discriminator and preserves the remaining extension fields.
1048    #[must_use]
1049    pub fn new(
1050        type_: impl Into<String>,
1051        method_id: impl Into<AuthMethodId>,
1052        name: impl Into<String>,
1053        mut fields: BTreeMap<String, serde_json::Value>,
1054    ) -> Self {
1055        fields.remove("type");
1056        fields.remove("methodId");
1057        fields.remove("name");
1058        Self {
1059            type_: type_.into(),
1060            method_id: method_id.into(),
1061            name: name.into(),
1062            fields,
1063        }
1064    }
1065}
1066
1067impl<'de> Deserialize<'de> for OtherAuthMethod {
1068    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1069    where
1070        D: serde::Deserializer<'de>,
1071    {
1072        #[derive(Deserialize)]
1073        #[serde(rename_all = "camelCase")]
1074        struct RawOtherAuthMethod {
1075            #[serde(rename = "type")]
1076            type_: String,
1077            method_id: AuthMethodId,
1078            name: String,
1079            #[serde(flatten)]
1080            fields: BTreeMap<String, serde_json::Value>,
1081        }
1082
1083        let raw = RawOtherAuthMethod::deserialize(deserializer)?;
1084        if is_known_auth_method_type(&raw.type_) {
1085            return Err(serde::de::Error::custom(format!(
1086                "known authentication method `{}` did not match its schema",
1087                raw.type_
1088            )));
1089        }
1090
1091        Ok(Self {
1092            type_: raw.type_,
1093            method_id: raw.method_id,
1094            name: raw.name,
1095            fields: raw.fields,
1096        })
1097    }
1098}
1099
1100fn is_known_auth_method_type(type_: &str) -> bool {
1101    matches!(type_, "agent" | "terminal")
1102}
1103
1104#[cfg(feature = "schemars")]
1105fn other_auth_method_schema(schema: &mut Schema) {
1106    super::schema_util::reject_known_string_discriminators(schema, "type", &["agent", "terminal"]);
1107}
1108
1109/// Agent handles authentication itself through `auth/login`.
1110///
1111/// The `type` discriminator value is `agent`.
1112#[serde_as]
1113#[skip_serializing_none]
1114#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1115#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1116#[serde(rename_all = "camelCase")]
1117#[non_exhaustive]
1118pub struct AuthMethodAgent {
1119    /// Unique identifier for this authentication method.
1120    pub method_id: AuthMethodId,
1121    /// Human-readable name of the authentication method.
1122    pub name: String,
1123    /// Optional human-readable description of this authentication method.
1124    ///
1125    /// Omitted and `null` are equivalent and mean no description is provided.
1126    #[serde_as(deserialize_as = "DefaultOnError")]
1127    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1128    #[serde(default)]
1129    pub description: Option<String>,
1130    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1131    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1132    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1133    ///
1134    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1135    #[serde_as(deserialize_as = "DefaultOnError")]
1136    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1137    #[serde(default)]
1138    #[serde(rename = "_meta")]
1139    pub meta: Option<Meta>,
1140}
1141
1142impl AuthMethodAgent {
1143    /// Builds [`AuthMethodAgent`] with the required fields set. Optional fields start unset or empty.
1144    #[must_use]
1145    pub fn new(method_id: impl Into<AuthMethodId>, name: impl Into<String>) -> Self {
1146        Self {
1147            method_id: method_id.into(),
1148            name: name.into(),
1149            description: None,
1150            meta: None,
1151        }
1152    }
1153
1154    /// Optional human-readable description of this authentication method.
1155    #[must_use]
1156    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
1157        self.description = description.into_option();
1158        self
1159    }
1160
1161    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1162    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1163    /// do not recognize.
1164    ///
1165    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1166    #[must_use]
1167    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1168        self.meta = meta.into_option();
1169        self
1170    }
1171}
1172
1173/// Terminal-based authentication method.
1174///
1175/// The client runs the configured agent program as a separate interactive
1176/// process for the user to authenticate via a TUI. Agents MUST advertise this
1177/// method only when the client enabled its terminal authentication capability.
1178/// A zero exit status signals success. Any other termination signals failure.
1179/// The client MUST NOT pass this method to `auth/login`.
1180#[serde_as]
1181#[skip_serializing_none]
1182#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1183#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1184#[serde(rename_all = "camelCase")]
1185#[non_exhaustive]
1186pub struct AuthMethodTerminal {
1187    /// Unique identifier for this authentication method.
1188    pub method_id: AuthMethodId,
1189    /// Human-readable name of the authentication method.
1190    pub name: String,
1191    /// Optional human-readable description of this authentication method.
1192    ///
1193    /// Omitted and `null` are equivalent and mean no description is provided.
1194    #[serde_as(deserialize_as = "DefaultOnError")]
1195    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1196    #[serde(default)]
1197    pub description: Option<String>,
1198    /// Additional arguments to append to the configured agent invocation for terminal auth.
1199    #[serde_as(deserialize_as = "DefaultOnNull")]
1200    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1201    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1202    pub args: Vec<String>,
1203    /// Additional environment variables to set on the configured agent invocation for terminal auth.
1204    /// Names MUST be unique. These values override same-named variables in the
1205    /// base launch configuration.
1206    #[serde_as(deserialize_as = "DefaultOnNull")]
1207    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1208    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1209    pub env: Vec<EnvVariable>,
1210    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1211    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1212    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1213    ///
1214    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1215    #[serde_as(deserialize_as = "DefaultOnError")]
1216    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1217    #[serde(default)]
1218    #[serde(rename = "_meta")]
1219    pub meta: Option<Meta>,
1220}
1221
1222impl AuthMethodTerminal {
1223    /// Builds [`AuthMethodTerminal`] with the required fields set. Optional fields start unset or empty.
1224    #[must_use]
1225    pub fn new(method_id: impl Into<AuthMethodId>, name: impl Into<String>) -> Self {
1226        Self {
1227            method_id: method_id.into(),
1228            name: name.into(),
1229            description: None,
1230            args: Vec::new(),
1231            env: Vec::new(),
1232            meta: None,
1233        }
1234    }
1235
1236    /// Additional arguments to append to the configured agent invocation for terminal auth.
1237    #[must_use]
1238    pub fn args(mut self, args: Vec<String>) -> Self {
1239        self.args = args;
1240        self
1241    }
1242
1243    /// Additional environment variables to set on the configured agent invocation for terminal auth.
1244    /// Names MUST be unique. These values override same-named variables in the
1245    /// base launch configuration.
1246    #[must_use]
1247    pub fn env(mut self, env: Vec<EnvVariable>) -> Self {
1248        self.env = env;
1249        self
1250    }
1251
1252    /// Optional human-readable description of this authentication method.
1253    #[must_use]
1254    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
1255        self.description = description.into_option();
1256        self
1257    }
1258
1259    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1260    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1261    /// do not recognize.
1262    ///
1263    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1264    #[must_use]
1265    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1266        self.meta = meta.into_option();
1267        self
1268    }
1269}
1270
1271// New session
1272
1273/// Request parameters for creating a new session.
1274///
1275/// See protocol docs: [Creating a Session](https://agentclientprotocol.com/protocol/v2/session-setup#creating-a-session)
1276#[serde_as]
1277#[skip_serializing_none]
1278#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1279#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1280#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_NEW_METHOD_NAME)))]
1281#[serde(rename_all = "camelCase")]
1282#[non_exhaustive]
1283pub struct NewSessionRequest {
1284    /// The working directory for this session. Must be an absolute path.
1285    pub cwd: AbsolutePath,
1286    /// Additional workspace roots for this session. Each path must be absolute.
1287    ///
1288    /// These expand the session's workspace scope without changing `cwd`, which
1289    /// remains the base for relative paths. When omitted or empty, no
1290    /// additional roots are activated for the new session.
1291    #[serde_as(deserialize_as = "DefaultOnNull")]
1292    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1293    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1294    pub additional_directories: Vec<AbsolutePath>,
1295    /// List of MCP (Model Context Protocol) servers the agent should connect to.
1296    #[serde_as(deserialize_as = "DefaultOnNull")]
1297    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1298    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1299    pub mcp_servers: Vec<McpServer>,
1300    /// System-level instructions for the new session.
1301    ///
1302    /// Optional. Omitted and `null` are equivalent and mean the Agent uses its
1303    /// own default instructions. Clients MUST only send this when the Agent
1304    /// advertises `session.systemPrompt`.
1305    #[serde(default)]
1306    pub system_prompt: Option<SystemPrompt>,
1307    /// **UNSTABLE**
1308    ///
1309    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1310    ///
1311    /// Initial values for the session's config options.
1312    ///
1313    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1314    /// this when the Agent advertises `session.options`.
1315    ///
1316    /// The Agent applies the entries in list order, as if the Client had called
1317    /// `session/set_config_option` for each entry after the session was set up. Malformed
1318    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1319    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1320    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1321    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries.
1322    #[cfg(feature = "unstable_session_options")]
1323    #[serde_as(deserialize_as = "DefaultOnNull")]
1324    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1325    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1326    pub config_options: Vec<InitialSessionConfigOption>,
1327    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1328    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1329    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1330    ///
1331    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1332    #[serde_as(deserialize_as = "DefaultOnError")]
1333    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1334    #[serde(default)]
1335    #[serde(rename = "_meta")]
1336    pub meta: Option<Meta>,
1337}
1338
1339impl NewSessionRequest {
1340    /// Builds [`NewSessionRequest`] with the required request fields set. Optional fields start unset or empty.
1341    #[must_use]
1342    pub fn new(cwd: impl Into<AbsolutePath>) -> Self {
1343        Self {
1344            cwd: cwd.into(),
1345            additional_directories: vec![],
1346            mcp_servers: vec![],
1347            system_prompt: None,
1348            #[cfg(feature = "unstable_session_options")]
1349            config_options: vec![],
1350            meta: None,
1351        }
1352    }
1353
1354    /// Additional workspace roots for this session. Each path must be absolute.
1355    #[must_use]
1356    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1357    where
1358        I: IntoIterator<Item = P>,
1359        P: Into<AbsolutePath>,
1360    {
1361        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1362        self
1363    }
1364
1365    /// List of MCP (Model Context Protocol) servers the agent should connect to.
1366    #[must_use]
1367    pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1368        self.mcp_servers = mcp_servers;
1369        self
1370    }
1371
1372    /// System-level instructions for the new session.
1373    #[must_use]
1374    pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1375        self.system_prompt = system_prompt.into_option();
1376        self
1377    }
1378
1379    /// **UNSTABLE**
1380    ///
1381    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1382    ///
1383    /// Initial values for the session's config options.
1384    ///
1385    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1386    /// this when the Agent advertises `session.options`.
1387    ///
1388    /// The Agent applies the entries in list order, as if the Client had called
1389    /// `session/set_config_option` for each entry after the session was set up. Malformed
1390    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1391    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1392    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1393    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries.
1394    #[cfg(feature = "unstable_session_options")]
1395    #[must_use]
1396    pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1397        self.config_options = config_options;
1398        self
1399    }
1400
1401    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1402    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1403    /// do not recognize.
1404    ///
1405    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1406    #[must_use]
1407    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1408        self.meta = meta.into_option();
1409        self
1410    }
1411}
1412
1413/// Response from creating a new session.
1414///
1415/// New sessions default to `idle` until a state update reports otherwise.
1416/// Updates may arrive before or after this response. Clients MUST NOT overwrite
1417/// an already-reported state when the response arrives.
1418///
1419/// See protocol docs: [Creating a Session](https://agentclientprotocol.com/protocol/v2/session-setup#creating-a-session)
1420#[serde_as]
1421#[skip_serializing_none]
1422#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1423#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1424#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_NEW_METHOD_NAME)))]
1425#[serde(rename_all = "camelCase")]
1426#[non_exhaustive]
1427pub struct NewSessionResponse {
1428    /// Unique identifier for the created session.
1429    ///
1430    /// Used in all subsequent requests for this conversation.
1431    pub session_id: SessionId,
1432    /// Initial session configuration options.
1433    ///
1434    /// Optional. Omitted or empty means no config options are advertised.
1435    /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
1436    /// Later `config_option_update` notifications replace this list.
1437    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1438    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1439    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1440    pub config_options: Vec<SessionConfigOption>,
1441    /// Initial commands the agent can execute in this session.
1442    ///
1443    /// Optional. Omitted or empty means no initial commands are advertised.
1444    /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
1445    /// Later `available_commands_update` notifications replace this list.
1446    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1447    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1448    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1449    pub available_commands: Vec<AvailableCommand>,
1450    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1451    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1452    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1453    ///
1454    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1455    #[serde_as(deserialize_as = "DefaultOnError")]
1456    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1457    #[serde(default)]
1458    #[serde(rename = "_meta")]
1459    pub meta: Option<Meta>,
1460}
1461
1462impl NewSessionResponse {
1463    /// Builds [`NewSessionResponse`] with the required response fields set. Optional fields start unset or empty.
1464    #[must_use]
1465    pub fn new(session_id: impl Into<SessionId>) -> Self {
1466        Self {
1467            session_id: session_id.into(),
1468            config_options: Vec::new(),
1469            available_commands: Vec::new(),
1470            meta: None,
1471        }
1472    }
1473
1474    /// Initial session configuration options.
1475    ///
1476    /// Optional. Omitted or empty means no config options are advertised.
1477    /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
1478    /// Later `config_option_update` notifications replace this list.
1479    #[must_use]
1480    pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
1481        self.config_options = config_options;
1482        self
1483    }
1484
1485    /// Initial commands the agent can execute in this session.
1486    #[must_use]
1487    pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
1488        self.available_commands = available_commands;
1489        self
1490    }
1491
1492    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1493    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1494    /// do not recognize.
1495    ///
1496    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1497    #[must_use]
1498    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1499        self.meta = meta.into_option();
1500        self
1501    }
1502}
1503
1504// Fork session
1505
1506/// **UNSTABLE**
1507///
1508/// This capability is not part of the spec yet, and may be removed or changed at any point.
1509///
1510/// Request parameters for forking an existing session.
1511///
1512/// Creates a new session based on the context of an existing one, allowing
1513/// operations like generating summaries without affecting the original session's history.
1514///
1515/// Only available if the Agent supports the `session.fork` capability.
1516#[cfg(feature = "unstable_session_fork")]
1517#[serde_as]
1518#[skip_serializing_none]
1519#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1520#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1521#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_FORK_METHOD_NAME)))]
1522#[serde(rename_all = "camelCase")]
1523#[non_exhaustive]
1524pub struct ForkSessionRequest {
1525    /// The ID of the session to fork.
1526    pub session_id: SessionId,
1527    /// The working directory for this session. Must be an absolute path.
1528    pub cwd: AbsolutePath,
1529    /// Additional workspace roots to activate for this session. Each path must be absolute.
1530    ///
1531    /// When omitted or empty, no additional roots are activated. When non-empty,
1532    /// this is the complete resulting additional-root list for the forked
1533    /// session.
1534    #[serde_as(deserialize_as = "DefaultOnNull")]
1535    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1536    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1537    pub additional_directories: Vec<AbsolutePath>,
1538    /// List of MCP servers to connect to for this session.
1539    #[serde_as(deserialize_as = "DefaultOnNull")]
1540    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1541    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1542    pub mcp_servers: Vec<McpServer>,
1543    /// System-level instructions for the forked session.
1544    ///
1545    /// Optional. Omitted and `null` are equivalent. The Agent may then keep a
1546    /// system prompt it stored with the source session or use its default
1547    /// instructions. Clients MUST only send this when the Agent advertises
1548    /// `session.systemPrompt`, and SHOULD send the same value they used for the
1549    /// source session.
1550    #[serde(default)]
1551    pub system_prompt: Option<SystemPrompt>,
1552    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1553    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1554    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1555    ///
1556    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1557    #[serde_as(deserialize_as = "DefaultOnError")]
1558    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1559    #[serde(default)]
1560    #[serde(rename = "_meta")]
1561    pub meta: Option<Meta>,
1562}
1563
1564#[cfg(feature = "unstable_session_fork")]
1565impl ForkSessionRequest {
1566    /// Builds [`ForkSessionRequest`] with the required request fields set. Optional fields start unset or empty.
1567    #[must_use]
1568    pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
1569        Self {
1570            session_id: session_id.into(),
1571            cwd: cwd.into(),
1572            additional_directories: vec![],
1573            mcp_servers: vec![],
1574            system_prompt: None,
1575            meta: None,
1576        }
1577    }
1578
1579    /// Additional workspace roots to activate for this session. Each path must be absolute.
1580    #[must_use]
1581    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1582    where
1583        I: IntoIterator<Item = P>,
1584        P: Into<AbsolutePath>,
1585    {
1586        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1587        self
1588    }
1589
1590    /// List of MCP servers to connect to for this session.
1591    #[must_use]
1592    pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1593        self.mcp_servers = mcp_servers;
1594        self
1595    }
1596
1597    /// System-level instructions for the forked session.
1598    #[must_use]
1599    pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1600        self.system_prompt = system_prompt.into_option();
1601        self
1602    }
1603
1604    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1605    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1606    /// do not recognize.
1607    ///
1608    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1609    #[must_use]
1610    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1611        self.meta = meta.into_option();
1612        self
1613    }
1614}
1615
1616/// **UNSTABLE**
1617///
1618/// This capability is not part of the spec yet, and may be removed or changed at any point.
1619///
1620/// Response from forking an existing session.
1621#[cfg(feature = "unstable_session_fork")]
1622#[serde_as]
1623#[skip_serializing_none]
1624#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1625#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1626#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_FORK_METHOD_NAME)))]
1627#[serde(rename_all = "camelCase")]
1628#[non_exhaustive]
1629pub struct ForkSessionResponse {
1630    /// Unique identifier for the newly created forked session.
1631    pub session_id: SessionId,
1632    /// Initial session configuration options.
1633    ///
1634    /// Optional. Omitted or empty means no config options are advertised.
1635    /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
1636    /// Later `config_option_update` notifications replace this list.
1637    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1638    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1639    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1640    pub config_options: Vec<SessionConfigOption>,
1641    /// Initial commands the agent can execute in this session.
1642    ///
1643    /// Optional. Omitted or empty means no initial commands are advertised.
1644    /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
1645    /// Later `available_commands_update` notifications replace this list.
1646    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
1647    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1648    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1649    pub available_commands: Vec<AvailableCommand>,
1650    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1651    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1652    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1653    ///
1654    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1655    #[serde_as(deserialize_as = "DefaultOnError")]
1656    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1657    #[serde(default)]
1658    #[serde(rename = "_meta")]
1659    pub meta: Option<Meta>,
1660}
1661
1662#[cfg(feature = "unstable_session_fork")]
1663impl ForkSessionResponse {
1664    /// Builds [`ForkSessionResponse`] with the required response fields set. Optional fields start unset or empty.
1665    #[must_use]
1666    pub fn new(session_id: impl Into<SessionId>) -> Self {
1667        Self {
1668            session_id: session_id.into(),
1669            config_options: Vec::new(),
1670            available_commands: Vec::new(),
1671            meta: None,
1672        }
1673    }
1674
1675    /// Initial session configuration options.
1676    ///
1677    /// Optional. Omitted or empty means no config options are advertised.
1678    /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
1679    /// Later `config_option_update` notifications replace this list.
1680    #[must_use]
1681    pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
1682        self.config_options = config_options;
1683        self
1684    }
1685
1686    /// Initial commands the agent can execute in this session.
1687    #[must_use]
1688    pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
1689        self.available_commands = available_commands;
1690        self
1691    }
1692
1693    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1694    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1695    /// do not recognize.
1696    ///
1697    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1698    #[must_use]
1699    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1700        self.meta = meta.into_option();
1701        self
1702    }
1703}
1704
1705// Resume session
1706
1707/// Request parameters for resuming an existing session.
1708///
1709/// Resumes an existing session and optionally replays retained conversation
1710/// history according to `replayFrom`.
1711#[serde_as]
1712#[skip_serializing_none]
1713#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1714#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1715#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_RESUME_METHOD_NAME)))]
1716#[serde(rename_all = "camelCase")]
1717#[non_exhaustive]
1718pub struct ResumeSessionRequest {
1719    /// The ID of the session to resume.
1720    pub session_id: SessionId,
1721    /// The working directory for this session. Must be an absolute path.
1722    ///
1723    /// Clients MUST send the session's working directory. Agents MAY reject a different directory
1724    /// with `-32602`, and MAY normalize paths when comparing.
1725    pub cwd: AbsolutePath,
1726    /// Additional workspace roots to activate for this session. Each path must be absolute.
1727    ///
1728    /// When omitted or empty, no additional roots are activated. When non-empty,
1729    /// this is the complete resulting additional-root list for the resumed
1730    /// session. It may differ from any previously used or reported list as long as
1731    /// the request `cwd` matches the session's `cwd`.
1732    #[serde_as(deserialize_as = "DefaultOnNull")]
1733    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1734    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1735    pub additional_directories: Vec<AbsolutePath>,
1736    /// List of MCP servers to connect to for this session.
1737    ///
1738    /// The complete set of Client-provided servers. Omitted and `[]` mean none. Agents SHOULD
1739    /// NOT restore servers from earlier requests.
1740    #[serde_as(deserialize_as = "DefaultOnNull")]
1741    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1742    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1743    pub mcp_servers: Vec<McpServer>,
1744    /// Inclusive cursor describing where conversation replay should begin.
1745    ///
1746    /// Optional. Omitted and `null` are equivalent and mean the Agent should resume without
1747    /// replaying previous conversation history. Replay cursors are inclusive:
1748    /// replay includes the position identified by the cursor. Supplying
1749    /// `{ "type": "start" }` means the Agent should replay all retained
1750    /// conversation history before responding.
1751    ///
1752    /// Agents MUST reject unsupported cursor types or malformed cursor values
1753    /// with `-32602` (Invalid params), rather than substituting another cursor
1754    /// or resuming without replay.
1755    #[serde(default)]
1756    pub replay_from: Option<ReplayFrom>,
1757    /// System-level instructions for the resumed session.
1758    ///
1759    /// Optional. Omitted and `null` are equivalent. The Agent may then keep a
1760    /// system prompt it stored with the session or use its default instructions.
1761    /// Clients MUST only send this when the Agent advertises
1762    /// `session.systemPrompt`, and SHOULD send the same value they used when the
1763    /// session was created.
1764    #[serde(default)]
1765    pub system_prompt: Option<SystemPrompt>,
1766    /// **UNSTABLE**
1767    ///
1768    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1769    ///
1770    /// Initial values for the session's config options.
1771    ///
1772    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1773    /// this when the Agent advertises `session.options`.
1774    ///
1775    /// The Agent applies the entries in list order, as if the Client had called
1776    /// `session/set_config_option` for each entry after the session was set up. Malformed
1777    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1778    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1779    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1780    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries.
1781    ///
1782    /// The Agent applies the entries before it replays history for `replayFrom` and before
1783    /// it responds.
1784    #[cfg(feature = "unstable_session_options")]
1785    #[serde_as(deserialize_as = "DefaultOnNull")]
1786    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1787    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1788    pub config_options: Vec<InitialSessionConfigOption>,
1789    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1790    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1791    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1792    ///
1793    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1794    #[serde_as(deserialize_as = "DefaultOnError")]
1795    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1796    #[serde(default)]
1797    #[serde(rename = "_meta")]
1798    pub meta: Option<Meta>,
1799}
1800
1801impl ResumeSessionRequest {
1802    /// Builds [`ResumeSessionRequest`] with the required request fields set. Optional fields start unset or empty.
1803    #[must_use]
1804    pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
1805        Self {
1806            session_id: session_id.into(),
1807            cwd: cwd.into(),
1808            additional_directories: vec![],
1809            mcp_servers: vec![],
1810            replay_from: None,
1811            system_prompt: None,
1812            #[cfg(feature = "unstable_session_options")]
1813            config_options: vec![],
1814            meta: None,
1815        }
1816    }
1817
1818    /// Additional workspace roots to activate for this session. Each path must be absolute.
1819    #[must_use]
1820    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
1821    where
1822        I: IntoIterator<Item = P>,
1823        P: Into<AbsolutePath>,
1824    {
1825        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
1826        self
1827    }
1828
1829    /// List of MCP servers to connect to for this session.
1830    #[must_use]
1831    pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1832        self.mcp_servers = mcp_servers;
1833        self
1834    }
1835
1836    /// Inclusive cursor describing where conversation replay should begin.
1837    ///
1838    /// Omitted and `null` are equivalent and mean the Agent should resume without replaying
1839    /// previous conversation history. Replay cursors are inclusive: replay
1840    /// includes the position identified by the cursor. Supplying
1841    /// `{ "type": "start" }` means the Agent should replay all retained
1842    /// conversation history before responding.
1843    #[must_use]
1844    pub fn replay_from(mut self, replay_from: impl IntoOption<ReplayFrom>) -> Self {
1845        self.replay_from = replay_from.into_option();
1846        self
1847    }
1848
1849    /// System-level instructions for the resumed session.
1850    #[must_use]
1851    pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1852        self.system_prompt = system_prompt.into_option();
1853        self
1854    }
1855
1856    /// **UNSTABLE**
1857    ///
1858    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1859    ///
1860    /// Initial values for the session's config options.
1861    ///
1862    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1863    /// this when the Agent advertises `session.options`.
1864    ///
1865    /// The Agent applies the entries in list order, as if the Client had called
1866    /// `session/set_config_option` for each entry after the session was set up. Malformed
1867    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1868    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1869    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1870    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries.
1871    #[cfg(feature = "unstable_session_options")]
1872    #[must_use]
1873    pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1874        self.config_options = config_options;
1875        self
1876    }
1877
1878    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1879    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1880    /// do not recognize.
1881    ///
1882    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1883    #[must_use]
1884    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1885        self.meta = meta.into_option();
1886        self
1887    }
1888}
1889
1890/// Inclusive cursor describing where replayed session history should begin.
1891///
1892/// Replay includes the position identified by the cursor.
1893#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1894#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1895#[serde(tag = "type", rename_all = "snake_case")]
1896#[non_exhaustive]
1897pub enum ReplayFrom {
1898    /// Replay all retained conversation history from its first replayable entry.
1899    Start(ReplayFromStart),
1900    /// Custom or future replay cursor.
1901    ///
1902    /// Values beginning with `_` are reserved for implementation-specific
1903    /// extensions. Unknown values that do not begin with `_` are reserved for
1904    /// future ACP variants.
1905    ///
1906    /// Intermediaries SHOULD preserve the raw payload when storing, replaying,
1907    /// proxying, or forwarding requests. Agents that do not support this cursor
1908    /// MUST reject the request with `-32602` (Invalid params), rather than
1909    /// substituting another cursor or resuming without replay.
1910    #[serde(untagged)]
1911    Other(OtherReplayFrom),
1912}
1913
1914impl From<ReplayFromStart> for ReplayFrom {
1915    fn from(replay_from: ReplayFromStart) -> Self {
1916        Self::Start(replay_from)
1917    }
1918}
1919
1920/// Inclusive replay cursor requesting replay from the start of retained conversation history.
1921#[serde_as]
1922#[skip_serializing_none]
1923#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1924#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1925#[serde(rename_all = "camelCase")]
1926#[non_exhaustive]
1927pub struct ReplayFromStart {
1928    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1929    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1930    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1931    ///
1932    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1933    #[serde_as(deserialize_as = "DefaultOnError")]
1934    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1935    #[serde(default)]
1936    #[serde(rename = "_meta")]
1937    pub meta: Option<Meta>,
1938}
1939
1940impl ReplayFromStart {
1941    /// Builds [`ReplayFromStart`].
1942    #[must_use]
1943    pub fn new() -> Self {
1944        Self::default()
1945    }
1946
1947    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1948    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1949    /// do not recognize.
1950    ///
1951    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1952    #[must_use]
1953    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1954        self.meta = meta.into_option();
1955        self
1956    }
1957}
1958
1959/// Custom or future replay cursor payload.
1960#[serde_as]
1961#[skip_serializing_none]
1962#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1963#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1964#[cfg_attr(feature = "schemars", schemars(inline))]
1965#[cfg_attr(feature = "schemars", schemars(transform = other_replay_from_schema))]
1966#[serde(rename_all = "camelCase")]
1967#[non_exhaustive]
1968pub struct OtherReplayFrom {
1969    /// Custom or future replay cursor type.
1970    ///
1971    /// Values beginning with `_` are reserved for implementation-specific
1972    /// extensions. Unknown values that do not begin with `_` are reserved for
1973    /// future ACP variants.
1974    #[serde(rename = "type")]
1975    pub type_: String,
1976    /// The remaining fields of the unknown replay cursor payload, preserved verbatim,
1977    /// including `_meta`.
1978    #[serde(flatten)]
1979    pub fields: BTreeMap<String, serde_json::Value>,
1980}
1981
1982impl OtherReplayFrom {
1983    /// Builds [`OtherReplayFrom`] from an unknown discriminator and preserves the remaining extension fields.
1984    #[must_use]
1985    pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
1986        fields.remove("type");
1987        Self {
1988            type_: type_.into(),
1989            fields,
1990        }
1991    }
1992}
1993
1994impl<'de> Deserialize<'de> for OtherReplayFrom {
1995    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1996    where
1997        D: serde::Deserializer<'de>,
1998    {
1999        let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
2000        let type_ = fields
2001            .remove("type")
2002            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
2003        let serde_json::Value::String(type_) = type_ else {
2004            return Err(serde::de::Error::custom("`type` must be a string"));
2005        };
2006
2007        if is_known_replay_from_type(&type_) {
2008            return Err(serde::de::Error::custom(format!(
2009                "known replay cursor `{type_}` did not match its schema"
2010            )));
2011        }
2012
2013        Ok(Self { type_, fields })
2014    }
2015}
2016
2017fn is_known_replay_from_type(type_: &str) -> bool {
2018    matches!(type_, "start")
2019}
2020
2021#[cfg(feature = "schemars")]
2022fn other_replay_from_schema(schema: &mut Schema) {
2023    super::schema_util::reject_known_string_discriminators(schema, "type", &["start"]);
2024}
2025
2026crate::serde_util::default_on_null! {
2027    /// Response from resuming an existing session.
2028    ///
2029    /// The agent MUST send a current `state_update` after any requested history
2030    /// replay and before this response, even without replay. The update reports
2031    /// foreground state after resuming. The response alone does not imply `idle`.
2032    ///
2033    /// See protocol docs: [Current-State Synchronization](https://agentclientprotocol.com/protocol/v2/session-setup#current-state-synchronization)
2034    #[serde_as]
2035    #[skip_serializing_none]
2036    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2037    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2038    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_RESUME_METHOD_NAME)))]
2039    #[serde(rename_all = "camelCase")]
2040    #[non_exhaustive]
2041    pub struct ResumeSessionResponse {
2042        /// Initial session configuration options.
2043        ///
2044        /// Optional. Omitted or empty means no config options are advertised.
2045        /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
2046        /// Later `config_option_update` notifications replace this list.
2047        #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2048        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2049        #[serde(default, skip_serializing_if = "Vec::is_empty")]
2050        pub config_options: Vec<SessionConfigOption>,
2051        /// Initial commands the agent can execute in this session.
2052        ///
2053        /// Optional. Omitted or empty means no initial commands are advertised.
2054        /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
2055        /// Later `available_commands_update` notifications replace this list.
2056        #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2057        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2058        #[serde(default, skip_serializing_if = "Vec::is_empty")]
2059        pub available_commands: Vec<AvailableCommand>,
2060        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2061        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2062        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2063        ///
2064        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2065        #[serde_as(deserialize_as = "DefaultOnError")]
2066        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2067        #[serde(default)]
2068        #[serde(rename = "_meta")]
2069        pub meta: Option<Meta>,
2070    }
2071}
2072
2073impl ResumeSessionResponse {
2074    /// Builds [`ResumeSessionResponse`] with the required response fields set. Optional fields start unset or empty.
2075    #[must_use]
2076    pub fn new() -> Self {
2077        Self::default()
2078    }
2079
2080    /// Initial session configuration options.
2081    ///
2082    /// Optional. Omitted or empty means no config options are advertised.
2083    /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
2084    /// Later `config_option_update` notifications replace this list.
2085    #[must_use]
2086    pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
2087        self.config_options = config_options;
2088        self
2089    }
2090
2091    /// Initial commands the agent can execute in this session.
2092    #[must_use]
2093    pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
2094        self.available_commands = available_commands;
2095        self
2096    }
2097
2098    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2099    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2100    /// do not recognize.
2101    ///
2102    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2103    #[must_use]
2104    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2105        self.meta = meta.into_option();
2106        self
2107    }
2108}
2109
2110// Close session
2111
2112/// Request parameters for closing an active session.
2113///
2114/// The Agent MUST cancel any ongoing work related to the session as if `session/cancel`
2115/// was called, then free the resources associated with the session. Unlike `session/cancel`,
2116/// closing also stops the session's background work. After the close response, the Agent
2117/// sends no other messages for the session on that connection.
2118///
2119/// Closing a session that does not exist or is not active SHOULD succeed, and Clients SHOULD
2120/// treat a `-32002` response as a successful close.
2121///
2122/// When closing cancels active foreground work, the Agent MUST send the final
2123/// updates for that work and the idle `state_update` with `stopReason: "cancelled"`
2124/// before responding successfully to `session/close`. Closing an idle session
2125/// does not itself require another idle update.
2126///
2127/// Closing also cancels pending `session/prompt` requests whose messages have not
2128/// been inserted, including held prompts. If closing prevents a prompt's user message from being inserted, the
2129/// Agent MUST answer that request with `-32800` (Request Cancelled). If the message
2130/// has already been inserted, the Agent MUST respond successfully with its
2131/// `messageId`. Prompt responses need not precede the close response.
2132#[serde_as]
2133#[skip_serializing_none]
2134#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2135#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2136#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CLOSE_METHOD_NAME)))]
2137#[serde(rename_all = "camelCase")]
2138#[non_exhaustive]
2139pub struct CloseSessionRequest {
2140    /// The ID of the session to close.
2141    pub session_id: SessionId,
2142    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2143    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2144    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2145    ///
2146    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2147    #[serde_as(deserialize_as = "DefaultOnError")]
2148    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2149    #[serde(default)]
2150    #[serde(rename = "_meta")]
2151    pub meta: Option<Meta>,
2152}
2153
2154impl CloseSessionRequest {
2155    /// Builds [`CloseSessionRequest`] with the required request fields set. Optional fields start unset or empty.
2156    #[must_use]
2157    pub fn new(session_id: impl Into<SessionId>) -> Self {
2158        Self {
2159            session_id: session_id.into(),
2160            meta: None,
2161        }
2162    }
2163
2164    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2165    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2166    /// do not recognize.
2167    ///
2168    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2169    #[must_use]
2170    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2171        self.meta = meta.into_option();
2172        self
2173    }
2174}
2175
2176crate::serde_util::default_on_null! {
2177    /// Response from closing a session.
2178    #[serde_as]
2179    #[skip_serializing_none]
2180    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2181    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2182    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CLOSE_METHOD_NAME)))]
2183    #[serde(rename_all = "camelCase")]
2184    #[non_exhaustive]
2185    pub struct CloseSessionResponse {
2186        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2187        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2188        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2189        ///
2190        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2191        #[serde_as(deserialize_as = "DefaultOnError")]
2192        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2193        #[serde(default)]
2194        #[serde(rename = "_meta")]
2195        pub meta: Option<Meta>,
2196    }
2197}
2198
2199impl CloseSessionResponse {
2200    /// Builds [`CloseSessionResponse`] with the required response fields set. Optional fields start unset or empty.
2201    #[must_use]
2202    pub fn new() -> Self {
2203        Self::default()
2204    }
2205
2206    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2207    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2208    /// do not recognize.
2209    ///
2210    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2211    #[must_use]
2212    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2213        self.meta = meta.into_option();
2214        self
2215    }
2216}
2217
2218// Session status
2219
2220/// **UNSTABLE**
2221///
2222/// This capability is not part of the spec yet, and may be removed or changed at any point.
2223///
2224/// Request parameters for checking the status of a session.
2225///
2226/// Only available if the Agent supports the `session.status` capability.
2227///
2228/// `session/status` MUST NOT have side effects. The Agent does not load, resume, create,
2229/// close, or change the session, and does not attach the requesting connection to it.
2230/// A session the Agent does not know gets `-32002` with the requested `sessionId` in `data`.
2231#[cfg(feature = "unstable_session_status")]
2232#[serde_as]
2233#[skip_serializing_none]
2234#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2235#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2236#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_STATUS_METHOD_NAME)))]
2237#[serde(rename_all = "camelCase")]
2238#[non_exhaustive]
2239pub struct SessionStatusRequest {
2240    /// The ID of the session to check.
2241    pub session_id: SessionId,
2242    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2243    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2244    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2245    ///
2246    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2247    #[serde_as(deserialize_as = "DefaultOnError")]
2248    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2249    #[serde(default)]
2250    #[serde(rename = "_meta")]
2251    pub meta: Option<Meta>,
2252}
2253
2254#[cfg(feature = "unstable_session_status")]
2255impl SessionStatusRequest {
2256    /// Builds [`SessionStatusRequest`] with the required request fields set. Optional fields start unset or empty.
2257    #[must_use]
2258    pub fn new(session_id: impl Into<SessionId>) -> Self {
2259        Self {
2260            session_id: session_id.into(),
2261            meta: None,
2262        }
2263    }
2264
2265    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2266    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2267    /// do not recognize.
2268    ///
2269    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2270    #[must_use]
2271    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2272        self.meta = meta.into_option();
2273        self
2274    }
2275}
2276
2277/// **UNSTABLE**
2278///
2279/// This capability is not part of the spec yet, and may be removed or changed at any point.
2280///
2281/// Response from checking the status of a session.
2282///
2283/// The result is a snapshot. A session reported `open` may be closed or evicted before
2284/// the Client's next request.
2285#[cfg(feature = "unstable_session_status")]
2286#[serde_as]
2287#[skip_serializing_none]
2288#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2289#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2290#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_STATUS_METHOD_NAME)))]
2291#[serde(rename_all = "camelCase")]
2292#[non_exhaustive]
2293pub struct SessionStatusResponse {
2294    /// Whether the Agent has the session in memory.
2295    ///
2296    /// Required. Clients MUST treat a value they do not recognize as `saved`.
2297    pub status: SessionStatus,
2298    /// The session's current foreground state, as the same snapshot the Agent sends in
2299    /// `state_update` notifications.
2300    ///
2301    /// Optional. Agents SHOULD include it when `status` is `open`. Omitted, `null`, and
2302    /// malformed values mean the Agent is not reporting foreground state, and Clients
2303    /// MUST NOT read that as `idle`. This is a snapshot, not a new transition. Clients
2304    /// MUST NOT count an `idle` snapshot as a new completion.
2305    #[serde_as(deserialize_as = "DefaultOnError")]
2306    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2307    #[serde(default)]
2308    pub state: Option<StateUpdate>,
2309    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2310    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2311    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2312    ///
2313    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2314    #[serde_as(deserialize_as = "DefaultOnError")]
2315    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2316    #[serde(default)]
2317    #[serde(rename = "_meta")]
2318    pub meta: Option<Meta>,
2319}
2320
2321#[cfg(feature = "unstable_session_status")]
2322impl SessionStatusResponse {
2323    /// Builds [`SessionStatusResponse`] with the required response fields set. Optional fields start unset or empty.
2324    #[must_use]
2325    pub fn new(status: SessionStatus) -> Self {
2326        Self {
2327            status,
2328            state: None,
2329            meta: None,
2330        }
2331    }
2332
2333    /// The session's current foreground state, as the same snapshot the Agent sends in
2334    /// `state_update` notifications.
2335    #[must_use]
2336    pub fn state(mut self, state: impl IntoOption<StateUpdate>) -> Self {
2337        self.state = state.into_option();
2338        self
2339    }
2340
2341    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2342    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2343    /// do not recognize.
2344    ///
2345    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2346    #[must_use]
2347    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2348        self.meta = meta.into_option();
2349        self
2350    }
2351}
2352
2353/// **UNSTABLE**
2354///
2355/// This capability is not part of the spec yet, and may be removed or changed at any point.
2356///
2357/// Whether the Agent has a session in memory, as reported by `session/status`.
2358#[cfg(feature = "unstable_session_status")]
2359#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2360#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2361#[serde(rename_all = "snake_case")]
2362#[non_exhaustive]
2363pub enum SessionStatus {
2364    /// The Agent has the session in memory, for any connection.
2365    ///
2366    /// This does not mean the requesting connection is attached to it. A Client that did
2367    /// not create or resume the session on its own connection MUST still call
2368    /// `session/resume` before sending `session/prompt` or expecting
2369    /// `session/update` notifications.
2370    Open,
2371    /// The Agent knows the session and can resume it, but does not have it in memory.
2372    ///
2373    /// The Client can call `session/resume` to start it.
2374    Saved,
2375    /// Custom or future session status.
2376    ///
2377    /// Values beginning with `_` are reserved for implementation-specific
2378    /// extensions. Unknown values that do not begin with `_` are reserved for
2379    /// future ACP variants. Clients MUST treat a value they do not recognize as
2380    /// `saved`.
2381    #[serde(untagged)]
2382    Other(String),
2383}
2384
2385/// **UNSTABLE**
2386///
2387/// This capability is not part of the spec yet, and may be removed or changed at any point.
2388///
2389/// Request parameters for `session/options`, which returns the config options a session
2390/// would start with, without creating or resuming a session.
2391///
2392/// Only available if the Agent supports the `session.options` capability.
2393///
2394/// `session/options` MUST NOT create or resume a session, send `session/update`
2395/// notifications, add an entry to `session/list`, or change an existing session. Agents
2396/// SHOULD NOT connect to MCP servers to answer it.
2397#[cfg(feature = "unstable_session_options")]
2398#[serde_as]
2399#[skip_serializing_none]
2400#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2401#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2402#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_OPTIONS_METHOD_NAME)))]
2403#[serde(rename_all = "camelCase")]
2404#[non_exhaustive]
2405pub struct SessionOptionsRequest {
2406    /// The working directory to resolve options for. Must be an absolute path.
2407    pub cwd: AbsolutePath,
2408    /// Additional workspace roots to resolve options for. Each path must be absolute.
2409    ///
2410    /// Optional. Omitted and `null` are equivalent to an empty list.
2411    #[serde_as(deserialize_as = "DefaultOnNull")]
2412    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
2413    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2414    pub additional_directories: Vec<AbsolutePath>,
2415    /// The session to resolve options for.
2416    ///
2417    /// Optional. Omitted and `null` are equivalent and mean a new session. When present,
2418    /// the Agent returns what `session/resume` with the same `cwd` and
2419    /// `additionalDirectories` would return, with the same `cwd` rules. A session the
2420    /// Agent does not know gets `-32002`.
2421    #[serde(default)]
2422    pub session_id: Option<SessionId>,
2423    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2424    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2425    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2426    ///
2427    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2428    #[serde_as(deserialize_as = "DefaultOnError")]
2429    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2430    #[serde(default)]
2431    #[serde(rename = "_meta")]
2432    pub meta: Option<Meta>,
2433}
2434
2435#[cfg(feature = "unstable_session_options")]
2436impl SessionOptionsRequest {
2437    /// Builds [`SessionOptionsRequest`] with the required request fields set. Optional fields start unset or empty.
2438    #[must_use]
2439    pub fn new(cwd: impl Into<AbsolutePath>) -> Self {
2440        Self {
2441            cwd: cwd.into(),
2442            additional_directories: vec![],
2443            session_id: None,
2444            meta: None,
2445        }
2446    }
2447
2448    /// Additional workspace roots to resolve options for. Each path must be absolute.
2449    #[must_use]
2450    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
2451    where
2452        I: IntoIterator<Item = P>,
2453        P: Into<AbsolutePath>,
2454    {
2455        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
2456        self
2457    }
2458
2459    /// The session to resolve options for. Unset means a new session.
2460    #[must_use]
2461    pub fn session_id(mut self, session_id: impl IntoOption<SessionId>) -> Self {
2462        self.session_id = session_id.into_option();
2463        self
2464    }
2465
2466    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2467    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2468    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2469    ///
2470    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2471    #[must_use]
2472    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2473        self.meta = meta.into_option();
2474        self
2475    }
2476}
2477
2478#[cfg(feature = "unstable_session_options")]
2479crate::serde_util::default_on_null! {
2480    /// **UNSTABLE**
2481    ///
2482    /// This capability is not part of the spec yet, and may be removed or changed at any point.
2483    ///
2484    /// Response from `session/options`.
2485    ///
2486    /// The result is a snapshot. The options a session actually starts with are the ones in
2487    /// the session setup response.
2488    #[serde_as]
2489    #[skip_serializing_none]
2490    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2491    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2492    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_OPTIONS_METHOD_NAME)))]
2493    #[serde(rename_all = "camelCase")]
2494    #[non_exhaustive]
2495    pub struct SessionOptionsResponse {
2496        /// The config options the session would start with, with the same rules as on
2497        /// `NewSessionResponse`.
2498        ///
2499        /// Optional. Omitted or empty means no config options are advertised.
2500        /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
2501        #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2502        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2503        #[serde(default, skip_serializing_if = "Vec::is_empty")]
2504        pub config_options: Vec<SessionConfigOption>,
2505        /// Commands the Agent knows the session would have.
2506        ///
2507        /// Optional. Omitted or empty means no commands are advertised.
2508        /// Senders MUST use an array, not `null`. Receivers treat `null` like omission.
2509        ///
2510        /// Advisory. Agents MAY return a partial list. Clients MUST use the commands from the
2511        /// `session/new` or `session/resume` response and later `available_commands_update`
2512        /// notifications for the session itself.
2513        #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2514        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2515        #[serde(default, skip_serializing_if = "Vec::is_empty")]
2516        pub available_commands: Vec<AvailableCommand>,
2517        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2518        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2519        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2520        ///
2521        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2522        #[serde_as(deserialize_as = "DefaultOnError")]
2523        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2524        #[serde(default)]
2525        #[serde(rename = "_meta")]
2526        pub meta: Option<Meta>,
2527    }
2528}
2529
2530#[cfg(feature = "unstable_session_options")]
2531impl SessionOptionsResponse {
2532    /// Builds [`SessionOptionsResponse`] with the required response fields set. Optional fields start unset or empty.
2533    #[must_use]
2534    pub fn new() -> Self {
2535        Self::default()
2536    }
2537
2538    /// The config options the session would start with.
2539    #[must_use]
2540    pub fn config_options(mut self, config_options: Vec<SessionConfigOption>) -> Self {
2541        self.config_options = config_options;
2542        self
2543    }
2544
2545    /// Commands the Agent knows the session would have. Advisory.
2546    #[must_use]
2547    pub fn available_commands(mut self, available_commands: Vec<AvailableCommand>) -> Self {
2548        self.available_commands = available_commands;
2549        self
2550    }
2551
2552    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2553    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2554    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2555    ///
2556    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2557    #[must_use]
2558    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2559        self.meta = meta.into_option();
2560        self
2561    }
2562}
2563
2564/// **UNSTABLE**
2565///
2566/// This capability is not part of the spec yet, and may be removed or changed at any point.
2567///
2568/// An initial value for a config option, sent on session setup requests.
2569///
2570/// Same shape as `session/set_config_option` without `sessionId`. Unlike
2571/// `session/set_config_option`, an unknown `configId`, a `type` that does not match the
2572/// option, or a value that is not allowed is ignored instead of rejected.
2573#[cfg(feature = "unstable_session_options")]
2574#[serde_as]
2575#[skip_serializing_none]
2576#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2577#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2578#[serde(rename_all = "camelCase")]
2579#[non_exhaustive]
2580pub struct InitialSessionConfigOption {
2581    /// The ID of the configuration option to set.
2582    pub config_id: SessionConfigId,
2583    /// The value to set, including a `type` discriminator and the raw `value`.
2584    ///
2585    /// Payloads must send `type: "id"` for id-based options. A value `type` the Agent
2586    /// does not support fails the request with `-32602`.
2587    #[serde(flatten)]
2588    pub value: SessionConfigOptionValue,
2589    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2590    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2591    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2592    ///
2593    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2594    #[serde_as(deserialize_as = "DefaultOnError")]
2595    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2596    #[serde(default)]
2597    #[serde(rename = "_meta")]
2598    pub meta: Option<Meta>,
2599}
2600
2601#[cfg(feature = "unstable_session_options")]
2602impl InitialSessionConfigOption {
2603    /// Builds [`InitialSessionConfigOption`] with the required fields set. Optional fields start unset or empty.
2604    #[must_use]
2605    pub fn new(
2606        config_id: impl Into<SessionConfigId>,
2607        value: impl Into<SessionConfigOptionValue>,
2608    ) -> Self {
2609        Self {
2610            config_id: config_id.into(),
2611            value: value.into(),
2612            meta: None,
2613        }
2614    }
2615
2616    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2617    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2618    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2619    ///
2620    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2621    #[must_use]
2622    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2623        self.meta = meta.into_option();
2624        self
2625    }
2626}
2627
2628// Cancel tool call
2629
2630/// Request parameters for cancelling one tool call.
2631///
2632/// Clients MUST NOT send it unless the tool call currently advertises `capabilities.cancel`.
2633///
2634/// The Agent responds once it has accepted the cancellation. The response does not mean
2635/// the work has stopped. The Agent confirms it with a `tool_call_update` to a final
2636/// status: normally `cancelled`, or `completed` or `failed` if the work finished first.
2637///
2638/// The Agent responds with `-32602` if the tool call is unknown, already final, or not
2639/// cancellable. Cancelling a tool call does not change the foreground state by itself.
2640///
2641/// See protocol docs: [Cancelling Tool Calls](https://agentclientprotocol.com/protocol/v2/tool-calls#cancelling-tool-calls)
2642#[serde_as]
2643#[skip_serializing_none]
2644#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2645#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2646#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TOOL_CALL_CANCEL_METHOD_NAME)))]
2647#[serde(rename_all = "camelCase")]
2648#[non_exhaustive]
2649pub struct CancelToolCallRequest {
2650    /// The ID of the session that owns the tool call.
2651    pub session_id: SessionId,
2652    /// The ID of the tool call to cancel.
2653    pub tool_call_id: ToolCallId,
2654    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2655    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2656    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2657    ///
2658    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2659    #[serde_as(deserialize_as = "DefaultOnError")]
2660    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2661    #[serde(default)]
2662    #[serde(rename = "_meta")]
2663    pub meta: Option<Meta>,
2664}
2665
2666impl CancelToolCallRequest {
2667    /// Builds [`CancelToolCallRequest`] with the required request fields set. Optional fields start unset or empty.
2668    #[must_use]
2669    pub fn new(session_id: impl Into<SessionId>, tool_call_id: impl Into<ToolCallId>) -> Self {
2670        Self {
2671            session_id: session_id.into(),
2672            tool_call_id: tool_call_id.into(),
2673            meta: None,
2674        }
2675    }
2676
2677    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2678    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2679    /// do not recognize.
2680    ///
2681    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2682    #[must_use]
2683    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2684        self.meta = meta.into_option();
2685        self
2686    }
2687}
2688
2689crate::serde_util::default_on_null! {
2690    /// Response from cancelling a tool call.
2691    #[serde_as]
2692    #[skip_serializing_none]
2693    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2694    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2695    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = TOOL_CALL_CANCEL_METHOD_NAME)))]
2696    #[serde(rename_all = "camelCase")]
2697    #[non_exhaustive]
2698    pub struct CancelToolCallResponse {
2699        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2700        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2701        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2702        ///
2703        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2704        #[serde_as(deserialize_as = "DefaultOnError")]
2705        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2706        #[serde(default)]
2707        #[serde(rename = "_meta")]
2708        pub meta: Option<Meta>,
2709    }
2710}
2711
2712impl CancelToolCallResponse {
2713    /// Builds [`CancelToolCallResponse`] with the required response fields set. Optional fields start unset or empty.
2714    #[must_use]
2715    pub fn new() -> Self {
2716        Self::default()
2717    }
2718
2719    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2720    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2721    /// do not recognize.
2722    ///
2723    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2724    #[must_use]
2725    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2726        self.meta = meta.into_option();
2727        self
2728    }
2729}
2730
2731// Cancel terminal
2732
2733/// Request parameters for cancelling one terminal.
2734///
2735/// Clients MUST NOT send it unless the terminal currently advertises `capabilities.cancel`.
2736///
2737/// The Agent responds once it has accepted the cancellation. The response does not mean
2738/// the work has stopped. The Agent confirms it with a `terminal_update` that sets
2739/// `exitStatus`. Cancelling stops the process but does not release the terminal, and does
2740/// not change the status of a tool call that references it.
2741///
2742/// The Agent responds with `-32602` if the terminal is unknown, has already exited, or is not
2743/// cancellable. Cancelling a terminal does not change the foreground state by itself.
2744///
2745/// See protocol docs: [Cancelling Terminals](https://agentclientprotocol.com/protocol/v2/tool-calls#cancelling-terminals)
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" = TERMINAL_CANCEL_METHOD_NAME)))]
2751#[serde(rename_all = "camelCase")]
2752#[non_exhaustive]
2753pub struct CancelTerminalRequest {
2754    /// The ID of the session that owns the terminal.
2755    pub session_id: SessionId,
2756    /// The ID of the terminal to cancel.
2757    pub terminal_id: TerminalId,
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 CancelTerminalRequest {
2771    /// Builds [`CancelTerminalRequest`] with the required request fields set. Optional fields start unset or empty.
2772    #[must_use]
2773    pub fn new(session_id: impl Into<SessionId>, terminal_id: impl Into<TerminalId>) -> Self {
2774        Self {
2775            session_id: session_id.into(),
2776            terminal_id: terminal_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 terminal.
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" = TERMINAL_CANCEL_METHOD_NAME)))]
2800    #[serde(rename_all = "camelCase")]
2801    #[non_exhaustive]
2802    pub struct CancelTerminalResponse {
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 CancelTerminalResponse {
2817    /// Builds [`CancelTerminalResponse`] 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// List sessions
2836
2837/// An opaque cursor used to paginate `session/list` results.
2838#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2839#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
2840#[serde(transparent)]
2841#[from(Arc<str>, String, &str, &mut str, Box<str>, Cow<'_, str>)]
2842#[non_exhaustive]
2843pub struct SessionListCursor(pub Arc<str>);
2844
2845impl SessionListCursor {
2846    /// Wraps a protocol string as a typed [`SessionListCursor`].
2847    #[must_use]
2848    pub fn new(cursor: impl Into<Self>) -> Self {
2849        cursor.into()
2850    }
2851}
2852
2853impl AsRef<str> for SessionListCursor {
2854    fn as_ref(&self) -> &str {
2855        &self.0
2856    }
2857}
2858
2859impl From<&String> for SessionListCursor {
2860    fn from(cursor: &String) -> Self {
2861        Self(cursor.as_str().into())
2862    }
2863}
2864
2865macro_rules! impl_session_list_cursor_option_conversion {
2866    ($source:ty) => {
2867        impl IntoOption<SessionListCursor> for $source {
2868            fn into_option(self) -> Option<SessionListCursor> {
2869                Some(self.into())
2870            }
2871        }
2872    };
2873}
2874
2875impl_session_list_cursor_option_conversion!(Arc<str>);
2876impl_session_list_cursor_option_conversion!(String);
2877impl_session_list_cursor_option_conversion!(&str);
2878impl_session_list_cursor_option_conversion!(&mut str);
2879impl_session_list_cursor_option_conversion!(&String);
2880impl_session_list_cursor_option_conversion!(Box<str>);
2881impl_session_list_cursor_option_conversion!(Cow<'_, str>);
2882
2883crate::serde_util::default_on_null! {
2884    /// Request parameters for listing existing sessions.
2885    #[serde_as]
2886    #[skip_serializing_none]
2887    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2888    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2889    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LIST_METHOD_NAME)))]
2890    #[serde(rename_all = "camelCase")]
2891    #[non_exhaustive]
2892    pub struct ListSessionsRequest {
2893        /// Filter sessions by working directory. Must be an absolute path.
2894        ///
2895        /// Only sessions whose `cwd` is this same directory match. Subdirectories and
2896        /// `additionalDirectories` don't. Agents MAY normalize paths when comparing.
2897        ///
2898        /// Omitted and `null` are equivalent and mean sessions are not filtered by working directory.
2899        #[serde(default)]
2900        pub cwd: Option<AbsolutePath>,
2901        /// Opaque cursor token from a previous response's nextCursor field for cursor-based pagination
2902        ///
2903        /// Omitted and `null` are equivalent and mean the first page is requested.
2904        #[serde(default)]
2905        pub cursor: Option<SessionListCursor>,
2906        /// **UNSTABLE**
2907        ///
2908        /// This capability is not part of the spec yet, and may be removed or changed at any point.
2909        ///
2910        /// Filter sessions by archive state.
2911        ///
2912        /// Optional. Omitted and `null` are equivalent and mean `exclude`. Only send this when
2913        /// the Agent advertises the `session.archive` capability. The filter combines with `cwd` and
2914        /// applies before pagination. Clients keep the same value when following `nextCursor`.
2915        #[cfg(feature = "unstable_session_archive")]
2916        #[serde(default)]
2917        pub archived: Option<SessionArchiveFilter>,
2918        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2919        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2920        /// Implementations MUST NOT assign meaning to keys they do not recognize.
2921        ///
2922        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2923        #[serde_as(deserialize_as = "DefaultOnError")]
2924        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2925        #[serde(default)]
2926        #[serde(rename = "_meta")]
2927        pub meta: Option<Meta>,
2928    }
2929}
2930
2931impl ListSessionsRequest {
2932    /// Builds [`ListSessionsRequest`] with the required request fields set. Optional fields start unset or empty.
2933    #[must_use]
2934    pub fn new() -> Self {
2935        Self::default()
2936    }
2937
2938    /// Filter sessions by working directory. Must be an absolute path.
2939    #[must_use]
2940    pub fn cwd(mut self, cwd: impl IntoOption<AbsolutePath>) -> Self {
2941        self.cwd = cwd.into_option();
2942        self
2943    }
2944
2945    /// Opaque cursor token from a previous response's nextCursor field for cursor-based pagination
2946    #[must_use]
2947    pub fn cursor(mut self, cursor: impl IntoOption<SessionListCursor>) -> Self {
2948        self.cursor = cursor.into_option();
2949        self
2950    }
2951
2952    /// **UNSTABLE**
2953    ///
2954    /// This capability is not part of the spec yet, and may be removed or changed at any point.
2955    ///
2956    /// Filter sessions by archive state.
2957    #[cfg(feature = "unstable_session_archive")]
2958    #[must_use]
2959    pub fn archived(mut self, archived: impl IntoOption<SessionArchiveFilter>) -> Self {
2960        self.archived = archived.into_option();
2961        self
2962    }
2963
2964    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2965    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2966    /// do not recognize.
2967    ///
2968    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2969    #[must_use]
2970    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2971        self.meta = meta.into_option();
2972        self
2973    }
2974}
2975
2976/// Response from listing sessions.
2977#[serde_as]
2978#[skip_serializing_none]
2979#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2980#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2981#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LIST_METHOD_NAME)))]
2982#[serde(rename_all = "camelCase")]
2983#[non_exhaustive]
2984pub struct ListSessionsResponse {
2985    /// Array of session information objects.
2986    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2987    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2988    pub sessions: Vec<SessionInfo>,
2989    /// Opaque cursor token. If present, pass this in the next request's cursor parameter
2990    /// to fetch the next page. Omitted and `null` are equivalent and mean there are no more
2991    /// results. An empty string is a valid cursor, not the end of results.
2992    #[serde(default)]
2993    pub next_cursor: Option<SessionListCursor>,
2994    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2995    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2996    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2997    ///
2998    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2999    #[serde_as(deserialize_as = "DefaultOnError")]
3000    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3001    #[serde(default)]
3002    #[serde(rename = "_meta")]
3003    pub meta: Option<Meta>,
3004}
3005
3006impl ListSessionsResponse {
3007    /// Builds [`ListSessionsResponse`] with the required response fields set. Optional fields start unset or empty.
3008    #[must_use]
3009    pub fn new(sessions: Vec<SessionInfo>) -> Self {
3010        Self {
3011            sessions,
3012            next_cursor: None,
3013            meta: None,
3014        }
3015    }
3016
3017    /// Sets or clears the optional `nextCursor` field.
3018    #[must_use]
3019    pub fn next_cursor(mut self, next_cursor: impl IntoOption<SessionListCursor>) -> Self {
3020        self.next_cursor = next_cursor.into_option();
3021        self
3022    }
3023
3024    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3025    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3026    /// do not recognize.
3027    ///
3028    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3029    #[must_use]
3030    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3031        self.meta = meta.into_option();
3032        self
3033    }
3034}
3035
3036// Delete session
3037
3038/// Request parameters for deleting an existing session from `session/list`.
3039///
3040/// Only available if the Agent supports the `session.delete` capability.
3041#[serde_as]
3042#[skip_serializing_none]
3043#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3044#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3045#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_DELETE_METHOD_NAME)))]
3046#[serde(rename_all = "camelCase")]
3047#[non_exhaustive]
3048pub struct DeleteSessionRequest {
3049    /// The ID of the session to delete.
3050    pub session_id: SessionId,
3051    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3052    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3053    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3054    ///
3055    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3056    #[serde_as(deserialize_as = "DefaultOnError")]
3057    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3058    #[serde(default)]
3059    #[serde(rename = "_meta")]
3060    pub meta: Option<Meta>,
3061}
3062
3063impl DeleteSessionRequest {
3064    /// Builds [`DeleteSessionRequest`] with the required request fields set. Optional fields start unset or empty.
3065    #[must_use]
3066    pub fn new(session_id: impl Into<SessionId>) -> Self {
3067        Self {
3068            session_id: session_id.into(),
3069            meta: None,
3070        }
3071    }
3072
3073    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3074    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3075    /// do not recognize.
3076    ///
3077    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3078    #[must_use]
3079    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3080        self.meta = meta.into_option();
3081        self
3082    }
3083}
3084
3085crate::serde_util::default_on_null! {
3086    /// Response from deleting a session.
3087    #[serde_as]
3088    #[skip_serializing_none]
3089    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3090    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3091    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_DELETE_METHOD_NAME)))]
3092    #[serde(rename_all = "camelCase")]
3093    #[non_exhaustive]
3094    pub struct DeleteSessionResponse {
3095        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3096        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3097        /// Implementations MUST NOT assign meaning to keys they do not recognize.
3098        ///
3099        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3100        #[serde_as(deserialize_as = "DefaultOnError")]
3101        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3102        #[serde(default)]
3103        #[serde(rename = "_meta")]
3104        pub meta: Option<Meta>,
3105    }
3106}
3107
3108impl DeleteSessionResponse {
3109    /// Builds [`DeleteSessionResponse`] with the required response fields set. Optional fields start unset or empty.
3110    #[must_use]
3111    pub fn new() -> Self {
3112        Self::default()
3113    }
3114
3115    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3116    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3117    /// do not recognize.
3118    ///
3119    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3120    #[must_use]
3121    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3122        self.meta = meta.into_option();
3123        self
3124    }
3125}
3126
3127// Archive session
3128
3129/// **UNSTABLE**
3130///
3131/// This capability is not part of the spec yet, and may be removed or changed at any point.
3132///
3133/// Request parameters for archiving a session.
3134///
3135/// Only available if the Agent supports the `session.archive` capability.
3136///
3137/// Archiving hides the session from default `session/list` results. It keeps the session ID
3138/// and saved history. If the session is active, the Agent MUST cancel any ongoing work and
3139/// free the session's resources as if `session/close` had been called, then archive it.
3140/// Archiving an archived session succeeds. A session that does not exist gets `-32002`.
3141///
3142#[cfg(feature = "unstable_session_archive")]
3143#[serde_as]
3144#[skip_serializing_none]
3145#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3146#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3147#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_ARCHIVE_METHOD_NAME)))]
3148#[serde(rename_all = "camelCase")]
3149#[non_exhaustive]
3150pub struct ArchiveSessionRequest {
3151    /// The ID of the session to archive.
3152    pub session_id: SessionId,
3153    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3154    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3155    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3156    ///
3157    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3158    #[serde_as(deserialize_as = "DefaultOnError")]
3159    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3160    #[serde(default)]
3161    #[serde(rename = "_meta")]
3162    pub meta: Option<Meta>,
3163}
3164
3165#[cfg(feature = "unstable_session_archive")]
3166impl ArchiveSessionRequest {
3167    /// Builds [`ArchiveSessionRequest`] with the required request fields set. Optional fields start unset or empty.
3168    #[must_use]
3169    pub fn new(session_id: impl Into<SessionId>) -> Self {
3170        Self {
3171            session_id: session_id.into(),
3172            meta: None,
3173        }
3174    }
3175
3176    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3177    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3178    /// do not recognize.
3179    ///
3180    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3181    #[must_use]
3182    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3183        self.meta = meta.into_option();
3184        self
3185    }
3186}
3187
3188#[cfg(feature = "unstable_session_archive")]
3189crate::serde_util::default_on_null! {
3190    /// **UNSTABLE**
3191    ///
3192    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3193    ///
3194    /// Response from archiving a session.
3195    #[serde_as]
3196    #[skip_serializing_none]
3197    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3198    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3199    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_ARCHIVE_METHOD_NAME)))]
3200    #[serde(rename_all = "camelCase")]
3201    #[non_exhaustive]
3202    pub struct ArchiveSessionResponse {
3203        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3204        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3205        /// Implementations MUST NOT assign meaning to keys they do not recognize.
3206        ///
3207        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3208        #[serde_as(deserialize_as = "DefaultOnError")]
3209        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3210        #[serde(default)]
3211        #[serde(rename = "_meta")]
3212        pub meta: Option<Meta>,
3213    }
3214}
3215
3216#[cfg(feature = "unstable_session_archive")]
3217impl ArchiveSessionResponse {
3218    /// Builds [`ArchiveSessionResponse`] with the required response fields set. Optional fields start unset or empty.
3219    #[must_use]
3220    pub fn new() -> Self {
3221        Self::default()
3222    }
3223
3224    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3225    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3226    /// do not recognize.
3227    ///
3228    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3229    #[must_use]
3230    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3231        self.meta = meta.into_option();
3232        self
3233    }
3234}
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 unarchiving a session.
3241///
3242/// Only available if the Agent supports the `session.archive` capability.
3243///
3244/// Unarchiving returns the session to default `session/list` results with the same ID and
3245/// saved history. It never loads or resumes the session. Clients that want to continue an
3246/// archived session SHOULD unarchive it before calling `session/resume`.
3247/// Unarchiving a session that is not archived succeeds. A session that does not exist
3248/// gets `-32002`.
3249///
3250#[cfg(feature = "unstable_session_archive")]
3251#[serde_as]
3252#[skip_serializing_none]
3253#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3254#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3255#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_UNARCHIVE_METHOD_NAME)))]
3256#[serde(rename_all = "camelCase")]
3257#[non_exhaustive]
3258pub struct UnarchiveSessionRequest {
3259    /// The ID of the session to unarchive.
3260    pub session_id: SessionId,
3261    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3262    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3263    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3264    ///
3265    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3266    #[serde_as(deserialize_as = "DefaultOnError")]
3267    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3268    #[serde(default)]
3269    #[serde(rename = "_meta")]
3270    pub meta: Option<Meta>,
3271}
3272
3273#[cfg(feature = "unstable_session_archive")]
3274impl UnarchiveSessionRequest {
3275    /// Builds [`UnarchiveSessionRequest`] with the required request fields set. Optional fields start unset or empty.
3276    #[must_use]
3277    pub fn new(session_id: impl Into<SessionId>) -> Self {
3278        Self {
3279            session_id: session_id.into(),
3280            meta: None,
3281        }
3282    }
3283
3284    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3285    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3286    /// do not recognize.
3287    ///
3288    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3289    #[must_use]
3290    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3291        self.meta = meta.into_option();
3292        self
3293    }
3294}
3295
3296#[cfg(feature = "unstable_session_archive")]
3297crate::serde_util::default_on_null! {
3298    /// **UNSTABLE**
3299    ///
3300    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3301    ///
3302    /// Response from unarchiving a session.
3303    #[serde_as]
3304    #[skip_serializing_none]
3305    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3306    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3307    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_UNARCHIVE_METHOD_NAME)))]
3308    #[serde(rename_all = "camelCase")]
3309    #[non_exhaustive]
3310    pub struct UnarchiveSessionResponse {
3311        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3312        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3313        /// Implementations MUST NOT assign meaning to keys they do not recognize.
3314        ///
3315        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3316        #[serde_as(deserialize_as = "DefaultOnError")]
3317        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3318        #[serde(default)]
3319        #[serde(rename = "_meta")]
3320        pub meta: Option<Meta>,
3321    }
3322}
3323
3324#[cfg(feature = "unstable_session_archive")]
3325impl UnarchiveSessionResponse {
3326    /// Builds [`UnarchiveSessionResponse`] with the required response fields set. Optional fields start unset or empty.
3327    #[must_use]
3328    pub fn new() -> Self {
3329        Self::default()
3330    }
3331
3332    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3333    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3334    /// do not recognize.
3335    ///
3336    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3337    #[must_use]
3338    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3339        self.meta = meta.into_option();
3340        self
3341    }
3342}
3343
3344/// **UNSTABLE**
3345///
3346/// This capability is not part of the spec yet, and may be removed or changed at any point.
3347///
3348/// Which sessions `session/list` returns based on their archive state.
3349///
3350/// Unknown values are preserved so they can be stored, proxied, or forwarded. An Agent MUST
3351/// return `-32602` for a value it does not support rather than treating it as `exclude`.
3352#[cfg(feature = "unstable_session_archive")]
3353#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3354#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
3355#[serde(rename_all = "snake_case")]
3356#[non_exhaustive]
3357pub enum SessionArchiveFilter {
3358    /// Only sessions that are not archived. This is the default.
3359    #[default]
3360    Exclude,
3361    /// Both archived sessions and sessions that are not archived.
3362    Include,
3363    /// Only archived sessions.
3364    Only,
3365    /// Custom or future archive filter.
3366    ///
3367    /// Values beginning with `_` are reserved for implementation-specific
3368    /// extensions. Unknown values that do not begin with `_` are reserved for
3369    /// future ACP variants.
3370    #[serde(untagged)]
3371    Other(String),
3372}
3373
3374/// Information about a session returned by session/list
3375#[serde_as]
3376#[skip_serializing_none]
3377#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3378#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3379#[serde(rename_all = "camelCase")]
3380#[non_exhaustive]
3381pub struct SessionInfo {
3382    /// Unique identifier for the session
3383    pub session_id: SessionId,
3384    /// The working directory for this session. Must be an absolute path.
3385    pub cwd: AbsolutePath,
3386    /// Additional workspace roots reported for this session. Each path must be absolute.
3387    ///
3388    /// When present, this is the complete ordered additional-root list reported
3389    /// by the Agent. Omitted and empty values are equivalent: the response
3390    /// reports no additional roots.
3391    #[serde_as(deserialize_as = "DefaultOnNull")]
3392    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
3393    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3394    pub additional_directories: Vec<AbsolutePath>,
3395
3396    /// Human-readable title for the session
3397    ///
3398    /// Omitted and `null` are equivalent and mean no title is provided.
3399    #[serde_as(deserialize_as = "DefaultOnError")]
3400    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3401    #[serde(default)]
3402    pub title: Option<String>,
3403    /// RFC 3339 timestamp of last activity.
3404    ///
3405    /// Omitted and `null` are equivalent and mean the last activity time is not reported.
3406    #[serde_as(deserialize_as = "DefaultOnError")]
3407    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "format" = "date-time")))]
3408    #[serde(default)]
3409    pub updated_at: Option<String>,
3410    /// **UNSTABLE**
3411    ///
3412    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3413    ///
3414    /// Whether the session is archived.
3415    ///
3416    /// Optional. Omitted and `null` are equivalent and mean the archive state is not reported.
3417    /// Agents that advertise the `session.archive` capability MUST include it on every listed session.
3418    #[cfg(feature = "unstable_session_archive")]
3419    #[serde_as(deserialize_as = "DefaultOnError")]
3420    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3421    #[serde(default)]
3422    pub archived: Option<bool>,
3423    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3424    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3425    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3426    ///
3427    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3428    #[serde_as(deserialize_as = "DefaultOnError")]
3429    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3430    #[serde(default)]
3431    #[serde(rename = "_meta")]
3432    pub meta: Option<Meta>,
3433}
3434
3435impl SessionInfo {
3436    /// Builds [`SessionInfo`] with the required fields set. Optional fields start unset or empty.
3437    #[must_use]
3438    pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<AbsolutePath>) -> Self {
3439        Self {
3440            session_id: session_id.into(),
3441            cwd: cwd.into(),
3442            additional_directories: vec![],
3443            title: None,
3444            updated_at: None,
3445            #[cfg(feature = "unstable_session_archive")]
3446            archived: None,
3447            meta: None,
3448        }
3449    }
3450
3451    /// Additional workspace roots reported for this session. Each path must be absolute.
3452    #[must_use]
3453    pub fn additional_directories<I, P>(mut self, additional_directories: I) -> Self
3454    where
3455        I: IntoIterator<Item = P>,
3456        P: Into<AbsolutePath>,
3457    {
3458        self.additional_directories = additional_directories.into_iter().map(Into::into).collect();
3459        self
3460    }
3461
3462    /// Human-readable title for the session
3463    #[must_use]
3464    pub fn title(mut self, title: impl IntoOption<String>) -> Self {
3465        self.title = title.into_option();
3466        self
3467    }
3468
3469    /// RFC 3339 timestamp of last activity.
3470    #[must_use]
3471    pub fn updated_at(mut self, updated_at: impl IntoOption<String>) -> Self {
3472        self.updated_at = updated_at.into_option();
3473        self
3474    }
3475
3476    /// **UNSTABLE**
3477    ///
3478    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3479    ///
3480    /// Whether the session is archived.
3481    #[cfg(feature = "unstable_session_archive")]
3482    #[must_use]
3483    pub fn archived(mut self, archived: impl IntoOption<bool>) -> Self {
3484        self.archived = archived.into_option();
3485        self
3486    }
3487
3488    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3489    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3490    /// do not recognize.
3491    ///
3492    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3493    #[must_use]
3494    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3495        self.meta = meta.into_option();
3496        self
3497    }
3498}
3499
3500// Set session title
3501
3502/// **UNSTABLE**
3503///
3504/// This capability is not part of the spec yet, and may be removed or changed at any point.
3505///
3506/// Request parameters for setting the title of a session.
3507///
3508/// Only available if the Agent supports the `session.title` capability.
3509///
3510/// The session does not need to be active on the connection. Any session the Agent would
3511/// return from `session/list` can be retitled. A session that does not exist gets `-32002`.
3512///
3513/// The Agent responds only after it has stored the title. After a successful response, the
3514/// Agent SHOULD NOT replace the title with one it generates automatically.
3515#[cfg(feature = "unstable_session_set_title")]
3516#[serde_as]
3517#[skip_serializing_none]
3518#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3519#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3520#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_TITLE_METHOD_NAME)))]
3521#[serde(rename_all = "camelCase")]
3522#[non_exhaustive]
3523pub struct SetSessionTitleRequest {
3524    /// The ID of the session to retitle.
3525    pub session_id: SessionId,
3526    /// The new title for the session.
3527    ///
3528    /// Required and non-null. Omission and explicit `null` are both invalid. The Agent MAY
3529    /// normalize the title before storing it, for example by trimming whitespace or
3530    /// truncating it. The Agent rejects a title that fails its validation, including one
3531    /// that is empty after normalization, with `-32602`.
3532    pub title: String,
3533    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3534    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3535    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3536    ///
3537    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3538    #[serde_as(deserialize_as = "DefaultOnError")]
3539    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3540    #[serde(default)]
3541    #[serde(rename = "_meta")]
3542    pub meta: Option<Meta>,
3543}
3544
3545#[cfg(feature = "unstable_session_set_title")]
3546impl SetSessionTitleRequest {
3547    /// Builds [`SetSessionTitleRequest`] with the required request fields set. Optional fields start unset or empty.
3548    #[must_use]
3549    pub fn new(session_id: impl Into<SessionId>, title: impl Into<String>) -> Self {
3550        Self {
3551            session_id: session_id.into(),
3552            title: title.into(),
3553            meta: None,
3554        }
3555    }
3556
3557    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3558    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3559    /// do not recognize.
3560    ///
3561    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3562    #[must_use]
3563    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3564        self.meta = meta.into_option();
3565        self
3566    }
3567}
3568
3569/// **UNSTABLE**
3570///
3571/// This capability is not part of the spec yet, and may be removed or changed at any point.
3572///
3573/// Response from setting the title of a session.
3574#[cfg(feature = "unstable_session_set_title")]
3575#[serde_as]
3576#[skip_serializing_none]
3577#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3578#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3579#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_TITLE_METHOD_NAME)))]
3580#[serde(rename_all = "camelCase")]
3581#[non_exhaustive]
3582pub struct SetSessionTitleResponse {
3583    /// The title the Agent stored.
3584    ///
3585    /// This differs from the requested title if the Agent normalized it. Clients SHOULD
3586    /// display this value rather than the one they sent.
3587    pub title: String,
3588    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3589    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3590    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3591    ///
3592    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3593    #[serde_as(deserialize_as = "DefaultOnError")]
3594    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3595    #[serde(default)]
3596    #[serde(rename = "_meta")]
3597    pub meta: Option<Meta>,
3598}
3599
3600#[cfg(feature = "unstable_session_set_title")]
3601impl SetSessionTitleResponse {
3602    /// Builds [`SetSessionTitleResponse`] with the required response fields set. Optional fields start unset or empty.
3603    #[must_use]
3604    pub fn new(title: impl Into<String>) -> Self {
3605        Self {
3606            title: title.into(),
3607            meta: None,
3608        }
3609    }
3610
3611    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3612    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3613    /// do not recognize.
3614    ///
3615    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3616    #[must_use]
3617    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3618        self.meta = meta.into_option();
3619        self
3620    }
3621}
3622
3623// Session config options
3624
3625/// Unique identifier for a session configuration option.
3626#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3627#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3628#[serde(transparent)]
3629#[from(forward)]
3630#[non_exhaustive]
3631pub struct SessionConfigId(pub Arc<str>);
3632
3633impl SessionConfigId {
3634    /// Wraps a protocol string as a typed [`SessionConfigId`].
3635    #[must_use]
3636    pub fn new(id: impl Into<Self>) -> Self {
3637        id.into()
3638    }
3639}
3640
3641/// Unique identifier for a session configuration option value.
3642#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3643#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3644#[serde(transparent)]
3645#[from(forward)]
3646#[non_exhaustive]
3647pub struct SessionConfigValueId(pub Arc<str>);
3648
3649impl SessionConfigValueId {
3650    /// Wraps a protocol string as a typed [`SessionConfigValueId`].
3651    #[must_use]
3652    pub fn new(id: impl Into<Self>) -> Self {
3653        id.into()
3654    }
3655}
3656
3657/// Unique identifier for a session configuration option value group.
3658#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3659#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3660#[serde(transparent)]
3661#[from(forward)]
3662#[non_exhaustive]
3663pub struct SessionConfigGroupId(pub Arc<str>);
3664
3665impl SessionConfigGroupId {
3666    /// Wraps a protocol string as a typed [`SessionConfigGroupId`].
3667    #[must_use]
3668    pub fn new(id: impl Into<Self>) -> Self {
3669        id.into()
3670    }
3671}
3672
3673/// A possible value for a session configuration option.
3674#[serde_as]
3675#[skip_serializing_none]
3676#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3677#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3678#[serde(rename_all = "camelCase")]
3679#[non_exhaustive]
3680pub struct SessionConfigSelectOption {
3681    /// Unique identifier for this option value.
3682    pub value: SessionConfigValueId,
3683    /// Human-readable label for this option value.
3684    pub name: String,
3685    /// Optional description for this option value.
3686    ///
3687    /// Omitted and `null` are equivalent and mean no description is provided.
3688    #[serde_as(deserialize_as = "DefaultOnError")]
3689    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3690    #[serde(default)]
3691    pub description: Option<String>,
3692    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3693    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3694    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3695    ///
3696    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3697    #[serde_as(deserialize_as = "DefaultOnError")]
3698    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3699    #[serde(default)]
3700    #[serde(rename = "_meta")]
3701    pub meta: Option<Meta>,
3702}
3703
3704impl SessionConfigSelectOption {
3705    /// Builds [`SessionConfigSelectOption`] with the required fields set. Optional fields start unset or empty.
3706    #[must_use]
3707    pub fn new(value: impl Into<SessionConfigValueId>, name: impl Into<String>) -> Self {
3708        Self {
3709            value: value.into(),
3710            name: name.into(),
3711            description: None,
3712            meta: None,
3713        }
3714    }
3715
3716    /// Sets or clears the optional `description` field.
3717    #[must_use]
3718    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
3719        self.description = description.into_option();
3720        self
3721    }
3722
3723    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3724    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3725    /// do not recognize.
3726    ///
3727    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3728    #[must_use]
3729    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3730        self.meta = meta.into_option();
3731        self
3732    }
3733}
3734
3735/// A group of possible values for a session configuration option.
3736#[serde_as]
3737#[skip_serializing_none]
3738#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3739#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3740#[serde(rename_all = "camelCase")]
3741#[non_exhaustive]
3742pub struct SessionConfigSelectGroup {
3743    /// Unique identifier for this group.
3744    pub group_id: SessionConfigGroupId,
3745    /// Human-readable label for this group.
3746    pub name: String,
3747    /// The set of option values in this group. MUST contain at least one value.
3748    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
3749    #[cfg_attr(feature = "schemars", schemars(length(min = 1), extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3750    pub options: Vec<SessionConfigSelectOption>,
3751    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3752    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
3753    /// Implementations MUST NOT assign meaning to keys they do not recognize.
3754    ///
3755    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3756    #[serde_as(deserialize_as = "DefaultOnError")]
3757    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3758    #[serde(default)]
3759    #[serde(rename = "_meta")]
3760    pub meta: Option<Meta>,
3761}
3762
3763impl SessionConfigSelectGroup {
3764    /// Builds [`SessionConfigSelectGroup`] with the required fields set. Optional fields start unset or empty.
3765    #[must_use]
3766    pub fn new(
3767        group_id: impl Into<SessionConfigGroupId>,
3768        name: impl Into<String>,
3769        options: Vec<SessionConfigSelectOption>,
3770    ) -> Self {
3771        Self {
3772            group_id: group_id.into(),
3773            name: name.into(),
3774            options,
3775            meta: None,
3776        }
3777    }
3778
3779    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3780    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
3781    /// do not recognize.
3782    ///
3783    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
3784    #[must_use]
3785    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3786        self.meta = meta.into_option();
3787        self
3788    }
3789}
3790
3791/// Possible values for a session configuration option.
3792#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3793#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3794#[serde(untagged)]
3795#[non_exhaustive]
3796pub enum SessionConfigSelectOptions {
3797    /// A flat list of options with no grouping.
3798    Ungrouped(
3799        #[cfg_attr(feature = "schemars", schemars(length(min = 1)))] Vec<SessionConfigSelectOption>,
3800    ),
3801    /// A list of options grouped under headers.
3802    Grouped(
3803        #[cfg_attr(feature = "schemars", schemars(length(min = 1)))] Vec<SessionConfigSelectGroup>,
3804    ),
3805}
3806
3807impl From<Vec<SessionConfigSelectOption>> for SessionConfigSelectOptions {
3808    fn from(options: Vec<SessionConfigSelectOption>) -> Self {
3809        SessionConfigSelectOptions::Ungrouped(options)
3810    }
3811}
3812
3813impl From<Vec<SessionConfigSelectGroup>> for SessionConfigSelectOptions {
3814    fn from(groups: Vec<SessionConfigSelectGroup>) -> Self {
3815        SessionConfigSelectOptions::Grouped(groups)
3816    }
3817}
3818
3819/// A single-value selector (dropdown) session configuration option payload.
3820#[skip_serializing_none]
3821#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3822#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3823#[serde(rename_all = "camelCase")]
3824#[non_exhaustive]
3825pub struct SessionConfigSelect {
3826    /// The currently selected value. MUST be one of the `value`s in `options`.
3827    pub current_value: SessionConfigValueId,
3828    /// The set of selectable options. MUST contain at least one value, and each `value` MUST be
3829    /// unique within the option, including across groups.
3830    pub options: SessionConfigSelectOptions,
3831}
3832
3833impl SessionConfigSelect {
3834    /// Builds [`SessionConfigSelect`] with the required fields set. Optional fields start unset or empty.
3835    #[must_use]
3836    pub fn new(
3837        current_value: impl Into<SessionConfigValueId>,
3838        options: impl Into<SessionConfigSelectOptions>,
3839    ) -> Self {
3840        Self {
3841            current_value: current_value.into(),
3842            options: options.into(),
3843        }
3844    }
3845}
3846
3847/// A boolean on/off toggle session configuration option payload.
3848#[skip_serializing_none]
3849#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3850#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3851#[serde(rename_all = "camelCase")]
3852#[non_exhaustive]
3853pub struct SessionConfigBoolean {
3854    /// The current value of the boolean option.
3855    pub current_value: bool,
3856}
3857
3858impl SessionConfigBoolean {
3859    /// Builds [`SessionConfigBoolean`] with the required fields set. Optional fields start unset or empty.
3860    #[must_use]
3861    pub fn new(current_value: bool) -> Self {
3862        Self { current_value }
3863    }
3864}
3865
3866/// Semantic category for a session configuration option.
3867///
3868/// This is intended to help Clients distinguish broadly common selectors (e.g. model selector vs
3869/// session mode selector vs thought/reasoning level) for UX purposes (keyboard shortcuts, icons,
3870/// placement). It MUST NOT be required for correctness. Clients MUST handle missing or unknown
3871/// categories gracefully.
3872///
3873/// Category names beginning with `_` are free for custom use, like other ACP extension methods.
3874/// Category names that do not begin with `_` are reserved for the ACP spec.
3875#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3876#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3877#[serde(rename_all = "snake_case")]
3878#[non_exhaustive]
3879pub enum SessionConfigOptionCategory {
3880    /// Session mode selector.
3881    Mode,
3882    /// Model selector.
3883    Model,
3884    /// Model-related configuration parameter.
3885    ModelConfig,
3886    /// Thought/reasoning level selector.
3887    ThoughtLevel,
3888    /// Custom or future category.
3889    ///
3890    /// Values beginning with `_` are reserved for implementation-specific
3891    /// extensions. Unknown values that do not begin with `_` are reserved for
3892    /// future ACP variants.
3893    #[serde(untagged)]
3894    Other(String),
3895}
3896
3897/// Type-specific session configuration option payload.
3898#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3899#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3900#[serde(tag = "type", rename_all = "snake_case")]
3901#[non_exhaustive]
3902pub enum SessionConfigKind {
3903    /// Single-value selector (dropdown).
3904    Select(SessionConfigSelect),
3905    /// Boolean on/off toggle.
3906    Boolean(SessionConfigBoolean),
3907    /// Custom or future session configuration option payload.
3908    ///
3909    /// Values beginning with `_` are reserved for implementation-specific
3910    /// extensions. Unknown values that do not begin with `_` are reserved for
3911    /// future ACP variants.
3912    ///
3913    /// Clients that do not understand this option type should preserve the raw
3914    /// payload when storing, replaying, proxying, or forwarding configuration
3915    /// data, and otherwise ignore the option. The Agent keeps using its `currentValue`.
3916    #[serde(untagged)]
3917    Other(OtherSessionConfigKind),
3918}
3919
3920/// Custom or future session configuration option payload.
3921#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3922#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
3923#[cfg_attr(feature = "schemars", schemars(inline))]
3924#[cfg_attr(feature = "schemars", schemars(transform = other_session_config_kind_schema))]
3925#[serde(rename_all = "camelCase")]
3926#[non_exhaustive]
3927pub struct OtherSessionConfigKind {
3928    /// Custom or future session configuration option type.
3929    ///
3930    /// Values beginning with `_` are reserved for implementation-specific
3931    /// extensions. Unknown values that do not begin with `_` are reserved for
3932    /// future ACP variants.
3933    #[serde(rename = "type")]
3934    pub type_: String,
3935    /// Additional fields from the unknown session configuration option payload.
3936    #[serde(flatten)]
3937    pub fields: BTreeMap<String, serde_json::Value>,
3938}
3939
3940impl OtherSessionConfigKind {
3941    /// Builds [`OtherSessionConfigKind`] from an unknown discriminator and preserves the remaining extension fields.
3942    #[must_use]
3943    pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
3944        fields.remove("type");
3945        fields.remove("_meta");
3946        Self {
3947            type_: type_.into(),
3948            fields,
3949        }
3950    }
3951}
3952
3953impl<'de> Deserialize<'de> for OtherSessionConfigKind {
3954    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3955    where
3956        D: serde::Deserializer<'de>,
3957    {
3958        let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
3959        let type_ = fields
3960            .remove("type")
3961            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
3962        let serde_json::Value::String(type_) = type_ else {
3963            return Err(serde::de::Error::custom("`type` must be a string"));
3964        };
3965
3966        if is_known_session_config_kind_type(&type_) {
3967            return Err(serde::de::Error::custom(format!(
3968                "known session configuration option `{type_}` did not match its schema"
3969            )));
3970        }
3971
3972        Ok(Self { type_, fields })
3973    }
3974}
3975
3976fn is_known_session_config_kind_type(type_: &str) -> bool {
3977    matches!(type_, "select" | "boolean")
3978}
3979
3980#[cfg(feature = "schemars")]
3981fn other_session_config_kind_schema(schema: &mut Schema) {
3982    super::schema_util::reject_known_string_discriminators(schema, "type", &["select", "boolean"]);
3983}
3984
3985/// A session configuration option selector and its current state.
3986#[serde_as]
3987#[skip_serializing_none]
3988#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3989#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3990#[serde(rename_all = "camelCase")]
3991#[non_exhaustive]
3992pub struct SessionConfigOption {
3993    /// Unique identifier for the configuration option.
3994    pub config_id: SessionConfigId,
3995    /// Human-readable label for the option.
3996    pub name: String,
3997    /// Optional description for the Client to display to the user.
3998    ///
3999    /// Omitted and `null` are equivalent and mean no description is provided.
4000    #[serde_as(deserialize_as = "DefaultOnError")]
4001    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4002    #[serde(default)]
4003    pub description: Option<String>,
4004    /// Optional semantic category for this option (UX only).
4005    ///
4006    /// Omitted and `null` are equivalent and mean no category is provided.
4007    #[serde_as(deserialize_as = "DefaultOnError")]
4008    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4009    #[serde(default)]
4010    pub category: Option<SessionConfigOptionCategory>,
4011    /// Type-specific fields for this configuration option.
4012    #[serde(flatten)]
4013    pub kind: SessionConfigKind,
4014    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4015    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4016    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4017    ///
4018    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4019    #[serde_as(deserialize_as = "DefaultOnError")]
4020    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4021    #[serde(default)]
4022    #[serde(rename = "_meta")]
4023    pub meta: Option<Meta>,
4024}
4025
4026impl SessionConfigOption {
4027    /// Builds [`SessionConfigOption`] with the required fields set. Optional fields start unset or empty.
4028    #[must_use]
4029    pub fn new(
4030        config_id: impl Into<SessionConfigId>,
4031        name: impl Into<String>,
4032        kind: SessionConfigKind,
4033    ) -> Self {
4034        Self {
4035            config_id: config_id.into(),
4036            name: name.into(),
4037            description: None,
4038            category: None,
4039            kind,
4040            meta: None,
4041        }
4042    }
4043
4044    /// Builds a select-style session configuration option with its current value and choices.
4045    #[must_use]
4046    pub fn select(
4047        config_id: impl Into<SessionConfigId>,
4048        name: impl Into<String>,
4049        current_value: impl Into<SessionConfigValueId>,
4050        options: impl Into<SessionConfigSelectOptions>,
4051    ) -> Self {
4052        Self::new(
4053            config_id,
4054            name,
4055            SessionConfigKind::Select(SessionConfigSelect::new(current_value, options)),
4056        )
4057    }
4058
4059    /// Builds a boolean-style session configuration option with its current value.
4060    #[must_use]
4061    pub fn boolean(
4062        config_id: impl Into<SessionConfigId>,
4063        name: impl Into<String>,
4064        current_value: bool,
4065    ) -> Self {
4066        Self::new(
4067            config_id,
4068            name,
4069            SessionConfigKind::Boolean(SessionConfigBoolean::new(current_value)),
4070        )
4071    }
4072
4073    /// Sets or clears the optional `description` field.
4074    #[must_use]
4075    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
4076        self.description = description.into_option();
4077        self
4078    }
4079
4080    /// Sets or clears the optional `category` field.
4081    #[must_use]
4082    pub fn category(mut self, category: impl IntoOption<SessionConfigOptionCategory>) -> Self {
4083        self.category = category.into_option();
4084        self
4085    }
4086
4087    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4088    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4089    /// do not recognize.
4090    ///
4091    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4092    #[must_use]
4093    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4094        self.meta = meta.into_option();
4095        self
4096    }
4097}
4098
4099/// The value to set for a session configuration option.
4100///
4101/// The `type` field acts as the discriminator in the serialized JSON form.
4102///
4103/// The `type` discriminator describes the *shape* of the value, not the option
4104/// kind. For example every option kind that picks from a list of ids
4105/// (`select`, `radio`, …) would use [`Id`](Self::Id), while a future freeform
4106/// text option would get its own variant.
4107#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4108#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4109#[serde(tag = "type", rename_all = "snake_case")]
4110#[non_exhaustive]
4111pub enum SessionConfigOptionValue {
4112    /// A `SessionConfigValueId` string value (`type: "id"`).
4113    Id {
4114        /// The value ID.
4115        value: SessionConfigValueId,
4116    },
4117    /// A boolean value (`type: "boolean"`).
4118    Boolean {
4119        /// The boolean value.
4120        value: bool,
4121    },
4122    /// Custom or future session configuration option value payload.
4123    ///
4124    /// Values beginning with `_` are reserved for implementation-specific
4125    /// extensions. Unknown values that do not begin with `_` are reserved for
4126    /// future ACP variants.
4127    ///
4128    /// Agents MUST reject a `session/set_config_option` request with a value type
4129    /// they do not support with `-32602`.
4130    #[serde(untagged)]
4131    Other(OtherSessionConfigOptionValue),
4132}
4133
4134/// Custom or future session configuration option value payload.
4135#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4136#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4137#[cfg_attr(feature = "schemars", schemars(inline))]
4138#[cfg_attr(feature = "schemars", schemars(transform = other_session_config_option_value_schema))]
4139#[serde(rename_all = "camelCase")]
4140#[non_exhaustive]
4141pub struct OtherSessionConfigOptionValue {
4142    /// Custom or future session configuration option value type.
4143    ///
4144    /// Values beginning with `_` are reserved for implementation-specific
4145    /// extensions. Unknown values that do not begin with `_` are reserved for
4146    /// future ACP variants.
4147    #[serde(rename = "type")]
4148    pub type_: String,
4149    /// Raw value payload for the custom or future value type.
4150    pub value: serde_json::Value,
4151    /// Additional fields from the unknown session configuration option value payload.
4152    #[serde(flatten)]
4153    pub fields: BTreeMap<String, serde_json::Value>,
4154}
4155
4156impl OtherSessionConfigOptionValue {
4157    /// Builds [`OtherSessionConfigOptionValue`] from an unknown discriminator and preserves the remaining extension fields.
4158    #[must_use]
4159    pub fn new(
4160        type_: impl Into<String>,
4161        value: serde_json::Value,
4162        mut fields: BTreeMap<String, serde_json::Value>,
4163    ) -> Self {
4164        fields.remove("type");
4165        fields.remove("value");
4166        fields.remove("_meta");
4167        Self {
4168            type_: type_.into(),
4169            value,
4170            fields,
4171        }
4172    }
4173}
4174
4175impl<'de> Deserialize<'de> for OtherSessionConfigOptionValue {
4176    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4177    where
4178        D: serde::Deserializer<'de>,
4179    {
4180        let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
4181        let type_ = fields
4182            .remove("type")
4183            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4184        let serde_json::Value::String(type_) = type_ else {
4185            return Err(serde::de::Error::custom("`type` must be a string"));
4186        };
4187
4188        if is_known_session_config_option_value_type(&type_) {
4189            return Err(serde::de::Error::custom(format!(
4190                "known session configuration option value `{type_}` did not match its schema"
4191            )));
4192        }
4193
4194        let value = fields
4195            .remove("value")
4196            .ok_or_else(|| serde::de::Error::missing_field("value"))?;
4197
4198        Ok(Self {
4199            type_,
4200            value,
4201            fields,
4202        })
4203    }
4204}
4205
4206impl<'de> Deserialize<'de> for SessionConfigOptionValue {
4207    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4208    where
4209        D: serde::Deserializer<'de>,
4210    {
4211        let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
4212        let type_ = fields.remove("type");
4213        let value = fields
4214            .remove("value")
4215            .ok_or_else(|| serde::de::Error::missing_field("value"))?;
4216
4217        let type_ = type_.ok_or_else(|| serde::de::Error::missing_field("type"))?;
4218
4219        let serde_json::Value::String(type_) = type_ else {
4220            return Err(serde::de::Error::custom("`type` must be a string"));
4221        };
4222
4223        match type_.as_str() {
4224            "id" => {
4225                let value = serde_json::from_value(value).map_err(|error| {
4226                    serde::de::Error::custom(format!(
4227                        "`value` must be a string for `type: id`: {error}"
4228                    ))
4229                })?;
4230                Ok(Self::Id { value })
4231            }
4232            "boolean" => {
4233                let value = serde_json::from_value(value).map_err(|error| {
4234                    serde::de::Error::custom(format!(
4235                        "`value` must be a boolean for `type: boolean`: {error}"
4236                    ))
4237                })?;
4238                Ok(Self::Boolean { value })
4239            }
4240            _ => Ok(Self::Other(OtherSessionConfigOptionValue {
4241                type_,
4242                value,
4243                fields,
4244            })),
4245        }
4246    }
4247}
4248
4249fn is_known_session_config_option_value_type(type_: &str) -> bool {
4250    matches!(type_, "id" | "boolean")
4251}
4252
4253#[cfg(feature = "schemars")]
4254fn other_session_config_option_value_schema(schema: &mut Schema) {
4255    super::schema_util::reject_known_string_discriminators(schema, "type", &["id", "boolean"]);
4256}
4257
4258impl SessionConfigOptionValue {
4259    /// Create an id option value (used by `select` and other id-based option types).
4260    #[must_use]
4261    pub fn id(id: impl Into<SessionConfigValueId>) -> Self {
4262        Self::Id { value: id.into() }
4263    }
4264
4265    /// Create a boolean option value.
4266    #[must_use]
4267    pub fn boolean(val: bool) -> Self {
4268        Self::Boolean { value: val }
4269    }
4270
4271    /// Return the inner [`SessionConfigValueId`] if this is a
4272    /// [`Id`](Self::Id) value.
4273    #[must_use]
4274    pub fn as_id(&self) -> Option<&SessionConfigValueId> {
4275        match self {
4276            Self::Id { value } => Some(value),
4277            _ => None,
4278        }
4279    }
4280
4281    /// Return the inner [`bool`] if this is a [`Boolean`](Self::Boolean) value.
4282    #[must_use]
4283    pub fn as_bool(&self) -> Option<bool> {
4284        match self {
4285            Self::Boolean { value } => Some(*value),
4286            _ => None,
4287        }
4288    }
4289}
4290
4291impl From<SessionConfigValueId> for SessionConfigOptionValue {
4292    fn from(value: SessionConfigValueId) -> Self {
4293        Self::Id { value }
4294    }
4295}
4296
4297impl From<bool> for SessionConfigOptionValue {
4298    fn from(value: bool) -> Self {
4299        Self::Boolean { value }
4300    }
4301}
4302
4303impl From<&str> for SessionConfigOptionValue {
4304    fn from(value: &str) -> Self {
4305        Self::Id {
4306            value: SessionConfigValueId::new(value),
4307        }
4308    }
4309}
4310
4311/// Request parameters for setting a session configuration option.
4312///
4313/// Agents MUST support this method for any session where they advertise config options.
4314/// Agents MUST reject an unknown `configId` or invalid value with `-32602` and leave the
4315/// configuration unchanged.
4316///
4317/// See protocol docs: [Session Config Options](https://agentclientprotocol.com/protocol/v2/session-config-options#setting-a-config-option)
4318#[serde_as]
4319#[skip_serializing_none]
4320#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4321#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4322#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_CONFIG_OPTION_METHOD_NAME)))]
4323#[serde(rename_all = "camelCase")]
4324#[non_exhaustive]
4325pub struct SetSessionConfigOptionRequest {
4326    /// The ID of the session to set the configuration option for.
4327    pub session_id: SessionId,
4328    /// The ID of the configuration option to set.
4329    pub config_id: SessionConfigId,
4330    /// The value to set, including a `type` discriminator and the raw `value`.
4331    ///
4332    /// Payloads must send `type: "id"` for id-based options.
4333    #[serde(flatten)]
4334    pub value: SessionConfigOptionValue,
4335    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4336    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4337    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4338    ///
4339    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4340    #[serde_as(deserialize_as = "DefaultOnError")]
4341    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4342    #[serde(default)]
4343    #[serde(rename = "_meta")]
4344    pub meta: Option<Meta>,
4345}
4346
4347impl SetSessionConfigOptionRequest {
4348    /// Builds [`SetSessionConfigOptionRequest`] with the required request fields set. Optional fields start unset or empty.
4349    #[must_use]
4350    pub fn new(
4351        session_id: impl Into<SessionId>,
4352        config_id: impl Into<SessionConfigId>,
4353        value: impl Into<SessionConfigOptionValue>,
4354    ) -> Self {
4355        Self {
4356            session_id: session_id.into(),
4357            config_id: config_id.into(),
4358            value: value.into(),
4359            meta: None,
4360        }
4361    }
4362
4363    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4364    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4365    /// do not recognize.
4366    ///
4367    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4368    #[must_use]
4369    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4370        self.meta = meta.into_option();
4371        self
4372    }
4373}
4374
4375/// Response to `session/set_config_option` method.
4376#[serde_as]
4377#[skip_serializing_none]
4378#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4379#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4380#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_CONFIG_OPTION_METHOD_NAME)))]
4381#[serde(rename_all = "camelCase")]
4382#[non_exhaustive]
4383pub struct SetSessionConfigOptionResponse {
4384    /// The full set of configuration options and their current values.
4385    #[serde_as(deserialize_as = "VecSkipError<_>")]
4386    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-skip-invalid-items" = true)))]
4387    pub config_options: Vec<SessionConfigOption>,
4388    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4389    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4390    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4391    ///
4392    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4393    #[serde_as(deserialize_as = "DefaultOnError")]
4394    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4395    #[serde(default)]
4396    #[serde(rename = "_meta")]
4397    pub meta: Option<Meta>,
4398}
4399
4400impl SetSessionConfigOptionResponse {
4401    /// Builds [`SetSessionConfigOptionResponse`] with the required response fields set. Optional fields start unset or empty.
4402    #[must_use]
4403    pub fn new(config_options: Vec<SessionConfigOption>) -> Self {
4404        Self {
4405            config_options,
4406            meta: None,
4407        }
4408    }
4409
4410    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4411    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4412    /// do not recognize.
4413    ///
4414    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4415    #[must_use]
4416    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4417        self.meta = meta.into_option();
4418        self
4419    }
4420}
4421
4422// MCP
4423
4424/// Configuration for connecting to an MCP (Model Context Protocol) server.
4425///
4426/// MCP servers provide tools and context that the agent can use when
4427/// processing prompts.
4428///
4429/// See protocol docs: [MCP Servers](https://agentclientprotocol.com/protocol/v2/session-setup#mcp-servers)
4430#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4431#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4432#[serde(tag = "type", rename_all = "snake_case")]
4433#[non_exhaustive]
4434pub enum McpServer {
4435    /// HTTP transport configuration
4436    ///
4437    /// Only available when the Agent capabilities include `session.mcp.http`.
4438    Http(McpServerHttp),
4439    /// **UNSTABLE**
4440    ///
4441    /// This capability is not part of the spec yet, and may be removed or changed at any point.
4442    ///
4443    /// ACP transport configuration
4444    ///
4445    /// Only available when the Agent capabilities include `session.mcp.acp`.
4446    /// The MCP server is provided by an ACP component and communicates over the ACP channel.
4447    #[cfg(feature = "unstable_mcp_over_acp")]
4448    Acp(McpServerAcp),
4449    /// Stdio transport configuration
4450    ///
4451    /// Only available when the Agent capabilities include `session.mcp.stdio`.
4452    Stdio(McpServerStdio),
4453    /// Custom or future MCP server transport configuration.
4454    ///
4455    /// Values beginning with `_` are reserved for implementation-specific
4456    /// extensions. Unknown values that do not begin with `_` are reserved for
4457    /// future ACP variants.
4458    ///
4459    /// Receivers that do not understand this transport should preserve the raw
4460    /// payload when storing, replaying, proxying, or forwarding session setup
4461    /// data. Agents MUST reject a request with a transport they do not support
4462    /// with `-32602`.
4463    #[serde(untagged)]
4464    Other(OtherMcpServer),
4465}
4466
4467/// Custom or future MCP server transport payload.
4468#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4469#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
4470#[cfg_attr(feature = "schemars", schemars(inline))]
4471#[cfg_attr(feature = "schemars", schemars(transform = other_mcp_server_schema))]
4472#[serde(rename_all = "camelCase")]
4473#[non_exhaustive]
4474pub struct OtherMcpServer {
4475    /// Custom or future MCP server transport type.
4476    ///
4477    /// Values beginning with `_` are reserved for implementation-specific
4478    /// extensions. Unknown values that do not begin with `_` are reserved for
4479    /// future ACP variants.
4480    #[serde(rename = "type")]
4481    pub type_: String,
4482    /// Additional fields from the unknown MCP server transport payload.
4483    #[serde(flatten)]
4484    pub fields: BTreeMap<String, serde_json::Value>,
4485}
4486
4487impl OtherMcpServer {
4488    /// Builds [`OtherMcpServer`] from an unknown discriminator and preserves the remaining extension fields.
4489    #[must_use]
4490    pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
4491        fields.remove("type");
4492        Self {
4493            type_: type_.into(),
4494            fields,
4495        }
4496    }
4497}
4498
4499impl<'de> Deserialize<'de> for OtherMcpServer {
4500    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4501    where
4502        D: serde::Deserializer<'de>,
4503    {
4504        let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
4505        let type_ = fields
4506            .remove("type")
4507            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
4508        let serde_json::Value::String(type_) = type_ else {
4509            return Err(serde::de::Error::custom("`type` must be a string"));
4510        };
4511
4512        if is_known_mcp_server_type(&type_) {
4513            return Err(serde::de::Error::custom(format!(
4514                "known MCP server transport `{type_}` did not match its schema"
4515            )));
4516        }
4517
4518        Ok(Self { type_, fields })
4519    }
4520}
4521
4522fn is_known_mcp_server_type(type_: &str) -> bool {
4523    match type_ {
4524        "http" | "stdio" => true,
4525        #[cfg(feature = "unstable_mcp_over_acp")]
4526        "acp" => true,
4527        _ => false,
4528    }
4529}
4530
4531#[cfg(feature = "schemars")]
4532fn other_mcp_server_schema(schema: &mut Schema) {
4533    super::schema_util::reject_known_string_discriminators(
4534        schema,
4535        "type",
4536        &[
4537            "http",
4538            "stdio",
4539            #[cfg(feature = "unstable_mcp_over_acp")]
4540            "acp",
4541        ],
4542    );
4543}
4544
4545/// HTTP transport configuration for MCP.
4546#[serde_as]
4547#[skip_serializing_none]
4548#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4549#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4550#[serde(rename_all = "camelCase")]
4551#[non_exhaustive]
4552pub struct McpServerHttp {
4553    /// Human-readable name identifying this MCP server.
4554    pub name: String,
4555    /// URL to the MCP server.
4556    #[cfg_attr(feature = "schemars", schemars(url))]
4557    pub url: String,
4558    /// HTTP headers to set when making requests to the MCP server. Headers the MCP transport
4559    /// defines are owned by the transport, and Agents use the transport's values for them.
4560    #[serde_as(deserialize_as = "DefaultOnNull")]
4561    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4562    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4563    pub headers: Vec<HttpHeader>,
4564    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4565    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4566    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4567    ///
4568    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4569    #[serde_as(deserialize_as = "DefaultOnError")]
4570    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4571    #[serde(default)]
4572    #[serde(rename = "_meta")]
4573    pub meta: Option<Meta>,
4574}
4575
4576impl McpServerHttp {
4577    /// Builds [`McpServerHttp`] with the required fields set. Optional fields start unset or empty.
4578    #[must_use]
4579    pub fn new(name: impl Into<String>, url: impl Into<String>) -> Self {
4580        Self {
4581            name: name.into(),
4582            url: url.into(),
4583            headers: Vec::new(),
4584            meta: None,
4585        }
4586    }
4587
4588    /// HTTP headers to set when making requests to the MCP server. Headers the MCP transport
4589    /// defines are owned by the transport, and Agents use the transport's values for them.
4590    #[must_use]
4591    pub fn headers(mut self, headers: Vec<HttpHeader>) -> Self {
4592        self.headers = headers;
4593        self
4594    }
4595
4596    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4597    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4598    /// do not recognize.
4599    ///
4600    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4601    #[must_use]
4602    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4603        self.meta = meta.into_option();
4604        self
4605    }
4606}
4607
4608/// **UNSTABLE**
4609///
4610/// This capability is not part of the spec yet, and may be removed or changed at any point.
4611///
4612/// Unique identifier for an MCP server using the ACP transport.
4613///
4614/// The value is opaque and generated by the ACP component providing the MCP server. It is
4615/// used by `mcp/message` to route requests to the component that declared the server.
4616#[cfg(feature = "unstable_mcp_over_acp")]
4617#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4618#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
4619#[serde(transparent)]
4620#[from(forward)]
4621#[non_exhaustive]
4622pub struct McpServerAcpId(pub Arc<str>);
4623
4624#[cfg(feature = "unstable_mcp_over_acp")]
4625impl McpServerAcpId {
4626    /// Wraps a protocol string as a typed [`McpServerAcpId`].
4627    #[must_use]
4628    pub fn new(id: impl Into<Self>) -> Self {
4629        id.into()
4630    }
4631}
4632
4633/// **UNSTABLE**
4634///
4635/// This capability is not part of the spec yet, and may be removed or changed at any point.
4636///
4637/// ACP transport configuration for MCP.
4638///
4639/// The MCP server is provided by an ACP component and communicates over the ACP channel
4640/// using `mcp/message`.
4641#[serde_as]
4642#[skip_serializing_none]
4643#[cfg(feature = "unstable_mcp_over_acp")]
4644#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4645#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4646#[serde(rename_all = "camelCase")]
4647#[non_exhaustive]
4648pub struct McpServerAcp {
4649    /// Human-readable name identifying this MCP server.
4650    pub name: String,
4651    /// Unique identifier for this MCP server, generated by the component providing it.
4652    ///
4653    /// Providers MUST NOT reuse an ID for multiple ACP-transport MCP servers that are visible
4654    /// on the same ACP connection.
4655    pub server_id: McpServerAcpId,
4656    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4657    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4658    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4659    ///
4660    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4661    #[serde_as(deserialize_as = "DefaultOnError")]
4662    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4663    #[serde(default)]
4664    #[serde(rename = "_meta")]
4665    pub meta: Option<Meta>,
4666}
4667
4668#[cfg(feature = "unstable_mcp_over_acp")]
4669impl McpServerAcp {
4670    /// Builds [`McpServerAcp`] with the required fields set. Optional fields start unset or empty.
4671    #[must_use]
4672    pub fn new(name: impl Into<String>, server_id: impl Into<McpServerAcpId>) -> Self {
4673        Self {
4674            name: name.into(),
4675            server_id: server_id.into(),
4676            meta: None,
4677        }
4678    }
4679
4680    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4681    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4682    /// do not recognize.
4683    ///
4684    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4685    #[must_use]
4686    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4687        self.meta = meta.into_option();
4688        self
4689    }
4690}
4691
4692/// Stdio transport configuration for MCP.
4693#[serde_as]
4694#[skip_serializing_none]
4695#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4696#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4697#[serde(rename_all = "camelCase")]
4698#[non_exhaustive]
4699pub struct McpServerStdio {
4700    /// Human-readable name identifying this MCP server.
4701    pub name: String,
4702    /// Absolute path to the MCP server executable.
4703    pub command: AbsolutePath,
4704    /// Command-line arguments to pass to the MCP server.
4705    #[serde_as(deserialize_as = "DefaultOnNull")]
4706    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4707    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4708    pub args: Vec<String>,
4709    /// Environment variables to set when launching the MCP server. Names SHOULD be unique.
4710    /// Agents MAY reject duplicates with `-32602`, and otherwise the last entry wins.
4711    #[serde_as(deserialize_as = "DefaultOnNull")]
4712    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4713    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4714    pub env: Vec<EnvVariable>,
4715    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4716    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4717    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4718    ///
4719    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4720    #[serde_as(deserialize_as = "DefaultOnError")]
4721    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4722    #[serde(default)]
4723    #[serde(rename = "_meta")]
4724    pub meta: Option<Meta>,
4725}
4726
4727impl McpServerStdio {
4728    /// Builds [`McpServerStdio`] with the required fields set. Optional fields start unset or empty.
4729    #[must_use]
4730    pub fn new(name: impl Into<String>, command: impl Into<AbsolutePath>) -> Self {
4731        Self {
4732            name: name.into(),
4733            command: command.into(),
4734            args: Vec::new(),
4735            env: Vec::new(),
4736            meta: None,
4737        }
4738    }
4739
4740    /// Command-line arguments to pass to the MCP server.
4741    #[must_use]
4742    pub fn args(mut self, args: Vec<String>) -> Self {
4743        self.args = args;
4744        self
4745    }
4746
4747    /// Environment variables to set when launching the MCP server. Names SHOULD be unique.
4748    /// Agents MAY reject duplicates with `-32602`, and otherwise the last entry wins.
4749    #[must_use]
4750    pub fn env(mut self, env: Vec<EnvVariable>) -> Self {
4751        self.env = env;
4752        self
4753    }
4754
4755    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4756    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4757    /// do not recognize.
4758    ///
4759    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4760    #[must_use]
4761    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4762        self.meta = meta.into_option();
4763        self
4764    }
4765}
4766
4767/// An environment variable to set when launching a process.
4768#[serde_as]
4769#[skip_serializing_none]
4770#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4771#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4772#[serde(rename_all = "camelCase")]
4773#[non_exhaustive]
4774pub struct EnvVariable {
4775    /// The name of the environment variable.
4776    pub name: String,
4777    /// The value to set for the environment variable.
4778    pub value: String,
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
4791impl EnvVariable {
4792    /// Builds [`EnvVariable`] with the required fields set. Optional fields start unset or empty.
4793    #[must_use]
4794    pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
4795        Self {
4796            name: name.into(),
4797            value: value.into(),
4798            meta: None,
4799        }
4800    }
4801
4802    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4803    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4804    /// do not recognize.
4805    ///
4806    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4807    #[must_use]
4808    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4809        self.meta = meta.into_option();
4810        self
4811    }
4812}
4813
4814/// An HTTP header to set when making requests to the MCP server.
4815#[serde_as]
4816#[skip_serializing_none]
4817#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4818#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4819#[serde(rename_all = "camelCase")]
4820#[non_exhaustive]
4821pub struct HttpHeader {
4822    /// The name of the HTTP header.
4823    pub name: String,
4824    /// The value to set for the HTTP header.
4825    pub value: String,
4826    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4827    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4828    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4829    ///
4830    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4831    #[serde_as(deserialize_as = "DefaultOnError")]
4832    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4833    #[serde(default)]
4834    #[serde(rename = "_meta")]
4835    pub meta: Option<Meta>,
4836}
4837
4838impl HttpHeader {
4839    /// Builds [`HttpHeader`] with the required fields set. Optional fields start unset or empty.
4840    #[must_use]
4841    pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
4842        Self {
4843            name: name.into(),
4844            value: value.into(),
4845            meta: None,
4846        }
4847    }
4848
4849    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4850    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4851    /// do not recognize.
4852    ///
4853    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4854    #[must_use]
4855    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4856        self.meta = meta.into_option();
4857        self
4858    }
4859}
4860
4861// System prompt
4862
4863/// Client-provided system-level instructions for a session.
4864///
4865/// Clients MUST only send this when the Agent advertises
4866/// `session.systemPrompt`. Agents that cannot apply it, for example because of
4867/// an unadvertised mode or an unsupported content block type, MUST return an
4868/// error instead of creating or resuming the session.
4869#[serde_as]
4870#[skip_serializing_none]
4871#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4872#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4873#[serde(rename_all = "camelCase")]
4874#[non_exhaustive]
4875pub struct SystemPrompt {
4876    /// How the Agent combines `content` with its own instructions.
4877    ///
4878    /// Required. Agents MUST return an error for a mode they do not support rather than
4879    /// treating it as `append` or `override`.
4880    pub mode: SystemPromptMode,
4881    /// The system prompt content.
4882    ///
4883    /// Agents advertising the capability MUST accept `text` content blocks.
4884    /// Clients MUST NOT send other content block types until a future
4885    /// capability allows them, and Agents MUST return an error for content
4886    /// blocks they do not support, including unknown types.
4887    ///
4888    /// Clients MUST NOT send an empty array. Agents MAY reject one with
4889    /// `-32602` without creating or resuming the session.
4890    pub content: Vec<ContentBlock>,
4891    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4892    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
4893    /// Implementations MUST NOT assign meaning to keys they do not recognize.
4894    ///
4895    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4896    #[serde_as(deserialize_as = "DefaultOnError")]
4897    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4898    #[serde(default)]
4899    #[serde(rename = "_meta")]
4900    pub meta: Option<Meta>,
4901}
4902
4903impl SystemPrompt {
4904    /// Builds [`SystemPrompt`] with the required fields set. Optional fields start unset or empty.
4905    ///
4906    /// `mode` starts as [`SystemPromptMode::Append`]. Use [`SystemPrompt::mode`]
4907    /// to request another mode.
4908    #[must_use]
4909    pub fn new(content: Vec<ContentBlock>) -> Self {
4910        Self {
4911            mode: SystemPromptMode::default(),
4912            content,
4913            meta: None,
4914        }
4915    }
4916
4917    /// How the Agent combines `content` with its own instructions.
4918    #[must_use]
4919    pub fn mode(mut self, mode: SystemPromptMode) -> Self {
4920        self.mode = mode;
4921        self
4922    }
4923
4924    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4925    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
4926    /// do not recognize.
4927    ///
4928    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
4929    #[must_use]
4930    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4931        self.meta = meta.into_option();
4932        self
4933    }
4934}
4935
4936/// How the Agent combines a client-provided system prompt with its own instructions.
4937///
4938/// Unknown modes are preserved so they can be stored,
4939/// proxied, or forwarded. An Agent MUST return an error for a mode it does not
4940/// support rather than treating it as `append` or `override`.
4941#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4942#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
4943#[serde(rename_all = "snake_case")]
4944#[non_exhaustive]
4945pub enum SystemPromptMode {
4946    /// Add the content to the Agent's own instructions rather than replacing them.
4947    ///
4948    /// Every Agent that advertises `session.systemPrompt` supports this mode.
4949    /// Agents SHOULD give the content system-level precedence, for example in the
4950    /// model's system prompt or developer instructions rather than in user-turn
4951    /// content. Where it is placed and how it is formatted is implementation-defined.
4952    #[default]
4953    Append,
4954    /// Replace the Agent's built-in default instructions with the content.
4955    ///
4956    /// This does not change tool availability, MCP servers, permissions, or session
4957    /// configuration. Context the Agent supplies from the workspace or environment
4958    /// MAY still be included. Clients that use this mode take responsibility for any
4959    /// tool guidance or safety instructions the Agent's default instructions
4960    /// provided, and MUST only use it when the Agent advertises
4961    /// `session.systemPrompt.mode.override`.
4962    Override,
4963    /// Custom or future system prompt mode.
4964    ///
4965    /// Values beginning with `_` are reserved for implementation-specific
4966    /// extensions. Unknown values that do not begin with `_` are reserved for
4967    /// future ACP variants.
4968    #[serde(untagged)]
4969    Other(String),
4970}
4971
4972// Prompt
4973
4974/// Request parameters for sending a user prompt to the agent.
4975///
4976/// Contains the user's message and any additional context.
4977///
4978/// See protocol docs: [User Message](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#1-user-message)
4979#[serde_as]
4980#[skip_serializing_none]
4981#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4982#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4983#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_PROMPT_METHOD_NAME)))]
4984#[serde(rename_all = "camelCase")]
4985#[non_exhaustive]
4986pub struct PromptRequest {
4987    /// The ID of the session to send this user message to
4988    pub session_id: SessionId,
4989    /// The blocks of content that compose the user's message.
4990    ///
4991    /// As a baseline, the Agent MUST support `text` and `resource_link` content blocks,
4992    /// while other variants are optionally enabled via `PromptCapabilities`.
4993    ///
4994    /// The Client MUST adapt its interface according to `PromptCapabilities`.
4995    ///
4996    /// The client MAY include referenced pieces of context as either
4997    /// `resource` or `resource_link` content blocks.
4998    ///
4999    /// When available, `resource` is preferred
5000    /// as it avoids extra round-trips and allows the message to include
5001    /// pieces of context from sources the agent may not have access to.
5002    ///
5003    /// Clients MUST NOT send an empty array. Agents MAY reject one with `-32602` without
5004    /// inserting it.
5005    #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
5006    pub prompt: Vec<ContentBlock>,
5007    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5008    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5009    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5010    ///
5011    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5012    #[serde_as(deserialize_as = "DefaultOnError")]
5013    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5014    #[serde(default)]
5015    #[serde(rename = "_meta")]
5016    pub meta: Option<Meta>,
5017}
5018
5019impl PromptRequest {
5020    /// Builds [`PromptRequest`] with the required request fields set. Optional fields start unset or empty.
5021    #[must_use]
5022    pub fn new(session_id: impl Into<SessionId>, prompt: Vec<ContentBlock>) -> Self {
5023        Self {
5024            session_id: session_id.into(),
5025            prompt,
5026            meta: None,
5027        }
5028    }
5029
5030    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5031    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5032    /// do not recognize.
5033    ///
5034    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5035    #[must_use]
5036    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5037        self.meta = meta.into_option();
5038        self
5039    }
5040}
5041
5042/// Response acknowledging that a user prompt was inserted into the ACP conversation.
5043///
5044/// This response does not indicate that the prompt was merely received or held, nor that the
5045/// agent has finished processing it.
5046/// Processing and completion are reported through `state_update` session updates.
5047///
5048/// Insertion is the logical addition of a user message with a message ID and a position
5049/// relative to other messages in the ACP conversation.
5050///
5051/// See protocol docs: [Prompt Accepted](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#2-prompt-accepted)
5052#[serde_as]
5053#[skip_serializing_none]
5054#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5055#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5056#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_PROMPT_METHOD_NAME)))]
5057#[serde(rename_all = "camelCase")]
5058#[non_exhaustive]
5059pub struct PromptResponse {
5060    /// Identifies the user message inserted into the ACP conversation.
5061    ///
5062    /// Required and non-null. Omission and explicit `null` are both invalid.
5063    ///
5064    /// The corresponding user-message session update carries this same identifier and may arrive
5065    /// before or after this response. Agents must echo the message during the live session, but are
5066    /// not required to retain it. If retained and replayed, the message keeps this identifier.
5067    pub message_id: MessageId,
5068    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5069    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5070    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5071    ///
5072    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5073    #[serde_as(deserialize_as = "DefaultOnError")]
5074    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5075    #[serde(default)]
5076    #[serde(rename = "_meta")]
5077    pub meta: Option<Meta>,
5078}
5079
5080impl PromptResponse {
5081    /// Builds [`PromptResponse`] with the required response fields set. Optional fields start unset or empty.
5082    #[must_use]
5083    pub fn new(message_id: impl Into<MessageId>) -> Self {
5084        Self {
5085            message_id: message_id.into(),
5086            meta: None,
5087        }
5088    }
5089
5090    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5091    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5092    /// do not recognize.
5093    ///
5094    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5095    #[must_use]
5096    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5097        self.meta = meta.into_option();
5098        self
5099    }
5100}
5101
5102/// Reasons why an agent stops active session work.
5103///
5104/// See protocol docs: [Stop Reasons](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#stop-reasons)
5105#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5106#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
5107#[serde(tag = "stopReason", rename_all = "snake_case")]
5108#[non_exhaustive]
5109pub enum StopReason {
5110    /// The active work ended successfully.
5111    /// Includes locally handled commands that required no model call.
5112    EndTurn,
5113    /// The active work ended because the agent reached the maximum number of tokens.
5114    MaxTokens,
5115    /// The active work ended because the agent reached the maximum number of
5116    /// model requests for the foreground work.
5117    MaxTurnRequests,
5118    /// The active work ended because the agent refused to continue.
5119    Refusal,
5120    /// The user or client chose to stop the work: via `session/cancel`, by
5121    /// closing the session, or through an interaction the agent offers, such
5122    /// as a permission option that tells the agent to stop. Work the agent
5123    /// stops for its own reasons uses another reason, such as `error` for an
5124    /// internal timeout.
5125    ///
5126    /// Agents MUST report this stop reason on an idle `state_update` when
5127    /// cancellation ends active foreground work, even if aborting causes
5128    /// exceptions. Agents MUST catch these errors and report `cancelled`, not
5129    /// `error`.
5130    Cancelled,
5131    /// The active work ended because something failed.
5132    ///
5133    /// This includes pre-insertion foreground work. A prompt failure before
5134    /// insertion also requires an error response to `session/prompt`. After
5135    /// insertion, the prompt's response remains successful.
5136    Error(ErrorStopReason),
5137    /// Custom or future stop reason.
5138    ///
5139    /// Values beginning with `_` are reserved for implementation-specific
5140    /// extensions. Unknown values that do not begin with `_` are reserved for
5141    /// future ACP variants.
5142    #[serde(untagged)]
5143    Other(OtherStopReason),
5144}
5145
5146impl From<ErrorStopReason> for StopReason {
5147    fn from(value: ErrorStopReason) -> Self {
5148        Self::Error(value)
5149    }
5150}
5151
5152/// Details of a failure that ended active work.
5153#[serde_as]
5154#[skip_serializing_none]
5155#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5156#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
5157#[serde(rename_all = "camelCase")]
5158#[non_exhaustive]
5159pub struct ErrorStopReason {
5160    /// The failure, as a JSON-RPC error object.
5161    ///
5162    /// Optional. Omitted and `null` are equivalent and mean the agent is not reporting failure details.
5163    /// Agents SHOULD include it.
5164    #[serde_as(deserialize_as = "DefaultOnError")]
5165    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5166    #[serde(default)]
5167    pub error: Option<Box<Error>>,
5168}
5169
5170impl ErrorStopReason {
5171    /// Builds [`ErrorStopReason`] with the required fields set. Optional fields start unset or empty.
5172    #[must_use]
5173    pub fn new() -> Self {
5174        Self::default()
5175    }
5176
5177    /// The failure, as a JSON-RPC error object.
5178    #[must_use]
5179    pub fn error(mut self, error: impl IntoOption<Error>) -> Self {
5180        self.error = error.into_option().map(Box::new);
5181        self
5182    }
5183}
5184
5185/// Custom or future stop reason payload.
5186#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5187#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
5188#[cfg_attr(feature = "schemars", schemars(inline))]
5189#[cfg_attr(feature = "schemars", schemars(transform = other_stop_reason_schema))]
5190#[serde(rename_all = "camelCase")]
5191#[non_exhaustive]
5192pub struct OtherStopReason {
5193    /// Custom or future stop reason.
5194    ///
5195    /// Values beginning with `_` are reserved for implementation-specific
5196    /// extensions. Unknown values that do not begin with `_` are reserved for
5197    /// future ACP variants.
5198    pub stop_reason: String,
5199    /// Additional fields from the unknown stop reason payload.
5200    #[serde(flatten)]
5201    pub fields: BTreeMap<String, serde_json::Value>,
5202}
5203
5204impl OtherStopReason {
5205    /// Builds [`OtherStopReason`] from an unknown discriminator and preserves the remaining extension fields.
5206    #[must_use]
5207    pub fn new(
5208        stop_reason: impl Into<String>,
5209        mut fields: BTreeMap<String, serde_json::Value>,
5210    ) -> Self {
5211        remove_idle_state_update_fields(&mut fields);
5212        Self {
5213            stop_reason: stop_reason.into(),
5214            fields,
5215        }
5216    }
5217}
5218
5219impl<'de> Deserialize<'de> for OtherStopReason {
5220    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
5221    where
5222        D: serde::Deserializer<'de>,
5223    {
5224        let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
5225        let stop_reason = fields
5226            .remove("stopReason")
5227            .ok_or_else(|| serde::de::Error::missing_field("stopReason"))?;
5228        let serde_json::Value::String(stop_reason) = stop_reason else {
5229            return Err(serde::de::Error::custom("`stopReason` must be a string"));
5230        };
5231
5232        if KNOWN_STOP_REASONS.contains(&stop_reason.as_str()) {
5233            return Err(serde::de::Error::custom(format!(
5234                "known stop reason `{stop_reason}` did not match its schema"
5235            )));
5236        }
5237        remove_idle_state_update_fields(&mut fields);
5238
5239        Ok(Self {
5240            stop_reason,
5241            fields,
5242        })
5243    }
5244}
5245
5246const KNOWN_STOP_REASONS: &[&str] = &[
5247    "end_turn",
5248    "max_tokens",
5249    "max_turn_requests",
5250    "refusal",
5251    "cancelled",
5252    "error",
5253];
5254
5255/// Keeps the idle update's own fields out of an unknown stop reason's payload.
5256fn remove_idle_state_update_fields(fields: &mut BTreeMap<String, serde_json::Value>) {
5257    fields.remove("stopReason");
5258    fields.remove("usage");
5259    fields.remove("_meta");
5260}
5261
5262#[cfg(feature = "schemars")]
5263fn other_stop_reason_schema(schema: &mut Schema) {
5264    super::schema_util::reject_known_string_discriminators(
5265        schema,
5266        "stopReason",
5267        KNOWN_STOP_REASONS,
5268    );
5269}
5270
5271/// **UNSTABLE**
5272///
5273/// This capability is not part of the spec yet, and may be removed or changed at any point.
5274///
5275/// Token usage for the foreground work that just completed, not cumulative for the session.
5276#[cfg(feature = "unstable_end_turn_token_usage")]
5277#[serde_as]
5278#[skip_serializing_none]
5279#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5280#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5281#[serde(rename_all = "camelCase")]
5282#[non_exhaustive]
5283pub struct Usage {
5284    /// Sum of all token types for the completed work.
5285    pub total_tokens: u64,
5286    /// Input tokens for the completed work.
5287    pub input_tokens: u64,
5288    /// Output tokens for the completed work.
5289    pub output_tokens: u64,
5290    /// Thought/reasoning tokens for the completed work.
5291    ///
5292    /// Omitted and `null` are equivalent and mean the count is not reported.
5293    #[serde_as(deserialize_as = "DefaultOnError")]
5294    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5295    #[serde(default)]
5296    pub thought_tokens: Option<u64>,
5297    /// Cache read tokens for the completed work.
5298    ///
5299    /// Omitted and `null` are equivalent and mean the count is not reported.
5300    #[serde_as(deserialize_as = "DefaultOnError")]
5301    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5302    #[serde(default)]
5303    pub cached_read_tokens: Option<u64>,
5304    /// Cache write tokens for the completed work.
5305    ///
5306    /// Omitted and `null` are equivalent and mean the count is not reported.
5307    #[serde_as(deserialize_as = "DefaultOnError")]
5308    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5309    #[serde(default)]
5310    pub cached_write_tokens: Option<u64>,
5311    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5312    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5313    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5314    ///
5315    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5316    #[serde_as(deserialize_as = "DefaultOnError")]
5317    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5318    #[serde(default)]
5319    #[serde(rename = "_meta")]
5320    pub meta: Option<Meta>,
5321}
5322
5323#[cfg(feature = "unstable_end_turn_token_usage")]
5324impl Usage {
5325    /// Builds [`Usage`] with the required fields set. Optional fields start unset or empty.
5326    #[must_use]
5327    pub fn new(total_tokens: u64, input_tokens: u64, output_tokens: u64) -> Self {
5328        Self {
5329            total_tokens,
5330            input_tokens,
5331            output_tokens,
5332            thought_tokens: None,
5333            cached_read_tokens: None,
5334            cached_write_tokens: None,
5335            meta: None,
5336        }
5337    }
5338
5339    /// Thought/reasoning tokens for the completed work.
5340    #[must_use]
5341    pub fn thought_tokens(mut self, thought_tokens: impl IntoOption<u64>) -> Self {
5342        self.thought_tokens = thought_tokens.into_option();
5343        self
5344    }
5345
5346    /// Cache read tokens for the completed work.
5347    #[must_use]
5348    pub fn cached_read_tokens(mut self, cached_read_tokens: impl IntoOption<u64>) -> Self {
5349        self.cached_read_tokens = cached_read_tokens.into_option();
5350        self
5351    }
5352
5353    /// Cache write tokens for the completed work.
5354    #[must_use]
5355    pub fn cached_write_tokens(mut self, cached_write_tokens: impl IntoOption<u64>) -> Self {
5356        self.cached_write_tokens = cached_write_tokens.into_option();
5357        self
5358    }
5359
5360    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5361    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5362    /// do not recognize.
5363    ///
5364    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5365    #[must_use]
5366    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5367        self.meta = meta.into_option();
5368        self
5369    }
5370}
5371
5372// Providers
5373
5374/// **UNSTABLE**
5375///
5376/// This capability is not part of the spec yet, and may be removed or changed at any point.
5377///
5378/// Well-known API protocol identifiers for LLM providers.
5379///
5380/// Agents and clients MUST handle unknown protocol identifiers gracefully.
5381///
5382/// Protocol names beginning with `_` are free for custom use, like other ACP extension methods.
5383/// Protocol names that do not begin with `_` are reserved for the ACP spec.
5384#[cfg(feature = "unstable_llm_providers")]
5385#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5386#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5387#[serde(rename_all = "snake_case")]
5388#[non_exhaustive]
5389#[expect(clippy::doc_markdown)]
5390pub enum LlmProtocol {
5391    /// Anthropic API protocol.
5392    Anthropic,
5393    /// OpenAI API protocol.
5394    #[serde(rename = "openai")]
5395    OpenAi,
5396    /// Azure OpenAI API protocol.
5397    Azure,
5398    /// Google Vertex AI API protocol.
5399    Vertex,
5400    /// AWS Bedrock API protocol.
5401    Bedrock,
5402    /// Custom or future protocol.
5403    ///
5404    /// Values beginning with `_` are reserved for implementation-specific
5405    /// extensions. Unknown values that do not begin with `_` are reserved for
5406    /// future ACP variants.
5407    #[serde(untagged)]
5408    Other(String),
5409}
5410
5411/// **UNSTABLE**
5412///
5413/// This capability is not part of the spec yet, and may be removed or changed at any point.
5414///
5415/// Current effective non-secret routing configuration for a provider.
5416#[cfg(feature = "unstable_llm_providers")]
5417#[serde_as]
5418#[skip_serializing_none]
5419#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5420#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5421#[serde(rename_all = "camelCase")]
5422#[non_exhaustive]
5423pub struct ProviderCurrentConfig {
5424    /// Protocol currently used by this provider.
5425    pub api_type: LlmProtocol,
5426    /// Base URL currently used by this provider.
5427    #[cfg_attr(feature = "schemars", schemars(url))]
5428    pub base_url: String,
5429    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5430    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5431    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5432    ///
5433    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5434    #[serde_as(deserialize_as = "DefaultOnError")]
5435    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5436    #[serde(default)]
5437    #[serde(rename = "_meta")]
5438    pub meta: Option<Meta>,
5439}
5440
5441#[cfg(feature = "unstable_llm_providers")]
5442impl ProviderCurrentConfig {
5443    /// Builds [`ProviderCurrentConfig`] with the required fields set. Optional fields start unset or empty.
5444    #[must_use]
5445    pub fn new(api_type: LlmProtocol, base_url: impl Into<String>) -> Self {
5446        Self {
5447            api_type,
5448            base_url: base_url.into(),
5449            meta: None,
5450        }
5451    }
5452
5453    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5454    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5455    /// do not recognize.
5456    ///
5457    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5458    #[must_use]
5459    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5460        self.meta = meta.into_option();
5461        self
5462    }
5463}
5464
5465/// **UNSTABLE**
5466///
5467/// This capability is not part of the spec yet, and may be removed or changed at any point.
5468///
5469/// Unique identifier for a configurable LLM provider.
5470#[cfg(feature = "unstable_llm_providers")]
5471#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5472#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
5473#[serde(transparent)]
5474#[from(forward)]
5475#[non_exhaustive]
5476pub struct ProviderId(pub Arc<str>);
5477
5478#[cfg(feature = "unstable_llm_providers")]
5479impl ProviderId {
5480    /// Wraps a protocol string as a typed [`ProviderId`].
5481    #[must_use]
5482    pub fn new(id: impl Into<Self>) -> Self {
5483        id.into()
5484    }
5485}
5486
5487/// **UNSTABLE**
5488///
5489/// This capability is not part of the spec yet, and may be removed or changed at any point.
5490///
5491/// Information about a configurable LLM provider.
5492#[cfg(feature = "unstable_llm_providers")]
5493#[serde_as]
5494#[skip_serializing_none]
5495#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5496#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5497#[serde(rename_all = "camelCase")]
5498#[non_exhaustive]
5499pub struct ProviderInfo {
5500    /// Provider identifier, for example "main" or "openai".
5501    pub provider_id: ProviderId,
5502    /// Supported protocol types for this provider.
5503    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
5504    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
5505    pub supported: Vec<LlmProtocol>,
5506    /// Whether this provider is mandatory and cannot be disabled via `providers/disable`.
5507    /// If true, clients must not call `providers/disable` for this provider ID.
5508    pub required: bool,
5509    /// Current effective non-secret routing config.
5510    /// Null or omitted means provider is disabled.
5511    #[serde(default)]
5512    pub current: Option<ProviderCurrentConfig>,
5513    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5514    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5515    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5516    ///
5517    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5518    #[serde_as(deserialize_as = "DefaultOnError")]
5519    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5520    #[serde(default)]
5521    #[serde(rename = "_meta")]
5522    pub meta: Option<Meta>,
5523}
5524
5525#[cfg(feature = "unstable_llm_providers")]
5526impl ProviderInfo {
5527    /// Builds [`ProviderInfo`] with the required fields set. Optional fields start unset or empty.
5528    #[must_use]
5529    pub fn new(
5530        provider_id: impl Into<ProviderId>,
5531        supported: Vec<LlmProtocol>,
5532        required: bool,
5533        current: impl IntoOption<ProviderCurrentConfig>,
5534    ) -> Self {
5535        Self {
5536            provider_id: provider_id.into(),
5537            supported,
5538            required,
5539            current: current.into_option(),
5540            meta: None,
5541        }
5542    }
5543
5544    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5545    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5546    /// do not recognize.
5547    ///
5548    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5549    #[must_use]
5550    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5551        self.meta = meta.into_option();
5552        self
5553    }
5554}
5555
5556#[cfg(feature = "unstable_llm_providers")]
5557crate::serde_util::default_on_null! {
5558    /// **UNSTABLE**
5559    ///
5560    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5561    ///
5562    /// Request parameters for `providers/list`.
5563    #[serde_as]
5564    #[skip_serializing_none]
5565    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5566    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
5567    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_LIST_METHOD_NAME)))]
5568    #[serde(rename_all = "camelCase")]
5569    #[non_exhaustive]
5570    pub struct ListProvidersRequest {
5571        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5572        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5573        /// Implementations MUST NOT assign meaning to keys they do not recognize.
5574        ///
5575        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5576        #[serde_as(deserialize_as = "DefaultOnError")]
5577        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5578        #[serde(default)]
5579        #[serde(rename = "_meta")]
5580        pub meta: Option<Meta>,
5581    }
5582}
5583
5584#[cfg(feature = "unstable_llm_providers")]
5585impl ListProvidersRequest {
5586    /// Builds [`ListProvidersRequest`] with the required request fields set. Optional fields start unset or empty.
5587    #[must_use]
5588    pub fn new() -> Self {
5589        Self::default()
5590    }
5591
5592    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5593    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5594    /// do not recognize.
5595    ///
5596    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5597    #[must_use]
5598    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5599        self.meta = meta.into_option();
5600        self
5601    }
5602}
5603
5604/// **UNSTABLE**
5605///
5606/// This capability is not part of the spec yet, and may be removed or changed at any point.
5607///
5608/// Response to `providers/list`.
5609#[cfg(feature = "unstable_llm_providers")]
5610#[serde_as]
5611#[skip_serializing_none]
5612#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5613#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5614#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_LIST_METHOD_NAME)))]
5615#[serde(rename_all = "camelCase")]
5616#[non_exhaustive]
5617pub struct ListProvidersResponse {
5618    /// Configurable providers with current routing info suitable for UI display.
5619    pub providers: Vec<ProviderInfo>,
5620    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5621    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5622    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5623    ///
5624    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5625    #[serde_as(deserialize_as = "DefaultOnError")]
5626    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5627    #[serde(default)]
5628    #[serde(rename = "_meta")]
5629    pub meta: Option<Meta>,
5630}
5631
5632#[cfg(feature = "unstable_llm_providers")]
5633impl ListProvidersResponse {
5634    /// Builds [`ListProvidersResponse`] with the required response fields set. Optional fields start unset or empty.
5635    #[must_use]
5636    pub fn new(providers: Vec<ProviderInfo>) -> Self {
5637        Self {
5638            providers,
5639            meta: None,
5640        }
5641    }
5642
5643    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5644    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5645    /// do not recognize.
5646    ///
5647    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5648    #[must_use]
5649    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5650        self.meta = meta.into_option();
5651        self
5652    }
5653}
5654
5655/// **UNSTABLE**
5656///
5657/// This capability is not part of the spec yet, and may be removed or changed at any point.
5658///
5659/// Request parameters for `providers/set`.
5660///
5661/// Replaces the full configuration for one provider ID.
5662#[cfg(feature = "unstable_llm_providers")]
5663#[serde_as]
5664#[skip_serializing_none]
5665#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5666#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
5667#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_SET_METHOD_NAME)))]
5668#[serde(rename_all = "camelCase")]
5669#[non_exhaustive]
5670pub struct SetProviderRequest {
5671    /// Provider ID to configure.
5672    pub provider_id: ProviderId,
5673    /// Protocol type for this provider.
5674    pub api_type: LlmProtocol,
5675    /// Base URL for requests sent through this provider.
5676    #[cfg_attr(feature = "schemars", schemars(url))]
5677    pub base_url: String,
5678    /// Full headers map for this provider.
5679    /// May include authorization, routing, or other integration-specific headers.
5680    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
5681    pub headers: HashMap<String, String>,
5682    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5683    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5684    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5685    ///
5686    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5687    #[serde_as(deserialize_as = "DefaultOnError")]
5688    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5689    #[serde(default)]
5690    #[serde(rename = "_meta")]
5691    pub meta: Option<Meta>,
5692}
5693
5694#[cfg(feature = "unstable_llm_providers")]
5695impl SetProviderRequest {
5696    /// Builds [`SetProviderRequest`] with the required request fields set. Optional fields start unset or empty.
5697    #[must_use]
5698    pub fn new(
5699        provider_id: impl Into<ProviderId>,
5700        api_type: LlmProtocol,
5701        base_url: impl Into<String>,
5702    ) -> Self {
5703        Self {
5704            provider_id: provider_id.into(),
5705            api_type,
5706            base_url: base_url.into(),
5707            headers: HashMap::new(),
5708            meta: None,
5709        }
5710    }
5711
5712    /// Full headers map for this provider.
5713    /// May include authorization, routing, or other integration-specific headers.
5714    #[must_use]
5715    pub fn headers(mut self, headers: HashMap<String, String>) -> Self {
5716        self.headers = headers;
5717        self
5718    }
5719
5720    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5721    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5722    /// do not recognize.
5723    ///
5724    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5725    #[must_use]
5726    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5727        self.meta = meta.into_option();
5728        self
5729    }
5730}
5731
5732#[cfg(feature = "unstable_llm_providers")]
5733crate::serde_util::default_on_null! {
5734    /// **UNSTABLE**
5735    ///
5736    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5737    ///
5738    /// Response to `providers/set`.
5739    #[serde_as]
5740    #[skip_serializing_none]
5741    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5742    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
5743    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_SET_METHOD_NAME)))]
5744    #[serde(rename_all = "camelCase")]
5745    #[non_exhaustive]
5746    pub struct SetProviderResponse {
5747        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5748        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5749        /// Implementations MUST NOT assign meaning to keys they do not recognize.
5750        ///
5751        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5752        #[serde_as(deserialize_as = "DefaultOnError")]
5753        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5754        #[serde(default)]
5755        #[serde(rename = "_meta")]
5756        pub meta: Option<Meta>,
5757    }
5758}
5759
5760#[cfg(feature = "unstable_llm_providers")]
5761impl SetProviderResponse {
5762    /// Builds [`SetProviderResponse`] with the required response fields set. Optional fields start unset or empty.
5763    #[must_use]
5764    pub fn new() -> Self {
5765        Self::default()
5766    }
5767
5768    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5769    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5770    /// do not recognize.
5771    ///
5772    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5773    #[must_use]
5774    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5775        self.meta = meta.into_option();
5776        self
5777    }
5778}
5779
5780/// **UNSTABLE**
5781///
5782/// This capability is not part of the spec yet, and may be removed or changed at any point.
5783///
5784/// Request parameters for `providers/disable`.
5785#[cfg(feature = "unstable_llm_providers")]
5786#[serde_as]
5787#[skip_serializing_none]
5788#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5789#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5790#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_DISABLE_METHOD_NAME)))]
5791#[serde(rename_all = "camelCase")]
5792#[non_exhaustive]
5793pub struct DisableProviderRequest {
5794    /// Provider ID to disable.
5795    pub provider_id: ProviderId,
5796    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5797    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5798    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5799    ///
5800    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5801    #[serde_as(deserialize_as = "DefaultOnError")]
5802    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5803    #[serde(default)]
5804    #[serde(rename = "_meta")]
5805    pub meta: Option<Meta>,
5806}
5807
5808#[cfg(feature = "unstable_llm_providers")]
5809impl DisableProviderRequest {
5810    /// Builds [`DisableProviderRequest`] with the required request fields set. Optional fields start unset or empty.
5811    #[must_use]
5812    pub fn new(provider_id: impl Into<ProviderId>) -> Self {
5813        Self {
5814            provider_id: provider_id.into(),
5815            meta: None,
5816        }
5817    }
5818
5819    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5820    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5821    /// do not recognize.
5822    ///
5823    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5824    #[must_use]
5825    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5826        self.meta = meta.into_option();
5827        self
5828    }
5829}
5830
5831#[cfg(feature = "unstable_llm_providers")]
5832crate::serde_util::default_on_null! {
5833    /// **UNSTABLE**
5834    ///
5835    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5836    ///
5837    /// Response to `providers/disable`.
5838    #[serde_as]
5839    #[skip_serializing_none]
5840    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5841    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
5842    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_DISABLE_METHOD_NAME)))]
5843    #[serde(rename_all = "camelCase")]
5844    #[non_exhaustive]
5845    pub struct DisableProviderResponse {
5846        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5847        /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5848        /// Implementations MUST NOT assign meaning to keys they do not recognize.
5849        ///
5850        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5851        #[serde_as(deserialize_as = "DefaultOnError")]
5852        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5853        #[serde(default)]
5854        #[serde(rename = "_meta")]
5855        pub meta: Option<Meta>,
5856    }
5857}
5858
5859#[cfg(feature = "unstable_llm_providers")]
5860impl DisableProviderResponse {
5861    /// Builds [`DisableProviderResponse`] with the required response fields set. Optional fields start unset or empty.
5862    #[must_use]
5863    pub fn new() -> Self {
5864        Self::default()
5865    }
5866
5867    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5868    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5869    /// do not recognize.
5870    ///
5871    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5872    #[must_use]
5873    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5874        self.meta = meta.into_option();
5875        self
5876    }
5877}
5878
5879// Capabilities
5880
5881/// Capabilities supported by the agent.
5882///
5883/// Advertised during initialization to inform the client about
5884/// available features and content types.
5885///
5886/// See protocol docs: [Agent Capabilities](https://agentclientprotocol.com/protocol/v2/initialization#agent-capabilities)
5887#[serde_as]
5888#[skip_serializing_none]
5889#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5890#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5891#[serde(rename_all = "camelCase")]
5892#[non_exhaustive]
5893pub struct AgentCapabilities {
5894    /// Session capabilities supported by the agent.
5895    ///
5896    /// Optional. Omitted and `null` are equivalent and mean the agent does not support the
5897    /// `session/*` methods. Supplying `{}` means the agent supports the
5898    /// baseline session methods: `session/new`, `session/list`,
5899    /// `session/resume`, `session/close`, `session/prompt`, `session/cancel`,
5900    /// and `session/update`.
5901    #[serde_as(deserialize_as = "DefaultOnError")]
5902    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5903    #[serde(default)]
5904    pub session: Option<SessionCapabilities>,
5905    /// Authentication-related extension capabilities supported by the agent.
5906    ///
5907    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise any
5908    /// authentication-related extensions. This field does not advertise support
5909    /// for `auth/login` or `auth/logout`. Those methods are advertised by a
5910    /// non-empty `authMethods` list in the `initialize` response.
5911    #[serde_as(deserialize_as = "DefaultOnError")]
5912    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5913    #[serde(default)]
5914    pub auth: Option<AgentAuthCapabilities>,
5915    /// **UNSTABLE**
5916    ///
5917    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5918    ///
5919    /// Provider configuration capabilities supported by the agent.
5920    ///
5921    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
5922    /// Supplying `{}` means the agent supports provider configuration methods.
5923    #[cfg(feature = "unstable_llm_providers")]
5924    #[serde_as(deserialize_as = "DefaultOnError")]
5925    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5926    #[serde(default)]
5927    pub providers: Option<ProvidersCapabilities>,
5928    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5929    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
5930    /// Implementations MUST NOT assign meaning to keys they do not recognize.
5931    ///
5932    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5933    #[serde_as(deserialize_as = "DefaultOnError")]
5934    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5935    #[serde(default)]
5936    #[serde(rename = "_meta")]
5937    pub meta: Option<Meta>,
5938}
5939
5940impl AgentCapabilities {
5941    /// Builds an empty [`AgentCapabilities`]. Use builder methods to advertise supported sub-capabilities.
5942    #[must_use]
5943    pub fn new() -> Self {
5944        Self::default()
5945    }
5946
5947    /// Session capabilities supported by the agent.
5948    ///
5949    /// Omitted and `null` are equivalent and mean the agent does not support the `session/*`
5950    /// methods. Supplying `{}` means the agent supports the baseline
5951    /// session methods: `session/new`, `session/list`, `session/resume`,
5952    /// `session/close`, `session/prompt`, `session/cancel`, and
5953    /// `session/update`.
5954    #[must_use]
5955    pub fn session(mut self, session: impl IntoOption<SessionCapabilities>) -> Self {
5956        self.session = session.into_option();
5957        self
5958    }
5959
5960    /// Authentication-related extension capabilities supported by the agent.
5961    ///
5962    /// This field does not advertise support for `auth/login` or `auth/logout`.
5963    #[must_use]
5964    pub fn auth(mut self, auth: impl IntoOption<AgentAuthCapabilities>) -> Self {
5965        self.auth = auth.into_option();
5966        self
5967    }
5968
5969    /// **UNSTABLE**
5970    ///
5971    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5972    ///
5973    /// Provider configuration capabilities supported by the agent.
5974    #[cfg(feature = "unstable_llm_providers")]
5975    #[must_use]
5976    pub fn providers(mut self, providers: impl IntoOption<ProvidersCapabilities>) -> Self {
5977        self.providers = providers.into_option();
5978        self
5979    }
5980
5981    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5982    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
5983    /// do not recognize.
5984    ///
5985    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
5986    #[must_use]
5987    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5988        self.meta = meta.into_option();
5989        self
5990    }
5991}
5992
5993/// **UNSTABLE**
5994///
5995/// This capability is not part of the spec yet, and may be removed or changed at any point.
5996///
5997/// Provider configuration capabilities supported by the agent.
5998///
5999/// Supplying `{}` means the agent supports provider configuration methods.
6000#[cfg(feature = "unstable_llm_providers")]
6001#[serde_as]
6002#[skip_serializing_none]
6003#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6004#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6005#[non_exhaustive]
6006pub struct ProvidersCapabilities {
6007    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6008    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6009    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6010    ///
6011    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6012    #[serde_as(deserialize_as = "DefaultOnError")]
6013    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6014    #[serde(default)]
6015    #[serde(rename = "_meta")]
6016    pub meta: Option<Meta>,
6017}
6018
6019#[cfg(feature = "unstable_llm_providers")]
6020impl ProvidersCapabilities {
6021    /// Builds an empty [`ProvidersCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6022    #[must_use]
6023    pub fn new() -> Self {
6024        Self::default()
6025    }
6026
6027    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6028    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6029    /// do not recognize.
6030    ///
6031    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6032    #[must_use]
6033    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6034        self.meta = meta.into_option();
6035        self
6036    }
6037}
6038
6039/// Session capabilities supported by the agent.
6040///
6041/// Supplying `{}` means the agent supports the baseline session methods:
6042/// `session/new`, `session/list`, `session/resume`, `session/close`,
6043/// `session/prompt`, `session/cancel`, and `session/update`.
6044///
6045/// Agents that support sessions **MAY** support additional session methods,
6046/// prompt content types, and MCP transports by specifying additional
6047/// capabilities.
6048///
6049/// See protocol docs: [Session Capabilities](https://agentclientprotocol.com/protocol/v2/initialization#session-capabilities)
6050#[serde_as]
6051#[skip_serializing_none]
6052#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6053#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6054#[serde(rename_all = "camelCase")]
6055#[non_exhaustive]
6056pub struct SessionCapabilities {
6057    /// Prompt capabilities supported by the agent in `session/prompt` requests.
6058    ///
6059    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise any
6060    /// prompt extensions beyond the baseline text and resource-link content
6061    /// required by `session/prompt`.
6062    #[serde_as(deserialize_as = "DefaultOnError")]
6063    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6064    #[serde(default)]
6065    pub prompt: Option<PromptCapabilities>,
6066    /// MCP capabilities supported by the agent for session lifecycle requests.
6067    ///
6068    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise MCP
6069    /// server transport support for sessions.
6070    #[serde_as(deserialize_as = "DefaultOnError")]
6071    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6072    #[serde(default)]
6073    pub mcp: Option<McpCapabilities>,
6074    /// Whether the agent supports `session/delete`.
6075    ///
6076    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
6077    /// Supplying `{}` means the agent supports deleting sessions from `session/list`.
6078    #[serde_as(deserialize_as = "DefaultOnError")]
6079    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6080    #[serde(default)]
6081    pub delete: Option<SessionDeleteCapabilities>,
6082    /// Whether the agent supports `additionalDirectories` on supported session lifecycle requests.
6083    ///
6084    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
6085    /// Supplying `{}` means the agent supports `additionalDirectories` on
6086    /// supported session lifecycle requests.
6087    ///
6088    /// Agents may return `SessionInfo.additionalDirectories` to report the
6089    /// complete ordered additional-root list associated with a listed session.
6090    #[serde_as(deserialize_as = "DefaultOnError")]
6091    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6092    #[serde(default)]
6093    pub additional_directories: Option<SessionAdditionalDirectoriesCapabilities>,
6094    /// Whether the agent supports `systemPrompt` on session lifecycle requests.
6095    ///
6096    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
6097    /// Supplying `{}` means the agent supports `systemPrompt` in `append` mode.
6098    #[serde_as(deserialize_as = "DefaultOnError")]
6099    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6100    #[serde(default)]
6101    pub system_prompt: Option<SessionSystemPromptCapabilities>,
6102    /// **UNSTABLE**
6103    ///
6104    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6105    ///
6106    /// Whether the agent supports `session/fork`.
6107    ///
6108    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
6109    /// Supplying `{}` means the agent supports forking sessions.
6110    #[cfg(feature = "unstable_session_fork")]
6111    #[serde_as(deserialize_as = "DefaultOnError")]
6112    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6113    #[serde(default)]
6114    pub fork: Option<SessionForkCapabilities>,
6115    /// **UNSTABLE**
6116    ///
6117    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6118    ///
6119    /// Whether the agent supports `session/archive` and `session/unarchive`.
6120    ///
6121    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
6122    /// Supplying `{}` means the agent supports both methods, the `archived` filter on
6123    /// `session/list`, and `SessionInfo.archived`.
6124    #[cfg(feature = "unstable_session_archive")]
6125    #[serde_as(deserialize_as = "DefaultOnError")]
6126    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6127    #[serde(default)]
6128    pub archive: Option<SessionArchiveCapabilities>,
6129    /// **UNSTABLE**
6130    ///
6131    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6132    ///
6133    /// Whether the agent supports `session/status`.
6134    ///
6135    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
6136    /// Supplying `{}` means the agent supports checking session status.
6137    #[cfg(feature = "unstable_session_status")]
6138    #[serde_as(deserialize_as = "DefaultOnError")]
6139    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6140    #[serde(default)]
6141    pub status: Option<SessionStatusCapabilities>,
6142    /// **UNSTABLE**
6143    ///
6144    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6145    ///
6146    /// Whether the agent supports `session/options`.
6147    ///
6148    /// Optional. Omitted or `null` both mean the agent does not advertise support.
6149    /// Supplying `{}` means the agent supports `session/options` and accepts initial
6150    /// config option values on session setup requests.
6151    #[cfg(feature = "unstable_session_options")]
6152    #[serde_as(deserialize_as = "DefaultOnError")]
6153    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6154    #[serde(default)]
6155    pub options: Option<SessionOptionsCapabilities>,
6156    /// **UNSTABLE**
6157    ///
6158    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6159    ///
6160    /// Whether the agent supports `session/set_title`.
6161    ///
6162    /// Agents report titles through `session/list` and `session_info_update` without this
6163    /// capability. It only advertises that Clients can set titles.
6164    ///
6165    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
6166    /// Supplying `{}` means the agent supports setting session titles.
6167    #[cfg(feature = "unstable_session_set_title")]
6168    #[serde_as(deserialize_as = "DefaultOnError")]
6169    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6170    #[serde(default)]
6171    pub title: Option<SessionTitleCapabilities>,
6172    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6173    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6174    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6175    ///
6176    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6177    #[serde_as(deserialize_as = "DefaultOnError")]
6178    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6179    #[serde(default)]
6180    #[serde(rename = "_meta")]
6181    pub meta: Option<Meta>,
6182}
6183
6184impl SessionCapabilities {
6185    /// Builds an empty [`SessionCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6186    #[must_use]
6187    pub fn new() -> Self {
6188        Self::default()
6189    }
6190
6191    /// Prompt capabilities supported by the agent in `session/prompt` requests.
6192    ///
6193    /// Omitted and `null` are equivalent and mean the agent does not advertise any prompt
6194    /// extensions beyond the baseline text and resource-link content required by
6195    /// `session/prompt`.
6196    #[must_use]
6197    pub fn prompt(mut self, prompt: impl IntoOption<PromptCapabilities>) -> Self {
6198        self.prompt = prompt.into_option();
6199        self
6200    }
6201
6202    /// MCP capabilities supported by the agent for session lifecycle requests.
6203    ///
6204    /// Omitted and `null` are equivalent and mean the agent does not advertise MCP server
6205    /// transport support for sessions.
6206    #[must_use]
6207    pub fn mcp(mut self, mcp: impl IntoOption<McpCapabilities>) -> Self {
6208        self.mcp = mcp.into_option();
6209        self
6210    }
6211
6212    /// Whether the agent supports `session/delete`.
6213    ///
6214    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
6215    /// Supplying `{}` means the agent supports deleting sessions from `session/list`.
6216    #[must_use]
6217    pub fn delete(mut self, delete: impl IntoOption<SessionDeleteCapabilities>) -> Self {
6218        self.delete = delete.into_option();
6219        self
6220    }
6221
6222    /// Whether the agent supports `additionalDirectories` on supported session lifecycle requests.
6223    ///
6224    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
6225    /// Supplying `{}` means the agent supports `additionalDirectories` on
6226    /// supported session lifecycle requests.
6227    ///
6228    /// Agents may return `SessionInfo.additionalDirectories` to report the
6229    /// complete ordered additional-root list associated with a listed session.
6230    #[must_use]
6231    pub fn additional_directories(
6232        mut self,
6233        additional_directories: impl IntoOption<SessionAdditionalDirectoriesCapabilities>,
6234    ) -> Self {
6235        self.additional_directories = additional_directories.into_option();
6236        self
6237    }
6238
6239    /// Whether the agent supports `systemPrompt` on session lifecycle requests.
6240    ///
6241    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
6242    /// Supplying `{}` means the agent supports `systemPrompt` in `append` mode.
6243    #[must_use]
6244    pub fn system_prompt(
6245        mut self,
6246        system_prompt: impl IntoOption<SessionSystemPromptCapabilities>,
6247    ) -> Self {
6248        self.system_prompt = system_prompt.into_option();
6249        self
6250    }
6251
6252    #[cfg(feature = "unstable_session_fork")]
6253    /// Whether the agent supports `session/fork`.
6254    ///
6255    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
6256    /// Supplying `{}` means the agent supports forking sessions.
6257    #[must_use]
6258    pub fn fork(mut self, fork: impl IntoOption<SessionForkCapabilities>) -> Self {
6259        self.fork = fork.into_option();
6260        self
6261    }
6262
6263    /// **UNSTABLE**
6264    ///
6265    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6266    ///
6267    /// Whether the agent supports `session/archive` and `session/unarchive`.
6268    ///
6269    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
6270    /// Supplying `{}` means the agent supports both methods, the `archived` filter on
6271    /// `session/list`, and `SessionInfo.archived`.
6272    #[cfg(feature = "unstable_session_archive")]
6273    #[must_use]
6274    pub fn archive(mut self, archive: impl IntoOption<SessionArchiveCapabilities>) -> Self {
6275        self.archive = archive.into_option();
6276        self
6277    }
6278
6279    /// **UNSTABLE**
6280    ///
6281    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6282    ///
6283    /// Whether the agent supports `session/status`.
6284    ///
6285    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
6286    /// Supplying `{}` means the agent supports checking session status.
6287    #[cfg(feature = "unstable_session_status")]
6288    #[must_use]
6289    pub fn status(mut self, status: impl IntoOption<SessionStatusCapabilities>) -> Self {
6290        self.status = status.into_option();
6291        self
6292    }
6293
6294    /// **UNSTABLE**
6295    ///
6296    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6297    ///
6298    /// Whether the agent supports `session/options`.
6299    ///
6300    /// Omitted or `null` both mean the agent does not advertise support.
6301    /// Supplying `{}` means the agent supports `session/options` and accepts initial
6302    /// config option values on session setup requests.
6303    #[cfg(feature = "unstable_session_options")]
6304    #[must_use]
6305    pub fn options(mut self, options: impl IntoOption<SessionOptionsCapabilities>) -> Self {
6306        self.options = options.into_option();
6307        self
6308    }
6309
6310    /// **UNSTABLE**
6311    ///
6312    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6313    ///
6314    /// Whether the agent supports `session/set_title`.
6315    ///
6316    /// Agents report titles through `session/list` and `session_info_update` without this
6317    /// capability. It only advertises that Clients can set titles.
6318    ///
6319    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
6320    /// Supplying `{}` means the agent supports setting session titles.
6321    #[cfg(feature = "unstable_session_set_title")]
6322    #[must_use]
6323    pub fn title(mut self, title: impl IntoOption<SessionTitleCapabilities>) -> Self {
6324        self.title = title.into_option();
6325        self
6326    }
6327
6328    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6329    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6330    /// do not recognize.
6331    ///
6332    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6333    #[must_use]
6334    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6335        self.meta = meta.into_option();
6336        self
6337    }
6338}
6339
6340/// Capabilities for the `session/delete` method.
6341///
6342/// Supplying `{}` means the agent supports deleting sessions from `session/list`.
6343#[serde_as]
6344#[skip_serializing_none]
6345#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6346#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6347#[non_exhaustive]
6348pub struct SessionDeleteCapabilities {
6349    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6350    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6351    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6352    ///
6353    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6354    #[serde_as(deserialize_as = "DefaultOnError")]
6355    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6356    #[serde(default)]
6357    #[serde(rename = "_meta")]
6358    pub meta: Option<Meta>,
6359}
6360
6361impl SessionDeleteCapabilities {
6362    /// Builds an empty [`SessionDeleteCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6363    #[must_use]
6364    pub fn new() -> Self {
6365        Self::default()
6366    }
6367
6368    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6369    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6370    /// do not recognize.
6371    ///
6372    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6373    #[must_use]
6374    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6375        self.meta = meta.into_option();
6376        self
6377    }
6378}
6379
6380/// Capabilities for additional session directories support.
6381///
6382/// Supplying `{}` means the agent supports the `additionalDirectories` field on
6383/// supported session lifecycle requests. Agents may return
6384/// `SessionInfo.additionalDirectories` in `session/list` to report the
6385/// complete ordered additional-root list associated with a listed session.
6386#[serde_as]
6387#[skip_serializing_none]
6388#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6389#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6390#[non_exhaustive]
6391pub struct SessionAdditionalDirectoriesCapabilities {
6392    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6393    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6394    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6395    ///
6396    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6397    #[serde_as(deserialize_as = "DefaultOnError")]
6398    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6399    #[serde(default)]
6400    #[serde(rename = "_meta")]
6401    pub meta: Option<Meta>,
6402}
6403
6404impl SessionAdditionalDirectoriesCapabilities {
6405    /// Builds an empty [`SessionAdditionalDirectoriesCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6406    #[must_use]
6407    pub fn new() -> Self {
6408        Self::default()
6409    }
6410
6411    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6412    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6413    /// do not recognize.
6414    ///
6415    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6416    #[must_use]
6417    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6418        self.meta = meta.into_option();
6419        self
6420    }
6421}
6422
6423/// Capabilities for client-provided system prompts.
6424///
6425/// Supplying `{}` means the agent supports `systemPrompt` on session lifecycle
6426/// requests in `append` mode.
6427#[serde_as]
6428#[skip_serializing_none]
6429#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6430#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6431#[serde(rename_all = "camelCase")]
6432#[non_exhaustive]
6433pub struct SessionSystemPromptCapabilities {
6434    /// Delivery modes the agent supports in addition to `append`.
6435    ///
6436    /// Optional. Omitted and `null` are equivalent and mean the agent supports only `append`.
6437    #[serde_as(deserialize_as = "DefaultOnError")]
6438    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6439    #[serde(default)]
6440    pub mode: Option<SessionSystemPromptModeCapabilities>,
6441    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6442    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6443    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6444    ///
6445    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6446    #[serde_as(deserialize_as = "DefaultOnError")]
6447    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6448    #[serde(default)]
6449    #[serde(rename = "_meta")]
6450    pub meta: Option<Meta>,
6451}
6452
6453impl SessionSystemPromptCapabilities {
6454    /// Builds an empty [`SessionSystemPromptCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6455    #[must_use]
6456    pub fn new() -> Self {
6457        Self::default()
6458    }
6459
6460    /// Delivery modes the agent supports in addition to `append`.
6461    ///
6462    /// Omitted and `null` are equivalent and mean the agent supports only `append`.
6463    #[must_use]
6464    pub fn mode(mut self, mode: impl IntoOption<SessionSystemPromptModeCapabilities>) -> Self {
6465        self.mode = mode.into_option();
6466        self
6467    }
6468
6469    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6470    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6471    /// do not recognize.
6472    ///
6473    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6474    #[must_use]
6475    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6476        self.meta = meta.into_option();
6477        self
6478    }
6479}
6480
6481/// System prompt delivery modes the agent supports in addition to `append`.
6482///
6483/// `append` has no entry because every agent advertising `session.systemPrompt`
6484/// supports it.
6485#[serde_as]
6486#[skip_serializing_none]
6487#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6488#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6489#[serde(rename_all = "camelCase")]
6490#[non_exhaustive]
6491pub struct SessionSystemPromptModeCapabilities {
6492    /// Whether the agent supports `override` mode.
6493    ///
6494    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
6495    /// Supplying `{}` means the agent supports replacing its built-in default
6496    /// instructions with the client-provided system prompt.
6497    #[serde_as(deserialize_as = "DefaultOnError")]
6498    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6499    #[serde(default, rename = "override")]
6500    pub override_: Option<SessionSystemPromptOverrideCapabilities>,
6501    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6502    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6503    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6504    ///
6505    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6506    #[serde_as(deserialize_as = "DefaultOnError")]
6507    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6508    #[serde(default)]
6509    #[serde(rename = "_meta")]
6510    pub meta: Option<Meta>,
6511}
6512
6513impl SessionSystemPromptModeCapabilities {
6514    /// Builds an empty [`SessionSystemPromptModeCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6515    #[must_use]
6516    pub fn new() -> Self {
6517        Self::default()
6518    }
6519
6520    /// Whether the agent supports `override` mode.
6521    ///
6522    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
6523    /// Supplying `{}` means the agent supports replacing its built-in default
6524    /// instructions with the client-provided system prompt.
6525    #[must_use]
6526    pub fn override_(
6527        mut self,
6528        override_: impl IntoOption<SessionSystemPromptOverrideCapabilities>,
6529    ) -> Self {
6530        self.override_ = override_.into_option();
6531        self
6532    }
6533
6534    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6535    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6536    /// do not recognize.
6537    ///
6538    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6539    #[must_use]
6540    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6541        self.meta = meta.into_option();
6542        self
6543    }
6544}
6545
6546/// Capabilities for the `override` system prompt mode.
6547///
6548/// Supplying `{}` means the agent supports replacing its built-in default
6549/// instructions with the client-provided system prompt.
6550#[serde_as]
6551#[skip_serializing_none]
6552#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6553#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6554#[non_exhaustive]
6555pub struct SessionSystemPromptOverrideCapabilities {
6556    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6557    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6558    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6559    ///
6560    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6561    #[serde_as(deserialize_as = "DefaultOnError")]
6562    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6563    #[serde(default)]
6564    #[serde(rename = "_meta")]
6565    pub meta: Option<Meta>,
6566}
6567
6568impl SessionSystemPromptOverrideCapabilities {
6569    /// Builds an empty [`SessionSystemPromptOverrideCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6570    #[must_use]
6571    pub fn new() -> Self {
6572        Self::default()
6573    }
6574
6575    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6576    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6577    /// do not recognize.
6578    ///
6579    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6580    #[must_use]
6581    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6582        self.meta = meta.into_option();
6583        self
6584    }
6585}
6586
6587/// **UNSTABLE**
6588///
6589/// This capability is not part of the spec yet, and may be removed or changed at any point.
6590///
6591/// Capabilities for the `session/fork` method.
6592///
6593/// Supplying `{}` means the agent supports forking sessions.
6594#[cfg(feature = "unstable_session_fork")]
6595#[serde_as]
6596#[skip_serializing_none]
6597#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6598#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6599#[non_exhaustive]
6600pub struct SessionForkCapabilities {
6601    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6602    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6603    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6604    ///
6605    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6606    #[serde_as(deserialize_as = "DefaultOnError")]
6607    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6608    #[serde(default)]
6609    #[serde(rename = "_meta")]
6610    pub meta: Option<Meta>,
6611}
6612
6613#[cfg(feature = "unstable_session_fork")]
6614impl SessionForkCapabilities {
6615    /// Builds an empty [`SessionForkCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6616    #[must_use]
6617    pub fn new() -> Self {
6618        Self::default()
6619    }
6620
6621    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6622    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6623    /// do not recognize.
6624    ///
6625    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6626    #[must_use]
6627    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6628        self.meta = meta.into_option();
6629        self
6630    }
6631}
6632
6633/// **UNSTABLE**
6634///
6635/// This capability is not part of the spec yet, and may be removed or changed at any point.
6636///
6637/// Capabilities for `session/archive` and `session/unarchive`.
6638///
6639/// Supplying `{}` means the agent supports both methods, the `archived` filter on
6640/// `session/list`, and `SessionInfo.archived`.
6641#[cfg(feature = "unstable_session_archive")]
6642#[serde_as]
6643#[skip_serializing_none]
6644#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6645#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6646#[non_exhaustive]
6647pub struct SessionArchiveCapabilities {
6648    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6649    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6650    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6651    ///
6652    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6653    #[serde_as(deserialize_as = "DefaultOnError")]
6654    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6655    #[serde(default)]
6656    #[serde(rename = "_meta")]
6657    pub meta: Option<Meta>,
6658}
6659
6660#[cfg(feature = "unstable_session_archive")]
6661impl SessionArchiveCapabilities {
6662    /// Builds an empty [`SessionArchiveCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6663    #[must_use]
6664    pub fn new() -> Self {
6665        Self::default()
6666    }
6667
6668    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6669    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6670    /// do not recognize.
6671    ///
6672    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6673    #[must_use]
6674    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6675        self.meta = meta.into_option();
6676        self
6677    }
6678}
6679
6680/// **UNSTABLE**
6681///
6682/// This capability is not part of the spec yet, and may be removed or changed at any point.
6683///
6684/// Capabilities for the `session/status` method.
6685///
6686/// Supplying `{}` means the agent supports checking session status.
6687#[cfg(feature = "unstable_session_status")]
6688#[serde_as]
6689#[skip_serializing_none]
6690#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6691#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6692#[non_exhaustive]
6693pub struct SessionStatusCapabilities {
6694    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6695    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6696    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6697    ///
6698    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6699    #[serde_as(deserialize_as = "DefaultOnError")]
6700    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6701    #[serde(default)]
6702    #[serde(rename = "_meta")]
6703    pub meta: Option<Meta>,
6704}
6705
6706#[cfg(feature = "unstable_session_status")]
6707impl SessionStatusCapabilities {
6708    /// Builds an empty [`SessionStatusCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6709    #[must_use]
6710    pub fn new() -> Self {
6711        Self::default()
6712    }
6713
6714    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6715    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6716    /// do not recognize.
6717    ///
6718    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6719    #[must_use]
6720    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6721        self.meta = meta.into_option();
6722        self
6723    }
6724}
6725
6726/// **UNSTABLE**
6727///
6728/// This capability is not part of the spec yet, and may be removed or changed at any point.
6729///
6730/// Capabilities for the `session/options` method.
6731///
6732/// Supplying `{}` means the agent supports `session/options` and accepts initial config
6733/// option values on session setup requests.
6734#[cfg(feature = "unstable_session_options")]
6735#[serde_as]
6736#[skip_serializing_none]
6737#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6738#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6739#[non_exhaustive]
6740pub struct SessionOptionsCapabilities {
6741    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6742    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6743    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6744    ///
6745    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6746    #[serde_as(deserialize_as = "DefaultOnError")]
6747    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6748    #[serde(default)]
6749    #[serde(rename = "_meta")]
6750    pub meta: Option<Meta>,
6751}
6752
6753#[cfg(feature = "unstable_session_options")]
6754impl SessionOptionsCapabilities {
6755    /// Builds an empty [`SessionOptionsCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6756    #[must_use]
6757    pub fn new() -> Self {
6758        Self::default()
6759    }
6760
6761    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6762    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6763    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6764    ///
6765    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6766    #[must_use]
6767    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6768        self.meta = meta.into_option();
6769        self
6770    }
6771}
6772
6773/// **UNSTABLE**
6774///
6775/// This capability is not part of the spec yet, and may be removed or changed at any point.
6776///
6777/// Capabilities for Client-set session titles.
6778///
6779/// Supplying `{}` means the agent supports `session/set_title`. Agents report titles
6780/// through `session/list` and `session_info_update` without this capability.
6781#[cfg(feature = "unstable_session_set_title")]
6782#[serde_as]
6783#[skip_serializing_none]
6784#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6785#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6786#[non_exhaustive]
6787pub struct SessionTitleCapabilities {
6788    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6789    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6790    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6791    ///
6792    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6793    #[serde_as(deserialize_as = "DefaultOnError")]
6794    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6795    #[serde(default)]
6796    #[serde(rename = "_meta")]
6797    pub meta: Option<Meta>,
6798}
6799
6800#[cfg(feature = "unstable_session_set_title")]
6801impl SessionTitleCapabilities {
6802    /// Builds an empty [`SessionTitleCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6803    #[must_use]
6804    pub fn new() -> Self {
6805        Self::default()
6806    }
6807
6808    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6809    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6810    /// do not recognize.
6811    ///
6812    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6813    #[must_use]
6814    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6815        self.meta = meta.into_option();
6816        self
6817    }
6818}
6819
6820/// Prompt capabilities supported by the agent in `session/prompt` requests.
6821///
6822/// Baseline agent functionality requires support for `text`
6823/// and `resource_link` content blocks in prompt requests.
6824///
6825/// Other variants must be explicitly opted in to.
6826/// Capabilities for different types of content in prompt requests.
6827///
6828/// Indicates which content types beyond the baseline (text and resource links)
6829/// the agent can process.
6830///
6831/// See protocol docs: [Session Prompt Capabilities](https://agentclientprotocol.com/protocol/v2/initialization#session-prompt-capabilities)
6832#[serde_as]
6833#[skip_serializing_none]
6834#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6835#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6836#[serde(rename_all = "camelCase")]
6837#[non_exhaustive]
6838pub struct PromptCapabilities {
6839    /// Agent supports `image` content blocks.
6840    ///
6841    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
6842    /// Supplying `{}` means the agent supports image content in prompts.
6843    #[serde_as(deserialize_as = "DefaultOnError")]
6844    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6845    #[serde(default)]
6846    pub image: Option<PromptImageCapabilities>,
6847    /// Agent supports `audio` content blocks.
6848    ///
6849    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
6850    /// Supplying `{}` means the agent supports audio content in prompts.
6851    #[serde_as(deserialize_as = "DefaultOnError")]
6852    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6853    #[serde(default)]
6854    pub audio: Option<PromptAudioCapabilities>,
6855    /// Agent supports embedded context in `session/prompt` requests.
6856    ///
6857    /// When enabled, the Client is allowed to include `resource` content blocks
6858    /// in prompt requests for pieces of context that are referenced in the message.
6859    ///
6860    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
6861    /// Supplying `{}` means the agent supports embedded context in prompts.
6862    #[serde_as(deserialize_as = "DefaultOnError")]
6863    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6864    #[serde(default)]
6865    pub embedded_context: Option<PromptEmbeddedContextCapabilities>,
6866    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6867    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6868    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6869    ///
6870    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6871    #[serde_as(deserialize_as = "DefaultOnError")]
6872    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6873    #[serde(default)]
6874    #[serde(rename = "_meta")]
6875    pub meta: Option<Meta>,
6876}
6877
6878impl PromptCapabilities {
6879    /// Builds an empty [`PromptCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6880    #[must_use]
6881    pub fn new() -> Self {
6882        Self::default()
6883    }
6884
6885    /// Agent supports `image` content blocks.
6886    ///
6887    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
6888    /// Supplying `{}` means the agent supports image content in prompts.
6889    #[must_use]
6890    pub fn image(mut self, image: impl IntoOption<PromptImageCapabilities>) -> Self {
6891        self.image = image.into_option();
6892        self
6893    }
6894
6895    /// Agent supports `audio` content blocks.
6896    ///
6897    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
6898    /// Supplying `{}` means the agent supports audio content in prompts.
6899    #[must_use]
6900    pub fn audio(mut self, audio: impl IntoOption<PromptAudioCapabilities>) -> Self {
6901        self.audio = audio.into_option();
6902        self
6903    }
6904
6905    /// Agent supports embedded context in `session/prompt` requests.
6906    ///
6907    /// When enabled, the Client is allowed to include `resource` content blocks
6908    /// in prompt requests for pieces of context that are referenced in the message.
6909    ///
6910    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
6911    /// Supplying `{}` means the agent supports embedded context in prompts.
6912    #[must_use]
6913    pub fn embedded_context(
6914        mut self,
6915        embedded_context: impl IntoOption<PromptEmbeddedContextCapabilities>,
6916    ) -> Self {
6917        self.embedded_context = embedded_context.into_option();
6918        self
6919    }
6920
6921    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6922    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6923    /// do not recognize.
6924    ///
6925    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6926    #[must_use]
6927    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6928        self.meta = meta.into_option();
6929        self
6930    }
6931}
6932
6933/// Capabilities for image content in prompt requests.
6934///
6935/// Supplying `{}` means the agent supports image content in prompts.
6936#[serde_as]
6937#[skip_serializing_none]
6938#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6939#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6940#[non_exhaustive]
6941pub struct PromptImageCapabilities {
6942    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6943    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6944    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6945    ///
6946    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6947    #[serde_as(deserialize_as = "DefaultOnError")]
6948    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6949    #[serde(default)]
6950    #[serde(rename = "_meta")]
6951    pub meta: Option<Meta>,
6952}
6953
6954impl PromptImageCapabilities {
6955    /// Builds an empty [`PromptImageCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6956    #[must_use]
6957    pub fn new() -> Self {
6958        Self::default()
6959    }
6960
6961    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6962    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
6963    /// do not recognize.
6964    ///
6965    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6966    #[must_use]
6967    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6968        self.meta = meta.into_option();
6969        self
6970    }
6971}
6972
6973/// Capabilities for audio content in prompt requests.
6974///
6975/// Supplying `{}` means the agent supports audio content in prompts.
6976#[serde_as]
6977#[skip_serializing_none]
6978#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6979#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6980#[non_exhaustive]
6981pub struct PromptAudioCapabilities {
6982    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6983    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
6984    /// Implementations MUST NOT assign meaning to keys they do not recognize.
6985    ///
6986    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
6987    #[serde_as(deserialize_as = "DefaultOnError")]
6988    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6989    #[serde(default)]
6990    #[serde(rename = "_meta")]
6991    pub meta: Option<Meta>,
6992}
6993
6994impl PromptAudioCapabilities {
6995    /// Builds an empty [`PromptAudioCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6996    #[must_use]
6997    pub fn new() -> Self {
6998        Self::default()
6999    }
7000
7001    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7002    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7003    /// do not recognize.
7004    ///
7005    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7006    #[must_use]
7007    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7008        self.meta = meta.into_option();
7009        self
7010    }
7011}
7012
7013/// Capabilities for embedded context in prompt requests.
7014///
7015/// Supplying `{}` means the agent supports embedded context in prompts.
7016#[serde_as]
7017#[skip_serializing_none]
7018#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7019#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7020#[non_exhaustive]
7021pub struct PromptEmbeddedContextCapabilities {
7022    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7023    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7024    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7025    ///
7026    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7027    #[serde_as(deserialize_as = "DefaultOnError")]
7028    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7029    #[serde(default)]
7030    #[serde(rename = "_meta")]
7031    pub meta: Option<Meta>,
7032}
7033
7034impl PromptEmbeddedContextCapabilities {
7035    /// Builds an empty [`PromptEmbeddedContextCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7036    #[must_use]
7037    pub fn new() -> Self {
7038        Self::default()
7039    }
7040
7041    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7042    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7043    /// do not recognize.
7044    ///
7045    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7046    #[must_use]
7047    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7048        self.meta = meta.into_option();
7049        self
7050    }
7051}
7052
7053/// MCP capabilities supported by the agent for session lifecycle requests.
7054#[serde_as]
7055#[skip_serializing_none]
7056#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7057#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7058#[serde(rename_all = "camelCase")]
7059#[non_exhaustive]
7060pub struct McpCapabilities {
7061    /// Agent supports `stdio` MCP servers.
7062    ///
7063    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
7064    /// Supplying `{}` means the agent supports stdio MCP server transports.
7065    #[serde_as(deserialize_as = "DefaultOnError")]
7066    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7067    #[serde(default)]
7068    pub stdio: Option<McpStdioCapabilities>,
7069    /// Agent supports `http` MCP servers.
7070    ///
7071    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
7072    /// Supplying `{}` means the agent supports HTTP MCP server transports.
7073    #[serde_as(deserialize_as = "DefaultOnError")]
7074    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7075    #[serde(default)]
7076    pub http: Option<McpHttpCapabilities>,
7077    /// **UNSTABLE**
7078    ///
7079    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7080    ///
7081    /// Agent supports `acp` MCP servers.
7082    ///
7083    /// Optional. Omitted and `null` are equivalent and mean the agent does not advertise support.
7084    /// Supplying `{}` means the agent supports ACP MCP server transports.
7085    #[cfg(feature = "unstable_mcp_over_acp")]
7086    #[serde_as(deserialize_as = "DefaultOnError")]
7087    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7088    #[serde(default)]
7089    pub acp: Option<McpAcpCapabilities>,
7090    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7091    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7092    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7093    ///
7094    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7095    #[serde_as(deserialize_as = "DefaultOnError")]
7096    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7097    #[serde(default)]
7098    #[serde(rename = "_meta")]
7099    pub meta: Option<Meta>,
7100}
7101
7102impl McpCapabilities {
7103    /// Builds an empty [`McpCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7104    #[must_use]
7105    pub fn new() -> Self {
7106        Self::default()
7107    }
7108
7109    /// Agent supports `stdio` MCP servers.
7110    ///
7111    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
7112    /// Supplying `{}` means the agent supports stdio MCP server transports.
7113    #[must_use]
7114    pub fn stdio(mut self, stdio: impl IntoOption<McpStdioCapabilities>) -> Self {
7115        self.stdio = stdio.into_option();
7116        self
7117    }
7118
7119    /// Agent supports `http` MCP servers.
7120    ///
7121    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
7122    /// Supplying `{}` means the agent supports HTTP MCP server transports.
7123    #[must_use]
7124    pub fn http(mut self, http: impl IntoOption<McpHttpCapabilities>) -> Self {
7125        self.http = http.into_option();
7126        self
7127    }
7128
7129    /// **UNSTABLE**
7130    ///
7131    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7132    ///
7133    /// Agent supports `acp` MCP servers.
7134    #[cfg(feature = "unstable_mcp_over_acp")]
7135    ///
7136    /// Omitted and `null` are equivalent and mean the agent does not advertise support.
7137    /// Supplying `{}` means the agent supports ACP MCP server transports.
7138    #[must_use]
7139    pub fn acp(mut self, acp: impl IntoOption<McpAcpCapabilities>) -> Self {
7140        self.acp = acp.into_option();
7141        self
7142    }
7143
7144    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7145    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7146    /// do not recognize.
7147    ///
7148    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7149    #[must_use]
7150    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7151        self.meta = meta.into_option();
7152        self
7153    }
7154}
7155
7156/// Capabilities for stdio MCP server transports.
7157///
7158/// Supplying `{}` means the agent supports stdio MCP server transports.
7159#[serde_as]
7160#[skip_serializing_none]
7161#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7162#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7163#[non_exhaustive]
7164pub struct McpStdioCapabilities {
7165    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7166    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7167    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7168    ///
7169    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7170    #[serde_as(deserialize_as = "DefaultOnError")]
7171    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7172    #[serde(default)]
7173    #[serde(rename = "_meta")]
7174    pub meta: Option<Meta>,
7175}
7176
7177impl McpStdioCapabilities {
7178    /// Builds an empty [`McpStdioCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7179    #[must_use]
7180    pub fn new() -> Self {
7181        Self::default()
7182    }
7183
7184    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7185    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7186    /// do not recognize.
7187    ///
7188    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7189    #[must_use]
7190    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7191        self.meta = meta.into_option();
7192        self
7193    }
7194}
7195
7196/// Capabilities for HTTP MCP server transports.
7197///
7198/// Supplying `{}` means the agent supports HTTP MCP server transports.
7199#[serde_as]
7200#[skip_serializing_none]
7201#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7202#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7203#[non_exhaustive]
7204pub struct McpHttpCapabilities {
7205    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7206    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7207    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7208    ///
7209    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7210    #[serde_as(deserialize_as = "DefaultOnError")]
7211    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7212    #[serde(default)]
7213    #[serde(rename = "_meta")]
7214    pub meta: Option<Meta>,
7215}
7216
7217impl McpHttpCapabilities {
7218    /// Builds an empty [`McpHttpCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7219    #[must_use]
7220    pub fn new() -> Self {
7221        Self::default()
7222    }
7223
7224    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7225    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7226    /// do not recognize.
7227    ///
7228    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7229    #[must_use]
7230    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7231        self.meta = meta.into_option();
7232        self
7233    }
7234}
7235
7236/// **UNSTABLE**
7237///
7238/// This capability is not part of the spec yet, and may be removed or changed at any point.
7239///
7240/// Capabilities for ACP MCP server transports.
7241///
7242/// Supplying `{}` means the agent supports ACP MCP server transports.
7243#[cfg(feature = "unstable_mcp_over_acp")]
7244#[serde_as]
7245#[skip_serializing_none]
7246#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7247#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7248#[non_exhaustive]
7249pub struct McpAcpCapabilities {
7250    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7251    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
7252    /// Implementations MUST NOT assign meaning to keys they do not recognize.
7253    ///
7254    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7255    #[serde_as(deserialize_as = "DefaultOnError")]
7256    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7257    #[serde(default)]
7258    #[serde(rename = "_meta")]
7259    pub meta: Option<Meta>,
7260}
7261
7262#[cfg(feature = "unstable_mcp_over_acp")]
7263impl McpAcpCapabilities {
7264    /// Builds an empty [`McpAcpCapabilities`]. Use builder methods to advertise supported sub-capabilities.
7265    #[must_use]
7266    pub fn new() -> Self {
7267        Self::default()
7268    }
7269
7270    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7271    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7272    /// do not recognize.
7273    ///
7274    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7275    #[must_use]
7276    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7277        self.meta = meta.into_option();
7278        self
7279    }
7280}
7281
7282/// Notification to cancel a session's foreground work and its prompts not yet inserted.
7283///
7284/// See protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#cancellation)
7285#[serde_as]
7286#[skip_serializing_none]
7287#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7288#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7289#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CANCEL_METHOD_NAME)))]
7290#[serde(rename_all = "camelCase")]
7291#[non_exhaustive]
7292pub struct CancelSessionNotification {
7293    /// The ID of the session whose foreground work to cancel.
7294    pub session_id: SessionId,
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 CancelSessionNotification {
7308    /// Builds [`CancelSessionNotification`] with the required notification fields set. Optional fields start unset or empty.
7309    #[must_use]
7310    pub fn new(session_id: impl Into<SessionId>) -> Self {
7311        Self {
7312            session_id: session_id.into(),
7313            meta: None,
7314        }
7315    }
7316
7317    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7318    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
7319    /// do not recognize.
7320    ///
7321    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7322    #[must_use]
7323    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7324        self.meta = meta.into_option();
7325        self
7326    }
7327}
7328
7329// Method schema
7330
7331/// Names of all methods that agents handle.
7332///
7333/// Provides a centralized definition of method names used in the protocol.
7334#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7335#[non_exhaustive]
7336pub struct AgentMethodNames {
7337    /// Method for initializing the connection.
7338    pub initialize: &'static str,
7339    /// Method for authenticating with the agent.
7340    pub auth_login: &'static str,
7341    /// Method for listing configurable providers.
7342    #[cfg(feature = "unstable_llm_providers")]
7343    pub providers_list: &'static str,
7344    /// Method for setting provider configuration.
7345    #[cfg(feature = "unstable_llm_providers")]
7346    pub providers_set: &'static str,
7347    /// Method for disabling a provider.
7348    #[cfg(feature = "unstable_llm_providers")]
7349    pub providers_disable: &'static str,
7350    /// Method for creating a new session.
7351    pub session_new: &'static str,
7352    /// Method for setting a configuration option for a session.
7353    pub session_set_config_option: &'static str,
7354    /// Method for sending a prompt to the agent.
7355    pub session_prompt: &'static str,
7356    /// Notification for cancelling operations.
7357    pub session_cancel: &'static str,
7358    /// Method for exchanging MCP-over-ACP messages.
7359    #[cfg(feature = "unstable_mcp_over_acp")]
7360    pub mcp_message: &'static str,
7361    /// Method for listing existing sessions.
7362    pub session_list: &'static str,
7363    /// Method for deleting an existing session.
7364    pub session_delete: &'static str,
7365    /// Method for forking an existing session.
7366    #[cfg(feature = "unstable_session_fork")]
7367    pub session_fork: &'static str,
7368    /// Method for archiving a session.
7369    #[cfg(feature = "unstable_session_archive")]
7370    pub session_archive: &'static str,
7371    /// Method for unarchiving a session.
7372    #[cfg(feature = "unstable_session_archive")]
7373    pub session_unarchive: &'static str,
7374    /// Method for checking the status of a session.
7375    #[cfg(feature = "unstable_session_status")]
7376    pub session_status: &'static str,
7377    /// Method for querying the config options a session would start with.
7378    #[cfg(feature = "unstable_session_options")]
7379    pub session_options: &'static str,
7380    /// Method for setting the title of a session.
7381    #[cfg(feature = "unstable_session_set_title")]
7382    pub session_set_title: &'static str,
7383    /// Method for resuming an existing session.
7384    pub session_resume: &'static str,
7385    /// Method for closing an active session.
7386    pub session_close: &'static str,
7387    /// Method for cancelling one tool call.
7388    pub tool_call_cancel: &'static str,
7389    /// Method for cancelling one terminal's process.
7390    pub terminal_cancel: &'static str,
7391    /// Method for logging out of an authenticated session.
7392    pub auth_logout: &'static str,
7393    /// Method for querying the agent's authentication state.
7394    #[cfg(feature = "unstable_auth_status")]
7395    pub auth_status: &'static str,
7396}
7397
7398/// Constant containing all agent method names.
7399pub const AGENT_METHOD_NAMES: AgentMethodNames = AgentMethodNames {
7400    initialize: INITIALIZE_METHOD_NAME,
7401    auth_login: AUTH_LOGIN_METHOD_NAME,
7402    #[cfg(feature = "unstable_llm_providers")]
7403    providers_list: PROVIDERS_LIST_METHOD_NAME,
7404    #[cfg(feature = "unstable_llm_providers")]
7405    providers_set: PROVIDERS_SET_METHOD_NAME,
7406    #[cfg(feature = "unstable_llm_providers")]
7407    providers_disable: PROVIDERS_DISABLE_METHOD_NAME,
7408    session_new: SESSION_NEW_METHOD_NAME,
7409    session_set_config_option: SESSION_SET_CONFIG_OPTION_METHOD_NAME,
7410    session_prompt: SESSION_PROMPT_METHOD_NAME,
7411    session_cancel: SESSION_CANCEL_METHOD_NAME,
7412    #[cfg(feature = "unstable_mcp_over_acp")]
7413    mcp_message: MCP_MESSAGE_METHOD_NAME,
7414    session_list: SESSION_LIST_METHOD_NAME,
7415    session_delete: SESSION_DELETE_METHOD_NAME,
7416    #[cfg(feature = "unstable_session_fork")]
7417    session_fork: SESSION_FORK_METHOD_NAME,
7418    #[cfg(feature = "unstable_session_archive")]
7419    session_archive: SESSION_ARCHIVE_METHOD_NAME,
7420    #[cfg(feature = "unstable_session_archive")]
7421    session_unarchive: SESSION_UNARCHIVE_METHOD_NAME,
7422    #[cfg(feature = "unstable_session_status")]
7423    session_status: SESSION_STATUS_METHOD_NAME,
7424    #[cfg(feature = "unstable_session_options")]
7425    session_options: SESSION_OPTIONS_METHOD_NAME,
7426    #[cfg(feature = "unstable_session_set_title")]
7427    session_set_title: SESSION_SET_TITLE_METHOD_NAME,
7428    session_resume: SESSION_RESUME_METHOD_NAME,
7429    session_close: SESSION_CLOSE_METHOD_NAME,
7430    tool_call_cancel: TOOL_CALL_CANCEL_METHOD_NAME,
7431    terminal_cancel: TERMINAL_CANCEL_METHOD_NAME,
7432    auth_logout: AUTH_LOGOUT_METHOD_NAME,
7433    #[cfg(feature = "unstable_auth_status")]
7434    auth_status: AUTH_STATUS_METHOD_NAME,
7435};
7436
7437/// Method name for the initialize request.
7438pub(crate) const INITIALIZE_METHOD_NAME: &str = "initialize";
7439/// Method name for the `auth/login` request.
7440pub(crate) const AUTH_LOGIN_METHOD_NAME: &str = "auth/login";
7441/// Method name for listing configurable providers.
7442#[cfg(feature = "unstable_llm_providers")]
7443pub(crate) const PROVIDERS_LIST_METHOD_NAME: &str = "providers/list";
7444/// Method name for setting provider configuration.
7445#[cfg(feature = "unstable_llm_providers")]
7446pub(crate) const PROVIDERS_SET_METHOD_NAME: &str = "providers/set";
7447/// Method name for disabling a provider.
7448#[cfg(feature = "unstable_llm_providers")]
7449pub(crate) const PROVIDERS_DISABLE_METHOD_NAME: &str = "providers/disable";
7450/// Method name for creating a new session.
7451pub(crate) const SESSION_NEW_METHOD_NAME: &str = "session/new";
7452/// Method name for setting a configuration option for a session.
7453pub(crate) const SESSION_SET_CONFIG_OPTION_METHOD_NAME: &str = "session/set_config_option";
7454/// Method name for sending a prompt.
7455pub(crate) const SESSION_PROMPT_METHOD_NAME: &str = "session/prompt";
7456/// Method name for the cancel notification.
7457pub(crate) const SESSION_CANCEL_METHOD_NAME: &str = "session/cancel";
7458/// Method name for listing existing sessions.
7459pub(crate) const SESSION_LIST_METHOD_NAME: &str = "session/list";
7460/// Method name for deleting an existing session.
7461pub(crate) const SESSION_DELETE_METHOD_NAME: &str = "session/delete";
7462/// Method name for forking an existing session.
7463#[cfg(feature = "unstable_session_fork")]
7464pub(crate) const SESSION_FORK_METHOD_NAME: &str = "session/fork";
7465/// Method name for archiving a session.
7466#[cfg(feature = "unstable_session_archive")]
7467pub(crate) const SESSION_ARCHIVE_METHOD_NAME: &str = "session/archive";
7468/// Method name for unarchiving a session.
7469#[cfg(feature = "unstable_session_archive")]
7470pub(crate) const SESSION_UNARCHIVE_METHOD_NAME: &str = "session/unarchive";
7471/// Method name for checking the status of a session.
7472#[cfg(feature = "unstable_session_status")]
7473pub(crate) const SESSION_STATUS_METHOD_NAME: &str = "session/status";
7474/// Method name for querying the config options a session would start with.
7475#[cfg(feature = "unstable_session_options")]
7476pub(crate) const SESSION_OPTIONS_METHOD_NAME: &str = "session/options";
7477/// Method name for setting the title of a session.
7478#[cfg(feature = "unstable_session_set_title")]
7479pub(crate) const SESSION_SET_TITLE_METHOD_NAME: &str = "session/set_title";
7480/// Method name for resuming an existing session.
7481pub(crate) const SESSION_RESUME_METHOD_NAME: &str = "session/resume";
7482/// Method name for closing an active session.
7483pub(crate) const SESSION_CLOSE_METHOD_NAME: &str = "session/close";
7484/// Method name for cancelling one tool call.
7485pub(crate) const TOOL_CALL_CANCEL_METHOD_NAME: &str = "tool_call/cancel";
7486/// Method name for cancelling one terminal's process.
7487pub(crate) const TERMINAL_CANCEL_METHOD_NAME: &str = "terminal/cancel";
7488/// Method name for the `auth/logout` request.
7489pub(crate) const AUTH_LOGOUT_METHOD_NAME: &str = "auth/logout";
7490/// Method name for the `auth/status` request.
7491#[cfg(feature = "unstable_auth_status")]
7492pub(crate) const AUTH_STATUS_METHOD_NAME: &str = "auth/status";
7493
7494/// All possible requests that a client can send to an agent.
7495///
7496/// This enum is used internally for routing RPC requests. You typically won't need
7497/// to use this directly.
7498///
7499/// This enum encompasses all method calls from client to agent.
7500#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7501#[derive(Clone, Debug, Serialize, Deserialize)]
7502#[serde(untagged)]
7503#[cfg_attr(feature = "schemars", schemars(inline))]
7504#[non_exhaustive]
7505pub enum ClientRequest {
7506    /// Establishes the connection with a client and negotiates protocol capabilities.
7507    ///
7508    /// This method is called at the beginning of the connection, before any other request, to:
7509    /// - Negotiate the protocol version to use
7510    /// - Exchange capability information between client and agent
7511    /// - Determine available authentication methods
7512    ///
7513    /// The Client may repeat it before its first other request. The latest successful
7514    /// `initialize` is authoritative.
7515    ///
7516    /// The agent should respond with its supported protocol version and capabilities.
7517    ///
7518    /// See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/v2/initialization)
7519    InitializeRequest(Box<InitializeRequest>),
7520    /// Authenticates the client using the specified authentication method.
7521    ///
7522    /// Agents MUST support this method when their `initialize` response included
7523    /// a non-empty `authMethods` list. Clients MUST call this method only
7524    /// with a method whose type defines a protocol-driven login flow, and MUST NOT
7525    /// call it when `authMethods` was omitted or empty.
7526    ///
7527    /// Called when the agent requires authentication before allowing session creation.
7528    /// The client provides the authentication method ID that was advertised during initialization.
7529    ///
7530    /// After successful authentication, the client can proceed to create sessions with
7531    /// `session/new` without receiving an `auth_required` (`-32000`) error.
7532    ///
7533    /// See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/v2/initialization)
7534    LoginAuthRequest(Box<LoginAuthRequest>),
7535    /// **UNSTABLE**
7536    ///
7537    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7538    ///
7539    /// Lists providers that can be configured by the client.
7540    #[cfg(feature = "unstable_llm_providers")]
7541    ListProvidersRequest(Box<ListProvidersRequest>),
7542    /// **UNSTABLE**
7543    ///
7544    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7545    ///
7546    /// Replaces the configuration for a provider.
7547    #[cfg(feature = "unstable_llm_providers")]
7548    SetProviderRequest(Box<SetProviderRequest>),
7549    /// **UNSTABLE**
7550    ///
7551    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7552    ///
7553    /// Disables a provider.
7554    #[cfg(feature = "unstable_llm_providers")]
7555    DisableProviderRequest(Box<DisableProviderRequest>),
7556    /// Logs out of the current authenticated state.
7557    ///
7558    /// Agents MUST support this method when their `initialize` response included
7559    /// a non-empty `authMethods` list. Clients MUST NOT call this method
7560    /// when `authMethods` was omitted or empty.
7561    ///
7562    /// After a successful logout, authentication-gated requests require the
7563    /// client to complete an advertised authentication flow again. There is no
7564    /// guarantee about the behavior of already running sessions.
7565    LogoutAuthRequest(Box<LogoutAuthRequest>),
7566    /// **UNSTABLE**
7567    ///
7568    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7569    ///
7570    /// Queries the agent's current authentication state.
7571    ///
7572    /// This method is only available if the agent advertises the `auth.status` capability.
7573    /// It MUST NOT change any agent state, and agents MUST NOT reject it with `auth_required`.
7574    #[cfg(feature = "unstable_auth_status")]
7575    AuthStatusRequest(Box<AuthStatusRequest>),
7576    /// Creates a new conversation session with the agent.
7577    ///
7578    /// Sessions represent independent conversation contexts with their own history and state.
7579    ///
7580    /// The agent should:
7581    /// - Create a new session context
7582    /// - Connect to any specified MCP servers
7583    /// - Return a unique session ID for future requests
7584    ///
7585    /// May return an `auth_required` (`-32000`) error if the agent requires authentication.
7586    ///
7587    /// See protocol docs: [Session Setup](https://agentclientprotocol.com/protocol/v2/session-setup)
7588    NewSessionRequest(Box<NewSessionRequest>),
7589    /// Lists existing sessions known to the agent.
7590    ///
7591    /// The agent should return metadata about sessions with optional filtering and pagination support.
7592    ListSessionsRequest(Box<ListSessionsRequest>),
7593    /// Deletes an existing session from `session/list`.
7594    ///
7595    /// This method is only available if the agent advertises the `session.delete` capability.
7596    DeleteSessionRequest(Box<DeleteSessionRequest>),
7597    #[cfg(feature = "unstable_session_fork")]
7598    /// **UNSTABLE**
7599    ///
7600    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7601    ///
7602    /// Forks an existing session to create a new independent session.
7603    ///
7604    /// This method is only available if the agent advertises the `session.fork` capability.
7605    ///
7606    /// The agent should create a new session with the same conversation context as the
7607    /// original, allowing operations like generating summaries without affecting the
7608    /// original session's history.
7609    ///
7610    /// As with `session/new`, the forked session is active once the agent responds,
7611    /// set up with the request's `cwd`, `additionalDirectories`, and `mcpServers`.
7612    /// The client can prompt it without calling `session/resume` first.
7613    ForkSessionRequest(Box<ForkSessionRequest>),
7614    #[cfg(feature = "unstable_session_archive")]
7615    /// **UNSTABLE**
7616    ///
7617    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7618    ///
7619    /// Archives a session, hiding it from default `session/list` results.
7620    ///
7621    /// This method is only available if the agent advertises the `session.archive` capability.
7622    ArchiveSessionRequest(Box<ArchiveSessionRequest>),
7623    #[cfg(feature = "unstable_session_archive")]
7624    /// **UNSTABLE**
7625    ///
7626    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7627    ///
7628    /// Unarchives a session, returning it to default `session/list` results.
7629    ///
7630    /// This method is only available if the agent advertises the `session.archive` capability.
7631    UnarchiveSessionRequest(Box<UnarchiveSessionRequest>),
7632    #[cfg(feature = "unstable_session_status")]
7633    /// **UNSTABLE**
7634    ///
7635    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7636    ///
7637    /// Checks whether the Agent has a session in memory, without changing it.
7638    ///
7639    /// This method is only available if the agent advertises the `session.status` capability.
7640    SessionStatusRequest(Box<SessionStatusRequest>),
7641    #[cfg(feature = "unstable_session_options")]
7642    /// **UNSTABLE**
7643    ///
7644    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7645    ///
7646    /// Returns the config options a session would start with, without creating or resuming a session.
7647    ///
7648    /// This method is only available if the agent advertises the `session.options` capability.
7649    SessionOptionsRequest(Box<SessionOptionsRequest>),
7650    #[cfg(feature = "unstable_session_set_title")]
7651    /// **UNSTABLE**
7652    ///
7653    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7654    ///
7655    /// Sets the title of a session.
7656    ///
7657    /// This method is only available if the agent advertises the `session.title` capability.
7658    ///
7659    /// The session does not need to be active on the connection. The agent stores the
7660    /// title and returns the stored title, which may be normalized.
7661    SetSessionTitleRequest(Box<SetSessionTitleRequest>),
7662    /// Resumes an existing session.
7663    ///
7664    /// The agent should resume the session context, allowing the conversation
7665    /// to continue. If `replayFrom` is set, the agent should replay
7666    /// retained conversation history before responding.
7667    ResumeSessionRequest(Box<ResumeSessionRequest>),
7668    /// Closes an active session and frees up any resources associated with it.
7669    ///
7670    /// The Agent MUST cancel any ongoing work as if `session/cancel` was called, stop the
7671    /// session's background work, and then free the resources associated with the session.
7672    CloseSessionRequest(Box<CloseSessionRequest>),
7673    /// Cancels one tool call without cancelling the rest of the session's work.
7674    ///
7675    /// This method is only available while the tool call advertises `capabilities.cancel`.
7676    /// The response means the Agent accepted the cancellation. A final `tool_call_update`
7677    /// confirms it.
7678    CancelToolCallRequest(Box<CancelToolCallRequest>),
7679    /// Stops one terminal's process without cancelling the rest of the session's work.
7680    ///
7681    /// This method is only available while the terminal advertises `capabilities.cancel`.
7682    /// The response means the Agent accepted the cancellation. A `terminal_update` with
7683    /// `exitStatus` confirms it.
7684    CancelTerminalRequest(Box<CancelTerminalRequest>),
7685    /// Sets the current value for a session configuration option.
7686    SetSessionConfigOptionRequest(Box<SetSessionConfigOptionRequest>),
7687    /// Processes a user prompt within a session.
7688    ///
7689    /// Acceptance means adding a logical user message with an ID and a position
7690    /// relative to other messages in the ACP conversation, not receipt or queueing.
7691    /// The Agent MUST return the inserted message's ID without waiting for
7692    /// processing to finish.
7693    ///
7694    /// The Agent reports the user message with the same ID through `session/update`.
7695    /// This notification may arrive before or after the response, but neither may
7696    /// precede insertion. Processing state, output, tool calls, and completion are
7697    /// also reported through session updates.
7698    ///
7699    /// An error response means the user message was not inserted. Once it is
7700    /// inserted, the Agent MUST NOT answer with an error, even if the work fails
7701    /// before the response is sent. It ends that work with the `error` stop reason.
7702    ///
7703    /// A rejected submission produces no user-message updates. Foreground state
7704    /// follows its normal lifecycle independently of the request outcome:
7705    /// `running` may precede insertion, and rejection alone does not imply `idle`.
7706    ///
7707    /// See protocol docs: [Prompt Lifecycle](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle)
7708    PromptRequest(Box<PromptRequest>),
7709    /// Handles extension method requests from the client.
7710    ///
7711    /// Extension methods provide a way to add custom functionality while maintaining
7712    /// protocol compatibility.
7713    ///
7714    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7715    ExtMethodRequest(Box<ExtRequest>),
7716}
7717
7718impl ClientRequest {
7719    /// Returns the corresponding method name of the request.
7720    #[must_use]
7721    pub fn method(&self) -> &str {
7722        match self {
7723            Self::InitializeRequest(_) => AGENT_METHOD_NAMES.initialize,
7724            Self::LoginAuthRequest(_) => AGENT_METHOD_NAMES.auth_login,
7725            #[cfg(feature = "unstable_llm_providers")]
7726            Self::ListProvidersRequest(_) => AGENT_METHOD_NAMES.providers_list,
7727            #[cfg(feature = "unstable_llm_providers")]
7728            Self::SetProviderRequest(_) => AGENT_METHOD_NAMES.providers_set,
7729            #[cfg(feature = "unstable_llm_providers")]
7730            Self::DisableProviderRequest(_) => AGENT_METHOD_NAMES.providers_disable,
7731            Self::LogoutAuthRequest(_) => AGENT_METHOD_NAMES.auth_logout,
7732            #[cfg(feature = "unstable_auth_status")]
7733            Self::AuthStatusRequest(_) => AGENT_METHOD_NAMES.auth_status,
7734            Self::NewSessionRequest(_) => AGENT_METHOD_NAMES.session_new,
7735            Self::ListSessionsRequest(_) => AGENT_METHOD_NAMES.session_list,
7736            Self::DeleteSessionRequest(_) => AGENT_METHOD_NAMES.session_delete,
7737            #[cfg(feature = "unstable_session_fork")]
7738            Self::ForkSessionRequest(_) => AGENT_METHOD_NAMES.session_fork,
7739            #[cfg(feature = "unstable_session_archive")]
7740            Self::ArchiveSessionRequest(_) => AGENT_METHOD_NAMES.session_archive,
7741            #[cfg(feature = "unstable_session_archive")]
7742            Self::UnarchiveSessionRequest(_) => AGENT_METHOD_NAMES.session_unarchive,
7743            #[cfg(feature = "unstable_session_status")]
7744            Self::SessionStatusRequest(_) => AGENT_METHOD_NAMES.session_status,
7745            #[cfg(feature = "unstable_session_options")]
7746            Self::SessionOptionsRequest(_) => AGENT_METHOD_NAMES.session_options,
7747            #[cfg(feature = "unstable_session_set_title")]
7748            Self::SetSessionTitleRequest(_) => AGENT_METHOD_NAMES.session_set_title,
7749            Self::ResumeSessionRequest(_) => AGENT_METHOD_NAMES.session_resume,
7750            Self::CloseSessionRequest(_) => AGENT_METHOD_NAMES.session_close,
7751            Self::CancelToolCallRequest(_) => AGENT_METHOD_NAMES.tool_call_cancel,
7752            Self::CancelTerminalRequest(_) => AGENT_METHOD_NAMES.terminal_cancel,
7753            Self::SetSessionConfigOptionRequest(_) => AGENT_METHOD_NAMES.session_set_config_option,
7754            Self::PromptRequest(_) => AGENT_METHOD_NAMES.session_prompt,
7755            Self::ExtMethodRequest(ext_request) => &ext_request.method,
7756        }
7757    }
7758}
7759
7760/// All possible responses that an agent can send to a client.
7761///
7762/// This enum is used internally for routing RPC responses. You typically won't need
7763/// to use this directly - the responses are handled automatically by the connection.
7764///
7765/// These are responses to the corresponding `ClientRequest` variants.
7766#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7767#[derive(Clone, Debug, Serialize, Deserialize)]
7768#[serde(untagged)]
7769#[cfg_attr(feature = "schemars", schemars(inline))]
7770#[non_exhaustive]
7771pub enum AgentResponse {
7772    /// Successful result returned for a `initialize` request.
7773    InitializeResponse(Box<InitializeResponse>),
7774    /// Successful result returned for an `auth/login` request.
7775    LoginAuthResponse(#[serde(default)] Box<LoginAuthResponse>),
7776    /// Successful result returned for a `providers/list` request.
7777    #[cfg(feature = "unstable_llm_providers")]
7778    ListProvidersResponse(Box<ListProvidersResponse>),
7779    /// Successful result returned for a `providers/set` request.
7780    #[cfg(feature = "unstable_llm_providers")]
7781    SetProviderResponse(#[serde(default)] Box<SetProviderResponse>),
7782    /// Successful result returned for a `providers/disable` request.
7783    #[cfg(feature = "unstable_llm_providers")]
7784    DisableProviderResponse(#[serde(default)] Box<DisableProviderResponse>),
7785    /// Successful result returned for an `auth/logout` request.
7786    LogoutAuthResponse(#[serde(default)] Box<LogoutAuthResponse>),
7787    /// Successful result returned for an `auth/status` request.
7788    #[cfg(feature = "unstable_auth_status")]
7789    AuthStatusResponse(Box<AuthStatusResponse>),
7790    /// Successful result returned for a `session/new` request.
7791    NewSessionResponse(Box<NewSessionResponse>),
7792    /// Successful result returned for a `session/list` request.
7793    ListSessionsResponse(Box<ListSessionsResponse>),
7794    /// Successful result returned for a `session/delete` request.
7795    DeleteSessionResponse(#[serde(default)] Box<DeleteSessionResponse>),
7796    /// Successful result returned for a `session/fork` request.
7797    #[cfg(feature = "unstable_session_fork")]
7798    ForkSessionResponse(Box<ForkSessionResponse>),
7799    /// Successful result returned for a `session/archive` request.
7800    #[cfg(feature = "unstable_session_archive")]
7801    ArchiveSessionResponse(#[serde(default)] Box<ArchiveSessionResponse>),
7802    /// Successful result returned for a `session/unarchive` request.
7803    #[cfg(feature = "unstable_session_archive")]
7804    UnarchiveSessionResponse(#[serde(default)] Box<UnarchiveSessionResponse>),
7805    /// Successful result returned for a `session/status` request.
7806    #[cfg(feature = "unstable_session_status")]
7807    SessionStatusResponse(Box<SessionStatusResponse>),
7808    /// Successful result returned for a `session/options` request.
7809    #[cfg(feature = "unstable_session_options")]
7810    SessionOptionsResponse(#[serde(default)] Box<SessionOptionsResponse>),
7811    /// Successful result returned for a `session/set_title` request.
7812    #[cfg(feature = "unstable_session_set_title")]
7813    SetSessionTitleResponse(Box<SetSessionTitleResponse>),
7814    /// Successful result returned for a `session/resume` request.
7815    ResumeSessionResponse(#[serde(default)] Box<ResumeSessionResponse>),
7816    /// Successful result returned for a `session/close` request.
7817    CloseSessionResponse(#[serde(default)] Box<CloseSessionResponse>),
7818    /// Successful result returned for a `tool_call/cancel` request.
7819    CancelToolCallResponse(#[serde(default)] Box<CancelToolCallResponse>),
7820    /// Successful result returned for a `terminal/cancel` request.
7821    CancelTerminalResponse(#[serde(default)] Box<CancelTerminalResponse>),
7822    /// Successful result returned for a `session/set_config_option` request.
7823    SetSessionConfigOptionResponse(Box<SetSessionConfigOptionResponse>),
7824    /// Successful result returned for a `session/prompt` request.
7825    PromptResponse(Box<PromptResponse>),
7826    /// Successful result returned by an extension method outside the core ACP method set.
7827    ExtMethodResponse(Box<ExtResponse>),
7828}
7829
7830/// All possible notifications that a client can send to an agent.
7831///
7832/// This enum is used internally for routing RPC notifications. You typically won't need
7833/// to use this directly.
7834///
7835/// Notifications do not expect a response.
7836#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7837#[derive(Clone, Debug, Serialize, Deserialize)]
7838#[serde(untagged)]
7839#[cfg_attr(feature = "schemars", schemars(inline))]
7840#[non_exhaustive]
7841pub enum ClientNotification {
7842    /// Cancels a session's foreground work and its prompts not yet inserted.
7843    ///
7844    /// Work in the latest `background` list is not covered and keeps running. The
7845    /// Agent MAY stop background activity it does not list.
7846    ///
7847    /// Upon receiving this notification, the Agent SHOULD stop all language model
7848    /// requests and all tool call invocations of the cancelled foreground work as soon
7849    /// as possible.
7850    ///
7851    /// The Agent MUST stop waiting for pending `session/request_permission` requests of
7852    /// the cancelled work and treat them as not approved. It SHOULD cancel each of them
7853    /// with `$/cancel_request`.
7854    ///
7855    /// After all ongoing operations have been successfully aborted and pending
7856    /// updates have been sent, the Agent MUST send an idle `state_update` session
7857    /// update with the `cancelled` stop reason if cancellation ended active
7858    /// foreground work. No additional completion update is required if no
7859    /// foreground work was active.
7860    ///
7861    /// After cancellation completes, the Agent SHOULD ignore late answers rather
7862    /// than use them to resume the cancelled work.
7863    ///
7864    /// Agents MUST catch errors caused by aborting cancelled work and report the
7865    /// `cancelled` stop reason, not `error`.
7866    ///
7867    /// The Agent MAY send content or tool call updates after receiving
7868    /// `session/cancel`, but MUST send them before the idle `state_update` that
7869    /// reports cancellation.
7870    ///
7871    /// See protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle#cancellation)
7872    CancelSessionNotification(Box<CancelSessionNotification>),
7873    /// **UNSTABLE**
7874    ///
7875    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7876    ///
7877    /// Sends an MCP-over-ACP notification.
7878    #[cfg(feature = "unstable_mcp_over_acp")]
7879    MessageMcpNotification(Box<MessageMcpNotification>),
7880    /// Handles extension notifications from the client.
7881    ///
7882    /// Extension notifications provide a way to send one-way messages for custom functionality
7883    /// while maintaining protocol compatibility.
7884    ///
7885    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
7886    ExtNotification(Box<ExtNotification>),
7887}
7888
7889impl ClientNotification {
7890    /// Returns the corresponding method name of the notification.
7891    #[must_use]
7892    pub fn method(&self) -> &str {
7893        match self {
7894            Self::CancelSessionNotification(_) => AGENT_METHOD_NAMES.session_cancel,
7895            #[cfg(feature = "unstable_mcp_over_acp")]
7896            Self::MessageMcpNotification(_) => AGENT_METHOD_NAMES.mcp_message,
7897            Self::ExtNotification(ext_notification) => &ext_notification.method,
7898        }
7899    }
7900}
7901
7902#[cfg(test)]
7903mod test_serialization {
7904    use std::path::PathBuf;
7905
7906    use super::*;
7907    use serde_json::json;
7908
7909    fn test_meta() -> Meta {
7910        json!({ "source": "test" }).as_object().unwrap().clone()
7911    }
7912
7913    #[test]
7914    fn list_sessions_cursor_and_session_directories_are_strict() {
7915        for cursor in [json!(null), json!("next")] {
7916            let response = json!({ "sessions": [], "nextCursor": cursor });
7917            serde_json::from_value::<ListSessionsResponse>(response).unwrap();
7918        }
7919        let malformed = json!({ "sessions": [], "nextCursor": 42 });
7920        assert!(serde_json::from_value::<ListSessionsResponse>(malformed).is_err());
7921
7922        let session = |dirs: serde_json::Value| json!({ "sessionId": "s", "cwd": "/w", "additionalDirectories": dirs });
7923        let info: SessionInfo = serde_json::from_value(session(json!(null))).unwrap();
7924        assert_eq!(info.additional_directories, Vec::<AbsolutePath>::new());
7925        for bad in [json!(["/a", 42]), json!("/a")] {
7926            assert!(serde_json::from_value::<SessionInfo>(session(bad)).is_err());
7927        }
7928        // A session with malformed directories is skipped, not truncated.
7929        let response = json!({ "sessions": [session(json!(["/a", 42]))] });
7930        let response: ListSessionsResponse = serde_json::from_value(response).unwrap();
7931        assert_eq!(response.sessions, Vec::<SessionInfo>::new());
7932    }
7933
7934    #[test]
7935    fn other_fallbacks_preserve_optional_fields_verbatim() {
7936        let valid = json!({ "type": "_custom", "methodId": "m", "name": "M",
7937            "description": "d", "_meta": { "k": 1 } });
7938        let method: AuthMethod = serde_json::from_value(valid.clone()).unwrap();
7939        assert_eq!(method.description(), Some("d"));
7940        assert_eq!(
7941            method.meta(),
7942            Some(&json!({ "k": 1 }).as_object().unwrap().clone())
7943        );
7944        assert_eq!(serde_json::to_value(&method).unwrap(), valid);
7945
7946        // Malformed optional fields are kept as sent and read as absent.
7947        let malformed = json!({ "type": "_custom", "methodId": "m", "name": "M",
7948            "description": 42, "_meta": "bad", "extra": true });
7949        let method: AuthMethod = serde_json::from_value(malformed.clone()).unwrap();
7950        assert_eq!(method.description(), None);
7951        assert_eq!(method.meta(), None);
7952        assert_eq!(serde_json::to_value(&method).unwrap(), malformed);
7953
7954        let replay = json!({ "type": "_custom", "_meta": "bad", "cursor": 3 });
7955        let decoded: ReplayFrom = serde_json::from_value(replay.clone()).unwrap();
7956        assert_eq!(serde_json::to_value(&decoded).unwrap(), replay);
7957    }
7958
7959    fn serialized_meta_key_count(value: &impl serde::Serialize) -> usize {
7960        serde_json::to_string(value)
7961            .unwrap()
7962            .matches("\"_meta\"")
7963            .count()
7964    }
7965
7966    #[test]
7967    fn prompt_response_without_metadata_round_trips() {
7968        let response = PromptResponse::new(MessageId::new("message-1"));
7969        let serialized = serde_json::to_value(&response).unwrap();
7970        assert_eq!(serialized, json!({ "messageId": "message-1" }));
7971        assert_eq!(
7972            serde_json::from_value::<PromptResponse>(serialized).unwrap(),
7973            response
7974        );
7975        assert_eq!(
7976            serde_json::from_value::<PromptResponse>(json!({
7977                "messageId": "message-1",
7978                "_meta": null
7979            }))
7980            .unwrap(),
7981            response
7982        );
7983    }
7984
7985    #[test]
7986    fn prompt_response_requires_message_id_and_preserves_metadata_tolerance() {
7987        let response = PromptResponse::new("message-1").meta(test_meta());
7988        let serialized = serde_json::to_value(&response).unwrap();
7989        assert_eq!(
7990            serialized,
7991            json!({
7992                "messageId": "message-1",
7993                "_meta": { "source": "test" }
7994            })
7995        );
7996
7997        let deserialized: PromptResponse = serde_json::from_value(serialized).unwrap();
7998        assert_eq!(deserialized.message_id, MessageId::new("message-1"));
7999        assert_eq!(deserialized.meta, Some(test_meta()));
8000
8001        let malformed_meta: PromptResponse = serde_json::from_value(json!({
8002            "messageId": "message-2",
8003            "_meta": false
8004        }))
8005        .unwrap();
8006        assert_eq!(malformed_meta.message_id, MessageId::new("message-2"));
8007        assert_eq!(malformed_meta.meta, None);
8008
8009        for invalid in [
8010            json!({}),
8011            json!({ "messageId": null }),
8012            json!({ "messageId": 1 }),
8013            json!({ "messageId": false }),
8014            json!({ "messageId": {} }),
8015            json!({ "messageId": [] }),
8016        ] {
8017            assert!(
8018                serde_json::from_value::<PromptResponse>(invalid).is_err(),
8019                "missing, null, and non-string message IDs must be rejected"
8020            );
8021        }
8022    }
8023
8024    #[cfg(feature = "schemars")]
8025    #[test]
8026    fn prompt_response_schema_requires_non_null_string_message_id_reference() {
8027        let schema = serde_json::to_value(schemars::schema_for!(PromptResponse)).unwrap();
8028
8029        assert_eq!(schema["required"], json!(["messageId"]));
8030        assert_eq!(
8031            schema["properties"]["messageId"]["$ref"],
8032            "#/$defs/MessageId"
8033        );
8034        assert_eq!(schema["$defs"]["MessageId"]["type"], "string");
8035    }
8036
8037    #[test]
8038    fn test_initialize_capabilities_default_on_malformed_values() {
8039        let request: InitializeRequest = serde_json::from_value(json!({
8040            "protocolVersion": 2,
8041            "capabilities": false,
8042            "info": {
8043                "name": "client",
8044                "version": "1.0.0"
8045            }
8046        }))
8047        .unwrap();
8048        assert_eq!(request.capabilities, ClientCapabilities::default());
8049
8050        let response: InitializeResponse = serde_json::from_value(json!({
8051            "protocolVersion": 2,
8052            "capabilities": false,
8053            "info": {
8054                "name": "agent",
8055                "version": "1.0.0"
8056            }
8057        }))
8058        .unwrap();
8059        assert_eq!(response.capabilities, AgentCapabilities::default());
8060    }
8061
8062    #[test]
8063    fn test_agent_capabilities_default_on_malformed_values() {
8064        let capabilities: AgentCapabilities = serde_json::from_value(json!({
8065            "session": false,
8066            "auth": false
8067        }))
8068        .unwrap();
8069
8070        assert!(capabilities.session.is_none());
8071        assert_eq!(capabilities.auth, None);
8072    }
8073
8074    #[test]
8075    fn test_mcp_server_stdio_serialization() {
8076        let server = McpServer::Stdio(
8077            McpServerStdio::new("test-server", "/usr/bin/server")
8078                .args(vec!["--port".to_string(), "3000".to_string()])
8079                .env(vec![EnvVariable::new("API_KEY", "secret123")]),
8080        );
8081
8082        let json = serde_json::to_value(&server).unwrap();
8083        assert_eq!(
8084            json,
8085            json!({
8086                "type": "stdio",
8087                "name": "test-server",
8088                "command": "/usr/bin/server",
8089                "args": ["--port", "3000"],
8090                "env": [
8091                    {
8092                        "name": "API_KEY",
8093                        "value": "secret123"
8094                    }
8095                ]
8096            })
8097        );
8098
8099        let deserialized: McpServer = serde_json::from_value(json).unwrap();
8100        match deserialized {
8101            McpServer::Stdio(McpServerStdio {
8102                name,
8103                command,
8104                args,
8105                env,
8106                meta: _,
8107            }) => {
8108                assert_eq!(name, "test-server");
8109                assert_eq!(command, AbsolutePath::new("/usr/bin/server"));
8110                assert_eq!(args, vec!["--port", "3000"]);
8111                assert_eq!(env.len(), 1);
8112                assert_eq!(env[0].name, "API_KEY");
8113                assert_eq!(env[0].value, "secret123");
8114            }
8115            _ => panic!("Expected Stdio variant"),
8116        }
8117    }
8118
8119    #[test]
8120    fn test_mcp_server_empty_arrays_are_optional() {
8121        let stdio = McpServer::Stdio(McpServerStdio::new("test-server", "/usr/bin/server"));
8122        assert_eq!(
8123            serde_json::to_value(&stdio).unwrap(),
8124            json!({
8125                "type": "stdio",
8126                "name": "test-server",
8127                "command": "/usr/bin/server"
8128            })
8129        );
8130
8131        let McpServer::Stdio(McpServerStdio { args, env, .. }) =
8132            serde_json::from_value::<McpServer>(json!({
8133                "type": "stdio",
8134                "name": "test-server",
8135                "command": "/usr/bin/server"
8136            }))
8137            .unwrap()
8138        else {
8139            panic!("Expected Stdio variant");
8140        };
8141        assert_eq!(args, Vec::<String>::new());
8142        assert_eq!(env, []);
8143
8144        let http = McpServer::Http(McpServerHttp::new("http-server", "https://api.example.com"));
8145        assert_eq!(
8146            serde_json::to_value(&http).unwrap(),
8147            json!({
8148                "type": "http",
8149                "name": "http-server",
8150                "url": "https://api.example.com"
8151            })
8152        );
8153
8154        let McpServer::Http(McpServerHttp { headers, .. }) =
8155            serde_json::from_value::<McpServer>(json!({
8156                "type": "http",
8157                "name": "http-server",
8158                "url": "https://api.example.com"
8159            }))
8160            .unwrap()
8161        else {
8162            panic!("Expected Http variant");
8163        };
8164        assert_eq!(headers, []);
8165    }
8166
8167    #[test]
8168    fn test_mcp_server_unknown_transport_serialization() {
8169        let json = json!({
8170            "type": "websocket",
8171            "name": "future-server",
8172            "url": "wss://example.com/mcp",
8173            "protocolVersion": "2026-01-01"
8174        });
8175
8176        let deserialized: McpServer = serde_json::from_value(json.clone()).unwrap();
8177        let McpServer::Other(OtherMcpServer { type_, fields }) = &deserialized else {
8178            panic!("Expected Other variant");
8179        };
8180
8181        assert_eq!(type_, "websocket");
8182        assert_eq!(fields["name"], "future-server");
8183        assert_eq!(fields["url"], "wss://example.com/mcp");
8184        assert_eq!(fields["protocolVersion"], "2026-01-01");
8185        assert_eq!(serde_json::to_value(&deserialized).unwrap(), json);
8186    }
8187
8188    #[test]
8189    fn test_mcp_server_stdio_requires_type() {
8190        let result = serde_json::from_value::<McpServer>(json!({
8191            "name": "test-server",
8192            "command": "/usr/bin/server",
8193            "args": [],
8194            "env": []
8195        }));
8196
8197        assert!(result.is_err());
8198    }
8199
8200    #[test]
8201    fn test_mcp_server_unknown_does_not_hide_malformed_known_transport() {
8202        let result = serde_json::from_value::<McpServer>(json!({
8203            "type": "stdio",
8204            "name": "test-server",
8205            "args": [],
8206            "env": []
8207        }));
8208
8209        assert!(result.is_err());
8210    }
8211
8212    #[test]
8213    fn test_mcp_server_http_serialization() {
8214        let server = McpServer::Http(
8215            McpServerHttp::new("http-server", "https://api.example.com").headers(vec![
8216                HttpHeader::new("Authorization", "Bearer token123"),
8217                HttpHeader::new("Content-Type", "application/json"),
8218            ]),
8219        );
8220
8221        let json = serde_json::to_value(&server).unwrap();
8222        assert_eq!(
8223            json,
8224            json!({
8225                "type": "http",
8226                "name": "http-server",
8227                "url": "https://api.example.com",
8228                "headers": [
8229                    {
8230                        "name": "Authorization",
8231                        "value": "Bearer token123"
8232                    },
8233                    {
8234                        "name": "Content-Type",
8235                        "value": "application/json"
8236                    }
8237                ]
8238            })
8239        );
8240
8241        let deserialized: McpServer = serde_json::from_value(json).unwrap();
8242        match deserialized {
8243            McpServer::Http(McpServerHttp {
8244                name,
8245                url,
8246                headers,
8247                meta: _,
8248            }) => {
8249                assert_eq!(name, "http-server");
8250                assert_eq!(url, "https://api.example.com");
8251                assert_eq!(headers.len(), 2);
8252                assert_eq!(headers[0].name, "Authorization");
8253                assert_eq!(headers[0].value, "Bearer token123");
8254                assert_eq!(headers[1].name, "Content-Type");
8255                assert_eq!(headers[1].value, "application/json");
8256            }
8257            _ => panic!("Expected Http variant"),
8258        }
8259    }
8260
8261    #[cfg(feature = "schemars")]
8262    #[test]
8263    fn mcp_server_http_schema_marks_url_as_uri() {
8264        let schema = serde_json::to_value(schemars::schema_for!(McpServerHttp)).unwrap();
8265
8266        assert_eq!(schema["properties"]["url"]["format"], "uri");
8267    }
8268
8269    #[cfg(feature = "unstable_mcp_over_acp")]
8270    #[test]
8271    fn test_client_mcp_message_method_names() {
8272        use serde_json::json;
8273
8274        assert_eq!(AGENT_METHOD_NAMES.mcp_message, "mcp/message");
8275
8276        let notification =
8277            MessageMcpNotification::new("server-1", "req-1", "notifications/progress");
8278        assert_eq!(
8279            ClientNotification::MessageMcpNotification(Box::new(notification.clone())).method(),
8280            "mcp/message"
8281        );
8282        assert_eq!(
8283            serde_json::to_value(notification).unwrap(),
8284            json!({
8285                "serverId": "server-1",
8286                "requestId": "req-1",
8287                "method": "notifications/progress"
8288            })
8289        );
8290        let notification: MessageMcpNotification = serde_json::from_value(json!({
8291            "serverId": "server-1", "requestId": "req-1", "method": "notifications/progress",
8292            "params": null, "_meta": null
8293        }))
8294        .unwrap();
8295        assert_eq!(notification.params, None);
8296        assert_eq!(notification.meta, None);
8297        for key in ["serverId", "requestId", "method"] {
8298            let mut value = json!({"serverId":"server-1", "requestId":"req-1", "method":"notifications/progress"});
8299            value.as_object_mut().unwrap().remove(key);
8300            assert!(serde_json::from_value::<MessageMcpNotification>(value).is_err());
8301        }
8302    }
8303
8304    #[test]
8305    fn test_auth_method_names() {
8306        assert_eq!(AGENT_METHOD_NAMES.auth_login, "auth/login");
8307        assert_eq!(AGENT_METHOD_NAMES.auth_logout, "auth/logout");
8308
8309        assert_eq!(
8310            ClientRequest::LoginAuthRequest(Box::new(LoginAuthRequest::new("agent-login")))
8311                .method(),
8312            "auth/login"
8313        );
8314        assert_eq!(
8315            ClientRequest::LogoutAuthRequest(Box::new(LogoutAuthRequest::new())).method(),
8316            "auth/logout"
8317        );
8318    }
8319
8320    #[test]
8321    fn test_session_config_option_category_known_variants() {
8322        // Test serialization of known variants
8323        assert_eq!(
8324            serde_json::to_value(&SessionConfigOptionCategory::Mode).unwrap(),
8325            json!("mode")
8326        );
8327        assert_eq!(
8328            serde_json::to_value(&SessionConfigOptionCategory::Model).unwrap(),
8329            json!("model")
8330        );
8331        assert_eq!(
8332            serde_json::to_value(&SessionConfigOptionCategory::ModelConfig).unwrap(),
8333            json!("model_config")
8334        );
8335        assert_eq!(
8336            serde_json::to_value(&SessionConfigOptionCategory::ThoughtLevel).unwrap(),
8337            json!("thought_level")
8338        );
8339
8340        // Test deserialization of known variants
8341        assert_eq!(
8342            serde_json::from_str::<SessionConfigOptionCategory>("\"mode\"").unwrap(),
8343            SessionConfigOptionCategory::Mode
8344        );
8345        assert_eq!(
8346            serde_json::from_str::<SessionConfigOptionCategory>("\"model\"").unwrap(),
8347            SessionConfigOptionCategory::Model
8348        );
8349        assert_eq!(
8350            serde_json::from_str::<SessionConfigOptionCategory>("\"model_config\"").unwrap(),
8351            SessionConfigOptionCategory::ModelConfig
8352        );
8353        assert_eq!(
8354            serde_json::from_str::<SessionConfigOptionCategory>("\"thought_level\"").unwrap(),
8355            SessionConfigOptionCategory::ThoughtLevel
8356        );
8357    }
8358
8359    #[test]
8360    fn test_session_config_option_category_unknown_variants() {
8361        // Test that unknown strings are captured in Other variant
8362        let unknown: SessionConfigOptionCategory =
8363            serde_json::from_str("\"some_future_category\"").unwrap();
8364        assert_eq!(
8365            unknown,
8366            SessionConfigOptionCategory::Other("some_future_category".to_string())
8367        );
8368
8369        // Test round-trip of unknown category
8370        let json = serde_json::to_value(&unknown).unwrap();
8371        assert_eq!(json, json!("some_future_category"));
8372    }
8373
8374    #[test]
8375    fn test_session_config_option_category_custom_categories() {
8376        // Category names beginning with `_` are free for custom use
8377        let custom: SessionConfigOptionCategory =
8378            serde_json::from_str("\"_my_custom_category\"").unwrap();
8379        assert_eq!(
8380            custom,
8381            SessionConfigOptionCategory::Other("_my_custom_category".to_string())
8382        );
8383
8384        // Test round-trip preserves the custom category name
8385        let json = serde_json::to_value(&custom).unwrap();
8386        assert_eq!(json, json!("_my_custom_category"));
8387
8388        // Deserialize back and verify
8389        let deserialized: SessionConfigOptionCategory = serde_json::from_value(json).unwrap();
8390        assert_eq!(
8391            deserialized,
8392            SessionConfigOptionCategory::Other("_my_custom_category".to_string()),
8393        );
8394    }
8395
8396    fn test_config_option() -> SessionConfigOption {
8397        SessionConfigOption::select(
8398            "mode",
8399            "Mode",
8400            "ask",
8401            vec![SessionConfigSelectOption::new("ask", "Ask")],
8402        )
8403    }
8404
8405    #[test]
8406    fn test_session_response_initial_state_default_empty_and_skip_serializing() {
8407        assert_eq!(
8408            serde_json::to_value(NewSessionResponse::new("sess")).unwrap(),
8409            json!({ "sessionId": "sess" })
8410        );
8411        assert_eq!(
8412            serde_json::to_value(ResumeSessionResponse::new()).unwrap(),
8413            json!({})
8414        );
8415        #[cfg(feature = "unstable_session_fork")]
8416        assert_eq!(
8417            serde_json::to_value(ForkSessionResponse::new("fork")).unwrap(),
8418            json!({ "sessionId": "fork" })
8419        );
8420
8421        let json = serde_json::to_value(
8422            NewSessionResponse::new("sess").config_options(vec![test_config_option()]),
8423        )
8424        .unwrap();
8425        assert_eq!(json["configOptions"].as_array().unwrap().len(), 1);
8426    }
8427
8428    #[test]
8429    fn test_session_response_config_options_deserialize_missing_null_and_invalid() {
8430        let missing: NewSessionResponse =
8431            serde_json::from_value(json!({ "sessionId": "sess" })).unwrap();
8432        assert_eq!(missing.config_options, []);
8433
8434        let null: NewSessionResponse = serde_json::from_value(json!({
8435            "sessionId": "sess",
8436            "configOptions": null
8437        }))
8438        .unwrap();
8439        assert_eq!(null.config_options, []);
8440
8441        let wrong_shape: NewSessionResponse = serde_json::from_value(json!({
8442            "sessionId": "sess",
8443            "configOptions": "oops"
8444        }))
8445        .unwrap();
8446        assert_eq!(wrong_shape.config_options, []);
8447
8448        let valid_option = serde_json::to_value(test_config_option()).unwrap();
8449        let mixed: NewSessionResponse = serde_json::from_value(json!({
8450            "sessionId": "sess",
8451            "configOptions": ["oops", valid_option]
8452        }))
8453        .unwrap();
8454        assert_eq!(mixed.config_options.len(), 1);
8455
8456        let resume: ResumeSessionResponse = serde_json::from_value(json!({})).unwrap();
8457        assert_eq!(resume.config_options, []);
8458        #[cfg(feature = "unstable_session_fork")]
8459        {
8460            let fork: ForkSessionResponse =
8461                serde_json::from_value(json!({ "sessionId": "fork" })).unwrap();
8462            assert_eq!(fork.config_options, []);
8463        }
8464    }
8465
8466    #[test]
8467    fn test_session_response_available_commands_roundtrip_with_config_options() {
8468        use super::super::{AvailableCommandInput, Command, TextCommandInput};
8469
8470        let commands = vec![
8471            AvailableCommand::Command(
8472                Command::new("web", "Search the web")
8473                    .input(AvailableCommandInput::Text(TextCommandInput::new("Query"))),
8474            ),
8475            AvailableCommand::Command(Command::new("test", "Run project tests")),
8476        ];
8477        let mut expected = json!({
8478            "sessionId": "sess",
8479            "configOptions": [test_config_option()],
8480            "availableCommands": [
8481                {
8482                    "type": "command",
8483                    "name": "web",
8484                    "description": "Search the web",
8485                    "input": { "type": "text", "hint": "Query" }
8486                },
8487                { "type": "command", "name": "test", "description": "Run project tests" }
8488            ]
8489        });
8490
8491        let new = NewSessionResponse::new("sess")
8492            .config_options(vec![test_config_option()])
8493            .available_commands(commands.clone());
8494        assert_eq!(serde_json::to_value(&new).unwrap(), expected);
8495        assert_eq!(
8496            serde_json::from_value::<NewSessionResponse>(expected.clone()).unwrap(),
8497            new
8498        );
8499
8500        expected.as_object_mut().unwrap().remove("sessionId");
8501        let resume = ResumeSessionResponse::new()
8502            .config_options(vec![test_config_option()])
8503            .available_commands(commands.clone());
8504        assert_eq!(serde_json::to_value(&resume).unwrap(), expected);
8505        assert_eq!(
8506            serde_json::from_value::<ResumeSessionResponse>(expected.clone()).unwrap(),
8507            resume
8508        );
8509
8510        #[cfg(feature = "unstable_session_fork")]
8511        {
8512            expected["sessionId"] = json!("fork");
8513            let fork = ForkSessionResponse::new("fork")
8514                .config_options(vec![test_config_option()])
8515                .available_commands(commands);
8516            assert_eq!(serde_json::to_value(&fork).unwrap(), expected);
8517            assert_eq!(
8518                serde_json::from_value::<ForkSessionResponse>(expected).unwrap(),
8519                fork
8520            );
8521        }
8522    }
8523
8524    #[test]
8525    fn test_session_response_available_commands_deserialize_missing_null_and_invalid() {
8526        let command =
8527            AvailableCommand::Command(super::super::Command::new("test", "Run project tests"));
8528        let config_options = vec![test_config_option()];
8529
8530        for (commands, expected) in [
8531            (None, vec![]),
8532            (Some(json!(null)), vec![]),
8533            (Some(json!([])), vec![]),
8534            (Some(json!("oops")), vec![]),
8535            (Some(json!({})), vec![]),
8536            (Some(json!([null, {}, { "name": "invalid" }])), vec![]),
8537            (
8538                Some(json!([{ "name": "test", "description": "Run project tests" }])),
8539                vec![],
8540            ),
8541            (
8542                Some(json!([null, command, { "name": "invalid" }])),
8543                vec![command.clone()],
8544            ),
8545        ] {
8546            let mut value = json!({
8547                "sessionId": "sess",
8548                "configOptions": config_options
8549            });
8550            if let Some(commands) = commands {
8551                value["availableCommands"] = commands;
8552            }
8553
8554            let new: NewSessionResponse = serde_json::from_value(value.clone()).unwrap();
8555            assert_eq!(new.available_commands, expected);
8556            assert_eq!(new.config_options, config_options);
8557
8558            #[cfg(feature = "unstable_session_fork")]
8559            {
8560                let fork: ForkSessionResponse = serde_json::from_value(value.clone()).unwrap();
8561                assert_eq!(fork.available_commands, expected);
8562                assert_eq!(fork.config_options, config_options);
8563            }
8564
8565            value.as_object_mut().unwrap().remove("sessionId");
8566            let resume: ResumeSessionResponse = serde_json::from_value(value).unwrap();
8567            assert_eq!(resume.available_commands, expected);
8568            assert_eq!(resume.config_options, config_options);
8569        }
8570
8571        let resume: ResumeSessionResponse = serde_json::from_value(json!(null)).unwrap();
8572        assert_eq!(resume.available_commands, []);
8573    }
8574
8575    #[test]
8576    fn test_resume_session_replay_from_serialization() {
8577        assert_eq!(
8578            serde_json::to_value(ResumeSessionRequest::new(
8579                "sess_abc123",
8580                "/home/user/project"
8581            ))
8582            .unwrap(),
8583            json!({
8584                "sessionId": "sess_abc123",
8585                "cwd": "/home/user/project"
8586            })
8587        );
8588        assert_eq!(
8589            serde_json::to_value(
8590                ResumeSessionRequest::new("sess_abc123", "/home/user/project")
8591                    .replay_from(ReplayFrom::from(ReplayFromStart::new()))
8592            )
8593            .unwrap(),
8594            json!({
8595                "sessionId": "sess_abc123",
8596                "cwd": "/home/user/project",
8597                "replayFrom": {
8598                    "type": "start"
8599                }
8600            })
8601        );
8602
8603        let replay: ResumeSessionRequest = serde_json::from_value(json!({
8604            "sessionId": "sess_abc123",
8605            "cwd": "/home/user/project",
8606            "replayFrom": {
8607                "type": "start"
8608            }
8609        }))
8610        .unwrap();
8611        assert!(matches!(replay.replay_from, Some(ReplayFrom::Start(_))));
8612
8613        let none: ResumeSessionRequest = serde_json::from_value(json!({
8614            "sessionId": "sess_abc123",
8615            "cwd": "/home/user/project",
8616            "replayFrom": null
8617        }))
8618        .unwrap();
8619        assert!(none.replay_from.is_none());
8620    }
8621
8622    #[test]
8623    fn test_auth_method_agent_serialization() {
8624        let method = AuthMethod::Agent(AuthMethodAgent::new("default-auth", "Default Auth"));
8625
8626        let json = serde_json::to_value(&method).unwrap();
8627        assert_eq!(
8628            json,
8629            json!({
8630                "methodId": "default-auth",
8631                "name": "Default Auth",
8632                "type": "agent"
8633            })
8634        );
8635        // description should be omitted when None
8636        assert!(!json.as_object().unwrap().contains_key("description"));
8637
8638        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
8639        match deserialized {
8640            AuthMethod::Agent(AuthMethodAgent {
8641                method_id, name, ..
8642            }) => {
8643                assert_eq!(method_id.0.as_ref(), "default-auth");
8644                assert_eq!(name, "Default Auth");
8645            }
8646            _ => panic!("Expected Agent variant"),
8647        }
8648    }
8649
8650    #[test]
8651    fn test_auth_method_agent_deserialization() {
8652        let json = json!({
8653            "methodId": "agent-auth",
8654            "name": "Agent Auth",
8655            "type": "agent"
8656        });
8657
8658        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
8659        assert!(matches!(deserialized, AuthMethod::Agent(_)));
8660    }
8661
8662    #[test]
8663    fn test_auth_method_agent_requires_type() {
8664        assert!(
8665            serde_json::from_value::<AuthMethod>(json!({
8666                "methodId": "agent-auth",
8667                "name": "Agent Auth"
8668            }))
8669            .is_err()
8670        );
8671    }
8672
8673    #[test]
8674    fn test_auth_method_agent_rejects_null_type() {
8675        assert!(
8676            serde_json::from_value::<AuthMethod>(json!({
8677                "methodId": "agent-auth",
8678                "name": "Agent Auth",
8679                "type": null
8680            }))
8681            .is_err()
8682        );
8683    }
8684
8685    #[test]
8686    fn test_auth_method_unknown_does_not_hide_malformed_agent() {
8687        assert!(
8688            serde_json::from_value::<AuthMethod>(json!({
8689                "methodId": "agent-auth",
8690                "type": "agent"
8691            }))
8692            .is_err()
8693        );
8694        assert!(
8695            serde_json::from_value::<AuthMethod>(json!({
8696                "methodId": "api-key",
8697                "type": "env_var",
8698                "vars": [{"name": "API_KEY"}]
8699            }))
8700            .is_err()
8701        );
8702    }
8703
8704    #[test]
8705    fn test_auth_method_unknown_variant_roundtrip() {
8706        let method: AuthMethod = serde_json::from_value(json!({
8707            "methodId": "oauth",
8708            "name": "OAuth",
8709            "type": "_oauth",
8710            "authorizationUrl": "https://example.com/auth"
8711        }))
8712        .unwrap();
8713
8714        assert_eq!(method.method_id().0.as_ref(), "oauth");
8715        assert_eq!(method.name(), "OAuth");
8716        let AuthMethod::Other(unknown) = method else {
8717            panic!("expected unknown auth method");
8718        };
8719        assert_eq!(unknown.type_, "_oauth");
8720        assert_eq!(
8721            unknown.fields.get("authorizationUrl"),
8722            Some(&json!("https://example.com/auth"))
8723        );
8724
8725        assert_eq!(
8726            serde_json::to_value(AuthMethod::Other(unknown)).unwrap(),
8727            json!({
8728                "methodId": "oauth",
8729                "name": "OAuth",
8730                "type": "_oauth",
8731                "authorizationUrl": "https://example.com/auth"
8732            })
8733        );
8734    }
8735
8736    #[test]
8737    fn test_auth_method_unknown_does_not_hide_malformed_known_variant() {
8738        assert!(
8739            serde_json::from_value::<AuthMethod>(json!({
8740                "methodId": "terminal-auth",
8741                "type": "terminal"
8742            }))
8743            .is_err()
8744        );
8745    }
8746
8747    #[test]
8748    fn test_tool_call_and_terminal_cancel_serialization() {
8749        assert_eq!(AGENT_METHOD_NAMES.tool_call_cancel, "tool_call/cancel");
8750        assert_eq!(AGENT_METHOD_NAMES.terminal_cancel, "terminal/cancel");
8751        assert_eq!(
8752            ClientRequest::CancelToolCallRequest(Box::new(CancelToolCallRequest::new(
8753                "sess_abc123",
8754                "call_012"
8755            )))
8756            .method(),
8757            "tool_call/cancel"
8758        );
8759        assert_eq!(
8760            ClientRequest::CancelTerminalRequest(Box::new(CancelTerminalRequest::new(
8761                "sess_abc123",
8762                "term_003"
8763            )))
8764            .method(),
8765            "terminal/cancel"
8766        );
8767        assert_eq!(
8768            serde_json::to_value(CancelToolCallRequest::new("sess_abc123", "call_012")).unwrap(),
8769            json!({"sessionId": "sess_abc123", "toolCallId": "call_012"})
8770        );
8771        assert_eq!(
8772            serde_json::to_value(CancelTerminalRequest::new("sess_abc123", "term_003")).unwrap(),
8773            json!({"sessionId": "sess_abc123", "terminalId": "term_003"})
8774        );
8775        assert!(
8776            serde_json::from_value::<CancelToolCallRequest>(json!({"sessionId": "sess_abc123"}))
8777                .is_err()
8778        );
8779        assert_eq!(
8780            serde_json::to_value(CancelTerminalResponse::new()).unwrap(),
8781            json!({})
8782        );
8783    }
8784
8785    #[test]
8786    fn test_session_delete_serialization() {
8787        assert_eq!(AGENT_METHOD_NAMES.session_delete, "session/delete");
8788        assert_eq!(
8789            ClientRequest::DeleteSessionRequest(Box::new(DeleteSessionRequest::new("sess_abc123")))
8790                .method(),
8791            "session/delete"
8792        );
8793        assert_eq!(
8794            serde_json::to_value(DeleteSessionRequest::new("sess_abc123")).unwrap(),
8795            json!({
8796                "sessionId": "sess_abc123"
8797            })
8798        );
8799        assert_eq!(
8800            serde_json::to_value(DeleteSessionResponse::new()).unwrap(),
8801            json!({})
8802        );
8803        assert_eq!(
8804            serde_json::to_value(
8805                SessionCapabilities::new().delete(SessionDeleteCapabilities::new())
8806            )
8807            .unwrap(),
8808            json!({
8809                "delete": {}
8810            })
8811        );
8812    }
8813    #[cfg(feature = "unstable_session_set_title")]
8814    #[test]
8815    fn test_session_set_title_serialization() {
8816        assert_eq!(AGENT_METHOD_NAMES.session_set_title, "session/set_title");
8817        assert_eq!(
8818            ClientRequest::SetSessionTitleRequest(Box::new(SetSessionTitleRequest::new(
8819                "sess_abc123",
8820                "Investigate OAuth timeout"
8821            )))
8822            .method(),
8823            "session/set_title"
8824        );
8825        assert_eq!(
8826            serde_json::to_value(SetSessionTitleRequest::new(
8827                "sess_abc123",
8828                "Investigate OAuth timeout"
8829            ))
8830            .unwrap(),
8831            json!({
8832                "sessionId": "sess_abc123",
8833                "title": "Investigate OAuth timeout"
8834            })
8835        );
8836        assert_eq!(
8837            serde_json::to_value(SetSessionTitleResponse::new("Investigate OAuth timeout"))
8838                .unwrap(),
8839            json!({
8840                "title": "Investigate OAuth timeout"
8841            })
8842        );
8843        assert_eq!(
8844            serde_json::to_value(SessionCapabilities::new().title(SessionTitleCapabilities::new()))
8845                .unwrap(),
8846            json!({
8847                "title": {}
8848            })
8849        );
8850    }
8851
8852    #[cfg(feature = "unstable_session_set_title")]
8853    #[test]
8854    fn test_session_set_title_requires_title() {
8855        for params in [
8856            json!({"sessionId": "sess_abc123"}),
8857            json!({"sessionId": "sess_abc123", "title": null}),
8858            json!({"sessionId": "sess_abc123", "title": 42}),
8859        ] {
8860            assert!(serde_json::from_value::<SetSessionTitleRequest>(params).is_err());
8861        }
8862        for result in [json!({}), json!({"title": null})] {
8863            assert!(serde_json::from_value::<SetSessionTitleResponse>(result).is_err());
8864        }
8865    }
8866
8867    #[cfg(feature = "unstable_session_options")]
8868    #[test]
8869    fn test_session_options_serialization() {
8870        assert_eq!(AGENT_METHOD_NAMES.session_options, "session/options");
8871        assert_eq!(
8872            ClientRequest::SessionOptionsRequest(Box::new(SessionOptionsRequest::new(
8873                "/home/user/project"
8874            )))
8875            .method(),
8876            "session/options"
8877        );
8878        assert_eq!(
8879            serde_json::to_value(
8880                SessionOptionsRequest::new("/home/user/project")
8881                    .session_id(SessionId::new("sess_abc123"))
8882            )
8883            .unwrap(),
8884            json!({"cwd": "/home/user/project", "sessionId": "sess_abc123"})
8885        );
8886        assert_eq!(
8887            serde_json::from_value::<SessionOptionsRequest>(
8888                json!({"cwd": "/home/user/project", "additionalDirectories": null, "sessionId": null})
8889            )
8890            .unwrap(),
8891            SessionOptionsRequest::new("/home/user/project")
8892        );
8893        let request = NewSessionRequest::new("/home/user/project").config_options(vec![
8894            InitialSessionConfigOption::new("model", SessionConfigOptionValue::id("model-2")),
8895            InitialSessionConfigOption::new("fast", SessionConfigOptionValue::boolean(true)),
8896        ]);
8897        let value = serde_json::to_value(&request).unwrap();
8898        assert_eq!(
8899            value["configOptions"],
8900            json!([
8901                {"configId": "model", "type": "id", "value": "model-2"},
8902                {"configId": "fast", "type": "boolean", "value": true}
8903            ])
8904        );
8905        assert_eq!(
8906            serde_json::from_value::<NewSessionRequest>(value).unwrap(),
8907            request
8908        );
8909        assert!(
8910            serde_json::from_value::<NewSessionRequest>(json!({
8911                "cwd": "/home/user/project",
8912                "mcpServers": [],
8913                "configOptions": [{"type": "boolean", "value": true}]
8914            }))
8915            .is_err()
8916        );
8917        assert_eq!(
8918            serde_json::to_value(SessionOptionsResponse::new()).unwrap(),
8919            json!({})
8920        );
8921        assert_eq!(
8922            serde_json::to_value(
8923                SessionCapabilities::new().options(SessionOptionsCapabilities::new())
8924            )
8925            .unwrap(),
8926            json!({"options": {}})
8927        );
8928    }
8929
8930    #[cfg(feature = "unstable_session_status")]
8931    #[test]
8932    fn test_session_status_serialization() {
8933        assert_eq!(AGENT_METHOD_NAMES.session_status, "session/status");
8934        assert_eq!(
8935            ClientRequest::SessionStatusRequest(Box::new(SessionStatusRequest::new("sess_abc123")))
8936                .method(),
8937            "session/status"
8938        );
8939        assert_eq!(
8940            serde_json::to_value(SessionStatusRequest::new("sess_abc123")).unwrap(),
8941            json!({"sessionId": "sess_abc123"})
8942        );
8943        assert_eq!(
8944            serde_json::to_value(SessionStatusResponse::new(SessionStatus::Saved)).unwrap(),
8945            json!({"status": "saved"})
8946        );
8947        assert_eq!(
8948            serde_json::to_value(
8949                SessionCapabilities::new().status(SessionStatusCapabilities::new())
8950            )
8951            .unwrap(),
8952            json!({"status": {}})
8953        );
8954        assert_eq!(
8955            serde_json::to_value(SessionStatusResponse::new(SessionStatus::Open).state(
8956                StateUpdate::RequiresAction(crate::v2::RequiresActionStateUpdate::new())
8957            ))
8958            .unwrap(),
8959            json!({
8960                "status": "open",
8961                "state": {"state": "requires_action"}
8962            })
8963        );
8964        for state in [json!(null), json!("running"), json!({"state": 7})] {
8965            let response = serde_json::from_value::<SessionStatusResponse>(
8966                json!({"status": "open", "state": state}),
8967            )
8968            .unwrap();
8969            assert_eq!(response.state, None);
8970        }
8971    }
8972
8973    #[cfg(feature = "unstable_session_status")]
8974    #[test]
8975    fn test_session_status_is_strict_and_open() {
8976        let custom =
8977            serde_json::from_value::<SessionStatusResponse>(json!({"status": "_suspended"}))
8978                .unwrap();
8979        assert_eq!(
8980            custom.status,
8981            SessionStatus::Other("_suspended".to_string())
8982        );
8983        assert_eq!(
8984            serde_json::to_value(&custom).unwrap(),
8985            json!({"status": "_suspended"})
8986        );
8987        for result in [json!({}), json!({"status": null}), json!({"status": 1})] {
8988            assert!(serde_json::from_value::<SessionStatusResponse>(result).is_err());
8989        }
8990        for params in [json!({}), json!({"sessionId": null})] {
8991            assert!(serde_json::from_value::<SessionStatusRequest>(params).is_err());
8992        }
8993    }
8994
8995    #[cfg(feature = "unstable_session_archive")]
8996    #[test]
8997    fn test_session_archive_serialization() {
8998        assert_eq!(AGENT_METHOD_NAMES.session_archive, "session/archive");
8999        assert_eq!(AGENT_METHOD_NAMES.session_unarchive, "session/unarchive");
9000        assert_eq!(
9001            ClientRequest::ArchiveSessionRequest(Box::new(ArchiveSessionRequest::new(
9002                "sess_abc123"
9003            )))
9004            .method(),
9005            "session/archive"
9006        );
9007        assert_eq!(
9008            ClientRequest::UnarchiveSessionRequest(Box::new(UnarchiveSessionRequest::new(
9009                "sess_abc123"
9010            )))
9011            .method(),
9012            "session/unarchive"
9013        );
9014        assert_eq!(
9015            serde_json::to_value(ArchiveSessionRequest::new("sess_abc123")).unwrap(),
9016            json!({"sessionId": "sess_abc123"})
9017        );
9018        assert_eq!(
9019            serde_json::to_value(UnarchiveSessionResponse::new()).unwrap(),
9020            json!({})
9021        );
9022        assert_eq!(
9023            serde_json::to_value(
9024                SessionCapabilities::new().archive(SessionArchiveCapabilities::new())
9025            )
9026            .unwrap(),
9027            json!({"archive": {}})
9028        );
9029        assert_eq!(
9030            serde_json::to_value(
9031                ListSessionsRequest::new()
9032                    .cwd("/home/user/project")
9033                    .archived(SessionArchiveFilter::Only)
9034            )
9035            .unwrap(),
9036            json!({"cwd": "/home/user/project", "archived": "only"})
9037        );
9038        assert_eq!(
9039            serde_json::to_value(
9040                SessionInfo::new("sess_abc123", "/home/user/project").archived(true)
9041            )
9042            .unwrap(),
9043            json!({"sessionId": "sess_abc123", "cwd": "/home/user/project", "archived": true})
9044        );
9045    }
9046
9047    #[cfg(feature = "unstable_session_archive")]
9048    #[test]
9049    fn test_session_archive_filter_is_strict_and_open() {
9050        for (value, expected) in [
9051            (json!(null), None),
9052            (json!("include"), Some(SessionArchiveFilter::Include)),
9053            (
9054                json!("_recent"),
9055                Some(SessionArchiveFilter::Other("_recent".to_string())),
9056            ),
9057        ] {
9058            let request =
9059                serde_json::from_value::<ListSessionsRequest>(json!({"archived": value})).unwrap();
9060            assert_eq!(request.archived, expected);
9061        }
9062        for value in [json!(true), json!(1), json!({})] {
9063            assert!(
9064                serde_json::from_value::<ListSessionsRequest>(json!({"archived": value})).is_err()
9065            );
9066        }
9067        let info = serde_json::from_value::<SessionInfo>(
9068            json!({"sessionId": "sess_abc123", "cwd": "/home/user/project", "archived": "yes"}),
9069        )
9070        .unwrap();
9071        assert_eq!(info.archived, None);
9072    }
9073
9074    #[test]
9075    fn test_session_additional_directories_serialization() {
9076        assert_eq!(
9077            serde_json::to_value(NewSessionRequest::new("/home/user/project")).unwrap(),
9078            json!({
9079                "cwd": "/home/user/project",
9080            })
9081        );
9082        assert_eq!(
9083            serde_json::to_value(
9084                NewSessionRequest::new("/home/user/project").additional_directories(vec![
9085                    PathBuf::from("/home/user/shared-lib"),
9086                    PathBuf::from("/home/user/product-docs"),
9087                ])
9088            )
9089            .unwrap(),
9090            json!({
9091                "cwd": "/home/user/project",
9092                "additionalDirectories": [
9093                    "/home/user/shared-lib",
9094                    "/home/user/product-docs"
9095                ],
9096            })
9097        );
9098        assert_eq!(
9099            serde_json::to_value(ResumeSessionRequest::new(
9100                "sess_abc123",
9101                "/home/user/project"
9102            ))
9103            .unwrap(),
9104            json!({
9105                "sessionId": "sess_abc123",
9106                "cwd": "/home/user/project",
9107            })
9108        );
9109        assert_eq!(
9110            serde_json::from_value::<ResumeSessionRequest>(json!({
9111                "sessionId": "sess_abc123",
9112                "cwd": "/home/user/project"
9113            }))
9114            .unwrap()
9115            .mcp_servers,
9116            Vec::<McpServer>::new()
9117        );
9118        assert_eq!(
9119            serde_json::from_value::<ResumeSessionRequest>(json!({
9120                "sessionId": "sess_abc123",
9121                "cwd": "/home/user/project",
9122                "mcpServers": null
9123            }))
9124            .unwrap()
9125            .mcp_servers,
9126            Vec::<McpServer>::new()
9127        );
9128        assert_eq!(
9129            serde_json::to_value(SessionInfo::new("sess_abc123", "/home/user/project")).unwrap(),
9130            json!({
9131                "sessionId": "sess_abc123",
9132                "cwd": "/home/user/project"
9133            })
9134        );
9135        assert_eq!(
9136            serde_json::to_value(
9137                SessionInfo::new("sess_abc123", "/home/user/project").additional_directories(vec![
9138                    PathBuf::from("/home/user/shared-lib"),
9139                    PathBuf::from("/home/user/product-docs"),
9140                ])
9141            )
9142            .unwrap(),
9143            json!({
9144                "sessionId": "sess_abc123",
9145                "cwd": "/home/user/project",
9146                "additionalDirectories": [
9147                    "/home/user/shared-lib",
9148                    "/home/user/product-docs"
9149                ]
9150            })
9151        );
9152        assert_eq!(
9153            serde_json::from_value::<SessionInfo>(json!({
9154                "sessionId": "sess_abc123",
9155                "cwd": "/home/user/project"
9156            }))
9157            .unwrap()
9158            .additional_directories,
9159            Vec::<AbsolutePath>::new()
9160        );
9161    }
9162    #[test]
9163    fn test_session_additional_directories_capabilities_serialization() {
9164        assert_eq!(
9165            serde_json::to_value(
9166                SessionCapabilities::new()
9167                    .additional_directories(SessionAdditionalDirectoriesCapabilities::new())
9168            )
9169            .unwrap(),
9170            json!({
9171                "additionalDirectories": {}
9172            })
9173        );
9174    }
9175
9176    #[test]
9177    fn test_session_system_prompt_capabilities_serialization() {
9178        assert_eq!(
9179            serde_json::to_value(
9180                SessionCapabilities::new().system_prompt(SessionSystemPromptCapabilities::new())
9181            )
9182            .unwrap(),
9183            json!({ "systemPrompt": {} })
9184        );
9185        assert_eq!(
9186            serde_json::to_value(
9187                SessionCapabilities::new().system_prompt(
9188                    SessionSystemPromptCapabilities::new().mode(
9189                        SessionSystemPromptModeCapabilities::new()
9190                            .override_(SessionSystemPromptOverrideCapabilities::new())
9191                    )
9192                )
9193            )
9194            .unwrap(),
9195            json!({ "systemPrompt": { "mode": { "override": {} } } })
9196        );
9197        assert_eq!(
9198            serde_json::from_value::<SessionCapabilities>(
9199                json!({ "systemPrompt": { "mode": { "override": {} } } })
9200            )
9201            .unwrap()
9202            .system_prompt
9203            .and_then(|capabilities| capabilities.mode)
9204            .and_then(|mode| mode.override_),
9205            Some(SessionSystemPromptOverrideCapabilities::new())
9206        );
9207
9208        // Capabilities fall back to "not advertised" when malformed.
9209        assert_eq!(
9210            serde_json::from_value::<SessionCapabilities>(json!({ "systemPrompt": "yes" }))
9211                .unwrap()
9212                .system_prompt,
9213            None
9214        );
9215        assert_eq!(
9216            serde_json::from_value::<SessionCapabilities>(
9217                json!({ "systemPrompt": { "mode": { "override": true } } })
9218            )
9219            .unwrap()
9220            .system_prompt,
9221            Some(
9222                SessionSystemPromptCapabilities::new()
9223                    .mode(SessionSystemPromptModeCapabilities::new())
9224            )
9225        );
9226        assert_eq!(
9227            serde_json::from_value::<SessionCapabilities>(
9228                json!({ "systemPrompt": { "mode": "override" } })
9229            )
9230            .unwrap()
9231            .system_prompt,
9232            Some(SessionSystemPromptCapabilities::new())
9233        );
9234    }
9235
9236    #[test]
9237    fn test_system_prompt_lifecycle_request_serialization() {
9238        let system_prompt = SystemPrompt::new(vec![ContentBlock::from(
9239            "You are a code review specialist.",
9240        )]);
9241        let system_prompt_json = json!({
9242            "mode": "append",
9243            "content": [{ "type": "text", "text": "You are a code review specialist." }]
9244        });
9245
9246        let request =
9247            NewSessionRequest::new("/home/user/project").system_prompt(system_prompt.clone());
9248        let request_json = json!({
9249            "cwd": "/home/user/project",
9250            "systemPrompt": system_prompt_json
9251        });
9252        assert_eq!(serde_json::to_value(&request).unwrap(), request_json);
9253        assert_eq!(
9254            serde_json::from_value::<NewSessionRequest>(request_json).unwrap(),
9255            request
9256        );
9257
9258        assert_eq!(
9259            serde_json::to_value(
9260                ResumeSessionRequest::new("sess_abc123", "/home/user/project")
9261                    .system_prompt(system_prompt.clone())
9262            )
9263            .unwrap()["systemPrompt"],
9264            system_prompt_json
9265        );
9266        #[cfg(feature = "unstable_session_fork")]
9267        assert_eq!(
9268            serde_json::to_value(
9269                ForkSessionRequest::new("sess_abc123", "/home/user/project")
9270                    .system_prompt(system_prompt.clone())
9271            )
9272            .unwrap()["systemPrompt"],
9273            system_prompt_json
9274        );
9275
9276        let override_prompt =
9277            SystemPrompt::new(vec![ContentBlock::from("...")]).mode(SystemPromptMode::Override);
9278        let override_json = json!({
9279            "mode": "override",
9280            "content": [{ "type": "text", "text": "..." }]
9281        });
9282        assert_eq!(
9283            serde_json::to_value(&override_prompt).unwrap(),
9284            override_json
9285        );
9286        assert_eq!(
9287            serde_json::from_value::<SystemPrompt>(override_json).unwrap(),
9288            override_prompt
9289        );
9290    }
9291
9292    /// `SystemPrompt::new` defaults to `append` in Rust, but `mode` is required on
9293    /// the wire, so it is always serialized.
9294    #[test]
9295    fn test_system_prompt_new_defaults_to_append() {
9296        let system_prompt = SystemPrompt::new(vec![ContentBlock::from("...")]);
9297        assert_eq!(system_prompt.mode, SystemPromptMode::Append);
9298        assert_eq!(
9299            serde_json::to_value(&system_prompt).unwrap(),
9300            json!({ "mode": "append", "content": [{ "type": "text", "text": "..." }] })
9301        );
9302    }
9303
9304    /// Unknown modes follow the enum variant extension rule: they parse as
9305    /// `SystemPromptMode::Other` so they are not dropped, and an agent that does
9306    /// not support them must reject the request.
9307    #[test]
9308    fn test_system_prompt_preserves_unknown_modes() {
9309        for mode in ["_vendor_mode", "prepend"] {
9310            let system_prompt_json =
9311                json!({ "mode": mode, "content": [{ "type": "text", "text": "..." }] });
9312            let system_prompt: SystemPrompt =
9313                serde_json::from_value(system_prompt_json.clone()).unwrap();
9314            assert_eq!(
9315                system_prompt.mode,
9316                SystemPromptMode::Other(mode.to_string())
9317            );
9318            assert_eq!(
9319                serde_json::to_value(&system_prompt).unwrap(),
9320                system_prompt_json
9321            );
9322        }
9323    }
9324
9325    /// The receiver acts on `systemPrompt`, so malformed values fail the request
9326    /// (`-32602`) instead of creating a session without the prompt, and `null`
9327    /// is equivalent to omitting the field.
9328    fn assert_system_prompt_is_strict<T>(base: &serde_json::Value)
9329    where
9330        T: serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
9331    {
9332        let name = std::any::type_name::<T>();
9333        let with = |system_prompt: serde_json::Value| {
9334            let mut request = base.clone();
9335            request["systemPrompt"] = system_prompt;
9336            serde_json::from_value::<T>(request)
9337        };
9338
9339        for system_prompt in [
9340            json!("You are a code review specialist."),
9341            json!({ "content": [{ "type": "text", "text": "..." }] }),
9342            json!({ "mode": null, "content": [{ "type": "text", "text": "..." }] }),
9343            json!({ "mode": 1, "content": [{ "type": "text", "text": "..." }] }),
9344            json!({ "mode": "append" }),
9345            json!({ "mode": "append", "content": "..." }),
9346            json!({ "mode": "append", "content": [{ "type": "text" }] }),
9347        ] {
9348            assert!(
9349                with(system_prompt.clone()).is_err(),
9350                "{name}.systemPrompt: {system_prompt}"
9351            );
9352        }
9353
9354        assert_eq!(
9355            with(serde_json::Value::Null).unwrap(),
9356            serde_json::from_value::<T>(base.clone()).unwrap(),
9357            "{name}.systemPrompt"
9358        );
9359    }
9360
9361    #[test]
9362    fn test_session_setup_requests_reject_malformed_system_prompts() {
9363        assert!(
9364            serde_json::to_value(NewSessionRequest::new("/repo"))
9365                .unwrap()
9366                .get("systemPrompt")
9367                .is_none()
9368        );
9369        assert_system_prompt_is_strict::<NewSessionRequest>(&json!({ "cwd": "/repo" }));
9370        assert_system_prompt_is_strict::<ResumeSessionRequest>(&json!({
9371            "sessionId": "sess-1",
9372            "cwd": "/repo"
9373        }));
9374        #[cfg(feature = "unstable_session_fork")]
9375        assert_system_prompt_is_strict::<ForkSessionRequest>(&json!({
9376            "sessionId": "sess-1",
9377            "cwd": "/repo"
9378        }));
9379    }
9380
9381    /// Unknown content block types parse as `ContentBlock::Other` so they are not
9382    /// dropped. An agent that does not support them must reject the request.
9383    #[test]
9384    fn test_system_prompt_preserves_unknown_content_blocks() {
9385        let request: NewSessionRequest = serde_json::from_value(json!({
9386            "cwd": "/home/user/project",
9387            "systemPrompt": {
9388                "mode": "append",
9389                "content": [{ "type": "_vendor_video", "uri": "https://example.com/intro.mp4" }]
9390            }
9391        }))
9392        .unwrap();
9393        let content = request.system_prompt.unwrap().content;
9394        assert_eq!(content.len(), 1);
9395        assert!(matches!(content[0], ContentBlock::Other(_)));
9396    }
9397
9398    #[test]
9399    fn test_auth_method_terminal_serialization() {
9400        let method = AuthMethod::Terminal(AuthMethodTerminal::new("tui-auth", "Terminal Auth"));
9401
9402        let json = serde_json::to_value(&method).unwrap();
9403        assert_eq!(
9404            json,
9405            json!({
9406                "methodId": "tui-auth",
9407                "name": "Terminal Auth",
9408                "type": "terminal"
9409            })
9410        );
9411        // args and env should be omitted when empty
9412        assert!(!json.as_object().unwrap().contains_key("args"));
9413        assert!(!json.as_object().unwrap().contains_key("env"));
9414
9415        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9416        match deserialized {
9417            AuthMethod::Terminal(AuthMethodTerminal { args, env, .. }) => {
9418                assert_eq!(args, Vec::<String>::new());
9419                assert_eq!(env, []);
9420            }
9421            _ => panic!("Expected Terminal variant"),
9422        }
9423    }
9424
9425    #[test]
9426    fn test_auth_method_terminal_with_args_and_env_serialization() {
9427        let method = AuthMethod::Terminal(
9428            AuthMethodTerminal::new("tui-auth", "Terminal Auth")
9429                .args(vec!["--interactive".to_string(), "--color".to_string()])
9430                .env(vec![EnvVariable::new("TERM", "xterm-256color")]),
9431        );
9432
9433        let json = serde_json::to_value(&method).unwrap();
9434        assert_eq!(
9435            json,
9436            json!({
9437                "methodId": "tui-auth",
9438                "name": "Terminal Auth",
9439                "type": "terminal",
9440                "args": ["--interactive", "--color"],
9441                "env": [
9442                    {
9443                        "name": "TERM",
9444                        "value": "xterm-256color"
9445                    }
9446                ]
9447            })
9448        );
9449
9450        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
9451        match deserialized {
9452            AuthMethod::Terminal(AuthMethodTerminal { args, env, .. }) => {
9453                assert_eq!(args, vec!["--interactive", "--color"]);
9454                assert_eq!(env.len(), 1);
9455                assert_eq!(env[0].name, "TERM");
9456                assert_eq!(env[0].value, "xterm-256color");
9457            }
9458            _ => panic!("Expected Terminal variant"),
9459        }
9460    }
9461
9462    #[test]
9463    fn test_session_config_option_id_serialize() {
9464        let val = SessionConfigOptionValue::id("model-1");
9465        let json = serde_json::to_value(&val).unwrap();
9466        assert_eq!(json, json!({ "type": "id", "value": "model-1" }));
9467    }
9468
9469    #[test]
9470    fn test_session_config_option_value_boolean_serialize() {
9471        let val = SessionConfigOptionValue::boolean(true);
9472        let json = serde_json::to_value(&val).unwrap();
9473        assert_eq!(json, json!({ "type": "boolean", "value": true }));
9474    }
9475
9476    #[test]
9477    fn test_session_config_option_value_deserialize_id() {
9478        let json = json!({ "type": "id", "value": "model-1" });
9479        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9480        assert_eq!(val, SessionConfigOptionValue::id("model-1"));
9481        assert_eq!(val.as_id().unwrap().to_string(), "model-1");
9482    }
9483
9484    #[test]
9485    fn test_session_config_option_value_deserialize_requires_type() {
9486        let json = json!({ "value": "model-1" });
9487        let result = serde_json::from_value::<SessionConfigOptionValue>(json);
9488        assert!(result.is_err());
9489    }
9490
9491    #[test]
9492    fn test_session_config_option_value_deserialize_boolean() {
9493        let json = json!({ "type": "boolean", "value": true });
9494        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9495        assert_eq!(val, SessionConfigOptionValue::boolean(true));
9496        assert_eq!(val.as_bool(), Some(true));
9497    }
9498
9499    #[test]
9500    fn test_session_config_option_value_deserialize_boolean_false() {
9501        let json = json!({ "type": "boolean", "value": false });
9502        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9503        assert_eq!(val, SessionConfigOptionValue::boolean(false));
9504        assert_eq!(val.as_bool(), Some(false));
9505    }
9506
9507    #[test]
9508    fn test_session_config_option_value_deserialize_unknown_type_with_string_value() {
9509        let json = json!({
9510            "type": "text",
9511            "value": "freeform input",
9512            "maxLength": 200
9513        });
9514        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9515        let SessionConfigOptionValue::Other(unknown) = val else {
9516            panic!("Expected Other variant");
9517        };
9518        assert_eq!(unknown.type_, "text");
9519        assert_eq!(unknown.value, json!("freeform input"));
9520        assert_eq!(unknown.fields["maxLength"], json!(200));
9521    }
9522
9523    #[test]
9524    fn test_session_config_option_value_deserialize_unknown_type_with_object_value() {
9525        let json = json!({
9526            "type": "range",
9527            "value": { "min": 1, "max": 5 }
9528        });
9529        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9530        let SessionConfigOptionValue::Other(unknown) = val else {
9531            panic!("Expected Other variant");
9532        };
9533        assert_eq!(unknown.type_, "range");
9534        assert_eq!(unknown.value, json!({ "min": 1, "max": 5 }));
9535    }
9536
9537    #[test]
9538    fn test_session_config_option_value_roundtrip_id() {
9539        let original = SessionConfigOptionValue::id("option-a");
9540        let json = serde_json::to_value(&original).unwrap();
9541        let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9542        assert_eq!(original, roundtripped);
9543    }
9544
9545    #[test]
9546    fn test_session_config_option_value_roundtrip_boolean() {
9547        let original = SessionConfigOptionValue::boolean(false);
9548        let json = serde_json::to_value(&original).unwrap();
9549        let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9550        assert_eq!(original, roundtripped);
9551    }
9552
9553    #[test]
9554    fn test_session_config_option_value_roundtrip_other() {
9555        let mut fields = BTreeMap::new();
9556        fields.insert("maxLength".to_string(), json!(200));
9557        let original = SessionConfigOptionValue::Other(OtherSessionConfigOptionValue::new(
9558            "text",
9559            json!("freeform input"),
9560            fields,
9561        ));
9562        let json = serde_json::to_value(&original).unwrap();
9563        let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
9564        assert_eq!(original, roundtripped);
9565    }
9566
9567    #[test]
9568    fn test_session_config_option_value_type_mismatch_boolean_with_string() {
9569        let json = json!({ "type": "boolean", "value": "not a bool" });
9570        let result = serde_json::from_value::<SessionConfigOptionValue>(json);
9571        assert!(result.is_err());
9572    }
9573
9574    #[test]
9575    fn test_session_config_option_value_from_impls() {
9576        let from_str: SessionConfigOptionValue = "model-1".into();
9577        assert_eq!(from_str.as_id().unwrap().to_string(), "model-1");
9578
9579        let from_id: SessionConfigOptionValue = SessionConfigValueId::new("model-2").into();
9580        assert_eq!(from_id.as_id().unwrap().to_string(), "model-2");
9581
9582        let from_bool: SessionConfigOptionValue = true.into();
9583        assert_eq!(from_bool.as_bool(), Some(true));
9584    }
9585
9586    #[test]
9587    fn test_set_session_config_option_request_id() {
9588        let req = SetSessionConfigOptionRequest::new("sess_1", "model", "model-1");
9589        let json = serde_json::to_value(&req).unwrap();
9590        assert_eq!(
9591            json,
9592            json!({
9593                "sessionId": "sess_1",
9594                "configId": "model",
9595                "type": "id",
9596                "value": "model-1"
9597            })
9598        );
9599    }
9600
9601    #[test]
9602    fn test_set_session_config_option_request_boolean() {
9603        let req = SetSessionConfigOptionRequest::new("sess_1", "brave_mode", true);
9604        let json = serde_json::to_value(&req).unwrap();
9605        assert_eq!(
9606            json,
9607            json!({
9608                "sessionId": "sess_1",
9609                "configId": "brave_mode",
9610                "type": "boolean",
9611                "value": true
9612            })
9613        );
9614    }
9615
9616    #[test]
9617    fn test_set_session_config_option_request_deserialize_requires_type() {
9618        let json = json!({
9619            "sessionId": "sess_1",
9620            "configId": "model",
9621            "value": "model-1"
9622        });
9623        let result = serde_json::from_value::<SetSessionConfigOptionRequest>(json);
9624        assert!(result.is_err());
9625    }
9626
9627    #[test]
9628    fn test_set_session_config_option_request_deserialize_boolean() {
9629        let json = json!({
9630            "sessionId": "sess_1",
9631            "configId": "brave_mode",
9632            "type": "boolean",
9633            "value": true
9634        });
9635        let req: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
9636        assert_eq!(req.value.as_bool(), Some(true));
9637    }
9638
9639    #[test]
9640    fn test_set_session_config_option_request_roundtrip_id() {
9641        let original = SetSessionConfigOptionRequest::new("s", "c", "v");
9642        let json = serde_json::to_value(&original).unwrap();
9643        let roundtripped: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
9644        assert_eq!(original, roundtripped);
9645    }
9646
9647    #[test]
9648    fn test_set_session_config_option_request_roundtrip_boolean() {
9649        let original = SetSessionConfigOptionRequest::new("s", "c", false);
9650        let json = serde_json::to_value(&original).unwrap();
9651        let roundtripped: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
9652        assert_eq!(original, roundtripped);
9653    }
9654
9655    #[test]
9656    fn test_session_config_boolean_serialization() {
9657        let cfg = SessionConfigBoolean::new(true);
9658        let json = serde_json::to_value(&cfg).unwrap();
9659        assert_eq!(json, json!({ "currentValue": true }));
9660
9661        let deserialized: SessionConfigBoolean = serde_json::from_value(json).unwrap();
9662        assert!(deserialized.current_value);
9663    }
9664
9665    #[test]
9666    fn test_session_config_option_boolean_variant() {
9667        let opt = SessionConfigOption::boolean("brave_mode", "Brave Mode", false)
9668            .description("Skip confirmation prompts")
9669            .meta(test_meta());
9670        assert_eq!(serialized_meta_key_count(&opt), 1);
9671
9672        let json = serde_json::to_value(&opt).unwrap();
9673        assert_eq!(
9674            json,
9675            json!({
9676                "configId": "brave_mode",
9677                "name": "Brave Mode",
9678                "description": "Skip confirmation prompts",
9679                "type": "boolean",
9680                "currentValue": false,
9681                "_meta": {
9682                    "source": "test"
9683                }
9684            })
9685        );
9686
9687        let deserialized: SessionConfigOption = serde_json::from_value(json).unwrap();
9688        assert_eq!(deserialized.config_id.to_string(), "brave_mode");
9689        assert_eq!(deserialized.name, "Brave Mode");
9690        match deserialized.kind {
9691            SessionConfigKind::Boolean(ref b) => assert!(!b.current_value),
9692            _ => panic!("Expected Boolean kind"),
9693        }
9694    }
9695
9696    #[test]
9697    fn test_session_config_option_select_still_works() {
9698        // Make sure existing select options are unaffected
9699        let opt = SessionConfigOption::select(
9700            "model",
9701            "Model",
9702            "model-1",
9703            vec![
9704                SessionConfigSelectOption::new("model-1", "Model 1"),
9705                SessionConfigSelectOption::new("model-2", "Model 2"),
9706            ],
9707        )
9708        .meta(test_meta());
9709        assert_eq!(serialized_meta_key_count(&opt), 1);
9710
9711        let json = serde_json::to_value(&opt).unwrap();
9712        assert_eq!(json["type"], "select");
9713        assert_eq!(json["currentValue"], "model-1");
9714        assert_eq!(json["options"].as_array().unwrap().len(), 2);
9715        assert_eq!(json["_meta"]["source"], "test");
9716
9717        let deserialized: SessionConfigOption = serde_json::from_value(json).unwrap();
9718        match deserialized.kind {
9719            SessionConfigKind::Select(ref s) => {
9720                assert_eq!(s.current_value.to_string(), "model-1");
9721            }
9722            _ => panic!("Expected Select kind"),
9723        }
9724    }
9725
9726    #[test]
9727    fn test_session_config_option_unknown_kind_roundtrip() {
9728        let option: SessionConfigOption = serde_json::from_value(json!({
9729            "configId": "verbosity",
9730            "name": "Verbosity",
9731            "type": "_slider",
9732            "currentValue": 3,
9733            "min": 0,
9734            "max": 5,
9735            "_meta": {
9736                "source": "test"
9737            }
9738        }))
9739        .unwrap();
9740
9741        assert_eq!(option.config_id.to_string(), "verbosity");
9742        assert_eq!(option.meta.as_ref().unwrap()["source"], "test");
9743        let SessionConfigKind::Other(unknown) = &option.kind else {
9744            panic!("expected unknown config kind");
9745        };
9746        assert_eq!(unknown.type_, "_slider");
9747        assert_eq!(unknown.fields.get("currentValue"), Some(&json!(3)));
9748        assert!(!unknown.fields.contains_key("_meta"));
9749        assert_eq!(serialized_meta_key_count(&option), 1);
9750
9751        let json = serde_json::to_value(&option).unwrap();
9752        assert_eq!(json["type"], "_slider");
9753        assert_eq!(json["currentValue"], 3);
9754        assert_eq!(json["min"], 0);
9755        assert_eq!(json["max"], 5);
9756        assert_eq!(json["_meta"]["source"], "test");
9757    }
9758
9759    #[test]
9760    fn test_session_config_option_unknown_kind_does_not_duplicate_flattened_meta() {
9761        let mut fields = std::collections::BTreeMap::new();
9762        fields.insert("currentValue".to_string(), json!(3));
9763        fields.insert("_meta".to_string(), json!({ "inner": "ignored" }));
9764
9765        let option = SessionConfigOption::new(
9766            "verbosity",
9767            "Verbosity",
9768            SessionConfigKind::Other(OtherSessionConfigKind::new("_slider", fields)),
9769        )
9770        .meta(test_meta());
9771
9772        let SessionConfigKind::Other(unknown) = &option.kind else {
9773            panic!("expected unknown config kind");
9774        };
9775        assert!(!unknown.fields.contains_key("_meta"));
9776        assert_eq!(serialized_meta_key_count(&option), 1);
9777
9778        let json = serde_json::to_value(&option).unwrap();
9779        assert_eq!(json["type"], "_slider");
9780        assert_eq!(json["currentValue"], 3);
9781        assert_eq!(json["_meta"]["source"], "test");
9782    }
9783
9784    #[test]
9785    fn test_session_config_option_unknown_does_not_hide_malformed_known_kind() {
9786        assert!(
9787            serde_json::from_value::<SessionConfigOption>(json!({
9788                "configId": "model",
9789                "name": "Model",
9790                "type": "select"
9791            }))
9792            .is_err()
9793        );
9794    }
9795
9796    #[cfg(feature = "unstable_llm_providers")]
9797    #[test]
9798    fn test_llm_protocol_known_variants() {
9799        assert_eq!(
9800            serde_json::to_value(&LlmProtocol::Anthropic).unwrap(),
9801            json!("anthropic")
9802        );
9803        assert_eq!(
9804            serde_json::to_value(&LlmProtocol::OpenAi).unwrap(),
9805            json!("openai")
9806        );
9807        assert_eq!(
9808            serde_json::to_value(&LlmProtocol::Azure).unwrap(),
9809            json!("azure")
9810        );
9811        assert_eq!(
9812            serde_json::to_value(&LlmProtocol::Vertex).unwrap(),
9813            json!("vertex")
9814        );
9815        assert_eq!(
9816            serde_json::to_value(&LlmProtocol::Bedrock).unwrap(),
9817            json!("bedrock")
9818        );
9819
9820        assert_eq!(
9821            serde_json::from_str::<LlmProtocol>("\"anthropic\"").unwrap(),
9822            LlmProtocol::Anthropic
9823        );
9824        assert_eq!(
9825            serde_json::from_str::<LlmProtocol>("\"openai\"").unwrap(),
9826            LlmProtocol::OpenAi
9827        );
9828        assert_eq!(
9829            serde_json::from_str::<LlmProtocol>("\"azure\"").unwrap(),
9830            LlmProtocol::Azure
9831        );
9832        assert_eq!(
9833            serde_json::from_str::<LlmProtocol>("\"vertex\"").unwrap(),
9834            LlmProtocol::Vertex
9835        );
9836        assert_eq!(
9837            serde_json::from_str::<LlmProtocol>("\"bedrock\"").unwrap(),
9838            LlmProtocol::Bedrock
9839        );
9840    }
9841
9842    #[cfg(feature = "unstable_llm_providers")]
9843    #[test]
9844    fn test_llm_protocol_unknown_variant() {
9845        let unknown: LlmProtocol = serde_json::from_str("\"cohere\"").unwrap();
9846        assert_eq!(unknown, LlmProtocol::Other("cohere".to_string()));
9847
9848        let json = serde_json::to_value(&unknown).unwrap();
9849        assert_eq!(json, json!("cohere"));
9850    }
9851
9852    #[cfg(feature = "unstable_llm_providers")]
9853    #[test]
9854    fn test_provider_current_config_serialization() {
9855        let config =
9856            ProviderCurrentConfig::new(LlmProtocol::Anthropic, "https://api.anthropic.com");
9857
9858        let json = serde_json::to_value(&config).unwrap();
9859        assert_eq!(
9860            json,
9861            json!({
9862                "apiType": "anthropic",
9863                "baseUrl": "https://api.anthropic.com"
9864            })
9865        );
9866
9867        let deserialized: ProviderCurrentConfig = serde_json::from_value(json).unwrap();
9868        assert_eq!(deserialized.api_type, LlmProtocol::Anthropic);
9869        assert_eq!(deserialized.base_url, "https://api.anthropic.com");
9870    }
9871
9872    #[cfg(feature = "unstable_llm_providers")]
9873    #[test]
9874    fn test_provider_info_with_current_config() {
9875        let info = ProviderInfo::new(
9876            "main",
9877            vec![LlmProtocol::Anthropic, LlmProtocol::OpenAi],
9878            true,
9879            Some(ProviderCurrentConfig::new(
9880                LlmProtocol::Anthropic,
9881                "https://api.anthropic.com",
9882            )),
9883        );
9884
9885        let json = serde_json::to_value(&info).unwrap();
9886        assert_eq!(
9887            json,
9888            json!({
9889                "providerId": "main",
9890                "supported": ["anthropic", "openai"],
9891                "required": true,
9892                "current": {
9893                    "apiType": "anthropic",
9894                    "baseUrl": "https://api.anthropic.com"
9895                }
9896            })
9897        );
9898
9899        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
9900        assert_eq!(deserialized.provider_id.to_string(), "main");
9901        assert_eq!(deserialized.supported.len(), 2);
9902        assert!(deserialized.required);
9903        assert!(deserialized.current.is_some());
9904        assert_eq!(
9905            deserialized.current.as_ref().unwrap().api_type,
9906            LlmProtocol::Anthropic
9907        );
9908    }
9909
9910    #[cfg(feature = "unstable_llm_providers")]
9911    #[test]
9912    fn test_provider_info_disabled() {
9913        let info = ProviderInfo::new(
9914            "secondary",
9915            vec![LlmProtocol::OpenAi],
9916            false,
9917            None::<ProviderCurrentConfig>,
9918        );
9919
9920        let json = serde_json::to_value(&info).unwrap();
9921        assert_eq!(
9922            json,
9923            json!({
9924                "providerId": "secondary",
9925                "supported": ["openai"],
9926                "required": false
9927            })
9928        );
9929
9930        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
9931        assert_eq!(deserialized.provider_id.to_string(), "secondary");
9932        assert!(!deserialized.required);
9933        assert!(deserialized.current.is_none());
9934    }
9935
9936    #[cfg(feature = "unstable_llm_providers")]
9937    #[test]
9938    fn test_provider_info_missing_current_defaults_to_none() {
9939        // current is optional; omitting it should decode as None
9940        let json = json!({
9941            "providerId": "main",
9942            "supported": ["anthropic"],
9943            "required": true
9944        });
9945        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
9946        assert!(deserialized.current.is_none());
9947    }
9948
9949    #[cfg(feature = "unstable_llm_providers")]
9950    #[test]
9951    fn test_provider_info_explicit_null_current_decodes_to_none() {
9952        // current: null and an omitted current are equivalent on the wire;
9953        // both must deserialize into None so the disabled state is preserved
9954        // regardless of which form the peer chose to send.
9955        let json = json!({
9956            "providerId": "main",
9957            "supported": ["anthropic"],
9958            "required": true,
9959            "current": null
9960        });
9961        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
9962        assert!(deserialized.current.is_none());
9963    }
9964
9965    #[cfg(feature = "unstable_llm_providers")]
9966    #[test]
9967    fn test_list_providers_response_serialization() {
9968        let response = ListProvidersResponse::new(vec![ProviderInfo::new(
9969            "main",
9970            vec![LlmProtocol::Anthropic],
9971            true,
9972            Some(ProviderCurrentConfig::new(
9973                LlmProtocol::Anthropic,
9974                "https://api.anthropic.com",
9975            )),
9976        )]);
9977
9978        let json = serde_json::to_value(&response).unwrap();
9979        assert_eq!(json["providers"].as_array().unwrap().len(), 1);
9980        assert_eq!(json["providers"][0]["providerId"], "main");
9981
9982        let deserialized: ListProvidersResponse = serde_json::from_value(json).unwrap();
9983        assert_eq!(deserialized.providers.len(), 1);
9984    }
9985
9986    #[cfg(feature = "unstable_llm_providers")]
9987    #[test]
9988    fn test_set_provider_request_serialization() {
9989        use std::collections::HashMap;
9990
9991        let mut headers = HashMap::new();
9992        headers.insert("Authorization".to_string(), "Bearer sk-test".to_string());
9993
9994        let request =
9995            SetProviderRequest::new("main", LlmProtocol::OpenAi, "https://api.openai.com/v1")
9996                .headers(headers);
9997
9998        let json = serde_json::to_value(&request).unwrap();
9999        assert_eq!(
10000            json,
10001            json!({
10002                "providerId": "main",
10003                "apiType": "openai",
10004                "baseUrl": "https://api.openai.com/v1",
10005                "headers": {
10006                    "Authorization": "Bearer sk-test"
10007                }
10008            })
10009        );
10010
10011        let deserialized: SetProviderRequest = serde_json::from_value(json).unwrap();
10012        assert_eq!(deserialized.provider_id.to_string(), "main");
10013        assert_eq!(deserialized.api_type, LlmProtocol::OpenAi);
10014        assert_eq!(deserialized.base_url, "https://api.openai.com/v1");
10015        assert_eq!(deserialized.headers.len(), 1);
10016        assert_eq!(
10017            deserialized.headers.get("Authorization").unwrap(),
10018            "Bearer sk-test"
10019        );
10020    }
10021
10022    #[cfg(feature = "unstable_llm_providers")]
10023    #[test]
10024    fn test_set_provider_request_omits_empty_headers() {
10025        let request =
10026            SetProviderRequest::new("main", LlmProtocol::Anthropic, "https://api.anthropic.com");
10027
10028        let json = serde_json::to_value(&request).unwrap();
10029        // headers should be omitted when empty
10030        assert!(!json.as_object().unwrap().contains_key("headers"));
10031    }
10032
10033    #[cfg(feature = "unstable_llm_providers")]
10034    #[test]
10035    fn test_disable_provider_request_serialization() {
10036        let request = DisableProviderRequest::new("secondary");
10037
10038        let json = serde_json::to_value(&request).unwrap();
10039        assert_eq!(json, json!({ "providerId": "secondary" }));
10040
10041        let deserialized: DisableProviderRequest = serde_json::from_value(json).unwrap();
10042        assert_eq!(deserialized.provider_id.to_string(), "secondary");
10043    }
10044
10045    #[cfg(feature = "unstable_llm_providers")]
10046    #[test]
10047    fn test_providers_capabilities_serialization() {
10048        let caps = ProvidersCapabilities::new();
10049
10050        let json = serde_json::to_value(&caps).unwrap();
10051        assert_eq!(json, json!({}));
10052
10053        let deserialized: ProvidersCapabilities = serde_json::from_value(json).unwrap();
10054        assert!(deserialized.meta.is_none());
10055    }
10056
10057    #[cfg(feature = "unstable_llm_providers")]
10058    #[test]
10059    fn test_agent_capabilities_with_providers() {
10060        let caps = AgentCapabilities::new().providers(ProvidersCapabilities::new());
10061
10062        let json = serde_json::to_value(&caps).unwrap();
10063        assert_eq!(json["providers"], json!({}));
10064
10065        let deserialized: AgentCapabilities = serde_json::from_value(json).unwrap();
10066        assert!(deserialized.providers.is_some());
10067    }
10068
10069    #[test]
10070    fn test_agent_capabilities_session_is_explicit() {
10071        let json = serde_json::to_value(AgentCapabilities::new()).unwrap();
10072        assert!(json.get("session").is_none());
10073
10074        let caps = AgentCapabilities::new().session(
10075            SessionCapabilities::new()
10076                .prompt(PromptCapabilities::new().image(PromptImageCapabilities::new()))
10077                .mcp(McpCapabilities::new().stdio(McpStdioCapabilities::new())),
10078        );
10079
10080        assert_eq!(
10081            serde_json::to_value(&caps).unwrap(),
10082            json!({
10083                "session": {
10084                    "prompt": {
10085                        "image": {}
10086                    },
10087                    "mcp": {
10088                        "stdio": {}
10089                    }
10090                }
10091            })
10092        );
10093
10094        let deserialized: AgentCapabilities = serde_json::from_value(json!({
10095            "session": false
10096        }))
10097        .unwrap();
10098        assert!(deserialized.session.is_none());
10099    }
10100
10101    #[test]
10102    fn test_prompt_capabilities_serialize_supported_content_as_objects() {
10103        let caps = PromptCapabilities::new()
10104            .image(PromptImageCapabilities::new())
10105            .audio(PromptAudioCapabilities::new())
10106            .embedded_context(PromptEmbeddedContextCapabilities::new());
10107
10108        assert_eq!(
10109            serde_json::to_value(&caps).unwrap(),
10110            json!({
10111                "image": {},
10112                "audio": {},
10113                "embeddedContext": {}
10114            })
10115        );
10116
10117        let deserialized: PromptCapabilities = serde_json::from_value(json!({
10118            "image": null,
10119            "audio": false,
10120            "embeddedContext": {}
10121        }))
10122        .unwrap();
10123        assert!(deserialized.image.is_none());
10124        assert!(deserialized.audio.is_none());
10125        assert!(deserialized.embedded_context.is_some());
10126    }
10127
10128    #[test]
10129    fn test_mcp_capabilities_serialize_supported_transports_as_objects() {
10130        let caps = McpCapabilities::new()
10131            .stdio(McpStdioCapabilities::new())
10132            .http(McpHttpCapabilities::new());
10133
10134        assert_eq!(
10135            serde_json::to_value(&caps).unwrap(),
10136            json!({
10137                "stdio": {},
10138                "http": {}
10139            })
10140        );
10141
10142        let deserialized: McpCapabilities = serde_json::from_value(json!({
10143            "stdio": null,
10144            "http": false
10145        }))
10146        .unwrap();
10147        assert!(deserialized.stdio.is_none());
10148        assert!(deserialized.http.is_none());
10149    }
10150
10151    #[cfg(feature = "unstable_mcp_over_acp")]
10152    #[test]
10153    fn test_mcp_capabilities_serialize_acp_support_as_object() {
10154        let caps = McpCapabilities::new().acp(McpAcpCapabilities::new());
10155
10156        assert_eq!(
10157            serde_json::to_value(&caps).unwrap(),
10158            json!({
10159                "acp": {}
10160            })
10161        );
10162    }
10163
10164    #[test]
10165    fn prompt_request_rejects_malformed_content_block() {
10166        use serde_json::json;
10167
10168        assert!(
10169            serde_json::from_value::<PromptRequest>(json!({
10170                "sessionId": "sess-1",
10171                "prompt": [{"type": "text"}]
10172            }))
10173            .is_err()
10174        );
10175    }
10176
10177    #[test]
10178    fn prompt_request_rejects_non_array_prompt() {
10179        use serde_json::json;
10180
10181        assert!(
10182            serde_json::from_value::<PromptRequest>(json!({
10183                "sessionId": "sess-1",
10184                "prompt": "hello"
10185            }))
10186            .is_err()
10187        );
10188    }
10189
10190    fn assert_session_setup_lists_are_strict<T>(base: &serde_json::Value)
10191    where
10192        T: serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
10193    {
10194        let name = std::any::type_name::<T>();
10195        let with = |field: &str, value: serde_json::Value| {
10196            let mut request = base.clone();
10197            request[field] = value;
10198            serde_json::from_value::<T>(request)
10199        };
10200
10201        for (field, value) in [
10202            // Dropping the malformed server would start the session without it.
10203            (
10204                "mcpServers",
10205                json!([
10206                    {"type": "stdio", "name": "github", "command": "/usr/bin/gh-mcp", "env": [{"name": "GITHUB_TOKEN", "value": null}]},
10207                    {"type": "stdio", "name": "fs", "command": "/usr/bin/fs-mcp"}
10208                ]),
10209            ),
10210            ("mcpServers", json!({"type": "stdio", "name": "fs"})),
10211            ("additionalDirectories", json!(["/repo/lib", 42])),
10212            ("additionalDirectories", json!("/repo/lib")),
10213        ] {
10214            assert!(
10215                with(field, value.clone()).is_err(),
10216                "{name}.{field}: {value}"
10217            );
10218        }
10219
10220        let empty = serde_json::from_value::<T>(base.clone()).unwrap();
10221        for field in ["mcpServers", "additionalDirectories"] {
10222            assert_eq!(
10223                with(field, serde_json::Value::Null).unwrap(),
10224                empty,
10225                "{name}.{field}"
10226            );
10227        }
10228    }
10229
10230    #[test]
10231    fn session_setup_requests_reject_malformed_mcp_servers_and_directories() {
10232        assert_session_setup_lists_are_strict::<NewSessionRequest>(&json!({"cwd": "/repo"}));
10233        assert_session_setup_lists_are_strict::<ResumeSessionRequest>(&json!({
10234            "sessionId": "sess-1",
10235            "cwd": "/repo"
10236        }));
10237        #[cfg(feature = "unstable_session_fork")]
10238        assert_session_setup_lists_are_strict::<ForkSessionRequest>(&json!({
10239            "sessionId": "sess-1",
10240            "cwd": "/repo"
10241        }));
10242    }
10243
10244    #[test]
10245    fn resume_session_request_rejects_malformed_replay_from() {
10246        let request = |replay_from: serde_json::Value| {
10247            serde_json::from_value::<ResumeSessionRequest>(json!({
10248                "sessionId": "sess-1",
10249                "cwd": "/repo",
10250                "replayFrom": replay_from
10251            }))
10252        };
10253
10254        // Treating this as omitted would reconnect without the requested replay.
10255        assert!(request(json!("start")).is_err());
10256        assert_eq!(request(serde_json::Value::Null).unwrap().replay_from, None);
10257        assert!(matches!(
10258            request(json!({"type": "start"})).unwrap().replay_from,
10259            Some(ReplayFrom::Start(_))
10260        ));
10261    }
10262
10263    #[test]
10264    fn mcp_server_lists_treat_null_as_empty() {
10265        let servers: Vec<McpServer> = serde_json::from_value(json!([
10266            {"type": "stdio", "name": "fs", "command": "/usr/bin/fs-mcp", "args": null, "env": null},
10267            {"type": "http", "name": "api", "url": "https://example.com/mcp", "headers": null}
10268        ]))
10269        .unwrap();
10270
10271        assert_eq!(
10272            servers,
10273            vec![
10274                McpServer::Stdio(McpServerStdio::new("fs", "/usr/bin/fs-mcp")),
10275                McpServer::Http(McpServerHttp::new("api", "https://example.com/mcp")),
10276            ]
10277        );
10278    }
10279
10280    #[test]
10281    fn terminal_auth_methods_reject_malformed_launch_config() {
10282        // The client spawns a process from `args` and `env`, so a malformed
10283        // method is dropped from `authMethods` instead of launched with
10284        // altered arguments or preserved as an unknown method.
10285        let response: InitializeResponse = serde_json::from_value(json!({
10286            "protocolVersion": 2,
10287            "info": {"name": "agent", "version": "1.0.0"},
10288            "authMethods": [
10289                {"type": "terminal", "methodId": "bad-args", "name": "Log in", "args": ["auth", "--port", 8123]},
10290                {"type": "terminal", "methodId": "bad-env", "name": "Log in", "env": [{"name": "DEBUG", "value": 1}]},
10291                {"type": "terminal", "methodId": "null-config", "name": "Log in", "args": null, "env": null},
10292                {"type": "agent", "methodId": "agent", "name": "Agent login"}
10293            ]
10294        }))
10295        .unwrap();
10296
10297        assert_eq!(
10298            response.auth_methods,
10299            vec![
10300                AuthMethod::Terminal(AuthMethodTerminal::new("null-config", "Log in")),
10301                AuthMethod::Agent(AuthMethodAgent::new("agent", "Agent login")),
10302            ]
10303        );
10304    }
10305
10306    #[cfg(feature = "unstable_auth_status")]
10307    #[test]
10308    fn auth_status_response_round_trips() {
10309        let response = AuthStatusResponse::new(AuthState::Authenticated).accounts(vec![
10310            AuthAccount::new("Anthropic API key")
10311                .description("API key helper".to_string())
10312                .active(true),
10313            AuthAccount::new("Claude Max").email("user@example.com".to_string()),
10314        ]);
10315        let json = serde_json::to_value(&response).unwrap();
10316        assert_eq!(
10317            json,
10318            json!({
10319                "state": "authenticated",
10320                "accounts": [
10321                    {
10322                        "label": "Anthropic API key",
10323                        "description": "API key helper",
10324                        "active": true
10325                    },
10326                    {
10327                        "label": "Claude Max",
10328                        "email": "user@example.com"
10329                    }
10330                ]
10331            })
10332        );
10333        assert_eq!(
10334            serde_json::from_value::<AuthStatusResponse>(json).unwrap(),
10335            response
10336        );
10337        assert_eq!(
10338            serde_json::to_value(AuthStatusResponse::new(AuthState::NotRequired)).unwrap(),
10339            json!({"state": "not_required"})
10340        );
10341    }
10342
10343    #[cfg(feature = "unstable_auth_status")]
10344    #[test]
10345    fn auth_status_state_is_strict_and_accounts_are_lenient() {
10346        assert!(serde_json::from_value::<AuthStatusResponse>(json!({})).is_err());
10347        assert!(serde_json::from_value::<AuthStatusResponse>(json!({"state": null})).is_err());
10348        assert!(serde_json::from_value::<AuthStatusResponse>(json!({"state": 1})).is_err());
10349
10350        let response: AuthStatusResponse = serde_json::from_value(json!({
10351            "state": "_vendor_state",
10352            "accounts": [
10353                {"active": true},
10354                {
10355                    "label": "Vertex AI",
10356                    "description": 42,
10357                    "active": "yes",
10358                    "email": ["not", "a", "string"]
10359                }
10360            ]
10361        }))
10362        .unwrap();
10363        assert_eq!(
10364            response,
10365            AuthStatusResponse::new(AuthState::Other("_vendor_state".to_string()))
10366                .accounts(vec![AuthAccount::new("Vertex AI")])
10367        );
10368        assert_eq!(
10369            serde_json::from_value::<AuthStatusResponse>(
10370                json!({"state": "unknown", "accounts": null})
10371            )
10372            .unwrap(),
10373            AuthStatusResponse::new(AuthState::Unknown)
10374        );
10375    }
10376
10377    #[cfg(feature = "unstable_auth_status")]
10378    #[test]
10379    fn auth_status_update_notification_routes() {
10380        use crate::v2::{AgentNotification, CLIENT_METHOD_NAMES};
10381
10382        assert_eq!(AGENT_METHOD_NAMES.auth_status, "auth/status");
10383        assert_eq!(CLIENT_METHOD_NAMES.auth_status_update, "auth/status_update");
10384        let notification = AgentNotification::AuthStatusUpdateNotification(Box::new(
10385            AuthStatusUpdateNotification::new(AuthState::Unauthenticated),
10386        ));
10387        assert_eq!(notification.method(), "auth/status_update");
10388        assert_eq!(
10389            serde_json::to_value(&notification).unwrap(),
10390            json!({"state": "unauthenticated"})
10391        );
10392    }
10393}